Working with code snippets in Sublime Text 3

This is another article about my transition from Netbeans to Sublime Text 3. This time I’m going to handle code snippets topic. This is another area, which is much better solved in Sublime Text 3 than in Netbeans.

This article is generally based on “Working With Code Snippets In Sublime Text” blog text from hongkiat.com. And — of course — wonderful, yet unofficial Sublime Text documentation’s chapter about snippets. With some my personal additions and updates.

Inserting a snippet

Snippet’s insertion in Sublime Text is (as nearly everything) lightning-fast:

  1. Type (start typing) snippet’s keyword:
    1. This will open a standard Sublime Text code completion helper list.
    2. It might be a little bit crowded with entries, especially, if you installed PHP Completions Kit or similar plugin.
    3. Hit Enter to confirm.
  2. Alternatively, select Tools > Snippets:
    1. This will bring a magical “Command Palette” with Snippet: inserted and this limits entries to snippets only.
    2. Select snippet ( and arrows)
    3. Hit Enter to confirm.

The Netbeans-like keyboard shortcuts in Text 3 article (Other keyboard shortcuts section) contains tips, how to add own keyboard shortcut to Tools > Snippets menu item, to be able to execute it from keyboard. May be interesting for you, if you prefer this way of inserting snippets.

Browsing snippets

There is a really impressive number of code snippets them available (10 pages!). Among them as obvious as:

So, you should browse this repository, before you continue to the next chapter and start creating own snippet.

There’s a AAAPackage​Dev can help to build and manage own snippets. I didn’t check it though. Writing own snippets without any aid is a quite easy process.

Creating your first snippet

Start with selecting Tools > New Snippet. You should get something like that:

<snippet>
    <content>< ![CDATA[
Hello, ${1:this} is a ${2:snippet}.
   
    <!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
    <!-- <tabTrigger>hello -->
    <!-- Optional: Set a scope to limit where the snippet will trigger -->
    <!-- <scope>source.python -->

]]></content></snippet>

Save it. Where? It is up to you:

  • Sublime Text 3 browses many locations, so you can many choices to pick.
  • The best option is IMHO Packages\User folder in application data.
  • (%AppData%\Roaming\Sublime Text 3\Packages\User in Windows 7).
  • This folder will never be overwritten by ST, even during upgrade process.
  • I suggest using a new subfolder (either Snippets or with name of snippet’s language).

Make sure, that your snippet code is saved within a .sublime-snippet extension.

In this example, I’ll make my favorite “PHP Debug” snippet:

  • It uses print_r,
  • outlined with HTML <pre> tags and
  • adds die() in the end.

So, my snippet body is:

<content>< ![CDATA[
    echo '<pre>'.print_r($variable, TRUE).'</pre>';
    die();
]]></content>

The tabTrigger and scope are optional, but we’ll make use of it to:

  • define prn trigger text and
  • narrow this snippet to PHP language only.

You’ll find information about scopes in ST3 in an unofficial documentation.

Entire snippet code should like like that:

<snippet>
    <content>< ![CDATA[
echo '<pre>'.print_r(${1:$variable}, TRUE).'';
die();
    <tabtrigger>prn</tabtrigger>
    <scope>source.php</scope>
]]></content></snippet>

After saving this code / file, test, if it works:

  • open any PHP code file,
  • type prn and
  • hit Enter or Tab.

You can also select this snippet from Tools > Snippets menu.

Congratulations on your first Sublime Text 3’s snippet. We’ll handle ${1:$variable} part in the next chapter.

Field markers

Sublime Text provides you with the ability of highlighting specific fields (which user may want to edit, after inserting the code snippet) and cycling through them using Tab key. These field markers can be specified as:

  • placeholders with no value:
    • just $ character and order number,
    • i.e. My name is $1 and I'm $2 years old,
  • simple placeholders with default values:
    • the ${} character sequence with order and default value inside,
    • i.e. My name is ${1:Maria} and I'm ${3:34} years old.
  • nested placeholders with default values:
    • for example: Example: ${1:Outsider ${2:Insider}}.

So, for example:

  • our ${1:$$variable} causes ST3 to highlight this places in snippet as the only editable field marker and
  • fill it with $variable initially (notice escape char — $).
  • Immediately after inserting snippet, user can edit variable.

You can, of course have, more field markers in one snippet, and user can cycle through them using Tab key, with or without filling particular field. User can break Tab-cycle sequence any time, by hitting Esc.

Note, that you can use mirrored fields markers, that is — use one field in two or more places. When user of your snippet edit the first one, the rest will be populated in real time with the same value. An example from unofficial docs:

First Name: $1
Second Name: $2
Address: $3
User name: $1

In this example, part after User name will be populated with the same value as user enter for First Name.

Important aspects of writing own snippets body

  1. As you already know, the $ character must be escaped with another $.
  2. Entire snippet content must be included insider < ![CDATA[...]]>. Your snippet won’t work, if you skip this.
  3. Always use tabs for indentation. Sublime Text 3 will convert them on-the-fly to user-set indentation type.
  4. Your snippet code must not contain ]]> characters sequence, or it will cause XML parse error.

Read chapter “Snippets: Snippets File Format” for a workaround on the last problem.

Some other general rules

Keep these in mind, if you’re working with code snippets in Sublime Text 3:

  1. Snippet is always entered with respecting indentation — all lines will be properly indented, no matter, where cursor previously was.
  2. If you wish to be able to enter particular snippet from both quick list and “Command Palette” (Ctrl+Shift+P):
    1. You need to save your snippet under the same name as tabTrigger value.
    2. In example above, we have prn trigger and thus such snippet must be saved as prn.sublime-snippet
    3. Only that way user will be able to bring it by writing prn in both editor (quick list) and “Command Palette”.
  3. With insert_snippet command, you can define simple snippets, bind to specific keyboard shortcuts.

These snippets will be very simple, but will be bind directly in user key bindings configuration file. Without need of writing own snippet file.

Follow to Netbeans-like keyboard shortcuts in Text 3 article to Quick HTML shortcuts section for more information about defining own keyboard shortcuts and inserting code snippets with them.

Final words

These are basics of snippets in ST3. There’s more.

However, these are advanced topics, that goes beyond article scope. Consult unnoficial docs, if you’re interested in these areas.

Leave a Reply