tags:

views:

2277

answers:

8

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?

+3  A: 

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

V
%
>
innaM
+1  A: 

Use '>' to tab a block

Brian
A: 

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
+1  A: 

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

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

Mykola Golubyev
A: 

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.

Kristo
+10  A: 

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

=%

All code within this block will be correctly indented.

skinp
it indends only one line in my vim. Any idea?
Mykola Golubyev
You're not on one of the {}s.
Steve K
@Steve K: I am. Selecting all lines and pressing = works. =% doesn't :(
Mykola Golubyev
@Steve K: Sorry. I misunderstood. I didn't put on the {}. I put inside.
Mykola Golubyev
@skinp: set cindent seams doesn't play any role in this case. Instead you should be aware of set 'equalprg' option to '' to make this work.
Mykola Golubyev
using :he textobjects you could =i{ and not have to be on the specific starting/ending line of the block
michael
A: 

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
42
A: 

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.

Steve K