Workflow & Tools

Snippets Saved My Life: How Sublime Text 3 Snippets Changed Everything

We are always striving to find better, faster ways to do the mundane tasks we have in our lives.

We got bored with having to make our coffee in the morning, so some brilliant mind created an automatic coffee maker with a timer so we could tell that machine when to make our coffee and how much of our coffee it should make.

We grew weary of the painful necessity of talking to actual human beings in order to have food arrive at our front doors, so the greatest pizza scientists in the world made it possible to order a lovely cheese pizza–just for me–by texting a single emoji. ?

We became so incensed at our watermelons constantly rolling away from us that the top watermelon doctors on the planet engineered square watermelons.

…Yes, the first milestones in human advancement that I can think of are all related to food and I will make no apologies for that.

When I’m not eating food or thinking about eating food, though, I’m probably working on a fabulous WordPress website using my editor of choice, Sublime Text 3 (ST).

ST is simple, yet robust, and offers countless packages to help speed along your development process. In addition to offering fully-developed packages for mass consumption, ST also offers the opportunity to craft custom snippets to take the legwork out of the things you type over and over again from day to day. In this post, we’ll show off a handful of examples we’ve picked up along the way as well as some that we’ve crafted for our specific uses at WDS.

What are snippets?

Snippets are a quick, shorthand way to type out a longer or more elaborate string or output. As you’ll see in our examples below, snippets can be extremely robust and can be customized to fit your needs.

How do I make a snippet?

ST3 makes it super easy to create a snippet. You simply select Tools > Developer > New Snippet from the toolbar menu and you’re off to the races!

snippet-create-new-snippet

ST3’s website offers some great information on snippets and how they are setup.

In order for a snippet to be used later on, it must be saved in the proper place. ST3 will typically place you in the proper directory when you save your new snippet, but if it does not you will need to look for User > Library > Application Support > Sublime Text 3 > Packages > User and save your snippets there with the .sublime-snippet file extension.

Comment Snippets

Comments are key. They let the person coming after you know what you were doing and why; they also let you know what you did and why when you come back to your code in six months. They are the trail of breadcrumbs leading you back to the genesis of your reasonable thought process. If there are no comments, how are we to know why you coded something a certain way?

WDS is a big proponent of docblocks and inline comments throughout our PHP, JS, and Sass files. We should make our files easy to understand and leave no question as to why we chose to do things This Way rather than That Way.

Recently we upped our Sass partial comment game by making it a standard to add a comment after the closing bracket to indicate what is being closed. This helps with any Sass partial where are a parent selector contains a lot of information within it; we no longer have to scroll up the page to see where the selector is opened. This became tedious for me, though. I kept having to manually click down to the closing bracket, type a double // and then my comment. Oftentimes, ST would adjust the indentation of my closing bracket forcing me to take another step before I was ready to click inside of my selector, tab in, and begin my actual work.

Exhausting!

So, I created this handy little snippet:

<snippet>
    <!-- Type `bracket` and hit tab to open a bracket with a closing comment. -->
    <!-- Type the class for the element you are styling and it is placed at the top and in the comment after the closing bracket -->
    <!-- Hit tab a second time to put your cursor into a beautifuly tabbed spot within the bracket -->
    <content><![CDATA[
${1:this} {
    $2
} // ${1:this}
]]></content>
    <!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
    <tabTrigger>bracket</tabTrigger>
    <!-- Optional: Set a scope to limit where the snippet will trigger -->
    <scope>source.scss</scope>
</snippet>

Not only do we strive for clear comments in our theme files, but look at those comments in the snippet itself – you know exactly what it does without me having to explain it! Nonetheless, here is a snappy little gif so you can see it in action:

snippet-css-brackets

It was only then that I took a step back and began to look at the rest of the partial. What about a quickly utilized comment block at the top of the partial itself, or even one when we begin to style a parent element? Well, you’re in luck!

Here’s a snippet that will output a comment block at the top of a Sass partial:

<snippet>
    <!-- Type `partialcomment` or `pcomment` and hit tab to output a comment block. -->
    <!-- Type a short description of your partial and you're good to go! -->
    <content><![CDATA[
//--------------------------------------------------------------
// ${1:Partial Description}
//--------------------------------------------------------------
]]></content>
    <!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
    <tabTrigger>partialcomment</tabTrigger>
    <tabTrigger>pcomment</tabTrigger>
    <!-- Optional: Set a scope to limit where the snippet will trigger -->
    <scope>source.scss</scope>
</snippet>

snippet-partial-comment

And a modified version of the above for a smaller comment block above a parent selector:

<snippet>
    <!-- Type `selectorcomment` or `scomment` and hit tab to output a comment block. -->
    <!-- Type a short description of the element you are styling and you're good to go! -->
    <content><![CDATA[
//-----------------------------------------
// ${1:Selector Comment}
//-----------------------------------------
]]></content>
    <!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
    <tabTrigger>selectorcomment</tabTrigger>
    <tabTrigger>scomment</tabTrigger>
    <!-- Optional: Set a scope to limit where the snippet will trigger -->
    <scope>source.scss</scope>
</snippet>

snippet-element-comment

So easy! One great thing you’ll notice in the snippets above is the <scope> setting. This is a great list of available scopes to be used with snippets. In our examples above source.scss guarantees that our snippet will only be available when editing a .scss file, so we don’t need to worry about any unexpected results while working in a PHP or JS file.

There is also a great package called DocBlockr which simplifies and expedites the process of writing docblocks above your functions. One of the settings I really love is the ability to set your name as the author of the function to eliminate any additional typing. Not only that, but it sniffs out any values being passed into your function and allows you to tab through and add additional details:

snippet-docblockr

Sass Snippets

Comments are beautiful and important, but there is also so much more we can do with snippets inside of a Sass partial. We use Bourbon Neat at WDS in our wd_s starter theme, so it only makes sense to use some snippets specific to the wonderful things available thanks to Neat.

Let’s start with one of the cornerstones of Neat: ridiculously simple columns. While putting these columns into place is easy as pie, that’s no reason to give up on making it even easier to use. Check out our span-columns snippet below:

<snippet>
    <!-- Type `span-columns` and hit tab to output the span-columns() mixin. -->
    <!-- The cursor will be placed inside of the mixin's parenthesis for ease of entering a column size. -->
    <content><![CDATA[
@include span-columns(${1:8});
]]></content>
    <tabTrigger>span-columns</tabTrigger>
    <description>Set a column width using Neat</description>
    <scope>source.scss</scope>
</snippet>

snippet-span-columns

Of course, there is a chance we’ll want to change the size of this column at a larger breakpoint. It’s a good thing we have a quick little snippet for that, too!

<snippet>
    <!-- Type `media` and hit tab to output the media() mixin. -->
    <!-- The cursor will be placed inside of the mixin's parenthesis for ease of entering a breakpoint. -->
    <content><![CDATA[
@include media(${1:\$tablet-landscape}) {

}
]]></content>
    <tabTrigger>media</tabTrigger>
    <description>WDS Media Query</description>
    <scope>source.scss</scope>
</snippet>

 

snippet-media-query

Sometimes we need something a bit more simpler, though. Adjusting margins and paddings on an element are no huge task, but there are going to be times when we just need a fresh reset on the margin and padding of an element to zero. Why manually type out the values for margin and reset when we can type a single word, hit a single key, and have a beautifully simple element free of margin and padding? The answer is “Don’t manually type it out,” ya big turkey!

<snippet>
    <!-- Type `margin reset` and hit tab to output the margin-padding-reset mixin. -->
    <content><![CDATA[
@include margin-padding-reset;
]]></content>
    <tabTrigger>margin reset</tabTrigger>
    <description>Reset the margin and padding</description>
    <scope>source.scss</scope>
</snippet>

snippet-margin-reset

PHP

We work in and love WordPress, so most of our snippets are WP-centric. However, that doesn’t mean that we don’t have some more generalized snippets for good ole PHP. These mostly help us debug issues or print data to the front-end for testing purposes. I make frequent use of an echoprintr snippet first shared with me by Justin Sternberg:

<snippet>
    <!-- Type `echoprintr` and hit tab to output the print_r function wrapped in xmp tags mixin. -->
    <!-- The cursor will be placed inside of the print_r function. -->
    <!-- Hitting tab will palce the cursor before the colon inside the opening xmp tag for the addition of helper text. -->
    <content><![CDATA[
echo '<xmp>${2}: '. print_r( ${1}, true ) .'</xmp>';$0
]]></content>
    <tabTrigger>echoprintr</tabTrigger>
    <scope>source.php</scope>
</snippet>

snippet-echoprintr

Need to view the contents of an array or an object? Give this sweet little var_dump snippet a whirl and let it brighten your day:

<snippet>
    <!-- Type `echovardump` and hit tab to output the print_r function wrapped in xmp tags mixin. -->
    <!-- The cursor will be placed inside of the var_dump function and inside of the preceding <strong> tags. -->
    <content><![CDATA[
echo '<strong>${1}:</strong><br>', var_dump( ${1} ), '<hr>';
]]></content>
    <tabTrigger>echovardump</tabTrigger>
    <scope>source.php</scope>
</snippet>

snippet-echovardump

WordPress Snippets

Of course, as mentioned above, WordPress is really our bread and butter here at WDS, and we love bread and butter. WordPress offers a ton of helpful hooks, filters, and template tags to customize your custom WP build to your heart’s desire. We’ll show off just a few snippets used during theme setup and throughout the entire theming process.

We know our website is going to have images. Your website is going to be some sweet combo of images and text, and we need to make sure we have the proper image sizes being served at the proper times for whatever use cases we need. Have a massive hero section at the top of your page and need an image sized and cropped to specific dimensions? Have a river of posts below that massive hero with smaller, yet just as important, featured images? Adding those image sizes in WordPress is easy peasy with add_image_size, but with a nifty snippet we can make that even easier peasier:

<snippet>
    <!-- Type `add_image` and hit tab to output the add_image_size function. -->
    <!-- The cursor will be placed inside of the function where you can enter the name of your custom image size. -->
    <!-- Hitting tab once will allow you to set the width of the image. -->
    <!-- Hitting tab a second time will allow you to set the height of the image. -->
    <!-- Hitting tab a third time will select the entire crop setting. This can be a boolean (true/false) or an array with more custom settings. -->
    <!-- If using the crop array, hitting tab again will allow you to specify the x-crop position. -->
    <!-- If using the crop array, hitting tab a final time will allow you to specify the y-crop position. -->
    <content><![CDATA[
add_image_size( '${1:foo}', ${2:300}, ${3:350}, ${4:array( '${5:left}', '${6:top}' )} );
]]></content>
    <tabTrigger>add_image</tabTrigger>
    <description>Register a new image size with WordPress</description>
    <scope>source.php</scope>
</snippet>

snippet-add-image-size

 

The power of WordPress lives within its loops. The loop is the life-force by which all posts exist. We need the loop to display our content, but we don’t need the loop to be a potentially confusing and hard to remember series of strings and if/else statements. The following loop assumes you have already established the $args for your new instance of WP_Query. Once those arguments are set, simply type loop, hit tab, and voila!

<snippet>
    <!-- Type `loop` and hit tab to output a simple WP_Query loop. -->
    <content><![CDATA[
<?php \$foo_query = new WP_Query( \$args ); ?>

<?php if ( \$foo_query->have_posts() ) : ?>

    <?php while ( \$foo_query->have_posts() ) : \$foo_query->the_post(); ?>

    <?php endwhile; ?>

<?php endif; ?>
<?php wp_reset_postdata(); ?>
]]></content>
    <tabTrigger>loop</tabTrigger>
    <description>A custom WordPress Loop</description>
    <scope>source.php</scope>
</snippet>

snippet-loop

Now you’ve got a loop where you can pull in content and display it to the outside world. But, what happens when the people viewing your website come from different parts of the world? You want every person to be able to have the same experience no matter what language their preferred language, right? It sounds like you might need to internationalize your text strings! This is a key component of anything we develop at WDS; we always want to make sure that any text string in a theme or plugin is going to be easily translatable to other languages. If you haven’t hopped aboard the i18n train just yet, read up on what it is and why it’s so important. We’ll wait here.

All done? Good! Now you’re ready to use this slick ST snippet for ease i18n strings:

<snippet>
    <!-- Type `i18n` and hit tab to output a ready-to-use escaped and translatable string. -->
    <!-- The cursor will initially be placed where your text string needs to be entered. -->
    <!-- Hitting tab a second time will allow you to type your textdomain. -->
    <content><![CDATA[
<?php esc_html_e( '${1:some text}', '${2:textdomain}' ); ?>
]]></content>

    <tabTrigger>i18n</tabTrigger>
    <description>i18n a text string</description>
    <scope>source.php</scope>
</snippet>

snippet-i18n

jQuery

Last in our list but certainly not least is jQuery. While you may not always require any fancy jQuery for your project, it’s always nice to have an easy way to quickly create a JavaScript file from which wonderful jQuery goodness can bloom. With the help of JS Mastermind Camden Segal, the following starter script was created and later spun into an easy to use snippet. It provides us with sample variables, functions, and lots of great inline comments to help guide us along our way. It’s incredibly easy to extend and even easier to read–no jQuery Soup over here!

Take a look at the snippet itself, then see it in action below:

<snippet>
        <!-- Type `jquery-wds` and hit tab to output a ready-to-use jQuery function. -->
        <content><![CDATA[
/**
 * Foo Script
 */
window.Foo_Object = {};
( function( window, \$, that ) {

    // Private variable
    var fooVariable = 'foo';

    // Constructor
    that.init = function() {
        that.cache();

        if ( that.meetsRequirements() ) {
            that.bindEvents();
        }
    };

    // Cache all the things
    that.cache = function() {
        that.\$c = {
            window: \$(window),
            fooSelector: \$( '.foo' ),
        };
    };

    // Combine all events
    that.bindEvents = function() {
        that.\$c.window.on( 'load', that.doFoo );
    };

    // Do we meet the requirements?
    that.meetsRequirements = function() {
        return that.\$c.fooSelector.length;
    };

    // Some function
    that.doFoo = function() {
        // do stuff
    };

    // Engage
    \$( that.init );

})( window, jQuery, window.Foo_Object );
]]></content>
    <tabTrigger>jquery-wds</tabTrigger>
    <description>Insert a Javascript function - the WDS way</description>
    <scope>source.js</scope>
</snippet>

snippet-jquery

Wrapping Up

At this point, you’ve seen a handful of snippets which can save you time and headaches by taking almost all of the legwork out of building sometimes complex functionality. At the end of the day, saving time is key; as the adage goes, “Time is money.” When we can cut time off of our development schedule by automating standard processes, not only are we saving time and money but we also begin to look at our work from a completely different viewpoint. We can take a step back, look at the big picture, and pick out the trouble spots or redundancies in our work and find a way to chop those down dramatically.

Take a moment to think about the code you write and how much of it is used from project to project. Then, create your own snippet to save yourself some time when you’re in the trenches day in and day out. Share any snippets you’ve created to boost your workflow or any helpful snippets you’ve come across in the comments below!

Comments

13 thoughts on “Snippets Saved My Life: How Sublime Text 3 Snippets Changed Everything

  1. hi,
    I have created snippets for the codes which we use repeatedly. How I can place those snippets folder(like a source folder) so that any team member can access it and if I made any change in any snippet file, each team member can have that updated snippet file without manually saving it?

    Thanks.

    1. I don’t know of anything that will automatically update across the board for all users the way you’re asking – but what we do is create shared folders in some kind of file sharing platform (whether that’s Dropbox, Google Drive, etc.) so everyone has access to the snippets at any time. If they need to change, they need to be manually updated and everyone would need to go manually copy them down again.

      I guess a decent solution may be a Github repo? Everyone could just clone the repo into their snippets directory and anytime something is updated, they just pull and get the fresh version.

    2. Just a little late to the party, But, There is a sublime package syncing that you can use and add into a repo. I use it to keep sublime up to date between my Virtual machine and Host.

      1. Nice! I’ve since moved from Sublime Text to VS Code, but that’s a helpful tip. Thanks for sharing!

  2. Hi Corey!
    I’m using ST3 for writing latex reports and I’m really interested in creating snippets. However some shortcuts are already used by default snippets. I’ve been looking, but I’m not able to find all the snippets… Is there any way to delete these duplicated (and hidden) snippets?

    Thank you 🙂

  3. Hi,
    Is there any way to add the author and the date the file was created using snippets?

    Thanks! 🙂

    1. Where would you be looking to add them? If memory serves, I believe you can set defaults for something like a Docblock to set your name by default as the @author. I bet there is some way to grab the file creation date in Sublime, however it’s been about 6 months since I’ve last used it. I wound up moving over to VS Code after hitting some speed bumps with ST3 and it has an equally robust snippet system – I was able to port over my existing ST3 snippets without too much legwork.

      Let us know if you find a way to grab the file creation date!

  4. Well explained , especially in the beginning, how article was brought up, with coffee and pizza examples 🙂 Thanks Collins it was helpful.
    1. AdvancedNewFile package helps you create files using keyboard(only) just give the path.
    2. Blade Snippet for php>Laravel devs, helps in typing @ syntax in blade file eg. @if
    3. Laravel 5 Artisan for php>Laravel devs, helps in executing artisan command right from ST3.
    4. Laravel Blade Highlighter also for php>Laravel devs, this just highlights the blade commands.

  5. The path that Sublime is defaulting to is your User package, and is indeed the best place to store your snippets. That package is meant to contain your own specific customization to Sublime text, and Sublime makes sure to always load that package last to ensure that your changes are always applied.
    That said, you can create your own directory structure inside of the User package and store the snippets there. For example you could create a snippets folder, and then inside of that folder folders for your different uses .

  6. Just a little late to the party, But, There is a sublime package syncing that you can use and add into a repo. I use it to keep sublime up to date between my Virtual machine and Host.

Have a comment?

Your email address will not be published. Required fields are marked *

accessibilityadminaggregationanchorarrow-rightattach-iconbackupsblogbookmarksbuddypresscachingcalendarcaret-downcartunifiedcouponcrediblecredit-cardcustommigrationdesigndevecomfriendsgallerygoodgroupsgrowthhostingideasinternationalizationiphoneloyaltymailmaphealthmessagingArtboard 1migrationsmultiple-sourcesmultisitenewsnotificationsperformancephonepluginprofilesresearcharrowscalablescrapingsecuresecureseosharearrowarrowsourcestreamsupporttwitchunifiedupdatesvaultwebsitewordpress