Reformat a Python file to have 4 space indentations


Question

I'm editing a Python file that uses two spaces for programmatic indents - I prefer 4 spaces. In my .vimrc I have the following settings related to indentation:

set tabstop=4                     "Indentation levels every four columns
set expandtab                     "Convert all tabs typed to spaces
set shiftwidth=4                  "Indent/outdent by four columns
set softtabstop=4

How do I get Vim to convert all the existing 2 space indents to be 4 space indents?

In other words:

if something:
  dothis()

becomes

if something:
    dothis()

When I tried gg=G

def check():
  for a in list:
    for  b in list2:
      check(a, b)
      while (len > MAX) :
        poll()

  while(len(thelist) > 0) :
    poll()  

  return results

became

def check():
    for a in list:
    for  b in list2:
    check(a, b)
    while (len > MAX) : 
        poll()

        while(len(thelist) > 0) :
            poll()

            return results
1
22
12/1/2014 11:26:55 AM

Accepted Answer

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

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

& in replacement pattern is the matched pattern.

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

50
3/7/2011 9:02:39 AM

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

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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon