How to Create a Sublime Text 2 Snippet
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 2 editor.
Update: found some unofficial Snippets documentation
Sublime Text 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:
- The content of the line on which the snippet is called
- the word in which the caret is located.
- The absolute path of the file
- The position of the caret within the current line
- The line number where the caret was
- 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
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
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
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
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