Debian Codegraph @

texmf-dist/scripts/de-macro/de-macro

raw ◀ ▶
1 Debian patch touch this file
•1 #!/usr/bin/python3 -O
2
3 r"""
4 Copyright 2005-2020 Peter Gacs
5 Licensed under the Academic Free Licence version 2.1
6
7 DE-MACRO
8
9 Version 1.4.1 - A small typo corrected.
10
11 Version 1.4 - Luca Citi made it python2.7 and python3 compatible.
12 Peter Gacs improved the parsing of \input{<filename>},
13 and made @ a letter in the style files.
14 Version 1.3 - this version is much more conservative about deleting
15 comments and inserting or deleting blank space: tries to
16 leave in all comments, adds space only when necessary, and
17 tries not to delete space in the main text.
18 The motivating comments came from Daniel Webb.
19 Version 1.2 - a syntactical bug corrected, thanks Brian de Alwis!
20
21
22 PURPOSE
23
24 This program can eliminate most private macros from a LaTeX file.
25 Applications:
26 - your publisher has difficulty dealing with many private macros
27 - you cooperate with colleagues who do not understand your macros
28 - preprocessing before a system like latex2html, which is somewhat
29 unpredictable with private macros.
30
31 It cannot be used to eliminate more complex macros that rely on
32 more programming-like constructs in style files. In particular, it will
33 not replace style files that have options.
34
35 USAGE
36
37 de-macro [--defs <defs-db>] <tex-file-1>[.tex] [<tex-file-2>[.tex] ...]
38
39 Simplest example: de-macro testament
40
41 (As you see, the <> is used only in the notation of this documentation,
42 you should not type it.)
43
44 If <tex-file-i> contains a command \usepackage{<defs-file>-private}
45 then the file <defs-file>-private.sty will be read, and its macros will be
46 replaced in <tex-file-i> with their definitions.
47 The result is in <tex-file-i>-clean.tex.
48
49 Only newcommand, renewcommand, newenvironment, and renewenvironment are
50 understood (it does not matter, whether you write new or renew).
51 These can be nested but do not be too clever, since I do not
52 guarantee the same expansion order as in TeX.
53
54 FILES
55
56 <tex-file-1>.db
57 <tex-file>-clean.tex
58 <defs-file>-private.sty
59
60 For speed, a macro database file called <defs-file>.db is created.
61 If such a file exists already then it is used.
62 If <defs-file>-private.sty is older than <tex-file-1>.db then it will not
63 be used.
64
65 It is possible to specify another database filename via --defs <defs-db>.
66 Then <defs-db>.db will be used.
67
68 For each <tex-file-i>, a file <tex-file-i>-clean.tex will be produced.
69 If <tex-file-i>-clean.tex is newer than <tex-file-i>.tex then it stays.
70
71 INPUT COMMAND
72
73 If a tex file contains a command \input{<tex-file-j>} or \input <tex-file-j>
74 then <tex-file-j>.tex is processed recursively, and <tex-file-j>-clean.tex
75 will be inserted into the final output.
76 For speed, if <tex-file-j>-clean.tex is newer than <tex-file-j>.tex
77 then <tex-file-j>.tex will not be reprocessed.
78
79 The dependency checking is not sophisticated, so if you rewrite some macros
80 then remove all *-clean.tex files!
81
82 """
83
84 import sys, os, re, shelve
85
86 # Utilities
87
88 class No_detail:
89 strerror = ""
90
91 no_detail = No_detail()
92
93
94 class Error(Exception):
95 """Base class for exceptions in this module."""
96 pass
97
98 class Empty_text_error(Error):
99 """Exception raised for errors in the input.
100
101 Attributes:
102 data -- data that was found empty
103 message
104 """
105
106 def __init__(self, data, message):
107 self.data = data
108 self.message = message
109
110 def warn(error_message, detail = no_detail):
111 sys.stderr.write(error_message + "\n")
112 if no_detail != detail:
113 sys.stderr.write(detail.strerror + "\n")
114
115 def die(error_message, detail = no_detail):
116 warn(error_message, detail = no_detail)
117 sys.exit(1)
118
119 def getopt_map(one_letter_opts, long_optlist):
120 "Turns long options into an option map, using getopt."
121 import getopt
122 optlist, args = getopt.getopt(sys.argv[1:],
123 one_letter_opts, long_optlist)
124 opt_map = {}
125 for pair in optlist: opt_map[pair[0]] = pair[1] or 1
126 return opt_map, args
127
128 def newer(file1, file2):
129
130 if not os.path.isfile(file1):
131 return False
132
133 try:
134 stat_return = os.lstat(file1)
135 except OSError as detail:
136 die("lstat " + file1 + " failed:", detail)
137 time1 = stat_return.st_mtime
138
139 try:
140 stat_return = os.lstat(file2)
141 except OSError as detail:
142 die("lstat " + file2 + " failed:", detail)
143 time2 = stat_return.st_mtime
144
145 return time1 > time2
146
147 def cut_extension(filename, ext):
148 """
149 If filename has extension ext (including the possible dot),
150 it will be cut off.
151 """
152 file = filename
153 index = filename.rfind(ext)
154 if 0 <= index and len(file)-len(ext) == index:
155 file = file[:index]
156 return file
157
158
159 class Stream:
160 data = None
161 pos = None
162 item = None
163
164 def legal(self):
165 return 0 <= self.pos and self.pos < len(self.data)
166
167 def uplegal(self):
168 return self.pos < len(self.data)
169
170 def __init__(self, data_v = None):
171 self.data = data_v
172 if self.data:
173 self.pos = 0
174 self.item = self.data[self.pos]
175
176 def next(self):
177 self.pos += 1
178 if self.pos < len(self.data):
179 self.item = self.data[self.pos]
180 return self.item
181
182 def reset(self):
183 if self.data and 0 < len(self.data):
184 self.pos = 0
185 self.item = self.data[0]
186 return self.item
187
188
189 # Basic classes
190
191 blank_re = re.compile(r"\s")
192 blanked_filename_re = re.compile(r"^\s+(\w*)\s+")
193 braced_filename_re = re.compile(r"^\s*{\s*(\w*)\s*}")
194 blank_or_rbrace_re = re.compile(r"[\s}]")
195 pos_digit_re = re.compile(r"[1-9]")
196
197 def isletter(c, isatletter=False):
198 if "@" == c:
199 return isatletter
200 else:
201 return c.isalpha()
202
203 class Token:
204 """Type 0 means ordinary character, types 1,2 mean escape sequence
205 (without the \ ), type 3 means comment.
206 """
207 simple_ty = 0
208 esc_symb_ty = 1
209 esc_str_ty = 2
210 comment_ty = 3
211
212 type = simple_ty
213 val = " "
214
215 def __init__(self, type_v=simple_ty, val_v=" "):
216 self.type = type_v
217 self.val = val_v
218
219 def show(self):
220 out = ""
221 if simple_ty == self.type or comment_ty == self.type:
222 out = self.val
223 else:
224 out = "\\" + self.val
225 return out
226
227
228 # Constants
229
230 g_token = Token(0," ") # generic token
231 simple_ty = g_token.simple_ty
232 comment_ty = g_token.comment_ty
233 esc_symb_ty = g_token.esc_symb_ty
234 esc_str_ty = g_token.esc_str_ty
235
236
237 def detokenize(text, isatletter=False):
238 """
239 Input is a list of tokens.
240 Output is a string.
241 """
242 out = ""
243 if 0 == len(text):
244 return
245 pos = 0
246 out += text[pos].show()
247 pos += 1
248 while pos < len(text):
249 previtem = text[pos-1]
250 item = text[pos]
251 """Insert a separating space after an escape sequence if it is a
252 string and is followed by a letter."""
253 if (esc_str_ty == previtem.type
254 and simple_ty == item.type and isletter(item.val[0], isatletter)):
255 out += " "
256 out += item.show()
257 pos += 1
258 return out
259
260
261 def strip_comments(text):
262 """
263 Input is a list of tokens.
264 Output is the same list except the comment tokens.
265 """
266 out = []
267 for token in text:
268 if not comment_ty == token.type:
269 out.append(token)
270 return out
271
272 class Group:
273 """type 0 means a token, type 1 means contents of a group within {}
274 """
275 token_ty = 0
276 group_ty = 1
277 type = token_ty
278 val = [] # Value is a token list.
279
280 def __init__(self, type_v, val_v):
281 self.type = type_v
282 self.val = val_v
283
284 def show(self):
285 if token_ty == self.type:
286 return self.val.show()
287 else:
288 return "{%s}" % detokenize(self.val)
289
290 # Constants
291
292 g_group = Group(0, [])
293 token_ty = g_group.token_ty
294 group_ty = g_group.group_ty
295
296
297 def tokenize(in_str, isatletter=False):
298 """Returns a list of tokens.
299 """
300 text = []
301 cs = Char_stream(in_str)
302 cs.reset()
303 if not cs.legal():
304 raise Error("No string to tokenize.")
305 while cs.uplegal():
306 if "%" == cs.item:
307 comment = cs.scan_comment_token()
308 text.append(Token(comment_ty, comment))
309 elif "\\" != cs.item:
310 text.append(Token(simple_ty, cs.item))
311 cs.next()
312 else:
313 cs.next()
314 name = cs.scan_escape_token(isatletter)
315 if isletter(name[0], isatletter):
316 token = Token(esc_str_ty, name)
317 else:
318 token = Token(esc_symb_ty, name)
319 text.append(token)
320 if "makeatletter" == name:
321 isatletter=True
322 elif "makeatother" == name:
323 isatletter=False
324 return text
325
326
327 class Command_def:
328 name = "1"
329 numargs = 0
330 body= ""
331
332 def __init__(self, name_v, numargs_v, body_v):
333 self.name = name_v
334 self.numargs = numargs_v
335 self.body = body_v
336
337 def show(self):
338 out = "\\newcommand{\\%s}" % (self.name)
339 if 0 < self.numargs:
340 out += "[%d]" % self.numargs
341 out += "{%s}" % detokenize(self.body)
342 return out
343
344
345 class Env_def:
346 name = "1"
347 numargs = 0
348 begin = ""
349 end = ""
350
351 def __init__(self, name_v, numargs_v, begin_v, end_v):
352 self.name = name_v
353 self.numargs = numargs_v
354 self.begin = begin_v
355 self.end = end_v
356
357 def show(self):
358 out = "\\newenvironment{%s}" % self.name
359 if 0 < self.numargs:
360 out += "[%d]" % self.numargs
361 out += "{%s}" % detokenize(self.begin)
362 out += "{%s}" % detokenize(self.end)
363 return out
364
365
366 class Command_instance:
367 name = "1"
368 args = []
369
370 def __init__(self, name_v, args_v):
371 self.name = name_v
372 self.args = args_v
373
374 def show(self):
375 out = "\\"+self.name
376 for arg in self.args:
377 out += "{%s}" % detokenize(arg)
378 return out
379
380
381 class Env_instance:
382 name = "1"
383 args = []
384
385 def __init__(self, name_v, args_v, body_v):
386 self.name = name_v
387 self.args = args_v
388 self.body = body_v
389
390 def show(self):
391 out = "\\begin{%s}" % self.name
392 for arg in self.args:
393 out += "{%s}" % detokenize(arg)
394 out += detokenize(self.body)
395 out += "\\end{%s}" % self.name
396 return out
397
398 class Char_stream(Stream):
399
400 def scan_escape_token(self, isatletter=False):
401 """
402 Starts after the escape sign, assumes that it is scanning a symbol.
403 Returns a token-string.
404 """
405 out = self.item # Continue only if this is a letter.
406 item = self.next()
407 if isletter(out, isatletter):
408 while self.uplegal() and isletter(item, isatletter):
409 out += item
410 item = self.next()
411 return out
412
413 def scan_comment_token(self):
414 """
415 Starts at the comment sign %, assumes that it is scanning a comment.
416 Returns the whole comment string,
417 including the % and all empty space after it.
418 """
419 comment = ""
420 while self.uplegal() and "\n" != self.item:
421 comment += self.item
422 self.next()
423 while self.uplegal() and blank_re.match(self.item):
424 comment += self.item
425 self.next()
426 return comment
427
428 def scan_input_filename(self):
429 """We have just read an \input token. The next group or word will be
430 interpreted as a filename (possibly without .tex). Filenames should not begin with spaces.
431 Return the filename.
432 """
433 item = self.item
434 file = ""
435 while self.uplegal() and blank_re.match(self.item):
436 item = self.next()
437 if "{" == item:
438 item = self.next()
439 while self.uplegal() and not "}" == item:
440 file += item
441 item = self.next()
442 self.next()
443 else:
444 while self.uplegal() and not blank_re.match(item):
445 file += item
446 item = self.next()
447 return file
448
449 def scan_package_filenames(self):
450 r"""We just read a \usepackage token. The next group will be
451 interpreted as a list of filenames (without .sty) separated by commas.
452 Return the list.
453 """
454 item = self.item
455 while self.uplegal() and blank_re.match(item):
456 item = self.next()
457 file = ""
458 if not "{" == item:
459 raise Error("\\usepackage not followed by brace.")
460 item = self.next()
461 while self.uplegal() and not blank_or_rbrace_re.match(item):
462 file += item
463 item = self.next()
464 self.next()
465 return file.split(",")
466
467
468 class Tex_stream(Stream):
469
470 defs = ({}, {})
471 defs_db = "x"
472 defs_db_file = "x.db"
473 debug = False
474
475 def smart_tokenize(self, in_str, handle_inputs=False, isatletter=False):
476 """Returns a list of tokens.
477 It may interpret and carry out all \input commands.
478 """
479 self.data = []
480 text = self.data
481 cs = Char_stream(in_str)
482 cs.reset()
483 if not cs.legal():
484 raise Error("No string to tokenize.")
485 while cs.uplegal():
486 if "%" == cs.item:
487 comment = cs.scan_comment_token()
488 text.append(Token(comment_ty, comment))
489 elif "\\" != cs.item:
490 text.append(Token(simple_ty, cs.item))
491 cs.next()
492 else:
493 cs.next()
494 name = cs.scan_escape_token(isatletter)
495 if "input" == name and handle_inputs:
496 file = cs.scan_input_filename()
497 to_add = self.process_if_newer(file)
498 text.extend(to_add)
499 elif "usepackage" == name:
500 while cs.uplegal() and blank_re.match(cs.item):
501 cs.next()
502 if "[" == cs.item: # Packages with options will not be processed.
503 text.extend([Token(esc_str_ty, "usepackage"),
504 Token(simple_ty, "[")])
505 cs.next()
506 continue
507 files = cs.scan_package_filenames()
508 i = 0
509 while i < len(files): # process private packages
510 file = files[i]
511 p = file.rfind("-private")
512 if p < 0 or not len(file) - len("-private") == p:
513 i += 1
514 continue
515 defs_db_file = file+".db"
516 self.add_defs(file)
517 del files[i:(i+1)]
518 if files: # non-private packages left
519 group_content = ",".join(files)
520 to_add_str = "\\usepackage{%s}" % (group_content)
521 to_add = tokenize(to_add_str,isatletter)
522 text.extend(to_add)
523 else:
524 if isletter(name[0], isatletter):
525 token = Token(esc_str_ty, name)
526 else:
527 token = Token(esc_symb_ty, name)
528 text.append(token)
529 if "makeatletter" == name:
530 isatletter=True
531 elif "makeatother" == name:
532 isatletter=False
533 self.reset()
534 return self.data
535
536 def smart_detokenize(self,isatletter=False):
537 """
538 Output is a string.
539 If the list contains an \input{file} then the content of file
540 file-clean.tex replaces it in the output.
541 """
542 self.reset()
543 if not self.legal():
544 return ""
545 out = ""
546 previtem = None
547 while self.uplegal():
548 item = self.item
549 """Insert a separating space after an escape sequence if it is a
550 string and is followed by a letter."""
551 if (None != previtem and esc_str_ty == previtem.type
552 and simple_ty == item.type and isletter(item.val[0], isatletter)):
553 out += " "
554 previtem = item
555 if not (esc_str_ty == item.type and "input" == item.val):
556 out += item.show()
557 self.next()
558 else:
559 self.next()
560 group = self.scan_group()
561 file = detokenize(group.val)
562 clean_file = "%s-clean.tex" % (file)
563 print("Reading file %s" % (clean_file))
564 fp = open(clean_file,"r")
565 content = fp.read()
566 fp.close()
567 out += content
568 return out
569
570 # Basic tex scanning
571
572 def skip_blank_tokens(self): # we also skip comment tokens.
573 item = self.item
574 while (self.uplegal() and
575 (comment_ty == item.type or
576 (simple_ty == item.type and blank_re.match(item.val)))):
577 item = self.next()
578 return item
579
580 def scan_group(self):
581 """Returns group.
582 """
583 if not self.legal():
584 raise Error("No group to scan.")
585 item = self.item
586 if not (simple_ty == item.type and "{" == item.val):
587 return Group(token_ty, [self.item])
588 count = 1
589 group = []
590 item = self.next()
591 while count and self.uplegal():
592 if simple_ty == item.type:
593 if "{" == item.val:
594 count += 1
595 elif "}" == item.val:
596 count -= 1
597 if count != 0:
598 group.append(item)
599 item = self.next()
600 return Group(group_ty, group)
601
602 # Command and environment definitions
603
604 def scan_command_name(self):
605 """Returns name.
606 """
607 if not self.legal():
608 raise Error("No command name to scan.")
609 item = self.item
610 name = ""
611 if item.type in [esc_symb_ty, esc_str_ty]:
612 name = item.val
613 else:
614 if not "{" == item.val:
615 raise Error("Command definition misses first {.")
616 self.next()
617 item = self.skip_blank_tokens()
618 if not item.type in [esc_symb_ty, esc_str_ty]:
619 raise Error("Command definition does not begin with control sequence.")
620 name = item.val
621 self.next()
622 item = self.skip_blank_tokens()
623 if not "}" == item.val:
624 raise Error("Definition for commmand %s misses first }., %s" %
625 (name, item.val))
626 self.next()
627 self.skip_blank_tokens()
628 return name
629
630 def scan_numargs(self, name):
631 """
632 name is the name of the command or environment definition being
633 scanned.
634 Starts on a nonblank token.
635 Returns numargs
636 where numargs is the number of arguments in a command or environment
637 definition,
638 """
639 if not self.legal():
640 raise Error("No numargs to scan.")
641 item = self.item
642 numargs = 0
643 if not simple_ty == item.type:
644 raise Error("Illegal command or environment definition: "+name)
645 if "[" == item.val:
646 if not 4 < len(self.data):
647 raise Error("Command or environment definition is illegal: "+name)
648 item = self.next()
649 if not simple_ty == item.type:
650 raise Error("Illegal command or environment definition: "+name)
651 numargs = item.val
652 if not pos_digit_re.match(numargs):
653 raise Error("%s must be argument number after %s" % (numargs, name))
654 numargs = int(numargs)
655 self.next()
656 item = self.skip_blank_tokens()
657 if not simple_ty == item.type:
658 raise Error("Illegal command definition: "+name)
659 if "]" != item.val:
660 raise Error("Illegal command definition: "+name)
661 self.next()
662 self.skip_blank_tokens()
663 return numargs
664
665 def scan_command_def(self):
666 """Scan a command definition.
667 Return command_def.
668 Assumes that the number of arguments is at most 9.
669 """
670 if not self.legal():
671 raise Error("No command definition to scan.")
672 item = self.item
673 if not 2 < len(self.data):
674 raise Error("Command definition is illegal.")
675 # newcommand or renewcommand
676 if not item.type in [esc_symb_ty, esc_str_ty]:
677 raise Error("Command definition should begin with control sequence: "+item.val)
678 if item.val not in ["newcommand", "renewcommand"]:
679 raise Error("Command definition should begin with control sequence.")
680 self.next()
681 self.skip_blank_tokens()
682
683 cmd_name = self.scan_command_name()
684 numargs = self.scan_numargs(cmd_name)
685
686 body_group = self.scan_group()
687 if group_ty != body_group.type:
688 raise Error("Command body missing: "+cmd_name)
689 body_val = strip_comments(body_group.val)
690 return Command_def(cmd_name, numargs, body_val)
691
692 def scan_env_name(self):
693 """Starts on a {.
694 Returns name.
695 """
696 if not self.legal():
697 raise Error("No environment name to scan.")
698 item = self.item
699 if not "{" == item.val:
700 raise Error("Env. definition begins with %s, not with {" % (item.val))
701 self.next()
702 item = self.skip_blank_tokens()
703 name = ""
704 if not simple_ty == item.type:
705 raise Error("1. Env. def. begins with cont. seq. %s, not with env.name."
706 % (item.val))
707 while self.uplegal() and not blank_or_rbrace_re.match(item.val):
708 name += item.val
709 item = self.next()
710 if not simple_ty == item.type:
711 raise Error("2. Env. def. begins with cont. seq. %s, not with env.name."
712 % (item.val))
713 item = self.skip_blank_tokens()
714 if not "}" == item.val:
715 raise Error("Command definition does not begin with control sequence.")
716 self.next()
717 self.skip_blank_tokens()
718 return name
719
720 def scan_env_def(self):
721 """Scan an environment definition.
722 Return env_def
723 Assumes that the number of arguments is at most 9.
724 """
725 if not self.legal():
726 raise Error("No environment definition to scan.")
727 item = self.item
728 if not 7 < len(self.data):
729 raise Error("Environment definition is illegal.")
730 pos = 0
731
732 if not item.type in [esc_symb_ty, esc_str_ty]:
733 raise Error("Env. definition does not begin with control sequence:"+
734 item.val)
735 if item.val not in ["newenvironment", "renewenvironment"]:
736 raise Error("Env. definition does not begin with control sequence.")
737 self.next()
738 self.skip_blank_tokens()
739
740 env_name = self.scan_env_name()
741 numargs = self.scan_numargs(env_name)
742 self.skip_blank_tokens()
743
744 begin_group = self.scan_group()
745 if group_ty != begin_group.type:
746 raise Error("Begin body missing: "+env_name)
747 begin_val = strip_comments(begin_group.val)
748
749 self.skip_blank_tokens()
750
751 end_group = self.scan_group()
752 if group_ty != end_group.type:
753 raise Error("End body missing:"+env_name)
754 end_val = strip_comments(end_group.val)
755
756 return Env_def(env_name, numargs, begin_val, end_val)
757
758 def scan_defs(self):
759 if not self.legal():
760 raise Error("No definitions to scan.")
761 self.reset()
762 command_defs, env_defs = self.defs
763 while self.uplegal():
764 if (esc_str_ty == self.item.type
765 and self.item.val in ["newcommand", "renewcommand"]):
766 command_def = self.scan_command_def()
767 command_defs[command_def.name] = command_def
768 elif (esc_str_ty == self.item.type and self.item.val
769 in ["newenvironment", "renewenvironment"]):
770 env_def = self.scan_env_def()
771 env_defs[env_def.name] = env_def
772 else:
773 self.next()
774
775 # Instances
776
777 def scan_args(self, command_or_env_def):
778 """Scan the arguments of a command or environment.
779 Return [args].
780 """
781 if not self.legal():
782 raise Error("No arguments to scan.")
783 numargs = command_or_env_def.numargs
784 name = command_or_env_def.name
785
786 args = []
787 for i in range(numargs):
788 arg = []
789 if not (simple_ty == self.item.type and "{" == self.item.val):
790 arg = [self.item]
791 self.next()
792 else:
793 group = self.scan_group()
794 arg = group.val
795 args.append(arg)
796 return args
797
798 def scan_command(self, command_def):
799 """Scan the arguments of a command.
800 Return command_instance
801 """
802 if not self.legal():
803 raise Error("No command to scan.")
804 if not self.item.type in [esc_symb_ty, esc_str_ty]:
805 raise Error("Command does not begin with control sequence.")
806 name = self.item.val
807 self.next()
808 if 0 < command_def.numargs:
809 self.skip_blank_tokens()
810 args = self.scan_args(command_def)
811 else:
812 args = []
813 return Command_instance(name, args)
814
815 def test_env_boundary(self, item):
816 """Check whether an environment begin or end follows.
817 Return 1 if \begin, -1 if \end, 0 otherwise.
818 """
819 d = 0
820 if esc_str_ty == item.type:
821 if "begin"==item.val:
822 d = 1
823 elif "end"==item.val:
824 d = -1
825 return d
826
827 def scan_env_begin(self):
828 """Scan an environment name.
829 Return env_name.
830 """
831 if not self.legal():
832 raise Error("No environment begin to scan.")
833 item = self.item
834 if not (esc_str_ty == item.type and "begin" == item.val):
835 raise Error("Environment does not begin with begin.")
836 self.next()
837 name_group = self.scan_group()
838 name = detokenize(name_group.val)
839 return name
840
841 def scan_env_end(self):
842 """Scan an environment end.
843 Return env_name.
844 """
845 if not self.legal():
846 raise Error("No environment end to scan.")
847 item = self.item
848 if not (esc_str_ty == item.type and "end" == item.val):
849 raise Error("Environment does not end with end.")
850 self.next()
851 name_group = self.scan_group()
852 name = detokenize(name_group.val)
853 return name
854
855 def scan_env_rest(self, env_def):
856 """Scanning starts after \begin{envname}.
857 Returns env_instance.
858 """
859 if not self.legal():
860 raise Error("No environment rest to scan.")
861 count = 1 # We are already within a boundary.
862 args = self.scan_args(env_def)
863 body = []
864 while count and self.uplegal():
865 old_pos = self.pos
866 d = self.test_env_boundary(self.item)
867 count += d
868 if 1 == d:
869 self.scan_env_begin()
870 elif -1 == d:
871 self.scan_env_end()
872 else:
873 self.next()
874 if 0 < count:
875 body.extend(self.data[old_pos : self.pos])
876 return Env_instance(env_def.name, args, body)
877
878 # Definitions
879
880 def restore_defs(self):
881 if os.path.isfile(self.defs_db_file):
882 print("Using defs db %s" % (self.defs_db_file))
883 db_h = shelve.open(self.defs_db)
884 self.defs = db_h["defs"]
885 db_h.close()
886
887 def save_defs(self):
888 db_h = shelve.open(self.defs_db)
889 if "defs" in db_h:
890 del db_h["defs"]
891 db_h["defs"] = self.defs
892 db_h.close()
893
894 def add_defs(self, defs_file):
895 defs_file_compl = defs_file + ".sty"
896 if not os.path.isfile(defs_file_compl):
897 raise Error("%s does not exist" % (defs_file_compl))
898
899 defs_db_file = self.defs_db_file
900 if newer(defs_db_file, defs_file_compl):
901 print("Using defs db %s for %s" % (defs_db_file, defs_file))
902 else:
903 defs_fp = open(defs_file_compl, "r")
904 defs_str = defs_fp.read()
905 defs_fp.close()
906 ds = Tex_stream()
907 ds.defs = self.defs
908 defs_text = ds.smart_tokenize(defs_str,isatletter=True)
909 # changing ds.defs will change self.defs
910 if self.debug:
911 defs_seen_file = "%s-seen.sty" % (defs_file)
912 defs_seen_fp = open(defs_seen_file, "w")
913 out = detokenize(defs_text,isatletter=True)
914 defs_seen_fp.write(out)
915 defs_seen_fp.close()
916 ds.scan_defs()
917 if self.debug:
918 out = ""
919 command_defs, env_defs = self.defs
920 for def_name in command_defs.keys():
921 out += command_defs[def_name].show() + "\n"
922 for def_name in env_defs.keys():
923 out += env_defs[def_name].show() +"\n"
924 print("Definitions after reading %s:" % (defs_file))
925 print(out)
926
927 # Applying definitions, recursively
928 # (maybe not quite in Knuth order, so avoid tricks!)
929
930 def subst_args(self, body, args):
931 out = []
932 pos = 0
933 while pos < len(body):
934 item = body[pos]
935 if not (simple_ty == item.type and "#" == item.val):
936 out.append(item)
937 pos += 1
938 continue
939 pos += 1
940 token = body[pos]
941 argnum = token.val
942 if not pos_digit_re.match(argnum):
943 raise Error("# is not followed by number.")
944 argnum = int(argnum)
945 if argnum > len(args):
946 raise Error("Too large argument number.")
947 arg = args[argnum-1]
948 out += arg
949 pos += 1
950 return out
951
952 def apply_command_recur(self, command_instance):
953 command_defs, env_defs = self.defs
954 name = command_instance.name
955 command_def = command_defs[name]
956
957 args = command_instance.args
958 body = command_def.body
959 result = self.subst_args(body, args)
960 try:
961 result = self.apply_all_recur(result)
962 except Empty_text_error as e:
963 raise Error("apply_all_recur fails on command instance %s: %s, %s" % \
964 (command_instance.show(), detokenize(e.data), e.message))
965 return result
966
967 def apply_env_recur(self, env_instance):
968 command_defs, env_defs = self.defs
969 name = env_instance.name
970 env_def = env_defs[name]
971
972 begin, end = env_def.begin, env_def.end
973 body, args = env_instance.body, env_instance.args
974 out = self.subst_args(begin, args) + body + self.subst_args(end, args)
975 return self.apply_all_recur(out)
976
977
978 def apply_all_recur(self, data, report=False):
979 ts = Tex_stream(data)
980 ts.defs = self.defs
981 command_defs, env_defs = self.defs
982 out = []
983 progress_step = 10000
984 progress = progress_step
985 if not ts.legal():
986 raise Empty_text_error(data, "No text to process.")
987 while ts.uplegal():
988 if self.pos > progress:
989 if report:
990 print(self.pos)
991 progress += progress_step
992 if not ts.item.type in [esc_symb_ty, esc_str_ty]:
993 out.append(ts.item)
994 ts.next()
995 continue
996 if 1 == ts.test_env_boundary(ts.item):
997 old_pos = ts.pos
998 env_name = ts.scan_env_begin()
999 if env_name not in env_defs:
1000 out.extend(ts.data[old_pos : ts.pos])
1001 continue
1002 else:
1003 env_def = env_defs[env_name]
1004 env_instance = ts.scan_env_rest(env_def)
1005 result = ts.apply_env_recur(env_instance)
1006 out.extend(result)
1007 elif ts.item.val not in command_defs:
1008 out.append(ts.item)
1009 ts.next()
1010 continue
1011 else:
1012 command_def = command_defs[ts.item.val]
1013 command_inst = ts.scan_command(command_def)
1014 result = ts.apply_command_recur(command_inst)
1015 out.extend(result)
1016 return out
1017
1018
1019 # Processing files
1020
1021 def process_file(self, file):
1022 """Returns the new defs.
1023 """
1024 file = cut_extension(file, ".tex")
1025 source_file = "%s.tex" % (file)
1026 print("File %s [" % (source_file))
1027 source_fp = open(source_file, "r")
1028 text_str = source_fp.read()
1029 source_fp.close()
1030
1031 self.smart_tokenize(text_str, handle_inputs=True)
1032 if not self.data:
1033 raise Error("Empty tokenization result.")
1034 self.reset()
1035
1036 if self.debug:
1037 source_seen_fname = "%s-seen.tex" % (file)
1038 source_seen_fp = open(source_seen_fname, "w")
1039 source_seen_fp.write(detokenize(self.data))
1040 source_seen_fp.close()
1041
1042 self.data = self.apply_all_recur(self.data, report=True)
1043
1044 result_fname = "%s-clean.tex" % (file)
1045 print("Writing %s [" % (result_fname))
1046 result_fp = open(result_fname, "w")
1047 result_fp.write(self.smart_detokenize())
1048 result_fp.close()
1049 print("] file %s" % (result_fname))
1050 print("] file %s" % (source_file))
1051
1052 def process_if_newer(self, file):
1053 """
1054 \input{file} is added to the token list.
1055 If the input file is newer it is processed.
1056 Returns tokenized \input{file}.
1057 """
1058 file = cut_extension(file, ".tex")
1059 tex_file = file+".tex"
1060 clean_tex_file = file+"-clean.tex"
1061 if newer(clean_tex_file, tex_file):
1062 print("Using %s." % (clean_tex_file))
1063 else:
1064 ts = Tex_stream()
1065 ts.data = []
1066 ts.defs = self.defs
1067 ts.process_file(file)
1068 to_add = "\\input{%s}" % (file)
1069 return tokenize(to_add)
1070
1071 # Main
1072
1073 long_optlist = ["debug","defs="]
1074 options, restargs = getopt_map("x", long_optlist)
1075
1076 debug = False
1077 if "--debug" in options:
1078 debug = True
1079
1080 root = restargs[0]
1081 root = cut_extension(root, ".tex")
1082 if "--defs" in options:
1083 defs_root = options["--defs"]
1084 else:
1085 defs_root = "%s" % (root)
1086 defs_db = defs_root
1087 defs_db_file = defs_root+".db"
1088
1089 ts = Tex_stream()
1090 ts.defs_db = defs_db
1091 ts.defs_db_file = defs_db_file
1092 ts.debug = debug
1093
1094 ts.restore_defs()
1095 for root in restargs:
1096 ts.process_file(root)
1097
1098 print("(Re)creating defs db %s" % (defs_db))
1099 ts.save_defs()