blob: 1c27b131748d2eaa70929bc4bc5800aaaff94dd8 [file] [log] [blame]
Guido van Rossumf06ee5f1996-11-27 19:52:01 +00001#! /usr/bin/env python
Guido van Rossum1d28e171994-05-15 18:14:33 +00002
Guido van Rossum59811b12000-06-28 22:47:22 +00003# This file contains a class and a main program that perform three
Guido van Rossum1d28e171994-05-15 18:14:33 +00004# related (though complimentary) formatting operations on Python
Guido van Rossum59811b12000-06-28 22:47:22 +00005# programs. When called as "pindent -c", it takes a valid Python
Guido van Rossum1d28e171994-05-15 18:14:33 +00006# program as input and outputs a version augmented with block-closing
Guido van Rossum59811b12000-06-28 22:47:22 +00007# comments. When called as "pindent -e", 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
Guido van Rossum1d28e171994-05-15 18:14:33 +000010# Python program with block-closing comments but with its indentation
11# messed up, and outputs a properly indented version.
12
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:
18
19# def foobar(a, b):
20# if a == b:
21# a = a+1
22# elif a < b:
23# b = b-1
24# if b > a: a = a-1
25# # end if
26# else:
27# print 'oops!'
28# # end if
29# # end def foobar
30
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
37# comments).
38
Guido van Rossum59811b12000-06-28 22:47:22 +000039# The operations are idempotent (i.e. applied to their own output
Guido van Rossum1d28e171994-05-15 18:14:33 +000040# 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
Guido van Rossum59811b12000-06-28 22:47:22 +000043# be different). Running "pindent -e" on that output produces a
44# program that only differs from the original in indentation.
Guido van Rossum1d28e171994-05-15 18:14:33 +000045
46# Other options:
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# file ... : input file(s) (default standard input)
50# The results always go to standard output
51
52# Caveats:
53# - comments ending in a backslash will be mistaken for continued lines
54# - continuations using backslash are always left unchanged
55# - continuations inside parentheses are not extra indented by -r
56# but must be indented for -c to work correctly (this breaks
57# idempotency!)
58# - continued lines inside triple-quoted strings are totally garbled
59
60# Secret feature:
61# - On input, a block may also be closed with an "end statement" --
62# this is a block-closing comment without the '#' sign.
63
64# Possible improvements:
65# - check syntax based on transitions in 'next' table
66# - better error reporting
67# - better error recovery
68# - check identifier after class/def
69
70# The following wishes need a more complete tokenization of the source:
71# - Don't get fooled by comments ending in backslash
72# - reindent continuation lines indicated by backslash
73# - handle continuation lines inside parentheses/braces/brackets
74# - handle triple quoted strings spanning lines
75# - realign comments
76# - optionally do much more thorough reformatting, a la C indent
77
Guido van Rossum0038cd91994-06-07 22:19:41 +000078# Defaults
79STEPSIZE = 8
80TABSIZE = 8
81
Guido van Rossum1d28e171994-05-15 18:14:33 +000082import os
Guido van Rossumf57736e1998-06-19 21:39:27 +000083import re
Guido van Rossum1d28e171994-05-15 18:14:33 +000084import string
85import sys
86
87next = {}
88next['if'] = next['elif'] = 'elif', 'else', 'end'
89next['while'] = next['for'] = 'else', 'end'
90next['try'] = 'except', 'finally'
91next['except'] = 'except', 'else', 'end'
92next['else'] = next['finally'] = next['def'] = next['class'] = 'end'
93next['end'] = ()
94start = 'if', 'while', 'for', 'try', 'def', 'class'
95
96class PythonIndenter:
97
98 def __init__(self, fpi = sys.stdin, fpo = sys.stdout,
Guido van Rossum0038cd91994-06-07 22:19:41 +000099 indentsize = STEPSIZE, tabsize = TABSIZE):
Guido van Rossum1d28e171994-05-15 18:14:33 +0000100 self.fpi = fpi
101 self.fpo = fpo
102 self.indentsize = indentsize
103 self.tabsize = tabsize
104 self.lineno = 0
105 self.write = fpo.write
Guido van Rossumf57736e1998-06-19 21:39:27 +0000106 self.kwprog = re.compile(
107 r'^\s*(?P<kw>[a-z]+)'
108 r'(\s+(?P<id>[a-zA-Z_]\w*))?'
109 r'[^\w]')
110 self.endprog = re.compile(
111 r'^\s*#?\s*end\s+(?P<kw>[a-z]+)'
112 r'(\s+(?P<id>[a-zA-Z_]\w*))?'
113 r'[^\w]')
114 self.wsprog = re.compile(r'^[ \t]*')
Guido van Rossum1d28e171994-05-15 18:14:33 +0000115 # end def __init__
116
117 def readline(self):
118 line = self.fpi.readline()
119 if line: self.lineno = self.lineno + 1
120 # end if
121 return line
122 # end def readline
123
124 def error(self, fmt, *args):
125 if args: fmt = fmt % args
126 # end if
127 sys.stderr.write('Error at line %d: %s\n' % (self.lineno, fmt))
128 self.write('### %s ###\n' % fmt)
129 # end def error
130
131 def getline(self):
132 line = self.readline()
133 while line[-2:] == '\\\n':
134 line2 = self.readline()
135 if not line2: break
136 # end if
137 line = line + line2
138 # end while
139 return line
140 # end def getline
141
142 def putline(self, line, indent = None):
143 if indent is None:
144 self.write(line)
145 return
146 # end if
147 tabs, spaces = divmod(indent*self.indentsize, self.tabsize)
Guido van Rossumf57736e1998-06-19 21:39:27 +0000148 i = 0
149 m = self.wsprog.match(line)
150 if m: i = m.end()
151 # end if
Guido van Rossum1d28e171994-05-15 18:14:33 +0000152 self.write('\t'*tabs + ' '*spaces + line[i:])
153 # end def putline
154
155 def reformat(self):
156 stack = []
157 while 1:
158 line = self.getline()
159 if not line: break # EOF
160 # end if
Guido van Rossumf57736e1998-06-19 21:39:27 +0000161 m = self.endprog.match(line)
162 if m:
Guido van Rossum1d28e171994-05-15 18:14:33 +0000163 kw = 'end'
Guido van Rossumf57736e1998-06-19 21:39:27 +0000164 kw2 = m.group('kw')
Guido van Rossum1d28e171994-05-15 18:14:33 +0000165 if not stack:
166 self.error('unexpected end')
167 elif stack[-1][0] != kw2:
168 self.error('unmatched end')
169 # end if
170 del stack[-1:]
171 self.putline(line, len(stack))
172 continue
173 # end if
Guido van Rossumf57736e1998-06-19 21:39:27 +0000174 m = self.kwprog.match(line)
175 if m:
176 kw = m.group('kw')
Guido van Rossum1d28e171994-05-15 18:14:33 +0000177 if kw in start:
178 self.putline(line, len(stack))
179 stack.append((kw, kw))
180 continue
181 # end if
182 if next.has_key(kw) and stack:
183 self.putline(line, len(stack)-1)
184 kwa, kwb = stack[-1]
185 stack[-1] = kwa, kw
186 continue
187 # end if
188 # end if
189 self.putline(line, len(stack))
190 # end while
191 if stack:
192 self.error('unterminated keywords')
193 for kwa, kwb in stack:
194 self.write('\t%s\n' % kwa)
195 # end for
196 # end if
197 # end def reformat
198
Guido van Rossum59811b12000-06-28 22:47:22 +0000199 def eliminate(self):
200 begin_counter = 0
201 end_counter = 0
202 while 1:
203 line = self.getline()
204 if not line: break # EOF
205 # end if
206 m = self.endprog.match(line)
207 if m:
208 end_counter = end_counter + 1
209 continue
210 # end if
211 m = self.kwprog.match(line)
212 if m:
213 kw = m.group('kw')
214 if kw in start:
215 begin_counter = begin_counter + 1
216 # end if
217 # end if
218 self.putline(line)
219 # end while
220 if begin_counter - end_counter < 0:
221 sys.stderr.write('Warning: input contained more end tags than expected\n')
222 elif begin_counter - end_counter > 0:
223 sys.stderr.write('Warning: input contained less end tags than expected\n')
224 # end if
225 # end def eliminate
226
Guido van Rossum1d28e171994-05-15 18:14:33 +0000227 def complete(self):
228 self.indentsize = 1
229 stack = []
230 todo = []
231 current, firstkw, lastkw, topid = 0, '', '', ''
232 while 1:
233 line = self.getline()
Guido van Rossumf57736e1998-06-19 21:39:27 +0000234 i = 0
235 m = self.wsprog.match(line)
236 if m: i = m.end()
237 # end if
238 m = self.endprog.match(line)
239 if m:
Guido van Rossum1d28e171994-05-15 18:14:33 +0000240 thiskw = 'end'
Guido van Rossumf57736e1998-06-19 21:39:27 +0000241 endkw = m.group('kw')
242 thisid = m.group('id')
243 else:
244 m = self.kwprog.match(line)
245 if m:
246 thiskw = m.group('kw')
247 if not next.has_key(thiskw):
248 thiskw = ''
249 # end if
250 if thiskw in ('def', 'class'):
251 thisid = m.group('id')
252 else:
253 thisid = ''
254 # end if
255 elif line[i:i+1] in ('\n', '#'):
256 todo.append(line)
257 continue
258 else:
Guido van Rossum1d28e171994-05-15 18:14:33 +0000259 thiskw = ''
260 # end if
Guido van Rossum1d28e171994-05-15 18:14:33 +0000261 # end if
262 indent = len(string.expandtabs(line[:i], self.tabsize))
263 while indent < current:
264 if firstkw:
265 if topid:
266 s = '# end %s %s\n' % (
267 firstkw, topid)
268 else:
269 s = '# end %s\n' % firstkw
270 # end if
271 self.putline(s, current)
272 firstkw = lastkw = ''
273 # end if
274 current, firstkw, lastkw, topid = stack[-1]
275 del stack[-1]
276 # end while
277 if indent == current and firstkw:
278 if thiskw == 'end':
279 if endkw != firstkw:
280 self.error('mismatched end')
281 # end if
282 firstkw = lastkw = ''
283 elif not thiskw or thiskw in start:
284 if topid:
285 s = '# end %s %s\n' % (
286 firstkw, topid)
287 else:
288 s = '# end %s\n' % firstkw
289 # end if
290 self.putline(s, current)
291 firstkw = lastkw = topid = ''
292 # end if
293 # end if
294 if indent > current:
Guido van Rossumf57736e1998-06-19 21:39:27 +0000295 stack.append((current, firstkw, lastkw, topid))
Guido van Rossum1d28e171994-05-15 18:14:33 +0000296 if thiskw and thiskw not in start:
297 # error
298 thiskw = ''
299 # end if
300 current, firstkw, lastkw, topid = \
301 indent, thiskw, thiskw, thisid
302 # end if
303 if thiskw:
304 if thiskw in start:
305 firstkw = lastkw = thiskw
306 topid = thisid
307 else:
308 lastkw = thiskw
309 # end if
310 # end if
311 for l in todo: self.write(l)
312 # end for
313 todo = []
314 if not line: break
315 # end if
316 self.write(line)
317 # end while
318 # end def complete
319
320# end class PythonIndenter
321
Guido van Rossum0038cd91994-06-07 22:19:41 +0000322# Simplified user interface
323# - xxx_filter(input, output): read and write file objects
324# - xxx_string(s): take and return string object
325# - xxx_file(filename): process file in place, return true iff changed
326
Guido van Rossum59811b12000-06-28 22:47:22 +0000327def complete_filter(input = sys.stdin, output = sys.stdout,
Guido van Rossum0038cd91994-06-07 22:19:41 +0000328 stepsize = STEPSIZE, tabsize = TABSIZE):
329 pi = PythonIndenter(input, output, stepsize, tabsize)
330 pi.complete()
331# end def complete_filter
332
Guido van Rossum59811b12000-06-28 22:47:22 +0000333def eliminate_filter(input= sys.stdin, output = sys.stdout,
334 stepsize = STEPSIZE, tabsize = TABSIZE):
335 pi = PythonIndenter(input, output, stepsize, tabsize)
336 pi.eliminate()
337# end def eliminate_filter
338
Guido van Rossum0038cd91994-06-07 22:19:41 +0000339def reformat_filter(input = sys.stdin, output = sys.stdout,
340 stepsize = STEPSIZE, tabsize = TABSIZE):
341 pi = PythonIndenter(input, output, stepsize, tabsize)
342 pi.reformat()
Guido van Rossuma04ff0f2000-06-28 22:55:20 +0000343# end def reformat_filter
Guido van Rossum0038cd91994-06-07 22:19:41 +0000344
345class StringReader:
346 def __init__(self, buf):
347 self.buf = buf
348 self.pos = 0
349 self.len = len(self.buf)
350 # end def __init__
351 def read(self, n = 0):
352 if n <= 0:
353 n = self.len - self.pos
354 else:
355 n = min(n, self.len - self.pos)
356 # end if
357 r = self.buf[self.pos : self.pos + n]
358 self.pos = self.pos + n
359 return r
360 # end def read
361 def readline(self):
362 i = string.find(self.buf, '\n', self.pos)
363 return self.read(i + 1 - self.pos)
364 # end def readline
365 def readlines(self):
366 lines = []
367 line = self.readline()
368 while line:
369 lines.append(line)
370 line = self.readline()
371 # end while
372 return lines
373 # end def readlines
374 # seek/tell etc. are left as an exercise for the reader
375# end class StringReader
376
377class StringWriter:
378 def __init__(self):
379 self.buf = ''
380 # end def __init__
381 def write(self, s):
382 self.buf = self.buf + s
383 # end def write
384 def getvalue(self):
385 return self.buf
386 # end def getvalue
387# end class StringWriter
388
389def complete_string(source, stepsize = STEPSIZE, tabsize = TABSIZE):
390 input = StringReader(source)
391 output = StringWriter()
392 pi = PythonIndenter(input, output, stepsize, tabsize)
393 pi.complete()
394 return output.getvalue()
395# end def complete_string
396
Guido van Rossum59811b12000-06-28 22:47:22 +0000397def eliminate_string(source, stepsize = STEPSIZE, tabsize = TABSIZE):
398 input = StringReader(source)
399 output = StringWriter()
400 pi = PythonIndenter(input, output, stepsize, tabsize)
401 pi.eliminate()
402 return output.getvalue()
403# end def eliminate_string
404
Guido van Rossum0038cd91994-06-07 22:19:41 +0000405def reformat_string(source, stepsize = STEPSIZE, tabsize = TABSIZE):
406 input = StringReader(source)
407 output = StringWriter()
408 pi = PythonIndenter(input, output, stepsize, tabsize)
409 pi.reformat()
410 return output.getvalue()
411# end def reformat_string
412
413def complete_file(filename, stepsize = STEPSIZE, tabsize = TABSIZE):
414 source = open(filename, 'r').read()
415 result = complete_string(source, stepsize, tabsize)
416 if source == result: return 0
417 # end if
418 import os
419 try: os.rename(filename, filename + '~')
420 except os.error: pass
421 # end try
422 f = open(filename, 'w')
423 f.write(result)
424 f.close()
425 return 1
426# end def complete_file
427
Guido van Rossum59811b12000-06-28 22:47:22 +0000428def eliminate_file(filename, stepsize = STEPSIZE, tabsize = TABSIZE):
429 source = open(filename, 'r').read()
430 result = eliminate_string(source, stepsize, tabsize)
431 if source == result: return 0
432 # end if
433 import os
434 try: os.rename(filename, filename + '~')
435 except os.error: pass
436 # end try
437 f = open(filename, 'w')
438 f.write(result)
439 f.close()
440 return 1
441# end def eliminate_file
442
Guido van Rossum0038cd91994-06-07 22:19:41 +0000443def reformat_file(filename, stepsize = STEPSIZE, tabsize = TABSIZE):
444 source = open(filename, 'r').read()
445 result = reformat_string(source, stepsize, tabsize)
446 if source == result: return 0
447 # end if
448 import os
Guido van Rossum59811b12000-06-28 22:47:22 +0000449 try: os.rename(filename, filename + '~')
450 except os.error: pass
451 # end try
Guido van Rossum0038cd91994-06-07 22:19:41 +0000452 f = open(filename, 'w')
453 f.write(result)
454 f.close()
455 return 1
456# end def reformat_file
457
458# Test program when called as a script
459
460usage = """
Guido van Rossum59811b12000-06-28 22:47:22 +0000461usage: pindent (-c|-e|-r) [-s stepsize] [-t tabsize] [file] ...
Guido van Rossum0038cd91994-06-07 22:19:41 +0000462-c : complete a correctly indented program (add #end directives)
Guido van Rossum59811b12000-06-28 22:47:22 +0000463-e : eliminate #end directives
Guido van Rossum0038cd91994-06-07 22:19:41 +0000464-r : reformat a completed program (use #end directives)
465-s stepsize: indentation step (default %(STEPSIZE)d)
466-t tabsize : the worth in spaces of a tab (default %(TABSIZE)d)
467[file] ... : files are changed in place, with backups in file~
468If no files are specified or a single - is given,
469the program acts as a filter (reads stdin, writes stdout).
470""" % vars()
471
Guido van Rossum1d28e171994-05-15 18:14:33 +0000472def test():
473 import getopt
Guido van Rossum0038cd91994-06-07 22:19:41 +0000474 try:
Guido van Rossum59811b12000-06-28 22:47:22 +0000475 opts, args = getopt.getopt(sys.argv[1:], 'cers:t:')
Guido van Rossum0038cd91994-06-07 22:19:41 +0000476 except getopt.error, msg:
477 sys.stderr.write('Error: %s\n' % msg)
478 sys.stderr.write(usage)
479 sys.exit(2)
480 # end try
Guido van Rossum1d28e171994-05-15 18:14:33 +0000481 action = None
Guido van Rossum0038cd91994-06-07 22:19:41 +0000482 stepsize = STEPSIZE
483 tabsize = TABSIZE
Guido van Rossum1d28e171994-05-15 18:14:33 +0000484 for o, a in opts:
485 if o == '-c':
Guido van Rossum0038cd91994-06-07 22:19:41 +0000486 action = 'complete'
Guido van Rossum59811b12000-06-28 22:47:22 +0000487 elif o == '-e':
488 action = 'eliminate'
Guido van Rossum1d28e171994-05-15 18:14:33 +0000489 elif o == '-r':
Guido van Rossum0038cd91994-06-07 22:19:41 +0000490 action = 'reformat'
Guido van Rossum3962fdb1994-05-27 14:13:46 +0000491 elif o == '-s':
Guido van Rossum1d28e171994-05-15 18:14:33 +0000492 stepsize = string.atoi(a)
Guido van Rossum3962fdb1994-05-27 14:13:46 +0000493 elif o == '-t':
Guido van Rossum1d28e171994-05-15 18:14:33 +0000494 tabsize = string.atoi(a)
495 # end if
496 # end for
497 if not action:
Guido van Rossum0038cd91994-06-07 22:19:41 +0000498 sys.stderr.write(
Guido van Rossum59811b12000-06-28 22:47:22 +0000499 'You must specify -c(omplete), -e(eliminate) or -r(eformat)\n')
Guido van Rossum0038cd91994-06-07 22:19:41 +0000500 sys.stderr.write(usage)
Guido van Rossum1d28e171994-05-15 18:14:33 +0000501 sys.exit(2)
502 # end if
Guido van Rossum0038cd91994-06-07 22:19:41 +0000503 if not args or args == ['-']:
504 action = eval(action + '_filter')
505 action(sys.stdin, sys.stdout, stepsize, tabsize)
506 else:
507 action = eval(action + '_file')
508 for file in args:
509 action(file, stepsize, tabsize)
510 # end for
Guido van Rossum1d28e171994-05-15 18:14:33 +0000511 # end if
Guido van Rossum1d28e171994-05-15 18:14:33 +0000512# end def test
513
514if __name__ == '__main__':
515 test()
516# end if