Skip to content

Fix Python source code to use spaces instead of tabs

2008 December 7
tags:
by pk

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 and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • LinkedIn
  • Posterous
  • Tumblr
  • Twitter
9 Responses leave one →
  1. December 7, 2008

    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. December 7, 2008

    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. December 7, 2008

    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. December 7, 2008

    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. December 7, 2008

    Doh! Formatting messed that up.

    Try:

    :%s/^V^I/ /g

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

  6. December 8, 2008

    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 permalink
    December 8, 2008

    Why would anyone untab stuff? Tabs are the best.

  8. December 8, 2008

    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 permalink
    December 8, 2008

    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 Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS