Debian Codegraph @

texmf-dist/doc/latex/newcommand/newcommand.py

raw
1 #! /usr/bin/env python
2
3 # -----------------------------------------------------------------------
4 # Convert a macro prototype to a LaTeX \newcommand
5 # By Scott Pakin <[email protected]>
6 # -----------------------------------------------------------------------
7 # Copyright (C) 2010 Scott Pakin, [email protected]
8 #
9 # This package may be distributed and/or modified under the conditions
10 # of the LaTeX Project Public License, either version 1.3c of this
11 # license or (at your option) any later version. The latest version of
12 # this license is in:
13 #
14 # http://www.latex-project.org/lppl.txt
15 #
16 # and version 1.3c or later is part of all distributions of LaTeX version
17 # 2006/05/20 or later.
18 # -----------------------------------------------------------------------
19
20 from spark import GenericScanner, GenericParser, GenericASTTraversal
21 import re
22 import copy
23
24 class ParseError(Exception):
25 "Represent any error that occurs during processing."
26 pass
27
28
29 class Token:
30 "Represent a single lexed token."
31
32 def __init__(self, type, charOffset, attr=None):
33 self.type = type
34 self.attr = attr
35 self.charOffset = charOffset
36
37 def __cmp__(self, o):
38 return cmp(self.type, o)
39
40 def __str__(self):
41 return self.attr
42
43
44 class AST:
45 "Represent an abstract syntax tree."
46
47 def __init__(self, type, charOffset, attr=None, kids=[]):
48 self.type = type
49 self.charOffset = charOffset
50 self.attr = attr
51 self.kids = kids
52
53 def __getitem__(self, child):
54 return self.kids[child]
55
56 def __len__(self):
57 return len(self.kids)
58
59
60 class CmdScanner(GenericScanner):
61 "Defines a lexer for macro prototypes."
62
63 def __init__(self):
64 GenericScanner.__init__(self)
65 self.charOffset = 0
66
67 def tokenize(self, input):
68 self.rv = []
69 GenericScanner.tokenize(self, input)
70 return self.rv
71
72 def t_whitespace(self, whiteSpace):
73 r' [\s\r\n]+ '
74 self.charOffset = self.charOffset + len(whiteSpace)
75
76 def t_command(self, cmd):
77 r' MACRO '
78 self.rv.append(Token(type='command',
79 attr=cmd,
80 charOffset=self.charOffset))
81 self.charOffset = self.charOffset + len(cmd)
82
83 def t_argument_type(self, arg):
84 r' OPT '
85 self.rv.append(Token(type='argtype',
86 attr=arg,
87 charOffset=self.charOffset))
88 self.charOffset = self.charOffset + len(arg)
89
90 def t_argument(self, arg):
91 r' \#\d+ '
92 self.rv.append(Token(type='argument',
93 attr=arg,
94 charOffset=self.charOffset))
95 self.charOffset = self.charOffset + len(arg)
96
97 def t_equal(self, equal):
98 r' = '
99 self.rv.append(Token(type=equal,
100 attr=equal,
101 charOffset=self.charOffset))
102 self.charOffset = self.charOffset + len(equal)
103
104 def t_quoted(self, quoted):
105 r' \{[^\}]*\} '
106 self.rv.append(Token(type='quoted',
107 attr=quoted,
108 charOffset=self.charOffset))
109 self.charOffset = self.charOffset + len(quoted)
110
111 def t_identifier(self, ident):
112 r' [A-Za-z]+ '
113 self.rv.append(Token(type='ident',
114 attr=ident,
115 charOffset=self.charOffset))
116 self.charOffset = self.charOffset + len(ident)
117
118 def t_delimiter(self, delim):
119 r' [()\[\]] '
120 self.rv.append(Token(type='delim',
121 attr=delim,
122 charOffset=self.charOffset))
123 self.charOffset = self.charOffset + len(delim)
124
125 def t_other(self, other):
126 r' [^()\[\]\{\}\#\s\r\n]+ '
127 self.rv.append(Token(type='other',
128 attr=other,
129 charOffset=self.charOffset))
130 self.charOffset = self.charOffset + len(other)
131
132
133 class CmdParser(GenericParser):
134 "Defines a parser for macro prototypes."
135
136 def __init__(self, start='decl'):
137 GenericParser.__init__(self, start)
138
139 def error(self, token):
140 raise ParseError, \
141 ("Syntax error", 1+token.charOffset)
142
143 def p_optarg(self, args):
144 ' optarg ::= argtype delim defvals delim '
145 return AST(type='optarg',
146 charOffset=args[0].charOffset,
147 attr=(args[1].attr, args[3].attr),
148 kids=[args[2]])
149
150 def p_rawtext(self, args):
151 ' rawtext ::= other '
152 return AST(type='rawtext',
153 charOffset=args[0].charOffset,
154 attr=args[0].attr)
155
156 def p_defval(self, args):
157 ' defval ::= argument = quoted '
158 return AST(type='defval',
159 charOffset=args[0].charOffset,
160 attr=(args[0].attr, args[2].attr))
161
162 def p_defvals_1(self, args):
163 ' defvals ::= defval '
164 return AST(type='defvals',
165 charOffset=args[0].charOffset,
166 kids=args)
167
168 def p_defvals_2(self, args):
169 '''
170 defvals ::= defval rawtext defvals
171 defvals ::= defval ident defvals
172 defvals ::= defval quoted defvals
173 '''
174 return AST(type='defvals',
175 charOffset=args[0].charOffset,
176 attr=(args[1].type, args[1].attr, args[1].charOffset),
177 kids=[args[0],args[2]])
178
179 # Top-level macro argument
180 def p_arg_1(self, args):
181 '''
182 arg ::= quoted
183 arg ::= argument
184 '''
185 return AST(type='arg',
186 charOffset=args[0].charOffset,
187 attr=[args[0].type]+[args[0].attr])
188
189 def p_arg_2(self, args):
190 ' arg ::= optarg '
191 return AST(type='arg',
192 charOffset=args[0].charOffset,
193 attr=[args[0].type]+[args[0].attr],
194 kids=args[0].kids)
195
196 def p_arg_3(self, args):
197 ' arg ::= rawtext '
198 if args[0].attr != "*":
199 raise ParseError, \
200 ('Literal text must be quoted between "{" and "}"',
201 args[0].charOffset + 1)
202 return AST(type='arg',
203 charOffset=args[0].charOffset,
204 attr=[args[0].type]+[args[0].attr])
205
206 def p_arglist_1(self, args):
207 ' arglist ::= arg '
208 return AST(type='arglist',
209 charOffset=args[0].charOffset,
210 kids=args)
211
212 def p_arglist_2(self, args):
213 ' arglist ::= arg arglist '
214 return AST(type='arglist',
215 charOffset=args[0].charOffset,
216 kids=args)
217
218 def p_decl_1(self, args):
219 ' decl ::= command ident '
220 return AST(type='decl',
221 charOffset=args[0].charOffset,
222 attr=(args[0].attr, args[1].attr),
223 kids=[])
224
225 def p_decl_2(self, args):
226 ' decl ::= command ident arglist '
227 return AST(type='decl',
228 charOffset=args[0].charOffset,
229 attr=(args[0].attr, args[1].attr),
230 kids=[args[2]])
231
232
233 def flattenAST(ast):
234 class FlattenAST(GenericASTTraversal):
235 "Flatten an AST into a list of arguments."
236
237 def __init__(self, ast):
238 GenericASTTraversal.__init__(self, ast)
239 self.postorder()
240 self.argList = ast.argList
241
242 def n_defval(self, node):
243 node.argList = (node.attr[0], node.attr[1], node.charOffset)
244
245 def n_defvals(self, node):
246 node.argList = [node.kids[0].argList]
247 if node.attr:
248 node.argList = node.argList + [node.attr] + node.kids[1].argList
249
250 def n_arg(self, node):
251 if node.attr[0] == "optarg":
252 node.argList = node.attr + node.kids[0].argList
253 else:
254 node.argList = tuple(node.attr + [node.charOffset])
255
256 def n_arglist(self, node):
257 node.argList = [node.kids[0].argList]
258 if len(node.kids) == 2:
259 node.argList = node.argList + node.kids[1].argList
260
261 def n_decl(self, node):
262 node.argList = [(node.attr[0], node.attr[1], node.charOffset)]
263 if node.kids != []:
264 node.argList = node.argList + node.kids[0].argList
265
266 def default(self, node):
267 raise ParseError, \
268 ('Internal error -- node type "%s" was unexpected' % node.type,
269 1+node.charOffset)
270
271 return FlattenAST(ast).argList
272
273
274 def checkArgList(argList):
275 "Raise an error if any problems are detected with the given argument list."
276
277 def getFormals(sublist):
278 "Return the formal-parameter numbers in the order in which they appear."
279 if sublist == []:
280 return []
281 head = sublist[0]
282 headval = []
283 if head[0] == "argument":
284 headval = [(int(head[1][1:]), head[2])]
285 elif head[0][0] == "#":
286 headval = [(int(head[0][1:]), head[2])]
287 elif head[0] == "optarg":
288 headval = getFormals(head[2:])
289 return headval + getFormals(sublist[1:])
290
291 # Ensure the formals appear in strict increasing order.
292 formals = getFormals(argList)
293 prevformal = 0
294 for form, pos in formals:
295 if form != prevformal + 1:
296 raise ParseError, \
297 ("Expected parameter %d but saw parameter %d" % (prevformal+1, form), 1+pos)
298 prevformal = form
299
300 # Ensure that "*" appears at most once at the top level.
301 seenStar = False
302 for arg in argList:
303 if arg[0] == "rawtext" and arg[1] == "*":
304 if seenStar:
305 raise ParseError, \
306 ("Only one star parameter is allowed", arg[2])
307 seenStar = True
308
309 # Ensure that no optional argument contains more than nine formals.
310 for arg in argList:
311 if arg[0] == "optarg":
312 optFormals = 0
313 for oarg in arg[2:]:
314 if oarg[0][0] == "#":
315 optFormals += 1
316 if optFormals > 9:
317 raise ParseError, \
318 ("An optional argument can contain at most nine formals",
319 oarg[2])
320
321 # Ensure that "#" is used only where it's allowed.
322 for arg in argList:
323 if arg[0] in ["rawtext", "quoted"]:
324 hashidx = string.find(arg[1], "#")
325 if hashidx == 0 or (hashidx > 0 and arg[1][hashidx-1] != "\\"):
326 if arg[0] == "quoted":
327 hashidx += 1
328 raise ParseError, \
329 ('The "#" character cannot be used as a literal character unless escaped with "\\"',
330 arg[2] + hashidx)
331 elif arg[0] == "optarg":
332 for oarg in arg[2:]:
333 if oarg[0] in ["rawtext", "quoted"]:
334 hashidx = string.find(oarg[1], "#")
335 if hashidx == 0 or (hashidx > 0 and oarg[1][hashidx-1] != "\\"):
336 if oarg[0] == "quoted":
337 hashidx += 1
338 raise ParseError, \
339 ('The "#" character cannot be used as a literal character unless escaped with "\\"',
340 oarg[2] + hashidx)
341
342
343 class LaTeXgenerator():
344 "Generate LaTeX code from a list of arguments."
345
346 def __init__(self):
347 "Initialize all of LaTeXgenerator's instance variables."
348 self.argList = [] # List of arguments provided to generate()
349 self.topLevelName = "???" # Base macro name
350 self.haveStar = False # True=need to define \ifNAME@star
351 self.haveAt = False # True=need to use \makeatletter...\makeatother
352 self.numFormals = 0 # Total number of formal arguments
353 self.codeList = [] # List of lines of code to output
354
355 def toRoman(self, num):
356 "Convert a decimal number to roman."
357 dec2rom = [("m", 1000),
358 ("cm", 900),
359 ("d", 500),
360 ("cd", 400),
361 ("c", 100),
362 ("xc", 90),
363 ("l", 50),
364 ("xl", 40),
365 ("x", 10),
366 ("ix", 9),
367 ("v", 5),
368 ("iv", 4),
369 ("i", 1)]
370 romanStr = ""
371 if num > 4000:
372 raise ParseError, ("Too many arguments", 0)
373 for rom, dec in dec2rom:
374 while num >= dec:
375 romanStr += rom
376 num -= dec
377 return romanStr
378
379 def partitionArgList(self):
380 "Group arguments, one per macro to generate."
381 self.argGroups = []
382 argIdx = 1
383
384 # Specially handle the first group because it's limited by
385 # \newcomand's semantics.
386 group = []
387 if len(self.argList) == 1:
388 # No arguments whatsoever
389 self.argGroups.append(group)
390 return
391 arg = self.argList[argIdx]
392 if arg[0] == "optarg" and arg[1] == ("[", "]") and len(arg) == 3:
393 group.append(arg)
394 argIdx += 1
395 while len(group) < 9 and argIdx < len(self.argList) and self.argList[argIdx][0] == "argument":
396 group.append(self.argList[argIdx])
397 argIdx += 1
398 self.argGroups.append(group)
399
400 # Handle the remaining groups, each ending before an optional
401 # argument.
402 group = []
403 numFormals = 0
404 for arg in self.argList[argIdx:]:
405 if arg[0] == "rawtext":
406 # Treat "*" as an optional argument.
407 if arg[1] == "*":
408 if group != []:
409 self.argGroups.append(group)
410 group = []
411 numFormals = 0
412 group.append(arg)
413 elif arg[0] == "quoted":
414 group.append(arg)
415 elif arg[0] == "argument":
416 group.append(arg)
417 numFormals += 1
418 if numFormals == 9:
419 if group != []:
420 self.argGroups.append(group)
421 group = []
422 numFormals = 0
423 elif arg[0] == "optarg":
424 # Note that we know from checkArgList() that there are
425 # no more than 10 formals specified within the
426 # optional argument.
427 if group != []:
428 self.argGroups.append(group)
429 group = []
430 numFormals = 0
431 optarg = arg[0:2]
432 for oarg in arg[2:]:
433 if oarg[0] in ["rawtext", "quoted"]:
434 optarg.append(oarg)
435 elif oarg[0][0] == "#":
436 numFormals += 1
437 optarg.append(oarg)
438 else:
439 optarg.append(oarg)
440 group.append(optarg)
441 if group != []:
442 self.argGroups.append(group)
443
444 def argsToString(self, argList, mode, argSubtract=0):
445 '''
446 Produce a string version of a list of arguments.
447 mode is one of "define", "call", or "calldefault".
448 argSubtract is subtracted from each argument number.
449 '''
450 if mode not in ["define", "call", "calldefault"]:
451 raise ParseError, ('Internal error (mode="%s")' % mode, argList[0][2])
452 argStr = ""
453 findArgRE = re.compile('#(\d+)')
454 for arg in argList:
455 if arg[0] == "argument":
456 if mode == "define":
457 argStr += "#%d" % (int(arg[1][1:]) - argSubtract)
458 else:
459 argStr += "{#%d}" % (int(arg[1][1:]) - argSubtract)
460 elif arg[0] == "rawtext":
461 argStr += arg[1]
462 elif arg[0] == "quoted":
463 argStr += arg[1][1:-1]
464 elif arg[0] == "optarg":
465 argStr += arg[1][0]
466 for oarg in arg[2:]:
467 if oarg[0][0] == "#":
468 if mode == "define":
469 argStr += "#%d" % (int(oarg[0][1:]) - argSubtract)
470 elif mode == "call":
471 argStr += "{#%d}" % (int(oarg[0][1:]) - argSubtract)
472 else:
473 if self.numFormals > 9:
474 argStr += findArgRE.sub(lambda a: "\\"+self.topLevelName+"@arg@"+self.toRoman(int(a.group(0)[1:])),
475 oarg[1])
476 else:
477 argStr += oarg[1]
478 elif oarg[0] == "quoted":
479 argStr += oarg[1][1:-1]
480 elif oarg[0] == "rawtext":
481 argStr += oarg[1]
482 else:
483 raise ParseError, ('Internal error ("%s")' % oarg[0],
484 oarg[2])
485 argStr += arg[1][1]
486 else:
487 raise ParseError, ('Internal error ("%s")' % arg[0], arg[2])
488 return argStr
489
490 def callMacro(self, macroNum):
491 "Return an array of strings suitable for calling macro macroNum."
492 if macroNum >= len(self.argGroups):
493 # No more macros.
494 return []
495 macroName = "\\%s@%s" % (self.topLevelName, self.toRoman(macroNum))
496 nextArg = self.argGroups[macroNum][0]
497 callSeq = []
498 if self.numFormals > 9:
499 # More than nine formal parameters
500 if nextArg[0] == "optarg":
501 callSeq.append(" \\@ifnextchar%s{%s}{%s%s}%%" % \
502 (nextArg[1][0], macroName, macroName,
503 self.argsToString([nextArg], mode="calldefault")))
504 elif nextArg[0] == "rawtext" and nextArg[1] == "*":
505 callSeq.append(" \\@ifstar{\\%s@startrue%s*}{\\%s@starfalse%s*}%%" % \
506 (self.topLevelName, macroName,
507 self.topLevelName, macroName))
508 else:
509 callSeq.append(" %s" % macroName)
510 else:
511 # Nine or fewer formal parameters
512 argStr = ""
513 for g in range(0, macroNum):
514 argStr += self.argsToString(self.argGroups[g], mode="call")
515 if nextArg[0] == "optarg":
516 callSeq.append(" \\@ifnextchar%s{%s%s}{%s%s%s}%%" % \
517 (nextArg[1][0],
518 macroName, argStr, macroName, argStr,
519 self.argsToString([nextArg], mode="calldefault")))
520 elif nextArg[0] == "rawtext" and nextArg[1] == "*":
521 callSeq.append(" \\@ifstar{\\%s@startrue%s%s*}{\\%s@starfalse%s%s*}%%" % \
522 (self.topLevelName, macroName, argStr,
523 self.topLevelName, macroName, argStr))
524 else:
525 callSeq.append(" %s%s%%" % (macroName, argStr))
526 return callSeq
527
528 def putCodeHere(self):
529 'Return an array of strings representing "Put code here".'
530 code = []
531 if self.haveStar:
532 code.extend([" \\if%s@star" % self.topLevelName,
533 ' % Put code for the "*" case here.',
534 " \\else",
535 ' % Put code for the non-"*" case here.',
536 " \\fi",
537 " %% Put code common to both cases here (and/or above the \\if%s@star)." % self.topLevelName])
538 else:
539 code.append(" % Put your code here.")
540 if self.numFormals == 0:
541 return code
542 if self.numFormals > 9:
543 firstArgName = "\\%s@arg@i" % self.topLevelName
544 lastArgName = "\\%s@arg@%s" % (self.topLevelName, self.toRoman(self.numFormals))
545 else:
546 firstArgName = "#1"
547 lastArgName = "#%d" % self.numFormals
548 if self.numFormals == 1:
549 code.append(" %% You can refer to the argument as %s." % firstArgName)
550 elif self.numFormals == 2:
551 code.append(" %% You can refer to the arguments as %s and %s." % (firstArgName, lastArgName))
552 else:
553 code.append(" %% You can refer to the arguments as %s through %s." % (firstArgName, lastArgName))
554 return code
555
556 def produceTopLevel(self):
557 "Generate the code for the top-level macro definition."
558 # Generate the macro definition.
559 defStr = "\\newcommand{\\%s}" % self.topLevelName
560 argList = self.argGroups[0]
561 if argList != []:
562 defStr += "[%d]" % len(argList)
563 firstArg = argList[0]
564 if firstArg[0] == "optarg":
565 defVal = firstArg[2][1][1:-1]
566 if string.find(defVal, "]") != -1:
567 defVal = "{%s}" % defVal
568 defStr += "[%s]" % defVal
569 defStr += "{%"
570 self.codeList.append(defStr)
571
572 # Generate the macro body.
573 if len(self.argGroups) == 1:
574 # Single macro definition.
575 self.codeList.extend(self.putCodeHere())
576 else:
577 # More macros are forthcoming.
578 if self.numFormals > 9:
579 # More than nine formal parameters
580 for f in range(1, len(argList)+1):
581 self.codeList.append(" \\def\\%s@arg@%s{#%d}%%" % (self.topLevelName, self.toRoman(f), f))
582 self.codeList.extend(self.callMacro(1))
583 self.codeList.append("}")
584
585 def produceRemainingMacros(self):
586 "Generate code for all macros except the first."
587 formalsSoFar = len(self.argGroups[0])
588 for groupNum in range(1, len(self.argGroups)):
589 # Generate the macro header.
590 self.codeList.append("")
591 argList = self.argGroups[groupNum]
592 defStr = "\\def\\%s@%s" % (self.topLevelName, self.toRoman(groupNum))
593 if self.numFormals > 9:
594 defStr += self.argsToString(argList, mode="define", argSubtract=formalsSoFar)
595 else:
596 for g in range (0, groupNum+1):
597 defStr += self.argsToString(self.argGroups[g], mode="define")
598 self.codeList.append(defStr + "{%")
599
600 # Generate the macro body.
601 if self.numFormals > 9:
602 # More than nine formal parameters
603 for arg in argList:
604 if arg[0] == "argument":
605 formalNum = int(arg[1][1:])
606 self.codeList.append(" \\def\\%s@arg@%s{#%d}%%" % \
607 (self.topLevelName,
608 self.toRoman(formalNum),
609 formalNum - formalsSoFar))
610 elif arg[0] == "optarg":
611 for oarg in arg[2:]:
612 if oarg[0][0] == "#":
613 formalNum = int(oarg[0][1:])
614 self.codeList.append(" \\def\\%s@arg@%s{#%d}%%" % \
615 (self.topLevelName,
616 self.toRoman(formalNum),
617 formalNum - formalsSoFar))
618 if groupNum == len(self.argGroups) - 1:
619 self.codeList.extend(self.putCodeHere())
620 else:
621 self.codeList.extend(self.callMacro(groupNum + 1))
622 else:
623 # Nine or fewer formal parameters.
624 if groupNum == len(self.argGroups) - 1:
625 self.codeList.extend(self.putCodeHere())
626 else:
627 self.codeList.extend(self.callMacro(groupNum + 1))
628
629 # Generate the macro trailer.
630 self.codeList.append("}")
631
632 # Increment the count of formals seen so far.
633 for arg in argList:
634 if arg[0] == "argument":
635 formalsSoFar += 1
636 elif arg[0] == "optarg":
637 formalsSoFar += len(filter(lambda o: o[0][0] == "#", arg[2:]))
638
639 def generate(self, argList):
640 "Generate LaTeX code from an argument list."
641 # Group arguments and identify characteristics that affect the output.
642 self.argList = argList
643 self.partitionArgList()
644 self.haveAt = len(self.argGroups) > 1
645 self.haveStar = filter(lambda arg: arg[0]=="rawtext" and arg[1]=="*", self.argList) != []
646 self.topLevelName = self.argList[0][1]
647 for arg in self.argList:
648 if arg[0] == "argument":
649 self.numFormals += 1
650 elif arg[0] == "optarg":
651 for oarg in arg[2:]:
652 if oarg[0][0] == "#":
653 self.numFormals += 1
654
655 # Output LaTeX code.
656 if self.haveAt:
657 self.codeList.append("\\makeatletter")
658 if self.haveStar:
659 self.codeList.append("\\newif\\if%s@star" % self.topLevelName)
660 self.produceTopLevel()
661 self.produceRemainingMacros()
662 if self.haveAt:
663 self.codeList.append("\\makeatother")
664 for codeLine in self.codeList:
665 print codeLine
666
667
668 # The buck starts here.
669 if __name__ == '__main__':
670 import sys
671 import string
672
673 def processLine():
674 "Parses the current value of oneLine."
675 global oneLine
676 try:
677 sys.stdout.softspace = 0 # Cancel the %$#@! space.
678 oneLine = string.strip(oneLine)
679 if oneLine=="" or oneLine[0]=="%":
680 return
681 if not isStdin:
682 print prompt, oneLine
683 scanner = CmdScanner()
684 parser = CmdParser()
685 tokens = scanner.tokenize(oneLine)
686 ast = parser.parse(tokens)
687 argList = flattenAST(ast)
688 checkArgList(argList)
689 gen = LaTeXgenerator()
690 gen.generate(argList)
691 except ParseError,(message, pos):
692 sys.stderr.write((" "*(len(prompt)+pos)) + "^\n")
693 sys.stderr.write("%s: %s.\n" % (sys.argv[0], message))
694 if isStdin:
695 print ""
696
697 sys.setrecursionlimit(5000)
698 prompt = "% Prototype:"
699 if len(sys.argv) <= 1:
700 isStdin = 1
701 print prompt + " ",
702 while 1:
703 oneLine = sys.stdin.readline()
704 if not oneLine:
705 break
706 processLine()
707 print prompt + " ",
708 else:
709 isStdin = 0
710 oneLine = string.join(sys.argv[1:])
711 processLine()