Search code examples
javascriptsublimetext3code-completionsublimetext-snippet

How can I omit (or delete) auto matching parenthesis when triggering a SublimeText custom snippet?


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>

Solution

  • 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.