This repository has been archived by the owner on Feb 5, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
tex2txt.py
1990 lines (1766 loc) · 71.9 KB
/
tex2txt.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
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
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Tex2txt, a flexible LaTeX filter
# Copyright (C) 2018-2020 Matthias Baumann
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
#######################################################################
#
# Python3:
# Extract raw text from LaTeX file, write result to standard output
#
# Usage and main operations:
# - see README.md
#
# Principle of operation:
# - read complete input text into a string, then make replacements
# - replacements are performed via the "reimplementation" mysub() of
# re.sub() in order to observe deletion and inclusion of line breaks
# - in order to treat nested braces / brackets and some nested
# environments, we construct regular expressions by iteration;
# maximum recognised nesting depth (and thus length of these expressions)
# is controlled by the variables parms.max_depth_br and
# parms.max_depth_env
#
class Aux:
pass
parms = Aux()
# LAB:MACROS
# these are macros with tailored treatment;
# replacement only if not given in option --extr
#
# Simple(name, repl='', extr=''):
# abbreviation for Macro(name, '', repl, extr)
#
# Macro(name, args, repl='', extr=''):
# name:
# - macro name without leading backslash
# - characters with special meaning in regular expressions, e.g. '*',
# may need to be escaped; see for example declaration of \hspace,
# and use only unreferenced groups (?:...), see \renewcommand
# args:
# - string that codes argument sequence
# - A: a mandatory {...} argument
# - O: an optional [...] argument
# - P: a mandatory [...] argument, see for instance \cite
# repl:
# - replacement pattern, r'...\d...' (d: single digit) extracts text
# from position d in args (counting from 1)
# - other escape rules: see escape handling at myexpand() below;
# e.g., include a single backslash: repl=r'...\\...'
# - inclusion of % only accepted as escaped version r'...\\%...',
# will be resolved to % at the end by before_output()
# - inclusion of double backslash \\ and replacement ending with \
# will be rejected
# - reference by r'\d' to an optional argument will be refused
# extr:
# - append this replacement (specified as in repl) at the end
# of the text, separated by blank lines
#
# REMARKS:
# - if a macro does not find its mandatory argument(s) in the text,
# it is treated as unknown and can be seen with option --unkn
#
#
parms.project_macros = lambda: (
# our LaTeX macro: \newcommand{\comment}[1]{}
Macro('comment', 'A'),
# non-breaking space in acronyms to avoid LT warning
# our LaTeX macro: \newcommand{\zB}{z.\,B.\ }
Simple('zB', 'z.~B. '),
# Simple('zB', r'z.\\,B. '),
# see LAB:VERBATIM below
# Macro('verb', 'A', '[verbatim]'),
Macro('verb', 'A', r'\1'),
# Macro(r'verb\*', 'A', '[verbatim*]'),
Macro(r'verb\*', 'A', r'\1'),
# macros to suppress rare LT warnings by altering the LaTeX text
Macro('LTadd', 'A', r'\1'),
# for LaTeX, argument is ignored: \newcommand{\LTadd}[1]{}
Macro('LTalter', 'AA', r'\2'),
# for LaTeX, first argument is used: \newcommand{\LTalter}[2]{#1}
Macro('LTskip', 'A'),
# for LaTeX, first argument is used: \newcommand{\LTskip}[1]{#1}
) + defs.project_macros
# BUG: quite probably, some macro is missing here ;-)
#
parms.system_macros = lambda: (
Macro('caption', 'OA', extr=r'\2'), # extract to end of text
Macro('cite', 'A', '[1]'),
Macro('cite', 'PA', r'[1, \1]'),
Macro('color', 'A'),
Macro('colorbox', 'AA', r'\2'),
Macro('documentclass', 'OA'),
Macro('eqref', 'A', '(7)'),
Macro('fcolorbox', 'AAA', r'\3'),
Macro('footnote', 'OA', extr=r'\2'), # extract to end of text
Macro('footnotemark', 'O'),
Macro('footnotetext', 'OA', extr=r'\2'), # extract to end of text
Macro('framebox', 'OOA', r'\3'),
Simple('hfill', ' '),
Macro(r'hspace\*?', 'A'),
Macro('include', 'A'),
Macro('includegraphics', 'OA'),
Macro('input', 'A'),
# \label: see LAB:EQU_MACROS
# \mathrlap: see LAB:EQU_MACROS
# \medspace: treated at LAB:SPACE, parms.mathspace
Simple('newline', ' '),
# \nonumber: see LAB:EQU_MACROS
# \notag: see LAB:EQU_MACROS
Macro('pageref', 'A', '99'),
Simple('par', r'\n\n'),
# \qedhere: see LAB:EQU_MACROS
# \qquad: treated at LAB:SPACE, parms.mathspace
# \quad: treated at LAB:SPACE, parms.mathspace
Macro('ref', 'A', '13'),
Macro(r'(?:re)?newcommand\*?', 'AOOA'),
Macro('texorpdfstring', 'AA', r'\1'),
# \textasciicircum: defined below
# \textasciitilde: defined below
# \textbackslash: defined below
Macro('textcolor', 'AA', r'\2'),
# \thickspace: treated at LAB:SPACE, parms.mathspace
# \thinspace: treated at LAB:SPACE, parms.mathspace
Macro('usepackage', 'OA'),
Macro(r'vspace\*?', 'A'),
Simple('ss', 'ß'),
Simple('S', '§'),
Simple('l', 'ł'),
Simple('L', 'Ł'),
Simple('aa', 'å'),
Simple('AA', 'Å'),
Simple('ae', 'æ'),
Simple('AE', 'Æ'),
Simple('oe', 'œ'),
Simple('OE', 'Œ'),
Simple('o', 'ø'),
Simple('O', 'Ø'),
# macro for foreign-language text
Macro(parms.foreign_lang_mac, 'A', parms.replace_frgn_lang_mac),
# LAB:EQU_MACROS
# necessary for correct parsing of equation environments
# (might hide interpunction, see LAB:EQUATIONS)
Macro('label', 'A'),
Macro('mathrlap', 'A', r'\1'),
Simple('nonumber'),
Simple('notag'),
Simple('qedhere'),
) + defs.system_macros
# heading macros with optional argument [...]:
# copy content of {...} and add '.' if not ending with interpunction
# (avoids false positives from LanguageTool)
#
parms.heading_macros_punct = '!?'
# do not add '.' if ending with that;
# title mistakenly ends with '.' --> '..' will lead to LT warning
parms.heading_macros = lambda: (
r'chapter\*?',
r'part\*?',
r'section\*?',
r'subsection\*?',
r'subsubsection\*?',
r'title',
) + defs.heading_macros
# equation environments, partly from LaTeX package amsmath;
# see comments at LAB:EQUATIONS below
#
# EquEnv(name, args='', repl='')
# - args: arguments at \begin, as for Macro()
# - repl not empty: replace whole environment with this fix text;
# if the actual content ends with a character from variable
# parms.mathpunct (ignoring macros from LAB:EQU_MACROS and variable
# parms.mathspace), then this sign is appended
# - repl: plain string, no backslashes accepted
#
parms.equation_environments = lambda: (
EquEnv(r'align'),
EquEnv(r'align\*'),
# extra pattern with *: safely match begin and end
EquEnv(r'alignat', args='A'),
EquEnv(r'alignat\*', args='A'),
EquEnv(r'displaymath'),
EquEnv(r'equation'),
EquEnv(r'equation\*'),
EquEnv(r'eqnarray'),
EquEnv(r'eqnarray\*'),
EquEnv(r'flalign', repl='[Komplex-Formelausdruck]'),
EquEnv(r'flalign\*', repl='[Komplex-Formelausdruck]'),
) + defs.equation_environments
# these environments are deleted or replaced completely (with body)
#
# EnvRepl(name, repl='')
# - repl: plain string, no backslashes accepted
#
parms.environments = lambda: (
EnvRepl('table', '[Tabelle].'),
# EnvRepl('comment'),
# EnvRepl('verbatim', '[verbatim]'),
# EnvRepl(r'verbatim\*', '[verbatim*]'),
) + defs.environments
# at the end, we delete all unknown "standard" environment frames;
# here are environments with options / arguments at \begin{...},
# or with a replacement text for \begin{...}
#
# EnvBegin(name, args='', repl='')
# - args: as for Macro()
# - repl: as for Macro()
#
# ATTENTION: do not include itemize and enumerate here,
# see label LAB:ENUMERATE below
#
parms.environment_begins = lambda: (
EnvBegin('figure', 'O'),
EnvBegin('minipage', 'A'),
EnvBegin('tabular', 'A'),
EnvBegin('verbatim'), # only, if not in parms.environments
EnvBegin(r'verbatim\*'), # only, if not in parms.environments
# proof: try replacement with option, and only after that without
EnvBegin('proof', 'P', r'\1.'),
EnvBegin('proof', '', parms.proof_title + '.'),
# theorems: same order as for proof
) + tuple(EnvBegin(env, 'P', title + r' 1.2 (\1).')
for (env, title) in parms.theorem_environments()
) + tuple(EnvBegin(env, '', title + ' 1.2.')
for (env, title) in parms.theorem_environments()
) + defs.environment_begins
# theorem environments from package amsthm with optional argument [...]:
# display a title and text in optional argument as (...) with final dot
#
parms.theorem_environments = lambda: (
# (environment name, text title)
('Anmerkung', 'Anmerkung'),
('Beispiel', 'Beispiel'),
('Definition', 'Definition'),
('Korollar', 'Korollar'),
('Nachweis', 'Nachweis'),
('Proposition', 'Proposition'),
('Satz', 'Satz'),
('corollary', 'Corollary'),
('definition', 'Definition'),
('example', 'Example'),
('lemma', 'Lemma'),
('proposition', 'Proposition'),
('remark', 'Remark'),
('theorem', 'Theorem'),
) + defs.theorem_environments
# a list of 2-tuples for other things to be replaced
# [0]: search pattern as regular expression
# [1]: replacement text
# see also LAB:SPACE and before_output() below
#
# ATTENTION:
# - prepend mark_deleted, if replacement may evaluate to empty string
# or begin with white space
# - do not use replacement that
# - ends with a backslash
# - may insert a double backslash
# - may insert an unescaped % sign
# (see comments at Macro() above and compare checks in re_code_args())
#
parms.misc_replace = lambda: (
# \[ ==> ...
(r'\\\[', r'\\begin{equation*}'),
# \] ==> ...
(r'\\\]', r'\\end{equation*}'),
# --- ==> UTF-8 em dash
(r'(?<!\\)---', utf8_emdash), # (?<!x)y matches y not preceded by x
# -- ==> UTF-8 en dash
(r'(?<!\\)--', utf8_endash),
# `` ==> UTF-8 double quotation mark (left)
(r'(?<!\\)``', utf8_lqq),
# '' ==> UTF-8 double quotation mark (right)
(r'(?<!\\)' + "''", utf8_rqq),
# \! \- ==> delete
(r'\\[!-]', mark_deleted),
) + parms.misc_replace_lang() + defs.misc_replace
parms.misc_replace_de = lambda: (
# "= ==> -
(r'(?<!\\)"=', '-'),
# "` ==> UTF-8 German double quotation mark (left)
(r'(?<!\\)"`', utf8_glqq),
# "' ==> UTF-8 German double quotation mark (right)
(r'(?<!\\)"' + "'", utf8_grqq),
# "- ==> delete
(r'(?<!\\)"-', mark_deleted),
)
parms.misc_replace_en = lambda: (
)
# macro for "plain text" in equation environments;
# its argument will be copied, see LAB:EQUATIONS below
#
parms.text_macro = 'text' # LaTeX package amsmath
# maximum nesting depths
#
parms.max_depth_br = 20 # for {} braces and [] brackets
parms.max_depth_env = 10 # for environments of the same type
# recognise {} braces inside of [] brackets?
# - generates really large regular expressions
#
parms.recognise_braces_in_brackets = False
# keep \item labels, if given in [...] option?
# (if set to False: use default labels defined next)
#
parms.keep_item_labels = True
# default \item labels in itemize environment
# (used for \item without [...], or if not parms.keep_item_labels)
#
parms.default_item_labs = ('',)
# default \item labels in enumerate environment
# (used for \item without [...], or if not parms.keep_item_labels)
#
parms.default_item_enum_labs = ('1.', '2.', '3.', '4.', '5.',
'6.', '7.', '8.', '9.', '10.')
# parms.default_item_enum_labs = ('',) # turn labels off
# repeat punctuation sign in front of an \item with [...] option?
# see LAB:ITEMS
#
parms.item_label_repeat_punct = True
# message on warnings / errors that should be found by LT;
# don't include line breaks: will disrupt line number tracking
#
parms.warning_error_msg = ' WARNINGORERROR '
# LAB:LANGUAGE
#
def set_language_de():
# properties of these replacements for inline formulas:
# - no need to add to LT dictionary
# - absent leading / trailing space causes spelling errors
# - LT accepts e.g. 'mit einer Konstanten $C$ folgt', 'für alle $x$',
# 'für ein $x$'
# - LT recognises mistakes like 'die $\epsilon$-Argument'
# - word repetitions are detected
# - resulting text can be checked for single letters (German)
# other variant: AInlA, BInlB, ... (but has to be added to dictionary)
# parms.inline_math = ('I1I', 'I2I', 'I3I', 'I4I', 'I5I', 'I6I')
# parms.inline_math = ('AInlA', 'BInlB', 'CInlC',
# 'DInlD', 'EInlE', 'FInlF')
# replacements for maths parts in displayed formulas
# parms.display_math = ('D1D', 'D2D', 'D3D', 'D4D', 'D5D', 'D6D')
# parms.display_math = ('ADsplA', 'BDsplB', 'CDsplC',
# 'DDsplD', 'EDsplE', 'FDsplF')
# compare Issue #22
parms.inline_math = ('B-B-B', 'C-C-C', 'D-D-D', 'E-E-E', 'F-F-F', 'G-G-G')
parms.display_math = ('U-U-U', 'V-V-V', 'W-W-W', 'X-X-X', 'Y-Y-Y', 'Z-Z-Z')
# LAB:CHECK_EQU_REPLS
# this check is important if replacements had to be added to dictionary
parms.check_equation_replacements = True
# texts for maths operators; default: key None
parms.mathoptext = {'+': ' plus ', '-': ' minus ',
'*': ' mal ', '/': ' durch ',
None: ' gleich '}
# proof environment:
parms.proof_title = 'Beweis'
# macro to mark foreign language:
parms.foreign_lang_mac = 'engl'
# replacement for this macro:
parms.replace_frgn_lang_mac = '[englisch]'
# language-dependent part of parms.misc_replace
parms.misc_replace_lang = parms.misc_replace_de
def set_language_en():
# see comments in set_language_de()
# parms.inline_math = ('B', 'C', 'D', 'E', 'F', 'G')
# parms.display_math = ('U', 'V', 'W', 'X', 'Y', 'Z')
# compare Issue #22
parms.inline_math = ('B-B-B', 'C-C-C', 'D-D-D', 'E-E-E', 'F-F-F', 'G-G-G')
parms.display_math = ('U-U-U', 'V-V-V', 'W-W-W', 'X-X-X', 'Y-Y-Y', 'Z-Z-Z')
parms.check_equation_replacements = False
parms.mathoptext = {'+': ' plus ', '-': ' minus ',
'*': ' times ', '/': ' over ',
None: ' equal '}
parms.proof_title = 'Proof'
parms.foreign_lang_mac = 'foreign'
parms.replace_frgn_lang_mac = '[foreign]'
parms.misc_replace_lang = parms.misc_replace_en
# parameters used for parsing of equations
# see LAB:EQUATIONS
#
def set_math_parms():
parms.mathspace = (r'(?:\\[ ,;:\n\t]|(?<!\\)~'
+ r'|\\(?:q?quad|(?:thin|med|thick)space)'
+ end_mac + skip_space_macro + r')')
parms.mathop = (
r'\+|-|\*|/'
+ r'|=|<|>|(?<!\\):=?' # accept ':=' and ':'
+ r'|\\[gl]eq?' + end_mac
+ r'|\\su[bp]set(?:eq)?' + end_mac
+ r'|\\Leftrightarrow' + end_mac
+ r'|\\to' + end_mac
+ r'|\\stackrel' + sp_braced + skip_space + r'\{=\}'
+ r'|\\c[au]p' + end_mac
)
parms.mathpunct = r'(?:(?<!\\)[;,.])'
parms.change_repl_after_punct = True
# further replacements performed below:
#
# - translation of $$...$$ to equation* environment
# - replacement of $...$ and \(...\) inline maths
# - macros \textbackslash, \textasciicircum, \textasciitilde
# - treatment of text-mode accents
# - handling of displayed equations
# - some treatment of \item[...] labels
# - environments not listed above: \begin{...} and \end{...} deleted
# - macros not listed:
# \xxx is deleted, content of a possible braced argument is copied
#######################################################################
#######################################################################
#
# Implementation part
#
#######################################################################
#######################################################################
import argparse
import re
import sys
import unicodedata
# first of all ...
#
def fatal(msg, detail=None):
raise_error('internal error', msg, detail, xit=1)
def warning(msg, detail=None):
raise_error('warning', msg, detail)
def myopen(f, encoding, mode='r'):
try:
return open(f, mode=mode, encoding=encoding)
except:
raise_error('problem', 'could not open file "' + f + '"', xit=1)
warning_or_error = Aux()
warning_or_error.msg = ''
def raise_error(kind, msg, detail=None, xit=None):
warning_or_error.msg = parms.warning_error_msg
err = '\n*** ' + sys.argv[0] + ': ' + kind + ':\n' + msg + '\n'
if detail:
err += strip_internal_marks(detail) + '\n'
sys.stderr.write(err)
if xit is not None:
sys.exit(xit)
def strip_internal_marks(s):
# will be redefined below
return s
# for internal marks: cannot appear in text after removal of % comments
# (has to be asymmetrical)
#
mark_internal_pre = '%%%%' # CROSS-CHECK with re_code_args()
mark_internal_post = '%%' # CROSS-CHECK with re_code_args()
# when deleting macros or environment frames, we do not want to create
# new empty lines that break sentences for LT;
# thus replace deleted text with tag in mark_deleted which is removed
# at the end;
# this also protects space behind a macro already resolved from being
# consumed by a macro in front
#
mark_deleted = mark_internal_pre + 'D' + mark_internal_post
# after resolution of an environment frame, we leave this mark;
# it will avoid that a preceding macro that is treated later will
# consume too much space;
# see also variable skip_space_macro
#
mark_begin_env = r'\begin{' + mark_internal_pre + r'}'
mark_end_env = r'\end{' + mark_internal_pre + r'}'
# if replacement argument of ..sub():
mark_begin_env_sub = r'\\begin{' + mark_internal_pre + r'}'
mark_end_env_sub = r'\\end{' + mark_internal_pre + r'}'
# this mark enforces a line break without creating a new blank line
#
mark_enforce_linebreak = mark_deleted + '\n' + mark_deleted
# internal representation of double backslash \\
#
mark_linebreak = mark_internal_pre + 'L' + mark_internal_post
# mark for internal representation of a single verbatim character,
# will be resolved only at output by before_output()
#
mark_verbatim = (mark_internal_pre + 'V', 'V' + mark_internal_post)
mark_verbatim_tmp = ('____V', 'V__') # before removal of % comments
# only for error messages: remove internal marks
#
def strip_internal_marks(s):
s = re.sub(mark_deleted, '', s)
s = re.sub(mark_linebreak, r'\\\\', s)
s = re.sub(mark_verbatim[0], r'\\verb.', s)
s = re.sub(mark_verbatim[1], r'.', s)
s = re.sub(re.escape(mark_begin_env), r'\\begin{.}', s)
s = re.sub(re.escape(mark_end_env), r'\\end{.}', s)
return s
# space allowed inside of current paragraph, at most one line break
#
skip_space = r'(?:[ \t]*\n?[ \t]*)'
# regular expression for nested {} braces
# BUG (but error message on overrun): the nesting limit is unjustified
#
def re_braced(max_depth, inner_beg, inner_end, outer_beg='(', outer_end=')'):
atom = r'[^\\{}]|\\.|\\\n'
braced = inner_beg + r'\{(?:' + atom + r')*\}' + inner_end
# (?:...) is (...) without creation of a reference
for i in range(max_depth - 2):
braced = r'\{(?:' + atom + r'|' + braced + r')*\}'
braced = (r'(?<!\\)\{' + outer_beg + r'(?:' + atom + r'|' + braced + r')*'
+ outer_end + r'\}')
# outer-most (...) for reference at substitutions below
# '(?<!x)y' matches 'y' not preceded by 'x'
return braced
braced = re_braced(parms.max_depth_br, '', '')
sp_braced = skip_space + braced
# the same for [] brackets
#
def re_bracketed(max_depth, inner_beg, inner_end):
if parms.recognise_braces_in_brackets:
atom = (r'[^][{\\]|\\.|\\\n|'
+ re_braced(parms.max_depth_br, '', '', '(?:', ')'))
else:
atom = r'[^][\\]|\\.|\\\n'
bracketed = inner_beg + r'\[(?:' + atom + r')*\]' + inner_end
for i in range(max_depth - 2):
bracketed = r'\[(?:' + atom + r'|' + bracketed + r')*\]'
bracketed = r'(?<!\\)\[((?:' + atom + r'|' + bracketed + r')*)\]'
return bracketed
bracketed = re_bracketed(parms.max_depth_br, '', '')
sp_bracketed = skip_space + bracketed
# regular expression for an environment
# BUG (but error message on overrun): the nesting limit is unjustified
#
begin_lbr = r'\\begin' + skip_space + r'\{'
end_lbr = r'\\end' + skip_space + r'\{'
def re_nested_env(s, max_depth, arg):
env_begin = begin_lbr + s + r'\}'
env_end = end_lbr + s + r'\}'
# important here: non-greedy *? repetition
env = r'(?P<inner>' + env_begin + r'(?:.|\n)*?' + env_end + r')'
for i in range(max_depth - 2):
# important here: non-greedy *? repetition
env = env_begin + r'(?:(?:' + env + r')|.|\n)*?' + env_end
env = (env_begin + arg + r'(?P<body>(?:(?:' + env + r')|.|\n)*?)'
+ env_end)
return env
# helpers for "declaration" of macros and environments
#
def Macro(name, args, repl='', extr=''):
return (name, args, repl, extr)
def Simple(name, repl='', extr=''):
return (name, '', repl, extr)
def EquEnv(name, args='', repl=''):
return (name, args, repl)
def EnvRepl(name, repl=''):
return (name, repl)
def EnvBegin(name, args='', repl=''):
return (name, args, repl)
def re_code_args(args, repl, who, s, no_backslash=False):
# return regular expression for 'OAA' code in args, and modified
# replacement string repl
# - do some checks for replacement string repl:
# CROSS-CHECK with mark_internal_pre and mark_internal_post
# - modify replacement:
# append mark_deleted to each expanded argument, otherwise problem in
# ... \textcolor{red}{This\xyz} is ...
ret = ''
for a in args:
if a == 'A':
ret += sp_braced
elif a == 'O':
ret += r'(?:' + sp_bracketed + r')?'
elif a == 'P':
ret += sp_bracketed
else:
fatal(who + "('" + s + "',...): bad argument code '" + args + "'")
def err(e):
fatal('error in replacement for ' + who + "('" + s + "', ...):\n" + e)
if no_backslash and repl.count('\\'):
err('no backslashes allowed')
for m in re.finditer(r'(?<!\\)(?:\\\\)*\\(\d)', repl):
# avoid exceptions from re module
n = int(m.group(1))
if n < 1 or n > len(args) or args[n - 1] not in 'AP':
err('invalid reference "\\' + m.group(1) + '"')
if re.search(r'(?<!\\)\\(?:\\\\)*%', repl):
# ensure that mark_linebreak and mark_deleted do work
err(r"please use r'\\%' to insert escaped percent sign")
if repl.endswith('\\') or repl.count('\\\\\\\\'):
# ensure that double backslashes do not appear in text
err('backslash at end or insertion of double backslash')
repl = re.sub(r'((?<!\\)(?:\\\\)*\\(\d))', r'\1' + mark_deleted, repl)
return (ret, repl)
# this is an eligible name of a "normal" macro
#
macro_name = r'[a-zA-Z]+'
# the expression r'\\to\b' does not work as necessary for \to0
# --> use r'\\to' + end_mac
#
end_mac = r'(?![a-zA-Z])'
# space that can be consumed after a macro without argument:
# only consume line break, if non-space on next line found,
# and if line break not in front of a \begin or \end for environment
#
skip_space_macro = (r'(?:[ \t]*(?:\n(?=[ \t]*\S)(?![ \t]*\\(?:begin|end)'
+ end_mac + r'))?[ \t]*)')
# now all is defined to call ...
#
set_math_parms()
# these RE match beginning and end of arbitrary "standard" environments
#
environ_name = r'[^\\{}\n]+'
re_begin_env = begin_lbr + environ_name + r'\}'
re_end_env = end_lbr + environ_name + r'\}'
# UTF-8 characters;
# name lookup, if char given e.g. from copy-and-paste:
# import unicodedata
# print(unicodedata.name('„'))
#
utf8_endash = '\N{EN DASH}'
utf8_emdash = '\N{EM DASH}'
utf8_lqq = '\N{LEFT DOUBLE QUOTATION MARK}'
utf8_rqq = '\N{RIGHT DOUBLE QUOTATION MARK}'
utf8_glqq = '\N{DOUBLE LOW-9 QUOTATION MARK}'
utf8_grqq = '\N{LEFT DOUBLE QUOTATION MARK}'
utf8_nbsp = '\N{NO-BREAK SPACE}'
utf8_nnbsp = '\N{NARROW NO-BREAK SPACE}'
# create internal verbatim representation of a string
#
def verbatim(s, mark, ast):
ret = ''
for c in s:
if ast and c == ' ':
c = '⊔'
ret += mark[0] + str(ord(c)) + mark[1]
if c == '\n':
# for line number tracking, compare before_output()
ret += c
return ret
#######################################################################
#
# This "reimplementation" of re.sub() operates a small machinery for
# line number tracking.
# Argument text is a 2-tuple.
# text[0]: the text as string
# text[1]: array with line numbers
# Return value: tuple (string, number array)
# As for re.sub(), argument repl may be a callable.
# Argument track_repl: function for extraction of replacements
# and detection of inserted braces etc.
# Argument only_one: perform at most one replacement
#
# For each line in the current text string, the number array
# contains the original line number (before any changes took place).
# On deletion of line breaks, the corresponding entries in the number
# array are removed. On creation of an additional line, a negative
# placeholder is inserted in the number array.
#
def mysub(expr, repl, text, flags=0, track_repl=None, only_one=False):
(txt, numbers) = text
res = ''
last = 0
for m in re.finditer(expr, txt, flags=flags):
t = m.group(0)
if type(repl) is str:
ex = myexpand(m, repl, text)
else:
ex = repl(m)
if type(ex) is tuple:
# replacement contains line number information
(r, nums2) = ex
else:
(r, nums2) = (ex, None)
res += txt[last:m.start(0)]
last = m.end(0)
(lin, nt, nr) = mysub_offsets(res, t, r)
if nums2 is None:
ll = numbers[lin]
nums2 = [ll,] + [-abs(ll),] * nr
if track_repl:
track_repl((t, numbers[lin:lin+nt+1]), (r, nums2))
(res, numbers) = mysub_combine(lin, res, r, nt, nr,
numbers, nums2, text)
if only_one:
break
return (res + txt[last:], numbers)
# will be changed for tracking of character positions
#
def mysub_offsets_lins(res, t, r):
return (res.count('\n'), t.count('\n'), r.count('\n'))
# will be changed for tracking of character positions
#
def mysub_combine_lins(lin, res, r, nt, nr, numbers, nums2, text):
tmp = text_combine((res, numbers[:lin+1]), (r, nums2))
return text_combine(tmp, ('', numbers[lin+nt:]))
# combine (add) two text elements with line number information
# ATTENTION:
# mysub() depends on the fact that we only look backwards in text1,
# but not forwards in text2
#
def text_combine_lins(text1, text2):
(t1, n1) = text1
(t2, n2) = text2
if n1[-1] == n2[0] or not t1[t1.rfind('\n')+1:].strip():
# same line numbers at junction or
# only space after last line break in text1:
# use first line number from text2 at junction
n = n1[:-1] + n2
else:
# use last line number from text1 at junction,
# but attention in case of decreasing line numbers
j = min(abs(n1[-1]), abs(n2[0]))
n = n1[:-1] + [-j,] + n2[1:]
return (t1 + t2, n)
# prepend and append plain strings to a text with line number information
#
def text_add_frame_lins(pre, post, text):
return (
pre + text[0] + post,
[text[1][0],] * pre.count('\n') + text[1]
+ [text[1][-1],] * post.count('\n')
)
# extract text with line number information from a group of a match
#
def text_from_match_lins(m ,grp, text):
if m.string is not text[0]:
fatal('text_from_match(): bad match object')
beg = m.string[:m.start(grp)].count('\n')
end = beg + m.group(grp).count('\n') + 1
return (m.group(grp), text[1][beg:end])
# expansion of a match from replacement template repl:
# returned text element provides line number information,
# if repl contains a reference to a capturing group
#
def myexpand(m, repl, text):
# return m.expand(repl) # fail-save version
if not repl:
return ''
# first parse repl: build list 'ops' of
# (strings) and (numbers of referenced capturing groups)
# - compare parse_template() in /usr/lib/python?.?/sre_parse.py
escapes = {
'a': '\a', 'b': '\b', 'f': '\f', 'n': '\n',
'r': '\r', 't': '\t', 'v': '\v', '\\': '\\'
}
ops = []
first = None
cur_str = ''
i = 0
while i < len(repl):
c = repl[i]
i += 1
if c != '\\':
cur_str += c
continue
if i >= len(repl):
cur_str += '\\'
break
c = repl[i]
i += 1
if c in escapes:
cur_str += escapes[c]
elif c in '0g':
fatal('myexpand(): escape sequences \\0... and \\g<...>'
+ ' not implemented')
elif c.isdecimal():
if cur_str:
ops += [cur_str]
cur_str = ''
if first is None:
first = len(ops)
ops += [int(c)]
else:
cur_str += '\\' + c
if cur_str:
ops += [cur_str]
if first is None:
# no group reference found, repl == '' was excluded above
return ops[0]
# build replacement text with line number information
t = text_from_match(m, ops[first], text)
if first > 0:
t = text_add_frame(ops[0], '', t)
for i in range(first + 1, len(ops)):
if type(ops[i]) is int:
t2 = text_from_match(m, ops[i], text)
t = text_combine(t, t2)
else:
t = text_add_frame('', ops[i], t)
return t
def mysearch(expr, text, flags=0):
(txt, n) = text
return re.search(expr, txt, flags=flags)
def text_get_txt(text):
return text[0]
def text_get_num(text):
return text[1]
def text_new_lins(s=None):
if s is None:
return ('', [-1,])
return (s, list(range(1, s.count('\n') + 2)))
#######################################################################
#
# the same machinery for tracking of character offset
#
def mysub_offsets_char(res, t, r):
return (len(res), len(t), len(r))
def mysub_combine_char(pos, res, r, nt, nr, numbers, nums2, text):
if numbers is text[1]:
# myexpand() in mysub() still needs the original array
numbers = numbers.copy()
numbers[pos:pos+nt] = nums2[:nr]
return (res + r, numbers)
def text_combine_char(t1, t2):
return (t1[0] + t2[0], t1[1][:-1] + t2[1])
def text_add_frame_char(pre, post, text):
return (
pre + text[0] + post,
[text[1][0],] * len(pre) + text[1] + [text[1][-1],] * len(post)
)
def text_from_match_char(m ,grp, text):
if m.string is not text[0]:
fatal('text_from_match_char(): bad match object')
return (m.group(grp), text[1][m.start(grp):m.end(grp)+1])
def text_new_char(s=None):
if s is None:
return ('', [-1,])
return (s, list(range(1, len(s) + 2)))
#######################################################################
#
# text2txt(): collects all actual work on text input
# - argument txt: input text string
# - argument options: options
# - return: tuple (text string, number array)
#
#######################################################################
def tex2txt(txt, options):
global mysub_offsets, mysub_combine, text_combine
global text_add_frame, text_from_match, text_new
if options.char:
# track character offsets instead of line numbers
mysub_offsets = mysub_offsets_char
mysub_combine = mysub_combine_char
text_combine = text_combine_char
text_add_frame = text_add_frame_char
text_from_match = text_from_match_char
text_new = text_new_char
else:
mysub_offsets = mysub_offsets_lins
mysub_combine = mysub_combine_lins
text_combine = text_combine_lins
text_add_frame = text_add_frame_lins
text_from_match = text_from_match_lins
text_new = text_new_lins
if not options.lang or options.lang == 'de':
set_language_de()
elif options.lang == 'en':
set_language_en()
else:
raise_error('problem', 'unrecognized language "' + options.lang
+ '" given in option --lang', xit=1)
if options.extr:
options.extr_list = [m for m in options.extr.split(',') if m]
options.extr_re = '|'.join(options.extr_list)
else:
options.extr_list = []
global defs
defs = options.defs
# for mysub():
# text becomes a 2-tuple of text string and number array
#