summaryrefslogtreecommitdiffstats
path: root/Doc/tools/sgmlconv/latex2esis.py
blob: 1ea928d9dc3a4dbe9b7b0b07d7d3b6af15a42f58 (plain)
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
#! /usr/bin/env python

"""Generate ESIS events based on a LaTeX source document and configuration
data.
"""
__version__ = '$Revision$'

import errno
import re
import string
import StringIO
import sys

from esistools import encode


DEBUG = 0


class Error(Exception):
    pass

class LaTeXFormatError(Error):
    pass


_begin_env_rx = re.compile(r"[\\]begin{([^}]*)}")
_end_env_rx = re.compile(r"[\\]end{([^}]*)}")
_begin_macro_rx = re.compile("[\\\\]([a-zA-Z]+[*]?)({|\\s*\n?)")
_comment_rx = re.compile("%+ ?(.*)\n[ \t]*")
_text_rx = re.compile(r"[^]%\\{}]+")
_optional_rx = re.compile(r"\s*[[]([^]]*)[]]")
# _parameter_rx is this complicated to allow {...} inside a parameter;
# this is useful to match tabular layout specifications like {c|p{24pt}}
_parameter_rx = re.compile("[ \n]*{(([^{}}]|{[^}]*})*)}")
_token_rx = re.compile(r"[a-zA-Z][a-zA-Z0-9.-]*$")
_start_group_rx = re.compile("[ \n]*{")
_start_optional_rx = re.compile("[ \n]*[[]")


ESCAPED_CHARS = "$%#^ {}&~"


def pushing(name, point, depth):
    if DEBUG:
        sys.stderr.write("%s<%s> at %s\n" % (" "*depth, name, point))

def popping(name, point, depth):
    if DEBUG:
        sys.stderr.write("%s</%s> at %s\n" % (" "*depth, name, point))


class Conversion:
    def __init__(self, ifp, ofp, table=None, discards=(), autoclosing=()):
        self.ofp_stack = [ofp]
        self.pop_output()
        self.table = table
        self.discards = discards
        self.autoclosing = autoclosing
        self.line = string.join(map(string.rstrip, ifp.readlines()), "\n")
        self.err_write = sys.stderr.write
        self.preamble = 1

    def push_output(self, ofp):
        self.ofp_stack.append(self.ofp)
        self.ofp = ofp
        self.write = ofp.write

    def pop_output(self):
        self.ofp = self.ofp_stack.pop()
        self.write = self.ofp.write

    def subconvert(self, endchar=None, depth=0):
        if DEBUG and endchar:
            self.err_write(
                "subconvert(%s)\n  line = %s\n" % (`endchar`, `line[:20]`))
        stack = []
        line = self.line
        while line:
            if line[0] == endchar and not stack:
                if DEBUG:
                    self.err_write("subconvert() --> %s\n" % `line[1:21]`)
                self.line = line
                return line
            m = _comment_rx.match(line)
            if m:
                text = m.group(1)
                if text:
                    self.write("(COMMENT\n- %s \n)COMMENT\n-\\n\n"
                               % encode(text))
                line = line[m.end():]
                continue
            m = _begin_env_rx.match(line)
            if m:
                # re-write to use the macro handler
                line = r"\%s %s" % (m.group(1), line[m.end():])
                continue
            m = _end_env_rx.match(line)
            if m:
                # end of environment
                envname = m.group(1)
                if envname == "document":
                    # special magic
                    for n in stack[1:]:
                        if n not in self.autoclosing:
                            raise LaTeXFormatError(
                                "open element on stack: " + `n`)
                    # should be more careful, but this is easier to code:
                    stack = []
                    self.write(")document\n")
                elif envname == stack[-1]:
                    self.write(")%s\n" % envname)
                    del stack[-1]
                    popping(envname, "a", len(stack) + depth)
                else:
                    self.err_write("stack: %s\n" % `stack`)
                    raise LaTeXFormatError(
                        "environment close for %s doesn't match" % envname)
                line = line[m.end():]
                continue
            m = _begin_macro_rx.match(line)
            if m:
                # start of macro
                macroname = m.group(1)
                if macroname == "verbatim":
                    # really magic case!
                    pos = string.find(line, "\\end{verbatim}")
                    text = line[m.end(1):pos]
                    self.write("(verbatim\n")
                    self.write("-%s\n" % encode(text))
                    self.write(")verbatim\n")
                    line = line[pos + len("\\end{verbatim}"):]
                    continue
                numbered = 1
                opened = 0
                if macroname[-1] == "*":
                    macroname = macroname[:-1]
                    numbered = 0
                if macroname in self.autoclosing and macroname in stack:
                    while stack[-1] != macroname:
                        top = stack.pop()
                        if top and top not in self.discards:
                            self.write(")%s\n-\\n\n" % top)
                        popping(top, "b", len(stack) + depth)
                    if macroname not in self.discards:
                        self.write("-\\n\n)%s\n-\\n\n" % macroname)
                    popping(macroname, "c", len(stack) + depth - 1)
                    del stack[-1]
                #
                if macroname in self.discards:
                    self.push_output(StringIO.StringIO())
                else:
                    self.push_output(self.ofp)
                #
                params, optional, empty, environ = self.start_macro(macroname)
                if not numbered:
                    self.write("Anumbered TOKEN no\n")
                # rip off the macroname
                if params:
                    if optional and len(params) == 1:
                        line = line[m.end():]
                    else:
                        line = line[m.end(1):]
                elif empty:
                    line = line[m.end(1):]
                else:
                    line = line[m.end():]
                #
                # Very ugly special case to deal with \item[].  The catch
                # is that this needs to occur outside the for loop that
                # handles attribute parsing so we can 'continue' the outer
                # loop.
                #
                if optional and type(params[0]) is type(()):
                    # the attribute name isn't used in this special case
                    pushing(macroname, "a", depth + len(stack))
                    stack.append(macroname)
                    self.write("(%s\n" % macroname)
                    m = _start_optional_rx.match(line)
                    if m:
                        self.line = line[m.end():]
                        line = self.subconvert("]", depth + len(stack))
                    line = "}" + line
                    continue
                # handle attribute mappings here:
                for attrname in params:
                    if optional:
                        optional = 0
                        if type(attrname) is type(""):
                            m = _optional_rx.match(line)
                            if m:
                                line = line[m.end():]
                                self.write("A%s TOKEN %s\n"
                                           % (attrname, encode(m.group(1))))
                    elif type(attrname) is type(()):
                        # This is a sub-element; but don't place the
                        # element we found on the stack (\section-like)
                        pushing(macroname, "b", len(stack) + depth)
                        stack.append(macroname)
                        self.write("(%s\n" % macroname)
                        macroname = attrname[0]
                        m = _start_group_rx.match(line)
                        if m:
                            line = line[m.end():]
                    elif type(attrname) is type([]):
                        # A normal subelement.
                        attrname = attrname[0]
                        if not opened:
                            opened = 1
                            self.write("(%s\n" % macroname)
                            pushing(macroname, "c", len(stack) + depth)
                        self.write("(%s\n" % attrname)
                        pushing(attrname, "sub-elem", len(stack) + depth + 1)
                        self.line = skip_white(line)[1:]
                        line = subconvert("}", depth + len(stack) + 2)
                        popping(attrname, "sub-elem", len(stack) + depth + 1)
                        self.write(")%s\n" % attrname)
                    else:
                        m = _parameter_rx.match(line)
                        if not m:
                            raise LaTeXFormatError(
                                "could not extract parameter %s for %s: %s"
                                % (attrname, macroname, `line[:100]`))
                        value = m.group(1)
                        if _token_rx.match(value):
                            dtype = "TOKEN"
                        else:
                            dtype = "CDATA"
                        self.write("A%s %s %s\n"
                                   % (attrname, dtype, encode(value)))
                        line = line[m.end():]
                if params and type(params[-1]) is type('') \
                   and (not empty) and not environ:
                    # attempt to strip off next '{'
                    m = _start_group_rx.match(line)
                    if not m:
                        raise LaTeXFormatError(
                            "non-empty element '%s' has no content: %s"
                            % (macroname, line[:12]))
                    line = line[m.end():]
                if not opened:
                    self.write("(%s\n" % macroname)
                    pushing(macroname, "d", len(stack) + depth)
                if empty:
                    line = "}" + line
                stack.append(macroname)
                self.pop_output()
                continue
            if line[0] == endchar and not stack:
                if DEBUG:
                    self.err_write("subconvert() --> %s\n" % `line[1:21]`)
                self.line = line[1:]
                return self.line
            if line[0] == "}":
                # end of macro or group
                macroname = stack[-1]
                conversion = self.table.get(macroname)
                if macroname \
                   and macroname not in self.discards \
                   and type(conversion) is not type(""):
                    # otherwise, it was just a bare group
                    self.write(")%s\n" % stack[-1])
                popping(macroname, "d", len(stack) + depth - 1)
                del stack[-1]
                line = line[1:]
                continue
            if line[0] == "{":
                pushing("", "e", len(stack) + depth)
                stack.append("")
                line = line[1:]
                continue
            if line[0] == "\\" and line[1] in ESCAPED_CHARS:
                self.write("-%s\n" % encode(line[1]))
                line = line[2:]
                continue
            if line[:2] == r"\\":
                self.write("(BREAK\n)BREAK\n")
                line = line[2:]
                continue
            m = _text_rx.match(line)
            if m:
                text = encode(m.group())
                self.write("-%s\n" % text)
                line = line[m.end():]
                continue
            # special case because of \item[]
            if line[0] == "]":
                self.write("-]\n")
                line = line[1:]
                continue
            # avoid infinite loops
            extra = ""
            if len(line) > 100:
                extra = "..."
            raise LaTeXFormatError("could not identify markup: %s%s"
                                   % (`line[:100]`, extra))
        while stack and stack[-1] in self.autoclosing:
            self.write("-\\n\n")
            self.write(")%s\n" % stack[-1])
            popping(stack.pop(), "e", len(stack) + depth - 1)
        if stack:
            raise LaTeXFormatError("elements remain on stack: "
                                   + string.join(stack, ", "))
        # otherwise we just ran out of input here...

    def convert(self):
        self.subconvert()

    def start_macro(self, name):
        conversion = self.table.get(name, ([], 0, 0, 0, 0))
        params, optional, empty, environ, nocontent = conversion
        if empty:
            self.write("e\n")
        elif nocontent:
            empty = 1
        return params, optional, empty, environ


def convert(ifp, ofp, table={}, discards=(), autoclosing=()):
    c = Conversion(ifp, ofp, table, discards, autoclosing)
    try:
        c.convert()
    except IOError, (err, msg):
        if err != errno.EPIPE:
            raise


def skip_white(line):
    while line and line[0] in " %\n\t":
        line = string.lstrip(line[1:])
    return line


def main():
    if 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)
    convert(ifp, ofp, {
        # entries have the form:
        # name: ([attribute names], is1stOptional, isEmpty, isEnv, nocontent)
        # attribute names can be:
        #   "string" -- normal attribute
        #   ("string",) -- sub-element with content of macro; like for \section
        #   ["string"] -- sub-element
        "appendix": ([], 0, 1, 0, 0),
        "bifuncindex": (["name"], 0, 1, 0, 0),
        "catcode": ([], 0, 1, 0, 0),
        "cfuncdesc": (["type", "name", ("args",)], 0, 0, 1, 0),
        "chapter": ([("title",)], 0, 0, 0, 0),
        "chapter*": ([("title",)], 0, 0, 0, 0),
        "classdesc": (["name", ("args",)], 0, 0, 1, 0),
        "ctypedesc": (["name"], 0, 0, 1, 0),
        "cvardesc":  (["type", "name"], 0, 0, 1, 0),
        "datadesc":  (["name"], 0, 0, 1, 0),
        "declaremodule": (["id", "type", "name"], 1, 1, 0, 0),
        "deprecated": (["release"], 0, 0, 0, 0),
        "documentclass": (["classname"], 0, 1, 0, 0),
        "excdesc": (["name"], 0, 0, 1, 0),
        "funcdesc": (["name", ("args",)], 0, 0, 1, 0),
        "funcdescni": (["name", ("args",)], 0, 0, 1, 0),
        "funcline": (["name"], 0, 0, 0, 0),
        "funclineni": (["name"], 0, 0, 0, 0),
        "geq": ([], 0, 1, 0, 0),
        "hline": ([], 0, 1, 0, 0),
        "indexii": (["ie1", "ie2"], 0, 1, 0, 0),
        "indexiii": (["ie1", "ie2", "ie3"], 0, 1, 0, 0),
        "indexiv": (["ie1", "ie2", "ie3", "ie4"], 0, 1, 0, 0),
        "indexname": ([], 0, 0, 0, 0),
        "input": (["source"], 0, 1, 0, 0),
        "item": ([("leader",)], 1, 0, 0, 0),
        "label": (["id"], 0, 1, 0, 0),
        "labelwidth": ([], 0, 1, 0, 0),
        "LaTeX": ([], 0, 1, 0, 0),
        "leftmargin": ([], 0, 1, 0, 0),
        "leq": ([], 0, 1, 0, 0),
        "lineii": ([["entry"], ["entry"]], 0, 0, 0, 1),
        "lineiii": ([["entry"], ["entry"], ["entry"]], 0, 0, 0, 1),
        "lineiv": ([["entry"], ["entry"], ["entry"], ["entry"]], 0, 0, 0, 1),
        "localmoduletable": ([], 0, 1, 0, 0),
        "makeindex": ([], 0, 1, 0, 0), 
        "makemodindex": ([], 0, 1, 0, 0), 
        "maketitle": ([], 0, 1, 0, 0),
        "manpage": (["name", "section"], 0, 1, 0, 0),
        "memberdesc": (["class", "name"], 1, 0, 1, 0),
        "methoddesc": (["class", "name", ("args",)], 1, 0, 1, 0),
        "methoddescni": (["class", "name", ("args",)], 1, 0, 1, 0),
        "methodline": (["class", "name"], 1, 0, 0, 0),
        "methodlineni": (["class", "name"], 1, 0, 0, 0),
        "moduleauthor": (["name", "email"], 0, 1, 0, 0),
        "opcodedesc": (["name", "var"], 0, 0, 1, 0),
        "par": ([], 0, 1, 0, 0),
        "paragraph": ([("title",)], 0, 0, 0, 0),
        "renewcommand": (["macro"], 0, 0, 0, 0),
        "rfc": (["num"], 0, 1, 0, 0),
        "section": ([("title",)], 0, 0, 0, 0),
        "sectionauthor": (["name", "email"], 0, 1, 0, 0),
        "seemodule": (["ref", "name"], 1, 0, 0, 0),
        "stindex": (["type"], 0, 1, 0, 0),
        "subparagraph": ([("title",)], 0, 0, 0, 0),
        "subsection": ([("title",)], 0, 0, 0, 0),
        "subsubsection": ([("title",)], 0, 0, 0, 0),
        "list": (["bullet", "init"], 0, 0, 1, 0),
        "tableii": (["colspec", "style",
                     ["entry"], ["entry"]], 0, 0, 1, 0),
        "tableiii": (["colspec", "style",
                      ["entry"], ["entry"], ["entry"]], 0, 0, 1, 0),
        "tableiv": (["colspec", "style",
                     ["entry"], ["entry"], ["entry"], ["entry"]], 0, 0, 1, 0),
        "version": ([], 0, 1, 0, 0),
        "versionadded": (["version"], 0, 1, 0, 0),
        "versionchanged": (["version"], 0, 1, 0, 0),
        "withsubitem": (["text"], 0, 0, 0, 0),
        #
        "ABC": ([], 0, 1, 0, 0),
        "ASCII": ([], 0, 1, 0, 0),
        "C": ([], 0, 1, 0, 0),
        "Cpp": ([], 0, 1, 0, 0),
        "EOF": ([], 0, 1, 0, 0),
        "e": ([], 0, 1, 0, 0),
        "ldots": ([], 0, 1, 0, 0),
        "NULL": ([], 0, 1, 0, 0),
        "POSIX": ([], 0, 1, 0, 0),
        "UNIX": ([], 0, 1, 0, 0),
        #
        # Things that will actually be going away!
        #
        "fi": ([], 0, 1, 0, 0),
        "ifhtml": ([], 0, 1, 0, 0),
        "makeindex": ([], 0, 1, 0, 0),
        "makemodindex": ([], 0, 1, 0, 0),
        "maketitle": ([], 0, 1, 0, 0),
        "noindent": ([], 0, 1, 0, 0),
        "protect": ([], 0, 1, 0, 0),
        "tableofcontents": ([], 0, 1, 0, 0),
        },
            discards=["fi", "ifhtml", "makeindex", "makemodindex", "maketitle",
                      "noindent", "tableofcontents"],
            autoclosing=["chapter", "section", "subsection", "subsubsection",
                         "paragraph", "subparagraph", ])


if __name__ == "__main__":
    main()