blob: 02711a30617baec31d3791bcc5f7026375a38270 [file] [log] [blame]
Fred Drake30a68c71998-11-23 16:59:39 +00001#! /usr/bin/env python
2
Fred Drake0eb7b2a1999-05-19 17:37:37 +00003"""Generate ESIS events based on a LaTeX source document and
4configuration data.
5
6The conversion is not strong enough to work with arbitrary LaTeX
7documents; it has only been designed to work with the highly stylized
8markup used in the standard Python documentation. A lot of
9information about specific markup is encoded in the control table
10passed to the convert() function; changing this table can allow this
11tool to support additional LaTeX markups.
12
13The format of the table is largely undocumented; see the commented
14headers where the table is specified in main(). There is no provision
15to load an alternate table from an external file.
Fred Drake30a68c71998-11-23 16:59:39 +000016"""
17__version__ = '$Revision$'
18
Fred Drake96e4a061999-07-29 22:22:13 +000019import copy
Fred Drake30a68c71998-11-23 16:59:39 +000020import errno
Fred Drake96e4a061999-07-29 22:22:13 +000021import getopt
22import os
Fred Drake30a68c71998-11-23 16:59:39 +000023import re
24import string
25import StringIO
26import sys
Fred Drake96e4a061999-07-29 22:22:13 +000027import UserList
Fred Drake30a68c71998-11-23 16:59:39 +000028
Fred Drakeaeea9811998-12-01 19:04:12 +000029from esistools import encode
Fred Drake54fb7fb1999-05-10 19:36:03 +000030from types import ListType, StringType, TupleType
Fred Drakeaeea9811998-12-01 19:04:12 +000031
Fred Drake96e4a061999-07-29 22:22:13 +000032try:
33 from xml.parsers.xmllib import XMLParser
34except ImportError:
35 from xmllib import XMLParser
36
Fred Drake30a68c71998-11-23 16:59:39 +000037
Fred Draked7acf021999-01-14 17:38:12 +000038DEBUG = 0
39
40
Fred Drake96e4a061999-07-29 22:22:13 +000041class LaTeXFormatError(Exception):
Fred Drake30a68c71998-11-23 16:59:39 +000042 pass
43
44
Fred Drake96e4a061999-07-29 22:22:13 +000045class LaTeXStackError(LaTeXFormatError):
46 def __init__(self, found, stack):
47 msg = "environment close for %s doesn't match;\n stack = %s" \
48 % (found, stack)
49 self.found = found
50 self.stack = stack[:]
51 LaTeXFormatError.__init__(self, msg)
52
53
Fred Drake30a68c71998-11-23 16:59:39 +000054_begin_env_rx = re.compile(r"[\\]begin{([^}]*)}")
55_end_env_rx = re.compile(r"[\\]end{([^}]*)}")
Fred Drake0eb7b2a1999-05-19 17:37:37 +000056_begin_macro_rx = re.compile(r"[\\]([a-zA-Z]+[*]?) ?({|\s*\n?)")
Fred Drake96c00b01999-05-07 19:59:02 +000057_comment_rx = re.compile("%+ ?(.*)\n[ \t]*")
Fred Drake30a68c71998-11-23 16:59:39 +000058_text_rx = re.compile(r"[^]%\\{}]+")
59_optional_rx = re.compile(r"\s*[[]([^]]*)[]]")
Fred Drakeaeea9811998-12-01 19:04:12 +000060# _parameter_rx is this complicated to allow {...} inside a parameter;
61# this is useful to match tabular layout specifications like {c|p{24pt}}
62_parameter_rx = re.compile("[ \n]*{(([^{}}]|{[^}]*})*)}")
Fred Drake30a68c71998-11-23 16:59:39 +000063_token_rx = re.compile(r"[a-zA-Z][a-zA-Z0-9.-]*$")
64_start_group_rx = re.compile("[ \n]*{")
65_start_optional_rx = re.compile("[ \n]*[[]")
66
67
Fred Drake42f52981998-11-30 14:45:24 +000068ESCAPED_CHARS = "$%#^ {}&~"
Fred Drake30a68c71998-11-23 16:59:39 +000069
70
Fred Drakef79acbd1999-05-07 21:12:21 +000071def dbgmsg(msg):
Fred Draked7acf021999-01-14 17:38:12 +000072 if DEBUG:
Fred Drakef79acbd1999-05-07 21:12:21 +000073 sys.stderr.write(msg + "\n")
74
75def pushing(name, point, depth):
Fred Drake96e4a061999-07-29 22:22:13 +000076 dbgmsg("pushing <%s> at %s" % (name, point))
Fred Draked7acf021999-01-14 17:38:12 +000077
78def popping(name, point, depth):
Fred Drake96e4a061999-07-29 22:22:13 +000079 dbgmsg("popping </%s> at %s" % (name, point))
Fred Draked7acf021999-01-14 17:38:12 +000080
81
Fred Drake96e4a061999-07-29 22:22:13 +000082class _Stack(UserList.UserList):
Fred Drake96e4a061999-07-29 22:22:13 +000083 def append(self, entry):
Fred Drake4fbdf971999-08-02 14:35:25 +000084 if type(entry) is not StringType:
Fred Drake96e4a061999-07-29 22:22:13 +000085 raise LaTeXFormatError("cannot push non-string on stack: "
86 + `entry`)
87 sys.stderr.write("%s<%s>\n" % (" "*len(self.data), entry))
88 self.data.append(entry)
89
90 def pop(self, index=-1):
91 entry = self.data[index]
92 del self.data[index]
93 sys.stderr.write("%s</%s>\n" % (" "*len(self.data), entry))
94
95 def __delitem__(self, index):
96 entry = self.data[index]
97 del self.data[index]
98 sys.stderr.write("%s</%s>\n" % (" "*len(self.data), entry))
99
100
101def new_stack():
102 if DEBUG:
103 return _Stack()
104 return []
105
106
Fred Drake4fbdf971999-08-02 14:35:25 +0000107class Conversion:
108 def __init__(self, ifp, ofp, table):
109 self.write = ofp.write
110 self.ofp = ofp
Fred Drake96c00b01999-05-07 19:59:02 +0000111 self.table = table
Fred Drake96c00b01999-05-07 19:59:02 +0000112 self.line = string.join(map(string.rstrip, ifp.readlines()), "\n")
Fred Drake96c00b01999-05-07 19:59:02 +0000113 self.preamble = 1
Fred Drake96c00b01999-05-07 19:59:02 +0000114
Fred Drake96e4a061999-07-29 22:22:13 +0000115 def err_write(self, msg):
116 if DEBUG:
117 sys.stderr.write(str(msg) + "\n")
118
119 def convert(self):
120 self.subconvert()
121
Fred Drake96e4a061999-07-29 22:22:13 +0000122 def subconvert(self, endchar=None, depth=0):
123 #
124 # Parses content, including sub-structures, until the character
125 # 'endchar' is found (with no open structures), or until the end
126 # of the input data is endchar is None.
127 #
128 stack = new_stack()
129 line = self.line
130 while line:
131 if line[0] == endchar and not stack:
132 self.line = line
133 return line
134 m = _comment_rx.match(line)
135 if m:
136 text = m.group(1)
137 if text:
138 self.write("(COMMENT\n- %s \n)COMMENT\n-\\n\n"
139 % encode(text))
140 line = line[m.end():]
141 continue
142 m = _begin_env_rx.match(line)
143 if m:
144 name = m.group(1)
145 entry = self.get_env_entry(name)
146 # re-write to use the macro handler
147 line = r"\%s %s" % (name, line[m.end():])
148 continue
149 m = _end_env_rx.match(line)
150 if m:
151 # end of environment
152 envname = m.group(1)
153 entry = self.get_entry(envname)
154 while stack and envname != stack[-1] \
155 and stack[-1] in entry.endcloses:
156 self.write(")%s\n" % stack.pop())
157 if stack and envname == stack[-1]:
158 self.write(")%s\n" % entry.outputname)
159 del stack[-1]
160 else:
161 raise LaTeXStackError(envname, stack)
162 line = line[m.end():]
163 continue
164 m = _begin_macro_rx.match(line)
165 if m:
166 # start of macro
167 macroname = m.group(1)
168 entry = self.get_entry(macroname)
169 if entry.verbatim:
170 # magic case!
171 pos = string.find(line, "\\end{%s}" % macroname)
172 text = line[m.end(1):pos]
173 stack.append(entry.name)
174 self.write("(%s\n" % entry.outputname)
175 self.write("-%s\n" % encode(text))
176 self.write(")%s\n" % entry.outputname)
177 stack.pop()
178 line = line[pos + len("\\end{%s}" % macroname):]
179 continue
180 while stack and stack[-1] in entry.closes:
181 top = stack.pop()
182 topentry = self.get_entry(top)
183 if topentry.outputname:
184 self.write(")%s\n-\\n\n" % topentry.outputname)
185 #
186 if entry.outputname:
187 if entry.empty:
188 self.write("e\n")
Fred Drake96e4a061999-07-29 22:22:13 +0000189 #
190 params, optional, empty, environ = self.start_macro(macroname)
191 # rip off the macroname
192 if params:
193 line = line[m.end(1):]
194 elif empty:
195 line = line[m.end(1):]
196 else:
197 line = line[m.end():]
198 opened = 0
199 implied_content = 0
200
201 # handle attribute mappings here:
202 for pentry in params:
203 if pentry.type == "attribute":
204 if pentry.optional:
205 m = _optional_rx.match(line)
Fred Drake4fbdf971999-08-02 14:35:25 +0000206 if m and entry.outputname:
Fred Drake96e4a061999-07-29 22:22:13 +0000207 line = line[m.end():]
208 self.dump_attr(pentry, m.group(1))
Fred Drake4fbdf971999-08-02 14:35:25 +0000209 elif pentry.text and entry.outputname:
Fred Drake96e4a061999-07-29 22:22:13 +0000210 # value supplied by conversion spec:
211 self.dump_attr(pentry, pentry.text)
212 else:
213 m = _parameter_rx.match(line)
214 if not m:
215 raise LaTeXFormatError(
216 "could not extract parameter %s for %s: %s"
217 % (pentry.name, macroname, `line[:100]`))
Fred Drake4fbdf971999-08-02 14:35:25 +0000218 if entry.outputname:
219 self.dump_attr(pentry, m.group(1))
Fred Drake96e4a061999-07-29 22:22:13 +0000220 line = line[m.end():]
221 elif pentry.type == "child":
222 if pentry.optional:
223 m = _optional_rx.match(line)
224 if m:
225 line = line[m.end():]
226 if entry.outputname and not opened:
227 opened = 1
228 self.write("(%s\n" % entry.outputname)
229 stack.append(macroname)
230 stack.append(pentry.name)
231 self.write("(%s\n" % pentry.name)
232 self.write("-%s\n" % encode(m.group(1)))
233 self.write(")%s\n" % pentry.name)
234 stack.pop()
235 else:
236 if entry.outputname and not opened:
237 opened = 1
238 self.write("(%s\n" % entry.outputname)
239 stack.append(entry.name)
240 self.write("(%s\n" % pentry.name)
241 stack.append(pentry.name)
242 self.line = skip_white(line)[1:]
243 line = self.subconvert(
244 "}", len(stack) + depth + 1)[1:]
245 self.write(")%s\n" % stack.pop())
246 elif pentry.type == "content":
247 if pentry.implied:
248 implied_content = 1
249 else:
250 if entry.outputname and not opened:
251 opened = 1
252 self.write("(%s\n" % entry.outputname)
253 stack.append(entry.name)
254 line = skip_white(line)
255 if line[0] != "{":
256 raise LaTeXFormatError(
257 "missing content for " + macroname)
258 self.line = line[1:]
259 line = self.subconvert("}", len(stack) + depth + 1)
260 if line and line[0] == "}":
261 line = line[1:]
Fred Drake4fbdf971999-08-02 14:35:25 +0000262 elif pentry.type == "text" and pentry.text:
263 if entry.outputname and not opened:
264 opened = 1
265 stack.append(entry.name)
266 self.write("(%s\n" % entry.outputname)
267 self.err_write("--- text: %s\n" % `pentry.text`)
268 self.write("-%s\n" % encode(pentry.text))
Fred Drake96e4a061999-07-29 22:22:13 +0000269 if entry.outputname:
270 if not opened:
271 self.write("(%s\n" % entry.outputname)
272 stack.append(entry.name)
273 if not implied_content:
274 self.write(")%s\n" % entry.outputname)
275 stack.pop()
Fred Drake96e4a061999-07-29 22:22:13 +0000276 continue
277 if line[0] == endchar and not stack:
278 self.line = line[1:]
279 return self.line
280 if line[0] == "}":
281 # end of macro or group
282 macroname = stack[-1]
283 if macroname:
284 conversion = self.table.get(macroname)
285 if conversion.outputname:
286 # otherwise, it was just a bare group
287 self.write(")%s\n" % conversion.outputname)
288 del stack[-1]
289 line = line[1:]
290 continue
291 if line[0] == "{":
292 stack.append("")
293 line = line[1:]
294 continue
295 if line[0] == "\\" and line[1] in ESCAPED_CHARS:
296 self.write("-%s\n" % encode(line[1]))
297 line = line[2:]
298 continue
299 if line[:2] == r"\\":
300 self.write("(BREAK\n)BREAK\n")
301 line = line[2:]
302 continue
303 m = _text_rx.match(line)
304 if m:
305 text = encode(m.group())
306 self.write("-%s\n" % text)
307 line = line[m.end():]
308 continue
309 # special case because of \item[]
310 # XXX can we axe this???
311 if line[0] == "]":
312 self.write("-]\n")
313 line = line[1:]
314 continue
315 # avoid infinite loops
316 extra = ""
317 if len(line) > 100:
318 extra = "..."
319 raise LaTeXFormatError("could not identify markup: %s%s"
320 % (`line[:100]`, extra))
321 while stack:
322 entry = self.get_entry(stack[-1])
323 if entry.closes:
324 self.write(")%s\n-%s\n" % (entry.outputname, encode("\n")))
325 del stack[-1]
326 else:
327 break
328 if stack:
329 raise LaTeXFormatError("elements remain on stack: "
330 + string.join(stack, ", "))
331 # otherwise we just ran out of input here...
332
333 def start_macro(self, name):
334 conversion = self.get_entry(name)
335 parameters = conversion.parameters
336 optional = parameters and parameters[0].optional
Fred Drake96e4a061999-07-29 22:22:13 +0000337 return parameters, optional, conversion.empty, conversion.environment
338
339 def get_entry(self, name):
340 entry = self.table.get(name)
341 if entry is None:
342 self.err_write("get_entry(%s) failing; building default entry!"
343 % `name`)
344 # not defined; build a default entry:
345 entry = TableEntry(name)
346 entry.has_content = 1
347 entry.parameters.append(Parameter("content"))
348 self.table[name] = entry
349 return entry
350
351 def get_env_entry(self, name):
352 entry = self.table.get(name)
353 if entry is None:
354 # not defined; build a default entry:
355 entry = TableEntry(name, 1)
356 entry.has_content = 1
357 entry.parameters.append(Parameter("content"))
358 entry.parameters[-1].implied = 1
359 self.table[name] = entry
360 elif not entry.environment:
361 raise LaTeXFormatError(
362 name + " is defined as a macro; expected environment")
363 return entry
364
365 def dump_attr(self, pentry, value):
366 if not (pentry.name and value):
367 return
368 if _token_rx.match(value):
369 dtype = "TOKEN"
370 else:
371 dtype = "CDATA"
372 self.write("A%s %s %s\n" % (pentry.name, dtype, encode(value)))
373
374
Fred Drakeeac8abe1999-07-29 22:42:27 +0000375def convert(ifp, ofp, table):
376 c = Conversion(ifp, ofp, table)
Fred Drake96e4a061999-07-29 22:22:13 +0000377 try:
378 c.convert()
379 except IOError, (err, msg):
380 if err != errno.EPIPE:
381 raise
382
383
Fred Draked7acf021999-01-14 17:38:12 +0000384def skip_white(line):
Fred Drake96e4a061999-07-29 22:22:13 +0000385 while line and line[0] in " %\n\t\r":
Fred Draked7acf021999-01-14 17:38:12 +0000386 line = string.lstrip(line[1:])
387 return line
388
389
Fred Drake96e4a061999-07-29 22:22:13 +0000390
391class TableEntry:
392 def __init__(self, name, environment=0):
393 self.name = name
394 self.outputname = name
395 self.environment = environment
396 self.empty = not environment
397 self.has_content = 0
398 self.verbatim = 0
399 self.auto_close = 0
400 self.parameters = []
401 self.closes = []
402 self.endcloses = []
403
404class Parameter:
405 def __init__(self, type, name=None, optional=0):
406 self.type = type
407 self.name = name
408 self.optional = optional
409 self.text = ''
410 self.implied = 0
411
412
413class TableParser(XMLParser):
Fred Drake4fbdf971999-08-02 14:35:25 +0000414 def __init__(self, table=None):
415 if table is None:
416 table = {}
417 self.__table = table
Fred Drake96e4a061999-07-29 22:22:13 +0000418 self.__current = None
419 self.__buffer = ''
420 XMLParser.__init__(self)
421
422 def get_table(self):
423 for entry in self.__table.values():
424 if entry.environment and not entry.has_content:
425 p = Parameter("content")
426 p.implied = 1
427 entry.parameters.append(p)
428 entry.has_content = 1
429 return self.__table
430
431 def start_environment(self, attrs):
432 name = attrs["name"]
433 self.__current = TableEntry(name, environment=1)
434 self.__current.verbatim = attrs.get("verbatim") == "yes"
435 if attrs.has_key("outputname"):
436 self.__current.outputname = attrs.get("outputname")
437 self.__current.endcloses = string.split(attrs.get("endcloses", ""))
438 def end_environment(self):
439 self.end_macro()
440
441 def start_macro(self, attrs):
442 name = attrs["name"]
443 self.__current = TableEntry(name)
444 self.__current.closes = string.split(attrs.get("closes", ""))
445 if attrs.has_key("outputname"):
446 self.__current.outputname = attrs.get("outputname")
447 def end_macro(self):
Fred Drake96e4a061999-07-29 22:22:13 +0000448 self.__table[self.__current.name] = self.__current
449 self.__current = None
450
451 def start_attribute(self, attrs):
452 name = attrs.get("name")
453 optional = attrs.get("optional") == "yes"
454 if name:
455 p = Parameter("attribute", name, optional=optional)
456 else:
457 p = Parameter("attribute", optional=optional)
458 self.__current.parameters.append(p)
459 self.__buffer = ''
460 def end_attribute(self):
461 self.__current.parameters[-1].text = self.__buffer
462
463 def start_child(self, attrs):
464 name = attrs["name"]
465 p = Parameter("child", name, attrs.get("optional") == "yes")
466 self.__current.parameters.append(p)
467 self.__current.empty = 0
468
469 def start_content(self, attrs):
470 p = Parameter("content")
471 p.implied = attrs.get("implied") == "yes"
472 if self.__current.environment:
473 p.implied = 1
474 self.__current.parameters.append(p)
475 self.__current.has_content = 1
476 self.__current.empty = 0
477
478 def start_text(self, attrs):
Fred Drake4fbdf971999-08-02 14:35:25 +0000479 self.__current.empty = 0
Fred Drake96e4a061999-07-29 22:22:13 +0000480 self.__buffer = ''
481 def end_text(self):
482 p = Parameter("text")
483 p.text = self.__buffer
484 self.__current.parameters.append(p)
485
486 def handle_data(self, data):
487 self.__buffer = self.__buffer + data
488
489
Fred Drake4fbdf971999-08-02 14:35:25 +0000490def load_table(fp, table=None):
491 parser = TableParser(table=table)
Fred Drake96e4a061999-07-29 22:22:13 +0000492 parser.feed(fp.read())
493 parser.close()
494 return parser.get_table()
495
496
Fred Drake30a68c71998-11-23 16:59:39 +0000497def main():
Fred Drake96e4a061999-07-29 22:22:13 +0000498 global DEBUG
499 #
Fred Drakeeac8abe1999-07-29 22:42:27 +0000500 opts, args = getopt.getopt(sys.argv[1:], "D", ["debug"])
Fred Drake96e4a061999-07-29 22:22:13 +0000501 for opt, arg in opts:
Fred Drakeeac8abe1999-07-29 22:42:27 +0000502 if opt in ("-D", "--debug"):
Fred Drake96e4a061999-07-29 22:22:13 +0000503 DEBUG = DEBUG + 1
504 if len(args) == 0:
505 ifp = sys.stdin
Fred Drake30a68c71998-11-23 16:59:39 +0000506 ofp = sys.stdout
Fred Drake96e4a061999-07-29 22:22:13 +0000507 elif len(args) == 1:
508 ifp = open(args)
509 ofp = sys.stdout
510 elif len(args) == 2:
511 ifp = open(args[0])
512 ofp = open(args[1], "w")
Fred Drake30a68c71998-11-23 16:59:39 +0000513 else:
514 usage()
515 sys.exit(2)
Fred Drakeeac8abe1999-07-29 22:42:27 +0000516
517 table = load_table(open(os.path.join(sys.path[0], 'conversion.xml')))
518 convert(ifp, ofp, table)
Fred Drake30a68c71998-11-23 16:59:39 +0000519
520
521if __name__ == "__main__":
522 main()