I have a plugin for Sublime but I want to do something when the user types a }
or ;
I've tried to handle it on a on_modified
event but I can't quite get it to work.
Is this the best approach to take?
Add a new keybinding that is bundled with your plugin. As an example, here is the default keybindings that trigger the auto-pairing of curly brackets:
{ "keys": ["{"], "command": "insert_snippet", "args": {"contents": "{$0}"}, "context":
[
{ "key": "setting.auto_match_enabled", "operator": "equal", "operand": true },
{ "key": "selection_empty", "operator": "equal", "operand": true, "match_all": true },
{ "key": "following_text", "operator": "regex_contains", "operand": "^(?:\t| |\\)|]|\\}|$)", "match_all": true }
]
},
{ "keys": ["{"], "command": "wrap_block", "args": {"begin": "{", "end": "}"}, "context":
[
{ "key": "indented_block", "match_all": true },
{ "key": "setting.auto_match_enabled", "operator": "equal", "operand": true },
{ "key": "selection_empty", "operator": "equal", "operand": true, "match_all": true },
{ "key": "following_text", "operator": "regex_match", "operand": "^$", "match_all": true },
]
},
{ "keys": ["{"], "command": "insert_snippet", "args": {"contents": "{${0:$SELECTION}}"}, "context":
[
{ "key": "setting.auto_match_enabled", "operator": "equal", "operand": true },
{ "key": "selection_empty", "operator": "equal", "operand": false, "match_all": true }
]
},
Note that by using a single character as a keybinding, you are intercepting the keypress and it will not show up in the buffer. If you want the character to be sent to the buffer, you will need to put it there as part of your command.
You can see that in the example. The two insert_snippet
commands wrap any arguments with curly-brackets: "contents": "{$0}"
and the wrap_block
command sends the curly-brackets as beginning and ending args: "args": {"begin": "{", "end": "}"}