[ACCEPTED]-Reformat a Python file to have 4 space indentations-vim

Accepted answer
Score: 49

In order to double the number of spaces 4 at the beginning of every line (and only 3 at the beginning):

:%s/^\s*/&&/g

& in replacement pattern 2 is the matched pattern.

Probably it will 1 not have any side-effect for you.

Score: 18

Pressing gg=G is the command to re-indent everything 9 in a file. If you have other elements that 8 can be re-indented, vim will indent these 7 as well, which doesn't always give the desired 6 effects. You'll have to clean these up 5 manually if they're ugly.

Alternately, you 4 can use the > command to indent, with ranges 3 to go through the file somewhat efficiently 2 manually. 99>k, for example, would indent the 1 99 lines below the cursor by one level.

Score: 4

I've found the reindent script http://pypi.python.org/pypi/Reindent/0.1.0 works well 7 for me. Not pure vim, but really easy!

After 6 its installed you can use it in vim with 5

:%! reindent

(ie pipe the entire buffer through the reindent 4 program) and it's done.

From the command 3 line it can be used to reindent multiple 2 files (eg all files in a directory, or even 1 recursively down a directory tree).

Score: 2

try the following substitution command:

:%s/  /    /g

(To 6 clarify: there are two spaces between the 5 first and second '/' and four the second 4 and third '/'.)

One helpful command when 3 working with whitespace issues is also the 2 set list command which will visually show all whitespace. Use set nolist to 1 unset.

Score: 2

The best current way to reformat Python, fix 5 many other issues, and also make it PEP8 4 compliant is to use autopep8. See this related question. So after 3 you've installed autopep8 (e.g. pip install autopep8) in vim 2 you do:

:%! autopep8 -

There's also a vim-autopep8 plugin to make things 1 even simpler.

Score: 0

The vim plugin vim-autoformat integrates the formatter 7 autopep8 into vim automatically, if it is installed. You 6 can format the whole file, or the visually 5 selected part using a single keystroke.

More 4 importantly, vim-autoformat takes the relevant 3 settings of your .vimrc into account, e.g. if 2 you have

set shiftwidth=4

in your .vimrc, it will pass this information 1 on to autopep8.

More Related questions