The Anything Box.com

Spacer.py

A tool to change spaces into tabs, for nicer code indenting



Tabs are almost always ten times better than spaces for indenting code, for several reasons. The two most important reasons are that the number of spaces represented by a tab is a setting, and that tabs are much less prone to indentation problems. Quite a lot of code, however, is indented using spaces (this seems to occur most frequently when the programmer is using automatic indenting). I find space-indented code to be annoying to read, and even more annoying to edit.

This program attempts to identify the indentation scheme in a text file, and replace the spaces with tabs sensibly. The algorithm it uses is based on changes in indentation as well as the number of spaces, so arbitrary and sudden shifts in the indentation tendencies of the code don't purterb it (usually). Spacer operates on arbitrary text files, so you could use it to re-indent an outline, or any programming language, or XML files, or anything else that is represented in a plain text file.

The program is very easy to run. The command line takes two files, an input file and an output file (either or both may be -, so 'spacer - -' is a filter). The input file is treated as if every line begins with some number of spaces (which may be zero), and tabs do not count as spaces. The output is the same, except that the spaces at the beginning are replaced with some number of tabs. Although I have tried to make this program robust in the event that the input and output files are the same, it's still not a good idea to overwrite your code mechanically!

Download:

License
This program is distributed under the de facto public domain license. That is, do with it what you want, but remember that it will be done to you. Have fun!

Last Update: Friday, 8 May 2009