Code beautifiers, anyone?

Matti J. Karki mjk at iki.fi
Thu Aug 24 22:00:23 UTC 2006


On 8/24/06, Kyrre Nygård <kyrreny at broadpark.no> wrote:
>
> Perhaps you could share with us whatever scripts you've written?
>

Totally forgot to include the actual intendation script.

There should be a Python script attached to this mail. Please note,
that the script is not a silver bullet! It was designed to clean up
some pretty messed up C code. Usually I study the coding style before
creating this kind of clean-up-scripts. Also, the code is not very
clean itself (pretty ironic, I guess) :) It's just a hack to take care
of one step of the cleaning process.


        -Matti
-------------- next part --------------
import sys
import re
import os

INDENTSTR = "    "

f = open(sys.argv[1], "r")
inbuffer = f.read()
f.close()

outbuffer = ""
indent = 0
indentnext = 0

inbuffer = re.sub('\n +', '\n', inbuffer)
inbuffer = re.sub('\t+', '', inbuffer)
inbuffer = re.sub('\) *?\n\{', ') {', inbuffer)
inbuffer = re.sub('\) *?{', ') {', inbuffer)
inbuffer = re.sub('else *?\n{', 'else {\n', inbuffer)
inbuffer = re.sub('{ *?(.+?\n)', '{\n\g<1>', inbuffer)
inbuffer = re.sub('(\n.+?)}', '\g<1>\n}', inbuffer)
inbuffer = re.sub('\n +', '\n', inbuffer)

for chr in inbuffer:
	if chr == "{":
		indent += 1
		outbuffer += "{"
		continue
	if chr == "}":
		indent -= 1
		outbuffer += indent * INDENTSTR + "}"
		indentnext = 0
		continue
	if chr == "\n":
		outbuffer += "\n"
		indentnext = 1
		continue
	if indentnext == 1:
		outbuffer +=  indent * INDENTSTR + chr
		indentnext = 0
	else:
		outbuffer += chr

outfilename = sys.argv[1]
oldfilename = outfilename + ".bak"

os.rename(outfilename, oldfilename)

f = open(outfilename, "w")
f.write(outbuffer)
f.close()


More information about the freebsd-questions mailing list