Sublime Forum

Safe to Dynamically Bind/Unbind Keys?

#1

Hello, I am preparing to write a simple (I hope) plugin for Sublime Text and I was hoping to receive a little feedback on my planned approach before I get started.

Goal: Using a keybind (e.g. ctrl+shift+x) drop into a mode where my regular keys are all bound to snippets.

For example,

pressing ‘a’ activates snippet 1,
pressing ‘b’ activates snippet 2,

pressing ‘z’ activates snippet 26, and so on.

I was thinking of approaching this problem by writing several commands that insert the snippets like so:

class ExampleCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        contents = 'snippet contents'
        self.view.run_command('insert_snippet', {"contents": contents})

and creating one additional command that dynamically binds/unbinds the regular character keys to the commands.

I am particularly unsure if that last command is a good idea. I am unsure if it can be done and, possibly more importantly, if it can be, whether it should be done or not.

Any feedback for this first-time plugin writer is very appreciated.

0 Likes

#2

One way I can think of to approach this problem is to use the <character> key. For example, let’s say you have the following key binding :-

{
	"keys": ["<character>"],
	"command": "echo",
},

If you save this in your User keymap file, then on every character press, you would see that character being logged to the console (So be careful because this robs your typing ability).

This is because using <character> will cause ST to send that character as an argument to the command (the example in this case being the echo command). Hence, it is best to have some kind of context to prevent it from being active all the time.

In your case, you can use your key binding ctrl+shift+x to maybe add a custom view setting and as a keybinding context, use the setting. key to check for that setting on the view.

Once that’s done, your ExampleCommand can be written to use insert_snippet to insert the contents of a snippet file. Like,
a -> snippet_a.sublime-snippet
b -> snippet_b.sublime-snippet
and so on …

Of course, there might be a better way to do it (or maybe this is the best approach ?).

0 Likes

#3

Thanks for your reply UltraInstinct05! I didn’t know about the <character> key. I think your proposal is better than mine.

0 Likes