To do something like that you need a custom EventListener
or ViewEventListener
that implements the on_query_context
event; see the documentation for full details of the event in question.
There may already be a package that provides such an event listener, but for reference an example of one is something like this:
import sublime
import sublime_plugin
import os
class MyEventListener(sublime_plugin.EventListener):
def on_query_context(self, view, key, operator, operand, match_all):
# Do nothing if we don't recognize the key or there is no file name
if key != "current_file" or view.file_name() is None:
return None
# Do nothing unless the operand is one of the equality tests.
if operator != sublime.OP_EQUAL and operator != sublime.OP_NOT_EQUAL:
return None
# Get the name of the file in the current view (with no path)
name = os.path.split(view.file_name())[-1]
# Handle the provided operator
if operator == sublime.OP_EQUAL:
return name == operand
elif operator == sublime.OP_NOT_EQUAL:
return name != operand
return None
This implements a context key
of current_file
that can match whether the current file has or does not have a particular file name (here the match is case sensitive and applies only to the file name and not the full path of the file; adjust as appropriate).
The handler needs to returns either True
(allow the key), False
(don’t allow the key) or None
(we don’t know what the key is so don’t take our word for it one way or the other).
In use, you can now create key bindings like this:
{
"keys": ["ctrl+alt+t"],
"command": "echo", "args": {
"message": "The current file is the windows keymap"
},
"context": [
{ "key": "current_file", "operator": "equal", "operand": "Default (Windows).sublime-keymap"}
],
},
The key will only work if the current file is the Windows keymap and will display a message in the Sublime console when the command triggers.