jedierikb
jedierikb

Reputation: 13099

converting white space in python files?

I have some tab formatted code in python and I have some space formatted code in python.

Integrating the code in a pain... my editor wants to work in tabs or spaces, but not both.

Is there a command line function in linux or, well, anything which will convert python code formatting one way or the other?

Upvotes: 6

Views: 827

Answers (6)

unutbu
unutbu

Reputation: 880269

reindent.py is a nifty utility script which converts any python .py file into one using 4-space indents and no tabs.

This is useful for "normalizing" code from disparate sources, assuming you're willing to settle on the 4-space standard. (Or, if you want tabs, you could run reindent.py followed by the unix unexpand command.)

PS. Your installation of Python may have reindent.py already installed in a Tools or Examples folder. On Ubuntu it is provided by the python-examples package, and is located at /usr/share/doc/python2.6/examples/Tools/scripts/reindent.py.

Upvotes: 3

Russell Borogove
Russell Borogove

Reputation: 19047

A good programmer's editor will have a command that converts tabs to spaces or vice/versa; you can also do it with search-and-replace in the editor.

Upvotes: 0

dawg
dawg

Reputation: 104024

How about Perl: perl -pe 's/(.*?)\t/$1.(" " x (4-length($1)%4))/ge' file_with_tabs.txt

python (this is from the source of Markdown...):

def _detab_sub(self, match):
    g1 = match.group(1)
    return g1 + (' ' * (self.tab_width - len(g1) % self.tab_width))
def _detab(self, text):

    if '\t' not in text:
        return text
    return self._detab_re.subn(self._detab_sub, text)[0]

Upvotes: 0

SirMo
SirMo

Reputation: 21

You can use expand and unexpand Unix commands for this.

Generally if I code in vim for instance I have it automatically convert tabs to spaces.

my ~/.vimrc looks something like this:

set expandtab
set tabstop=4

Upvotes: 2

jcomeau_ictx
jcomeau_ictx

Reputation: 38472

'man expand' for some info

it's in coreutils on Debian

Upvotes: 2

tylerl
tylerl

Reputation: 30867

Many editors (vi for example) will convert tabs to or from spaces when you indent a line. So set the tab settings however you want, then indent the entire file 1 step, and then unindent one step, and your're done.

Vim commands:

1GVG  <-- select entire file (i have this bound to CTRL-A)
>     <-- indent one step
1GVG  <-- select again 
<     <--- unindent one step

Upvotes: 1

Related Questions