blob: bee99fa4a8c40c4e43ee7380049073a2d7264a66 [file] [log] [blame]
Fred Drake03204731998-11-23 17:02:03 +00001#! /usr/bin/env python
2
Fred Drake7dab6af1999-01-28 23:59:58 +00003"""Perform massive transformations on a document tree created from the LaTeX
4of the Python documentation, and dump the ESIS data for the transformed tree.
Fred Drake03204731998-11-23 17:02:03 +00005"""
6__version__ = '$Revision$'
7
8
9import errno
Fred Drake4db5b461998-12-01 19:03:01 +000010import esistools
11import re
Fred Drake03204731998-11-23 17:02:03 +000012import string
13import sys
14import xml.dom.core
15import xml.dom.esis_builder
16
17
Fred Drakef8ebb551999-01-14 19:45:38 +000018class ConversionError(Exception):
19 pass
20
21
Fred Drakefcc59101999-01-06 22:50:52 +000022DEBUG_PARA_FIXER = 0
23
Fred Drake7dab6af1999-01-28 23:59:58 +000024if DEBUG_PARA_FIXER:
25 def para_msg(s):
26 sys.stderr.write("*** %s\n" % s)
27else:
28 def para_msg(s):
29 pass
30
Fred Drakefcc59101999-01-06 22:50:52 +000031
Fred Drake03204731998-11-23 17:02:03 +000032# Workaround to deal with invalid documents (multiple root elements). This
33# does not indicate a bug in the DOM implementation.
34#
35def get_documentElement(self):
36 docelem = None
37 for n in self._node.children:
38 if n.type == xml.dom.core.ELEMENT:
39 docelem = xml.dom.core.Element(n, self, self)
40 return docelem
41
42xml.dom.core.Document.get_documentElement = get_documentElement
43
44
45# Replace get_childNodes for the Document class; without this, children
46# accessed from the Document object via .childNodes (no matter how many
47# levels of access are used) will be given an ownerDocument of None.
48#
49def get_childNodes(self):
50 return xml.dom.core.NodeList(self._node.children, self, self)
51
52xml.dom.core.Document.get_childNodes = get_childNodes
53
54
55def get_first_element(doc, gi):
56 for n in doc.childNodes:
57 if n.nodeType == xml.dom.core.ELEMENT and n.tagName == gi:
58 return n
59
60def extract_first_element(doc, gi):
61 node = get_first_element(doc, gi)
62 if node is not None:
63 doc.removeChild(node)
64 return node
65
66
Fred Drake7dab6af1999-01-28 23:59:58 +000067def find_all_elements(doc, gi):
68 nodes = []
69 if doc.nodeType == xml.dom.core.ELEMENT and doc.tagName == gi:
70 nodes.append(doc)
71 for child in doc.childNodes:
72 if child.nodeType == xml.dom.core.ELEMENT:
73 if child.tagName == gi:
74 nodes.append(child)
75 for node in child.getElementsByTagName(gi):
76 nodes.append(node)
77 return nodes
78
79
Fred Drake03204731998-11-23 17:02:03 +000080def simplify(doc):
81 # Try to rationalize the document a bit, since these things are simply
82 # not valid SGML/XML documents as they stand, and need a little work.
83 documentclass = "document"
84 inputs = []
85 node = extract_first_element(doc, "documentclass")
86 if node is not None:
87 documentclass = node.getAttribute("classname")
88 node = extract_first_element(doc, "title")
89 if node is not None:
90 inputs.append(node)
91 # update the name of the root element
92 node = get_first_element(doc, "document")
93 if node is not None:
94 node._node.name = documentclass
95 while 1:
96 node = extract_first_element(doc, "input")
97 if node is None:
98 break
99 inputs.append(node)
100 if inputs:
101 docelem = doc.documentElement
102 inputs.reverse()
103 for node in inputs:
104 text = doc.createTextNode("\n")
105 docelem.insertBefore(text, docelem.firstChild)
106 docelem.insertBefore(node, text)
107 docelem.insertBefore(doc.createTextNode("\n"), docelem.firstChild)
108 while doc.firstChild.nodeType == xml.dom.core.TEXT:
109 doc.removeChild(doc.firstChild)
110
111
112def cleanup_root_text(doc):
113 discards = []
114 skip = 0
115 for n in doc.childNodes:
116 prevskip = skip
117 skip = 0
118 if n.nodeType == xml.dom.core.TEXT and not prevskip:
119 discards.append(n)
Fred Drake4db5b461998-12-01 19:03:01 +0000120 elif n.nodeType == xml.dom.core.ELEMENT and n.tagName == "COMMENT":
Fred Drake03204731998-11-23 17:02:03 +0000121 skip = 1
122 for node in discards:
123 doc.removeChild(node)
124
125
Fred Drakecb657811999-01-29 20:55:07 +0000126DESCRIPTOR_ELEMENTS = (
127 "cfuncdesc", "cvardesc", "ctypedesc",
128 "classdesc", "memberdesc", "memberdescni", "methoddesc", "methoddescni",
129 "excdesc", "funcdesc", "funcdescni", "opcodedesc",
130 "datadesc", "datadescni",
131 )
132
133def fixup_descriptors(doc):
Fred Drake3a7ff991999-01-29 21:31:12 +0000134 sections = find_all_elements(doc, "section")
135 for section in sections:
136 find_and_fix_descriptors(doc, section)
137
138
139def find_and_fix_descriptors(doc, container):
140 children = container.childNodes
141 for child in children:
142 if child.nodeType == xml.dom.core.ELEMENT:
143 tagName = child.tagName
144 if tagName in DESCRIPTOR_ELEMENTS:
145 rewrite_descriptor(doc, child)
146 elif tagName == "subsection":
147 find_and_fix_descriptors(doc, child)
148
Fred Drakecb657811999-01-29 20:55:07 +0000149
150def rewrite_descriptor(doc, descriptor):
151 #
152 # Do these things:
153 # 1. Add an "index=noindex" attribute to the element if the tagName
154 # ends in 'ni', removing the 'ni' from the name.
155 # 2. Create a <signature> from the name attribute and <args>.
156 # 3. Create additional <signature>s from <*line{,ni}> elements,
157 # if found.
Fred Drake1dd152d1999-01-29 22:12:29 +0000158 # 4. If a <versionadded> is found, move it to an attribute on the
159 # descriptor.
160 # 5. Move remaining child nodes to a <description> element.
161 # 6. Put it back together.
Fred Drakecb657811999-01-29 20:55:07 +0000162 #
163 descname = descriptor.tagName
164 index = 1
165 if descname[-2:] == "ni":
166 descname = descname[:-2]
167 descriptor.setAttribute("index", "noindex")
168 descriptor._node.name = descname
169 index = 0
170 desctype = descname[:-4] # remove 'desc'
171 linename = desctype + "line"
172 if not index:
173 linename = linename + "ni"
174 # 2.
175 signature = doc.createElement("signature")
176 name = doc.createElement("name")
177 signature.appendChild(doc.createTextNode("\n "))
178 signature.appendChild(name)
179 name.appendChild(doc.createTextNode(descriptor.getAttribute("name")))
180 descriptor.removeAttribute("name")
181 if descriptor.attributes.has_key("var"):
182 variable = descriptor.getAttribute("var")
183 if variable:
184 args = doc.createElement("args")
185 args.appendChild(doc.createTextNode(variable))
Fred Drake7dab6af1999-01-28 23:59:58 +0000186 signature.appendChild(doc.createTextNode("\n "))
Fred Drakecb657811999-01-29 20:55:07 +0000187 signature.appendChild(args)
188 descriptor.removeAttribute("var")
189 newchildren = [signature]
190 children = descriptor.childNodes
191 pos = skip_leading_nodes(children, 0)
192 if pos < len(children):
193 child = children[pos]
194 if child.nodeType == xml.dom.core.ELEMENT and child.tagName == "args":
195 # create an <args> in <signature>:
196 args = doc.createElement("args")
197 argchildren = []
198 map(argchildren.append, child.childNodes)
199 for n in argchildren:
200 child.removeChild(n)
201 args.appendChild(n)
202 signature.appendChild(doc.createTextNode("\n "))
203 signature.appendChild(args)
204 signature.appendChild(doc.createTextNode("\n "))
Fred Drake1dd152d1999-01-29 22:12:29 +0000205 # 3, 4.
Fred Drakecb657811999-01-29 20:55:07 +0000206 pos = skip_leading_nodes(children, pos + 1)
207 while pos < len(children) \
208 and children[pos].nodeType == xml.dom.core.ELEMENT \
Fred Drake1dd152d1999-01-29 22:12:29 +0000209 and children[pos].tagName in (linename, "versionadded"):
210 if children[pos].tagName == linename:
211 # this is really a supplemental signature, create <signature>
212 sig = methodline_to_signature(doc, children[pos])
213 newchildren.append(sig)
214 else:
215 # <versionadded added=...>
216 descriptor.setAttribute(
217 "added", children[pos].getAttribute("version"))
Fred Drakecb657811999-01-29 20:55:07 +0000218 pos = skip_leading_nodes(children, pos + 1)
Fred Drake1dd152d1999-01-29 22:12:29 +0000219 # 5.
Fred Drakecb657811999-01-29 20:55:07 +0000220 description = doc.createElement("description")
221 description.appendChild(doc.createTextNode("\n"))
222 newchildren.append(description)
223 move_children(descriptor, description, pos)
224 last = description.childNodes[-1]
225 if last.nodeType == xml.dom.core.TEXT:
226 last.data = string.rstrip(last.data) + "\n "
Fred Drake1dd152d1999-01-29 22:12:29 +0000227 # 6.
Fred Drakecb657811999-01-29 20:55:07 +0000228 # should have nothing but whitespace and signature lines in <descriptor>;
229 # discard them
230 while descriptor.childNodes:
231 descriptor.removeChild(descriptor.childNodes[0])
232 for node in newchildren:
233 descriptor.appendChild(doc.createTextNode("\n "))
234 descriptor.appendChild(node)
235 descriptor.appendChild(doc.createTextNode("\n"))
Fred Drake03204731998-11-23 17:02:03 +0000236
Fred Drake7dab6af1999-01-28 23:59:58 +0000237
238def methodline_to_signature(doc, methodline):
239 signature = doc.createElement("signature")
240 signature.appendChild(doc.createTextNode("\n "))
241 name = doc.createElement("name")
242 name.appendChild(doc.createTextNode(methodline.getAttribute("name")))
Fred Drakecb657811999-01-29 20:55:07 +0000243 methodline.removeAttribute("name")
Fred Drake7dab6af1999-01-28 23:59:58 +0000244 signature.appendChild(name)
Fred Drake7dab6af1999-01-28 23:59:58 +0000245 if len(methodline.childNodes):
Fred Drakecb657811999-01-29 20:55:07 +0000246 args = doc.createElement("args")
Fred Drake7dab6af1999-01-28 23:59:58 +0000247 signature.appendChild(doc.createTextNode("\n "))
Fred Drakecb657811999-01-29 20:55:07 +0000248 signature.appendChild(args)
249 move_children(methodline, args)
Fred Drake7dab6af1999-01-28 23:59:58 +0000250 signature.appendChild(doc.createTextNode("\n "))
251 return signature
Fred Drake03204731998-11-23 17:02:03 +0000252
253
Fred Drakecb657811999-01-29 20:55:07 +0000254def move_children(origin, dest, start=0):
255 children = origin.childNodes
256 while start < len(children):
257 node = children[start]
258 origin.removeChild(node)
259 dest.appendChild(node)
260
261
Fred Drake4db5b461998-12-01 19:03:01 +0000262def handle_appendix(doc):
263 # must be called after simplfy() if document is multi-rooted to begin with
264 docelem = doc.documentElement
265 toplevel = docelem.tagName == "manual" and "chapter" or "section"
266 appendices = 0
267 nodes = []
268 for node in docelem.childNodes:
269 if appendices:
270 nodes.append(node)
271 elif node.nodeType == xml.dom.core.ELEMENT:
272 appnodes = node.getElementsByTagName("appendix")
273 if appnodes:
274 appendices = 1
275 parent = appnodes[0].parentNode
276 parent.removeChild(appnodes[0])
277 parent.normalize()
278 if nodes:
279 map(docelem.removeChild, nodes)
280 docelem.appendChild(doc.createTextNode("\n\n\n"))
281 back = doc.createElement("back-matter")
282 docelem.appendChild(back)
283 back.appendChild(doc.createTextNode("\n"))
284 while nodes and nodes[0].nodeType == xml.dom.core.TEXT \
285 and not string.strip(nodes[0].data):
286 del nodes[0]
287 map(back.appendChild, nodes)
288 docelem.appendChild(doc.createTextNode("\n"))
Fred Drake03204731998-11-23 17:02:03 +0000289
290
291def handle_labels(doc):
Fred Drake7dab6af1999-01-28 23:59:58 +0000292 for label in find_all_elements(doc, "label"):
293 id = label.getAttribute("id")
294 if not id:
295 continue
296 parent = label.parentNode
297 if parent.tagName == "title":
298 parent.parentNode.setAttribute("id", id)
299 else:
300 parent.setAttribute("id", id)
301 # now, remove <label id="..."/> from parent:
302 parent.removeChild(label)
Fred Drake03204731998-11-23 17:02:03 +0000303
304
Fred Drake1ff6db41998-11-23 23:10:35 +0000305def fixup_trailing_whitespace(doc, wsmap):
306 queue = [doc]
307 while queue:
308 node = queue[0]
309 del queue[0]
310 if node.nodeType == xml.dom.core.ELEMENT \
311 and wsmap.has_key(node.tagName):
312 ws = wsmap[node.tagName]
313 children = node.childNodes
314 children.reverse()
315 if children[0].nodeType == xml.dom.core.TEXT:
316 data = string.rstrip(children[0].data) + ws
317 children[0].data = data
318 children.reverse()
319 # hack to get the title in place:
320 if node.tagName == "title" \
321 and node.parentNode.firstChild.nodeType == xml.dom.core.ELEMENT:
322 node.parentNode.insertBefore(doc.createText("\n "),
323 node.parentNode.firstChild)
324 for child in node.childNodes:
325 if child.nodeType == xml.dom.core.ELEMENT:
326 queue.append(child)
327
328
329def normalize(doc):
330 for node in doc.childNodes:
331 if node.nodeType == xml.dom.core.ELEMENT:
332 node.normalize()
333
334
335def cleanup_trailing_parens(doc, element_names):
336 d = {}
337 for gi in element_names:
338 d[gi] = gi
339 rewrite_element = d.has_key
340 queue = []
341 for node in doc.childNodes:
342 if node.nodeType == xml.dom.core.ELEMENT:
343 queue.append(node)
344 while queue:
345 node = queue[0]
346 del queue[0]
347 if rewrite_element(node.tagName):
348 children = node.childNodes
349 if len(children) == 1 \
350 and children[0].nodeType == xml.dom.core.TEXT:
351 data = children[0].data
352 if data[-2:] == "()":
353 children[0].data = data[:-2]
354 else:
355 for child in node.childNodes:
356 if child.nodeType == xml.dom.core.ELEMENT:
357 queue.append(child)
358
359
Fred Drakeaaed9711998-12-10 20:25:30 +0000360def contents_match(left, right):
361 left_children = left.childNodes
362 right_children = right.childNodes
363 if len(left_children) != len(right_children):
364 return 0
365 for l, r in map(None, left_children, right_children):
366 nodeType = l.nodeType
367 if nodeType != r.nodeType:
368 return 0
369 if nodeType == xml.dom.core.ELEMENT:
370 if l.tagName != r.tagName:
371 return 0
372 # should check attributes, but that's not a problem here
373 if not contents_match(l, r):
374 return 0
375 elif nodeType == xml.dom.core.TEXT:
376 if l.data != r.data:
377 return 0
378 else:
379 # not quite right, but good enough
380 return 0
381 return 1
382
383
384def create_module_info(doc, section):
385 # Heavy.
386 node = extract_first_element(section, "modulesynopsis")
387 if node is None:
388 return
389 node._node.name = "synopsis"
390 lastchild = node.childNodes[-1]
391 if lastchild.nodeType == xml.dom.core.TEXT \
392 and lastchild.data[-1:] == ".":
393 lastchild.data = lastchild.data[:-1]
Fred Drake4259f0d1999-01-19 23:09:31 +0000394 modauthor = extract_first_element(section, "moduleauthor")
395 if modauthor:
396 modauthor._node.name = "author"
397 modauthor.appendChild(doc.createTextNode(
398 modauthor.getAttribute("name")))
399 modauthor.removeAttribute("name")
Fred Drakeaaed9711998-12-10 20:25:30 +0000400 if section.tagName == "section":
401 modinfo_pos = 2
402 modinfo = doc.createElement("moduleinfo")
403 moddecl = extract_first_element(section, "declaremodule")
404 name = None
405 if moddecl:
406 modinfo.appendChild(doc.createTextNode("\n "))
407 name = moddecl.attributes["name"].value
408 namenode = doc.createElement("name")
409 namenode.appendChild(doc.createTextNode(name))
410 modinfo.appendChild(namenode)
411 type = moddecl.attributes.get("type")
412 if type:
413 type = type.value
414 modinfo.appendChild(doc.createTextNode("\n "))
415 typenode = doc.createElement("type")
416 typenode.appendChild(doc.createTextNode(type))
417 modinfo.appendChild(typenode)
Fred Drake1dd152d1999-01-29 22:12:29 +0000418 versionadded = extract_first_element(section, "versionadded")
419 if versionadded:
420 modinfo.setAttribute("added", versionadded.getAttribute("version"))
Fred Drakeaaed9711998-12-10 20:25:30 +0000421 title = get_first_element(section, "title")
422 if title:
423 children = title.childNodes
424 if len(children) >= 2 \
425 and children[0].nodeType == xml.dom.core.ELEMENT \
426 and children[0].tagName == "module" \
427 and children[0].childNodes[0].data == name:
428 # this is it; morph the <title> into <short-synopsis>
429 first_data = children[1]
430 if first_data.data[:4] == " ---":
431 first_data.data = string.lstrip(first_data.data[4:])
432 title._node.name = "short-synopsis"
Fred Drake7dab6af1999-01-28 23:59:58 +0000433 if children[-1].nodeType == xml.dom.core.TEXT \
434 and children[-1].data[-1:] == ".":
Fred Drakeaaed9711998-12-10 20:25:30 +0000435 children[-1].data = children[-1].data[:-1]
436 section.removeChild(title)
437 section.removeChild(section.childNodes[0])
438 title.removeChild(children[0])
439 modinfo_pos = 0
440 else:
441 sys.stderr.write(
442 "module name in title doesn't match"
443 " <declaremodule>; no <short-synopsis>\n")
444 else:
445 sys.stderr.write(
446 "Unexpected condition: <section> without <title>\n")
447 modinfo.appendChild(doc.createTextNode("\n "))
448 modinfo.appendChild(node)
449 if title and not contents_match(title, node):
450 # The short synopsis is actually different,
451 # and needs to be stored:
452 modinfo.appendChild(doc.createTextNode("\n "))
453 modinfo.appendChild(title)
Fred Drake4259f0d1999-01-19 23:09:31 +0000454 if modauthor:
455 modinfo.appendChild(doc.createTextNode("\n "))
456 modinfo.appendChild(modauthor)
Fred Drakeaaed9711998-12-10 20:25:30 +0000457 modinfo.appendChild(doc.createTextNode("\n "))
458 section.insertBefore(modinfo, section.childNodes[modinfo_pos])
459 section.insertBefore(doc.createTextNode("\n "), modinfo)
460
461
Fred Drakefba0ba21998-12-10 05:07:09 +0000462def cleanup_synopses(doc):
Fred Drake7dab6af1999-01-28 23:59:58 +0000463 for node in find_all_elements(doc, "section"):
464 create_module_info(doc, node)
Fred Drakeaaed9711998-12-10 20:25:30 +0000465
466
Fred Drakef8ebb551999-01-14 19:45:38 +0000467def remap_element_names(root, name_map):
468 queue = []
469 for child in root.childNodes:
470 if child.nodeType == xml.dom.core.ELEMENT:
471 queue.append(child)
472 while queue:
473 node = queue.pop()
474 tagName = node.tagName
475 if name_map.has_key(tagName):
476 name, attrs = name_map[tagName]
477 node._node.name = name
478 for attr, value in attrs.items():
479 node.setAttribute(attr, value)
480 for child in node.childNodes:
481 if child.nodeType == xml.dom.core.ELEMENT:
482 queue.append(child)
483
484
485def fixup_table_structures(doc):
486 # must be done after remap_element_names(), or the tables won't be found
Fred Drake7dab6af1999-01-28 23:59:58 +0000487 for table in find_all_elements(doc, "table"):
488 fixup_table(doc, table)
489
Fred Drakef8ebb551999-01-14 19:45:38 +0000490
491def fixup_table(doc, table):
492 # create the table head
493 thead = doc.createElement("thead")
494 row = doc.createElement("row")
495 move_elements_by_name(doc, table, row, "entry")
496 thead.appendChild(doc.createTextNode("\n "))
497 thead.appendChild(row)
498 thead.appendChild(doc.createTextNode("\n "))
499 # create the table body
500 tbody = doc.createElement("tbody")
501 prev_row = None
502 last_was_hline = 0
503 children = table.childNodes
504 for child in children:
505 if child.nodeType == xml.dom.core.ELEMENT:
506 tagName = child.tagName
507 if tagName == "hline" and prev_row is not None:
508 prev_row.setAttribute("rowsep", "1")
509 elif tagName == "row":
510 prev_row = child
511 # save the rows:
512 tbody.appendChild(doc.createTextNode("\n "))
513 move_elements_by_name(doc, table, tbody, "row", sep="\n ")
514 # and toss the rest:
515 while children:
516 child = children[0]
517 nodeType = child.nodeType
518 if nodeType == xml.dom.core.TEXT:
519 if string.strip(child.data):
520 raise ConversionError("unexpected free data in table")
521 table.removeChild(child)
522 continue
523 if nodeType == xml.dom.core.ELEMENT:
524 if child.tagName != "hline":
525 raise ConversionError(
526 "unexpected <%s> in table" % child.tagName)
527 table.removeChild(child)
528 continue
529 raise ConversionError(
530 "unexpected %s node in table" % child.__class__.__name__)
531 # nothing left in the <table>; add the <thead> and <tbody>
532 tgroup = doc.createElement("tgroup")
533 tgroup.appendChild(doc.createTextNode("\n "))
534 tgroup.appendChild(thead)
535 tgroup.appendChild(doc.createTextNode("\n "))
536 tgroup.appendChild(tbody)
537 tgroup.appendChild(doc.createTextNode("\n "))
538 table.appendChild(tgroup)
539 # now make the <entry>s look nice:
540 for row in table.getElementsByTagName("row"):
541 fixup_row(doc, row)
542
543
544def fixup_row(doc, row):
545 entries = []
546 map(entries.append, row.childNodes[1:])
547 for entry in entries:
548 row.insertBefore(doc.createTextNode("\n "), entry)
549# row.appendChild(doc.createTextNode("\n "))
550
551
552def move_elements_by_name(doc, source, dest, name, sep=None):
553 nodes = []
554 for child in source.childNodes:
555 if child.nodeType == xml.dom.core.ELEMENT and child.tagName == name:
556 nodes.append(child)
557 for node in nodes:
558 source.removeChild(node)
559 dest.appendChild(node)
560 if sep:
561 dest.appendChild(doc.createTextNode(sep))
562
563
Fred Drake7dab6af1999-01-28 23:59:58 +0000564RECURSE_INTO_PARA_CONTAINERS = (
Fred Drakecb657811999-01-29 20:55:07 +0000565 "chapter", "abstract", "enumerate",
Fred Drake7dab6af1999-01-28 23:59:58 +0000566 "section", "subsection", "subsubsection",
567 "paragraph", "subparagraph",
Fred Drakecb657811999-01-29 20:55:07 +0000568 "howto", "manual",
Fred Drake4259f0d1999-01-19 23:09:31 +0000569 )
Fred Drakefcc59101999-01-06 22:50:52 +0000570
571PARA_LEVEL_ELEMENTS = (
Fred Drakecb657811999-01-29 20:55:07 +0000572 "moduleinfo", "title", "verbatim", "enumerate", "item",
Fred Drake93d762f1999-02-18 16:32:21 +0000573 "interpreter-session",
Fred Drakecb657811999-01-29 20:55:07 +0000574 "opcodedesc", "classdesc", "datadesc",
Fred Drake7dab6af1999-01-28 23:59:58 +0000575 "funcdesc", "methoddesc", "excdesc",
576 "funcdescni", "methoddescni", "excdescni",
Fred Drakefcc59101999-01-06 22:50:52 +0000577 "tableii", "tableiii", "tableiv", "localmoduletable",
Fred Drake7dab6af1999-01-28 23:59:58 +0000578 "sectionauthor", "seealso",
Fred Drakefcc59101999-01-06 22:50:52 +0000579 # include <para>, so we can just do it again to get subsequent paras:
580 "para",
581 )
582
583PARA_LEVEL_PRECEEDERS = (
Fred Drakecb657811999-01-29 20:55:07 +0000584 "index", "indexii", "indexiii", "indexiv", "setindexsubitem",
585 "stindex", "obindex", "COMMENT", "label", "input", "title",
Fred Drakefcc59101999-01-06 22:50:52 +0000586 )
587
Fred Drake7dab6af1999-01-28 23:59:58 +0000588
Fred Drakeaaed9711998-12-10 20:25:30 +0000589def fixup_paras(doc):
Fred Drakefcc59101999-01-06 22:50:52 +0000590 for child in doc.childNodes:
591 if child.nodeType == xml.dom.core.ELEMENT \
Fred Drake7dab6af1999-01-28 23:59:58 +0000592 and child.tagName in RECURSE_INTO_PARA_CONTAINERS:
593 #
Fred Drakefcc59101999-01-06 22:50:52 +0000594 fixup_paras_helper(doc, child)
Fred Drakecb657811999-01-29 20:55:07 +0000595 descriptions = find_all_elements(doc, "description")
596 for description in descriptions:
597 fixup_paras_helper(doc, description)
Fred Drakefcc59101999-01-06 22:50:52 +0000598
599
Fred Drake7dab6af1999-01-28 23:59:58 +0000600def fixup_paras_helper(doc, container, depth=0):
Fred Drakefcc59101999-01-06 22:50:52 +0000601 # document is already normalized
602 children = container.childNodes
603 start = 0
Fred Drake7dab6af1999-01-28 23:59:58 +0000604 while len(children) > start:
605 start = skip_leading_nodes(children, start)
606 if start >= len(children):
607 break
608 #
609 # Either paragraph material or something to recurse into:
610 #
611 if (children[start].nodeType == xml.dom.core.ELEMENT) \
612 and (children[start].tagName in RECURSE_INTO_PARA_CONTAINERS):
613 fixup_paras_helper(doc, children[start])
614 start = skip_leading_nodes(children, start + 1)
615 continue
616 #
617 # paragraph material:
618 #
619 build_para(doc, container, start, len(children))
620 if DEBUG_PARA_FIXER and depth == 10:
621 sys.exit(1)
622 start = start + 1
Fred Drakefcc59101999-01-06 22:50:52 +0000623
624
625def build_para(doc, parent, start, i):
626 children = parent.childNodes
Fred Drakefcc59101999-01-06 22:50:52 +0000627 after = start + 1
628 have_last = 0
Fred Drakecb657811999-01-29 20:55:07 +0000629 BREAK_ELEMENTS = PARA_LEVEL_ELEMENTS + RECURSE_INTO_PARA_CONTAINERS
Fred Drake7dab6af1999-01-28 23:59:58 +0000630 # Collect all children until \n\n+ is found in a text node or a
631 # member of BREAK_ELEMENTS is found.
Fred Drakefcc59101999-01-06 22:50:52 +0000632 for j in range(start, i):
633 after = j + 1
634 child = children[j]
635 nodeType = child.nodeType
636 if nodeType == xml.dom.core.ELEMENT:
637 if child.tagName in BREAK_ELEMENTS:
638 after = j
639 break
640 elif nodeType == xml.dom.core.TEXT:
641 pos = string.find(child.data, "\n\n")
642 if pos == 0:
643 after = j
644 break
645 if pos >= 1:
646 child.splitText(pos)
647 break
648 else:
649 have_last = 1
Fred Drake7dab6af1999-01-28 23:59:58 +0000650 if (start + 1) > after:
651 raise ConversionError(
652 "build_para() could not identify content to turn into a paragraph")
Fred Drakefcc59101999-01-06 22:50:52 +0000653 if children[after - 1].nodeType == xml.dom.core.TEXT:
654 # we may need to split off trailing white space:
655 child = children[after - 1]
656 data = child.data
657 if string.rstrip(data) != data:
658 have_last = 0
659 child.splitText(len(string.rstrip(data)))
Fred Drakefcc59101999-01-06 22:50:52 +0000660 para = doc.createElement("para")
661 prev = None
662 indexes = range(start, after)
663 indexes.reverse()
664 for j in indexes:
Fred Drake7dab6af1999-01-28 23:59:58 +0000665 node = parent.childNodes[j]
Fred Drakefcc59101999-01-06 22:50:52 +0000666 parent.removeChild(node)
667 para.insertBefore(node, prev)
668 prev = node
669 if have_last:
670 parent.appendChild(para)
Fred Drake7dab6af1999-01-28 23:59:58 +0000671 return len(parent.childNodes)
Fred Drakefcc59101999-01-06 22:50:52 +0000672 else:
673 parent.insertBefore(para, parent.childNodes[start])
Fred Drake7dab6af1999-01-28 23:59:58 +0000674 return start + 1
Fred Drakefcc59101999-01-06 22:50:52 +0000675
676
Fred Drake7dab6af1999-01-28 23:59:58 +0000677def skip_leading_nodes(children, start):
678 """Return index into children of a node at which paragraph building should
679 begin or a recursive call to fixup_paras_helper() should be made (for
680 subsections, etc.).
681
682 When the return value >= len(children), we've built all the paras we can
683 from this list of children.
684 """
685 i = len(children)
Fred Drakefcc59101999-01-06 22:50:52 +0000686 while i > start:
687 # skip over leading comments and whitespace:
Fred Drake7dab6af1999-01-28 23:59:58 +0000688 child = children[start]
Fred Drakefcc59101999-01-06 22:50:52 +0000689 nodeType = child.nodeType
Fred Drake7dab6af1999-01-28 23:59:58 +0000690 if nodeType == xml.dom.core.TEXT:
Fred Drakefcc59101999-01-06 22:50:52 +0000691 data = child.data
692 shortened = string.lstrip(data)
693 if shortened:
694 if data != shortened:
695 # break into two nodes: whitespace and non-whitespace
696 child.splitText(len(data) - len(shortened))
Fred Drake7dab6af1999-01-28 23:59:58 +0000697 return start + 1
698 return start
Fred Drakefcc59101999-01-06 22:50:52 +0000699 # all whitespace, just skip
Fred Drakefcc59101999-01-06 22:50:52 +0000700 elif nodeType == xml.dom.core.ELEMENT:
Fred Drake7dab6af1999-01-28 23:59:58 +0000701 tagName = child.tagName
702 if tagName in RECURSE_INTO_PARA_CONTAINERS:
703 return start
704 if tagName not in PARA_LEVEL_ELEMENTS + PARA_LEVEL_PRECEEDERS:
705 return start
706 start = start + 1
707 return start
Fred Drakefba0ba21998-12-10 05:07:09 +0000708
709
Fred Draked24167b1999-01-14 21:18:03 +0000710def fixup_rfc_references(doc):
Fred Drake7dab6af1999-01-28 23:59:58 +0000711 for rfcnode in find_all_elements(doc, "rfc"):
712 rfcnode.appendChild(doc.createTextNode(
713 "RFC " + rfcnode.getAttribute("num")))
Fred Draked24167b1999-01-14 21:18:03 +0000714
715
716def fixup_signatures(doc):
717 for child in doc.childNodes:
718 if child.nodeType == xml.dom.core.ELEMENT:
719 args = child.getElementsByTagName("args")
720 for arg in args:
721 fixup_args(doc, arg)
Fred Drake7dab6af1999-01-28 23:59:58 +0000722 arg.normalize()
Fred Draked24167b1999-01-14 21:18:03 +0000723 args = child.getElementsByTagName("constructor-args")
724 for arg in args:
725 fixup_args(doc, arg)
726 arg.normalize()
727
728
729def fixup_args(doc, arglist):
730 for child in arglist.childNodes:
731 if child.nodeType == xml.dom.core.ELEMENT \
732 and child.tagName == "optional":
733 # found it; fix and return
734 arglist.insertBefore(doc.createTextNode("["), child)
735 optkids = child.childNodes
736 while optkids:
737 k = optkids[0]
738 child.removeChild(k)
739 arglist.insertBefore(k, child)
740 arglist.insertBefore(doc.createTextNode("]"), child)
741 arglist.removeChild(child)
742 return fixup_args(doc, arglist)
743
744
Fred Drake7dab6af1999-01-28 23:59:58 +0000745def fixup_sectionauthors(doc):
746 for sectauth in find_all_elements(doc, "sectionauthor"):
747 section = sectauth.parentNode
748 section.removeChild(sectauth)
749 sectauth._node.name = "author"
750 sectauth.appendChild(doc.createTextNode(
751 sectauth.getAttribute("name")))
752 sectauth.removeAttribute("name")
753 after = section.childNodes[2]
754 title = section.childNodes[1]
755 if title.nodeType == xml.dom.core.ELEMENT and title.tagName != "title":
756 after = section.childNodes[0]
757 section.insertBefore(doc.createTextNode("\n "), after)
758 section.insertBefore(sectauth, after)
759
760
Fred Drake93d762f1999-02-18 16:32:21 +0000761def fixup_verbatims(doc):
762 for verbatim in find_all_elements(doc, "verbatim"):
763 child = verbatim.childNodes[0]
764 if child.nodeType == xml.dom.core.TEXT \
765 and string.lstrip(child.data)[:3] == ">>>":
766 verbatim._node.name = "interpreter-session"
767 #verbatim.setAttribute("interactive", "interactive")
768
769
Fred Drake4db5b461998-12-01 19:03:01 +0000770_token_rx = re.compile(r"[a-zA-Z][a-zA-Z0-9.-]*$")
Fred Drakefcc59101999-01-06 22:50:52 +0000771
Fred Drake4db5b461998-12-01 19:03:01 +0000772def write_esis(doc, ofp, knownempty):
773 for node in doc.childNodes:
774 nodeType = node.nodeType
775 if nodeType == xml.dom.core.ELEMENT:
776 gi = node.tagName
777 if knownempty(gi):
778 if node.hasChildNodes():
779 raise ValueError, "declared-empty node has children"
780 ofp.write("e\n")
781 for k, v in node.attributes.items():
782 value = v.value
783 if _token_rx.match(value):
784 dtype = "TOKEN"
785 else:
786 dtype = "CDATA"
787 ofp.write("A%s %s %s\n" % (k, dtype, esistools.encode(value)))
788 ofp.write("(%s\n" % gi)
789 write_esis(node, ofp, knownempty)
790 ofp.write(")%s\n" % gi)
791 elif nodeType == xml.dom.core.TEXT:
792 ofp.write("-%s\n" % esistools.encode(node.data))
793 else:
794 raise RuntimeError, "unsupported node type: %s" % nodeType
795
796
Fred Drake03204731998-11-23 17:02:03 +0000797def convert(ifp, ofp):
Fred Drake4db5b461998-12-01 19:03:01 +0000798 p = esistools.ExtendedEsisBuilder()
Fred Drake03204731998-11-23 17:02:03 +0000799 p.feed(ifp.read())
800 doc = p.document
Fred Drake1ff6db41998-11-23 23:10:35 +0000801 normalize(doc)
Fred Drake03204731998-11-23 17:02:03 +0000802 simplify(doc)
803 handle_labels(doc)
Fred Drake4db5b461998-12-01 19:03:01 +0000804 handle_appendix(doc)
Fred Drake1ff6db41998-11-23 23:10:35 +0000805 fixup_trailing_whitespace(doc, {
806 "abstract": "\n",
807 "title": "",
808 "chapter": "\n\n",
809 "section": "\n\n",
810 "subsection": "\n\n",
811 "subsubsection": "\n\n",
812 "paragraph": "\n\n",
813 "subparagraph": "\n\n",
814 })
Fred Drake03204731998-11-23 17:02:03 +0000815 cleanup_root_text(doc)
Fred Drake1ff6db41998-11-23 23:10:35 +0000816 cleanup_trailing_parens(doc, ["function", "method", "cfunction"])
Fred Drakefba0ba21998-12-10 05:07:09 +0000817 cleanup_synopses(doc)
Fred Drakecb657811999-01-29 20:55:07 +0000818 fixup_descriptors(doc)
Fred Drake93d762f1999-02-18 16:32:21 +0000819 fixup_verbatims(doc)
Fred Drakeaaed9711998-12-10 20:25:30 +0000820 normalize(doc)
821 fixup_paras(doc)
Fred Drake7dab6af1999-01-28 23:59:58 +0000822 fixup_sectionauthors(doc)
Fred Drakef8ebb551999-01-14 19:45:38 +0000823 remap_element_names(doc, {
824 "tableii": ("table", {"cols": "2"}),
825 "tableiii": ("table", {"cols": "3"}),
826 "tableiv": ("table", {"cols": "4"}),
827 "lineii": ("row", {}),
828 "lineiii": ("row", {}),
829 "lineiv": ("row", {}),
Fred Draked6ced7d1999-01-19 17:11:23 +0000830 "refmodule": ("module", {"link": "link"}),
Fred Drakef8ebb551999-01-14 19:45:38 +0000831 })
832 fixup_table_structures(doc)
Fred Draked24167b1999-01-14 21:18:03 +0000833 fixup_rfc_references(doc)
834 fixup_signatures(doc)
Fred Drake4db5b461998-12-01 19:03:01 +0000835 #
836 d = {}
837 for gi in p.get_empties():
838 d[gi] = gi
Fred Draked24167b1999-01-14 21:18:03 +0000839 if d.has_key("rfc"):
840 del d["rfc"]
Fred Drake4db5b461998-12-01 19:03:01 +0000841 knownempty = d.has_key
842 #
Fred Drake03204731998-11-23 17:02:03 +0000843 try:
Fred Drake4db5b461998-12-01 19:03:01 +0000844 write_esis(doc, ofp, knownempty)
Fred Drake03204731998-11-23 17:02:03 +0000845 except IOError, (err, msg):
846 # Ignore EPIPE; it just means that whoever we're writing to stopped
847 # reading. The rest of the output would be ignored. All other errors
848 # should still be reported,
849 if err != errno.EPIPE:
850 raise
851
852
853def main():
854 if len(sys.argv) == 1:
855 ifp = sys.stdin
856 ofp = sys.stdout
857 elif len(sys.argv) == 2:
858 ifp = open(sys.argv[1])
859 ofp = sys.stdout
860 elif len(sys.argv) == 3:
861 ifp = open(sys.argv[1])
862 ofp = open(sys.argv[2], "w")
863 else:
864 usage()
865 sys.exit(2)
866 convert(ifp, ofp)
867
868
869if __name__ == "__main__":
870 main()