3 # This file contains a class and a main program that perform three
4 # related (though complimentary) formatting operations on Python
5 # programs. When called as "pindent -c", it takes a valid Python
6 # program as input and outputs a version augmented with block-closing
7 # comments. When called as "pindent -d", it assumes its input is a
8 # Python program with block-closing comments and outputs a commentless
9 # version. When called as "pindent -r" it assumes its input is a
10 # Python program with block-closing comments but with its indentation
11 # messed up, and outputs a properly indented version.
13 # A "block-closing comment" is a comment of the form '# end <keyword>'
14 # where <keyword> is the keyword that opened the block. If the
15 # opening keyword is 'def' or 'class', the function or class name may
16 # be repeated in the block-closing comment as well. Here is an
17 # example of a program fully augmented with block-closing comments:
31 # Note that only the last part of an if...elif...else... block needs a
32 # block-closing comment; the same is true for other compound
33 # statements (e.g. try...except). Also note that "short-form" blocks
34 # like the second 'if' in the example must be closed as well;
35 # otherwise the 'else' in the example would be ambiguous (remember
36 # that indentation is not significant when interpreting block-closing
39 # The operations are idempotent (i.e. applied to their own output
40 # they yield an identical result). Running first "pindent -c" and
41 # then "pindent -r" on a valid Python program produces a program that
42 # is semantically identical to the input (though its indentation may
43 # be different). Running "pindent -e" on that output produces a
44 # program that only differs from the original in indentation.
47 # -s stepsize: set the indentation step size (default 8)
48 # -t tabsize : set the number of spaces a tab character is worth (default 8)
49 # -e : expand TABs into spaces
50 # file ... : input file(s) (default standard input)
51 # The results always go to standard output
54 # - comments ending in a backslash will be mistaken for continued lines
55 # - continuations using backslash are always left unchanged
56 # - continuations inside parentheses are not extra indented by -r
57 # but must be indented for -c to work correctly (this breaks
59 # - continued lines inside triple-quoted strings are totally garbled
62 # - On input, a block may also be closed with an "end statement" --
63 # this is a block-closing comment without the '#' sign.
65 # Possible improvements:
66 # - check syntax based on transitions in 'next' table
67 # - better error reporting
68 # - better error recovery
69 # - check identifier after class/def
71 # The following wishes need a more complete tokenization of the source:
72 # - Don't get fooled by comments ending in backslash
73 # - reindent continuation lines indicated by backslash
74 # - handle continuation lines inside parentheses/braces/brackets
75 # - handle triple quoted strings spanning lines
77 # - optionally do much more thorough reformatting, a la C indent
90 next
['if'] = next
['elif'] = 'elif', 'else', 'end'
91 next
['while'] = next
['for'] = 'else', 'end'
92 next
['try'] = 'except', 'finally'
93 next
['except'] = 'except', 'else', 'end'
94 next
['else'] = next
['finally'] = next
['def'] = next
['class'] = 'end'
96 start
= 'if', 'while', 'for', 'try', 'def', 'class'
100 def __init__(self
, fpi
= sys
.stdin
, fpo
= sys
.stdout
,
101 indentsize
= STEPSIZE
, tabsize
= TABSIZE
, expandtabs
= EXPANDTABS
):
104 self
.indentsize
= indentsize
105 self
.tabsize
= tabsize
107 self
.expandtabs
= expandtabs
108 self
._write
= fpo
.write
109 self
.kwprog
= re
.compile(
110 r
'^\s*(?P<kw>[a-z]+)'
111 r
'(\s+(?P<id>[a-zA-Z_]\w*))?'
113 self
.endprog
= re
.compile(
114 r
'^\s*#?\s*end\s+(?P<kw>[a-z]+)'
115 r
'(\s+(?P<id>[a-zA-Z_]\w*))?'
117 self
.wsprog
= re
.compile(r
'^[ \t]*')
120 def write(self
, line
):
122 self
._write
(string
.expandtabs(line
, self
.tabsize
))
129 line
= self
.fpi
.readline()
130 if line
: self
.lineno
= self
.lineno
+ 1
135 def error(self
, fmt
, *args
):
136 if args
: fmt
= fmt
% args
138 sys
.stderr
.write('Error at line %d: %s\n' % (self
.lineno
, fmt
))
139 self
.write('### %s ###\n' % fmt
)
143 line
= self
.readline()
144 while line
[-2:] == '\\\n':
145 line2
= self
.readline()
153 def putline(self
, line
, indent
= None):
158 tabs
, spaces
= divmod(indent
*self
.indentsize
, self
.tabsize
)
160 m
= self
.wsprog
.match(line
)
163 self
.write('\t'*tabs
+ ' '*spaces
+ line
[i
:])
169 line
= self
.getline()
170 if not line
: break # EOF
172 m
= self
.endprog
.match(line
)
177 self
.error('unexpected end')
178 elif stack
[-1][0] != kw2
:
179 self
.error('unmatched end')
182 self
.putline(line
, len(stack
))
185 m
= self
.kwprog
.match(line
)
189 self
.putline(line
, len(stack
))
190 stack
.append((kw
, kw
))
193 if next
.has_key(kw
) and stack
:
194 self
.putline(line
, len(stack
)-1)
200 self
.putline(line
, len(stack
))
203 self
.error('unterminated keywords')
204 for kwa
, kwb
in stack
:
205 self
.write('\t%s\n' % kwa
)
214 line
= self
.getline()
215 if not line
: break # EOF
217 m
= self
.endprog
.match(line
)
219 end_counter
= end_counter
+ 1
222 m
= self
.kwprog
.match(line
)
226 begin_counter
= begin_counter
+ 1
231 if begin_counter
- end_counter
< 0:
232 sys
.stderr
.write('Warning: input contained more end tags than expected\n')
233 elif begin_counter
- end_counter
> 0:
234 sys
.stderr
.write('Warning: input contained less end tags than expected\n')
242 current
, firstkw
, lastkw
, topid
= 0, '', '', ''
244 line
= self
.getline()
246 m
= self
.wsprog
.match(line
)
249 m
= self
.endprog
.match(line
)
252 endkw
= m
.group('kw')
253 thisid
= m
.group('id')
255 m
= self
.kwprog
.match(line
)
257 thiskw
= m
.group('kw')
258 if not next
.has_key(thiskw
):
261 if thiskw
in ('def', 'class'):
262 thisid
= m
.group('id')
266 elif line
[i
:i
+1] in ('\n', '#'):
273 indent
= len(string
.expandtabs(line
[:i
], self
.tabsize
))
274 while indent
< current
:
277 s
= '# end %s %s\n' % (
280 s
= '# end %s\n' % firstkw
282 self
.putline(s
, current
)
283 firstkw
= lastkw
= ''
285 current
, firstkw
, lastkw
, topid
= stack
[-1]
288 if indent
== current
and firstkw
:
291 self
.error('mismatched end')
293 firstkw
= lastkw
= ''
294 elif not thiskw
or thiskw
in start
:
296 s
= '# end %s %s\n' % (
299 s
= '# end %s\n' % firstkw
301 self
.putline(s
, current
)
302 firstkw
= lastkw
= topid
= ''
306 stack
.append((current
, firstkw
, lastkw
, topid
))
307 if thiskw
and thiskw
not in start
:
311 current
, firstkw
, lastkw
, topid
= \
312 indent
, thiskw
, thiskw
, thisid
316 firstkw
= lastkw
= thiskw
322 for l
in todo
: self
.write(l
)
331 # end class PythonIndenter
333 # Simplified user interface
334 # - xxx_filter(input, output): read and write file objects
335 # - xxx_string(s): take and return string object
336 # - xxx_file(filename): process file in place, return true iff changed
338 def complete_filter(input = sys
.stdin
, output
= sys
.stdout
,
339 stepsize
= STEPSIZE
, tabsize
= TABSIZE
, expandtabs
= EXPANDTABS
):
340 pi
= PythonIndenter(input, output
, stepsize
, tabsize
, expandtabs
)
342 # end def complete_filter
344 def delete_filter(input= sys
.stdin
, output
= sys
.stdout
,
345 stepsize
= STEPSIZE
, tabsize
= TABSIZE
, expandtabs
= EXPANDTABS
):
346 pi
= PythonIndenter(input, output
, stepsize
, tabsize
, expandtabs
)
348 # end def delete_filter
350 def reformat_filter(input = sys
.stdin
, output
= sys
.stdout
,
351 stepsize
= STEPSIZE
, tabsize
= TABSIZE
, expandtabs
= EXPANDTABS
):
352 pi
= PythonIndenter(input, output
, stepsize
, tabsize
, expandtabs
)
354 # end def reformat_filter
357 def __init__(self
, buf
):
360 self
.len = len(self
.buf
)
362 def read(self
, n
= 0):
364 n
= self
.len - self
.pos
366 n
= min(n
, self
.len - self
.pos
)
368 r
= self
.buf
[self
.pos
: self
.pos
+ n
]
369 self
.pos
= self
.pos
+ n
373 i
= string
.find(self
.buf
, '\n', self
.pos
)
374 return self
.read(i
+ 1 - self
.pos
)
378 line
= self
.readline()
381 line
= self
.readline()
385 # seek/tell etc. are left as an exercise for the reader
386 # end class StringReader
393 self
.buf
= self
.buf
+ s
398 # end class StringWriter
400 def complete_string(source
, stepsize
= STEPSIZE
, tabsize
= TABSIZE
, expandtabs
= EXPANDTABS
):
401 input = StringReader(source
)
402 output
= StringWriter()
403 pi
= PythonIndenter(input, output
, stepsize
, tabsize
, expandtabs
)
405 return output
.getvalue()
406 # end def complete_string
408 def delete_string(source
, stepsize
= STEPSIZE
, tabsize
= TABSIZE
, expandtabs
= EXPANDTABS
):
409 input = StringReader(source
)
410 output
= StringWriter()
411 pi
= PythonIndenter(input, output
, stepsize
, tabsize
, expandtabs
)
413 return output
.getvalue()
414 # end def delete_string
416 def reformat_string(source
, stepsize
= STEPSIZE
, tabsize
= TABSIZE
, expandtabs
= EXPANDTABS
):
417 input = StringReader(source
)
418 output
= StringWriter()
419 pi
= PythonIndenter(input, output
, stepsize
, tabsize
, expandtabs
)
421 return output
.getvalue()
422 # end def reformat_string
424 def complete_file(filename
, stepsize
= STEPSIZE
, tabsize
= TABSIZE
, expandtabs
= EXPANDTABS
):
425 source
= open(filename
, 'r').read()
426 result
= complete_string(source
, stepsize
, tabsize
, expandtabs
)
427 if source
== result
: return 0
430 try: os
.rename(filename
, filename
+ '~')
431 except os
.error
: pass
433 f
= open(filename
, 'w')
437 # end def complete_file
439 def delete_file(filename
, stepsize
= STEPSIZE
, tabsize
= TABSIZE
, expandtabs
= EXPANDTABS
):
440 source
= open(filename
, 'r').read()
441 result
= delete_string(source
, stepsize
, tabsize
, expandtabs
)
442 if source
== result
: return 0
445 try: os
.rename(filename
, filename
+ '~')
446 except os
.error
: pass
448 f
= open(filename
, 'w')
452 # end def delete_file
454 def reformat_file(filename
, stepsize
= STEPSIZE
, tabsize
= TABSIZE
, expandtabs
= EXPANDTABS
):
455 source
= open(filename
, 'r').read()
456 result
= reformat_string(source
, stepsize
, tabsize
, expandtabs
)
457 if source
== result
: return 0
460 try: os
.rename(filename
, filename
+ '~')
461 except os
.error
: pass
463 f
= open(filename
, 'w')
467 # end def reformat_file
469 # Test program when called as a script
472 usage: pindent (-c|-d|-r) [-s stepsize] [-t tabsize] [-e] [file] ...
473 -c : complete a correctly indented program (add #end directives)
474 -d : delete #end directives
475 -r : reformat a completed program (use #end directives)
476 -s stepsize: indentation step (default %(STEPSIZE)d)
477 -t tabsize : the worth in spaces of a tab (default %(TABSIZE)d)
478 -e : expand TABs into spaces (defailt OFF)
479 [file] ... : files are changed in place, with backups in file~
480 If no files are specified or a single - is given,
481 the program acts as a filter (reads stdin, writes stdout).
484 def error_both(op1
, op2
):
485 sys
.stderr
.write('Error: You can not specify both '+op1
+' and -'+op2
[0]+' at the same time\n')
486 sys
.stderr
.write(usage
)
493 opts
, args
= getopt
.getopt(sys
.argv
[1:], 'cdrs:t:e')
494 except getopt
.error
, msg
:
495 sys
.stderr
.write('Error: %s\n' % msg
)
496 sys
.stderr
.write(usage
)
502 expandtabs
= EXPANDTABS
505 if action
: error_both(o
, action
)
509 if action
: error_both(o
, action
)
513 if action
: error_both(o
, action
)
517 stepsize
= string
.atoi(a
)
519 tabsize
= string
.atoi(a
)
526 'You must specify -c(omplete), -d(elete) or -r(eformat)\n')
527 sys
.stderr
.write(usage
)
530 if not args
or args
== ['-']:
531 action
= eval(action
+ '_filter')
532 action(sys
.stdin
, sys
.stdout
, stepsize
, tabsize
, expandtabs
)
534 action
= eval(action
+ '_file')
536 action(file, stepsize
, tabsize
, expandtabs
)
541 if __name__
== '__main__':