Sublime Text: One Editor to Rule Them All?

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 http://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 http://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 http://docs.sublimetext.info/en/latest. Forums also are active on http://www.sublimetext.com, and many programmers—especially in the Python community—use the editor actively, making its community robust. Enjoy and happy coding.

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Sublime Is Brilliant!

Assaf Koss's picture

I loved Bluefish's environment and style, but it just crashed on me, repeatedly. That became tiresome. This is Windows, of course.

Sublime works so well! Just smooth and good with plenty of useful packages. The transition from 2 to 3 may be a bit awkward with package support and what not, but still this is the best Text and Code editor I have ever laid my hands on.

I'm working on a NodeJS project now with Sublime, and the ride is smooth and pleasant. :-)

www.AssafKoss.com

++++

cnbestmall's picture

++++ http://www.cnbestmall.com ++++

Accept Paypal and Credit Card, FREE SHIPPING

Nike AIr max, Shox, Rift, dunk, blazer, air force 1 shoes: 48 USD

Nike free running shoes: 42 USD

D&G, LV, Gucci, parda DC, polo, puma, supra shoes: 42 USD.

Timberland boot: 50 USD

T-shirts (polo, ed hardy, lacoste,gucci, lv, etc) $28

Jeans (AF, armani, bape, BBC, CA, coogi, D&G, Diesel, Evisu, Levis, gucci, true religion, versace) 45 USD

Down Coat jacket parka vests (moncler, canada goose, barbour, parajumpers, woolrich) 168 USD-268 USD

++++ http://www.cnbestmall.com ++++

You might have mentioned that

Anonymous's picture

You might have mentioned that this software is commercial and only free for evaluation.

Once skeptical

Anonymous's picture

As a long time vim user I was skeptical of ST but once you pull the hood off its amazingly powerful. Notepad++ and Geany are quality products as well but ST is just on a different level. That said there is a rather steep learning curve but thats to be expected, check youtube.

Not the best choise

Anonymous's picture

On Windows I use Notepad++ (freeware):
http://notepad-plus-plus.org/

On Linux I use Geany (freeware):
http://www.geany.org/

Reply to comment | Linux Journal

Rex's picture

You actually make it seem so easy with your presentation but I
find this topic to be actually something which I think I would never understand.
It seems too complex and extremely broad for me. I'm looking forward for
your next post, I will try to get the hang of it!

Upvote :)

Anonymous's picture

Upvote :)

Not the best choise

Anonymous's picture

On Windows I use Notepad++ (freeware):
http://notepad-plus-plus.org/

On Linux I use Geany (freeware):
http://www.geany.org/

awesome stuff

rosehosting's picture

Great article for a great piece of software. Yes, it's proprietary, but it's one of the best text editors I've ever used. I do use vim too, but Sublime is also extraordinary piece of work. Imo, not to be even compared to the most of them out there.

Anyway, great post, bookmarked!

a proprietary editor on my

Recettes Thai's picture

a proprietary editor on my open system ? no thanx, i'll stick to the basics

How does this editor compare

John O&#039;Hara's picture

How does this editor compare to Geany, for instance ?

Wow

Anomalous's picture

I've needed a WP to do much of these for regular writing, let alone coding. Top!

Webinar
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Webinar
Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix