3 # This file contains a class and a main program that perform two
4 # related (though complimentary) formatting operations on Python
5 # programs. When called as "pindend -c", it takes a valid Python
6 # program as input and outputs a version augmented with block-closing
7 # comments. When called as "pindent -r" it assumes its input is a
8 # Python program with block-closing comments but with its indentation
9 # messed up, and outputs a properly indented version.
11 # A "block-closing comment" is a comment of the form '# end <keyword>'
12 # where <keyword> is the keyword that opened the block. If the
13 # opening keyword is 'def' or 'class', the function or class name may
14 # be repeated in the block-closing comment as well. Here is an
15 # example of a program fully augmented with block-closing comments:
29 # Note that only the last part of an if...elif...else... block needs a
30 # block-closing comment; the same is true for other compound
31 # statements (e.g. try...except). Also note that "short-form" blocks
32 # like the second 'if' in the example must be closed as well;
33 # otherwise the 'else' in the example would be ambiguous (remember
34 # that indentation is not significant when interpreting block-closing
37 # Both operations are idempotent (i.e. applied to their own output
38 # they yield an identical result). Running first "pindent -c" and
39 # then "pindent -r" on a valid Python program produces a program that
40 # is semantically identical to the input (though its indentation may
44 # -s stepsize: set the indentation step size (default 8)
45 # -t tabsize : set the number of spaces a tab character is worth (default 8)
46 # file ... : input file(s) (default standard input)
47 # The results always go to standard output
50 # - comments ending in a backslash will be mistaken for continued lines
51 # - continuations using backslash are always left unchanged
52 # - continuations inside parentheses are not extra indented by -r
53 # but must be indented for -c to work correctly (this breaks
55 # - continued lines inside triple-quoted strings are totally garbled
58 # - On input, a block may also be closed with an "end statement" --
59 # this is a block-closing comment without the '#' sign.
61 # Possible improvements:
62 # - check syntax based on transitions in 'next' table
63 # - better error reporting
64 # - better error recovery
65 # - check identifier after class/def
67 # The following wishes need a more complete tokenization of the source:
68 # - Don't get fooled by comments ending in backslash
69 # - reindent continuation lines indicated by backslash
70 # - handle continuation lines inside parentheses/braces/brackets
71 # - handle triple quoted strings spanning lines
73 # - optionally do much more thorough reformatting, a la C indent
85 next
['if'] = next
['elif'] = 'elif', 'else', 'end'
86 next
['while'] = next
['for'] = 'else', 'end'
87 next
['try'] = 'except', 'finally'
88 next
['except'] = 'except', 'else', 'end'
89 next
['else'] = next
['finally'] = next
['def'] = next
['class'] = 'end'
91 start
= 'if', 'while', 'for', 'try', 'def', 'class'
95 def __init__(self
, fpi
= sys
.stdin
, fpo
= sys
.stdout
,
96 indentsize
= STEPSIZE
, tabsize
= TABSIZE
):
99 self
.indentsize
= indentsize
100 self
.tabsize
= tabsize
102 self
.write
= fpo
.write
103 self
.kwprog
= re
.compile(
104 r
'^\s*(?P<kw>[a-z]+)'
105 r
'(\s+(?P<id>[a-zA-Z_]\w*))?'
107 self
.endprog
= re
.compile(
108 r
'^\s*#?\s*end\s+(?P<kw>[a-z]+)'
109 r
'(\s+(?P<id>[a-zA-Z_]\w*))?'
111 self
.wsprog
= re
.compile(r
'^[ \t]*')
115 line
= self
.fpi
.readline()
116 if line
: self
.lineno
= self
.lineno
+ 1
121 def error(self
, fmt
, *args
):
122 if args
: fmt
= fmt
% args
124 sys
.stderr
.write('Error at line %d: %s\n' % (self
.lineno
, fmt
))
125 self
.write('### %s ###\n' % fmt
)
129 line
= self
.readline()
130 while line
[-2:] == '\\\n':
131 line2
= self
.readline()
139 def putline(self
, line
, indent
= None):
144 tabs
, spaces
= divmod(indent
*self
.indentsize
, self
.tabsize
)
146 m
= self
.wsprog
.match(line
)
149 self
.write('\t'*tabs
+ ' '*spaces
+ line
[i
:])
155 line
= self
.getline()
156 if not line
: break # EOF
158 m
= self
.endprog
.match(line
)
163 self
.error('unexpected end')
164 elif stack
[-1][0] != kw2
:
165 self
.error('unmatched end')
168 self
.putline(line
, len(stack
))
171 m
= self
.kwprog
.match(line
)
175 self
.putline(line
, len(stack
))
176 stack
.append((kw
, kw
))
179 if next
.has_key(kw
) and stack
:
180 self
.putline(line
, len(stack
)-1)
186 self
.putline(line
, len(stack
))
189 self
.error('unterminated keywords')
190 for kwa
, kwb
in stack
:
191 self
.write('\t%s\n' % kwa
)
200 current
, firstkw
, lastkw
, topid
= 0, '', '', ''
202 line
= self
.getline()
204 m
= self
.wsprog
.match(line
)
207 m
= self
.endprog
.match(line
)
210 endkw
= m
.group('kw')
211 thisid
= m
.group('id')
213 m
= self
.kwprog
.match(line
)
215 thiskw
= m
.group('kw')
216 if not next
.has_key(thiskw
):
219 if thiskw
in ('def', 'class'):
220 thisid
= m
.group('id')
224 elif line
[i
:i
+1] in ('\n', '#'):
231 indent
= len(string
.expandtabs(line
[:i
], self
.tabsize
))
232 while indent
< current
:
235 s
= '# end %s %s\n' % (
238 s
= '# end %s\n' % firstkw
240 self
.putline(s
, current
)
241 firstkw
= lastkw
= ''
243 current
, firstkw
, lastkw
, topid
= stack
[-1]
246 if indent
== current
and firstkw
:
249 self
.error('mismatched end')
251 firstkw
= lastkw
= ''
252 elif not thiskw
or thiskw
in start
:
254 s
= '# end %s %s\n' % (
257 s
= '# end %s\n' % firstkw
259 self
.putline(s
, current
)
260 firstkw
= lastkw
= topid
= ''
264 stack
.append((current
, firstkw
, lastkw
, topid
))
265 if thiskw
and thiskw
not in start
:
269 current
, firstkw
, lastkw
, topid
= \
270 indent
, thiskw
, thiskw
, thisid
274 firstkw
= lastkw
= thiskw
280 for l
in todo
: self
.write(l
)
289 # end class PythonIndenter
291 # Simplified user interface
292 # - xxx_filter(input, output): read and write file objects
293 # - xxx_string(s): take and return string object
294 # - xxx_file(filename): process file in place, return true iff changed
296 def complete_filter(input= sys
.stdin
, output
= sys
.stdout
,
297 stepsize
= STEPSIZE
, tabsize
= TABSIZE
):
298 pi
= PythonIndenter(input, output
, stepsize
, tabsize
)
300 # end def complete_filter
302 def reformat_filter(input = sys
.stdin
, output
= sys
.stdout
,
303 stepsize
= STEPSIZE
, tabsize
= TABSIZE
):
304 pi
= PythonIndenter(input, output
, stepsize
, tabsize
)
309 def __init__(self
, buf
):
312 self
.len = len(self
.buf
)
314 def read(self
, n
= 0):
316 n
= self
.len - self
.pos
318 n
= min(n
, self
.len - self
.pos
)
320 r
= self
.buf
[self
.pos
: self
.pos
+ n
]
321 self
.pos
= self
.pos
+ n
325 i
= string
.find(self
.buf
, '\n', self
.pos
)
326 return self
.read(i
+ 1 - self
.pos
)
330 line
= self
.readline()
333 line
= self
.readline()
337 # seek/tell etc. are left as an exercise for the reader
338 # end class StringReader
345 self
.buf
= self
.buf
+ s
350 # end class StringWriter
352 def complete_string(source
, stepsize
= STEPSIZE
, tabsize
= TABSIZE
):
353 input = StringReader(source
)
354 output
= StringWriter()
355 pi
= PythonIndenter(input, output
, stepsize
, tabsize
)
357 return output
.getvalue()
358 # end def complete_string
360 def reformat_string(source
, stepsize
= STEPSIZE
, tabsize
= TABSIZE
):
361 input = StringReader(source
)
362 output
= StringWriter()
363 pi
= PythonIndenter(input, output
, stepsize
, tabsize
)
365 return output
.getvalue()
366 # end def reformat_string
368 def complete_file(filename
, stepsize
= STEPSIZE
, tabsize
= TABSIZE
):
369 source
= open(filename
, 'r').read()
370 result
= complete_string(source
, stepsize
, tabsize
)
371 if source
== result
: return 0
374 try: os
.rename(filename
, filename
+ '~')
375 except os
.error
: pass
377 f
= open(filename
, 'w')
381 # end def complete_file
383 def reformat_file(filename
, stepsize
= STEPSIZE
, tabsize
= TABSIZE
):
384 source
= open(filename
, 'r').read()
385 result
= reformat_string(source
, stepsize
, tabsize
)
386 if source
== result
: return 0
389 os
.rename(filename
, filename
+ '~')
390 f
= open(filename
, 'w')
394 # end def reformat_file
396 # Test program when called as a script
399 usage: pindent (-c|-r) [-s stepsize] [-t tabsize] [file] ...
400 -c : complete a correctly indented program (add #end directives)
401 -r : reformat a completed program (use #end directives)
402 -s stepsize: indentation step (default %(STEPSIZE)d)
403 -t tabsize : the worth in spaces of a tab (default %(TABSIZE)d)
404 [file] ... : files are changed in place, with backups in file~
405 If no files are specified or a single - is given,
406 the program acts as a filter (reads stdin, writes stdout).
412 opts
, args
= getopt
.getopt(sys
.argv
[1:], 'crs:t:')
413 except getopt
.error
, msg
:
414 sys
.stderr
.write('Error: %s\n' % msg
)
415 sys
.stderr
.write(usage
)
427 stepsize
= string
.atoi(a
)
429 tabsize
= string
.atoi(a
)
434 'You must specify -c(omplete) or -r(eformat)\n')
435 sys
.stderr
.write(usage
)
438 if not args
or args
== ['-']:
439 action
= eval(action
+ '_filter')
440 action(sys
.stdin
, sys
.stdout
, stepsize
, tabsize
)
442 action
= eval(action
+ '_file')
444 action(file, stepsize
, tabsize
)
449 if __name__
== '__main__':