1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
|
#! /usr/bin/env python
"""Convert ESIS events to SGML or XML markup.
This is limited, but seems sufficient for the ESIS generated by the
latex2esis.py script when run over the Python documentation.
"""
__version__ = '$Revision$'
import errno
import re
import string
_data_rx = re.compile(r"[^\\][^\\]*")
def decode(s):
r = ''
while s:
m = _data_rx.match(s)
if m:
r = r + m.group()
s = s[len(m.group()):]
elif s[1] == "\\":
r = r + "\\"
s = s[2:]
elif s[1] == "n":
r = r + "\n"
s = s[2:]
else:
raise ValueError, "can't handle " + `s`
return r
def format_attrs(attrs):
attrs = attrs.items()
attrs.sort()
s = ''
for name, value in attrs:
s = '%s %s="%s"' % (s, name, value)
return s
def do_convert(ifp, ofp, knownempties, xml=0):
attrs = {}
lastopened = None
knownempty = 0
lastempty = 0
while 1:
line = ifp.readline()
if not line:
break
type = line[0]
data = line[1:]
if data and data[-1] == "\n":
data = data[:-1]
if type == "-":
data = decode(data)
ofp.write(data)
if "\n" in data:
lastopened = None
knownempty = 0
lastempty = 0
elif type == "(":
if knownempty and xml:
ofp.write("<%s%s/>" % (data, format_attrs(attrs)))
else:
ofp.write("<%s%s>" % (data, format_attrs(attrs)))
if knownempty and data not in knownempties:
# accumulate knowledge!
knownempties.append(data)
attrs = {}
lastopened = data
lastempty = knownempty
knownempty = 0
elif type == ")":
if xml:
if not lastempty:
ofp.write("</%s>" % data)
elif data not in knownempties:
if lastopened == data:
ofp.write("</>")
else:
ofp.write("</%s>" % data)
lastopened = None
lastempty = 0
elif type == "A":
name, type, value = string.split(data, " ", 2)
attrs[name] = decode(value)
elif type == "e":
knownempty = 1
def sgml_convert(ifp, ofp, knownempties=()):
return do_convert(ifp, ofp, list(knownempties), xml=0)
def xml_convert(ifp, ofp, knownempties=()):
return do_convert(ifp, ofp, list(knownempties), xml=1)
def main():
import sys
#
convert = sgml_convert
if sys.argv[1:] and sys.argv[1] in ("-x", "--xml"):
convert = xml_convert
del sys.argv[1]
if len(sys.argv) == 1:
ifp = sys.stdin
ofp = sys.stdout
elif len(sys.argv) == 2:
ifp = open(sys.argv[1])
ofp = sys.stdout
elif len(sys.argv) == 3:
ifp = open(sys.argv[1])
ofp = open(sys.argv[2], "w")
else:
usage()
sys.exit(2)
# knownempties is ignored in the XML version
try:
convert(ifp, ofp)
except IOError, (err, msg):
if err != errno.EPIPE:
raise
if __name__ == "__main__":
main()
|