Sublime Forum

File specific context key

#1

Is it possible to have a context key who value is a specific file or filename? I am looking to create a macro/keybinding that is only run if a specific file is open and focused.

On the unofficial docs its notes that ‘Arbitrary keys may be provided by plugins’ but I could not find information on how to create such a key.

0 Likes

#2

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.

1 Like

#3

Wow, thank you very much for the complete reply! I look forward to testing this out after work this evening.

0 Likes

#4

Bit of feedback @OdatNurd. I’ve implemented the listener and it does exactly what I was looking for. Thanks again!

0 Likes