15

Duplicate:

How to indent code in vim editor in Windows?

Tabbing selected section in VIM

Sometimes I want to indent a block of C code in Vim. I usually ended up tabbing it line by line.

What is a better/faster way?

Community
  • 1
  • 1

8 Answers8

37

I'm surprised no one came up with =% yet.
Make sure you have :set cindent,
Place yourself on one of the {} of your block, and just hit:

=%

All code within this block will be correctly indented.

ib.
  • 26,410
  • 10
  • 77
  • 98
skinp
  • 3,897
  • 4
  • 25
  • 20
8

Use '>' to tab a block

Brian
  • 115,505
  • 16
  • 230
  • 296
7

Enter visual mode, select to the next matching bracket, indent:

V
%
>
innaM
  • 46,966
  • 4
  • 66
  • 87
4

While insert: C-d, C-t
While visual: >, <
While normal: >>, <<

In any of this modes use '.' to indent further.

Mykola Golubyev
  • 55,275
  • 15
  • 85
  • 101
1

Try

:set cindent

This will turn on C indenting magic in vim. So as soon as you open a brace, it will automatically tab until you close the brace.

Jason Punyon
  • 38,225
  • 12
  • 94
  • 120
0

If you have unindented code that looks like this...

if (foo)
{
/* line 1 */
/* line 2 */
/* line 3 */
}

...place your cursor on "line 1" in command mode and type 3==, where 3 is the number of lines to indent.

Michael Kristofik
  • 33,068
  • 15
  • 76
  • 123
0

I think this will do it without any indent switches being set.

:startRange,stopRange s/^/^\t/g

should add a tab space at beginning of line between the line number range you provide

unindent with:

:startRange,stopRange s/^\t/^/g
OldBuildingAndLoan
  • 2,694
  • 4
  • 30
  • 40
0

In addition to what skinp said, if you have:

   int foo()
   {
   /* line 1 */
       /* line 2 */
       /* line 3 */
       /* line 4 */
   }

and for whatever reason wish it to look like this (i.e. you want everything indented 4 spaces* from where they were previously, rather than indenting 'correctly' according to the cindent rules):

   int foo()
   {
       /* line 1 */
           /* line 2 */
           /* line 3 */
           /* line 4 */
   }

anywhere within the block, do viB> (visualselection innerBlock indent)**

* or whatever your shiftwidth is set at

** vi} is the same as viB, and may be easier to remember since vi} selects within {}, vi) selects within (), vi] selects within [], and vi> selects within <>.

Also, va}, va), etc. select the {}, (), etc in addition to what's contained within the block.

Yewge
  • 1,784
  • 2
  • 14
  • 15