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
  • 30,030
  • 21
  • 100
  • 124
runtimeZero
  • 24,338
  • 25
  • 69
  • 120
  • 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
  • 30,030
  • 21
  • 100
  • 124
Matt Woelk
  • 1,750
  • 1
  • 18
  • 23
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
  • 206,796
  • 16
  • 199
  • 282
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
  • 30,030
  • 21
  • 100
  • 124
Birei
  • 34,778
  • 2
  • 71
  • 80
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
  • 30,030
  • 21
  • 100
  • 124
Math
  • 2,269
  • 2
  • 18
  • 22