It’s possible in a couple of different ways.
space
is indeed a valid key, but it doesn’t work to use it without a modifier. However, you can create a key binding with a literal space in it to get a similar effect:
{
"keys": [" "],
"command": "do_something_space"
},
import sublime_plugin
class DoSomethingSpaceCommand(sublime_plugin.TextCommand):
def run(self, edit):
if not self.view.settings().get("is_widget", False):
print("Space was pressed in DoSomethingSpace")
self.view.run_command("insert", {"characters": " "})
An important takeaway here is that if you don’t explicitly insert a space in response to the command, you lose the ability to enter spaces in any files (which among other things can get in the way of you fixing the problem ;)).
Also, the command will trigger everywhere that space is pressed, which includes when you’re entering text in a quick panel, in the console input area, and so on. In these cases the views have a setting called is_widget
set to distinguish them, so in this example the indication that space was pressed only happens not within a widget.
Since you mention that you plan to do this for several characters, another alternative (assuming that what you’re doing in response is generally similar and could be handled by a single command) is something like this:
{
"keys": ["<character>"],
"command": "do_something_character"
}
import sublime_plugin
class DoSomethingCharacterCommand(sublime_plugin.TextCommand):
def run(self, edit, character):
if not self.view.settings().get("is_widget", False):
if character == " ":
print("Space pressed in DoSomethingCharacter!")
self.view.run_command("insert", {"characters": character})
The special key binding <character>
triggers for any entered character, and the command that you define will be passed character
argument to tell you what the character was.
The same caveats apply here with regards to the event triggering for more than just file views and that you need to handle the event by inserting the character that was pressed.