blob: 1845ed8286ffc29c0a08124788310ab5fab5e06e [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
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.
10
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:
16
17# def foobar(a, b):
18# if a == b:
19# a = a+1
20# elif a < b:
21# b = b-1
22# if b > a: a = a-1
23# # end if
24# else:
25# print 'oops!'
26# # end if
27# # end def foobar
28
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
35# comments).
36
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
41# be different).
42
43# Other options:
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
48
49# Caveats:
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
54# idempotency!)
55# - continued lines inside triple-quoted strings are totally garbled
56
57# Secret feature:
58# - On input, a block may also be closed with an "end statement" --
59# this is a block-closing comment without the '#' sign.
60
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
66
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
72# - realign comments
73# - optionally do much more thorough reformatting, a la C indent
74
Guido van Rossum0038cd91994-06-07 22:19:41 +000075# Defaults
76STEPSIZE = 8
77TABSIZE = 8
78
Guido van Rossum1d28e171994-05-15 18:14:33 +000079import os
80import regex
81import string
82import sys
83
84next = {}
85next['if'] = next['elif'] = 'elif', 'else', 'end'
86next['while'] = next['for'] = 'else', 'end'
87next['try'] = 'except', 'finally'
88next['except'] = 'except', 'else', 'end'
89next['else'] = next['finally'] = next['def'] = next['class'] = 'end'
90next['end'] = ()
91start = 'if', 'while', 'for', 'try', 'def', 'class'
92
93class PythonIndenter:
94
95 def __init__(self, fpi = sys.stdin, fpo = sys.stdout,
Guido van Rossum0038cd91994-06-07 22:19:41 +000096 indentsize = STEPSIZE, tabsize = TABSIZE):
Guido van Rossum1d28e171994-05-15 18:14:33 +000097 self.fpi = fpi
98 self.fpo = fpo
99 self.indentsize = indentsize
100 self.tabsize = tabsize
101 self.lineno = 0
102 self.write = fpo.write
103 self.kwprog = regex.symcomp(
104 '^[ \t]*\(<kw>[a-z]+\)'
105 '\([ \t]+\(<id>[a-zA-Z_][a-zA-Z0-9_]*\)\)?'
106 '[^a-zA-Z0-9_]')
107 self.endprog = regex.symcomp(
108 '^[ \t]*#?[ \t]*end[ \t]+\(<kw>[a-z]+\)'
109 '\([ \t]+\(<id>[a-zA-Z_][a-zA-Z0-9_]*\)\)?'
110 '[^a-zA-Z0-9_]')
111 self.wsprog = regex.compile('^[ \t]*')
112 # end def __init__
113
114 def readline(self):
115 line = self.fpi.readline()
116 if line: self.lineno = self.lineno + 1
117 # end if
118 return line
119 # end def readline
120
121 def error(self, fmt, *args):
122 if args: fmt = fmt % args
123 # end if
124 sys.stderr.write('Error at line %d: %s\n' % (self.lineno, fmt))
125 self.write('### %s ###\n' % fmt)
126 # end def error
127
128 def getline(self):
129 line = self.readline()
130 while line[-2:] == '\\\n':
131 line2 = self.readline()
132 if not line2: break
133 # end if
134 line = line + line2
135 # end while
136 return line
137 # end def getline
138
139 def putline(self, line, indent = None):
140 if indent is None:
141 self.write(line)
142 return
143 # end if
144 tabs, spaces = divmod(indent*self.indentsize, self.tabsize)
145 i = max(0, self.wsprog.match(line))
146 self.write('\t'*tabs + ' '*spaces + line[i:])
147 # end def putline
148
149 def reformat(self):
150 stack = []
151 while 1:
152 line = self.getline()
153 if not line: break # EOF
154 # end if
155 if self.endprog.match(line) >= 0:
156 kw = 'end'
157 kw2 = self.endprog.group('kw')
158 if not stack:
159 self.error('unexpected end')
160 elif stack[-1][0] != kw2:
161 self.error('unmatched end')
162 # end if
163 del stack[-1:]
164 self.putline(line, len(stack))
165 continue
166 # end if
167 if self.kwprog.match(line) >= 0:
168 kw = self.kwprog.group('kw')
169 if kw in start:
170 self.putline(line, len(stack))
171 stack.append((kw, kw))
172 continue
173 # end if
174 if next.has_key(kw) and stack:
175 self.putline(line, len(stack)-1)
176 kwa, kwb = stack[-1]
177 stack[-1] = kwa, kw
178 continue
179 # end if
180 # end if
181 self.putline(line, len(stack))
182 # end while
183 if stack:
184 self.error('unterminated keywords')
185 for kwa, kwb in stack:
186 self.write('\t%s\n' % kwa)
187 # end for
188 # end if
189 # end def reformat
190
191 def complete(self):
192 self.indentsize = 1
193 stack = []
194 todo = []
195 current, firstkw, lastkw, topid = 0, '', '', ''
196 while 1:
197 line = self.getline()
198 i = max(0, self.wsprog.match(line))
199 if self.endprog.match(line) >= 0:
200 thiskw = 'end'
201 endkw = self.endprog.group('kw')
202 thisid = self.endprog.group('id')
203 elif self.kwprog.match(line) >= 0:
204 thiskw = self.kwprog.group('kw')
205 if not next.has_key(thiskw):
206 thiskw = ''
207 # end if
208 if thiskw in ('def', 'class'):
209 thisid = self.kwprog.group('id')
210 else:
211 thisid = ''
212 # end if
213 elif line[i:i+1] in ('\n', '#'):
214 todo.append(line)
215 continue
216 else:
217 thiskw = ''
218 # end if
219 indent = len(string.expandtabs(line[:i], self.tabsize))
220 while indent < current:
221 if firstkw:
222 if topid:
223 s = '# end %s %s\n' % (
224 firstkw, topid)
225 else:
226 s = '# end %s\n' % firstkw
227 # end if
228 self.putline(s, current)
229 firstkw = lastkw = ''
230 # end if
231 current, firstkw, lastkw, topid = stack[-1]
232 del stack[-1]
233 # end while
234 if indent == current and firstkw:
235 if thiskw == 'end':
236 if endkw != firstkw:
237 self.error('mismatched end')
238 # end if
239 firstkw = lastkw = ''
240 elif not thiskw or thiskw in start:
241 if topid:
242 s = '# end %s %s\n' % (
243 firstkw, topid)
244 else:
245 s = '# end %s\n' % firstkw
246 # end if
247 self.putline(s, current)
248 firstkw = lastkw = topid = ''
249 # end if
250 # end if
251 if indent > current:
252 stack.append(current, firstkw, lastkw, topid)
253 if thiskw and thiskw not in start:
254 # error
255 thiskw = ''
256 # end if
257 current, firstkw, lastkw, topid = \
258 indent, thiskw, thiskw, thisid
259 # end if
260 if thiskw:
261 if thiskw in start:
262 firstkw = lastkw = thiskw
263 topid = thisid
264 else:
265 lastkw = thiskw
266 # end if
267 # end if
268 for l in todo: self.write(l)
269 # end for
270 todo = []
271 if not line: break
272 # end if
273 self.write(line)
274 # end while
275 # end def complete
276
277# end class PythonIndenter
278
Guido van Rossum0038cd91994-06-07 22:19:41 +0000279# Simplified user interface
280# - xxx_filter(input, output): read and write file objects
281# - xxx_string(s): take and return string object
282# - xxx_file(filename): process file in place, return true iff changed
283
284def complete_filter(input= sys.stdin, output = sys.stdout,
285 stepsize = STEPSIZE, tabsize = TABSIZE):
286 pi = PythonIndenter(input, output, stepsize, tabsize)
287 pi.complete()
288# end def complete_filter
289
290def reformat_filter(input = sys.stdin, output = sys.stdout,
291 stepsize = STEPSIZE, tabsize = TABSIZE):
292 pi = PythonIndenter(input, output, stepsize, tabsize)
293 pi.reformat()
294# end def reformat
295
296class StringReader:
297 def __init__(self, buf):
298 self.buf = buf
299 self.pos = 0
300 self.len = len(self.buf)
301 # end def __init__
302 def read(self, n = 0):
303 if n <= 0:
304 n = self.len - self.pos
305 else:
306 n = min(n, self.len - self.pos)
307 # end if
308 r = self.buf[self.pos : self.pos + n]
309 self.pos = self.pos + n
310 return r
311 # end def read
312 def readline(self):
313 i = string.find(self.buf, '\n', self.pos)
314 return self.read(i + 1 - self.pos)
315 # end def readline
316 def readlines(self):
317 lines = []
318 line = self.readline()
319 while line:
320 lines.append(line)
321 line = self.readline()
322 # end while
323 return lines
324 # end def readlines
325 # seek/tell etc. are left as an exercise for the reader
326# end class StringReader
327
328class StringWriter:
329 def __init__(self):
330 self.buf = ''
331 # end def __init__
332 def write(self, s):
333 self.buf = self.buf + s
334 # end def write
335 def getvalue(self):
336 return self.buf
337 # end def getvalue
338# end class StringWriter
339
340def complete_string(source, stepsize = STEPSIZE, tabsize = TABSIZE):
341 input = StringReader(source)
342 output = StringWriter()
343 pi = PythonIndenter(input, output, stepsize, tabsize)
344 pi.complete()
345 return output.getvalue()
346# end def complete_string
347
348def reformat_string(source, stepsize = STEPSIZE, tabsize = TABSIZE):
349 input = StringReader(source)
350 output = StringWriter()
351 pi = PythonIndenter(input, output, stepsize, tabsize)
352 pi.reformat()
353 return output.getvalue()
354# end def reformat_string
355
356def complete_file(filename, stepsize = STEPSIZE, tabsize = TABSIZE):
357 source = open(filename, 'r').read()
358 result = complete_string(source, stepsize, tabsize)
359 if source == result: return 0
360 # end if
361 import os
362 try: os.rename(filename, filename + '~')
363 except os.error: pass
364 # end try
365 f = open(filename, 'w')
366 f.write(result)
367 f.close()
368 return 1
369# end def complete_file
370
371def reformat_file(filename, stepsize = STEPSIZE, tabsize = TABSIZE):
372 source = open(filename, 'r').read()
373 result = reformat_string(source, stepsize, tabsize)
374 if source == result: return 0
375 # end if
376 import os
377 os.rename(filename, filename + '~')
378 f = open(filename, 'w')
379 f.write(result)
380 f.close()
381 return 1
382# end def reformat_file
383
384# Test program when called as a script
385
386usage = """
387usage: pindent (-c|-r) [-s stepsize] [-t tabsize] [file] ...
388-c : complete a correctly indented program (add #end directives)
389-r : reformat a completed program (use #end directives)
390-s stepsize: indentation step (default %(STEPSIZE)d)
391-t tabsize : the worth in spaces of a tab (default %(TABSIZE)d)
392[file] ... : files are changed in place, with backups in file~
393If no files are specified or a single - is given,
394the program acts as a filter (reads stdin, writes stdout).
395""" % vars()
396
Guido van Rossum1d28e171994-05-15 18:14:33 +0000397def test():
398 import getopt
Guido van Rossum0038cd91994-06-07 22:19:41 +0000399 try:
400 opts, args = getopt.getopt(sys.argv[1:], 'crs:t:')
401 except getopt.error, msg:
402 sys.stderr.write('Error: %s\n' % msg)
403 sys.stderr.write(usage)
404 sys.exit(2)
405 # end try
Guido van Rossum1d28e171994-05-15 18:14:33 +0000406 action = None
Guido van Rossum0038cd91994-06-07 22:19:41 +0000407 stepsize = STEPSIZE
408 tabsize = TABSIZE
Guido van Rossum1d28e171994-05-15 18:14:33 +0000409 for o, a in opts:
410 if o == '-c':
Guido van Rossum0038cd91994-06-07 22:19:41 +0000411 action = 'complete'
Guido van Rossum1d28e171994-05-15 18:14:33 +0000412 elif o == '-r':
Guido van Rossum0038cd91994-06-07 22:19:41 +0000413 action = 'reformat'
Guido van Rossum3962fdb1994-05-27 14:13:46 +0000414 elif o == '-s':
Guido van Rossum1d28e171994-05-15 18:14:33 +0000415 stepsize = string.atoi(a)
Guido van Rossum3962fdb1994-05-27 14:13:46 +0000416 elif o == '-t':
Guido van Rossum1d28e171994-05-15 18:14:33 +0000417 tabsize = string.atoi(a)
418 # end if
419 # end for
420 if not action:
Guido van Rossum0038cd91994-06-07 22:19:41 +0000421 sys.stderr.write(
422 'You must specify -c(omplete) or -r(eformat)\n')
423 sys.stderr.write(usage)
Guido van Rossum1d28e171994-05-15 18:14:33 +0000424 sys.exit(2)
425 # end if
Guido van Rossum0038cd91994-06-07 22:19:41 +0000426 if not args or args == ['-']:
427 action = eval(action + '_filter')
428 action(sys.stdin, sys.stdout, stepsize, tabsize)
429 else:
430 action = eval(action + '_file')
431 for file in args:
432 action(file, stepsize, tabsize)
433 # end for
Guido van Rossum1d28e171994-05-15 18:14:33 +0000434 # end if
Guido van Rossum1d28e171994-05-15 18:14:33 +0000435# end def test
436
437if __name__ == '__main__':
438 test()
439# end if