blob: c33c4d596def9465c2552a793d3c1f4db850360a [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"""
Fred Drake30a68c71998-11-23 16:59:39 +000017
18import errno
Fred Drake96e4a061999-07-29 22:22:13 +000019import getopt
20import os
Fred Drake30a68c71998-11-23 16:59:39 +000021import re
22import string
Fred Drake30a68c71998-11-23 16:59:39 +000023import sys
Fred Drake96e4a061999-07-29 22:22:13 +000024import UserList
Fred Drake691a5a72000-11-22 17:56:43 +000025import xml.sax.saxutils
Fred Drake30a68c71998-11-23 16:59:39 +000026
Fred Drake54fb7fb1999-05-10 19:36:03 +000027from types import ListType, StringType, TupleType
Fred Drakeaeea9811998-12-01 19:04:12 +000028
Fred Drake96e4a061999-07-29 22:22:13 +000029try:
30 from xml.parsers.xmllib import XMLParser
31except ImportError:
32 from xmllib import XMLParser
33
Fred Drake30a68c71998-11-23 16:59:39 +000034
Fred Drake2262a802001-03-23 16:53:34 +000035from esistools import encode
36
37
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 Drake691a5a72000-11-22 17:56:43 +000058_text_rx = re.compile(r"[^]~%\\{}]+")
Fred Drakeb5fc0ab2001-07-06 21:01:19 +000059_optional_rx = re.compile(r"\s*[[]([^]]*)[]]", re.MULTILINE)
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`)
Fred Drake2262a802001-03-23 16:53:34 +000087 #dbgmsg("%s<%s>" % (" "*len(self.data), entry))
Fred Drake96e4a061999-07-29 22:22:13 +000088 self.data.append(entry)
89
90 def pop(self, index=-1):
91 entry = self.data[index]
92 del self.data[index]
Fred Drake2262a802001-03-23 16:53:34 +000093 #dbgmsg("%s</%s>" % (" "*len(self.data), entry))
Fred Drake96e4a061999-07-29 22:22:13 +000094
95 def __delitem__(self, index):
96 entry = self.data[index]
97 del self.data[index]
Fred Drake2262a802001-03-23 16:53:34 +000098 #dbgmsg("%s</%s>" % (" "*len(self.data), entry))
Fred Drake96e4a061999-07-29 22:22:13 +000099
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 convert(self):
116 self.subconvert()
117
Fred Drake96e4a061999-07-29 22:22:13 +0000118 def subconvert(self, endchar=None, depth=0):
119 #
120 # Parses content, including sub-structures, until the character
121 # 'endchar' is found (with no open structures), or until the end
122 # of the input data is endchar is None.
123 #
124 stack = new_stack()
125 line = self.line
126 while line:
127 if line[0] == endchar and not stack:
128 self.line = line
129 return line
130 m = _comment_rx.match(line)
131 if m:
132 text = m.group(1)
133 if text:
134 self.write("(COMMENT\n- %s \n)COMMENT\n-\\n\n"
135 % encode(text))
136 line = line[m.end():]
137 continue
138 m = _begin_env_rx.match(line)
139 if m:
140 name = m.group(1)
141 entry = self.get_env_entry(name)
142 # re-write to use the macro handler
143 line = r"\%s %s" % (name, line[m.end():])
144 continue
145 m = _end_env_rx.match(line)
146 if m:
147 # end of environment
148 envname = m.group(1)
149 entry = self.get_entry(envname)
150 while stack and envname != stack[-1] \
151 and stack[-1] in entry.endcloses:
152 self.write(")%s\n" % stack.pop())
153 if stack and envname == stack[-1]:
154 self.write(")%s\n" % entry.outputname)
155 del stack[-1]
156 else:
157 raise LaTeXStackError(envname, stack)
158 line = line[m.end():]
159 continue
160 m = _begin_macro_rx.match(line)
161 if m:
162 # start of macro
163 macroname = m.group(1)
Fred Drake691a5a72000-11-22 17:56:43 +0000164 if macroname == "c":
165 # Ugh! This is a combining character...
166 endpos = m.end()
167 self.combining_char("c", line[endpos])
168 line = line[endpos + 1:]
169 continue
Fred Drake96e4a061999-07-29 22:22:13 +0000170 entry = self.get_entry(macroname)
171 if entry.verbatim:
172 # magic case!
173 pos = string.find(line, "\\end{%s}" % macroname)
174 text = line[m.end(1):pos]
175 stack.append(entry.name)
176 self.write("(%s\n" % entry.outputname)
177 self.write("-%s\n" % encode(text))
178 self.write(")%s\n" % entry.outputname)
179 stack.pop()
180 line = line[pos + len("\\end{%s}" % macroname):]
181 continue
182 while stack and stack[-1] in entry.closes:
183 top = stack.pop()
184 topentry = self.get_entry(top)
185 if topentry.outputname:
186 self.write(")%s\n-\\n\n" % topentry.outputname)
187 #
Fred Drake9eda3ae2001-09-25 20:57:36 +0000188 if entry.outputname and entry.empty:
189 self.write("e\n")
Fred Drake96e4a061999-07-29 22:22:13 +0000190 #
Fred Drake9eda3ae2001-09-25 20:57:36 +0000191 params, optional, empty = self.start_macro(macroname)
Fred Drake96e4a061999-07-29 22:22:13 +0000192 # rip off the macroname
193 if params:
194 line = line[m.end(1):]
195 elif empty:
196 line = line[m.end(1):]
197 else:
198 line = line[m.end():]
199 opened = 0
200 implied_content = 0
201
202 # handle attribute mappings here:
203 for pentry in params:
204 if pentry.type == "attribute":
205 if pentry.optional:
206 m = _optional_rx.match(line)
Fred Drake4fbdf971999-08-02 14:35:25 +0000207 if m and entry.outputname:
Fred Drake96e4a061999-07-29 22:22:13 +0000208 line = line[m.end():]
209 self.dump_attr(pentry, m.group(1))
Fred Drake4fbdf971999-08-02 14:35:25 +0000210 elif pentry.text and entry.outputname:
Fred Drake96e4a061999-07-29 22:22:13 +0000211 # value supplied by conversion spec:
212 self.dump_attr(pentry, pentry.text)
213 else:
214 m = _parameter_rx.match(line)
215 if not m:
216 raise LaTeXFormatError(
217 "could not extract parameter %s for %s: %s"
218 % (pentry.name, macroname, `line[:100]`))
Fred Drake4fbdf971999-08-02 14:35:25 +0000219 if entry.outputname:
220 self.dump_attr(pentry, m.group(1))
Fred Drake96e4a061999-07-29 22:22:13 +0000221 line = line[m.end():]
222 elif pentry.type == "child":
223 if pentry.optional:
224 m = _optional_rx.match(line)
225 if m:
226 line = line[m.end():]
227 if entry.outputname and not opened:
228 opened = 1
229 self.write("(%s\n" % entry.outputname)
230 stack.append(macroname)
231 stack.append(pentry.name)
232 self.write("(%s\n" % pentry.name)
233 self.write("-%s\n" % encode(m.group(1)))
234 self.write(")%s\n" % pentry.name)
235 stack.pop()
236 else:
237 if entry.outputname and not opened:
238 opened = 1
239 self.write("(%s\n" % entry.outputname)
240 stack.append(entry.name)
241 self.write("(%s\n" % pentry.name)
242 stack.append(pentry.name)
243 self.line = skip_white(line)[1:]
244 line = self.subconvert(
245 "}", len(stack) + depth + 1)[1:]
246 self.write(")%s\n" % stack.pop())
247 elif pentry.type == "content":
248 if pentry.implied:
249 implied_content = 1
250 else:
251 if entry.outputname and not opened:
252 opened = 1
253 self.write("(%s\n" % entry.outputname)
254 stack.append(entry.name)
255 line = skip_white(line)
256 if line[0] != "{":
257 raise LaTeXFormatError(
258 "missing content for " + macroname)
259 self.line = line[1:]
260 line = self.subconvert("}", len(stack) + depth + 1)
261 if line and line[0] == "}":
262 line = line[1:]
Fred Drake4fbdf971999-08-02 14:35:25 +0000263 elif pentry.type == "text" and pentry.text:
264 if entry.outputname and not opened:
265 opened = 1
266 stack.append(entry.name)
267 self.write("(%s\n" % entry.outputname)
Fred Drake2262a802001-03-23 16:53:34 +0000268 #dbgmsg("--- text: %s" % `pentry.text`)
Fred Drake4fbdf971999-08-02 14:35:25 +0000269 self.write("-%s\n" % encode(pentry.text))
Fred Drakef6199ed1999-08-26 17:54:16 +0000270 elif pentry.type == "entityref":
271 self.write("&%s\n" % pentry.name)
Fred Drake96e4a061999-07-29 22:22:13 +0000272 if entry.outputname:
273 if not opened:
274 self.write("(%s\n" % entry.outputname)
275 stack.append(entry.name)
276 if not implied_content:
277 self.write(")%s\n" % entry.outputname)
278 stack.pop()
Fred Drake96e4a061999-07-29 22:22:13 +0000279 continue
280 if line[0] == endchar and not stack:
281 self.line = line[1:]
282 return self.line
283 if line[0] == "}":
284 # end of macro or group
285 macroname = stack[-1]
286 if macroname:
Fred Drake2262a802001-03-23 16:53:34 +0000287 conversion = self.table[macroname]
Fred Drake96e4a061999-07-29 22:22:13 +0000288 if conversion.outputname:
289 # otherwise, it was just a bare group
290 self.write(")%s\n" % conversion.outputname)
291 del stack[-1]
292 line = line[1:]
293 continue
Fred Drake691a5a72000-11-22 17:56:43 +0000294 if line[0] == "~":
295 # don't worry about the "tie" aspect of this command
296 line = line[1:]
297 self.write("- \n")
298 continue
Fred Drake96e4a061999-07-29 22:22:13 +0000299 if line[0] == "{":
300 stack.append("")
301 line = line[1:]
302 continue
303 if line[0] == "\\" and line[1] in ESCAPED_CHARS:
304 self.write("-%s\n" % encode(line[1]))
305 line = line[2:]
306 continue
307 if line[:2] == r"\\":
308 self.write("(BREAK\n)BREAK\n")
309 line = line[2:]
310 continue
Fred Drake691a5a72000-11-22 17:56:43 +0000311 if line[:2] == r"\_":
312 line = "_" + line[2:]
313 continue
314 if line[:2] in (r"\'", r'\"'):
315 # combining characters...
316 self.combining_char(line[1], line[2])
317 line = line[3:]
318 continue
Fred Drake96e4a061999-07-29 22:22:13 +0000319 m = _text_rx.match(line)
320 if m:
321 text = encode(m.group())
322 self.write("-%s\n" % text)
323 line = line[m.end():]
324 continue
325 # special case because of \item[]
326 # XXX can we axe this???
327 if line[0] == "]":
328 self.write("-]\n")
329 line = line[1:]
330 continue
331 # avoid infinite loops
332 extra = ""
333 if len(line) > 100:
334 extra = "..."
335 raise LaTeXFormatError("could not identify markup: %s%s"
336 % (`line[:100]`, extra))
337 while stack:
338 entry = self.get_entry(stack[-1])
339 if entry.closes:
340 self.write(")%s\n-%s\n" % (entry.outputname, encode("\n")))
341 del stack[-1]
342 else:
343 break
344 if stack:
345 raise LaTeXFormatError("elements remain on stack: "
346 + string.join(stack, ", "))
347 # otherwise we just ran out of input here...
348
Fred Drake691a5a72000-11-22 17:56:43 +0000349 # This is a really limited table of combinations, but it will have
350 # to do for now.
351 _combinations = {
352 ("c", "c"): 0x00E7,
353 ("'", "e"): 0x00E9,
354 ('"', "o"): 0x00F6,
355 }
356
357 def combining_char(self, prefix, char):
358 ordinal = self._combinations[(prefix, char)]
359 self.write("-\\%%%d;\n" % ordinal)
360
Fred Drake96e4a061999-07-29 22:22:13 +0000361 def start_macro(self, name):
362 conversion = self.get_entry(name)
363 parameters = conversion.parameters
364 optional = parameters and parameters[0].optional
Fred Drake9eda3ae2001-09-25 20:57:36 +0000365 return parameters, optional, conversion.empty
Fred Drake96e4a061999-07-29 22:22:13 +0000366
367 def get_entry(self, name):
368 entry = self.table.get(name)
369 if entry is None:
Fred Drake2262a802001-03-23 16:53:34 +0000370 dbgmsg("get_entry(%s) failing; building default entry!" % `name`)
Fred Drake96e4a061999-07-29 22:22:13 +0000371 # not defined; build a default entry:
372 entry = TableEntry(name)
373 entry.has_content = 1
374 entry.parameters.append(Parameter("content"))
375 self.table[name] = entry
376 return entry
377
378 def get_env_entry(self, name):
379 entry = self.table.get(name)
380 if entry is None:
381 # not defined; build a default entry:
382 entry = TableEntry(name, 1)
383 entry.has_content = 1
384 entry.parameters.append(Parameter("content"))
385 entry.parameters[-1].implied = 1
386 self.table[name] = entry
387 elif not entry.environment:
388 raise LaTeXFormatError(
389 name + " is defined as a macro; expected environment")
390 return entry
391
392 def dump_attr(self, pentry, value):
393 if not (pentry.name and value):
394 return
395 if _token_rx.match(value):
396 dtype = "TOKEN"
397 else:
398 dtype = "CDATA"
399 self.write("A%s %s %s\n" % (pentry.name, dtype, encode(value)))
400
401
Fred Drakeeac8abe1999-07-29 22:42:27 +0000402def convert(ifp, ofp, table):
403 c = Conversion(ifp, ofp, table)
Fred Drake96e4a061999-07-29 22:22:13 +0000404 try:
405 c.convert()
406 except IOError, (err, msg):
407 if err != errno.EPIPE:
408 raise
409
410
Fred Draked7acf021999-01-14 17:38:12 +0000411def skip_white(line):
Fred Drake96e4a061999-07-29 22:22:13 +0000412 while line and line[0] in " %\n\t\r":
Fred Draked7acf021999-01-14 17:38:12 +0000413 line = string.lstrip(line[1:])
414 return line
415
416
Fred Drake96e4a061999-07-29 22:22:13 +0000417
418class TableEntry:
419 def __init__(self, name, environment=0):
420 self.name = name
421 self.outputname = name
422 self.environment = environment
423 self.empty = not environment
424 self.has_content = 0
425 self.verbatim = 0
426 self.auto_close = 0
427 self.parameters = []
428 self.closes = []
429 self.endcloses = []
430
431class Parameter:
432 def __init__(self, type, name=None, optional=0):
433 self.type = type
434 self.name = name
435 self.optional = optional
436 self.text = ''
437 self.implied = 0
438
439
440class TableParser(XMLParser):
Fred Drake4fbdf971999-08-02 14:35:25 +0000441 def __init__(self, table=None):
442 if table is None:
443 table = {}
444 self.__table = table
Fred Drake96e4a061999-07-29 22:22:13 +0000445 self.__current = None
446 self.__buffer = ''
447 XMLParser.__init__(self)
448
449 def get_table(self):
450 for entry in self.__table.values():
451 if entry.environment and not entry.has_content:
452 p = Parameter("content")
453 p.implied = 1
454 entry.parameters.append(p)
455 entry.has_content = 1
456 return self.__table
457
458 def start_environment(self, attrs):
459 name = attrs["name"]
460 self.__current = TableEntry(name, environment=1)
461 self.__current.verbatim = attrs.get("verbatim") == "yes"
462 if attrs.has_key("outputname"):
463 self.__current.outputname = attrs.get("outputname")
464 self.__current.endcloses = string.split(attrs.get("endcloses", ""))
465 def end_environment(self):
466 self.end_macro()
467
468 def start_macro(self, attrs):
469 name = attrs["name"]
470 self.__current = TableEntry(name)
471 self.__current.closes = string.split(attrs.get("closes", ""))
472 if attrs.has_key("outputname"):
473 self.__current.outputname = attrs.get("outputname")
474 def end_macro(self):
Fred Drake96e4a061999-07-29 22:22:13 +0000475 self.__table[self.__current.name] = self.__current
476 self.__current = None
477
478 def start_attribute(self, attrs):
479 name = attrs.get("name")
480 optional = attrs.get("optional") == "yes"
481 if name:
482 p = Parameter("attribute", name, optional=optional)
483 else:
484 p = Parameter("attribute", optional=optional)
485 self.__current.parameters.append(p)
486 self.__buffer = ''
487 def end_attribute(self):
488 self.__current.parameters[-1].text = self.__buffer
489
Fred Drakef6199ed1999-08-26 17:54:16 +0000490 def start_entityref(self, attrs):
491 name = attrs["name"]
492 p = Parameter("entityref", name)
493 self.__current.parameters.append(p)
494
Fred Drake96e4a061999-07-29 22:22:13 +0000495 def start_child(self, attrs):
496 name = attrs["name"]
497 p = Parameter("child", name, attrs.get("optional") == "yes")
498 self.__current.parameters.append(p)
499 self.__current.empty = 0
500
501 def start_content(self, attrs):
502 p = Parameter("content")
503 p.implied = attrs.get("implied") == "yes"
504 if self.__current.environment:
505 p.implied = 1
506 self.__current.parameters.append(p)
507 self.__current.has_content = 1
508 self.__current.empty = 0
509
510 def start_text(self, attrs):
Fred Drake4fbdf971999-08-02 14:35:25 +0000511 self.__current.empty = 0
Fred Drake96e4a061999-07-29 22:22:13 +0000512 self.__buffer = ''
513 def end_text(self):
514 p = Parameter("text")
515 p.text = self.__buffer
516 self.__current.parameters.append(p)
517
518 def handle_data(self, data):
519 self.__buffer = self.__buffer + data
520
521
Fred Drake4fbdf971999-08-02 14:35:25 +0000522def load_table(fp, table=None):
523 parser = TableParser(table=table)
Fred Drake96e4a061999-07-29 22:22:13 +0000524 parser.feed(fp.read())
525 parser.close()
526 return parser.get_table()
527
528
Fred Drake30a68c71998-11-23 16:59:39 +0000529def main():
Fred Drake96e4a061999-07-29 22:22:13 +0000530 global DEBUG
531 #
Fred Drakeeac8abe1999-07-29 22:42:27 +0000532 opts, args = getopt.getopt(sys.argv[1:], "D", ["debug"])
Fred Drake96e4a061999-07-29 22:22:13 +0000533 for opt, arg in opts:
Fred Drakeeac8abe1999-07-29 22:42:27 +0000534 if opt in ("-D", "--debug"):
Fred Drake96e4a061999-07-29 22:22:13 +0000535 DEBUG = DEBUG + 1
536 if len(args) == 0:
537 ifp = sys.stdin
Fred Drake30a68c71998-11-23 16:59:39 +0000538 ofp = sys.stdout
Fred Drake96e4a061999-07-29 22:22:13 +0000539 elif len(args) == 1:
540 ifp = open(args)
541 ofp = sys.stdout
542 elif len(args) == 2:
543 ifp = open(args[0])
544 ofp = open(args[1], "w")
Fred Drake30a68c71998-11-23 16:59:39 +0000545 else:
546 usage()
547 sys.exit(2)
Fred Drakeeac8abe1999-07-29 22:42:27 +0000548
549 table = load_table(open(os.path.join(sys.path[0], 'conversion.xml')))
550 convert(ifp, ofp, table)
Fred Drake30a68c71998-11-23 16:59:39 +0000551
552
553if __name__ == "__main__":
554 main()