How to create a Sublime Text snippet

2011-12-07

editors,
sublime text

Snippets are chunks of text that you can have your editor paste in when you type a shortcut. Here's how to create them with the Sublime Text editor. Update I know use Visual Studio Code so I'm not sure whether this still works.

Sublime Text snippets uses the same format as TextMate ones, which is handy. To create one, select Tools > New Snippet... A new Sublime document will open. Type your text inside the CDATA block. Some variables are available, more or less useful:

$TM_CURRENT_LINE

The content of the line on which the snippet is called

$TM_CURRENT_WORD

the word in which the caret is located.

$TM_FILEPATH

The absolute path of the file

$TM_LINE_INDEX

The position of the caret within the current line

TM_LINE_NUMBER

The line number where the caret was

$TM_SELECTED_TEXT`

The selected text (only works when calling snippet from meny or with shortcuts)

Slightly more useful are your own custom variables - you can create them in the .tmPreferences files inside the packages. Use Miscellanous.tmPreferences to apply them to all packages. Those files are in XML (plists in fact), and you need to find a node with key "settings" and add a fragment like this

Then save the file into Packages/User (so that it doesn't get overwritten when you upgrade).

But the most useful are tab stops - $0 is where the caret will placed after the snippet is pasted in, and $1, $2 etc are placeholders, i.e. positions where you can get to by using the tab key. So for example

<h1 id="$1">$2</h1>$0

The caret will be placed at $1, then when you tab it'll jump to $2, then finally to its resting place of $0.

Even better, with 'mirrors' you can edit more than one placeholder at once, for example

<$1> That was a $1 tag</$1>$0

When you tab, and type, say 'h1' , all the tab stops marked $1 will have 'h1' in them. But that's not all.

You can also use regular expressions to modify a mirror before replacing it. For example, int his completely contrived example

${1/(.+)_(.+)/\u\1 \u\2/} : $1

If you type "john_lennon" on the right, the left will transform it to "John Lennon"

The rest is easy - in the snippet file comment out the <tabTrigger>xxx</tabTrigger>, and replace the text with whatever you want to use to call your shortcut up - whenever you type that followed by tab, the snippet will be inserted.