This is totally do-able, but you need to do something like map a key binding or use some other method to invoke the command since typing while there is a selection will replace the selection.
Snippets can contain the special placeholder $SELECTION
, which is replaced with whatever the selected text was at the time that you invoked the snippet (or nothing, if nothing was selected).
As an example:
<snippet>
<content><![CDATA[
/****** DEBUG *******
$SELECTION
********************/
]]></content>
</snippet>
You could use a key binding like the following to insert this snippet:
{
"keys": ["ctrl+alt+c"],
"command": "insert_snippet",
"args": {"name": "Packages/User/sample.sublime-snippet"}
},
This will replace any selected text by wrapping it with the snippet body, or just insert the snippet at the current cursor location if there is nothing selected.
Snippets that have a tabTrigger
defined also show up in the command palette, which is another way for you to insert the snippet. This can be useful if you only occasionally need to use a snippet and you don’t want to bind a specific key for it. Such a snippet shows up in the command palette as a command named Snippet: snippetName
(which also includes the tab trigger as a hint) where SnippetName
is the first part of the filename (in this example it would show up as Snippet: sample
).
If your snippet has a scope
defined in it, it won’t show up in the command palette if the scope doesn’t match, so you can use this to hide snippets for languages that you don’t want them to appear in.
In this case the key binding will still work even if the scope is not correct. In order to modify that behavior you need to modify the key binding as well so that it only operates in the given scope. For example, if we wanted the above snippet to only trigger for C code, we could do this:
"keys": ["ctrl+alt+c"],
"command": "insert_snippet",
"args": {"name": "Packages/User/sample.sublime-snippet"},
"context": [
{"key": "selector", "operator": "equal", "operand": "source.c"}
]
},