# tabfix.py by Joe Strout # # converts a file built with 4-space tabs into a # similar file made with 8-space tabs and strings of 4 spaces. import sys import string import regex TAB = '\t' endspace = regex.compile(' * $') def fixTabs(str): # first, replace all tabs with spaces str = string.expandtabs(str,4) # assuming 4-space tabs # now collapse spaces to tabs, where possible tabsize = 8 col = (len(str)/tabsize)*tabsize while col >= 0: # check for at least spaces ending before the next tab stop; # if found, replace with tabs pos = col + endspace.search( str[col:col+tabsize] ) if pos >= col: str = str[:pos] + TAB + str[col+tabsize:] col = col - tabsize return str def processFile(filename): try: file = open( filename, 'r' ) # open the file except: print "Error opening",filename return lines = file.readlines() # read it for i in range(0,len(lines)): # process it... lines[i] = fixTabs(lines[i]) file = open( filename, 'w' ) # open it again file.writelines(lines) # write it print len(lines), "lines processed in",filename # end of processFile() function def run(filename=''): if filename=='': filename = raw_input('Enter name of a textfile to read: ') processFile(filename) # end of run() function # immediate-mode commands, for drag-and-drop or execfile() execution if __name__ == '__main__': if len(sys.argv) == 2: processFile(sys.argv[1]) # accept a command-line filename else: run() print raw_input("press Return>") else: print "Module tabfix imported." print "To run, type: tabfix.run()" print "To reload after changes to the source, type: reload(tabfix)" # end of tabfix.py