7

In Aptana Studio when I have to format code I choose a block of code and then press Ctrl + Shift + F.

What is the equivalent of this in Vim?

I.e., say we got the below lines of code:

function() {
var test = "Hello, World!";
var test2 = "Hello, World! Again";
}

The final output I want to see is well formatted code like below:

function(){
  var test = "Hello, World!";
  var test2 = "Hello, World! Again";
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
runtimeZero
  • 26,466
  • 27
  • 73
  • 126
  • 2
    Have you read [this](http://stackoverflow.com/questions/235839/how-do-i-indent-multiple-lines-quickly-in-vi?rq=1)? – admdrew Mar 11 '14 at 17:22

4 Answers4

9

If Vim knows the language you are using, you can use the = key to auto-indent a section of code.

Within the block type =a}, or to auto-indent the entire file by typing gg=G.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Matt Woelk
  • 1,940
  • 1
  • 20
  • 24
5

Use >i{ (right-shift inside current block), or better yet, =a{ (properly indent the current block), plus having a proper indent mode enabled (e.g. :set cindent).

If you're opening up a whole file that's badly indented, you might want to start off with gg=G (re-indent the whole file).

hobbs
  • 223,387
  • 19
  • 210
  • 288
3

You can use

set shiftwidth=2

to indent with two spaces, as I can see in your example, and then:

V

to insert in visual mode block,

j

to go one line down and select both,

>

to indent once.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Birei
  • 35,723
  • 2
  • 77
  • 82
2
  • Esc to get to normal mode.
  • Select with v or V, and then >.
  • >> or :> to indent one line.
  • X>> or :X> if you want to indent multiple times.

Check :help shiftwidth to set how many spaces your indentation will be.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Math
  • 2,399
  • 2
  • 20
  • 22