Sublime Forum

How to recieve key event (ESC) in a sublime_plugin.TextCommand plugin?

#1

I’m making a plugin which I wish to have to the following flow:

  1. The command is run and moves the caret to a certain location
  2. The user can enter some text at this caret location
  3. If the user (optionally) hits ESC or Enter key - I want to perform another action

I need help with number 3. How do I recieve the key event while staying in the same context, i.e. able to access data in my sublime_plugin.TextCommand class?

This is much alike what snippet does - you can hit ESC to exit ‘snippet mode’.

Thanks.

0 Likes

#2

You can not register for keyboard events within the API. You must define a key binding for it.

What you can do, however, is to define a context restriction for the key binding (esc in this case) that will only trigger if a certain condition is true. This condition could be checking a setting value or writing your own context callback function that will determine whether the context is “valid”.

Resources:

http://docs.sublimetext.info/en/latest/reference/key_bindings.html
http://www.sublimetext.com/docs/3/api_reference.html#sublime_plugin.EventListener (on_query_context)

1 Like

#3

Thank you. Okey, so I’ve looked into what you proposed and my only problem now is that I can’t put the EventListener and TextCommand class together (they must be two different) classes. Thus, I cannot access some variables in my TextCommand when I receive the event?

class GotoImportCommand(sublime_plugin.TextCommand): def run(self, edit): ...set some variables..

class Test(sublime_plugin.EventListener): def on_query_context(self, view, key, operator, operand, match_all): print ("Event: %s" % key)

{ "keys": ["ctrl+shift+e"], "command": "goto_import"}, { "keys": ["escape"], "command": "yolO", "context": [ {"key": "goto_import", "operator": "equal", "operand": true} ]

0 Likes

#4

That is correct, you need to share a global state. Which is where global variables come into mind. There are other options but they all follow the same principle and globals are just the easiest.

Make sure you compare against the view’s ID. You most likely want to do this for multiple views at the same time, so you should use a dictionary with an entry for each view.

0 Likes

#5

Nice. I got it working using globals. Thank you so much for your help!

0 Likes