Change 2-space indent to 4-space in vim

A general way of changing the indent is by changing the tabstop:

Paste your file into an empty buffer, then:

:set ts=2 sts=2 noet
:retab!

This changes every 2 spaces to a TAB character, then:

:set ts=4 sts=4 et
:retab

This changes every TAB to 4 spaces.

The advantage of this method is that you can also use it the other way around, to convert from 4 to 2 spaces for example.


It may be possible with :set shiftwidth=4 and gg=G.


What I do is very similar to esneider and cforbish's approaches, but a bit quicker to type:

:%s/^\s*/&&

Simply replaces leading space (spaces or tabs) with twice as much leading space (& is substituted with the matched expression).


This is a very old question, however all the answers are ... wrong ... Vim has a very easy way to reindent the entire file. I learned this after writing my own function to do it, so I'm in the same ignorance boat ;)

type

gg=G

this is assuming that you have your tabstop set to what you like, (so for the OP it would be ts=4)

I learned this from http://vim.wikia.com/wiki/Fix_indentation , which mentions

In normal mode, typing gg=G will reindent the entire file. This is a special case; = is an operator. Just like d or y, it will act on any text that you move over with a cursor motion command. In this case, gg positions the cursor on the first line, then =G re-indents from the current cursor position to the end of the buffer.


I used this regular expression (it doubles the number of leading spaces):

%s;^\(\s\+\);\=repeat(' ', len(submatch(0))*2);g