-
Notifications
You must be signed in to change notification settings - Fork 1
/
pyptex.html
2203 lines (2045 loc) · 107 KB
/
pyptex.html
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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<meta name="generator" content="pdoc 0.10.0" />
<title>pyptex API documentation</title>
<meta name="description" content="PypTeX: the Python Preprocessor for TeX …" />
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/sanitize.min.css" integrity="sha256-PK9q560IAAa6WVRRh76LtCaI8pjTJ2z11v0miyNNjrs=" crossorigin>
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/typography.min.css" integrity="sha256-7l/o7C8jubJiy74VsKTidCy1yBkRtiUGbVkYBylBqUg=" crossorigin>
<link rel="stylesheet preload" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/styles/github.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:30px;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:1em 0 .50em 0}h3{font-size:1.4em;margin:25px 0 10px 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .3s ease-in-out}a:hover{color:#e82}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900}pre code{background:#f8f8f8;font-size:.8em;line-height:1.4em}code{background:#f2f2f1;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{background:#f8f8f8;border:0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0;padding:1ex}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-weight:bold;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em .5em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.item .name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul{padding-left:1.5em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/highlight.min.js" integrity="sha256-Uv3H6lx7dJmRfRvH8TH6kJD1TSK1aFcwgx+mdg3epi8=" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => hljs.initHighlighting())</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Package <code>pyptex</code></h1>
</header>
<section id="section-intro">
<h2 id="pyptex-the-python-preprocessor-for-tex">PypTeX: the Python Preprocessor for TeX</h2>
<h3 id="author-sebastien-loisel">Author: Sébastien Loisel</h3>
<p>PypTeX is the Python Preprocessor for LaTeX. It allows one to embed Python
code fragments in a LaTeX template file.</p>
<h1 id="installation">Installation</h1>
<p><code>pip install <a title="pyptex.pyptex" href="#pyptex.pyptex">pyptex</a></code></p>
<ol>
<li>You will also need a LaTeX installation, and the default LaTeX processor is <code>pdflatex</code>.</li>
<li>You need a Python 3 installation.</li>
</ol>
<p><img alt="An example plot with PypTeX" width="500" src="examples/brochure.png"></p>
<h1 id="introduction">Introduction</h1>
<p>Assume <code>example.tex</code> contains the following text:</p>
<pre><code>\documentclass{article}
@{from sympy import *}
\begin{document}
$$\int x^3\,dx = @{S('integrate(x^3,x)')}+C$$
\end{document}
</code></pre>
<p>The command <code><a title="pyptex.pyptex" href="#pyptex.pyptex">pyptex</a> example.tex</code> will generate <code>example.pdf</code>,
as well as the intermediary file <code>example.pyptex</code>. PypTeX works by extracting Python
fragments in <code>example.tex</code> indicated by either <code>@{...}</code> or <code>@{{{...}}}</code> and substituting the
corresponding outputs to produce <code>example.pyptex</code>, which is then compiled with
<code>pdflatex example.pyptex</code>, although one can use any desired LaTeX processor in lieu of
<code>pdflatex</code>. The intermediary file <code>example.pyptex</code> is pure LaTeX.</p>
<p>When processing Python fragments, the global scope contains an object <code>pyp</code> that is a
(weakref proxy for a) <code><a title="pyptex.pyptex" href="#pyptex.pyptex">pyptex</a></code> object that makes available several helper functions
and useful data. For example, <code>pyp.print("hello, world")</code> inserts the string <code>hello, world</code>
into the generated <code>example.pyptex</code> file.</p>
<ul>
<li>The <code><a title="pyptex.pyptex" href="#pyptex.pyptex">pyptex</a></code> executable tries to locate the Python 3 executable using <code>/usr/bin/env python3</code>.
If this is causing you problems, try <code>python -u -m pyptex example.tex</code> instead.</li>
</ul>
<h1 id="slightly-bigger-examples">Slightly bigger examples</h1>
<ul>
<li>2d and 3d plotting <a href="examples/plots.tex">tex</a>
|
<a href="examples/plots.pdf">pdf</a></li>
<li>Matrix inverse exercise <a href="examples/matrixinverse.tex">tex</a>
|
<a href="examples/matrixinverse.pdf">pdf</a></li>
<li>The F19NB handout for numerical linear algebra at Heriot-Watt university is generated with PypTeX. <a href="https://www.macs.hw.ac.uk/~sl398/notes.pdf">pdf</a></li>
</ul>
<h1 id="plotting-with-sympy-and-matplotlib">Plotting with <code>sympy</code> and <code>matplotlib</code></h1>
<p>PypTeX implements its own <code>matplotlib</code> backend, a thin wrapper around the built-in postscript backend.
The PypTeX backend takes care of generating <code>.eps</code> files and importing them into your document via
<code>\includegraphics</code>. In that scenario, you must do <code>\usepackage{graphicx}</code> in your LaTeX preamble.
The precise "includegraphics" command can be set, e.g. by
<code>pyp.includegraphics=r"\includegraphics[width=0.9\textwidth]{%s}"</code>.</p>
<p>To create a plot with <code>sympy</code>, one can do:</p>
<pre><code class="language-python">sympy.plot(sympy.S('sin(x)+cos(pi*x)'))
</code></pre>
<p>At the end of each Python fragment <code>@{...}</code>, PypTeX saves each generated figure to a
<code>x.eps</code> file, and these figures are then inserted via <code>includegraphics</code> into the generated
<code>.tex</code> file. Once a figure has been auto-showed in this manner, it will not be
auto-showed again. The auto-show behavior can be disabled by setting <code>pyp.autoshow = False</code>.
Figures can also be displayed manually via <code>pyp.pp('{myfig})</code>.</p>
<pre><code class="language-python">plt.plot([1,2,3],[2,1,4])
</code></pre>
<h1 id="template-preprocessing-vs-embedding">Template preprocessing vs embedding</h1>
<p>PypTeX is a template preprocessor for LaTeX based on the Python language. When Python
is embedded into LaTeX, Python code fragments are identified by LaTeX commands that use
standard TeX notation, such as <code>\py{...}</code>. The code extraction is performed by TeX, then
the code fragments are executed by Python, finally TeX is run again to merge the
Python-generated LaTeX fragments back into the master file.</p>
<p>By contrast, PypTeX is a preprocessor that extracts Python code fragments indicated by
<code>@{...}</code> using regular expressions. Once the relevant Python outputs are collected, they
are also inserted by regular expressions. LaTeX is only invoked once, on the final output.</p>
<p>There may be specialized cases where Python embeddings are preferred, but we found
that template preprocessing is superior to embedding. There are many reasons (that
will be described elsewhere in detail) but we briefly mention the following reasons:
1. Embeddings can result in deadlock. If we have <code>\includegraphics{dog.png}</code>, but
<code>dog.png</code> is generated by a Python fragment, the first run of LaTeX will fail because
<code>dog.png</code> does not yet exist. Since LaTeX failed, it did not extract the Python fragments
and we cannot run the Python code that would generate <code>dog.png</code> unless we temporarily
delete the <code>\includegraphics{dog.png}</code> from <code>a.tex</code>. In our experience, deadlock
occurs almost every time we edit our large <code>.tex</code> files.
2. Embedding makes debugging difficult. By contrast, PypTeX treats Python's debugger Pdb
as a first-class citizen and everything should work as normal. Please let us know if some
debugging task somehow fails for you.
3. Performance. Substituting using regular expressions is faster than running the
LaTeX processor.</p>
<h1 id="pretty-printing-template-strings-from-python-with-pp">Pretty-printing template strings from Python with <code>pp</code></h1>
<p>The function <code>pyp.pp(X)</code> pretty-prints the template string <code>X</code> with substitutions
from the local scope of the caller. This is useful for medium length LaTeX fragments
containing a few Python substitutions:</p>
<pre><code class="language-python">from sympy import *
p = S('x^2-2*x+3')
dpdx = p.diff(S('x'))
pyp.print(pyp.pp('The minimum of $y=@p$ is at $x=@{solve(dpdx)[0]}$.'))
</code></pre>
<h1 id="caching">Caching</h1>
<p>When compiling <code>a.tex</code>, PypTeX creates a cache file <code>a.pickle</code>. This file is
automatically invalidated if the Python fragments in <code>a.tex</code> change, or if some
other dependencies have changed. Dependencies can be declared from inside <code>a.tex</code> via
<code>pyp.dep(…)</code>. Caching can be completely disabled with <code>pyp.disable_cache=True</code>,
and users can delete <code>a.pickle</code> as necessary.</p>
<h1 id="scopes">Scopes</h1>
<p>For each template file <code>a.tex</code>, <code>b.tex</code>, … a private global scope is created for
executing Python fragments. This means that Python fragments in <code>a.tex</code> cannot use
functions or variables defined in <code>b.tex</code>, although shared functions could be
implemented in a shared <code>c.py</code> Python module that is <code>import</code>ed into
<code>a.tex</code> and <code>b.tex</code>.</p>
<p>In particular, when does <code>pyp.input('b.tex')</code> from <code>a.tex</code>, the code in <code>b.tex</code> cannot
use functions and data generated in <code>a.tex</code>. This means that <code>b.tex</code> is effectively
a "compilation unit" whose semantics are essentially independent of <code>a.tex</code>.</p>
<p>For any given <code>a.tex</code> file, its private global scope is initialized with the
standard Python builtins and with a single <code>pyp</code> object, which is a <code>weakref.proxy</code>
to the <code>pyptex('a.tex')</code> instance. We use a <code>weakref.proxy</code> because the global
scope of <code>a.tex</code> is a <code>dict</code> stored in the (private) variable <code>pyp.__global__</code>. The
use of <code>weakref.proxy</code> avoids creating a circular data structure that would otherwise
stymie the Python garbage collector. For most purposes, this global <code>pyp</code> variable
acts exactly like a concrete <code><a title="pyptex.pyptex" href="#pyptex.pyptex">pyptex</a></code> instance.</p>
<h1 id="texshop">TeXShop</h1>
<p>If you want to use TeXShop on Mac, put the following into <code>~/Library/TeXShop/Engines/pyptex.engine</code> and restart TeXShop:</p>
<pre><code>#!/bin/bash
pyptex $1
</code></pre>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">r"""
## PypTeX: the Python Preprocessor for TeX
### Author: Sébastien Loisel
PypTeX is the Python Preprocessor for LaTeX. It allows one to embed Python
code fragments in a LaTeX template file.
# Installation
`pip install pyptex`
1. You will also need a LaTeX installation, and the default LaTeX processor is `pdflatex`.
2. You need a Python 3 installation.
<img alt="An example plot with PypTeX" width="500" src="examples/brochure.png">
# Introduction
Assume `example.tex` contains the following text:
\documentclass{article}
@{from sympy import *}
\begin{document}
$$\int x^3\,dx = @{S('integrate(x^3,x)')}+C$$
\end{document}
The command `pyptex example.tex` will generate `example.pdf`,
as well as the intermediary file `example.pyptex`. PypTeX works by extracting Python
fragments in `example.tex` indicated by either `@{...}` or `@{{{...}}}` and substituting the
corresponding outputs to produce `example.pyptex`, which is then compiled with
`pdflatex example.pyptex`, although one can use any desired LaTeX processor in lieu of
`pdflatex`. The intermediary file `example.pyptex` is pure LaTeX.
When processing Python fragments, the global scope contains an object `pyp` that is a
(weakref proxy for a) `pyptex.pyptex` object that makes available several helper functions
and useful data. For example, `pyp.print("hello, world")` inserts the string `hello, world`
into the generated `example.pyptex` file.
* The `pyptex` executable tries to locate the Python 3 executable using `/usr/bin/env python3`.
If this is causing you problems, try `python -u -m pyptex example.tex` instead.
# Slightly bigger examples
* 2d and 3d plotting [tex](examples/plots.tex)
|
[pdf](examples/plots.pdf)
* Matrix inverse exercise [tex](examples/matrixinverse.tex)
|
[pdf](examples/matrixinverse.pdf)
* The F19NB handout for numerical linear algebra at Heriot-Watt university is generated with PypTeX. [pdf](https://www.macs.hw.ac.uk/~sl398/notes.pdf)
# Plotting with `sympy` and `matplotlib`
PypTeX implements its own `matplotlib` backend, a thin wrapper around the built-in postscript backend.
The PypTeX backend takes care of generating `.eps` files and importing them into your document via
`\includegraphics`. In that scenario, you must do `\usepackage{graphicx}` in your LaTeX preamble.
The precise "includegraphics" command can be set, e.g. by
`pyp.includegraphics=r"\includegraphics[width=0.9\textwidth]{%s}"`.
To create a plot with `sympy`, one can do:
```python
sympy.plot(sympy.S('sin(x)+cos(pi*x)'))
```
At the end of each Python fragment `@{...}`, PypTeX saves each generated figure to a
`x.eps` file, and these figures are then inserted via `includegraphics` into the generated
`.tex` file. Once a figure has been auto-showed in this manner, it will not be
auto-showed again. The auto-show behavior can be disabled by setting `pyp.autoshow = False`.
Figures can also be displayed manually via `pyp.pp('{myfig})`.
```python
plt.plot([1,2,3],[2,1,4])
```
# Template preprocessing vs embedding
PypTeX is a template preprocessor for LaTeX based on the Python language. When Python
is embedded into LaTeX, Python code fragments are identified by LaTeX commands that use
standard TeX notation, such as `\py{...}`. The code extraction is performed by TeX, then
the code fragments are executed by Python, finally TeX is run again to merge the
Python-generated LaTeX fragments back into the master file.
By contrast, PypTeX is a preprocessor that extracts Python code fragments indicated by
`@{...}` using regular expressions. Once the relevant Python outputs are collected, they
are also inserted by regular expressions. LaTeX is only invoked once, on the final output.
There may be specialized cases where Python embeddings are preferred, but we found
that template preprocessing is superior to embedding. There are many reasons (that
will be described elsewhere in detail) but we briefly mention the following reasons:
1. Embeddings can result in deadlock. If we have `\includegraphics{dog.png}`, but
`dog.png` is generated by a Python fragment, the first run of LaTeX will fail because
`dog.png` does not yet exist. Since LaTeX failed, it did not extract the Python fragments
and we cannot run the Python code that would generate `dog.png` unless we temporarily
delete the `\includegraphics{dog.png}` from `a.tex`. In our experience, deadlock
occurs almost every time we edit our large `.tex` files.
2. Embedding makes debugging difficult. By contrast, PypTeX treats Python's debugger Pdb
as a first-class citizen and everything should work as normal. Please let us know if some
debugging task somehow fails for you.
3. Performance. Substituting using regular expressions is faster than running the
LaTeX processor.
# Pretty-printing template strings from Python with `pp`
The function ```pyp.pp(X)``` pretty-prints the template string `X` with substitutions
from the local scope of the caller. This is useful for medium length LaTeX fragments
containing a few Python substitutions:
```python
from sympy import *
p = S('x^2-2*x+3')
dpdx = p.diff(S('x'))
pyp.print(pyp.pp('The minimum of $y=@p$ is at $x=@{solve(dpdx)[0]}$.'))
```
# Caching
When compiling `a.tex`, PypTeX creates a cache file `a.pickle`. This file is
automatically invalidated if the Python fragments in `a.tex` change, or if some
other dependencies have changed. Dependencies can be declared from inside `a.tex` via
`pyp.dep(...)`. Caching can be completely disabled with `pyp.disable_cache=True`,
and users can delete `a.pickle` as necessary.
# Scopes
For each template file `a.tex`, `b.tex`, ... a private global scope is created for
executing Python fragments. This means that Python fragments in `a.tex` cannot use
functions or variables defined in `b.tex`, although shared functions could be
implemented in a shared `c.py` Python module that is `import`ed into
`a.tex` and `b.tex`.
In particular, when does `pyp.input('b.tex')` from `a.tex`, the code in `b.tex` cannot
use functions and data generated in `a.tex`. This means that `b.tex` is effectively
a "compilation unit" whose semantics are essentially independent of `a.tex`.
For any given `a.tex` file, its private global scope is initialized with the
standard Python builtins and with a single `pyp` object, which is a `weakref.proxy`
to the `pyptex('a.tex')` instance. We use a `weakref.proxy` because the global
scope of `a.tex` is a `dict` stored in the (private) variable `pyp.__global__`. The
use of `weakref.proxy` avoids creating a circular data structure that would otherwise
stymie the Python garbage collector. For most purposes, this global `pyp` variable
acts exactly like a concrete `pyptex` instance.
# TeXShop
If you want to use TeXShop on Mac, put the following into `~/Library/TeXShop/Engines/pyptex.engine` and restart TeXShop:
```
#!/bin/bash
pyptex $1
```
"""
from contextlib import suppress
import datetime
import glob
import inspect
import os
import pickle
import re
import string
import subprocess
import shlex
import sys
import time
import traceback
import weakref
import streamcapture
import numpy
import sympy
import types
import matplotlib
import matplotlib.pyplot
import matplotlib.artist
from pathlib import Path
from matplotlib.backend_bases import Gcf, FigureManagerBase
from matplotlib.backends.backend_ps import FigureCanvasPS
__pdoc__ = {
'pyptex.compile': False,
'pyptex.generateddir': False,
'pyptex.process': False,
'pyptex.resolvedeps': False,
'pyptex.run': False,
'FigureManager': False,
'FigureManager.show': False,
}
__pdoc__['pyptexNameSpace'] = False
class pyptexNameSpace:
def __init__(self,d):
self.__dict__.update(d)
def __str__(self):
return fr'\input{{{self.pyp.pyptexfilename}}}'
def __repr__(self):
return repr(str(self))
def __eq__(self, other):
if isinstance(self, pyptexNameSpace) and isinstance(other, pyptexNameSpace):
return self.__dict__ == other.__dict__
return NotImplemented
######################################################################
# The stuff below makes pyptex into a matplotlib backend
FigureCanvas = FigureCanvasPS
class FigureManager(FigureManagerBase):
def show(self, **kwargs):
pass
__pdoc__['show'] = False
def show(*args, **kwargs):
pass
ppparser = re.compile(r"(@@)|@([a-zA-Z_][a-zA-Z0-9_]*)|@{([^{}}]*)}",re.DOTALL)
pypparser = re.compile(r'((?<!\\)%[^\n]*\n)|(@@)|(@(\[([a-zA-Z]*)\])?{([^{}]+)}|@(\[([a-zA-Z]*)\])?{{{(.*?)}}})', re.DOTALL)
bibentryname = re.compile(r'[^{]*{([^,]*),', re.DOTALL)
stripext = re.compile(r'(.*?)(\.(pyp\.)?[^\.]*)?$', re.DOTALL)
__stringtag__ = "<PypTeX Format String>"
__pdoc__['format_my_nanos'] = False
# Credit: abarnet on StackOverflow
def format_my_nanos(nanos: int):
"""Convert nanoseconds to a human-readable format"""
dt = datetime.datetime.fromtimestamp(nanos / 1e9)
return '{}.{:09.0f}'.format(dt.strftime('%Y-%m-%d@%H:%M:%S'), nanos % 1e9)
__pdoc__['dictdiff'] = False
def dictdiff(A, B):
A = set(A.items())
B = set(B.items())
D = A ^ B
if len(D) == 0:
return None
return next(iter(D))
__pdoc__["filter_exception"] = False
def filter_exception(e):
global __stringtag__
tb = e.__traceback__
if tb is None:
return e
me = tb.tb_frame.f_code.co_filename
while tb.tb_next is not None:
code0 = tb.tb_frame.f_code
code1 = tb.tb_next.tb_frame.f_code
if code1.co_filename == me or code1.co_filename == __stringtag__:
tb.tb_next = tb.tb_next.tb_next
else:
tb = tb.tb_next
return e.with_traceback(e.__traceback__.tb_next)
__pdoc__["__format_exception__"] = False
def __format_exception__(e): # This is a workaround for broken things in Python 3.9
return '\n'.join(traceback.TracebackException(
type(e), e, e.__traceback__,limit=None,compact=True).format())
__pdoc__['exec_and_catch'] = False
def exec_and_catch(cmd,glob,loc,filename,linecount,modes=[eval,exec]):
for k in range(len(modes)):
mode = modes[k]
modename = 'exec' if mode==exec else 'eval'
if k<len(modes)-1:
try:
C = compile(('\n'*linecount)+cmd,filename,mode=modename)
except Exception:
continue
else:
C = compile(('\n'*linecount)+cmd,filename,mode=modename)
ret = mode(C,glob,loc)
return (ret,mode)
class pyptex:
r"""Class `pyptex.pyptex` is used to parse an input (templated) `a.tex` file
and produce an output `a.pyptex` file, and can be used as follows:
`pyp = pyptex('a.tex')`
The constructor reads `a.tex`, executes Python fragments and performs relevant
substitutions, writing `a.pyptex` to disk. The contents of `a.pyptex` are also
available as `pyp.compiled`.
"""
def genname(self, pattern: str = 'fig{gencount}.eps'):
r"""Generate a filename
To produce an automatically generated filename, use the statement
`pyp.genname()`, where `pyp` is an object of type `pyptex`, for parsing a
given file `a.tex`. By default, this will generate the name
`'a-generated/fig{gencount}.eps'`.
The subdirectory can be overridden by overwriting `pyp.gendir`,
and `gencount` denotes `pyp.gencount`. Any desired pattern can be used,
for example:
`name = pyp.genname('hello-{gencount}-{thing}.txt')`
will return something like `'a-generated/hello-X-Y.txt'`, where
`X` is `pyp.gencount` and `Y` is `pyp.thing`.
`pyp.genname()` does not actually create the file. `pyp.genname()` increments
`pyp.gencount` every time it is called.
"""
self.gencount += 1
return f'{self.gendir}/{pattern.format(**self.__dict__)}'
def __setupfig__(self, fig):
if not hasattr(fig,'__FIGNAME__'):
figname = self.genname()
Path(figname).touch()
self.dep(figname)
fig.__FIGNAME__ = figname
if not hasattr(fig,'__IG__'):
fig.__IG__ = (self.includegraphics%figname)
if not hasattr(fig,'drawn'):
fig.drawn = False
return fig.__IG__
def showall(self):
for num, figmanager in enumerate(Gcf.get_all_fig_managers()):
fig = figmanager.canvas.figure
self.__setupfig__(fig)
if fig.drawn:
pass
else:
self.print(fig)
def generateddir(self):
"""This is an internal function that creates the generated directory."""
self.gendir = f'{self.filename}-generated'
if not os.path.exists(self.gendir):
os.makedirs(self.gendir)
self.gencount = 0
def freeze(self):
"""'Freezes' the global scope of the caller by performing a shallow copy and copying it to
`pyp.__frozen__`
See also `pyptex.clear()`"""
self.__frozen__ = inspect.stack()[1][0].f_globals.copy()
def clear(self):
"""Clears all global variable.
pyptex.clear() clears all the global variables of the caller. Example usage:
```python
a = 1
print(a) # this prints 1
pyp.clear()
print(a) # this raises an exception because
# a is now undefined.
```
The global scope is restored from the dictionary `pyp.__frozen__`, which initially only contains
the pyp object and the `__builtins__` module. One can add more items to the `__frozen__` dict, e.g.
by importing some standard module. For example,
```python
my_variable = 78
import sys
pyp.freeze() # This freezes my_variable and sys.
foo = 1 # Now foo is defined...
pyp.clear()
# ...Now foo is undefined, but my_variable is still 78,
# and the sys module is still available.
```
Note that `pyp.freeze()` performs a shallow copy, so:
```python
a = [1,2,3]
pyp.freeze() # a = [1,2,3] is now in the frozen scope.
a[1] = 7 # Now a = [1,7,3] in the global scope.
pyp.clear()
# Still a = [1,7,3] because the scope copy was shallow.
```
"""
foo = self.__frozen__
bar = inspect.stack()[1][0].f_globals
for k,v in foo.items():
bar[k] = v
kk = list(bar.keys())
for k in kk:
if k not in foo:
del bar[k]
def __init__(self, texfilename, argv=None, latexcommand=False):
r"""`pyp = pyptex('a.tex')` reads in the LaTeX file a.tex and locates all
Python code fragments contained inside. These Python code fragments are
executed and their outputs are substituted to produce the `a.pyptex` output file.
`pyp = pyptex('a.tex', argv)` passes "command-line arguments". The pyptex
command-line passes `sys.argv[2:]` for this parameter. If omitted, `argv`
defaults to `[]`. If using PypTeX as an templating engine to generate
multiple documents from a single source `a.tex` file, one should use
the `argv` parameter to pass in the various side-parameters needed to generate
each document. For example, `a.tex` might have the line "Dear @{pyp.argv[0]}""
One could produce a letter to John by doing `pyp = pyptex('a.tex', ['John'])`.
`pyp = pyptex('a.tex', argv, latexcommand)` further executes a specific shell
command once `a.pyptex` has been written to disk (e.g. `pdflatex {pytexfilename}`).
The default value of `latexcommand` is `False`, in which case no shell command
is executed.
Some salient fields of the `pyp=pyptex('a.tex')` class are:
* `pyp.filename = 'a'` (so `a.tex`, with the extension stripped).
* `pyp.texfilename = 'a.tex'`.
* `pyp.cachefilename = 'a.pickle'`.
* `pyp.bibfilename = 'a.bib'`, used by the `pyp.bib()` function.
* `pyp.pyptexfilename = 'a.pyptex'`.
* `pyp.auxfilename = 'a.aux'`, useful in case bibtex is used.
* `pyp.latex = "pdflatex --file-line-error --synctex=1"`.
One may overwrite this in a.tex to choose a different latex engine, e.g.
`pyp.latex = "latex"`.
* `pyp.latexcommand` defaults to `False`, but the command-line version of `pyptex`
uses something like.
`r"{latex} {pyptexfilename} && (test ! -f {bibfilename} || bibtex {auxfilename})"`
The relevant substitutions are performed by `string.format` from `pyp.__dict__`.
* `pyp.disable_cache = False`, set this to `True` if you want to disable the `a.pickle`
cache. You shouldn't need to do this but if your Python code is nondeterministic
or if tracking dependencies is too hard, disabling all caching will ensure
that `a.pyptex` is correctly compiled into `a.pdf` and that a stale cache is
never used.
* `pyp.deps` is a dictionary of dependencies and timestamps.
* `pyp.lc` counts lines while parsing.
* `pyp.argv` stores the ``command-line arguments'' for template generation.
* `pyp.exitcode` is the exit code of the `pyp.latexcommand`.
* `pyp.gencount` is the counter for generated files (see `pyp.gen()`).
* `pyp.fragments` is the list of Python fragments extracted from a.tex.
* `pyp.outputs` is the matching outputs.
* `pyp.compiled` is the string that is written to `a.pyptex`.
* `pyp.autoshow` if True, each figure `fig` is automatically displayed (by `pyp.print`ing
a suitable `includegraphics` command) at the end of each Python block. When a `fig` is thus
displayed, `fig.drawn` is set to `True`. Figures that have already been `drawn` are not
automatically displayed at the end of the Python block.
"""
print(f'{texfilename}: pyptex compilation begins')
self.__sympy_plot__ = sympy.plotting.plot(1, show=False).__class__
self.__globals__ = {'__builtins__': __builtins__, 'pyp': self }
self.__frozen__ = self.__globals__.copy()
self.__substarts__ = []
self.__subends__ = []
self.filename = stripext.sub(lambda m: m.group(1),texfilename)
self.texfilename = texfilename
matplotlib.use("module://pyptex")
foo = self.filename+'.tex'
self.pyptexfilename = foo if foo!=texfilename else f'{self.filename}.pyptex'
self.cachefilename = f'{self.filename}.pickle'
self.linemapfilename = f'{self.filename}.linemap'
self.bibfilename = f'{self.filename}.bib'
self.auxfilename = f'{self.filename}.aux'
self.includegraphics = r'\includegraphics[width=\textwidth]{%s}'
self.latex = 'pdflatex -file-line-error --synctex=1'
self.latexcommand = latexcommand
self.disable_cache = False
self.autoshow = True
self.__show__ = matplotlib.pyplot.show
self.deps = {}
self.bibs = []
self.lc = 0
self.argv = [] if argv is None else argv
self.exitcode = 0
self.generateddir()
self.dep(__file__)
self.compile()
print(f'{texfilename}: pyptex compilation ends')
def pp(self, Z):
r"""Pretty-prints the template text string `Z`, using substitutions from the local
scope that is `levels` calls up on the stack. The template character is @.
For example, assume the caller has the value `x=3` in its local variables. Then,
`pyp.pp("$x=@x$")` produces `$x=3$`.
`pp` can also evaluate Python expressions in the template string, e.g.
`pyp.pp("@{3+4}")` produces `7`.
"""
global ppparser,__stringtag__
foo = inspect.currentframe().f_back
def do_work(m):
if m.start(1) >= 0:
return '@'
for k in [2,3]:
if m.start(k) >= 0:
return self.mylatex(eval(compile(m.group(k),__stringtag__,mode='eval'),
foo.f_globals, foo.f_locals))
raise Exception("Tragic regular expression committed seppuku")
return ppparser.sub(do_work, Z)
def run(self, S, k):
"""An internal function for executing Python code."""
print(f'Executing Python code:\n{S}')
glob_ = self.__globals__
doeval = False
self.__accum__ = []
(ret,mode) = exec_and_catch(
cmd=S,glob=glob_,loc=None,
filename=self.texfilename,linecount=k
)
if mode==eval:
self.__accum__.append(ret)
if self.autoshow:
self.showall()
print(f'Python result:\n{self.__accum__!s}')
return self.__accum__
def print(self, *argv):
"""If `pyp` is an object of type `pyptex`, `pyp.print(X)` causes `X` to be converted
to its latex representation and substituted into the `a.pyptex` output file.
The conversion is given by `sympy.latex(X)`, except that `None` is converted
to the empty string.
Many values can be printed at once with the notation `pyp.print(X, Y, ...)`."""
for k in range(len(argv)):
if isinstance(argv[k],matplotlib.pyplot.Figure):
self.mylatex(argv[k])
self.__accum__.extend(argv)
def cite(self,b):
r"""If `pyp` is an object of type `pyptex`, then `pyp.cite(X)` adds the relevant
entry to the bibTeX file and returns the entry name. Example usage:
`\cite{@{{{pyp.cite(r"@article{seb97,title=Some title etc...}")}}}}`
"""
self.bibs.append(b)
return bibentryname.match(b).group(1).strip()
def process(self, S, runner, record_substitutions):
"""An internal helper function for parsing the input file."""
ln = numpy.cumsum(numpy.array(numpy.array(list(S), dtype='U1') == '\n', int))
ln = numpy.insert(ln, 0, 0)
def do_work(m):
if m.start(1) >= 0:
return m.group(0)
if m.start(2) >= 0:
return '@'
for k in [6,9]:
if m.start(k) >= 0:
z = m.group(k)
z0 = m.start(k)
z1 = m.end(k)
o = m.group(k-1) or ''
break
self.lc += ln[z1] - ln[z0] + 1
ret = runner(z, ln[z0], o)
if record_substitutions:
self.__substarts__.append(ln[m.start(0)])
self.__subends__.append(ln[m.end(0)])
return ret
return pypparser.sub(do_work, S)
__pdoc__['mylatex'] = False
def mylatex(self, X):
if X is None:
return ''
if isinstance(X, str):
return X
if isinstance(X,pyptexNameSpace):
return str(X)
if isinstance(X,matplotlib.pyplot.Figure):
self.__setupfig__(X)
print(X.__IG__)
X.canvas.print_figure(X.__FIGNAME__)
X.drawn = True
return X.__IG__
if isinstance(X,self.__sympy_plot__):
return ""
if isinstance(X,matplotlib.artist.Artist):
return ""
if isinstance(X,list) and isinstance(X[0],matplotlib.artist.Artist):
return ""
return sympy.latex(X)
def compile(self):
"""An internal function for compiling the input file."""
with open(self.texfilename, 'rt') as file:
text = file.read()
try:
with open(self.cachefilename, 'rb') as file:
cache = pickle.load(file)
except Exception:
cache = {}
defaults = {
'fragments': [],
'outputs': [],
'deps': {},
'argv': [],
'disable_cache': True,
}
for k, v in defaults.items():
if k not in cache:
cache[k] = v
self.fragments = []
def scanner(C, k, o):
self.fragments.append(C)
assert o in ['','verbatim'],"Invalid option: "+o
return ''
self.process(text, runner=scanner, record_substitutions=True)
print(f'Found {self.lc!s} lines of Python.')
saveddeps = self.deps
self.deps = {}
for k in cache['deps']:
self.dep(k)
self.resolvedeps()
cached = True
if cache['disable_cache']:
print('disable_cache=True')
cached = False
elif cache['argv'] != self.argv:
print('argv differs', self.argv, cache['argv'])
cached = False
elif cache['fragments'] != self.fragments:
F1 = dict(enumerate(cache['fragments']))
F2 = dict(enumerate(self.fragments))
k = dictdiff(F1, F2)[0]
print('Fragment #', k,
'\nCached version:\n', F1[k] if k in F1 else None,
'\nLive version:\n', F2[k] if k in F2 else None)
cached = False
elif self.deps != cache['deps']:
F1 = cache['deps']
F2 = self.deps
k = dictdiff(F1, F2)[0]
print('Dependency mismatch', k,
'\nCached version:\n', F1[k] if k in F1 else None,
'\nLive version:\n', F2[k] if k in F2 else None)
cached = False
if cached:
print('Using cached Python outputs')
for k, v in cache.items():
self.__dict__[k] = v
self.subcount = -1
def subber(C, k, o):
self.subcount += 1
if(o==''):
return self.outputs[self.subcount]
if(o=='verbatim'):
return C
self.compiled = self.process(text, runner=subber, record_substitutions=False)
else:
print('Cache is invalidated.')
self.deps = saveddeps
self.outputs = []
def appender(C, k, o):
result = self.run(C, k)
self.outputs.append(''.join(map(self.mylatex, result)))
if(o==''):
return self.outputs[-1]
if(o=='verbatim'):
return C
self.compiled = self.process(text, runner=appender, record_substitutions=False)
sys.stdout.flush()
if self.pyptexfilename:
print(f'Saving to file: {self.pyptexfilename}')
with open(self.pyptexfilename, 'wt') as file:
file.write(self.compiled)
self.resolvedeps()
print(f'Dependencies are:\n{self.deps!s}')
numlines = len(text.split('\n'))
linemaps = []
prevline = 0
for k in range(len(self.outputs)):
linemaps.append(list(range(prevline+1,self.__substarts__[k]+1)))
count = len(self.outputs[k].split('\n'))
linemaps.append([self.__substarts__[k]]*(count-1))
prevline = self.__subends__[k]
linemaps.append(list(range(prevline+1,numlines+1)))
self.linemap = [str(x) for sublist in linemaps for x in sublist]
print('Saving cache file', self.cachefilename)
with open(self.cachefilename, 'wb') as file:
cache = {}
for k, v in self.__dict__.items():
if k[0:2] == '__' and k[-2:] == '__':
pass
elif callable(v):
pass
else:
cache[k] = v
pickle.dump(cache, file)
if self.latexcommand:
cmd = self.latexcommand.format(**self.__dict__)
print(f'Running Latex command:\n{cmd}')
self.exitcode = subprocess.Popen(shlex.split(cmd),close_fds=True).wait()
def bib(self, bib=""):
"""A helper function for creating a `.bib` file. If `pyp=pyptex('a.tex')`,
then `pyp.bib('''@book{knuth1984texbook, title={The {TEXbook}},
author={Knuth, Donald Ervin and Bibby, Duane}}''')` creates a file
`a.bib` with the given text. This is just a convenience function
that makes it easier to incorporate the bibtex file straight into the
`a.tex` source. In `a.tex`, the typical way of using it is:
`\\bibliography{@{{{pyp.bib("...")}}}}`.
"""
self.bibs.append(bib)
with self.open(self.bibfilename, 'wt') as file:
file.write("\n".join(self.bibs))
return self.filename
def dep(self, filename):
"""If `pyp=pyptex('a.tex')`, then `pyp.dep(filename)` declares that the Python code
in `a.tex` depends on the file designated by `filename`. When the object
`pyptex('a.tex')` is constructed, the file `a.pickle` will be loaded (if it exists).
`a.pickle` is a cache of the results of the Python calculations in `a.tex`.
If the cache is deemed valid, the `pyptex` constructor does not rerun all
the Python fragments in `a.tex` but instead uses the previously cached outputs.
The cache is invalidated under the following scenarios:
1. The new Python fragments in `a.tex` are not identical to the cached fragments.
2. The "last modification" timestamp on dependencies is not the same as in the cache.
3. `pyp.disable_cache==True`.
The list of dependencies defaults to only the `pyptex` executable. Additional
dependencies can be manually declared via `pyp.dep(filename)`.
For convenience, `pyp.dep(filename)` returns filename.
"""
self.deps[filename] = ''
return filename
def resolvedeps(self):
"""An internal function that actually computes the datestamps of dependencies."""
for k in self.deps:
try:
ds = format_my_nanos(os.stat(k).st_mtime_ns)
except Exception:
ds = ''
self.deps[k] = ds
def input(self, filename, argv=False):
r"""If `pyp = pyptex('a.tex')` then
`pyp.input('b.tex')`
returns the string `\input{"b.pyptex"}`. The common way of using this is to
put `@{pyp.input('b.tex')}` somewhere in `a.tex`.
The function `pyp.input('b.tex')` internally calls the constructor
`pyptex('b.tex')` so that `b.pyptex` is compiled from `b.tex`.
Note that the two files `a.tex` and `b.tex` are "semantically isolated". All
calculations, variables and functions defined in `a.tex` live in a global scope
that is private to `a.tex`, much like each Python module has a private global
scope. In a similar fashion, `b.tex` has its own private global scope.
The global `pyp` objects in `a.tex` and `b.tex` are also different instances
of the `pyptex` class. This is similar to the notion of "compilation units" in
the C programming language.
From `a.tex`, one can retrieve global variables of `b.tex` as follows. If
`foo = pyp.input('b.tex')`, and if `b.tex` defines a global variable `x`,
then it can be retrieved by `foo.x`. The `foo` variable is an instance of a
`pyptexNameSpace` that contains the global scope of `b.tex`. This type has a
custom string representation, so that `str(foo)` or `@{foo}` is
`'\input{b.pyptex}'`.
If one wishes to pass some parameters from `a.tex` to `b.tex`, one may use
the notation `pyp.input('b.tex', argv)`, which will initialize the global
`pyp` object of `b.tex` so that it contains the field `pyp.argv=argv`.
"""
ret = pyptex(filename, argv or self.argv, False)
ret2 = pyptexNameSpace(ret.__globals__)
return ret2
def open(self, filename, *argv, **kwargs):
"""If pyp = pyptex('a.tex') then pyp.open(filename, ...) is a wrapper for
the builtin function open(filename, ...) that further adds filename to
the list of dependencies via pyp.dep(filename).
"""
self.dep(filename)
return open(filename, *argv, **kwargs)
class MyWriter(streamcapture.Writer):
def __init__(self,stream):
super(MyWriter, self).__init__(stream)
self.last = b""
self.matcher = re.compile(b'([^:]*):([0-9]+): ')
self.caches = {}
def write_from(self,data,cap):
foo = data.split(b"\n")
n = len(foo)
for k in range(n):
bar = b"" if k>0 else self.last
baz = self.matcher.match(bar+foo[k])
if baz:
pyptexfile = baz.group(1).decode()
basename = stripext.sub(lambda m: m.group(1),pyptexfile)
picklefile = basename+'.pickle'
if picklefile not in self.caches:
try:
with open(picklefile, 'rb') as file:
self.caches[picklefile] = pickle.load(file)
except Exception:
self.caches[picklefile] = None
cache = self.caches[picklefile]
if cache is None:
continue
texfile = cache['texfilename']
pyptexlinenumber = int(baz.group(2).decode())
texlinenumber = cache['linemap'][pyptexlinenumber-1]
foo[k] += (f"\n{texfile}:{texlinenumber}: PypTeX source file").encode()
data = b"\n".join(foo)
if n<2:
self.last = b""
self.last += foo[n-1]
self._write(data)
os.write(cap.dup_fd,data)
def pyptexmain(argv: list = None):
"""This function parses an input file a.tex to produce a.pyptex and a.pdf, by
doing pyp = pyptex('a.tex', ...) object. The filename a.tex must be in argv[1];
if argv is not provided, it is taken from sys.argv.
The default pyp.latexcommand invokes pdflatex and, if a.bib is present, also bibtex.
If an exception occurs, pdb is automatically invoked in postmortem mode.
If "--pdb=no" is in argv, it is removed from argv and automatic pdb postmortem is disabled.
If "--pdb=yes" is in argv, automatic pdb postmortem is enabled. This is the default.
"""
argv = argv or sys.argv
dopdb = True
with suppress(Exception):
argv.remove('--pdb=no')
dopdb = False
with suppress(Exception):
argv.remove('--pdb=yes')
dopdb = True
if len(argv) < 2:
print('Usage: pyptex <filename.tex> ...')
sys.exit(1)
writer = MyWriter(open(f'{os.path.splitext(argv[1])[0]}.pyplog','wb'))
# writer = streamcapture.Writer(open(f'{os.path.splitext(argv[1])[0]}.pyplog','wb'),2)
with streamcapture.StreamCapture(sys.stdout,writer,echo=False), streamcapture.StreamCapture(sys.stderr,writer,echo=False):
try:
pyp = pyptex(argv[1], argv[2:],
latexcommand=r'{latex} {pyptexfilename} && (test ! -f {bibfilename} || bibtex {auxfilename})',
)
except Exception as e:
import pdb
e = filter_exception(e)
print(__format_exception__(e))
# print('\n'.join(traceback.TracebackException(exc_type=type(foo), exc_value=foo, exc_traceback=foo.__traceback__).format()))
if e.__traceback__ is not None and dopdb:
print('A Python error has occurred. Launching the debugger pdb.\n'
"Type 'help' for a list of commands, and 'quit' when done.")
pdb.post_mortem(e.__traceback__)
sys.exit(1)
return pyp.exitcode</code></pre>
</details>
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-functions">Functions</h2>
<dl>
<dt id="pyptex.pyptexmain"><code class="name flex">
<span>def <span class="ident">pyptexmain</span></span>(<span>argv: list = None)</span>
</code></dt>
<dd>
<div class="desc"><p>This function parses an input file a.tex to produce a.pyptex and a.pdf, by