1 #! /usr/local/bin/python
2 #! /usr/local/bin/python
4 # This file contains a class and a main program that perform two
5 # related (though complimentary) formatting operations on Python
6 # programs. When called as "pindend -c", it takes a valid Python
7 # program as input and outputs a version augmented with block-closing
8 # comments. When called as "pindent -r" it assumes its input is a
9 # Python program with block-closing comments but with its indentation
10 # messed up, and outputs a properly indented version.
12 # A "block-closing comment" is a comment of the form '# end <keyword>'
13 # where <keyword> is the keyword that opened the block. If the
14 # opening keyword is 'def' or 'class', the function or class name may
15 # be repeated in the block-closing comment as well. Here is an
16 # example of a program fully augmented with block-closing comments:
30 # Note that only the last part of an if...elif...else... block needs a
31 # block-closing comment; the same is true for other compound
32 # statements (e.g. try...except). Also note that "short-form" blocks
33 # like the second 'if' in the example must be closed as well;
34 # otherwise the 'else' in the example would be ambiguous (remember
35 # that indentation is not significant when interpreting block-closing
38 # Both operations are idempotent (i.e. applied to their own output
39 # they yield an identical result). Running first "pindent -c" and
40 # then "pindent -r" on a valid Python program produces a program that
41 # is semantically identical to the input (though its indentation may
45 # -s stepsize: set the indentation step size (default 8)
46 # -t tabsize : set the number of spaces a tab character is worth (default 8)
47 # file ... : input file(s) (default standard input)
48 # The results always go to standard output
51 # - comments ending in a backslash will be mistaken for continued lines
52 # - continuations using backslash are always left unchanged
53 # - continuations inside parentheses are not extra indented by -r
54 # but must be indented for -c to work correctly (this breaks
56 # - continued lines inside triple-quoted strings are totally garbled
59 # - On input, a block may also be closed with an "end statement" --
60 # this is a block-closing comment without the '#' sign.
62 # Possible improvements:
63 # - check syntax based on transitions in 'next' table
64 # - better error reporting
65 # - better error recovery
66 # - check identifier after class/def
68 # The following wishes need a more complete tokenization of the source:
69 # - Don't get fooled by comments ending in backslash
70 # - reindent continuation lines indicated by backslash
71 # - handle continuation lines inside parentheses/braces/brackets
72 # - handle triple quoted strings spanning lines
74 # - optionally do much more thorough reformatting, a la C indent
86 next
['if'] = next
['elif'] = 'elif', 'else', 'end'
87 next
['while'] = next
['for'] = 'else', 'end'
88 next
['try'] = 'except', 'finally'
89 next
['except'] = 'except', 'else', 'end'
90 next
['else'] = next
['finally'] = next
['def'] = next
['class'] = 'end'
92 start
= 'if', 'while', 'for', 'try', 'def', 'class'
96 def __init__(self
, fpi
= sys
.stdin
, fpo
= sys
.stdout
,
97 indentsize
= STEPSIZE
, tabsize
= TABSIZE
):
100 self
.indentsize
= indentsize
101 self
.tabsize
= tabsize
103 self
.write
= fpo
.write
104 self
.kwprog
= regex
.symcomp(
105 '^[ \t]*\(<kw>[a-z]+\)'
106 '\([ \t]+\(<id>[a-zA-Z_][a-zA-Z0-9_]*\)\)?'
108 self
.endprog
= regex
.symcomp(
109 '^[ \t]*#?[ \t]*end[ \t]+\(<kw>[a-z]+\)'
110 '\([ \t]+\(<id>[a-zA-Z_][a-zA-Z0-9_]*\)\)?'
112 self
.wsprog
= regex
.compile('^[ \t]*')
116 line
= self
.fpi
.readline()
117 if line
: self
.lineno
= self
.lineno
+ 1
122 def error(self
, fmt
, *args
):
123 if args
: fmt
= fmt
% args
125 sys
.stderr
.write('Error at line %d: %s\n' % (self
.lineno
, fmt
))
126 self
.write('### %s ###\n' % fmt
)
130 line
= self
.readline()
131 while line
[-2:] == '\\\n':
132 line2
= self
.readline()
140 def putline(self
, line
, indent
= None):
145 tabs
, spaces
= divmod(indent
*self
.indentsize
, self
.tabsize
)
146 i
= max(0, self
.wsprog
.match(line
))
147 self
.write('\t'*tabs
+ ' '*spaces
+ line
[i
:])
153 line
= self
.getline()
154 if not line
: break # EOF
156 if self
.endprog
.match(line
) >= 0:
158 kw2
= self
.endprog
.group('kw')
160 self
.error('unexpected end')
161 elif stack
[-1][0] != kw2
:
162 self
.error('unmatched end')
165 self
.putline(line
, len(stack
))
168 if self
.kwprog
.match(line
) >= 0:
169 kw
= self
.kwprog
.group('kw')
171 self
.putline(line
, len(stack
))
172 stack
.append((kw
, kw
))
175 if next
.has_key(kw
) and stack
:
176 self
.putline(line
, len(stack
)-1)
182 self
.putline(line
, len(stack
))
185 self
.error('unterminated keywords')
186 for kwa
, kwb
in stack
:
187 self
.write('\t%s\n' % kwa
)
196 current
, firstkw
, lastkw
, topid
= 0, '', '', ''
198 line
= self
.getline()
199 i
= max(0, self
.wsprog
.match(line
))
200 if self
.endprog
.match(line
) >= 0:
202 endkw
= self
.endprog
.group('kw')
203 thisid
= self
.endprog
.group('id')
204 elif self
.kwprog
.match(line
) >= 0:
205 thiskw
= self
.kwprog
.group('kw')
206 if not next
.has_key(thiskw
):
209 if thiskw
in ('def', 'class'):
210 thisid
= self
.kwprog
.group('id')
214 elif line
[i
:i
+1] in ('\n', '#'):
220 indent
= len(string
.expandtabs(line
[:i
], self
.tabsize
))
221 while indent
< current
:
224 s
= '# end %s %s\n' % (
227 s
= '# end %s\n' % firstkw
229 self
.putline(s
, current
)
230 firstkw
= lastkw
= ''
232 current
, firstkw
, lastkw
, topid
= stack
[-1]
235 if indent
== current
and firstkw
:
238 self
.error('mismatched end')
240 firstkw
= lastkw
= ''
241 elif not thiskw
or thiskw
in start
:
243 s
= '# end %s %s\n' % (
246 s
= '# end %s\n' % firstkw
248 self
.putline(s
, current
)
249 firstkw
= lastkw
= topid
= ''
253 stack
.append(current
, firstkw
, lastkw
, topid
)
254 if thiskw
and thiskw
not in start
:
258 current
, firstkw
, lastkw
, topid
= \
259 indent
, thiskw
, thiskw
, thisid
263 firstkw
= lastkw
= thiskw
269 for l
in todo
: self
.write(l
)
278 # end class PythonIndenter
280 # Simplified user interface
281 # - xxx_filter(input, output): read and write file objects
282 # - xxx_string(s): take and return string object
283 # - xxx_file(filename): process file in place, return true iff changed
285 def complete_filter(input= sys
.stdin
, output
= sys
.stdout
,
286 stepsize
= STEPSIZE
, tabsize
= TABSIZE
):
287 pi
= PythonIndenter(input, output
, stepsize
, tabsize
)
289 # end def complete_filter
291 def reformat_filter(input = sys
.stdin
, output
= sys
.stdout
,
292 stepsize
= STEPSIZE
, tabsize
= TABSIZE
):
293 pi
= PythonIndenter(input, output
, stepsize
, tabsize
)
298 def __init__(self
, buf
):
301 self
.len = len(self
.buf
)
303 def read(self
, n
= 0):
305 n
= self
.len - self
.pos
307 n
= min(n
, self
.len - self
.pos
)
309 r
= self
.buf
[self
.pos
: self
.pos
+ n
]
310 self
.pos
= self
.pos
+ n
314 i
= string
.find(self
.buf
, '\n', self
.pos
)
315 return self
.read(i
+ 1 - self
.pos
)
319 line
= self
.readline()
322 line
= self
.readline()
326 # seek/tell etc. are left as an exercise for the reader
327 # end class StringReader
334 self
.buf
= self
.buf
+ s
339 # end class StringWriter
341 def complete_string(source
, stepsize
= STEPSIZE
, tabsize
= TABSIZE
):
342 input = StringReader(source
)
343 output
= StringWriter()
344 pi
= PythonIndenter(input, output
, stepsize
, tabsize
)
346 return output
.getvalue()
347 # end def complete_string
349 def reformat_string(source
, stepsize
= STEPSIZE
, tabsize
= TABSIZE
):
350 input = StringReader(source
)
351 output
= StringWriter()
352 pi
= PythonIndenter(input, output
, stepsize
, tabsize
)
354 return output
.getvalue()
355 # end def reformat_string
357 def complete_file(filename
, stepsize
= STEPSIZE
, tabsize
= TABSIZE
):
358 source
= open(filename
, 'r').read()
359 result
= complete_string(source
, stepsize
, tabsize
)
360 if source
== result
: return 0
363 try: os
.rename(filename
, filename
+ '~')
364 except os
.error
: pass
366 f
= open(filename
, 'w')
370 # end def complete_file
372 def reformat_file(filename
, stepsize
= STEPSIZE
, tabsize
= TABSIZE
):
373 source
= open(filename
, 'r').read()
374 result
= reformat_string(source
, stepsize
, tabsize
)
375 if source
== result
: return 0
378 os
.rename(filename
, filename
+ '~')
379 f
= open(filename
, 'w')
383 # end def reformat_file
385 # Test program when called as a script
388 usage: pindent (-c|-r) [-s stepsize] [-t tabsize] [file] ...
389 -c : complete a correctly indented program (add #end directives)
390 -r : reformat a completed program (use #end directives)
391 -s stepsize: indentation step (default %(STEPSIZE)d)
392 -t tabsize : the worth in spaces of a tab (default %(TABSIZE)d)
393 [file] ... : files are changed in place, with backups in file~
394 If no files are specified or a single - is given,
395 the program acts as a filter (reads stdin, writes stdout).
401 opts
, args
= getopt
.getopt(sys
.argv
[1:], 'crs:t:')
402 except getopt
.error
, msg
:
403 sys
.stderr
.write('Error: %s\n' % msg
)
404 sys
.stderr
.write(usage
)
416 stepsize
= string
.atoi(a
)
418 tabsize
= string
.atoi(a
)
423 'You must specify -c(omplete) or -r(eformat)\n')
424 sys
.stderr
.write(usage
)
427 if not args
or args
== ['-']:
428 action
= eval(action
+ '_filter')
429 action(sys
.stdin
, sys
.stdout
, stepsize
, tabsize
)
431 action
= eval(action
+ '_file')
433 action(file, stepsize
, tabsize
)
438 if __name__
== '__main__':