Sublime Text 2: Auto fix indentation for javascript?

Here's some sample code I have, currently I'm set to only indent using 4 spaces at a time. Is there a way to highlight a block of javascript and press a single button or menu option to format it nicely like so:

Before:

app.get('/csvtest', function (req, res) {
  MyModel.find(function (err, mymodel) {
    if (!err) {
      var csv = [];
      _.each(mymodel, function(obj) {
       csv.push(obj['mymodel']);
      });
      res.send(csv.join());
    } else {
      console.log(err);
    }
  });
});

After:

app.get('/csvtest', function (req, res) {
    MyModel.find(function (err, mymodel) {
        if (!err) {
            var csv = [];
            _.each(mymodel, function(obj) {
                csv.push(obj['mymodel']);
            });
            res.send(csv.join());
        } else {
            console.log(err);
        }
    });
});

Here is a tool for this. Found it on the sublime forums.

  • Install Package control
  • Run Package Control: Install Package from the command palette. Type Ctrl + Shift + P (Windows) or Command + Shift + P to open the command palette
  • Search for jsFormat and hit enter
  • Ctrl + Alt + f to format

You could give JsFormat a go. ctrl+alt+f formats the selected text.


You can select all your code (ctrl+A) and use the in-app functionality, Reindent (Edit -> Line -> Reindent). It will format your code with looking at the Sublime's tab/intent setting.

Alternatively: You can use JsFormat formatting plugin for Sublime Text 2 if you would like to have more customizable settings on how to format your code to addition to the Sublime Text's default tab/indent settings.

https://github.com/jdc0589/JsFormat

More info how to install JsFormat to your Sublime IDE: You can easily install JsFormat with using Package Control (Preferences -> Package Control) Open package control then type install, hit enter. Then type "js format" and hit enter, you're done. (The package controller will show the status of the installation with success and errors on the bottom left bar of Sublime)

Setting the short cut: Add the following line to your key bindings (Preferences -> Key Bindings User)

{ "keys": ["ctrl+alt+2"], "command": "js_format"}

I'm using ctrl+alt+2, you can change this short cut key whatever you want to.

My opinion: JsFormat is a good one, definitely worth to try it!


If you specifically want to go from 2 to 4 spaces, click on the tab menu in the lower right corner. Click "convert indentation to tabs", change width to 4, then "convert indentation to spaces."