2

I'm trying to create a JavaScript arrow function snippet in SublimeText. It should be available when I type an open paren: (. I want to be able to tab to create this:

() => {}

With auto match enabled (a feature I like, normally), I can't figure out how to avoid this:

() => {})

Here is the code I have so far, which works great except for the auto match issue:

<snippet>
    <content><![CDATA[
(${1}) => {$2}
]]></content>
    <tabTrigger>(</tabTrigger>
    <scope>source.js</scope>
</snippet>
user6689821
  • 147
  • 11

1 Answers1

2

Snippets can only insert text or replace the selected text - they can't modify text elsewhere in the document, even next to the text caret. I think that the best way to achieve what you want is to use a keybinding, that will take precedence over the default auto_match_enabled behavior (which is also a keybinding) when ( is pressed, and get the keybinding to insert the snippet, avoiding the need for a separate .sublime-snippet file.

{
    "keys": ["(", "tab"], "command": "insert_snippet", "args": { "contents": "(${1}) => {$2}" }, "context":
    [
        { "key": "selector", "operator": "equal", "operand": "source.js" }
    ]
},

Note that, if you want the snippet to still show up in the Command Palette Snippet: options, you can keep your .sublime-snippet file without any negative effects - the keybinding will take precedence over the tab trigger defined in the snippet.

Keith Hall
  • 15,362
  • 3
  • 53
  • 71
  • That works! Thank you. Am I correct in assuming that a snippet cannot delete existing content? Only insert? Also, do you happen to know if this API is documented? I'm not following what's happening in the "context" key here (but I'd also like to be able to build my own in the future). – user6689821 Apr 10 '17 at 15:22
  • 1
    I believe the closest you can get to a snippet deleting existing content is to use it in a case such as this (expanding as a result of a key press) and then selecting some text before you press the key, which would replace the selection with the snippet. Note that in this case the special variable `$SELECTION` is available to your snippet. You could also use a macro (again in response to a key press) that would first execute commands to delete some text and then expand the snippet. – OdatNurd Apr 10 '17 at 16:26
  • 1
    Additionally, documentation on the usage of contexts in key bindings is available as well. There are a set of contexts that Sublime ships with, but using plugin code you can construct your own if needed. http://docs.sublimetext.info/en/latest/reference/key_bindings.html – OdatNurd Apr 10 '17 at 16:28
  • Thanks, @OdatNurd I looked at the docs, but somehow I missed that part of the page. :/ Still, there seems to be some room for improvement. I'll have to play around with it. Thanks for the tips! – user6689821 Apr 10 '17 at 16:43