Snippets in Sublime text

March 05, 2017

Step by ever so small step, I am trying to learn the tools I use better. One thing I am particularly trying to get better at is automating in whichever small and simple ways I can think of. Being highly untrained, it still takes a bit of effort before I even actively notice an opportunity, but I may be improving. My latest discovery was how easy it is to create snippets in Sublime text (which remains my default editor).

What are they? Where?

Documentation is over here. Snippets are available in many shapes in various editors, they are basically a saved piece of text which can quickly be brought in using some kind of shortcut.

My particular use case here is creating image tags for this site. Each image has two resolutions, which means two image tags with different CSS classes, displayed depending on screen retina-ness. After endless instances of digging through previous texts to find, copy, paste and edit image links, it finally dawned on me that there had to be a better way. Surely, Sublime had a snippet concept hidden somewhere? How hard could it be?

Almost too simple, was the answer. Well, being Sublime you had to edit a text file in a special format - XML of all things in this case - but hey, given the circumstances it was very easy.

My image link snippet

            <img class="nonRetinaImage" src="../../images/${1:imageName}.${2:ext}" alt="${3:description}" title="${3:description}">
            <img class="retinaImage" src="../../images/${1:imageName}@2x.${2:ext}" alt="${3:description}" title="${3:description}">
        <!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
        <!-- <tabTrigger>hello</tabTrigger> -->
        <!-- Optional: Set a scope to limit where the snippet will trigger -->
        <!-- <scope>source.python</scope> -->

The Sublime docs are easy to follow. In fact, the example snippet you got when choosing to create one gets you very far. The text you want pasted goes between the content tags, in my case three lines consisting of a paragraph ending and my two image tags.

The tabTrigger tag means I get my snippet inserted whenever I type imgTags and hit tab. The whole thing is inserted, and text entry cursors are placed with a selection around the whole ${1:imageName} piece, which in the pasted text will simply say imageName. I enter the image name, then hit tab, and the cursor and selection is changed to the image extensions. I enter that, then hit tab again and get all four descriptions selected at once. I enter that and boom, all done.

Writing this took a lot longer than creating the snippet. Actually, I wonder if even a single manual copy, paste and edit of the image tags may not also take longer than creating the snippet …