Sublime Text 2: Auto fix indentation for javascript?
Asked Answered
D

7

74

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);
        }
    });
});
Diplegia answered 12/10, 2012 at 20:54 Comment(0)
I
150

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
Intercalate answered 12/10, 2012 at 21:0 Comment(6)
This links to a GitHub page. How do you use it?Loiret
@Imray I added a little more detail to my answer. Hope you have resolved thisIntercalate
To add https://github.com/jdc0589/JsFormat as a Package Control repository in sublime you go to Preferences->Package Control->"Package Control: add Repository" and "Package Control: Install Package"Admeasurement
I had to type "Format" to get a "Format Javascript" option. Might help someone else who couldn't get these answers to work verbatimAblebodied
Thanks @CQM, I'll update these instructions, they seem to be stale.Intercalate
Nice tip, but there are some missing steps: restart sublime, run "Format: Javascript" command from the palette when needed (Ctrl + Alt + F) shortcut in mac.Gristede
I
40

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

Isologous answered 12/10, 2012 at 21:0 Comment(0)
D
37

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!

Dogface answered 24/6, 2013 at 23:41 Comment(2)
Thanks a lot - your first answer is really easy and helpful! Didn't know there existed an option for that :)Chobot
Kudos for your 1st answer that helps people without internet connection.Loath
M
7

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

Marjorymarjy answered 12/10, 2012 at 21:3 Comment(0)
B
2

The fastest way to do this, in general, is with a regex:

  • Press CTRL+H
  • Enable the Regular Expression button to the bottom-left (or press ALT+R)
  • Enter ^(\s+) in Find What
  • Enter \1\1 in Replace With
  • Click Replace All to the right

This will double the number of prefixed spaces (bringing 2 spaces to 4). The replace window can then be left open to easily apply this to multiple files.

Bricabrac answered 4/2, 2015 at 14:12 Comment(0)
A
1

It looks like Sublime Text 2 already has what you want (maybe they added this feature more recently).

Whether you're wanting to change the number of Spaces or you're wanting to convert Spaces to Tabs, you can use this path: View > Indentation

Within that dropdown menu you have the option to Convert Indentation to Tabs, to Convert Indentation to Spaces, or to choose how many Spaces the Tab Width (1-8) should be.

Hope this helps!

Archeozoic answered 18/2, 2016 at 20:11 Comment(2)
This doesn't answer the question that OP asked. He wants the inside of blocks to be more indented than the block declaration.Apomixis
@wilbur is right. OP was looking for a formatter hotkey extension of some sort.Archeozoic
P
0

Install jsFormat using PackageControl by selecting jsFormat from the Install Package menu.

Then do this to auto-format your code:

Ctrl + Alt + F

It is also helpful to review the jsLint recommendations for formatting. You can install the jsLint package and validate with formatting options enabled.

Ctrl + L

Pavid answered 22/5, 2015 at 19:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.