Enabling wrap mode in Sublime Text’s find

By josh / April 21, 2014

Subscriber Turang P. wrote to me a few days ago after the Find feature suddenly got weird on him:

Hi Josh,

Something has happened recently. When I used to use Find to look for something, it would Find until the last instance, then loop around to start from the start.

Now it wont loop and I need to do Find Previous.

Is there a setting that changes this?

This question hits on one of my pet peeves in Sublime’s user interface: The option or mode buttons that appear to the left of search-related panels like Find, Replace and Find in Files.

These buttons use cryptic icons instead of clear labels, and it’s never clear to me whether they’re selected or deselected. To make them even more confusing, most of them are global. If you enable the regular expression setting in Replace, for example, it’ll also be active when you go to use Find later.

These quirks kept me from using Sublime’s search features for quite a while when I first switched to Sublime.

This is definitely one of those cases where icons don’t tell the whole story, and text labels would have been much more effective.

rant mode off

To answer Turang’s specific question, I wrote back that he’d disabled the Wrap setting. This is the icon with the chunky little arrow that loops back on itself (ugh, these icons are so bad I can’t even describe them!). It’s the forth icon from the left when the Find panel is open.

That button needs to be selected to enable wrapping. But is it “selected” when it’s darker or lighter? With the default theme, it’s darker when the button is selected.

Bonus tip: You can hover your mouse cursor over the buttons for a couple of seconds to see their names in a tool tip.

P.S. Want to improve your mastery of Sublime Text? Start here:

http://sublimetexttips.com/newsletter

How to tell if a plugin is Sublime Text 3 compatible

By josh / April 19, 2014

After my email last week about the SyncedSideBar plugin, reader Keith W. replied with an observation:

Are you sure that SyncedSidebar is ok for Sublime 3 ? cos it just says a plugin for Sublime 2

Sure enough, if you search for SyncedSideBar in Package Control, you see:

Sublime Text 2 plugin to sync project sidebar (folder view) with currently active file.

So is it, or isn’t it?

When I want to check which versions a plugin supports, I head over to the official Package Control website and do a search. Here’s the page for SyncedSideBar:

https://sublime.wbond.net/packages/SyncedSideBar

Right under the plugin’s name, there’s a green badge that tells you which versions of Sublime the plugin supports. In this case, it says ST2/ST3, so Sublime Text 3 is supported.

(While you’re looking at the SyncedSideBar there, check out the installs graph. See that spike on April 17? That’s you guys!)

Another hint: If you can see the plugin listed when you search for it in Package Control within Sublime, it’s almost certainly compatible. Package Control requires developers to specify which versions of Sublime their plugin works with, and it filters out the ones that you can’t use based on the version of Sublime you’re using.

If your favorite plugin isn’t ST3 compatible yet, maybe you could help the author port it. It’s a great way to get your feet wet with plugin development, and many times it’s not that difficult to do.

P.S. Want to improve your mastery of Sublime Text? Start here:

http://sublimetexttips.com/newsletter

How to change the default UI fonts in Sublime Text

By josh / April 19, 2014

It’s easy enough to change the type face and size of the fonts in Sublime’s editor window.

But now that you’ve bumped that font up so it’s not microscopic on your retina MacBook, suddenly the menus, side bar and command palette smaller than ever.

While it’s not as convenient as going from Melano to Inconsolata, Sublime does allow you to exert fine-grained control over the fonts it uses in other parts of the user interface.

These settings are controlled by the active theme. Sublime themes control the appearance of the chrome around the editor window–tabs, side bar, status bar, stuff like that. (The theme is not to be confused with the color scheme, which controls the look of the text in the editing panel, including syntax highlighting.)

You can edit the theme to tweak the appearance of individual user interface elements, including font size and weight and the type face used.

Sublime Text 2 users can find the files for the default theme under Data/Packages/Theme - Default. In Sublime Text 3, you’ll need to unzip the Packages/Theme - Default.sublime-packages file to find them.

In the Default.sublime-theme file, you’ll see a list of JSON rules that govern each piece of UI, like this:

{
    "class": "sidebar_heading",
    "color": [130, 130, 130],
    "font.bold": true,
    "shadow_color": [250, 250, 250],
    "shadow_offset": [0, 1]
},

For some examples of what you can do with this file, check out this post on the official Sublime Text forum.

P.S. If you love tweaking Sublime, you’d enjoy the Sublime Text Tips newsletter. To get it, go here:

http://sublimetexttips.com/newsletter

Some Sublime Text fans have a little fun at vim’s expense. And check out what they said about emacs…

By josh / April 19, 2014

The authors of the Sublime Text unofficial documentation (a great resource, by the way) get a little feisty when they address some of the other big dogs in the text editing world. When it comes to vi and vim, well…

This information is mainly useful for dinosaurs and people who like to drop the term RSI in conversations. Vi is an ancient modal editor that lets the user perform all operations from the keyboard. Vim, a modern version of vi, is still in widespread use.

Sublime Text provides vi emulation through the Vintage package. The Vintage package is ignored by default.

And emacs… Oh, emacs:

This information is hardly useful for anyone. Emacs is… Well, nobody really knows what emacs is, but some people edit text with it.

If you are an emacs user, you’re probably not reading this.

If text editor humor makes you smile, you’ll enjoy the Sublime Text Tips newsletter:

http://sublimetexttips.com/newsletter

These two plugins make Sublime’s side bar a whole lot more useful

By josh / April 12, 2014

Lately at my day job, I’ve been doing a lot of iPhone development. We’re a .NET shop, so we’re using a set of tools created by a company called Xamarin that allow us to write iOS and Android apps in C#. The technology is incredible, and I have nothing but respect for the Xamarin team, but …

I’m not a huge fan of the IDE I have to use. It’s slow. It’s buggy. Not a day goes by that I don’t wish I could just use Sublime.

But it does offer a few convenient features. One that I’ve come to rely on is the way it always selects the file you’re editing in the sidebar. If you want to rename or delete the file, you can just flick over the sidebar do the deed.

Sublime doesn’t work this way by default, but naturally it’s easy enough to replicate with a couple of plugins.

First, you’ll need to install a plugin called SyncedSidebar. It’s available in Package Control for Sublime Text 2 and Sublime Text 3.

Just install and go–no configuration required. Sublime will always highlight the current file, even expanding folders and subfolders to show the one you’re editing.

Now if you right-click the file, you’ll probably be disappointed at the options available. Sublime’s default context menu in the side bar is pretty sparse. You can rename and delete a file, but not a whole lot more.

That’s why you need SideBarEnhancements. This one is near the top of my must-have plugins list. It adds tons of menu items including Cut, Copy and Open in Browser. You can even get an Open With menu that lets you open files with external apps like Photoshop or Illustrator.

With these two plugins in place, Sublime’s side bar is a lot more useful.

For more ways to streamline your Sublime Text workflow, check out:

http://sublimetexttips.com/newsletter

Two of your favorite tools, joined in quasi-perfect harmony

By josh / April 5, 2014

In the two years I’ve been writing about Sublime Text, one question has come up over and over: “Can I run a terminal inside of Sublime?”

Sublime doesn’t support this natively, and there were no plugins available that allowed you to run terminal commands without leaving the comfort of the editor.

Until last week, that is.

That’s when Chris Simpkins released the first version of Glue, a shell plugin with support for Sublime Text 2 and Sublime Text 3.

Glue allows you to run shell commands and view the output directly in Sublime. You can use it to perform a ton of useful tasks like interacting directly with the command line versions of Git or Mercurial, opening files, and using system utilities like grep.

It supports a variety of shells, inluding bash and zsh on OS X and Linux and PowerShell on Windows. You can even use it with scripting languages like Ruby, Python and JavaScript (via Node.js).

Now, there are a couple of caveats. You can’t run commands that require superuser powers (sudo), and you aren’t able to run commands that require interactive user input. (And no, you can’t use it to run emacs inside of Sublime. Why would you even ask?)

Even with those limitations, Glue is an extremely powerful plugin.

For all the details, check out the Glue documentation.

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

http://sublimetexttips.com/newsletter

How to easily get the path of the file you’re editing in Sublime Text

By josh / March 29, 2014

I got an email recently from Jesse, a subscriber who says he “pretty much lives in Sublime.”

Still, he had a minor bone to pick:

Often I’ll need to do something in the command line with the file I’m currently in. There’s no convenient way (that I’m aware of) to copy the full path to the clipboard.

To cope with this, he adopted a workaround:

I always end up hovering on the tab and doing some short-term mental memorization and then switching to the command line and typing it in.

So painful! I can’t begin to count the number of times I’ve done similar things.

Fortunately, there IS a way to easily grab the full path of the file you’re editing.

Ready?

Just right-click in the editor panel and select Copy File Path.

Boom.

It took me a while to find it when I first switched to Sublime, because other editors tend to stash this feature in a right-click menu that hangs off of the current file’s tab.

If that’s what you’re used to, you can easily add Copy File Path to the tab right click menu.

Open a new tab and paste the following:

[
    { "command": "copy_path", "caption": "Copy File Path" }
]

Save this in a new file named Tab Context.sublime-menu in your Packages/User folder.

For more ways to streamline your Sublime Text workflow, check out:

http://sublimetexttips.com/newsletter

If you do CSS, you *have* to install this plugin *right now*

By josh / March 26, 2014

I’m building a website for a client of mine. The site is aimed at people nearing retirement age, and I initially picked out a color scheme that used a lot of muted earth tones.

But … He decided he wants a brighter color palette. His exact words were, “We old people need cheering up.”

That means I need to go through the entire style sheet and change every single color.

I hate messing with colors in CSS. Maybe I’m the oddball here, but I don’t do it often enough that I’ve learned to “see the Matrix” and interpret hex colors in my head.

If that’s you, then stop everything and install the Gutter Color plugin.

Gutter Color displays a colored dot next to each line in your CSS file that contains a color. No more guessing about which color a given hex code represents! It makes it really easy to scan back through your style sheet if you can’t remember the hex code for alizarin crimson.

And … it supports SASS, Stylus and LESS files!

This plugin does require an external tool called ImageMagick, but it’s not hard to install. Sublime aficionado Wes Bos has an awesome writeup that walks through the installation on OS X and Windows.

Quick caveat: Gutter Color is less than a month old, and the GitHub page notes a few to-dos, like getting SASS and LESS variables working and fixing a conflict with Git Gutter. If those are a deal breaker for you, consider pitching in and helping to fix them!

For more ways to streamline your Sublime Text workflow, check out:

http://sublimetexttips.com/newsletter

This one simple Sublime Text tweak makes copying and pasting code a breeze

By josh / March 20, 2014

Pasting code from another file or from a sample you find on the Internet is a constant annoyance. The indentation levels hardly ever line up, so a quick copy-and-paste becomes an arduous formatting session.

And even if the indentation levels happen to match, chances are you didn’t select the leading whitespace, so you still have a hassle on your hands.

Think about it… If you copy and paste code 10 times per day on average, and spend 30 seconds messing with the indentation levels each time … Assuming you work 5 days a week, 50 weeks a year, you spend nearly 21 hours a year just fiddling with the tabs or spaces in front of your code!

Sublime’s Paste and Indent command fixes this by automatically adjusting the indentation of your pasted code to match the surrounding lines.

This command is bound to Ctrl+Shift+V on Windows and Linux or Shift+Cmd+V on Mac. Give it a try—it’s magical.

But … if you’re like me, you’ll find it’s impossible to fight muscle memory and find yourself falling back to the standard paste shortcut 90 percent of the time.

Fortunately, Sublime makes it easy to override its default shortcuts, so you can swap the bindings for the Paste command with Paste and Indent.

If you’re on a Mac, add the following to your Default (OSX).sublime-keymap file:

{ "keys": ["super+v"], "command": "paste_and_indent" },
{ "keys": ["super+shift+v"], "command": "paste" }

And if you’re a Windows user, you’ll want to edit your Default (Windows).sublime-keymap file and add:

{ "keys": ["ctrl+v"], "command": "paste_and_indent" },
{ "keys": ["ctrl+shift+v"], "command": "paste" }

For more ways to streamline your Sublime Text workflow, check out:

http://sublimetexttips.com/newsletter

Sublime plugins 101: How to write your own HTML5 template plugin

By guest / March 6, 2014

Why Write a Plugin?

Sublime Text is a powerful, full featured editor for manipulating text files, code, web pages, and more. At first use it might be hard to imagine that it would ever be missing anything. Then one day you find yourself wishing it had that one feature from that other editor you used to use. Or perhaps you have that moment of brilliance when you conceive an idea for a feature to end all features, and you realize you must write a plugin.

Plugins can be created for a variety of reasons and often are designed to solve some type of problem, shortcoming, or even just make our lives a little easier. Take a few moments to do a search on the Internet for “sublime plugins”. Go on, I’ll wait.

Take notice of the sheer number and styles of plugins available. Also note the “Top 10” lists, tutorials, guides, and unofficial document sites. Plugins range in features from auto-formatting text to validating code, HTML and web page stylesheets. If you feel that something is missing from, or could be done better in Sublime Text there is a good chance there is a plugin available. If not this is your chance to write one and make a difference!

Fear not. Writing and publishing your very own Sublime Text plugin is not only a fairly painless process, it can be a very rewarding experience! Creating an extension to your favorite text editor can take its abilities and your productivity to new levels. In this section we will think about what kind of feature we’d like to add to Sublime Text, decide on how it will behave and how someone would use this plugin. Later we’ll look into how we can share our creation with the rest of the world. So let’s get started.

How Do I Start?

One of the first steps to take involves not only deciding what you want to make, but how you and your users will use and interact with your plugin. Having thought this out will have an impact on where you begin when you start typing your first lines of code. Having some idea of how you envision your plugin working will help solidify the idea in your mind and make the transition into writing and implementing code easier.

For the purpose of demonstration let’s pretend you write a lot of web pages for clients. Much of your work involves creating the same HTML5 boilerplate code over and over again for each client or project you take on. So you’ve decided that you want to have some way in Sublime to quickly make a new HTML file with all the normal elements you would put into a new page. Think about what might go into that. Clearly you want your DOCTYPE, head and body sections. Perhaps you also put a meta tag with author information in every page you make. Would it be useful to include this in your output when you run your new imaginary plugin? You bet.

Tip

Imagine what your plugin would do when you run it. Try to visualize what the command might be called, or what shortcut key combination might make sense. Visualizing the final product can help you during design and implementation.

In our imaginary scenario there are already a few ideas starting to form. A user runs a command and a new tab opens up with a fresh, clean HTML5 template. Already this information is enough to provide some guidance on how we can start writing our plugin. Sublime Text supports a couple of types of plugins. In our case the type that makes the most sense is a WindowCommand. A WindowCommand is a plugin that works at a window level, meaning that the user does not have to have a file or empty tab already open to run your plugin. This is useful in our case because we want to create a new tab anyway!

Now we have some idea of what we wish to create, and a little information on what kind of plugin we can craft in Sublime to achieve this goal. I’m sure by this point you are anxious to dive right in and start writing code. If you are already a seasoned Python developer feel free to do so! However if you have never seen any Python code, or don’t even know what Python is you may want to take a little time to visit the Python website.

Getting Your Feet Wet

Python is a high level, powerful, and very easy to use programming language. It is a language the preaches readability of code as one of its most important tenets. Sublime Text is written in Python and as a result so are any plugins you wish to write or install. Here are a few resources that are worth going over to begin grasping some of the basics of what you will need to write Sublime Text plugins.

In this section we will dive right into the action. It is worth noting that in this article I will be presenting code compatible with Sublime Text 3. Version 2 will be similar and will have only a few small differences. We are going to take our idea for a command that generates an HTML5 template and bring it to life. We have already determined that we will need to create a WindowCommand type of plugin so the next step is to open up our Sublime Text editor and create a new file by pressing CTRL + N on Windows and Linux, or CMD + N on Mac.

Plugins are stored in a specific location. Go to your menu and select Preferences -> Browse Packages which then takes you to your Sublime Text user directory. In Sublime Text 3 you should see a folder named Packages. Create a new directory in this folder and name it Html5Template. We should also go ahead and save our plugin file even though we haven’t written any code yet. Go ahead and press CTRL + S (CMD + S on Mac), and give your plugin file the name Html5TemplateCommand.py. Please pay special attention to case as this does make a difference to Sublime. When you reference your new plugin in shortcut keys or command configuration files each capital letter signifies a word, and Sublime will assume underscores before each word. So to reference your new command you would use html5_template. More on this later.

Let’s Start With an Import

The first few lines of most any Python script begin with import statements. Import statements are commands that tell the Python interpreter to include functions and methods from other libraries so they can be used by your script. In our case we need to tell the Python interpreter to import Sublime libraries. There are two libraries we will need to import.

import sublime
import sublime_plugin

These two import commands, or statements, tell Python that we want to have access to the sublime and sublime_plugin libraries.

Making Our Command

Now we need to put together the code that will be our new command. In Sublime new commands are Python classes that extend specific Sublime classes. Think of a class as a blueprint to some thing. After you define the blueprint you may create one or more instances of this thing. As an example imagine you have a blueprint for a birdhouse. You only have one blueprint, but using that blueprint allows you to craft multiple birdhouses. Each birdhouse that you build is an instance.

Let’s begin with the shell of what we need. All Sublime plugins must have at least one method named run(). When your plugin runs, or executes, it calls the run() method. Let’s start our new class and method which for now will simply display some text in the Sublime Text console.

class Html5TemplateCommand(sublime_plugin.WindowCommand):
    def run(self):
        print("Starting Html5TemplateCommand")

Save your work. Now let’s create a file that gives Sublime Text a new command to display in the Command Palette that will run our new class. Create another new file, name it Html5TemplateCommands.sublime-commands, and save it in the same directory where the Python script lives. In this file put the following code.

[
    { "caption": "New HTML5 Template", "command": "html5_template" }
]

Save this, then let’s test what we have. Our new command only prints to the console at the moment. To open the console press the CTRL + ~ keys. Now we are going to run our new command. To do this bring up the command palette by pressing CTRL + SHIFT + P and a drop down box will be presented. Start typing the letters new html and the box should start to filter out possible matching commands. You should see your new HTML5 template command! Select it and press Enter. The console should display the words Starting Html5TemplateCommand. Sweet!

Putting Text Into The Buffer

Now we want to make our plugin do something useful. The first thing to do here is tell Sublime we wish to create a new file when our command is run. Inside the run() method, after the print() command let’s insert the following code.

buffer = self.window.new_file()
buffer.run_command("html5_template_text")

The first line of code listed above will create a new file tab, and you now have a reference to it in the variable named buffer. The second line of code is going to run the command html5_template_text against this new tab.

But what is html5_template_text? This is a command that you haven’t written yet! But do not worry, you are about to. Before we do you must know why. You see our plugin need to write text to a “buffer”, or tab. Sublime Text 3 does not let you do this directly, however, and TextCommand plugins are the best way to write to a buffer. So what we are going to do is create another class that will handle the writing to our new tab. That looks like this.

class Html5TemplateTextCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        templateCode = """<!DOCTYPE html5>
<html lang="en">
<head>
    <title>Title</title>

    <meta charset="utf-8" />
    <meta name="author" content="Me" />
</head>

<body>
</body>
</html>"""

        self.view.insert(edit, 0, templateCode)

The first few lines should look familiar. We are making a class, though this time we are basing it off of the TextCommand Sublime class. We also have our required run() method and it takes an additional argument. The argument named edit is a reference to the editable region in our new tab.

The next lines of code simply define a string, or sequence of characters. This string should look familiar as it is an HTML5 template, complete with title and meta tags. The final line calls the method insert() on the view object. Don’t worry too much about that right now. It is sufficient to know that this view object affords us the ability to insert text onto a tab. To do this you must pass it the edit region, a starting location, and the string to insert. For our case we want to insert our HTML5 template string at the beginning of the edit region.

This new code stays in the same file you’ve been working in, Html5TemplateCommand.py. Let’s take a look at the whole listing of code.

import sublime
import sublime_plugin

class Html5TemplateCommand(sublime_plugin.WindowCommand):
    def run(self):
        print("Starting HTML5TemplateCommand")
        buffer = self.window.new_file()
        buffer.run_command("html5_template_text")


class Html5TemplateTextCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        templateCode = """<!DOCTYPE html5>
<html lang="en">
<head>
    <title>Title</title>

    <meta charset="utf-8" />
    <meta name="author" content="Me" />
</head>

<body>
</body>
</html>"""

        self.view.insert(edit, 0, templateCode)

Go ahead and save your work and try running the command again. If all goes well you should have a new tab open with a simple HTML5 template! Feel free to play with the template string and customize it to add your personal flair.

Sharing Is Caring

Sublime plugins are an awesome way to extend and enhance this powerful text editing tool. It is even more special when you choose to share your plugin with the world. In this section we’ll talk briefly about how you can share your work with others so they can benefit from your awesome new work too!

GitHub

The first step in sharing your plugin is putting it somewhere in a version control system. I will not be going over the details of how to use, or even how version control works. Hopefully it will suffice to say that putting your source code into a system that keeps track of changes over time is a worthwhile endeavor.

One of the most popular version control platforms in the world today is GitHub. They offer a solid application for storing and versioning your source code, as well as powerful tools to allow other people to contribute to your plugin.

For a good tutorial on getting started with Git and GitHub, take a look at this post on Readwrite.com.

What Is Package Control?

If you have been using Sublime Text for longer than just a little bit there is a good chance you have heard of, or are even using Wbond’s Package Control plugin. This nifty piece of software makes installing plugins in Sublime super easy.

As a plugin writer you definitely want to make your plugin available for installation via Package Control. The benefits are clear. This tool makes installing your plugin easy for users. It provides the ability to automatically push updates of your plugin to your users without any effort. The choice is quite easy.

How To Submit Your Plugin

Submitting your plugin to Package Control is a pretty straightforward process. The high level steps are as follows.

  1. Fork the Package Control repository in Github
  2. Add your plugin to the list
  3. Submit a pull request

Forking and sending pull requests are well documented processes, and I highly encourage you to research these activities on the Github website.

Adding your plugin to the Package Control repository is pretty easy. After you fork Wbond’s repository you will have your own local version. In your working copy there is a folder named repository. In this folder there are .json files for each letter of the alphabet.

For explanation purposes let’s assume you are submitted your new HTML5 template plugin, and you want to call it HTML5 Template. You would open h.json and find the place to put your new plugin entry. Each file has plugin entries in alphabetical order. Once you’ve located the correct spot you would create an entry that looks like this.

{
    "name": "HTML5 Template",
    "details": "https://github.com/myname/html5template",
    "releases": [
        {
            "sublime_text": "*",
            "details": "https://github.com/myname/html5template/tree/master"
        }
    ]
}

That block on JSON data says three things. The first indicates the proper name of your plugin. In our case that will be HTML5 Template. The second piece of information, details, indicates the URL to find out more about your plugin. The main Github page for your plugin is a great place to point to.

The next key, releases, is an array, or list, of release versions. In this sample there is only one place to find releases, and that is the master version location of the source code. You may also note an asterisk next to the key sublime_text. This tells Package Control that your plugin works in Sublime Text 2 and 3.

For more details on how to contribute to the Package Control repository see the official package submission instructions.

Final Thoughts

Building a Sublime plugin can be a very rewarding exercise. Python is a very powerful language with a low barrier for entry, making plugin building an enjoyable experience. Once you become more comfortable with building plugins I highly recommend putting them on GitHub and contributing to Package Control. The more people who use your plugin the better it will become!

Happy coding!

Adam Presley has been developing software since the age of 12 years old, starting out on the great Commodore 64! Starting his career in C/C++ in the Document Imaging industry, Adam’s first exposure to the world of web development began in ASP Classic.

Over the years he has architected software solutions for various industries as a software engineer and architect, including medical, real estate, eCommerce, and non-profit. Adam crafts applications in ColdFusion, PHP, C#, Groovy, Python, and more.

Adam has also written a few Sublime plugins, including View In Browser and Debug Killer.

He blogs at www.adampresley.com and tweets as @adampresley.

P.S. To learn more about using Sublime–and building your own plugins–join the Sublime Text Tips newsletter. You’ll get new tips in your inbox each week, plus a FREE 12-page guide to help you master some of Sublime’s little-known editing features.

How to execute a command every time Sublime launches

By josh / February 20, 2014

Maybe you like to work with Sublime in full screen or distraction free mode, and the first thing you do when you open it is switch to your preferred display style.

Maybe you share your settings between several computers and wish that Sublime was smart enough to change a few settings depending on your operating system.

Or maybe you just want a freakin’ panel to stay open.

That’s the one that got me recently. I was writing and testing plugin code for my upcoming book, [Writing Sublime Plugins][1].

When you’re writing a Sublime plugin in Sublime, restarting the editor frequently is the name of the game.

For the most part, it’s painless, since Sublime remembers your open tabs. But I also needed the Sublime console open so I could see errors, and there’s no way to keep that panel visible across restarts. I was wearing out the Ctrl+` combo on my keyboard. It got old.

I finally decided that I could probably fix this plugin-writing annoyance with a plugin (how meta), and it turned out to be even simpler than I’d guessed.

Better yet, you can use this same approach to run just about any arbitrary command when Sublime launches.

Let’s see how it works.

To get started, open a new tab in Sublime, then enter the following code:

import sublime, sublime_plugin

def plugin_loaded():
    window = sublime.active_window()
    window.run_command("show_panel", {"panel": "console", "toggle": True})

In case you don’t recognize it, this is Python, which is the language Sublime uses for plugins. I’d never used Python before I started working on my own plugins, but it turns out to be an easy language to read and write. If you have some basic programming knowledge and understand a language like JavaScript, Ruby or PHP, you’ll pick up Python easily. (It’s one of my favorite languages to work in now.)

In the code above, we’re defining a plugin_loaded method. When Sublime loads our file, it will see this method and automatically execute any code it contains.

In plugin_loaded we’re getting a reference to the current Sublime window and using its run_command method to execute the show_panel command. This command is what displays panels like the find and replace panels. In this case, we’re letting Sublime know that we want the console panel.

Note: This plugin only works in Sublime Text 3. The plugin_loaded API method didn’t exist in Sublime Text 2.

That’s all there is to it. Now we just need to install it …

To install the plugin, first launch the command palette and run Preferences : Browse Packages. This opens your file browser to the Packages directory. Create a new folder in this directory folder called PinConsole.

Now switch back to Sublime and click File | Save to open the file save dialog. Browse to the Packages/PinConsole folder you just created, then save the plugin file as pin_console.py.

As soon as you save the file, Sublime will load the plugin and call plugin_loaded. The console should pop up immediately, and it’ll open every time you launch Sublime until you delete the plugin. (To make this plugin more sophisticated, we could create a settings file that allows the user to toggle the plugin off and on as desired.)

The plugin_loaded hook is extremely useful–the possibilities are endless. You could use it to automatically update your git repository. Or if you use Dropbox to sync settings between computers, you might use it to set a different font size on your Windows desktop (with it’s giant 4K monitor) than you use on your MacBook Air.

Here’s another example that sets a different font depending on whether the machine is running OS X or Windows:

import sublime, sublime_plugin

def plugin_loaded():

    s = sublime.load_settings("Preferences.sublime-settings")

    if sublime.platform() == "osx":
        s.set("font_face", 'Courier')
    else:
        s.set("font_face", 'Consolas')

    sublime.save_settings("Preferences.sublime-settings")

This is just a small example of what you can do with a basic knowledge of Sublime’s plugin system and APIs. Understanding these principles unlocks a whole universe of power and flexibility.

Want to see how you can take charge of Sublime by writing your own plugins? Join the Sublime Text Tips newsletter for more info:

http://sublimetexttips.com/newsletter

Show your current file in the Sublime Text side bar

By josh / February 1, 2014

You settle into your chair with your morning coffee and take a look at your next task.

Ah, good. Just a quick bug fix to the user account management page. You expertly fire the shortcut for Sublime’s Go to Anything command and type users.php

Wait, why are there two copies? I thought we deleted the old one months ago…

You guess and pick the first match. Wrong one, natch. Best to delete it now before it causes any more confusion …

You start poking around in the side bar, looking for the offending file. But this project is huge–dozens of folders, and folders within folders …

Where the heck is it?

Sublime’s support for keyboard navigation is a huge time saver, but sometimes it helps to be able to be able to browse to a file quickly.

Here a couple of tools to help you track down the current file in the side bar so you can delete or rename it.

SyncedSideBar

The SyncedSideBar plugin links the side bar to the editing window so that the current file is always visible and highlighted in the side bar.

You can install SyncedSideBar via Package Control, and it’s compatible with both Sublime Text 2 and Sublime Text 3.

Reveal in Side Bar

If you’ve already made the leap to Sublime Text 3, you can take advantage of the new Reveal in Side Bar command. Just right-click the open file and select Reveal in Side Bar.

There’s no keyboard shortcut for Reveal in Sidebar, but you can easily create one. Just run the Preferences: Key Bindings – User command in the command palette.

Then, if you’re using Windows or Linux, add the following to your user keyboard shortcuts file to bind Reveal in Side Bar to Ctrl+Shift+R:

[
    { "keys": ["ctrl+shift+r"], "command": "reveal_in_side_bar"}
]

If you’re on OS X, you might prefer a variation that uses the Command key:

[
    { "keys": ["super+shift+r"], "command": "reveal_in_side_bar"}
]

P.S. Get more tips every week! Sign up for my free Sublime Text Tips newsletter, and as a bonus, I’ll send you a FREE 12-page guide to Sublime’s advanced editing features so you can start using Sublime more effectively–today.

How to show whitespace in Sublime Text

By josh / January 25, 2014

There’s one every team: That one guy who’s taken the wrong side in the eternal Tabs vs. Space Debate.

Perhaps he doesn’t know any better. It’s possible he just hasn’t bothered to set up his text editor.

Or maybe, you suspect darkly, he knows and does it on purpose…

Whatever the reason, his commits are a pain to review. And editing files he’s touched makes you grind your teeth. Especially when the inconsistencies are on the same line. Like, four spaces, tab, four spaces. Nerdrage!!!

While Sublime can’t dish out the attitude adjustment this guy so justly deserves, it can make it easy to spot (and fix) inconsistent use of whitespace in files.

By default, Sublime shows whitespace on selected text:

whitespace-shown-on-selection

Tabs show up as dashes, while spaces are dots.

You can control when Sublime shows white space with the draw_white_space setting. The default value is selection, but you can override that with all to always show whitespace or none to never show it.

To change your whitespace preferences, run Preferences: Settings – User in the command palette, then add the draw_white_space setting:

{
    "draw_white_space": "all"
}

If you also want Sublime to automatically replace tab characters with spaces when you open a file, override the translate_tabs_to_spaces setting:

{
    "draw_white_space": "all",
    "translate_tabs_to_spaces": true
}

P.S. Don’t miss your chance to get more done with Sublime! Sign up for my free Sublime Text Tips newsletter to get more tips every week. As a bonus, I’ll send you a FREE 12-page guide to Sublime’s advanced editing features so you can start using Sublime more effectively–today.

Formatting HTML with Sublime Text

By josh / January 18, 2014

It’s almost quitting time, and the only thing standing between you and a relaxing evening is the one task you’ve been avoiding all day: Posting photos from the employee recognition dinner on the company intranet site.

A simple enough task, it would seem. But “intranet” is such a lofty term to apply to that rats nest of static HTML pages. It was originally assembled (you won’t deign to use the word “coded”) in Dreamweaver by a long-forgotten secretary when you were still in middleschool and IE3 was the hot new browser.

HTML5? CSS layouts? Semantic markup? Ha! This intranet never met a table it couldn’t nest.

And the formatting … As if tables within tables within tables weren’t hard enough to work with, the HTML looks like it was indented by a macaque after a couple of stiff shots of Jim Beam.

But the updates are due today, and there’s no getting around it.

You fire up Sublime Text, and wonder …

What’s the best way to untangle this gnarled mess?

To find out, I put several of the most popular HTML formatting Sublime Text plugins through their paces and compared the results.

For the tests, I used a nasty HTML test file courtesy of the creator of the HTML Beautify plugin (thanks, Ross!). This file includes just about every formatting misdeed ever conceived by the human mind, including misaligned code blocks, copious amounts of extra white space, pre formatted text and inline comments.

I ran two tests on each plugin–one with the test file as is, and a second one with a minified version of the file.

Which plugin came out on top? Let’s see how they stacked up.

Sublime’s build-in Reindent command

The Reindent command is handy for quickly formatting a messy block of HTML. No need to install anything here, just select the HTML you want to format and click Edit | Line | Reindent. You can also run the Indentation: Reindent Lines command from the command palette.

Reindent did a passable job on the test file. It didn’t delete any of the extraneous blank lines, but most of the HTML was properly indented.

One common complaint with this built-in formatting is the way it handles–or rather, doesn’t handle–multiple opening tags on one line. Due to this limitation, it utterly failed on the minified HTML file. There was literally no difference after running the command.

Reindent’s main virtue is convenience. It’ll get the job done in simple scenarios, but if you have more complex needs, you’ll want a plugin.

Tag

The Tag plugin, available for Sublime Text 3, is far and away the most popular plugin that offers HTML formatting. It also offers a handful of additional features that are useful when working with HTML and XML files, including niceties like strip attributes, autoclose on slash, close tags, and a new tag linting feature.

Unlike many of the other options, Tag doesn’t depend on any external binaries like Node.js or PHP.

To use Tag to format an HTML file, install the plugin, then run click Edit | Tag | Auto-Format Tags on Document, or run Tag: Auto-Format Tags on Document in the command palette.

Tag handled both tests fairly well. It was able to expand the minified file properly, and the formatting was reasonable on both files. Extra blank lines were removed properly. It didn’t align the tags in an embedded <script> block early in the file.

But Tag choked hard when it hit a PHP tag midway through the document. From that point forward, the indentation was hosed.

HTMLTidy

HTMLTidy is the second most popular option behind Tag. This plugin relies on the libtidy utility, which comes with PHP 5. To use it, you’ll need to have PHP installed and available in your system path. If PHP isn’t installed, the plugin falls back to a web service. HTMLTidy is ST2 only at this time.

It offers some settings that allow you to tweak the formatting–you can specify how to handle <br>, for example, and how many spaces to use for indentation.

To use the plugin, just run Tidy HTML in the command palette.

My test machine didn’t have PHP installed, so I used the web service fallback for my trials. Calling the web service caused a noticable delay, but it wasn’t bad, maybe a second or two. A slow network connection or larger file size would likely make this option less viable.

The plugin did a good job formatting both versions of the test file. It handled the embedded PHP scripting with no issues, and correctly removed the extra white space.

My main hesitation with this plugin is its seeming lack of support. It’s only available for Sublime Text 2, and as of this writing the plugin’s GitHub repository seemed dormant. Is this project dead?

HTML-CSS-JS Prettify

The HTML-CSS-JS Prettify plugin is the most flexible and feature-rich of the plugins I evaluated. Available for Sublime Text 2 and Sublime Text 3, this plugin handles HTML, CSS, JavaScript and JSON files. It integrates well with the Sublime user interface–you can run it from the command palette, keyboard shortcuts or the right-click context menu, and there’s an option to run a format every time you save a file.

By creating a .jsbeautifyrc file in your project, you can customize how you want your files formatted, including blank lines, tags to leave inline (like <a> tags) and indent size.

On the downside, HTML-CSS-JS Prettify requires Node.js to run. I always hate having to install external tools just to get a plugin working, but Node.js is pretty ubiqutious these days. I was testing on a Windows system, so I downloaded the portable version of Node and put it in Dropbox so it would sync between machines. The plugin allows you to specify the path to the Node.js executable, and after a little fiddling I got it working.

HTML-CSS-JS Prettify performed well on both the minified and unminified versions of the test files, indenting all of the HTML tags to my satisfaction. It didn’t remove the extra blank lines in the file or indent the JavaScript inside of a <script> block, but these are both settings that can be overriden in a .jsbeautifyrc file.

The one drawback I could see was the plugin’s handling of PHP code. It formatted a multi-line PHP script into a single line.

Other options

In addition to the main contenders above, there are currently three other HTML formatting plugins worth mentioning.

HTMLBeautify

The HTMLBeautify plugin is a basic script that assumes your HTML is already partially formatted with tags on separate lines. It doesn’t work well with inline comments. HTMLBeautify is ST2 only.

TidyHTML5

If you’re only interested in formatting HTML5, the TidyHTML5 plugin might be an option. While it uses an external utility to perform formatting, it comes bundled for Windows users. TidyHTML5 is ST2 only.

SublimeLinter-html-tidy

One of the newest options is SublimeLinter-html-tidy, which is a plugin for the fast-growing SublimeLinter 3 plugin. (Yep, it’s a plugin within a plugin.)

This plugin requires the tidy executable, which is preinstalled on OS X and is also available for Windows and Linux.

And the winner is …

From my review, HTML-CSS-JS Prettify seems like the best option due to its customizability, ongoing support and superior integration with Sublime.

I definitely plan to keep my eye on SublimeLinter-html-tidy as well, though. There’s an entire ecosystem of plugins developing around SublimeLinter project, and I wouldn’t be surprised to see this one gain popularity.

What do you think? Did I miss your favorite option? Let me know in the comments.

P.S. Don’t miss your chance to get more done with Sublime! Sign up for my free Sublime Text Tips newsletter to get more tips every week. As a bonus, I’ll send you a FREE 12-page guide to Sublime’s advanced editing features so you can start using Sublime more effectively–today.

Switch projects without browsing in Sublime Text

By josh / January 12, 2014

Sublime’s project files are a lifesaver. Just by adding a folder to your project you can instantly open anything in the folder with the magic of Goto Anything.

But that convenience is enough to make you resent having to dig around in your file manager every time you need to switch gears and work on another project.

Wouldn’t it be great if you could switch projects just as easily as you switch files within a project?

That’s what the Quick Switch Project feature is for. (Quick Switch Project was cryptically named Switch Project in Window in Sublime Text 2.)

When you run Quick Switch Project, Sublime opens a popup with a list of recent projects:

quick-switch-project

To use Quick Switch Project, click Project | Quick Switch Project or hit Ctrl+Alt+P on Windows and Linux or Ctrl+Cmd+P on OS X. Use the arrow keys to highlight a project, or start typing to filter the list. Press Enter to open the project you’d like to switch to.

Projects only appear in this list once you’ve opened them, so if you check out some fresh code, you’ll still have to open it from the file manager the first time around.

Once a project appears in this list, there isn’t an easy way to remove it. One option is resetting the list of recent projects. To reset the recent projects list, click Projects | Recent Projects | Clear items. If you nuke your recent projects list, you’re back to square one and will need to reopen projects by hand before you can use Quick Switch Project again.

A more surgical option is editing the list by hand. The recent projects list is stored in a file named Session.sublime_session. The easiest way to find this file is to use the command palette to run Preferences : Browse Packages command to open the Packages folder. Browse up a level, and look for a folder named Local (in Sublime Text 3) or Settings in Sublime Text 2. Open the session file and search for the name of the project you’d like to remove.

P.S. Do you love using Sublime to get more done? Sign up for the free Sublime Text Tips newsletter to get more tips every week. As a bonus, I’ll send you a FREE 12-page guide to Sublime’s advanced editing features so you can start using Sublime more effectively–today.

Easily view files modified since your last commit (without leaving Sublime)

By josh / January 11, 2014

After your editor, your version control tool is probably the second most important tool you use in your day to day work. Anything that helps these two tools work seamlessly together can improve your productivity–and make writing code more fun.

One of the sweetest version control plugins for Sublime that I’ve seen in a while is Modific.

Modific isn’t a full version control client–it’s best used as a companion to something like the Git plugin.

But what it does, it does well. As you make changes, Modific highlights modified and deleted lines with icons in the gutter, updating every time you save the file.

You can also see a list of modified files and generate diffs for convenient review.

Modific works with Git, Mercurial, SVN and Bazaar. It’s available for both Sublime Text 2 and Sublime Text 3 and for Windows, Linux and OS X. You can install it via Package Control.

For more ways to streamline your Sublime Text workflow, check out:

http://sublimetexttips.com/newsletter

How to apply custom settings to Ruby files (or any language) in Sublime Text

By josh / January 9, 2014

Like any good coder, you’re particular about your code formatting—and that includes white space. You have one preferred indentation style for Ruby and CoffeeScript (two spaces, please) but would rather use four spaces to indent CSS and plain JavaScript.

Sublime’s syntax-specific settings make it easy to override your default preferences for any file type.

To customize the tab size for Ruby files, first open a .rb file. Then click Preferences | Settings – More | Syntax-Specific on Windows and Linux or Sublime Text | Preferences | Settings – More | Syntax-Specific on OS X. Sublime opens a new tab named Ruby.sublime-settings.

Enter the following to change the tab width:

{
  "tab_size": 2
}

Now just save the file, and you’re ready to go.

If you’re curious, Sublime saves the file in your Packages/User directory. On my Windows 8 ThinkPad, the path is:

    C:\Users\Josh\AppData\Roaming\Sublime Text 3\Packages\User

You can use syntax-specific settings to override other preferences as well. For example, if you like line-width guides in code but don’t want to see them in Markdown files, you can create a Markdown.sublime-settings file that removes the guides.

For more ways to make Sublime Text “yours,” go here:

http://sublimetexttips.com/newsletter

Three hidden copy-and-paste gems in Sublime Text

By josh / November 16, 2013

Copy. Paste. Those shortcuts are so hardwired into your muscle memory that you probably never think about them.

But Sublime Text adds a few nuances to these familiar commands that are worth learning.

Cutting and copying entire lines. If you want to cut or copy a single line of text, you don’t need to select it first. Just position the cursor on the desired line and perform your copy or cut. Sublime automatically grabs the entire line.

Clipboard history. Isn’t it a pain when you carefully copy a block of code, then accidentally hit the shortcut for Copy when you meant to Paste? Sublime’s Paste from History command has you covered. To access the code you copied over, just click Edit | Paste from History. This command is also useful equally if you’re starting a new code file. Instead of bouncing back and forth between multiple files to get the boilerplate code you need, just find the code you want in each file and copy it, then execute Paste from History multiple times to dump the snippets into your new file.

Paste and Indent. Pasting code from another file or from a sample you find on the Internet is annoying, because you have to spend the next 30 seconds fixing the indentation levels. And even if the indentation levels happen to match, chances are you didn’t select the leading whitespace, so you still have a formatting hassle on your hands. The Paste and Indent command automatically adjusts the indentation of the code on your clipboard to match the surrounding code. This command is bound to Ctrl+Shift+V on Windows and Linux or Shift+Cmd+V on Mac, but it really ought to be the default behavior. If you agree, you can swap the bindings for the Paste command with Paste and Indent.

If you’re on a Mac, add the following to your Default (OSX).sublime-keymap file:

{ "keys": ["super+v"], "command": "paste_and_indent" },
{ "keys": ["super+shift+v"], "command": "paste" }

And if you’re a Windows user, you’ll want to edit your Default (Windows).sublime-keymap file and add:

{ "keys": ["ctrl+v"], "command": "paste_and_indent" },
{ "keys": ["ctrl+shift+v"], "command": "paste" }

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

http://sublimetexttips.com/newsletter

Win a free Sublime Text 3 license

By josh / November 5, 2013

Note: This contest is over, but I offer it periodically to subscribers on my email list. Jump onboard here:

http://sublimetexttips.com/newsletter

Sublime Text is a key part of your daily workflow. You couldn’t live without it and the dozens of plugins that let you tweak and customize to your heart’s content.

But there’s that “trial mode” message again, prompting a little stab of guilt.

I should pay for a license.

You’re not a freeloader—you like to support programmers who make the tools you love.

But $70 is a lot to shell out …

I’m giving away a full Sublime Text license this month.

This contest is only for subscribers to my Sublime Text newsletter.

Are you going to spam me?

No, I promise not to spam you, and I won’t share your email address with anyone.

You’ll get the free Sublime Text newsletter, which includes my hand-picked selection of Sublime-related tips and tricks, like this one detailing how to change Sublime’s default syntax highlighting for a file type, or this handy navigation shortcut.

I’ll also occasionally send updates or announcements about other Sublime Text-related projects I’m working on, like my Sublime Productivity ebook.

But I already get the newletter!

Great, then you’re eligible. No additional steps required!

Will this license cover the Sublime Text 3 upgrade?

Yes, it’ll be good for Sublime Text 3.

I’ve already paid for a Sublime license!

No problem—I’ll pay for your existing license you if you win.

When will you announce the winner?

I’ll announce the winner on November 21, 2013 edition of the newsletter.

What is the deadline for entering?

The cutoff is midnight Eastern Time (US & Canada) on November 19, 2013.

Don’t miss out—drop your email address in the form below to enter.

Improve your git workflow with this new Sublime Text 3 feature

By josh / October 26, 2013

You’re scowling at your screen, puzzling through a knotty optimized algorithm, when the QA lead abruptly interrupts.

“We just filed a bug against that feature you added last week. Can you take a look now so we can greenlight tomorrow’s release?”

So much for that productive afternoon you were hoping for.

With a sigh, you switch to the release branch to see what’s what.

But while you understand the magic of time travel via source control, Sublime doesn’t.

Unfortunately, some of the files you are editing today didn’t exist last week. Now Sublime is confused and showing “dirty” tabs all over the place, and you’re struggling to remember what you modified, and when …

If you’ve upgraded to Sublime Text 3, you can easily prevent this scenario with the New Workspace for Project feature.

ST3 allows you to create multiple workspaces for a single project, each with its own independent set of tabs and panels. This allows you to switch contexts easily without disturbing your current environment.

Before you switch branches to tackle that bug, create a second workspace for your current project by clicking Project | New Workspace for Project. A new Sublime window opens with a partial copy of your existing workspace. Preferences like Side Bar visibility and open folders are carried across, but open tabs are not.

When you’re done with your bug fix, simply close the temporary workspace and pick up where you left off.

For more ways to streamline your Sublime Text workflow, check out:

http://sublimetexttips.com/newsletter

Page 3 of 6