Let's say that I have some string, X
, and that I want this to be enclosed within some other strings, for example like this: \emph{X}
. Is there some tool that lets me do this quickly, for example through selecting the text and pressing a short-cut on my keyboard? I'm working in Sublime text in macOS Sierra.
This is something that is possible from directly within Sublime using a key binding that inserts a snippet, where the snippet body is told to include the text that is currently selected.
For your example above, the following key binding will wrap the selection in \emph{}
. I used Super+W for my own testing, but you probably want to pick something better for your own purposes.
{
"keys": ["super+w"],
"command": "insert_snippet",
"args": {"contents": "\\emph{${0:$SELECTION}}"},
"context": [
{ "key": "selection_empty", "operator": "equal", "operand": false, "match_all": true },
]
},
The inclusion of context
here makes the key binding only active while all of the cursors have at least one character selected. If desired you can remove the context
section entirely, in which case the key binding will either insert the snippet and leave the cursor between the braces, or wrap the selection, depending on the state of the selection.
If your snippet is more complex and involved than this (e.g. multiple lines), trying to insert the entire body of it into the key binding can be a little taxing. In that case, you probably want to use an external snippet instead.
To do that, you can select Tools > Developer > New Snippet...
from the menu, and use a snippet such as the following, which you should save in the location that Sublime defaults to:
<snippet>
<content><![CDATA[
\emph{${0:$SELECTION}}
]]></content>
<!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
<!-- <tabTrigger>hello</tabTrigger> -->
<!-- Optional: Set a scope to limit where the snippet will trigger -->
<!-- <scope>source.python</scope> -->
</snippet>
With this in place, the key binding from above needs to be modified to tell the insert_snippet
command to insert the snippet with a particular file name instead of with raw content:
{
"keys": ["super+w"],
"command": "insert_snippet",
"args": {"name": "Packages/User/emph.sublime-snippet"},
"context": [
{ "key": "selection_empty", "operator": "equal", "operand": false, "match_all": true },
]
},
Things to note here are that the key binding files are JSON, and so the contents of the snippet need to be adjusted slightly to make them valid JSON. In the example above that means using \\
instead of just \
to specify \emph
.
Snippets in general also have their own special characters in them, so if you for example need to insert a $
you need to quote it as \$
so that Sublime knows what you mean; this is true regardless of whether the snippet is in a snippet file or inline.
More information on key bindings and snippets can be found in the Unofficial Documentation for a more complete picture of everything that's possible with them.