LaTeXCompiler.py 21.4 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
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, \
Eckhart Arnold's avatar
Eckhart Arnold committed
22
23
    PreprocessorFunc, \
    Node, TransformationFunc, \
24
    traverse, join_children, remove_whitespace, remove_parser, \
Eckhart Arnold's avatar
Eckhart Arnold committed
25
    reduce_single_child, replace_by_single_child, remove_expendables, remove_empty, flatten, \
26
    collapse, replace_content, remove_brackets, remove_first
27
28
29
30


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

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

38

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


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

class LaTeXGrammar(Grammar):
    r"""Parser for a LaTeX source file, with this grammar:
    
52
    # LaTeX-Grammar for DHParser
53
54
55
56
57
58
    
    @ testing    = True
    @ whitespace = /[ \t]*(?:\n(?![ \t]*\n)[ \t]*)?/    # optional whitespace, including at most one linefeed
    @ comment    = /%.*(?:\n|$)/
    
    
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
    latexdoc       = preamble document
    preamble       = { command }+
    
    document       = [PARSEP] "\begin{document}" [PARSEP]
                     frontpages [PARSEP]
                     (Chapters | Sections) [PARSEP]
                     [Bibliography] [Index] [PARSEP]
                     "\end{document}" [PARSEP] §EOF
    frontpages     = sequence
    
    
    #######################################################################
    #
    # document structure
    #
    #######################################################################
    
    Chapters       = { Chapter [PARSEP] }+
    Chapter        = "\Chapter" block [PARSEP] { sequence | Sections }
    
    Sections       = { Section [PARSEP] }+
    Section        = "\Section" block [PARSEP] { sequence | SubSections }
    
    SubSections    = { SubSection [PARSEP] }+
    SubSection     = "\SubSection" block [PARSEP] { sequence | SubSubSections }
    
    SubSubSections = { SubSubSection [PARSEP] }+
    SubSubSection  = "\SubSubSection" block [PARSEP] { sequence | Paragraphs }
    
    Paragraphs     = { Paragraph [PARSEP] }+
    Paragraph      = "\paragraph" block [PARSEP] { sequence | SubParagraphs }
    
    SubParagraphs  = { SubParagraph [PARSEP] }+
    SubParagraph   = "\subparagpaph" block [PARSEP] { sequence }
    
    Bibliography   = "\bibliography" block [PARSEP]
    Index          = "\printindex" [PARSEP]
    
    
    #######################################################################
    #
    # document content
    #
    #######################################################################
    
    
    #### block environments ####
106
    
Eckhart Arnold's avatar
Eckhart Arnold committed
107
    block_environment   = known_environment | generic_block
108
    known_environment   = itemize | enumerate | figure | table | quotation
109
                        | verbatim
Eckhart Arnold's avatar
Eckhart Arnold committed
110
    generic_block       = begin_generic_block sequence §end_generic_block
111
112
    begin_generic_block = -&LB begin_environment -&LB
    end_generic_block   = -&LB  end_environment  -&LB
113
    
114
    itemize             = "\begin{itemize}" [PARSEP] { item } §"\end{itemize}"
115
    enumerate           = "\begin{enumerate}" [PARSEP] {item } §"\end{enumerate}"
116
    item                = "\item" [PARSEP] sequence
117
    
118
119
120
121
122
123
    figure              = "\begin{figure}" sequence "\end{figure}"
    quotation           = ("\begin{quotation}" sequence "\end{quotation}")
                        | ("\begin{quote}" sequence "\end{quote}")
    verbatim            = "\begin{verbatim}" sequence "\end{verbatim}"
    table               = "\begin{tabular}" table_config sequence "\end{tabular}"
    table_config        = "{" /[lcr|]+/~ "}"
124
125
    
    
126
127
128
    #### paragraphs and sequences of paragraphs ####
    
    block_of_paragraphs = /{/ sequence §/}/
129
    sequence            = { (paragraph | block_environment ) [PARSEP] }+
130
131
    
    paragraph           = { !blockcmd text_elements //~ }+
132
    text_elements       = command | text | block | inline_environment
133
134
135
136
    
    
    #### inline enivronments ####
    
137
    inline_environment  = known_inline_env | generic_inline_env
138
    known_inline_env    = inline_math
Eckhart Arnold's avatar
Eckhart Arnold committed
139
    generic_inline_env  = (begin_inline_env { text_elements }+ §end_environment)
Eckhart Arnold's avatar
Eckhart Arnold committed
140
    begin_inline_env    = (-!LB begin_environment) | (begin_environment -!LB)
Eckhart Arnold's avatar
Eckhart Arnold committed
141
    # end_inline_env      = (-!LB end_environment)   | (end_environment   -!LB)       # ambiguity with genric_block when EOF
142
143
    begin_environment   = "\begin{" §NAME §"}"
    end_environment     = "\end{" §::NAME §"}"
144
    
Eckhart Arnold's avatar
Eckhart Arnold committed
145
    inline_math         = "$" /[^$]*/ "$"
146
147
148
149
150
    
    
    #### commands ####
    
    command             = known_command | generic_command
Eckhart Arnold's avatar
Eckhart Arnold committed
151
    known_command       = footnote | includegraphics | caption
Eckhart Arnold's avatar
Eckhart Arnold committed
152
    generic_command     = !no_command CMDNAME [[ //~ config ] //~ block ]
153
154
    
    footnote            = "\footnote" block_of_paragraphs
Eckhart Arnold's avatar
Eckhart Arnold committed
155
156
    includegraphics     = "\includegraphics" config block
    caption             = "\caption" block
157
    
158
    
159
160
161
162
163
164
    #######################################################################
    #
    # low-level text and character sequences
    #
    #######################################################################
    
165
    
166
    config     = "[" cfgtext §"]"
167
    block      = /{/ { text_elements } §/}/
168
169
170
171
172
    
    text       = { cfgtext | (BRACKETS //~) }+
    cfgtext    = { word_sequence | (ESCAPED //~) }+
    word_sequence = { TEXTCHUNK //~ }+
    
Eckhart Arnold's avatar
Eckhart Arnold committed
173
174
175
176
177
    no_command = "\begin{" | "\end" | BACKSLASH structural
    blockcmd   = BACKSLASH ( ( "begin{" | "end{" )
                             ( "enumerate" | "itemize" | "figure" | "quote"
                             | "quotation" | "tabular") "}"
                           | structural | begin_generic_block | end_generic_block )
178
179
180
    
    structural = "subsection" | "section" | "chapter" | "subsubsection"
               | "paragraph" | "subparagraph" | "item"
181
182
183
184
185
186
187
    
    
    #######################################################################
    #
    # Primitives
    #
    #######################################################################
188
    
189
    
190
191
192
193
194
195
196
197
    CMDNAME    = /\\(?:(?!_)\w)+/~
    NAME       = /\w+/~
    
    ESCAPED    = /\\[%$&_\/]/
    BRACKETS   = /[\[\]]/                       # left or right square bracket: [ ]
    TEXTCHUNK  = /[^\\%$&\{\}\[\]\s\n]+/        # some piece of text excluding whitespace,
                                                # linefeed and special characters
    WSPC       = /[ \t]+/                       # (horizontal) whitespace
Eckhart Arnold's avatar
Eckhart Arnold committed
198
    LF         = !PARSEP /[ \t]*\n[ \t]*/       # linefeed but not an empty line
199
200
    PARSEP     = /[ \t]*(?:\n[ \t]*)+\n[ \t]*/  # at least one empty line, i.e.
                                                # [whitespace] linefeed [whitespace] linefeed
201
202
    LB         = /\s*?\n|$/                     # backwards line break for Lookbehind-Operator
                                                # beginning of text marker '$' added for test code
Eckhart Arnold's avatar
Eckhart Arnold committed
203
204
205
    BACKSLASH  = /[\\]/
    
    EOF        = /(?!.)/                        # End-Of-File
206
    """
Eckhart Arnold's avatar
Eckhart Arnold committed
207
    begin_generic_block = Forward()
208
    block_environment = Forward()
209
    block_of_paragraphs = Forward()
Eckhart Arnold's avatar
Eckhart Arnold committed
210
    end_generic_block = Forward()
211
    text_elements = Forward()
Eckhart Arnold's avatar
Eckhart Arnold committed
212
    source_hash__ = "06385bac4dd7cb009bd29712a8fc692c"
213
214
215
216
217
    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
218
    EOF = RegExp('(?!.)')
Eckhart Arnold's avatar
Eckhart Arnold committed
219
220
    BACKSLASH = RegExp('[\\\\]')
    LB = RegExp('\\s*?\\n|$')
Eckhart Arnold's avatar
Eckhart Arnold committed
221
222
223
224
225
226
    PARSEP = RegExp('[ \\t]*(?:\\n[ \\t]*)+\\n[ \\t]*')
    LF = Series(NegativeLookahead(PARSEP), RegExp('[ \\t]*\\n[ \\t]*'))
    WSPC = RegExp('[ \\t]+')
    TEXTCHUNK = RegExp('[^\\\\%$&\\{\\}\\[\\]\\s\\n]+')
    BRACKETS = RegExp('[\\[\\]]')
    ESCAPED = RegExp('\\\\[%$&_/]')
227
228
    NAME = Capture(RE('\\w+'))
    CMDNAME = RE('\\\\(?:(?!_)\\w)+')
Eckhart Arnold's avatar
Eckhart Arnold committed
229
    structural = Alternative(Token("subsection"), Token("section"), Token("chapter"), Token("subsubsection"), Token("paragraph"), Token("subparagraph"), Token("item"))
Eckhart Arnold's avatar
Eckhart Arnold committed
230
231
    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))
232
233
234
    word_sequence = OneOrMore(Series(TEXTCHUNK, RE('')))
    cfgtext = OneOrMore(Alternative(word_sequence, Series(ESCAPED, RE(''))))
    text = OneOrMore(Alternative(cfgtext, Series(BRACKETS, RE(''))))
Eckhart Arnold's avatar
Eckhart Arnold committed
235
    block = Series(RegExp('{'), ZeroOrMore(text_elements), Required(RegExp('}')))
236
    config = Series(Token("["), cfgtext, Required(Token("]")))
Eckhart Arnold's avatar
Eckhart Arnold committed
237
238
    caption = Series(Token("\\caption"), block)
    includegraphics = Series(Token("\\includegraphics"), config, block)
239
    footnote = Series(Token("\\footnote"), block_of_paragraphs)
Eckhart Arnold's avatar
Eckhart Arnold committed
240
    generic_command = Series(NegativeLookahead(no_command), CMDNAME, Optional(Series(Optional(Series(RE(''), config)), RE(''), block)))
Eckhart Arnold's avatar
Eckhart Arnold committed
241
    known_command = Alternative(footnote, includegraphics, caption)
242
    command = Alternative(known_command, generic_command)
Eckhart Arnold's avatar
Eckhart Arnold committed
243
    inline_math = Series(Token("$"), RegExp('[^$]*'), Token("$"))
244
245
    end_environment = Series(Token("\\end{"), Required(Pop(NAME)), Required(Token("}")))
    begin_environment = Series(Token("\\begin{"), Required(NAME), Required(Token("}")))
Eckhart Arnold's avatar
Eckhart Arnold committed
246
    begin_inline_env = Alternative(Series(NegativeLookbehind(LB), begin_environment), Series(begin_environment, NegativeLookbehind(LB)))
Eckhart Arnold's avatar
Eckhart Arnold committed
247
    generic_inline_env = Series(begin_inline_env, OneOrMore(text_elements), Required(end_environment))
248
    known_inline_env = Synonym(inline_math)
249
250
    inline_environment = Alternative(known_inline_env, generic_inline_env)
    text_elements.set(Alternative(command, text, block, inline_environment))
251
    paragraph = OneOrMore(Series(NegativeLookahead(blockcmd), text_elements, RE('')))
252
    sequence = OneOrMore(Series(Alternative(paragraph, block_environment), Optional(PARSEP)))
Eckhart Arnold's avatar
Eckhart Arnold committed
253
    block_of_paragraphs.set(Series(RegExp('{'), sequence, Required(RegExp('}'))))
254
255
256
    table_config = Series(Token("{"), RE('[lcr|]+'), Token("}"))
    table = Series(Token("\\begin{tabular}"), table_config, sequence, Token("\\end{tabular}"))
    verbatim = Series(Token("\\begin{verbatim}"), sequence, Token("\\end{verbatim}"))
Eckhart Arnold's avatar
Eckhart Arnold committed
257
    quotation = Alternative(Series(Token("\\begin{quotation}"), sequence, Token("\\end{quotation}")), Series(Token("\\begin{quote}"), sequence, Token("\\end{quote}")))
258
259
    figure = Series(Token("\\begin{figure}"), sequence, Token("\\end{figure}"))
    item = Series(Token("\\item"), Optional(PARSEP), sequence)
Eckhart Arnold's avatar
Eckhart Arnold committed
260
    enumerate = Series(Token("\\begin{enumerate}"), Optional(PARSEP), ZeroOrMore(item), Required(Token("\\end{enumerate}")))
261
    itemize = Series(Token("\\begin{itemize}"), Optional(PARSEP), ZeroOrMore(item), Required(Token("\\end{itemize}")))
262
263
    end_generic_block.set(Series(Lookbehind(LB), end_environment, Lookbehind(LB)))
    begin_generic_block.set(Series(Lookbehind(LB), begin_environment, Lookbehind(LB)))
Eckhart Arnold's avatar
Eckhart Arnold committed
264
    generic_block = Series(begin_generic_block, sequence, Required(end_generic_block))
265
    known_environment = Alternative(itemize, enumerate, figure, table, quotation, verbatim)
Eckhart Arnold's avatar
Eckhart Arnold committed
266
    block_environment.set(Alternative(known_environment, generic_block))
267
268
269
270
271
272
    Index = Series(Token("\\printindex"), Optional(PARSEP))
    Bibliography = Series(Token("\\bibliography"), block, Optional(PARSEP))
    SubParagraph = Series(Token("\\subparagpaph"), block, Optional(PARSEP), ZeroOrMore(sequence))
    SubParagraphs = OneOrMore(Series(SubParagraph, Optional(PARSEP)))
    Paragraph = Series(Token("\\paragraph"), block, Optional(PARSEP), ZeroOrMore(Alternative(sequence, SubParagraphs)))
    Paragraphs = OneOrMore(Series(Paragraph, Optional(PARSEP)))
Eckhart Arnold's avatar
Eckhart Arnold committed
273
    SubSubSection = Series(Token("\\SubSubSection"), block, Optional(PARSEP), ZeroOrMore(Alternative(sequence, Paragraphs)))
274
    SubSubSections = OneOrMore(Series(SubSubSection, Optional(PARSEP)))
Eckhart Arnold's avatar
Eckhart Arnold committed
275
    SubSection = Series(Token("\\SubSection"), block, Optional(PARSEP), ZeroOrMore(Alternative(sequence, SubSubSections)))
276
277
278
279
280
281
    SubSections = OneOrMore(Series(SubSection, Optional(PARSEP)))
    Section = Series(Token("\\Section"), block, Optional(PARSEP), ZeroOrMore(Alternative(sequence, SubSections)))
    Sections = OneOrMore(Series(Section, Optional(PARSEP)))
    Chapter = Series(Token("\\Chapter"), block, Optional(PARSEP), ZeroOrMore(Alternative(sequence, Sections)))
    Chapters = OneOrMore(Series(Chapter, Optional(PARSEP)))
    frontpages = Synonym(sequence)
Eckhart Arnold's avatar
Eckhart Arnold committed
282
    document = Series(Optional(PARSEP), Token("\\begin{document}"), Optional(PARSEP), frontpages, Optional(PARSEP), Alternative(Chapters, Sections), Optional(PARSEP), Optional(Bibliography), Optional(Index), Optional(PARSEP), Token("\\end{document}"), Optional(PARSEP), Required(EOF))
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
    preamble = OneOrMore(command)
    latexdoc = Series(preamble, document)
    root__ = latexdoc
    
def get_grammar() -> LaTeXGrammar:
    global thread_local_LaTeX_grammar_singleton
    try:
        grammar = thread_local_LaTeX_grammar_singleton
        return grammar
    except NameError:
        thread_local_LaTeX_grammar_singleton = LaTeXGrammar()
        return thread_local_LaTeX_grammar_singleton


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


def streamline_whitespace(node):
    assert node.tag_name in ['WSPC', ':Whitespace']
    s = str(node)
    c = s.find('%')
    n = s.find('\n')
    if c >= 0:
        node.result = ('  ' if (n >= c) or (n < 0) else '\n')+ s[c:].rstrip(' \t')
    elif s.find('\n') >= 0:
        node.result = '\n'
    else:
        node.result = ' '


LaTeX_AST_transformation_table = {
    # AST Transformations for the LaTeX-grammar
    "+":
        remove_empty,
    "latexdoc": [],
    "preamble": [],
    "document": [],
    "blockenv": [],
    "parblock": [],
    "sequence":
327
328
329
330
331
        [flatten, remove_parser('PARSEP'), replace_by_single_child],
    "enumerate, itemize":
        [remove_brackets, remove_parser('PARSEP'), reduce_single_child],
    "item":
        [remove_first, remove_parser('PARSEP')],
332
333
    "paragraph":
        [flatten(lambda node: not node.parser.name or node.parser.name == "text"),
334
335
336
337
338
339
340
341
342
         join_children('text', ':Whitespace')],
    "quotation, generic_bloc, generic_inline_env, inline_math":
        [remove_brackets],
    "inline_environment": [],
    "begin_environment": [],
    "end_environment": [],
    # "command": [],
    "generic_command": [],
    "config, block": [remove_brackets, reduce_single_child],
343
    "text":
344
        [reduce_single_child, join_children('text', 'word_sequence', ':Whitespace')],
345
346
347
348
349
350
    "cfgtext": [flatten, reduce_single_child],
    "word_sequence":
        [collapse],
    "blockcmd": [],
    "CMDNAME":
        [remove_expendables, reduce_single_child],
351
    "NAME": [reduce_single_child],
352
353
354
355
    "ESCAPED": [reduce_single_child],
    "BRACKETS": [],
    "TEXTCHUNK": [],
    "WSPC, :Whitespace":
356
        [],  # streamline_whitespace,  # whitespace will be removed anyway
357
358
359
    "LF":
        replace_content(lambda node: '\n'),
    "PARSEP":
360
        [],  # replace_content(lambda node: '\n\n'),
361
    "EOF": [],
362
363
    ":Token":
        [],  # [remove_whitespace, reduce_single_child],  # Tokens will be removed anyway?
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
    "*":
        replace_by_single_child,
}

LaTeXTransform = partial(traverse, processing_table=LaTeX_AST_transformation_table)
# LaTeXTransform = lambda tree : 1

def get_transformer() -> TransformationFunc:
    return LaTeXTransform


#######################################################################
#
# 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
390
        return node
391
392
393
394
395
396
397

    def on_preamble(self, node):
        pass

    def on_document(self, node):
        pass

Eckhart Arnold's avatar
Eckhart Arnold committed
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
    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):
477
478
        pass

Eckhart Arnold's avatar
Eckhart Arnold committed
479
480
481
482
    def on_table_config(self, node):
        pass

    def on_block_of_paragraphs(self, node):
483
484
485
486
487
488
489
490
        pass

    def on_sequence(self, node):
        pass

    def on_paragraph(self, node):
        pass

Eckhart Arnold's avatar
Eckhart Arnold committed
491
492
493
494
495
496
497
    def on_text_elements(self, node):
        pass

    def on_inline_environment(self, node):
        pass

    def on_known_inline_env(self, node):
498
499
        pass

Eckhart Arnold's avatar
Eckhart Arnold committed
500
    def on_generic_inline_env(self, node):
501
502
        pass

Eckhart Arnold's avatar
Eckhart Arnold committed
503
504
505
506
507
508
509
510
511
512
513
514
515
    def on_begin_inline_env(self, node):
        pass

    def on_end_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):
516
517
518
519
520
        pass

    def on_command(self, node):
        pass

Eckhart Arnold's avatar
Eckhart Arnold committed
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
    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

536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
    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

    def on_blockcmd(self, node):
        pass

Eckhart Arnold's avatar
Eckhart Arnold committed
554
555
556
    def on_structural(self, node):
        pass

557
558
559
560
561
562
    def on_CMDNAME(self, node):
        pass

    def on_NAME(self, node):
        pass

Eckhart Arnold's avatar
Eckhart Arnold committed
563
564
565
    def on_MATH(self, node):
        pass

566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
    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

    def on_EOF(self, node):
        pass

Eckhart Arnold's avatar
Eckhart Arnold committed
587
588
589
590
591
592
    def on_SUCC_LB(self, node):
        pass

    def on_PRED_LB(self, node):
        pass

593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619

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]) \
Eckhart Arnold's avatar
Eckhart Arnold committed
620
621
            if is_filename(source) < 0 else cname[:cname.find('.')] + '_out'
        result = compile_source(source, get_preprocessor(),
622
623
624
625
626
627
628
629
630
631
632
633
634
                                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
635
            print(result.as_xml() if isinstance(result, Node) else result)
636
637
    else:
        print("Usage: LaTeXCompiler.py [FILENAME]")