4

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
  • 28,342
  • 21
  • 95
  • 123
runtimeZero
  • 22,318
  • 19
  • 63
  • 115
  • 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

5

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
  • 28,342
  • 21
  • 95
  • 123
Matt Woelk
  • 1,570
  • 1
  • 17
  • 22
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
  • 187,508
  • 16
  • 182
  • 271
2

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
  • 28,342
  • 21
  • 95
  • 123
Birei
  • 33,968
  • 2
  • 69
  • 79
0
  • 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
  • 28,342
  • 21
  • 95
  • 123
Math
  • 2,149
  • 2
  • 15
  • 22