≡ Menu

Sublime Text Tips

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.

0 comments

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.

0 comments

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.

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? I’m putting the finishing touches on a new book, Writing Sublime Plugins, that will show you how.

Click here to learn more.

0 comments

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.

0 comments

How to show whitespace in Sublime Text

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.

0 comments

Formatting HTML with Sublime Text

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 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.

Tag supports both Sublime Text 2 and Sublime Text 3, and unlike many of the other options, it 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.

2 comments

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.

2 comments

Win a free Sublime Text 3 license

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.

To subscribe to the newsletter for your chance to win, just drop your email address in the form below.

I want to win a FREE Sublime Text license

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.

I want to win a FREE Sublime Text license

1 comment

It’s easy to get lost when you’re navigating code. You’re working your way down a trail of function calls, skimming, scanning, getting the lay of the land, when …

Bam. One wrong keystroke and you’re in the middle of an unfamiliar file, buried deep in who-knows-what folder.

The new Jump Back and Jump Forward commands in Sublime Text 3 are perfect for this situation. They make it easy to retrace your footsteps and see how the foreign code relates to what you already know.

Jump Back and Jump Forward work like the back and forward buttons in a web browser, but you’re navigating between edit points rather than web pages. Every time you open a new tab or insert your cursor on a line of code, Sublime adds that location to a history stack.

To use Jump Back to return to a previous edit point, click Goto | Jump Back. To navigate forward, click Goto | Jump Forward.

Better yet, learn the keyboard shortcuts: Alt+- and Alt+Shift+- on Windows and Linux or Ctrl+- and Ctrl+Shift+- on OS X.

Jump Back and Jump Forward are also great for toggling back and forth between related sections of code in a long file, such as when you’re simultaneously modifying a function’s definition and its usage in that massive jQuery plugin file, or to switch between multiple related files, such as an HTML file and its style sheet.

0 comments

Sublime Text 3 introduces the new Invert Selection command, and by combining it with multi-select or regular expressions and a little creativity, you can quickly accomplish tasks like zapping unwanted lines in a data file or stripping HTML tags from a block of text.

Invert Selection is useful in scenarios where you want to delete more text than you want to keep, or where it’s just simpler to select the text you’d like to retain.

As its name implies, the command will deselect any text that was highlighted and simultaneously select the text that was not highlighted.

Let’s look at a few scenarios where Invert Selection might be handy.

Clean up CSV data

Even with Sublime’s multi-select, it’s often a pain to select text for deletion. To extract first names from the following CSV list, you could use multi-select to carefully highlight the last name and comma in each row:

Knope,Leslie
Swanson,Ron
Haverford,Tom
Perkins,Ann
Ludgate,April

But a simpler alternative is to highlight all the first names by double clicking them while holding down Ctrl (Windows and Linux) or Command (OS X). Then click Selection | Invert Selection to highlight the unwanted text for deletion.

Filter unwanted lines

By combining Find and Invert Selection, you can easily filter out lines that don’t match a pattern, such as deleting everyone not named Josh in the following list:

Knope,Leslie
Earl,Josh
Swanson,Ron
Haverford,Tom
Perkins,Ann
Turner,Josh
Ludgate,April

Open the Find panel and enable the Regular expression option, then enter the following regular expression, which matches all lines containing the word Josh:

^.*Josh

Click Find All to highlight the two matching lines. Run Invert Selection, then click Edit | Text | Delete Line to eliminate the non-matching lines.

Strip HTML tags

With another regex, Invert Selection can remove HTML tags from a block of text. Let’s clean up a section of the Sublime release notes:

<span style="font-size: 10pt">Release Date: 8 July 2013</span>
    <ul>
  <li>
    Removed expiry date
  </li>

  <li>
    Backported various fixed from Sublime Text 3
  </li>

  <li>
    Improved minimap click behavior. The old behavior is available via the <tt>minimap_scroll_to_clicked_text</tt> setting
  </li>

  <li>
    Added <tt>copy_with_empty_selection</tt> setting, to control the behavior of the copy and cut commands when no text is selected
  </li>

</ul>

Launch Find and make sure the Regular expression option is enabled. Enter the following regex, which matches text that’s wrapped with HTML tags:

(?&lt;=>)(.+?)(?=&lt;)

Click Find All to select the text between the tags. Then run Invert Selection, highlighting the tags for deletion.

0 comments