By Brian StudwellMay 21, 2014

Sublime Text: Applying Code Snippets

One of the guiding principles of programming is the idea that we should use technology to make our lives easier. Make the machines do the grunt work! In that vein, let’s tangle with code snippets.

Code snippets, as the name suggests, are sections of code that you want to save and reuse later. Sublime Text has a very nice tool for creating snippets that can be tossed into your next document with the flick of a button. Here’s how:

1. Open a new blank document in Sublime.

2. Navigate to the Tools dropdown and click “New Snippet.” Some code will populate in a new tab.

New Code Snippet

3. Enter the code you want to reuse between the <content> tags.

Code Snippet Preview

4. Establish a tab trigger and scope, if you want.

Setting a scope tells Sublime the context in which you’ll be able to use the snippet; for instance .css files or even specific tags. If you don’t set a scope, the snippet will be universally available.

Setting a tab trigger is awesome, and I highly recommend it. Tab triggers allow you to type a short string anywhere in your document and hit tab to inject your code snippet into that spot. Hey presto.

To set the tab trigger, simply replace the word between the <tabTrigger> tags with your string of choice. For instance, I have some basic structural HTML with pieces of the HTML5 Boilerplate associated with the string h5bp. When I type h5bp and hit -tab- I’ve got instant structure.

5. Save your file.

This is a little tricky. Code snippets need to be stored in a specific file directory that’s hidden a few levels down. On Macs, from your User directory, navigate to your Library. If you can’t see your Library folder, find the gear icon in Finder and click it to access the settings dropdown. Click “Show View Options” and then check the box for “Show Library Folder” in the subsequent pop-out window.

From Library, move into Application Support. From there, move into Sublime Text 2, continue on into Packages, and finally, move into User. I told you it was a little ways down there. For clarity’s sake, that file path is:

~/User/Library/Application Support/Sublime Text 2/Packages/User/

This is where your snippets need to live. It’s a good idea to create subdirectories within this space for snippets of various types (CSS, JS, etc.). Save your file there with the extension .sublime-snippet and you’re good to go!

6. Take it for a spin. Open up a document in Sublime, type in the string you assigned to your snippet, and hit tab. Boom!

All of your snippets will also be available as a dropdown list with associated shortcuts from within the Tools menu under “Snippets…” This is clutch, should you not assign a tabTrigger or you forget what one is!

Accessing Code Snippets

List of Code Snippets


Check out more resources on Brian’s blog.