Blog from the Loft

Thoughts without walls

Blog from the Loft header image 2

Fix Python source code to use spaces instead of tabs

December 7th, 2008 · 9 Comments · django

What if someone gave you a Python source file that is indented using tabs? If you are using emacs, the following will let you convert it back to using spaces:

# first set the buffer tab width to 4 (or whatever you like)

M-x set-variable <return> tab-width < return> 4

# then mark the entire file
C-x h

# do untabify to convert:

M-x untabify <return>

# That’s it!

Technorati Tags: ,

  • Share/Bookmark

Tags:

9 responses so far ↓

  • 1 Max Battcher // Dec 7, 2008 at 11:25 pm

    In Vim:

    :set ts=4
    :set et!

    You can also use the long names tabstop and expand-tab. You may also want to update shiftwidth (sw) and soft tabstop (sts) to the same value as you choose for tabstop.

  • 2 Max Battcher // Dec 7, 2008 at 11:30 pm

    Oh, and in my experience in Vim :set et! will retab the document, but there is also the :retab command to explicitly do that as well.

  • 3 AJ // Dec 7, 2008 at 11:48 pm

    If you have access to command-line programs in the Unix tradition, the one that expands out tabs is called ‘expand’ and has an option -t to set the tab-width (or it may specify an explicit list of the tab stop columns to use instead).

  • 4 Ross Poulton // Dec 7, 2008 at 11:49 pm

    FWIW, to do that in vim you would use the command:

    :%s// /g

    Instead of typing , just press the ‘tab’ key (or press ^V^I) . The bit between the 2nd and 3rd ‘/’ marks is just 4 spaces.

  • 5 Ross Poulton // Dec 7, 2008 at 11:50 pm

    Doh! Formatting messed that up.

    Try:

    :%s/^V^I/ /g

    Again, just 4 spaces between the 2nd and 3rd slashes.

  • 6 Richard Lopes // Dec 8, 2008 at 12:17 am

    Hi,

    And what if you prefer tab formatted files ;-) ?
    Is there an equivalent to translate spaces into tabs ?
    Nowadays you can define how much spaces a tab translates into in your favourite editor.

  • 7 hachaboob // Dec 8, 2008 at 6:17 am

    Why would anyone untab stuff? Tabs are the best.

  • 8 Swaroop C H // Dec 8, 2008 at 7:34 am

    Just for completeness sake, this can be done in Vim using:

    :set tabstop=4 ” set spacing of 4
    :set expandtab ” instruct to expand tabs to spaces
    :1,$retab! ” replace existing tabs with spaces in the whole file

  • 9 Ken Arnold // Dec 8, 2008 at 2:25 pm

    Also check out reindent (http://pypi.python.org/pypi/Reindent/0.1.0). Can run on a whole directory tree at once, and fixes inconsistent indentation.

Leave a Comment