By josh / June 26, 2013

How to wrap selected code with a snippet in Sublime Text

Reader Simon asks: What is the easiest way to wrap some existing code in an if statement, preferably using built-in Sublime features?

Snippets are the way to go here, but not all snippets support wrapping existing code. Simon didn’t mention what language he’s interested in, so for this example we’ll look at the JavaScript if snippet, which does support wrapping.

To wrap this snippet around a block of code, first select the lines you’d like to wrap, then launch the Command Palette and type snip if. Press Enter to insert the highlighted snippet, which wraps the selection.

(Prefixing the snippet name with snip restricts the Command Palette matches to snippets and allows you to use fuzzy matching to quickly find the appropriate snippet.)

Wrapping snippets around existing text with the Command Palette is a little awkward. If you find yourself using the same snippets repeatedly you can define a custom keybinding for your favorites.

Here’s a keybinding that binds Ctrl+Shift+I to the if snippet:

   "keys": ["ctrl+shift+i"], "command": "insert_snippet", 
   "args": { "name": "Packages/JavaScript/if.sublime-snippet" } 

P.S. Ready to take the next step to Sublime Text mastery? Go here:

About the author


Click here to add a comment

Leave a comment: