LaTeXCompiler.py 24.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/python

#######################################################################
#
# SYMBOLS SECTION - Can be edited. Changes will be preserved.
#
#######################################################################


import os
import sys
Eckhart Arnold's avatar
Eckhart Arnold committed
12
13
from functools import partial

14
15
16
17
try:
    import regex as re
except ImportError:
    import re
Eckhart Arnold's avatar
Eckhart Arnold committed
18
19
20
from DHParser import logging, is_filename, Grammar, Compiler, Lookbehind, Alternative, Pop, \
    Required, Token, Synonym, \
    Optional, NegativeLookbehind, OneOrMore, RegExp, Series, RE, Capture, \
21
    ZeroOrMore, Forward, NegativeLookahead, mixin_comment, compile_source, \
22
    PreprocessorFunc, TransformationDict, \
Eckhart Arnold's avatar
Eckhart Arnold committed
23
    Node, TransformationFunc, traverse, remove_children_if, is_anonymous, \
24
    reduce_single_child, replace_by_single_child, remove_whitespace, \
Eckhart Arnold's avatar
Eckhart Arnold committed
25
    flatten, is_empty, collapse, replace_content, remove_brackets, is_one_of, remove_first
26
27
28
29


#######################################################################
#
Eckhart Arnold's avatar
Eckhart Arnold committed
30
# PREPROCESSOR SECTION - Can be edited. Changes will be preserved.
31
32
33
#
#######################################################################

Eckhart Arnold's avatar
Eckhart Arnold committed
34
def LaTeXPreprocessor(text):
35
36
    return text

Eckhart Arnold's avatar
Eckhart Arnold committed
37
38
def get_preprocessor() -> PreprocessorFunc:
    return LaTeXPreprocessor
39
40
41
42
43
44
45
46
47
48
49


#######################################################################
#
# PARSER SECTION - Don't edit! CHANGES WILL BE OVERWRITTEN!
#
#######################################################################

class LaTeXGrammar(Grammar):
    r"""Parser for a LaTeX source file, with this grammar:
    
50
    # LaTeX-Grammar for DHParser
51
52
53
54
55
56
    
    @ testing    = True
    @ whitespace = /[ \t]*(?:\n(?![ \t]*\n)[ \t]*)?/    # optional whitespace, including at most one linefeed
    @ comment    = /%.*(?:\n|$)/
    
    
57
    latexdoc       = preamble document
58
    preamble       = { [WSPC] command }+
59
    
Eckhart Arnold's avatar
Eckhart Arnold committed
60
61
62
63
64
    document       = [WSPC] "\begin{document}" [WSPC]
                     frontpages [WSPC]
                     (Chapters | Sections) [WSPC]
                     [Bibliography] [Index] [WSPC]
                     "\end{document}" [WSPC] §EOF
65
66
67
68
69
70
71
72
73
    frontpages     = sequence
    
    
    #######################################################################
    #
    # document structure
    #
    #######################################################################
    
Eckhart Arnold's avatar
Eckhart Arnold committed
74
    Chapters       = { Chapter [WSPC] }+
Eckhart Arnold's avatar
Eckhart Arnold committed
75
    Chapter        = "\chapter" block [WSPC] { sequence | Sections }
76
    
Eckhart Arnold's avatar
Eckhart Arnold committed
77
    Sections       = { Section [WSPC] }+
Eckhart Arnold's avatar
Eckhart Arnold committed
78
    Section        = "\section" block [WSPC] { sequence | SubSections }
79
    
Eckhart Arnold's avatar
Eckhart Arnold committed
80
    SubSections    = { SubSection [WSPC] }+
Eckhart Arnold's avatar
Eckhart Arnold committed
81
    SubSection     = "\subsection" block [WSPC] { sequence | SubSubSections }
82
    
Eckhart Arnold's avatar
Eckhart Arnold committed
83
    SubSubSections = { SubSubSection [WSPC] }+
Eckhart Arnold's avatar
Eckhart Arnold committed
84
    SubSubSection  = "\subsubsection" block [WSPC] { sequence | Paragraphs }
85
    
Eckhart Arnold's avatar
Eckhart Arnold committed
86
87
    Paragraphs     = { Paragraph [WSPC] }+
    Paragraph      = "\paragraph" block [WSPC] { sequence | SubParagraphs }
88
    
Eckhart Arnold's avatar
Eckhart Arnold committed
89
90
    SubParagraphs  = { SubParagraph [WSPC] }+
    SubParagraph   = "\subparagraph" block [WSPC] [ sequence ]
91
    
Eckhart Arnold's avatar
Eckhart Arnold committed
92
93
    Bibliography   = "\bibliography" block [WSPC]
    Index          = "\printindex" [WSPC]
94
95
96
97
98
99
100
101
102
103
    
    
    #######################################################################
    #
    # document content
    #
    #######################################################################
    
    
    #### block environments ####
104
    
Eckhart Arnold's avatar
Eckhart Arnold committed
105
    block_environment   = known_environment | generic_block
Eckhart Arnold's avatar
Eckhart Arnold committed
106
    known_environment   = itemize | enumerate | figure | tabular | quotation
107
                        | verbatim
Eckhart Arnold's avatar
Eckhart Arnold committed
108
    generic_block       = begin_generic_block sequence §end_generic_block
Eckhart Arnold's avatar
Eckhart Arnold committed
109
110
    begin_generic_block = -&LB begin_environment LFF
    end_generic_block   = -&LB  end_environment LFF
111
    
Eckhart Arnold's avatar
Eckhart Arnold committed
112
113
114
    itemize             = "\begin{itemize}" [WSPC] { item } §"\end{itemize}"
    enumerate           = "\begin{enumerate}" [WSPC] {item } §"\end{enumerate}"
    item                = "\item" [WSPC] sequence
115
    
Eckhart Arnold's avatar
Eckhart Arnold committed
116
117
118
119
    figure              = "\begin{figure}" sequence §"\end{figure}"
    quotation           = ("\begin{quotation}" sequence §"\end{quotation}")
                        | ("\begin{quote}" sequence §"\end{quote}")
    verbatim            = "\begin{verbatim}" sequence §"\end{verbatim}"
Eckhart Arnold's avatar
Eckhart Arnold committed
120
121
122
    tabular             = "\begin{tabular}" tabular_config { tabular_row } §"\end{tabular}"
    tabular_row         = [multicolumn | tabular_cell] { "&" [multicolumn | tabular_cell] } "\\" [ hline | cline ]
    tabular_cell        = { text_element //~ }+
Eckhart Arnold's avatar
Eckhart Arnold committed
123
    tabular_config      = "{" /[lcr|]+/~ §"}"
124
    
125
126
    #### paragraphs and sequences of paragraphs ####
    
Eckhart Arnold's avatar
Eckhart Arnold committed
127
    block_of_paragraphs = /{/~ [sequence] §/}/
128
    sequence            = { (paragraph | block_environment ) [PARSEP] }+
129
    paragraph           = { !blockcmd (text_element | LINEFEED) //~ }+
Eckhart Arnold's avatar
Eckhart Arnold committed
130
    text_element        = text | block | inline_environment | command
131
132
133
    
    #### inline enivronments ####
    
134
    inline_environment  = known_inline_env | generic_inline_env
135
    known_inline_env    = inline_math
Eckhart Arnold's avatar
Eckhart Arnold committed
136
137
    generic_inline_env  = begin_inline_env //~ paragraph §end_inline_env
    begin_inline_env    = (-!LB begin_environment) | (begin_environment !LFF)
138
    end_inline_env      = end_environment
Eckhart Arnold's avatar
Eckhart Arnold committed
139
140
141
                          ## (-!LB end_environment)   | (end_environment !LFF)  # ambiguity with genric_block when EOF
    begin_environment   = /\\begin{/ §NAME §/}/
    end_environment     = /\\end{/ §::NAME §/}/
142
    
Eckhart Arnold's avatar
Eckhart Arnold committed
143
    inline_math         = /\$/ /[^$]*/ §/\$/
144
145
146
    
    #### commands ####
    
Eckhart Arnold's avatar
Eckhart Arnold committed
147
    command             = known_command | text_command | generic_command
Eckhart Arnold's avatar
Eckhart Arnold committed
148
    known_command       = footnote | includegraphics | caption | multicolumn | hline | cline
149
    text_command        = TXTCOMMAND | ESCAPED | BRACKETS
Eckhart Arnold's avatar
Eckhart Arnold committed
150
    generic_command     = !no_command CMDNAME [[ //~ config ] //~ block ]
151
152
    
    footnote            = "\footnote" block_of_paragraphs
Eckhart Arnold's avatar
Eckhart Arnold committed
153
    includegraphics     = "\includegraphics" [ config ] block
Eckhart Arnold's avatar
Eckhart Arnold committed
154
    caption             = "\caption" block
Eckhart Arnold's avatar
Eckhart Arnold committed
155
156
157
158
    multicolumn         = "\multicolumn" "{" INTEGER "}" tabular_config block_of_paragraphs
    hline               = "\hline"
    cline               = "\cline{" INTEGER "-" INTEGER "}"
    
159
    
160
161
162
163
164
165
    #######################################################################
    #
    # low-level text and character sequences
    #
    #######################################################################
    
166
    
167
    config     = "[" cfg_text §"]"
Eckhart Arnold's avatar
Eckhart Arnold committed
168
    cfg_text   = { ([//~] text) | CMDNAME | SPECIAL }
Eckhart Arnold's avatar
Eckhart Arnold committed
169
170
    block      = /{/ //~ { !blockcmd text_element //~ } §/}/
    text       = TEXTCHUNK { //~ TEXTCHUNK }
171
    
Eckhart Arnold's avatar
Eckhart Arnold committed
172
173
174
175
176
    no_command = "\begin{" | "\end" | BACKSLASH structural
    blockcmd   = BACKSLASH ( ( "begin{" | "end{" )
                             ( "enumerate" | "itemize" | "figure" | "quote"
                             | "quotation" | "tabular") "}"
                           | structural | begin_generic_block | end_generic_block )
177
178
179
    
    structural = "subsection" | "section" | "chapter" | "subsubsection"
               | "paragraph" | "subparagraph" | "item"
180
181
182
183
184
185
186
    
    
    #######################################################################
    #
    # Primitives
    #
    #######################################################################
187
    
188
    
189
    CMDNAME    = /\\(?:(?!_)\w)+/~
Eckhart Arnold's avatar
Eckhart Arnold committed
190
191
    TXTCOMMAND = /\\text\w+/
    ESCAPED    = /\\[%$&_\/{}]/
Eckhart Arnold's avatar
Eckhart Arnold committed
192
    SPECIAL    = /[$&_\\\\\/]/
Eckhart Arnold's avatar
Eckhart Arnold committed
193
    BRACKETS   = /[\[\]]/                       # left or right square bracket: [ ]
194
    LINEFEED   = /[\\][\\]/
Eckhart Arnold's avatar
Eckhart Arnold committed
195
    
196
    NAME       = /\w+/~
197
    INTEGER    = /\d+/~
198
199
200
    
    TEXTCHUNK  = /[^\\%$&\{\}\[\]\s\n]+/        # some piece of text excluding whitespace,
                                                # linefeed and special characters
Eckhart Arnold's avatar
Eckhart Arnold committed
201
    LF         = !GAP /[ \t]*\n[ \t]*/          # linefeed but not an empty line
202
203
    LFF        = ~/\n?/ -&LB [ WSPC ]              # at least one linefeed
    WSPC       = { COMMENT__ | /\s+/ }+         # arbitrary horizontal or vertical whitespace
Eckhart Arnold's avatar
Eckhart Arnold committed
204
    # WSPC       = { /\s+/~ | ~/\s+/ }+           # arbitrary horizontal or vertical whitespace
Eckhart Arnold's avatar
Eckhart Arnold committed
205
206
    PARSEP     = { GAP }+                       # paragraph separator
    GAP        = /[ \t]*(?:\n[ \t]*)+\n/~       # at least one empty line, i.e.
207
                                                # [whitespace] linefeed [whitespace] linefeed
208
209
    LB         = /\s*?\n|$/                     # backwards line break for Lookbehind-Operator
                                                # beginning of text marker '$' added for test code
Eckhart Arnold's avatar
Eckhart Arnold committed
210
211
212
    BACKSLASH  = /[\\]/
    
    EOF        = /(?!.)/                        # End-Of-File
213
    """
Eckhart Arnold's avatar
Eckhart Arnold committed
214
    begin_generic_block = Forward()
215
    block_environment = Forward()
216
    block_of_paragraphs = Forward()
Eckhart Arnold's avatar
Eckhart Arnold committed
217
    end_generic_block = Forward()
Eckhart Arnold's avatar
Eckhart Arnold committed
218
    paragraph = Forward()
219
    tabular_config = Forward()
220
    text_element = Forward()
Eckhart Arnold's avatar
Eckhart Arnold committed
221
    source_hash__ = "4003d206b4ecbd76dd8be99df87af4c0"
222
223
224
225
226
    parser_initialization__ = "upon instantiation"
    COMMENT__ = r'%.*(?:\n|$)'
    WSP__ = mixin_comment(whitespace=r'[ \t]*(?:\n(?![ \t]*\n)[ \t]*)?', comment=r'%.*(?:\n|$)')
    wspL__ = ''
    wspR__ = WSP__
Eckhart Arnold's avatar
Eckhart Arnold committed
227
    EOF = RegExp('(?!.)')
Eckhart Arnold's avatar
Eckhart Arnold committed
228
229
    BACKSLASH = RegExp('[\\\\]')
    LB = RegExp('\\s*?\\n|$')
Eckhart Arnold's avatar
Eckhart Arnold committed
230
231
    GAP = RE('[ \\t]*(?:\\n[ \\t]*)+\\n')
    PARSEP = OneOrMore(GAP)
Eckhart Arnold's avatar
Eckhart Arnold committed
232
    WSPC = OneOrMore(Alternative(RegExp(COMMENT__), RegExp('\\s+')))
233
    LFF = Series(RE('\\n?', wR='', wL=WSP__), Lookbehind(LB), Optional(WSPC))
Eckhart Arnold's avatar
Eckhart Arnold committed
234
    LF = Series(NegativeLookahead(GAP), RegExp('[ \\t]*\\n[ \\t]*'))
Eckhart Arnold's avatar
Eckhart Arnold committed
235
    TEXTCHUNK = RegExp('[^\\\\%$&\\{\\}\\[\\]\\s\\n]+')
236
    INTEGER = RE('\\d+')
237
    NAME = Capture(RE('\\w+'))
238
    LINEFEED = RegExp('[\\\\][\\\\]')
Eckhart Arnold's avatar
Eckhart Arnold committed
239
    BRACKETS = RegExp('[\\[\\]]')
Eckhart Arnold's avatar
Eckhart Arnold committed
240
    SPECIAL = RegExp('[$&_\\\\\\\\/]')
Eckhart Arnold's avatar
Eckhart Arnold committed
241
242
    ESCAPED = RegExp('\\\\[%$&_/{}]')
    TXTCOMMAND = RegExp('\\\\text\\w+')
243
    CMDNAME = RE('\\\\(?:(?!_)\\w)+')
Eckhart Arnold's avatar
Eckhart Arnold committed
244
    structural = Alternative(Token("subsection"), Token("section"), Token("chapter"), Token("subsubsection"), Token("paragraph"), Token("subparagraph"), Token("item"))
Eckhart Arnold's avatar
Eckhart Arnold committed
245
246
    blockcmd = Series(BACKSLASH, Alternative(Series(Alternative(Token("begin{"), Token("end{")), Alternative(Token("enumerate"), Token("itemize"), Token("figure"), Token("quote"), Token("quotation"), Token("tabular")), Token("}")), structural, begin_generic_block, end_generic_block))
    no_command = Alternative(Token("\\begin{"), Token("\\end"), Series(BACKSLASH, structural))
Eckhart Arnold's avatar
Eckhart Arnold committed
247
248
    text = Series(TEXTCHUNK, ZeroOrMore(Series(RE(''), TEXTCHUNK)))
    block = Series(RegExp('{'), RE(''), ZeroOrMore(Series(NegativeLookahead(blockcmd), text_element, RE(''))), Required(RegExp('}')))
Eckhart Arnold's avatar
Eckhart Arnold committed
249
    cfg_text = ZeroOrMore(Alternative(Series(Optional(RE('')), text), CMDNAME, SPECIAL))
250
    config = Series(Token("["), cfg_text, Required(Token("]")))
Eckhart Arnold's avatar
Eckhart Arnold committed
251
252
    cline = Series(Token("\\cline{"), INTEGER, Token("-"), INTEGER, Token("}"))
    hline = Token("\\hline")
253
    multicolumn = Series(Token("\\multicolumn"), Token("{"), INTEGER, Token("}"), tabular_config, block_of_paragraphs)
Eckhart Arnold's avatar
Eckhart Arnold committed
254
    caption = Series(Token("\\caption"), block)
Eckhart Arnold's avatar
Eckhart Arnold committed
255
    includegraphics = Series(Token("\\includegraphics"), Optional(config), block)
256
    footnote = Series(Token("\\footnote"), block_of_paragraphs)
Eckhart Arnold's avatar
Eckhart Arnold committed
257
    generic_command = Series(NegativeLookahead(no_command), CMDNAME, Optional(Series(Optional(Series(RE(''), config)), RE(''), block)))
258
    text_command = Alternative(TXTCOMMAND, ESCAPED, BRACKETS)
Eckhart Arnold's avatar
Eckhart Arnold committed
259
    known_command = Alternative(footnote, includegraphics, caption, multicolumn, hline, cline)
Eckhart Arnold's avatar
Eckhart Arnold committed
260
261
262
263
    command = Alternative(known_command, text_command, generic_command)
    inline_math = Series(RegExp('\\$'), RegExp('[^$]*'), Required(RegExp('\\$')))
    end_environment = Series(RegExp('\\\\end{'), Required(Pop(NAME)), Required(RegExp('}')))
    begin_environment = Series(RegExp('\\\\begin{'), Required(NAME), Required(RegExp('}')))
264
    end_inline_env = Synonym(end_environment)
Eckhart Arnold's avatar
Eckhart Arnold committed
265
266
    begin_inline_env = Alternative(Series(NegativeLookbehind(LB), begin_environment), Series(begin_environment, NegativeLookahead(LFF)))
    generic_inline_env = Series(begin_inline_env, RE(''), paragraph, Required(end_inline_env))
267
    known_inline_env = Synonym(inline_math)
268
    inline_environment = Alternative(known_inline_env, generic_inline_env)
Eckhart Arnold's avatar
Eckhart Arnold committed
269
    text_element.set(Alternative(text, block, inline_environment, command))
Eckhart Arnold's avatar
Eckhart Arnold committed
270
    paragraph.set(OneOrMore(Series(NegativeLookahead(blockcmd), Alternative(text_element, LINEFEED), RE(''))))
271
    sequence = OneOrMore(Series(Alternative(paragraph, block_environment), Optional(PARSEP)))
Eckhart Arnold's avatar
Eckhart Arnold committed
272
    block_of_paragraphs.set(Series(RE('{'), Optional(sequence), Required(RegExp('}'))))
273
    tabular_config.set(Series(Token("{"), RE('[lcr|]+'), Required(Token("}"))))
Eckhart Arnold's avatar
Eckhart Arnold committed
274
275
276
    tabular_cell = OneOrMore(Series(text_element, RE('')))
    tabular_row = Series(Optional(Alternative(multicolumn, tabular_cell)), ZeroOrMore(Series(Token("&"), Optional(Alternative(multicolumn, tabular_cell)))), Token("\\\\"), Optional(Alternative(hline, cline)))
    tabular = Series(Token("\\begin{tabular}"), tabular_config, ZeroOrMore(tabular_row), Required(Token("\\end{tabular}")))
Eckhart Arnold's avatar
Eckhart Arnold committed
277
278
279
    verbatim = Series(Token("\\begin{verbatim}"), sequence, Required(Token("\\end{verbatim}")))
    quotation = Alternative(Series(Token("\\begin{quotation}"), sequence, Required(Token("\\end{quotation}"))), Series(Token("\\begin{quote}"), sequence, Required(Token("\\end{quote}"))))
    figure = Series(Token("\\begin{figure}"), sequence, Required(Token("\\end{figure}")))
Eckhart Arnold's avatar
Eckhart Arnold committed
280
281
282
    item = Series(Token("\\item"), Optional(WSPC), sequence)
    enumerate = Series(Token("\\begin{enumerate}"), Optional(WSPC), ZeroOrMore(item), Required(Token("\\end{enumerate}")))
    itemize = Series(Token("\\begin{itemize}"), Optional(WSPC), ZeroOrMore(item), Required(Token("\\end{itemize}")))
Eckhart Arnold's avatar
Eckhart Arnold committed
283
284
    end_generic_block.set(Series(Lookbehind(LB), end_environment, LFF))
    begin_generic_block.set(Series(Lookbehind(LB), begin_environment, LFF))
Eckhart Arnold's avatar
Eckhart Arnold committed
285
    generic_block = Series(begin_generic_block, sequence, Required(end_generic_block))
Eckhart Arnold's avatar
Eckhart Arnold committed
286
    known_environment = Alternative(itemize, enumerate, figure, tabular, quotation, verbatim)
Eckhart Arnold's avatar
Eckhart Arnold committed
287
    block_environment.set(Alternative(known_environment, generic_block))
Eckhart Arnold's avatar
Eckhart Arnold committed
288
289
290
291
292
293
    Index = Series(Token("\\printindex"), Optional(WSPC))
    Bibliography = Series(Token("\\bibliography"), block, Optional(WSPC))
    SubParagraph = Series(Token("\\subparagraph"), block, Optional(WSPC), Optional(sequence))
    SubParagraphs = OneOrMore(Series(SubParagraph, Optional(WSPC)))
    Paragraph = Series(Token("\\paragraph"), block, Optional(WSPC), ZeroOrMore(Alternative(sequence, SubParagraphs)))
    Paragraphs = OneOrMore(Series(Paragraph, Optional(WSPC)))
Eckhart Arnold's avatar
Eckhart Arnold committed
294
    SubSubSection = Series(Token("\\subsubsection"), block, Optional(WSPC), ZeroOrMore(Alternative(sequence, Paragraphs)))
Eckhart Arnold's avatar
Eckhart Arnold committed
295
    SubSubSections = OneOrMore(Series(SubSubSection, Optional(WSPC)))
Eckhart Arnold's avatar
Eckhart Arnold committed
296
    SubSection = Series(Token("\\subsection"), block, Optional(WSPC), ZeroOrMore(Alternative(sequence, SubSubSections)))
Eckhart Arnold's avatar
Eckhart Arnold committed
297
    SubSections = OneOrMore(Series(SubSection, Optional(WSPC)))
Eckhart Arnold's avatar
Eckhart Arnold committed
298
    Section = Series(Token("\\section"), block, Optional(WSPC), ZeroOrMore(Alternative(sequence, SubSections)))
Eckhart Arnold's avatar
Eckhart Arnold committed
299
    Sections = OneOrMore(Series(Section, Optional(WSPC)))
Eckhart Arnold's avatar
Eckhart Arnold committed
300
    Chapter = Series(Token("\\chapter"), block, Optional(WSPC), ZeroOrMore(Alternative(sequence, Sections)))
Eckhart Arnold's avatar
Eckhart Arnold committed
301
    Chapters = OneOrMore(Series(Chapter, Optional(WSPC)))
302
    frontpages = Synonym(sequence)
Eckhart Arnold's avatar
Eckhart Arnold committed
303
    document = Series(Optional(WSPC), Token("\\begin{document}"), Optional(WSPC), frontpages, Optional(WSPC), Alternative(Chapters, Sections), Optional(WSPC), Optional(Bibliography), Optional(Index), Optional(WSPC), Token("\\end{document}"), Optional(WSPC), Required(EOF))
304
    preamble = OneOrMore(Series(Optional(WSPC), command))
305
306
307
308
309
310
311
312
313
    latexdoc = Series(preamble, document)
    root__ = latexdoc
    
def get_grammar() -> LaTeXGrammar:
    global thread_local_LaTeX_grammar_singleton
    try:
        grammar = thread_local_LaTeX_grammar_singleton
    except NameError:
        thread_local_LaTeX_grammar_singleton = LaTeXGrammar()
Eckhart Arnold's avatar
Eckhart Arnold committed
314
315
        grammar = thread_local_LaTeX_grammar_singleton
    return grammar
316
317
318
319
320
321
322
323
324


#######################################################################
#
# AST SECTION - Can be edited. Changes will be preserved.
#
#######################################################################


325
326
def streamline_whitespace(context):
    node = context[-1]
327
328
329
330
331
    assert node.tag_name in ['WSPC', ':Whitespace']
    s = str(node)
    c = s.find('%')
    n = s.find('\n')
    if c >= 0:
332
333
334
        node.result = '\n'
        # node.result = ('  ' if (n >= c) or (n < 0) else '\n')+ s[c:].rstrip(' \t')
        # node.parser = MockParser('COMMENT', '')
335
336
337
338
339
340
    elif s.find('\n') >= 0:
        node.result = '\n'
    else:
        node.result = ' '


341
342
343
344
def watch(node):
    print(node.as_sxpr())


345
346
LaTeX_AST_transformation_table = {
    # AST Transformations for the LaTeX-grammar
Eckhart Arnold's avatar
Eckhart Arnold committed
347
348
    "+": remove_children_if(lambda node: is_empty(node) or is_one_of(node, {'PARSEP'})),
    # remove_empty,
349
350
351
    "latexdoc": [],
    "preamble": [],
    "document": [],
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
    "frontpages": [],
    "Chapters": [],
    "Chapter": [],
    "Sections": [],
    "Section": [],
    "SubSections": [],
    "SubSection": [],
    "SubSubSections": [],
    "SubSubSection": [],
    "Paragraphs": [],
    "Paragraph": [],
    "SubParagraphs": [],
    "SubParagraph": [],
    "Bibliography": [],
    "Index": [],
    "block_environment": replace_by_single_child,
    "known_environment": replace_by_single_child,
    "generic_block": [],
370
    "begin_generic_block, end_generic_block": replace_by_single_child,
371
372
373
374
375
376
377
378
379
380
381
382
383
384
    "itemize, enumerate": [remove_brackets, flatten],
    "item": [remove_first],
    "figure": [],
    "quotation": [reduce_single_child, remove_brackets],
    "verbatim": [],
    "table": [],
    "table_config": [],
    "block_of_paragraphs": [],
    "sequence": [flatten],
    "paragraph": [flatten],
    "text_element": [],
    "inline_environment": replace_by_single_child,
    "known_inline_env": replace_by_single_child,
    "generic_inline_env": [],
385
    "begin_inline_env, end_inline_env": [replace_by_single_child],
386
387
388
389
    "begin_environment, end_environment": [remove_brackets, reduce_single_child],
    "inline_math": [remove_brackets, reduce_single_child],
    "command": [],
    "known_command": [],
Eckhart Arnold's avatar
Eckhart Arnold committed
390
    "text_command": [],
391
392
393
394
395
    "generic_command": [flatten],
    "footnote": [],
    "includegraphics": [],
    "caption": [],
    "config": [remove_brackets],
Eckhart Arnold's avatar
Eckhart Arnold committed
396
    "block": [remove_brackets, flatten],
397
398
    "text": collapse,
    "no_command, blockcmd": [],
399
400
    "structural": [],
    "CMDNAME": [remove_whitespace, reduce_single_child(is_anonymous)],
Eckhart Arnold's avatar
Eckhart Arnold committed
401
    "TXTCOMMAND": [remove_whitespace, reduce_single_child(is_anonymous)],
402
403
    "NAME": [reduce_single_child, remove_whitespace, reduce_single_child],
    "ESCAPED": [replace_content(lambda node: str(node)[1:])],
404
405
    "BRACKETS": [],
    "TEXTCHUNK": [],
406
407
    "LF": [],
    "PARSEP": replace_content(lambda node: '\n\n'),
Eckhart Arnold's avatar
Eckhart Arnold committed
408
    "GAP": [],
409
410
    "LB": [],
    "BACKSLASH": [],
411
    "EOF": [],
412
413
414
415
    ":Token": [],
    ":RE": replace_by_single_child,
    ":Whitespace": streamline_whitespace,
    "*": replace_by_single_child
416
417
}

418

419
420
def LaTeXTransform() -> TransformationDict:
    return partial(traverse, processing_table=LaTeX_AST_transformation_table.copy())
421
422

def get_transformer() -> TransformationFunc:
423
424
425
426
427
428
429
430
    global thread_local_LaTeX_transformer_singleton
    try:
        transformer = thread_local_LaTeX_transformer_singleton
    except NameError:
        thread_local_LaTeX_transformer_singleton = LaTeXTransform()
        transformer = thread_local_LaTeX_transformer_singleton
    return transformer

431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447


#######################################################################
#
# COMPILER SECTION - Can be edited. Changes will be preserved.
#
#######################################################################

class LaTeXCompiler(Compiler):
    """Compiler for the abstract-syntax-tree of a LaTeX source file.
    """

    def __init__(self, grammar_name="LaTeX", grammar_source=""):
        super(LaTeXCompiler, self).__init__(grammar_name, grammar_source)
        assert re.match('\w+\Z', grammar_name)

    def on_latexdoc(self, node):
Eckhart Arnold's avatar
Eckhart Arnold committed
448
        return node
449
450
451
452
453
454
455

    def on_preamble(self, node):
        pass

    def on_document(self, node):
        pass

Eckhart Arnold's avatar
Eckhart Arnold committed
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
    def on_frontpages(self, node):
        pass

    def on_Chapters(self, node):
        pass

    def on_Chapter(self, node):
        pass

    def on_Sections(self, node):
        pass

    def on_Section(self, node):
        pass

    def on_SubSections(self, node):
        pass

    def on_SubSection(self, node):
        pass

    def on_SubSubSections(self, node):
        pass

    def on_SubSubSection(self, node):
        pass

    def on_Paragraphs(self, node):
        pass

    def on_Paragraph(self, node):
        pass

    def on_SubParagraphs(self, node):
        pass

    def on_SubParagraph(self, node):
        pass

    def on_Bibliography(self, node):
        pass

    def on_Index(self, node):
        pass

    def on_block_environment(self, node):
        pass

    def on_known_environment(self, node):
        pass

    def on_generic_block(self, node):
        pass

    def on_begin_generic_block(self, node):
        pass

    def on_end_generic_block(self, node):
        pass

    def on_itemize(self, node):
        pass

    def on_enumerate(self, node):
        pass

    def on_item(self, node):
        pass

    def on_figure(self, node):
        pass

    def on_quotation(self, node):
        pass

    def on_verbatim(self, node):
        pass

    def on_table(self, node):
535
536
        pass

Eckhart Arnold's avatar
Eckhart Arnold committed
537
538
539
540
    def on_table_config(self, node):
        pass

    def on_block_of_paragraphs(self, node):
541
542
543
544
545
546
547
548
        pass

    def on_sequence(self, node):
        pass

    def on_paragraph(self, node):
        pass

549
    def on_text_element(self, node):
Eckhart Arnold's avatar
Eckhart Arnold committed
550
551
552
553
554
555
        pass

    def on_inline_environment(self, node):
        pass

    def on_known_inline_env(self, node):
556
557
        pass

Eckhart Arnold's avatar
Eckhart Arnold committed
558
    def on_generic_inline_env(self, node):
559
560
        pass

Eckhart Arnold's avatar
Eckhart Arnold committed
561
562
563
564
565
566
567
568
569
570
    def on_begin_inline_env(self, node):
        pass

    def on_begin_environment(self, node):
        pass

    def on_end_environment(self, node):
        pass

    def on_inline_math(self, node):
571
572
573
574
575
        pass

    def on_command(self, node):
        pass

Eckhart Arnold's avatar
Eckhart Arnold committed
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
    def on_known_command(self, node):
        pass

    def on_generic_command(self, node):
        pass

    def on_footnote(self, node):
        pass

    def on_includegraphics(self, node):
        pass

    def on_caption(self, node):
        pass

591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
    def on_config(self, node):
        pass

    def on_block(self, node):
        pass

    def on_text(self, node):
        pass

    def on_cfgtext(self, node):
        pass

    def on_word_sequence(self, node):
        pass

606
607
608
    def on_no_command(self, node):
        pass

609
610
611
    def on_blockcmd(self, node):
        pass

Eckhart Arnold's avatar
Eckhart Arnold committed
612
613
614
    def on_structural(self, node):
        pass

615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
    def on_CMDNAME(self, node):
        pass

    def on_NAME(self, node):
        pass

    def on_ESCAPED(self, node):
        pass

    def on_BRACKETS(self, node):
        pass

    def on_TEXTCHUNK(self, node):
        pass

    def on_WSPC(self, node):
        pass

    def on_LF(self, node):
        pass

    def on_PARSEP(self, node):
        pass

639
    def on_LB(self, node):
640
641
        pass

642
    def on_BACKSLASH(self, node):
Eckhart Arnold's avatar
Eckhart Arnold committed
643
644
        pass

645
    def on_EOF(self, node):
Eckhart Arnold's avatar
Eckhart Arnold committed
646
647
        pass

648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674

def get_compiler(grammar_name="LaTeX", grammar_source="") -> LaTeXCompiler:
    global thread_local_LaTeX_compiler_singleton
    try:
        compiler = thread_local_LaTeX_compiler_singleton
        compiler.set_grammar_name(grammar_name, grammar_source)
        return compiler
    except NameError:
        thread_local_LaTeX_compiler_singleton = \
            LaTeXCompiler(grammar_name, grammar_source)
        return thread_local_LaTeX_compiler_singleton 


#######################################################################
#
# END OF DHPARSER-SECTIONS
#
#######################################################################


def compile_src(source):
    """Compiles ``source`` and returns (result, errors, ast).
    """
    with logging("LOGS"):
        compiler = get_compiler()
        cname = compiler.__class__.__name__
        log_file_name = os.path.basename(os.path.splitext(source)[0]) \
675
676
            if is_filename(source) < 0 else cname[:cname.find('.')] + '_out'    
        result = compile_source(source, get_preprocessor(), 
677
678
679
680
681
682
683
684
685
686
687
688
689
                                get_grammar(),
                                get_transformer(), compiler)
    return result


if __name__ == "__main__":
    if len(sys.argv) > 1:
        result, errors, ast = compile_src(sys.argv[1])
        if errors:
            for error in errors:
                print(error)
            sys.exit(1)
        else:
Eckhart Arnold's avatar
Eckhart Arnold committed
690
            print(result.as_xml() if isinstance(result, Node) else result)
691
692
    else:
        print("Usage: LaTeXCompiler.py [FILENAME]")