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.
  • 27,830
  • 11
  • 80
  • 100
skinp
  • 4,157
  • 4
  • 27
  • 20
8

Use '>' to tab a block

Brian
  • 117,631
  • 17
  • 236
  • 300
7

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

V
%
>
innaM
  • 47,505
  • 4
  • 67
  • 87
4

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

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

Mykola Golubyev
  • 57,943
  • 15
  • 89
  • 102
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.

Restore the Data Dumps
  • 38,967
  • 12
  • 96
  • 122
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
  • 34,290
  • 15
  • 75
  • 125
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,801
  • 4
  • 32
  • 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,894
  • 2
  • 15
  • 15