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!


{ 9 comments… read them below or add one }
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.
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.
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).
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.
Doh! Formatting messed that up.
Try:
:%s/^V^I/ /g
Again, just 4 spaces between the 2nd and 3rd slashes.
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.
Why would anyone untab stuff? Tabs are the best.
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
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.