Search code examples
sublimetext3sublimetext2sublimetextsublimetext-snippet

How to detect in keybindings if sidebar is open?


I'd like cmd+1 to alternate between reveal in sidebar (if closed) and if sidebar is open, close it.

if closed: { "keys": ["super+1"], "command": "reveal_in_side_bar"}

if open: { "keys": ["super+1"], "command": "toggle_side_bar" }

I don't know how to do the if part . Thanks


Solution

  • As far as I know, there is no built-in key binding context that can be used to tell whether the sidebar is open or closed. But this is something that can easily be done using the Python API, specifically with window.is_sidebar_visible() and it is also possible to create custom keybinding contexts.

    From the Tools menu, navigate to Developer > New Plugin. Then replace the contents of the view with:

    import sublime, sublime_plugin
    
    class SidebarContextListener(sublime_plugin.EventListener):
        def on_query_context(self, view, key, operator, operand, match_all):
            if key != 'sidebar_visible' or not (operand in ('reveal', 'toggle')):
                return None
            visible = view.window().is_sidebar_visible()
            if operand == 'toggle' and visible:
                return True
            if operand == 'reveal' and not visible:
                return True
            return None
    

    and save it, in the folder ST suggests (Packages/User) as something like sidebar_context.py - the extension is important, the name isn't.

    Now, we can use it in your keybindings, like:

    { "keys": ["super+1"], "command": "toggle_side_bar", "context":
        [
            { "key": "sidebar_visible", "operand": "toggle" },
        ],
    },
    
    { "keys": ["super+1"], "command": "reveal_in_side_bar", "context":
        [
            { "key": "sidebar_visible", "operand": "reveal" },
        ],
    },