Sublime Text: One Editor to Rule Them All?

Ken Kinder

Issue #232, August 2013

Get started editing code like a pro, with Sublime Text, a programmer's editor.

Sublime Text is a proprietary, cross-platform text editor designed for people who spend huge amounts of time shuffling code around. A programmer's editor, Sublime Text is a third option to the long-standing “Vi or Emacs” conundrum. Going beyond the basics of syntax highlighting and code folding, Sublime offers a litany of innovative and unique features. With version 3.0 just around the corner, I'm taking you on a tour of Sublime's most compelling features and add-on packages.

At the time of this writing, Sublime Text version 2 is $70 US, and the upgrade to version 3 (which is currently in beta) will be paid. Version 2 is downloadable as a trial, allowing you to get a feel for the editor for as long as you need before committing to buy. Because the application is available for Linux, Windows and Mac OS X, you do not need to buy a separate license for each platform. $70 US may seem like a lot for a text editor, but if you spend hundreds of hours a month in front of your editor, it's a worthy investment.

Most of the content in this article should apply to either Sublime Text 2 or 3. Sublime Text 3 is not available for pre-purchase evaluation, so if you're new to Sublime Text, you'll be stuck with version 2 for now. You can download Sublime Text from www.sublimetext.com.

Getting Around in Sublime Text

Start Sublime Text, and the first thing you're greeted with is a charcoal editor window. A traditional project sidebar is on the left, and on the right, is what Sublime calls the Minimap. The Minimap is a zoomed-out view of the currently open file, which works a bit like a WYSIWYG scroll bar. Open some source code, and the Minimap provides a useful way of navigating large files visually.

Figure 1. Sublime Text Editor Window

If you have a directory holding a project to work on, choose File→Open Folder to select the project folder, then save the project by using Project→Save Project As. Consistent with the spirit of Sublime Text, you can tweak the properties of the project simply by opening the .sublime-project file directly and editing its contents.

Open files in Sublime Text are shown in tabs reminiscent of Chrome. You can reorder and drag them between open Sublime Text windows, again like in Chrome or Firefox. This feature is particularly nice if you have multiple monitors, as it lets you quickly organize a vast workspace. If you want to focus (on writing a Linux Journal article, perhaps), use View→Enter Distraction Free Mode (Shift-F11) to view your file in full screen with all navigation widgets hidden.

Part of Sublime Text's appeal is speed, both in terms of application performance and UI design. A wide array of highly customizable keyboard shortcuts make using the mouse optional. My most frequently used hotkey is called Goto Anything and is available from the Goto→Goto Anything menu item (Ctrl-p). Provided you have the relevant language support installed (more on that later), Goto Anything lets you quickly access files, classes, functions and even regular old variables as you type. For example, I'll open up my project's icongrabber.py file by pressing Ctrl-p, and as I type my desired filename, Sublime Text narrows down possible completions. When using Goto Anything, you can prefix your query with @ to find a symbol, # to search within a file or : to jump to a line number. Unfortunately, Sublime Text does not search symbols in unopened files.

Figure 2. As you type the name of your file, Sublime Text narrows down possible completions.

A close second in useful keyboard shortcuts is the Command Palette. Similar to the Escape/Command prompt in Emacs, Sublime's Command Palette lets you quickly execute commands internal to Sublime Text or provided by an add-on package you've installed. For example, to toggle word wrap, use Tools→Command Palette (Shift-Ctrl-p) and type “wrap”. Sublime is smart enough to suggest “Toggle Word Wrap” as a completion. Notice that Sublime Text also shows keyboard shortcuts for commands that have them.

To view a full list of default key bindings, click on the Preferences Menu and choose “Key Bindings - Default”. This will open up the system-wide key-binding file. To create your own key-binding preferences, choose “Key Binding - User”, and use the same syntax as the default file.

Editing Kung Fu

Now to the heart of what makes Sublime Text such a powerful editor: its unique alchemy of text editing features. Sublime Text's most praised editing feature is multi-selection, which is a little tricky to wrap your head around at first. Most editors let you select only one contiguous span of text; some let you select text as a block. Sublime Text lets you select multiple noncontiguous spans of text and act on them collectively. After you've begun using this feature, its power will become apparent to you, especially in editing code or any file with a formal syntax.

Say, for example, that I'm converting the following source code from Python 2 to 3. The first thing I want to do is rename “raw_input” to just “input”:

your_name = raw_input('Enter your name: ')
print 'Hello,', your_name

printer_model = raw_input("What kind of printer do you have?: ")
print your_name, 'has a', printer_model

Using Sublime Text, such a task is easy. I'll select the first occurrence of “raw_input” and press Ctrl-d. Pay close attention, and you'll notice that both occurrences of raw_input are now selected, each with its own blinking cursor. As I begin to type the word “input”, both occurrences are replaced. It is true that such a change could have been accomplished easily with search and replace, but I've only scratched the surface with multiple selection.

Next, I'll want to replace the two “print” statements with Python 3's “print” function, which means making the commands look like print(...). Because the text “print” occurs four times in this document, the last technique won't work, so I'll show you another way to make multiple selections. I'll begin by positioning my cursor on the first print statement. Then, I'll hold Ctrl while clicking on the other print statement.

Figure 3. The editor cursor is blue, and the mouse pointer is red. By holding down Ctrl and clicking, you can create multiple editor cursors.

Although I haven't selected any text, I have two blinking cursors. Whatever I type will effect both lines. I'll type (, press end, and type ). Both lines received those keys, and now my file is Python 3-compliant.

There are several other ways of selecting multiple spans of text in Sublime Text, and as you experiment with them, you'll get a feel for how to use them. Ultimately, when used productively, Sublime's multiple selection feature replaces most editor macro, find/replace operations and refactoring operations all at once. Imagine, for example, how you could transform a plain-text list into an HTML <ul> list using multiple selection. If you can picture how this is done, you're starting to grok multiple selection. If not, don't fret: this is a new editor feature. A few trips to YouTube and some video demos will help you get the idea.

Search and Replace

Forget grepping through your codebase when the time comes for aggressive refactoring. Sublime Text offers a powerful recursive search and replace feature. Recursive search and replace eliminates the need for the GNU grep and find commands for many users. Many editors provide recursive search and replace, although I find Sublime Text really gets it right in a way that few other projects do.

Click on Find→Find in Files, and a large search bar will appear at the bottom of your editor. Using the toggle buttons on the left, you can toggle regular expression matching, case sensitivity and whole words. Hover over individual icons to see what they do. You also can select a directory to search and optionally specify replacement text.

If you expect many results or plan to refer to your search results over time, toggle the “Use Buffer” icon in the search area. When enabled, Sublime Text will open a summary of search results in its own editor buffer. When using a multihead workstation, I find it useful to put search results in one monitor and code in another. Toggling “Show Context” will include a few lines before and after each hit in the results.

Figure 4. Sublime Text can open up your search results in its own buffer. Click on any result to jump to its source.

Sublime Text uses Perl-style regular expressions implemented using the Boost C++ library. Sublime Text also supports regular expression replacements.

Snippets

Despite their best efforts to not repeat themselves, programmers often find themselves typing common blocks of text throughout their projects. Examples include standard class file layouts, unit tests and license warnings programmers put at the top of each file.

To support this work flow, Sublime Text features “snippets”. Suppose I have a standard unit test layout for my Python projects:


"""
Unit tests for <MODULE> in <PROJECT>.
"""
import unittest

class UnitTest(unittest.TestCase):
    def setUp(self):
        """
        Called before each test to set up the environment.
        """
        pass

    def tearDown(self):
        """
        Called after each test to clean up.
        """
        pass

    def test<METHOD>(self):
        pass

    if __name__ == '__main__':
        unittest.main()

I can use Tools→New Snippet. Sublime Text will give me an example snippet file. I'll modify it to read like this:

<snippet>
    <content><![CDATA[
"""
Unit tests for ${1:module} in ${1:project}.
"""
import unittest

class UnitTest(unittest.TestCase):
    def setUp(self):
        """
        Called before each test to set up the environment.
        """
        pass

    def tearDown(self):
        """
        Called after each test to clean up.
        """
        pass

    def test${1:method}(self):
        pass

if __name__ == '__main__':
    unittest.main()


]]></content>
    <tabTrigger>unittest</tabTrigger>
    <scope>source.python</scope>
</snippet>

Notice that I've made a “tabTrigger” tag and a “scope” tag in my snippet file. Using the settings I've given, any time I'm in a Python file and type the word “unittest”, I can press Tab, and the snippet will be inserted where the cursor is. To try it out, I'll save the snippet as “unittest.sublime-snippet” in the default directory. Now I can use the snippet to create unit tests quickly.

Packages Galore

Sublime Text can be scripted using plugins written in Python. These plugins are stored in packages that can be installed locally using a file manager or your favorite shell. Should you feel the urge to scratch an itch no one else has found, you can write packages in Python (more on that later).

I like to think that Sublime walks the fine line between an IDE and a text editor. Its speed and initial simplicity make it suitable for editing /etc files as easily as source code. Sublime's true power, however, is found in add-on packages users can write and install to do everything from synchronizing files over SSH to refactoring code. Basic syntax highlighting is included for major languages, but to make use of Python as a programming tool, I find it's best to install some handy packages.

Before anything else, you'll most likely want to install something called Package Control, which is a little bit like apt-get for Sublime Text. Package Control is itself a package that manages downloading, installing, updating and removing other packages. Download Package Control from wbond.net/sublime_packages/package_control. To install a package, just use the Tools→Command Palette (Shift-Ctrl-P), and type “Package Control”. Along with other actions, “Install Package” will be available as a completion.

Finding Coding Errors

One of the most compelling features an IDE offers over a text editor is real-time error detection. For example, if you type a Java syntax error into Eclipse, the editor realizes your mistake and warns you about it in real time.

SublimeLinter provides similar functionality for a variety of languages inside Sublime Text. Install SublimeLinter using the Package Control “Install Package” command described above or by downloading it from https://github.com/SublimeLinter/SublimeLinter.

SublimeLinter wraps native language tools, such as cppcheck for C and xmllint for XML, so you'll need the relevant tool installed for your language. Let's try an XML error.

Figure 5. Notice that Sublime Text highlights lines with errors, and in the status bar, it describes the error itself.

Can you spot the error in Figure 5? Notice in the gutter of the editor, there's a warning icon. You'll see in the status bar, SublimeLint is explaining the problem: I forgot to close the <head> tag. After fixing the problem, pressing Ctrl-Shift-L will force SublimeLint immediately to rescan the file, and the error will go away.

For Python Programmers

If you're a Python programmer, your first download for Python Develop undoubtedly will be SublimeRope. SublimeRope combines Python's Rope source code analysis and refactoring library with Sublime Text, offering context-specific completion, refactoring, jumping to symbols using Sublime Text's “Goto Anything” feature and more.

Install SublimeRope by using the Package Control “Install Package” command. To test out just one of Sublime Rope's features, try this code:

#!/usr/bin/env python2.7


def hello(name):
    print 'Hello, %s' % name

hello(raw_input('Enter your name: '))

Move the cursor over the definition of the hello function. To use a SublimeRope command to rename “hello” to “greet”, use the Command Palette (Shift-Ctrl-P) and type “rename”. You should notice a “Rope Refactoring: Rename” command. After choosing the Rename command, enter “greeting” as the new name of your function, and notice that the name has been replaced in both places.

To explore other features of SublimeRope, including organizing imports and showing documentation of Python methods, just use the Command Palette and type “rope” to see the handful of commands SublimeRope provides. In general, this is a quick way to explore commands provided by packages you add to Sublime Text.

Synchronizing Code to a Server

As a Web developer, I find myself testing and developing code on servers. Although one way to do this would be to make changes locally and rsync them up to the server after each edit, with a large codebase, this is a painfully slow solution. Another option is to use sshfs to mount a remote filesystem locally, but this too has its problems, especially in terms of latency over a typical broadband connection.

Enter Sublime SFTP. Although Sublime SFTP is a $16 “shareware” package, like Sublime Text itself, SFTP support is a justified expense for anyone who uses Sublime Text for a living. At the time of this writing, Sublime SFTP is available only for Sublime Text 2. Install Sublime FTP using the same method as other packages. Use Package Control's “Install Package” command and find the package called just “SFTP” in the list.

Figure 6. Sublime SFTP uses your ~/.ssh configuration for authentication.

To get started, choose File→SFTP/FTP→Setup Server. Sublime Text will open up a file letting you specify a hostname, user name and so on. Sublime SFTP will use your default SSH keys, so if you've already configured logging in to your remote host, this will be easy. Settings for remote servers are stored as files in ~/.config/sublime-text-2/Packages/User/sftp_servers. Each file in this directory represents a remote server, and files can be directly manipulated to update settings.

After configuring a server, you can open files remotely by going to File→SFTP/FTP→Browse Server or mapping a local directory to be synchronized remotely by right-clicking on a directory in your project and choosing SFTP/FTP→Map to Remote.

In my experience as a developer, Sublime SFTP is a surprisingly reliable and well-made package, well worth its unusually high price.

Where to Go from Here

Of course, I've just scratched the surface of Sublime Text's capabilities in this article. I've glossed over or left out many great features, and as you use Sublime Text, you'll find a great deal more. If I've whet your appetite to learn more, try reading the Sublime Text Unofficial Documentation at docs.sublimetext.info/en/latest. Forums also are active on www.sublimetext.com, and many programmers—especially in the Python community—use the editor actively, making its community robust. Enjoy and happy coding.

Ken Kinder is a Software Engineer at Juju.com, and he lives in Denver, Colorado. When not hacking Python or a Raspberry Pi, he enjoys hiking in the Rocky Mountains.