Fix Python source code to use spaces instead of tabs

by pk on December 7, 2008

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

{ 9 comments… read them below or add one }

Max Battcher December 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.

Max Battcher December 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.

AJ December 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).

Ross Poulton December 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.

Ross Poulton December 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.

Richard Lopes December 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.

hachaboob December 8, 2008 at 6:17 am

Why would anyone untab stuff? Tabs are the best.

Swaroop C H December 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

Ken Arnold December 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

Previous post: I am in the NY Times, sorta

Next post: SyntaxHighlighter plugin for Wordpress