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

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


10
from collections import defaultdict
11
12
import os
import sys
Eckhart Arnold's avatar
Eckhart Arnold committed
13
14
from functools import partial

15
16
17
18
try:
    import regex as re
except ImportError:
    import re
19
from DHParser import is_filename, Grammar, Compiler, Lookbehind, Alternative, Pop, \
20
21
    _Token, Synonym, Whitespace, \
    Option, NegativeLookbehind, OneOrMore, RegExp, Series, _RE, Capture, \
22
    ZeroOrMore, Forward, NegativeLookahead, mixin_comment, compile_source, \
23
    PreprocessorFunc, TransformationDict, \
Eckhart Arnold's avatar
Eckhart Arnold committed
24
    Node, TransformationFunc, traverse, remove_children_if, is_anonymous, \
Eckhart Arnold's avatar
Eckhart Arnold committed
25
    reduce_single_child, replace_by_single_child, remove_whitespace, \
26
27
    flatten, is_empty, collapse, replace_content, replace_content_by, remove_brackets, \
    is_one_of, traverse_locally, remove_tokens, remove_nodes, TOKEN_PTYPE, Error
28
from DHParser.log import logging
29
30
31
32


#######################################################################
#
Eckhart Arnold's avatar
Eckhart Arnold committed
33
# PREPROCESSOR SECTION - Can be edited. Changes will be preserved.
34
35
36
#
#######################################################################

Eckhart Arnold's avatar
Eckhart Arnold committed
37
def LaTeXPreprocessor(text):
38
39
    return text

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


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

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


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


353
def streamline_whitespace(context):
354
    if context[-2].parser.ptype == ":_Token":
eckhart's avatar
eckhart committed
355
        return
356
    node = context[-1]
357
    assert node.tag_name in ['WSPC', ':Whitespace']
358
359
    s = node.content
    if s.find('%') >= 0:
360
        node.result = '\n'
361
        # c = s.find('%')
362
363
        # node.result = ('  ' if (n >= c) or (n < 0) else '\n')+ s[c:].rstrip(' \t')
        # node.parser = MockParser('COMMENT', '')
364
365
366
    elif s.find('\n') >= 0:
        node.result = '\n'
    else:
367
        node.result = ' ' if s else ''
368
369


370
371
372
def watch(node):
    print(node.as_sxpr())

eckhart's avatar
eckhart committed
373
374
flatten_structure = flatten(lambda context: is_anonymous(context) or is_one_of(
    context, {"Chapters", "Sections", "SubSections", "SubSubSections", "Paragraphs",
375
              "SubParagraphs", "sequence"}), recursive=True)
eckhart's avatar
eckhart committed
376
377
378


def is_commandname(context):
eckhart's avatar
eckhart committed
379
380
    """Returns True, if last node in the content represents a (potentially
    unknown) LaTeX-command."""
eckhart's avatar
eckhart committed
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
    node = context[-1]
    if node.parser.ptype == TOKEN_PTYPE:
        parent = context[-2]
        if len(parent.children) > 1:
            parent_name = parent.tag_name.lower()
            content = str(node)
            if (content == '\\' + parent_name
                or content == '\\begin{' + parent_name + '}'
                or content == '\\end{' + parent_name + '}'):
                return True
    return False


drop_expendables = remove_children_if(lambda context: is_empty(context) or
                                                      is_one_of(context, {'PARSEP', 'WSPC'}) or
                                                      is_commandname(context))

398

399
400
LaTeX_AST_transformation_table = {
    # AST Transformations for the LaTeX-grammar
eckhart's avatar
eckhart committed
401
    "+": [drop_expendables, flatten_structure],
402
    "latexdoc": [],
403
    "preamble": [traverse_locally({'+': remove_whitespace, 'block': replace_by_single_child})],
eckhart's avatar
eckhart committed
404
    "document": [flatten_structure],
eckhart's avatar
eckhart committed
405
    "pdfinfo": [],
Eckhart Arnold's avatar
Eckhart Arnold committed
406
    "frontpages": reduce_single_child,
407
    "Chapters, Sections, SubSections, SubSubSections, Paragraphs, SubParagraphs": [],
eckhart's avatar
eckhart committed
408
    "Chapter, Section, SubSection, SubSubSection, Paragraph, SubParagraph": [],
Eckhart Arnold's avatar
Eckhart Arnold committed
409
    "heading": reduce_single_child,
410
411
    "Bibliography": [],
    "Index": [],
412
413
    "block_environment": replace_by_single_child,
    "known_environment": replace_by_single_child,
414
    "generic_block": [],
415
    "begin_generic_block, end_generic_block": [remove_nodes('NEW_LINE'), replace_by_single_child],
416
    "itemize, enumerate": [remove_brackets, flatten],
eckhart's avatar
eckhart committed
417
    "item": [],
418
    "figure": [],
Eckhart Arnold's avatar
Eckhart Arnold committed
419
    "quotation": [reduce_single_child, remove_brackets],
420
    "verbatim": [],
eckhart's avatar
eckhart committed
421
    "tabular": [],
Eckhart Arnold's avatar
Eckhart Arnold committed
422
    "tabular_config, block_of_paragraphs": [remove_brackets, reduce_single_child],
eckhart's avatar
eckhart committed
423
424
425
    "tabular_row": [flatten, remove_tokens('&', '\\')],
    "tabular_cell": [flatten, remove_whitespace],
    "multicolumn": [remove_tokens('{', '}')],
Eckhart Arnold's avatar
Eckhart Arnold committed
426
    "hline": [remove_whitespace, reduce_single_child],
427
428
    "sequence": [flatten],
    "paragraph": [flatten],
429
430
431
432
    "text_element": replace_by_single_child,
    "line_element": replace_by_single_child,
    "inline_environment": replace_by_single_child,
    "known_inline_env": replace_by_single_child,
433
    "generic_inline_env": [],
434
    "begin_inline_env, end_inline_env": [replace_by_single_child],
Eckhart Arnold's avatar
Eckhart Arnold committed
435
436
    "begin_environment, end_environment": [remove_brackets, reduce_single_child],
    "inline_math": [remove_brackets, reduce_single_child],
437
438
    "command": replace_by_single_child,
    "known_command": replace_by_single_child,
Eckhart Arnold's avatar
Eckhart Arnold committed
439
    "text_command": [],
440
441
442
443
    "generic_command": [flatten],
    "footnote": [],
    "includegraphics": [],
    "caption": [],
Eckhart Arnold's avatar
Eckhart Arnold committed
444
    "config": [remove_brackets, reduce_single_child],
445
    "block": [remove_brackets, flatten, replace_by_single_child],
446
447
    "text": collapse,
    "no_command, blockcmd": [],
448
    "structural": [],
Eckhart Arnold's avatar
Eckhart Arnold committed
449
450
451
    "CMDNAME": [remove_whitespace, reduce_single_child],
    "TXTCOMMAND": [remove_whitespace, reduce_single_child],
    "NAME": [reduce_single_child, remove_whitespace, reduce_single_child],
452
    "ESCAPED": [replace_content(lambda node: str(node)[1:])],
453
454
    "BRACKETS": [],
    "TEXTCHUNK": [],
455
456
    "LF": [],
    "PARSEP": replace_content(lambda node: '\n\n'),
Eckhart Arnold's avatar
Eckhart Arnold committed
457
    "GAP": [],
458
459
    "LB": [],
    "BACKSLASH": [],
460
    "EOF": [],
461
462
    # "PARSEP": [replace_content_by('\n\n')],
    # "WSPC": [replace_content_by(' ')],
463
    ":_Token":
Eckhart Arnold's avatar
Eckhart Arnold committed
464
        [remove_whitespace, reduce_single_child],
465
    ":_RE": replace_by_single_child,
466
    ":Whitespace": streamline_whitespace,
467
    "*": replace_by_single_child
468
469
}

470

471
472
def LaTeXTransform() -> TransformationDict:
    return partial(traverse, processing_table=LaTeX_AST_transformation_table.copy())
473

474

475
def get_transformer() -> TransformationFunc:
476
477
478
479
480
481
482
483
    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

484
485
486
487
488
489
490
491


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

492
493
494
495
496
497

def empty_defaultdict():
    """Returns a defaultdict with an empty defaultdict as default value."""
    return defaultdict(empty_defaultdict)


498
499
500
class LaTeXCompiler(Compiler):
    """Compiler for the abstract-syntax-tree of a LaTeX source file.
    """
501
502
    KNOWN_DOCUMENT_CLASSES = {'book', 'article'}
    KNOWN_LANGUAGES = {'english', 'german'}
503
504
505
506

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

509
510
511
512
    # def on_latexdoc(self, node):
    #     self.compile(node['preamble'])
    #     self.compile(node['document'])
    #     return node
513

514
515
    # def on_preamble(self, node):
    #     return node
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539

    # def on_document(self, node):
    #     return node

    # def on_frontpages(self, node):
    #     return node

    # def on_Chapters(self, node):
    #     return node

    # def on_Chapter(self, node):
    #     return node

    # def on_Sections(self, node):
    #     return node

    # def on_Section(self, node):
    #     return node

    # def on_SubSections(self, node):
    #     return node

    # def on_SubSection(self, node):
    #     return node
540

541
542
    # def on_SubSubSections(self, node):
    #     return node
543

544
545
    # def on_SubSubSection(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
546

547
548
    # def on_Paragraphs(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
549

550
551
    # def on_Paragraph(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
552

553
554
    # def on_SubParagraphs(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
555

556
557
    # def on_SubParagraph(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
558

559
560
    # def on_Bibliography(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
561

562
563
    # def on_Index(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
564

565
566
    # def on_heading(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
567

568
569
    # def on_block_environment(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
570

571
572
    # def on_known_environment(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
573

574
575
    # def on_generic_block(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
576

577
578
    # def on_begin_generic_block(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
579

580
581
    # def on_end_generic_block(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
582

583
584
    # def on_itemize(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
585

586
587
    # def on_enumerate(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
588

589
590
    # def on_item(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
591

592
593
    # def on_figure(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
594

595
596
    # def on_quotation(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
597

598
599
    # def on_verbatim(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
600

601
602
    # def on_tabular(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
603

604
605
    # def on_tabular_row(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
606

607
608
    # def on_tabular_cell(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
609

610
611
    # def on_tabular_config(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
612

613
614
    # def on_block_of_paragraphs(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
615

616
617
    # def on_sequence(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
618

619
620
    # def on_paragraph(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
621

622
623
    # def on_text_element(self, node):
    #     return node
624

625
626
    # def on_line_element(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
627

628
629
    # def on_inline_environment(self, node):
    #     return node
630

631
632
    # def on_known_inline_env(self, node):
    #     return node
633

634
635
    # def on_generic_inline_env(self, node):
    #     return node
636

637
638
    # def on_begin_inline_env(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
639

640
641
    # def on_end_inline_env(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
642

643
644
    # def on_begin_environment(self, node):
    #     return node
645

646
647
    # def on_end_environment(self, node):
    #     return node
648

649
650
    # def on_inline_math(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
651

652
653
    # def on_command(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
654

655
656
    # def on_known_command(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
657

658
659
    # def on_text_command(self, node):
    #     return node
660

661
662
    # def on_generic_command(self, node):
    #     return node
663

664
665
    # def on_footnote(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
666

667
668
    # def on_includegraphics(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
669

670
671
    # def on_caption(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
672

673
674
    # def on_multicolumn(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
675

676
677
    # def on_hline(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
678

679
680
    # def on_cline(self, node):
    #     return node
681

682
    def on_documentclass(self, node):
eckhart's avatar
eckhart committed
683
684
685
686
        """
        Saves the documentclass (if known) and the language (if given)
        in the metadata dictionary.
        """
687
688
689
690
691
692
        if 'config' in node:
            for it in {part.strip() for part in node['config'].content.split(',')}:
                if it in self.KNOWN_LANGUAGES:
                    if 'language' in node.attributes:
                        self.metadata['language'] = it
                    else:
eckhart's avatar
eckhart committed
693
                        self.tree.new_error(node, 'Only one document language supported. '
694
695
                                            'Using %s, ignoring %s.'
                                            % (self.metadata['language'], it), Error.WARNING)
696
697
698
699
700
701
702
        if node['text'] in self.KNOWN_DOCUMENT_CLASSES:
            self.metadata['documentclass'] = node['text']
        return node

    def on_pdfinfo(self, node):
        return node

703
704
    # def on_config(self, node):
    #     return node
705

706
707
    # def on_cfg_text(self, node):
    #     return node
708

709
710
    # def on_block(self, node):
    #     return node
711

712
713
    # def on_text(self, node):
    #     return node
714

715
716
    # def on_no_command(self, node):
    #     return node
717

718
719
    # def on_blockcmd(self, node):
    #     return node
720

721
722
    # def on_structural(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
723

724
725
    # def on_CMDNAME(self, node):
    #     return node
726

727
728
    # def on_TXTCOMMAND(self, node):
    #     return node
729

730
731
    # def on_ESCAPED(self, node):
    #     return node
732

733
734
    # def on_SPECIAL(self, node):
    #     return node
735

736
737
    # def on_BRACKETS(self, node):
    #     return node
738

739
740
    # def on_LINEFEED(self, node):
    #     return node
741

742
743
    # def on_NAME(self, node):
    #     return node
744

745
746
    # def on_INTEGER(self, node):
    #     return node
747

748
749
    # def on_TEXTCHUNK(self, node):
    #     return node
750

751
752
    # def on_LF(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
753

754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
    # def on_LFF(self, node):
    #     return node

    # def on_PARSEP(self, node):
    #     return node

    # def on_WSPC(self, node):
    #     return node

    # def on_GAP(self, node):
    #     return node

    # def on_NEW_LINE(self, node):
    #     return node

    # def on_LB(self, node):
    #     return node

    # def on_BACKSLASH(self, node):
    #     return node

    # def on_EOF(self, node):
    #     return node
Eckhart Arnold's avatar
Eckhart Arnold committed
777

778
779
780
781
782
783
784
785
786

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)
    except NameError:
        thread_local_LaTeX_compiler_singleton = \
            LaTeXCompiler(grammar_name, grammar_source)
787
788
        compiler = thread_local_LaTeX_compiler_singleton
    return compiler
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804


#######################################################################
#
# 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]) \
805
806
            if is_filename(source) < 0 else cname[:cname.find('.')] + '_out'    
        result = compile_source(source, get_preprocessor(), 
807
808
809
810
811
812
813
814
815
816
817
818
819
                                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
820
            print(result.as_xml() if isinstance(result, Node) else result)
821
822
    else:
        print("Usage: LaTeXCompiler.py [FILENAME]")