1
2
3
4
5
6
7 import shutil, re, sys, os
8
10 line = line.replace('renewcommand', 'newcommand')
11
12 pattern1 = r'\\newcommand\{(.+)\}\s*\{(.*)\}'
13 found = False
14 m = re.search(pattern1, line)
15 if m:
16
17
18
19 end_pattern = r'([^A-Za-z])'
20 pattern = m.group(1) + end_pattern
21 replacement = m.group(2) + r'\g<1>'
22
23
24
25 found = True
26
27
28 pattern2 = r'\\newcommand\{(.+)\}\[(\d)\]\{(.*)\}'
29 m = re.search(pattern2, line)
30 if m:
31 nargs = int(m.group(2))
32 args = r'\{(.+?)\}'*nargs
33 pattern = m.group(1) + args
34 replacement = m.group(3)
35 for i in range(1, nargs+1):
36 replacement = replacement.replace('#%d' % i, r'\g<%d>' % i)
37 found = True
38
39 if found:
40
41 from latex import fix_latex_command_regex as fix
42 pattern = fix(pattern, 'match')
43 replacement = fix(replacement, 'replacement')
44 return pattern, replacement
45
47 f = open(filename, 'r')
48 lines = f.readlines()
49 f.close()
50 newcommands = []
51
52 for line in lines:
53 line = line.strip()
54 if line.startswith('%') or line == '':
55 continue
56 elif line.startswith(r'\newcommand') or \
57 line.startswith(r'\renewcommand'):
58 pattern, replacement = process_newcommand(line)
59 newcommands.append((pattern, replacement))
60 else:
61 raise SyntaxError('Illegal line\n %s\nline' % line + \
62 'must start with %% or ' + r'\newcommand')
63 return newcommands
64
66 """
67 Expand all newcommands in the list 'newcommands' of
68 (pattern, replacement) pairs. source can be a filename
69 or just a string with text. If source is a filename, a backup
70 file with extension .old~ is first made and then the original
71 file is overwritten by the new text with expanded commands.
72 """
73 if os.path.isfile(source):
74 shutil.copy(source, source + '.old~')
75 f = open(source, 'r')
76 text = f.read()
77 f.close()
78 else:
79 text = source
80
81 for pattern, replacement in newcommands:
82 m = re.search(pattern, text)
83
84
85 text, n = re.subn(pattern, replacement, text)
86
87
88
89 depth = 2
90 for i in range(depth):
91 for pattern, replacement in newcommands:
92 m = re.search(pattern, text)
93
94
95 text, n = re.subn(pattern, replacement, text)
96
97
98 if os.path.isfile(source):
99 f = open(source, 'w')
100 f.write(text)
101 f.close()
102 else:
103 return text
104
106 if isinstance(newcommands_files, basestring):
107 newcommands_files = [newcommands_files]
108 newcommands = []
109 for filename in newcommands_files:
110 if os.path.isfile(filename):
111 newcommands.extend(parse_newcommands(filename))
112
113 return substitute(source, newcommands)
114
115 if __name__ == '__main__':
116 if len(sys.argv) < 3:
117 print 'Usage: expand_newcommands.py newcommands_file source_file1 source_file2 ...'
118 sys.exit(1)
119 newcommands_file = sys.argv[1]
120 for source_file in sys.argv[2:]:
121 print 'expanding newcommands in', source_file
122 expand_newcommands(newcommands_file, source_file)
123