#!/usr/bin/python # cbIndent.py - an automagic indenter for CoolBasic code # 03.08.2010 # by KilledWhale import sys, getopt, re output = [] def main(argv): infile = '' outfile = '' width = 0 try: opts, args = getopt.getopt(argv, "hi:o:w:", ["help", "input=", "output=", "width="]) except getopt.GetoptError: print 'cbIndent.py -i <input> -o <output>' sys.exit(2) for opt, arg in opts: if opt in ('-h', '--help'): print 'cbIndent.py -i <input> -o <output>' sys.exit() elif opt in ('-i', '--input'): infile = arg elif opt in ('-o', '--output'): outfile = arg elif opt in ('-w', '--width'): width = int(arg) if not infile: print 'You must give at least an input file!' sys.exit(2) inadd = re.compile('^(if.*then$|for |repeat|while|function|lock|startsearch|type)', re.I) indec = re.compile('^(end *if|next|until|for *ever|wend|end *function|unlock|endsearch|end *type)', re.I) doubleadd = re.compile('^select', re.I) doubledec = re.compile('^end *select', re.I) ined = re.compile('^(else *(if)?|case|default)', re.I) indent = '' file = open(infile) for line in file: line = line.strip() m = inadd.match(line) if m: output.append('%s%s' % (indent, line)) indent = '%s%s' % (indent, chr(9)) continue m = indec.match(line) if m: indent = indent[:len(indent) - 1] output.append('%s%s' % (indent, line)) continue m = doubleadd.match(line) if m: output.append('%s%s' % (indent, line)) indent = '%s%s%s' % (indent, chr(9), chr(9)) continue m = doubledec.match(line) if m: indent = indent[:len(indent) - 2] output.append('%s%s' % (indent, line)) continue m = ined.match(line) if m: output.append('%s%s' % (indent[:len(indent) - 1], line)) continue output.append('%s%s' % (indent, line)) file.close() if outfile: file = open(outfile, 'w') for line in output: if (width): line = line.expandtabs(width) if outfile: file.write('%s\n' % line) else: print line if outfile: file.close() if __name__ == "__main__": main(sys.argv[1:])