forked from gpoore/pythontex
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpythontex.dtx
More file actions
3706 lines (3684 loc) · 280 KB
/
pythontex.dtx
File metadata and controls
3706 lines (3684 loc) · 280 KB
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
% \iffalse meta-comment
%
% Copyright (C) 2012-2013 by Geoffrey M. Poore <[email protected]>
% ---------------------------------------------------------------------------
% This work may be distributed and/or modified under the
% conditions of the LaTeX Project Public License, either version 1.3
% of this license or (at your option) any later version.
% The latest version of this license is in
% http://www.latex-project.org/lppl.txt
% and version 1.3 or later is part of all distributions of LaTeX
% version 2005/12/01 or later.
%
% This work has the LPPL maintenance status `maintained'.
%
% The Current Maintainer of this work is Geoffrey M. Poore.
%
% This work consists of the files pythontex.dtx and pythontex.ins
% and the derived filebase pythontex.sty.
%
% \fi
%
% \iffalse
%<*driver>
\ProvidesFile{pythontex.dtx}
%</driver>
%<package>\NeedsTeXFormat{LaTeX2e}[1999/12/01]
%<package>\ProvidesPackage{pythontex}
%<*package>
[2013/04/30 Version~0.12]
%</package>
%
%<*driver>
\documentclass{ltxdoc}
\makeatletter
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{textcomp}
\usepackage[svgnames]{xcolor}
\usepackage{environ}
\usepackage{enumitem}
\usepackage[fixlr=false]{pythontex} %Need fixlr=false so can demo issue
\usepackage{hyperref}
\hypersetup{colorlinks=true,urlcolor=Green,linkcolor=blue}
\newcommand{\pytxtodo}[1]{}
%\newcommand{\pytxtodo}[1]{\textcolor{red}{TO~DO: \scantokens{#1}}}
\newcommand{\changestext}{}
\NewEnviron{changelog}[2]{%
\g@addto@macro\changestext{\item[#1] (#2) \begin{itemize}}%
\expandafter\g@addto@macro\expandafter\changestext\expandafter{\BODY}%
\g@addto@macro\changestext{\end{itemize}}%
}
\newcommand{\PrintChangelog}{%
\addcontentsline{toc}{section}{Version History}
\section*{Version History}%
\begin{description}%
\changestext
\end{description}%
}
\EnableCrossrefs
\CodelineIndex
%\RecordChanges
\makeatother
\begin{document}
\DocInput{pythontex.dtx}
%\PrintChanges
\PrintIndex
\end{document}
%</driver>
% \fi
%
% \CheckSum{2760}
%
% \CharacterTable
% {Upper-case \A\B\C\D\E\F\G\H\I\J\K\L\M\N\O\P\Q\R\S\T\U\V\W\X\Y\Z
% Lower-case \a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\x\y\z
% Digits \0\1\2\3\4\5\6\7\8\9
% Exclamation \! Double quote \" Hash (number) \#
% Dollar \$ Percent \% Ampersand \&
% Acute accent \' Left paren \( Right paren \)
% Asterisk \* Plus \+ Comma \,
% Minus \- Point \. Solidus \/
% Colon \: Semicolon \; Less than \<
% Equals \= Greater than \> Question mark \?
% Commercial at \@ Left bracket \[ Backslash \\
% Right bracket \] Circumflex \^ Underscore \_
% Grave accent \` Left brace \{ Vertical bar \|
% Right brace \} Tilde \~}
%
%
% \begin{changelog}{v0.12}{2013/05/05}
% \item Increased compatibilty with latexmk by providing warnings on not found files.
% \end{changelog}
%
% \begin{changelog}{v0.11}{2013/04/21}
% \item As the first non-beta release, this version adds several features and introduces several changes. You should read these release notes carefully, since some changes are not backwards-compatible. Changes are based on a thorough review of all current and planned features. PythonTeX's capabilities have already grown beyond what was originally intended, and a long list of features still remains to be implemented. As a result, some changes are needed to ensure consistent syntax and naming in the future. Insofar as possible, all command names and syntax will be frozen after this release.
% \item Added the \texttt{pythontex.py} and \texttt{depythontex.py} wrapper scripts. When run, these detect the current version of Python and import the correct PythonTeX code. It is still possible to run \texttt{pythontex*.py} and \texttt{depythontex*.py} directly, but the new wrapper scripts should be used instead for simplicity. There is now only a single \texttt{pythontex\_utils.py}, which works with both Python 2 and Python 3.
% \item Added the \texttt{beta} package option. This makes the current version behave like v0.11beta, for compatibility. This option is temporary and will probably only be retained for a few releases.
% \item Backward-incompatible changes (require the \texttt{beta} option to restore old behavior)
% \begin{itemize}
% \item The \texttt{pyverb} environment has been renamed \texttt{pyverbatim}. The old name was intended to be concise, but promoted confusion with LaTeX's \texttt{\string\verb} macro.
% \item For \texttt{\string\printpythontex}, \texttt{\string\stdoutpythontex}, and \texttt{\string\stderrpythontex}, the modes \texttt{inlineverb} and \texttt{v} have been replaced by \texttt{verb}, and the old mode \texttt{verb} has been replaced by \texttt{verbatim}. This brings naming conventions in line with standard LaTeX \texttt{\string\verb} and \texttt{verbatim}, avoiding a source of potential confusion.
% \item The \texttt{\string\setpythontexpyglexer}, \texttt{\string\setpythontexpygopt}, and \texttt{\string\setpygmentspygopt} commands now take an optional argument and a mandatory argument, rather than two mandatory arguments. This creates better uniformity among current and planned settings macros.
% \item The \texttt{\string\setpythontexformatter} and \texttt{\string\setpygmentsformatter} commands have been replaced by the \texttt{\string\setpythontexprettyprinter} and \texttt{\string\setpygmentsprettyprinter} commands. This anticipates possible upcoming features. It also avoids potential confusion with Pygments's formatters and the utilities class's \texttt{formatter()} method.
% \end{itemize}
% \item Deprecated (still work, but raise warnings; after a few releases, they will raise errors instead, and after that eventually be removed)
% \begin{itemize}
% \item The \texttt{rerun} setting \texttt{all} was renamed \texttt{always}, in preparation for upcoming features.
% \item The \texttt{stderr} option is replaced by \texttt{makestderr}. The \texttt{print}/\texttt{stdout} option is replaced by \texttt{debug}. These are intended to prevent confusion with future features.
% \item The \texttt{fixlr} option is deprecated. It was originally introduced to deal with some of SymPy's LaTeX formatting, which has since changed.
% \item The utilities class method \texttt{init\_sympy\_latex()} is deprecated. The \texttt{sympy\_latex()} and \texttt{set\_sympy\_latex()} methods now automatically initialize themselves on first use.
% \end{itemize}
% \item Added \texttt{autostdout} package option and \texttt{\string\setpythontexautostdout}, to complement \texttt{autoprint}. Added |prettyprinter| and |prettyprintinline| package options to complement new settings commands.
% \item Added quickstart guide.
% \item Installer now installs gallery and quickstart files, if present.
% \end{changelog}
%
% \begin{changelog}{v0.11beta}{2013/02/17}
% \item Commands like \texttt{\string\py} can now bring in any valid LaTeX code, including verbatim content, under the pdfTeX and XeTeX engines. Verbatim content was not allowed previously. LuaTeX cannot bring in verbatim, due to a known bug.
% \item Added package option \texttt{depythontex} and scripts \texttt{depythontex*.py}. These allow a PythonTeX document to be converted into a pure LaTeX document, with no Python dependency. The package option creates an auxiliary file with extension \texttt{.depytx}. The \texttt{depythontex*.py} scripts take this auxiliary file and the original LaTeX document, and combine the two to produce a new document that does not rely on the PythonTeX package. All PythonTeX commands and environments are replaced by their output. All Python-generated content is substituted directly into the document. By default, all typeset code is wrapped in \texttt{\string\verb} and \texttt{verbatim}, but \texttt{depythontex*.py} has a \texttt{-{}-listing} option that allows \texttt{fancyvrb}, \texttt{listings}, \texttt{minted}, or \texttt{pythontex} to be used instead.
% \item The current PythonTeX version is now saved in the \texttt{.pytxcode}. If this does not match the version of the PythonTeX scripts, a warning is issued. This makes it easier to determine errors due to version mismatches.
% \item Fixed an incompatibility with the latest release of \texttt{xstring} (version 1.7, 2013/01/13).
% \item Fixed a bug in the \texttt{console} environment that could cause problems when switching from Pygments highlighting to \texttt{fancyvrb} when using the \texttt{fvextfile} option. Fixed a bug introduced in the v0.10beta series that prevented the \texttt{console} environment from working with \texttt{fancyvrb}.
% \item Fixed a bug with PythonTeX verbatim commands and environments that use Pygments. The verbatim commands and environments were incorrectly treated as if they had the attributes of executed code in the v0.10beta series.
% \item Fixed a bug from the v0.10beta series that sometimes prevented imports from \texttt{\_\_future\_\_} from working when there were multiple sessions.
% \item Fixed a bug related to hashing dependencies' mtime under Python 3.
% \end{changelog}
%
% \begin{changelog}{v0.10beta2}{2013/01/23}
% \item Improved \texttt{pythontex*.py}'s handling of the name of the file being processed. A warning is no longer raised if the name is given with an extension; extensions are now processed (stripped) automatically. The filename may now contain a path to the file, so you need not run \texttt{pythontex*.py} from within the document's directory.
% \item Added command-line option \texttt{-{}-verbose} for more verbose output. Currently, this prints a list of all processes that are launched.
% \item Fixed a bug that could crash \texttt{pythontex*.py} when the package option \texttt{pygments=false}.
% \item Added documentation about \texttt{autoprint} behavior in the preamble. Summary: \texttt{code} commands and environments are allowed in the preamble as of v0.10beta. \texttt{autoprint} only applies to the body of the document, because nothing can be typeset in the preamble. Content printed in the preamble can be brought in by explicitly using \texttt{\string\printpythontex}, but this should be used with great care.
% \item Revised \texttt{\string\stdoutpythontex} and \texttt{\string\printpythontex} so that they work in the preamble. Again, this should be used with great care if at all.
% \item Revised treatment of any content that custom code attempts to print. Custom code is not allowed to print to the document (see documentation). If custom code attempts to print, a warning is raised, and the printed content is included in the \texttt{pythontex*.py} run summary.
% \item One-line entries in stderr, such as those produced by Python's \texttt{warnings.warn()}, were not previously parsed because they are of the form \texttt{:<linenumber>:} rather than \texttt{line~<linenumber>}. These are now parsed and synchronized with the document. They are also correctly parsed for inclusion in the document via \texttt{\string\stderrpythontex}.
% \item If the package option \texttt{stderrfilename} is changed, all sessions that produced errors or warnings are now re-executed automatically, so that their stderr content is properly updated with the new filename.
% \end{changelog}
%
% \begin{changelog}{v0.10beta}{2013/01/09}
% \item Backward-incompatible: Redid treatment of command-line options for \texttt{pythontex*.py}, using Python's \texttt{argparse} module. Run \texttt{pythontex*.py} with option \texttt{-h} to see new command line options.
% \item Deprecated: \texttt{\string\setpythontexcustomcode} is deprecated in favor of the \texttt{\string\pythontexcustomc} command and \texttt{pythontexcustomcode} environment. These allow entry of pure code, unlike \texttt{\string\setpythontexcustomcode}. These also allow custom code to be added to the beginning or end of a session, via an optional argument. Improved treatment of errors and warnings associated with custom code.
% \item The summary of errors and warnings now correctly differentiates errors and warnings produced by user code, rather than treating all of them as errors. By default, \texttt{pythontex*.py} now returns an exit code of 1 if there were errors.
% \item The PythonTeX utilities class now allows external file dependencies to be specified via \texttt{pytex.add\_dependencies()}, so that sessions are automatically re-executed when external dependencies are modified (modification is determined via either hash or mtime; this is governed by the new \texttt{hashdependencies} option).
% \item The PythonTeX utilities class now allows created files to be specified via \texttt{pytex.add\_created()}, so that created files may be automatically cleaned up (deleted) when the code that created them is modified (for example, name change for a saved plot).
% \item Added the following package options.
% \begin{itemize}
% \item \texttt{stdout} (or \texttt{print}): Allows input of stdout to be disabled. Useful for debugging.
% \item \texttt{runall}: Executes everything. Useful when code depends on external data.
% \item \texttt{rerun}: Determines when code is re-executed. Code may be set to always run (same as \texttt{runall} option), or only run when it is modified or when it produces errors or warnings. By default, code is always re-executed if there are errors or modifications, but not re-executed if there are warnings.
% \item \texttt{hashdependencies}: Determines whether external dependencies (data, external code files highlighted with Pygments, etc.) are checked for modification via hashing or modification time. Modification time is default for performance reasons.
% \end{itemize}
% \item Added the following new command line options. The options that are equivalent to package options are overridden by the package options when present.
% \begin{itemize}
% \item \texttt{-{}-error-exit-code}: Determines whether an exit code of 1 is returned if there were errors. On by default, but can be turned off since it is undesirable when working with some editors.
% \item \texttt{-{}-runall}: Equivalent to new package option.
% \item \texttt{-{}-rerun}: Equivalent to new package option.
% \item \texttt{-{}-hashdependencies}: Equivalent to new package option.
% \end{itemize}
% \item Modified the \texttt{fixlr} option, so that it only patches commands if they have not already been patched (avoids package conflicts).
% \item Added \texttt{\string\setpythontexautoprint} command for toggling autoprint on/off within the body of the document.
% \item Installer now attempts to create symlinks under OS X and Linux with TeX Live, and under OS X with MacPorts Tex Live.
% \item Performed compatibility testing under lualatex and xelatex (previously, had only tested with pdflatex). Added documentation for using these TeX engines; at most, slightly different preambles are needed. Modified the PythonTeX gallery to support all three engines.
% \item Code commands and environments may now be used in the preamble. This, combined with the new treatment of custom code, allows PythonTeX to be used in creating LaTeX packages.
% \item Added documentation for using PythonTeX in LaTeX programming.
% \item Fixed a bug that sometimes caused incorrect line numbers with \texttt{stderr} content. Improved processing of stderr.
% \item Fixed a bug in automatic detection of pre-existing listings environment.
% \item Improved the detection of imports from \texttt{\_\_future\_\_}. Detection should now be stricter, faster, and more accurate.
% \end{changelog}
%
% \begin{changelog}{v0.9beta3}{2012/07/17}
% \item Added Unicode support, which required the Python code to be split into one set for Python 2 and another set for Python 3. This will require any old installation to be completely removed, and a new installation created from scratch.
% \item Refactoring of Python code. Documents should automatically re-execute all code after updating to the new version. Otherwise, you should delete the PythonTeX directory and run PythonTeX.
% \item Improved installation script.
% \item Added package options: pyfuture, stderr, upquote, pyglexer, pyginline. Renamed the pygextfile option to fvextfile.
% \item Added custom code and workingdir commands.
% \item Added the console environment and associated options.
% \item Rewrote pythontex\_utils*.py, creating a new, context-aware interface to SymPy's LatexPrinter class.
% \item Content brought in via macros no longer uses labels. Rather, long defs are used, which allows line breaks.
% \item Pygments highlighting is now default for PythonTeX commands and environments
% \end{changelog}
%
% \begin{changelog}{v0.9beta2}{2012/05/09}
% \item Changed Python output extension to .stdout.
% \end{changelog}
%
% \begin{changelog}{v0.9beta}{2012/04/27}
% \item Initial public beta release.
% \end{changelog}
%
%
% \DoNotIndex{\newcommand,\newenvironment}
% \DoNotIndex{\#,\$,\%,\&,\@,\\,\{,\},\^,\_,\~,\ }
% \DoNotIndex{\@ne}
% \DoNotIndex{\advance,\begingroup,\catcode,\closein}
% \DoNotIndex{\closeout,\day,\def,\edef,\else,\empty,\endgroup}
% \DoNotIndex{\begin,\end,\bgroup,\egroup}
%
% \providecommand*{\url}{\texttt}
% \newcommand{\pytex}{Python\TeX}
% \GetFileInfo{pythontex.dtx}
% \title{The \textsf{pythontex} package}
% \author{Geoffrey M.\ Poore \\ \url{[email protected]} \\ \href{https://github.com/gpoore/pythontex}{\texttt{github.com/gpoore/pythontex}}}
% \date{\fileversion~from \filedate}
%
% \maketitle
%
% \begin{abstract}
% \pytex\ provides access to Python from within \LaTeX\ documents. It allows Python code entered within a \LaTeX\ document to be executed, and the results to be included within the original document. Python code and the figure or calculation it creates may be side by side. The package also makes possible macro definitions that mix Python and \LaTeX\ code. In addition, \pytex\ provides syntax highlighting for many programming languages via the Pygments syntax highlighter.
%
% \pytex\ is fast and user-friendly. Python code is only executed when it has been modified, or when user-specified criteria are met. When code is executed, sessions automatically run in parallel. If Python code produces errors, the error message line numbers are synchronized with the \LaTeX\ document line numbers, so that it is easy to find the error source. Dependencies may be specified so that code is automatically re-executed whenever its dependencies are modified.
%
% Because documents that use \pytex\ mix \LaTeX\ and Python code, they are less suitable than plain \LaTeX\ documents for journal submission, sharing, and conversion to other formats. \pytex\ includes a |depythontex| utility that creates a copy of a document in which all \pytex\ content is replaced by its output.
%
% While Python is the focus of \pytex, the package will add basic support for additional programming languages in the near future.
% \end{abstract}
%
%
% \section*{Warning}
% \pytex\ makes possible some pretty amazing things. But that power brings with it a certain risk and responsibility. Compiling a document that uses \pytex\ involves executing Python code, and potentially other programs, on your computer. You should only compile \pytex\ documents from sources you trust. \pytex\ comes with NO WARRANTY.\footnote{All \LaTeX\ code is licensed under the \href{http://www.latex-project.org/lppl.txt}{\LaTeX\ Project Public License (LPPL)} and all Python code is licensed under the \href{http://www.opensource.org/licenses/BSD-3-Clause}{BSD 3-Clause License}.} The copyright holder and any additional authors will not be liable for any damages.
%
%
%
% \pagebreak
% \tableofcontents
% \pagebreak
%
%
% \section{Introduction}
%
% This introduction provides background and objectives for the \pytex\ package. To jump right in and get started, you may wish to consult the |pythontex_quickstart| and |pythontex_gallery| documents, as well as Sections~\ref{sec:installing-and-running} and \ref{sec:usage}, below.
%
% \LaTeX\ can do a lot,\footnote{\TeX\ is a Turing-complete language.} but the programming required can sometimes be painful.\footnote{As I learned in creating this package.} Also, in spite of the many packages available for \LaTeX, the libraries and packages of a general-purpose programming language are lacking. For these reasons, there have been multiple attempts to allow other languages to be used within \LaTeX.\footnote{I am not including the various web and weave dialects in my discussion, since they typically involve a web or weave document from which the .tex source is generated, and thus offer less strong integration with \LaTeX. Two sophisticated examples of this approach are \href{http://www.stat.uni-muenchen.de/~leisch/Sweave/}{Sweave} and \href{http://yihui.name/knitr/}{knitr}, both of which combine \LaTeX\ with the R language for tasks such as dynamic report generation.}
% \begin{itemize}
% \item \href{http://www.ctan.org/tex-archive/macros/latex/contrib/perltex/}{Perl\TeX} allows the bodies of \LaTeX\ macros to be written in Perl.
% \item \href{http://www.ctan.org/tex-archive/macros/latex/contrib/sagetex/}{Sage\TeX} allows code for the Sage mathematics software to be executed from within a \LaTeX\ document.
% \item Martin R.\ Ehmsen's \href{http://www.ctan.org/pkg/python}{|python.sty|} provides a very basic method of executing Python code from within a \LaTeX\ document.
% \item \href{http://elec.otago.ac.nz/w/index.php/SympyTeX}{Sympy\TeX} allows more sophisticated Python execution, and is largely based on a subset of Sage\TeX.
% \item \href{http://www.luatex.org/}{Lua\TeX} extends the pdf\TeX\ engine to provide Lua as an embedded scripting language, and as a result yields tight, low-level Lua integration.
% \end{itemize}
%
% \pytex\ attempts to fill a perceived gap in the current integrations of \LaTeX\ with an additional language. It has a number of objectives, only some of which have been met by previous packages.
% \begin{description}
% \item[Execution speed]\hfill\\ In the approaches mentioned above, all the non-\LaTeX\ code is executed at every compilation of the \LaTeX\ document (Perl\TeX, Lua\TeX, and |python.sty|), or all the non-\LaTeX\ code is executed every time it is modified (Sage\TeX\ and Sympy\TeX). However, many tasks such as plotting and data analysis take significant time to execute. We need a way to fine-tune code execution, so that independent blocks of slow code may be separated into their own sessions and are only executed when modified. If we are going to split code into multiple sessions, we might as well run these sessions in parallel, further increasing speed. A byproduct of this approach is that it now becomes much more feasible to include slower code, since we can still have fast compilations whenever the slow code isn't modified.
% \item[Compiling without executing]\hfill\\ Even with all of these features to boost execution speed, there will be times when we have to run slow code. Thus, we need the execution of non-\LaTeX\ code to be separated from compiling the \LaTeX\ document. We need to be able to edit and compile a document containing unexecuted code. Unexecuted code should be invisible or be replaced by placeholders. Sage\TeX\ and Sympy\TeX\ have implemented such a separation of compiling and executing. In contrast, Lua\TeX\ and Perl\TeX\ execute all the code at each compilation---but that is appropriate given their goal of simplifying macro programming.
% \item[Error messages]\hfill\\ Whenever code is saved from a \LaTeX\ document to an external file and then executed, the line numbers for any error messages will not correspond to the line numbering of the original \LaTeX\ document. At one extreme, |python.sty| doesn't attempt to deal with this issue, while at the other extreme, Sage\TeX\ uses an ingenous system of |Try|/|Except| statements on every chunk of code. We need a system that translates all error messages so that they correspond to the line numbering of the original \LaTeX\ document, with minimal overhead when there are no errors.
% \item[Syntax highlighting]\hfill\\ Once we begin using non-\LaTeX\ code, sooner or later we will want to typeset some of it, which means we need syntax highlighting. A number of syntax highlighting packages currently exist for \LaTeX; perhaps the most popular are |listings| and |minted|. |listings| uses pure \LaTeX. It has not been updated since 2007, which makes it a less ideal solution in some circumstances. |minted| uses the Python-based syntax highlighter Pygments to perform highlighting. Pygments can provide superior syntax highlighting, but |minted| can be very slow because all code must be highlighted at each compilation and each instance of highlighting involves launching an external Python process. We need high-speed, user-friendly syntax highlighting via Pygments.\footnote{The author recently started maintaining the \texttt{minted} package. In the near future, \texttt{minted} will inherit \pytex's speed enhancements, and the two packages will become largely compatible so far as highlighting is concerned.}
% \item[Printing]\hfill\\ It would be nice for the |print| statement/function,\footnote{In Python, |print| was a statement until Python 3, when it became a function. The function form is available via import from |\textunderscore\textunderscore future\textunderscore\textunderscore| in Python 2.6 and later.} or its equivalent, to automatically return its output within the \LaTeX\ document. For example, using |python.sty| it is possible to generate some text while in Python, open a file, save the text to it, close the file, and then |\input| the file after returning to \LaTeX. But it is much simpler to generate the text and |print| it, since the printed content is automatically included in the \LaTeX\ document. This was one of the things that |python.sty| really got right.
% \item[Pure code]\hfill\\ \LaTeX\ has a number of special characters (|#| \texttt{\$} |%| |&| |~| |_| |^| |\| |{| |}|), which complicates the entry of code in a non-\LaTeX\ language since these same characters are common in many languages. Sage\TeX\ and Sympy\TeX\ delimit all inline code with curly braces (|{}|), but this approach fails in the (somewhat unlikely) event that code needs to contain an unmatched brace. More seriously, they do not allow the percent symbol |%| (modular arithmetic and string formatting in Sage and Python) to be used within inline code. Rather, a |\percent| macro must be used instead. This means that code must (sometimes) be entered as a hybrid between \LaTeX\ and the non-\LaTeX\ language. Lua\TeX\ is somewhat similar: ``The main thing about Lua code in a TeX document is this: the code is expanded by TeX before Lua gets to it. This means that all the Lua code, even the comments, must be valid TeX!''\footnote{\url{http://wiki.contextgarden.net/Programming_in_LuaTeX}} In the case of Lua\TeX, though, there is the \href{http://www.ctan.org/pkg/luacode}{\texttt{luacode}} package that allows for pure Lua.
%
% This language hybridization is not terribly difficult to work around in the Sage\TeX\ and Sympy\TeX\ cases, and is actually a Lua\TeX\ feature in many contexts. But if we are going to create a system for general-purpose access to a non-\LaTeX\ language, we need \textbf{all} valid code to work correctly in \textbf{all} contexts, with no hybridization of any sort required. We should be able to copy and paste valid code into a \LaTeX\ document, without having to worry about hybridizing it. Among other things, this means that inline code delimiters other than \LaTeX's default curly braces |{}| must be available.
% \item[Hybrid code]\hfill\\ Although we need a system that allows input of pure non-\LaTeX\ code, it would also be convenient to allow hybrid code, or code in which \LaTeX\ macros may be present and are expanded before the code is executed. This allows \LaTeX\ data to be easily passed to the non-\LaTeX\ language, facilitating a tighter integration of the two languages and the use of the non-\LaTeX\ language in macro definitions.
% \item[Math and science libraries]\hfill\\ The author decided to create \pytex\ after writing a physics dissertation using \LaTeX\ and realizing how frustrating it can be to switch back and forth between a \TeX\ editor and plotting software when fine-tuning figures. We need access to a non-\LaTeX\ language like Python, MATLAB, or Mathematica that provides strong support for data analysis and visualization. To maintain broad appeal, this language should primarily involve open-source tools, should have strong cross-platform support, and should also be suitable for general-purpose programming.
% \item[Language-independent implementation]\hfill\\ It would be nice to have a system for executing non-\LaTeX\ code that depends very little on the language of the code. We should not expect to be able to escape all language dependence. But if the system is designed to be as general as possible, then it may be expanded in the future to support additional languages.
% \end{description}
%
% Python was chosen as the language to fulfill these objectives for several reasons.
% \begin{itemize}
% \item It is open-source and has good cross-platform support.
% \item It has a strong set of scientific, numeric, and visualization packages, including \href{http://numpy.scipy.org/}{NumPy}, \href{http://www.scipy.org/}{SciPy}, \href{http://matplotlib.sourceforge.net/}{matplotlib}, and \href{http://sympy.org}{SymPy}. Much of the initial motivation for \pytex\ was the ability to create publication-quality plots and perform complex mathematical calculations without having to leave the \TeX\ editor.
% \item We need a language that is suitable for scripting. Lua is already available via Lua\TeX, and in any case lacks the math and science tools.\footnote{One could use \href{http://labix.org/lunatic-python}{Lunatic Python}, and some numeric packages for Lua are \href{http://numlua.luaforge.net/}{in development}.} Perl is already available via Perl\TeX, although Perl\TeX's emphasis on Perl for macro creation makes it rather unsuitable for scientific work using the \href{http://pdl.perl.org/}{Perl Data Language (PDL)} or for more general programming. Python is one logical choice for scripting.
% \end{itemize}
%
% Now at this point there will almost certainly be some reader, sooner or later, who wants to object, ``But what about language \textit{X}!'' Well, yes, in some respects the choice to use Python did come down to personal preference. But you should give Python a try, if you haven't already. You may also wish to consider the many interfaces that are available between Python and other languages. If you still aren't satisfied, keep in mind \pytex's ``language-independent'' implementation! Although \pytex\ is written to support Python within \LaTeX, the implementation has been specially crafted so that other languages may be supported in the near future.
%
%
%
% \section{Installing and running}
% \label{sec:installing-and-running}
%
% \subsection{Installing \pytex}
%
% \pytex\ requires a \TeX\ installation. \href{http://www.tug.org/texlive/}{\TeX\ Live} or \href{http://miktex.org/}{MiK\TeX} are preferred. \pytex\ requires the |Kpathsea| library, which is available in both of these distributions. The following \LaTeX\ packages, with their dependencies, are also required: |fancyvrb|, |etex|, |etoolbox|, |xstring|, |pgfopts|, |newfloat|, and |color| or |xcolor|. If you are creating and importing graphics using Python, you will also need |graphicx|. The \href{http://www.ctan.org/pkg/mdframed}{\texttt{mdframed}} package is recommended for enclosing typeset code in boxes with fancy borders and/or background colors; \href{http://www.ctan.org/pkg/tcolorbox}{\texttt{tcolorbox}} and \href{http://www.ctan.org/pkg/framed}{\texttt{framed}} are other alternatives.
%
% \pytex\ also requires a \href{http://www.python.org/}{Python} installation. Python 2.7 is recommended for the greatest compatibility with scientific tools, although many scientific packages are now compatible with Python 3. Python 3.2 and later will work as well. Earlier versions of Python 2 and 3 are not compatible, at least not without several modifications to the \pytex\ scripts. The Python package \href{http://pygments.org/}{Pygments} must be installed for syntax highlighting to function. \pytex\ has been tested with Pygments 1.4 and later, but the latest version is recommended. For scientific work, or to compile the |pythontex_gallery| file, the following are also recommended: \href{http://numpy.scipy.org/}{NumPy}, \href{http://www.scipy.org/}{SciPy}, \href{http://matplotlib.sourceforge.net/}{matplotlib}, and \href{http://sympy.org}{SymPy}.
%
% \pytex\ consists of the following files:
% \begin{itemize}
% \item Installer file |pythontex.ins|
% \item Documented \LaTeX\ source file |pythontex.dtx|, from which |pythontex.pdf| and |pythontex.sty| are generated
% \item Main script |pythontex.py|, which imports from |pythontex2.py| or |pythontex3.py|, based on the Python version
% \item Language definitions |pythontex_types2.py| and |pythontex_types3.py|
% \item Utilities class |pythontex_utils.py|
% \item |depythontex.py|, which imports from |depythontex2.py| or |depythontex3.py|, based on the Python version; used to remove \pytex\ dependence
% \item |README| (in rst style)
% \item |pythontex_gallery.tex| and |pythontex_gallery.pdf|
% \item |pythontex_quickstart.tex| and |pythontex_quickstart.pdf|
% \item Optional installation script |pythontex_install_texlive.py| for \TeX\ Live
% \item Optional batch file |pythontex.bat| for use in launching |pythontex.py| under Windows
% \item Optional conversion script |pythontex_2to3.py| for converting \pytex\ code written for Python 2 into a form compatible with Python 3
% \end{itemize}
% The style file |pythontex.sty| may be generated by running \LaTeX\ on |pythontex.ins|. The documentation you are reading may be generated by running \LaTeX\ on |pythontex.dtx|. Some code is provided in two forms, one for Python 2 and one for Python 3 (names ending in |2| and |3|). Whenever this is the case, a version-independent wrapper is supplied that automatically runs the correct code based on the Python version. For example, there are two main scripts, |pythontex2.py| and |pythontex3.py|, but you should actually run |pythontex.py|, which imports the correct code based on the Python version.\footnote{Unfortunately, it is not possible to provide full Unicode support for both Python 2 and 3 using a single script. Currently, all code is written for Python 2, and then the Python 3 version is automatically generated via the |pythontex\_2to3.py| script. This script comments out code that is only for Python 2, and un-comments code that is only for Python 3.}
%
% If you want the absolute latest version of \pytex, you should install it manually from \href{https://github.com/gpoore/pythontex}{github.com/gpoore/pythontex}. A Python installation script is provided for use with \TeX\ Live. It has been tested with Windows, Linux, and OS~X, but may need manual input or slight modifications depending on your system. The installation script performs the steps described below. Note that you may have to run the script with elevated privileges, and may need to run it using the user's PATH. For example, under Ubuntu Linux, you may need the following:
% \begin{verbatim}
% sudo env PATH=$PATH python pythontex_install_texlive.py
% \end{verbatim}
%
% The \pytex\ files should be installed within the \TeX\ directory structure as follows.
% \begin{itemize}
% \item \meta{\TeX\ tree root}|/doc/latex/pythontex/|
% \begin{itemize}
% \item |pythontex.pdf|
% \item |README|
% \item |pythontex_quickstart.tex|
% \item |pythontex_quickstart.pdf|
% \item |pythontex_gallery.tex|
% \item |pythontex_gallery.pdf|
% \end{itemize}
% \item \meta{\TeX\ tree root}|/scripts/pythontex/|
% \begin{itemize}
% \item |pythontex.py|, |pythontex2.py| and |pythontex3.py|
% \item |pythontex_types2.py| and |pythontex_types3.py|
% \item |pythontex_utils.py|
% \item |depythontex.py|, |depythontex2.py| and |depythontex3.py|
% \end{itemize}
% \item \meta{\TeX\ tree root}|/source/latex/pythontex/|
% \begin{itemize}
% \item |pythontex.dtx|
% \item |pythontex.ins|
% \end{itemize}
% \item \meta{\TeX\ tree root}|/tex/latex/pythontex/|
% \begin{itemize}
% \item |pythontex.sty|
% \end{itemize}
% \end{itemize}
% After the files are installed, the system must be made aware of their existence. Run |mktexlsr| to do this. In order for |pythontex.py| and |depythontex.py| to be executable, a symlink (\TeX\ Live under Linux), launching wrapper (\TeX\ Live under Windows), or batch file (general Windows) should be created in the |bin/|\meta{system} directory. For \TeX\ Live under Windows, simply copy |bin/win32/runscript.exe| to |bin/win32/pythontex.exe| to create the wrapper.\footnote{See the output of |runscript -h| under Windows for additional details.}
%
%
% \subsection{Compiling documents using \pytex}
%
% Compiling a document with \pytex\ involves three steps: running a \LaTeX-compatible \TeX\ engine, running |pythontex.py| (preferably via a symlink, wrapper, or batch file, as described above), and finally running the \TeX\ engine again. The first \TeX\ run saves code into an external file where \pytex\ can access it. The second \TeX\ run pulls the \pytex\ output back into the document.
%
% If you plan to use code that contains non-ASCII characters such as Unicode, you should make sure that your document is properly configured:
% \begin{itemize}
% \item Under pdfLaTeX, your documents need |\usepackage[T1]{fontenc}| and |\usepackage[utf8]{inputenc}|, or a similar configuration.
% \item Under LuaLaTeX, your documents need |\usepackage{fontspec}|, or a similar configuration.
% \item Under XeLaTeX, your documents need |\usepackage{fontspec}| as well as |\defaultfontfeatures{Ligatures=TeX}|, or a similar configuration.
% \end{itemize}
% For an example of a \pytex\ document that will correctly compile under all three engines, see the |pythontex_gallery.tex| source.
%
% If you use XeLaTeX, and your source code contains tabs, you \textbf{must} invoke XeLaTeX with the |-8bit| option so that tabs will be written to file as actual tab characters rather than as the character sequence |^^I|.\footnote{See \url{http://tex.stackexchange.com/questions/58732/how-to-output-a-tabulation-into-a-file} for more on tabs with XeTeX.}
%
% |pythontex.py| requires a single command-line argument: the name of the .tex file to process. The filename can be passed with or without an extension; the script really only needs the |\jobname|, so any extension is stripped off.\footnote{Thus, \pytex\ works happily with .tex, .ltx, .dtx, and any other extension.} The filename may include the path to the file; you do not have to be in the same directory as the file to run \pytex. If you are configuring your editor to run \pytex\ automatically via a shortcut, you may want to wrap the filename in double quotes |"| to allow for space characters.\footnote{Using spaces in the names of .tex files is apparently frowned upon. But if you configure things to handle spaces whenever it doesn't take much extra work, then that's one less thing that can go wrong.} For example, under Windows with \TeX\ Live and Python 2.7 we would create the wrapper |pythontex.exe|. Then we could run \pytex\ on a file \meta{file~name}.tex using the command |pythontex.exe "|\meta{file~name}|"|.
%
% |pythontex.py| accepts the following optional command-line arguments. Some of these options duplicate package-level options, so that settings may be configured either within the document or at the command line. In the event that the command-line and package options conflict, the package options always override the command-line options. For variations on these options that are acceptable, run |pythontex.py -h|.
% \begin{itemize}
% \item |--encoding=|\meta{encoding} This sets the file encoding. Any encoding supported by Python's \href{http://docs.python.org/library/codecs.html}{\texttt{codecs}} module may be used. If an encoding is not specified, \pytex\ uses UTF-8. Note that the encoding \textbf{must} be used consistently; the .tex source, the \pytex\ output, and any external code files that \pytex\ highlights should all use the same encoding. If support for characters beyond ASCII is required, then additional \LaTeX\ packages are required; see the discussion of \TeX\ engines above.
% \item |--error-exit-code={true,false}| By default, |pythontex.py| returns an exit code of 1 if there were any errors, and an exit code of 0 otherwise. This may be useful when \pytex\ is used in a scripting or command-line context, since the presence of errors may be easily detected. It is also useful with some \TeX\ editors. For example, \href{http://www.tug.org/texworks/}{TeXworks} automatically hides the output of external programs unless there are errors.
%
% But in some contexts, returning a nonzero exit code can be redundant. For example, with the \href{http://winshell.de/}{WinShell} editor under Windows with TeX Live, the complete output of \pytex\ is always available in the ``Output'' view, so it is clear if errors have occurred. Having a nonzero exit code causes |runscript.exe| to return an additional, redundant error message in the ``Output'' view. In such situations, it may be desirable to disable the nonzero exit code.
% \item |--runall=[{true,false}]| This causes \textbf{all} code to be executed, regardless of modification or |rerun| settings. It is useful when code has not been modified, but a dependency such as a library or external data has changed. Note that the \pytex\ utilities class also provides a mechanism for automatically re-executing code that depends on external files when those external files are modified.
%
% There is an equivalent |runall| package option. The command-line option |--rerun=always| is essentially equivalent.
% \item |--rerun={modified,errors,warnings,always}| This sets the threshold for re-executing code. By default, \pytex\ will rerun code that has been modified or that produced errors on the last run. Sometimes, we may wish to have a more lenient setting (only rerun if modified) or a more stringent setting (rerun even for warnings, or just rerun everything). |modified| only executes code that has been modified (or that has modified dependencies). |errors| executes all modified code as well as all code that produced errors on the last run; this is the default. |warnings| executes all modified code, as well as all code that produced errors or warnings. |always| executes all code always and is essentially equivalent to |--runall|.
%
% There is an equivalent |rerun| package option.
% \item |--hashdependencies=[{true,false}]| This determines whether dependencies (external files highlighted by Pygments, code dependencies specified via |pytex.add_dependencies()|, etc.) are considered to be modified based on their hash or modification time. By default, mtime is used, since it is faster. The package option |hashdependencies| is equivalent.
%
% \item |--verbose| This gives more verbose output, including a list of all processes that are launched.
% \end{itemize}
%
% \pytex\ currently does not provide means to choose between multiple Python installations; it will use the default Python installation. Support for multiple installations is unlikely to be added, since a cross-platform solution would be required.\footnote{Python 3.3's \texttt{py} launcher for Windows may make this more feasible.} If you need to work with multiple installations, you may wish to modify |pythontex_types*.py| to create additional command and environment families that invoke different versions of Python, based on your system.
%
% \pytex\ attempts to check for a wide range of errors and return meaningful error messages. But due to the interaction of \LaTeX\ and Python code, some strange errors are possible. If you cannot make sense of errors when using \pytex, the simplest thing to try is deleting all files created by \pytex, then recompiling. By default, these files are stored in a directory called |pythontex-files-|\meta{jobname}, in the same directory as your .tex document. See Section \ref{sec:troubleshooting} for more details regarding troubleshooting.
%
%
% \section{Usage}
% \label{sec:usage}
%
% \subsection{Package options}
% Package options may be set in the standard manner when the package is loaded:
% \begin{quote}
% |\usepackage|\oarg{options}|{pythontex}|
% \end{quote}
%
% All options are described as follows. The option is listed, followed by its possible values. When a value is not required, \meta{none} is listed as a possible value. In this case, the value to which \meta{none} defaults is also given. Each option lists its default setting, if the option is not invoked when the package is loaded.
%
% Some options have a command-line equivalent. Package options override command-line options.
%
% All options related to printed content are provided in two forms for convenience: one based on the word |print| and one based on |stdout|.
%
%
% \DescribeMacro{beta=\meta{none}/true/false default:false \meta{none}=true}
%
% This option provides compatibility with the beta releases from before the full v0.11 release, which introduced some changes in syntax and command names. This option should \textbf{only} be used with old \pytex\ documents that require it.
%
% You are encouraged to update old documents, since this compatility option will only be provided for a few releases.
%
%
% \DescribeMacro{runall=\meta{none}/true/false default:false \meta{none}=true}
%
% This option causes all code to be executed, regardless of whether it has been modified. This option is primarily useful when code depends on external files, and needs to be re-executed when those external files are modified, even though the code itself may not have changed. Note that the \pytex\ utilities class also provides a mechanism for automatically re-executing code that depends on external files when those external files are modified.
%
% A command-line equivalent |--runall| exists for |pythontex.py|. The package option |rerun=always| is essentially equivelent.
%
%
% \DescribeMacro{rerun=modified/errors/warnings/always default:errors}
%
% This option sets the threshold for re-executing code. By default, \pytex\ will rerun code that has been modified or that produced errors on the last run. Sometimes, we may wish to have a more lenient setting (only rerun if modified) or a more stringent setting (rerun even for warnings, or always rerun). |modified| only executes code that has been modified. |errors| executes all modified code as well as all code that produced errors on the last run; this is the default. |warnings| executes all modified code, as well as all code that produced errors or warnings. |always| executes all code regardless of its condition.
%
% A command-line equivalent |--rerun| exists for |pythontex.py|.
%
%
% \DescribeMacro{hashdependencies=\meta{none}/true/false default:false \meta{none}=true}
%
% When external code files are highlighted with Pygments, or external dependencies are specified via the \pytex\ utilities class, they are checked for modification via their modification time (Python's |os.path.getmtime()|). Usually, this should be sufficient---and it offers superior performance, which is important if data sets are large enough that hashing takes a noticeable amount of time. However, occasionally hashing may be necessary or desirable, so this option is provided.
%
% A command-line equivalent |--hashdependencies| exists for |pythontex.py|.
%
%
% \DescribeMacro{autoprint=\meta{none}/true/false default:true \meta{none}=true}
%
% \DescribeMacro{autostdout=\meta{none}/true/false default:true \meta{none}=true}
%
% Whenever a |print| command/statement is used, the printed content will automatically be included in the document, unless the code doing the printing is being typeset.\footnote{Note that |autoprint| only works within the body of the document. The |code| command and environment can be used in the preamble, but |autoprint| is disabled there. It is usually a not a good idea to print in the preamble, because nothing can be typeset; the only thing that could be validly printed is \LaTeX\ commands that do not typeset content, such as macro definitions. Thus, it is appropriate that printed content is only brought in while in the preamble if it is explicitly requested via |\string\printpythontex|. This approach is also helpful for writing packages using \pytex, since the author does not have to worry about any \LaTeX\ commands printed by the package either not being included (if |autoprint| is relied upon, but the user turns it off) or being included twice (if |\string\printpythontex| is used and |autoprint| is enabled). Printing should only be used in the preamble with great care.} In that case, the printed content must be included using the |\printpythontex| or |\stdoutpythontex| commands.
%
% Printed content is pulled in directly from the external file in which it is saved, and is interpreted by \LaTeX\ as \LaTeX\ code. If you wish to avoid this, you should print appropriate \LaTeX\ commands with your content to ensure that it is typeset as you desire. Alternatively, you may use |\printpythontex| or |\stdoutpythontex| to bring in printed content in verbatim form, using those commands' optional |verb| and |verbatim| options.
%
% The |autoprint| (|autostdout|) option sets autoprint behavior for the entire document. This may be overridden within the document using the |\setpythontexautoprint| command.
%
% \DescribeMacro{debug}
%
% This option aids in debugging invalid \LaTeX\ code that is brought in from Python. It disables the inclusion of printed content/content written to stdout. Since printed content should almost \textbf{always} be included, a warning is raised when this option is used. Not including printed content is useful when the printed content contains \LaTeX\ errors, and would cause document compilation to fail. When the document fails to compile, this can prevent modified Python code from being written to the code file, resulting in an inescapable loop unless printed content is disabled or the saved output is deleted.
%
% Note that since commands like |\py| involve printing, they are also disabled.
%
%
% \DescribeMacro{makestderr=\meta{none}/true/false default:false \meta{none}=true}
%
% This option determines whether the stderr produced by scripts is available for input by \pytex, via the |\stderrpythontex| macro. This will not be needed in most situations. It is intended for typeseting incorrect code next to the errors that it produces. This option is not |true| by default, because additional processing is required to synchronize stderr with the document.
%
% \DescribeMacro{stderrfilename=full/session/genericfile/genericscript default:full}
%
% This option governs the file name that appears in |stderr|. Python errors begin with a line of the form
% \begin{quote}
% | File "<file or source>", line <line>|
% \end{quote}
% By default (option |full|), |<file or source>| is the actual name of the script that was executed. The name will be in the form \meta{family~name}|_|\meta{session}|_|\meta{group}|.|\meta{extension}. For example, an error produced by a |py| command or environment, in the session |mysession|, using the default group (that is, the default |\restartpythontexsession| treatment), would be reported in |py_mysession_default.py|. The |session| option replaces the full file name with the name of the session, |mysession.py| in this example. The |genericfile| and |genericscript| options replace the file name with |<file>| and |<script>|, respectively.
%
% \DescribeMacro{pyfuture=none/all/default default:default}
%
% Under Python 2, this determines what is automatically imported from |__future__| for all code. |none| imports nothing from |__future__|; |all| imports everything available in Python 2.7 (|absolute_import|, |division|, |print_function|, and |unicode_literals|); and |default| imports everything except |unicode_literals|, since |unicode_literals| can conflict with some packages. Note that imports from |__future__| are also allowed within sessions, so long as they are at the very beginning of the session, as they would have to be in a normal script.
%
% This option has no effect under Python 3.
%
% \DescribeMacro{upquote=\meta{none}/true/false default:true \meta{none}=true}
%
% This option determines whether the |upquote| package is loaded. In general, the |upquote| package should be loaded, because it ensures that quotes within verbatim contexts are ``upquotes,'' that is, \expandafter|\textquotesingle| rather than |'|.
%
% Using |upquote| is important beyond mere presentation. It allows code to be copied directly from the compiled PDF and executed without any errors due to quotes |'| being copied as acute accents \texttt{\'}.
%
% \DescribeMacro{fixlr=\meta{none}/true/false default:false \meta{none}=true}
%
% This option removes ``extra'' spacing around |\left| and |\right| in math mode. This spacing is sometimes undesirable, especially when typesetting functions such as the trig functions. See the implementation for details. Similar functionality is provided by the \href{http://www.ctan.org/pkg/mleftright}{\texttt{mleftright}} package
%
% \DescribeMacro{keeptemps=\meta{none}/all/code/none default:none \meta{none}=all}
%
% When \pytex\ runs, it creates a number of temporary files. By default, none of these are kept. The |none| option keeps no temp files, the |code| option keeps only code temp files (these can be useful for debugging), and the |all| option keeps all temp files (code, stdout and stderr for each code file, etc.). Note that this option does not apply to any user-generated content, since \pytex\ knows very little about that; it only applies to files that \pytex\ automatically creates by itself.
%
% \DescribeMacro{prettyprinter=pygments/fancyvrb default:pygments}
%
% This allows the user to determine at the document level whether code is typeset using Pygments or |fancyvrb|.
%
% The package-level option can be overridden for individual command and environment families, using the |\setpythontexprettyprinter| command. Overriding is never automatic and should generally be avoided, since using Pygments to highlight only some content results in an inconsistent style. Keep in mind that Pygment's |text| lexer and/or |bw| style can be used when content needs little or no syntax highlighting.
%
%
% \DescribeMacro{prettyprintinline=\meta{none}/true/false default:true \meta{none}=true}
%
% This determines whether inline content is pretty printed. If it is turned off, inline content is typeset with |fancyvrb|.
%
%
% \DescribeMacro{pygments=\meta{none}/true/false default:true \meta{none}=true}
%
% This allows the user to determine at the document level whether code is typeset using Pygments rather than |fancyvrb|. It is an alias for |prettyprinter=pygments|.
%
%
% \DescribeMacro{pyginline=\meta{none}/true/false default:true \meta{none}=true}
%
% This option governs whether inline code, not just code in environments, is highlighted when Pygments highlighting is in use. When Pygments is in use, it will highlight everything by default.
%
% It is an alias for |prettyprintinline|.
%
%
% \DescribeMacro{pyglexer=\meta{pygments~lexer} default:\meta{none}}
%
% This allows a Pygments lexer to be set at the document level. In general, this option should \textbf{not} be used. It overrides the default lexer for all commands and environments, for both \pytex\ and Pygments content, and this is usually not desirable. It should be useful primarily when all content uses the same lexer, and multiple lexers are compatible with the content.
%
%
% \DescribeMacro{pygopt=\marg{pygments~options} default:\meta{none}}
%
% This allows Pygments options to be set at the document level. The options must be enclosed in curly braces |{}|. Currently, three options may be passed in this manner: |style=|\meta{style~name}, which sets the formatting style; |texcomments|, which allows \LaTeX\ in code comments to be rendered; and |mathescape|, which allows \LaTeX\ math mode (|$...$|) in comments. The |texcomments| and |mathescape| options may be used with an argument (for example, |texcomments=True/False|); if an argument is not supplied, |True| is assumed. Example: |pygopt={style=colorful, texcomments=True, mathescape=False}|.
%
% Pygments options for individual command and environment families may be set with the |\setpythontexpygopt| macro; for Pygments content, there is |\setpygmentspygopt|. These individual settings are always overridden by the package option.
%
%
% \DescribeMacro{fvextfile=\meta{none}/\meta{integer} default:$\infty$ \meta{none}=25}
%
% This option speeds the typesetting of long blocks of code that are created on the Python side. This includes content highlighted using Pygments and the |console| environment. Typesetting speed is increased at the expense of creating additional external files (in the \pytex\ directory). The \meta{integer} determines the number of lines of code at which the system starts using multiple external files, rather than a single external file. See the implementation for the technical details; basically, an external file is used rather than |fancyvrb|'s |SaveVerbatim|, which becomes increasingly inefficient as the length of the saved verbatim content grows. In most situations, this option should not be needed, or should be fine with the default value or similar ``small'' integers.
%
%
% \DescribeMacro{pyconbanner=none/standard/default/pyversion default:none}
%
% This option governs the appearance (or disappearance) of a banner at the beginning of Python console environments. (A banner only appears in the first environment within each session.) The options |none| (no banner), |standard| (standard Python banner), |default| (default banner for Python's |code| module, standard banner plus interactive console class name), and |pyversion| (banner in the form |Python x.y.z|) are accepted.
%
%
% \DescribeMacro{pyconfilename=stdin/console default:stdin}
%
% This governs the form of the filename that appears in error messages in Python console environments. Python errors messages have a form such as the following:
% \begin{verbatim}
% >>> z = 1 + 34 +
% File "<name>", line 1
% z = 1 + 34 +
% ^
% SyntaxError: invalid syntax
% \end{verbatim}
% The |stdin| option replaces |<name>| with |<stdin>|, as it appears in a standard Python interactive session. The |console| option uses |<console>| instead, which is the default setting for the Python |code| module used by \pytex\ to create Python console environments.
%
% \DescribeMacro{depythontex=\meta{none}/true/false default:false \meta{none}=true}
%
% This option is used to create a version of the \LaTeX\ document that does not require the \pytex\ package. When invoked, it creates an auxiliary file called |<filename>.depytx|. The script |depythontex.py| uses the original document and this auxiliary file to create a new document in which all \pytex\ commands and environments have been replaced by typeset code and code output. For additional information on |depythontex|, see Section~\ref{sec:depythontex}.
%
%
% \subsection{Commands and environments}
%
% \pytex\ provides four types of commands for use with inline code and three environments for use with multiple lines of code, plus a |console| environment. All commands and environments are named using a base name and a command- or environment-specific suffix. A complete set of commands and environments with the same base name constitutes a \textbf{command and environment family}. In what follows, the different commands and environments are described using the |py| base name (the |py| family) as an example.
%
% Most commands and environments cannot be used in the preamble, because they typeset material and that is not possible in the preamble. The one exception is the |code| command and environment. These can be used to enter code, but need not typeset anything. This allows you to collect your \pytex\ code in the preamble, if you wish, or even use \pytex\ in package writing. Note that the package option |autoprint| is never active in the preamble, so even if a |code| command or environment did print in the preamble, printed content would never be inputted unless |\printpythontex| or |\stdoutpythontex| were used.
%
% All commands and environments take a session name as an optional argument. The session name determines the session in which the code is executed. This allows code to be executed in multiple independent sessions, increasing speed (sessions run in parallel) and preventing naming conflicts. If a session is not specified, then the |default| session is used. Session names should use the characters a-z, A-Z, 0-9, the hyphen, and the underscore; all characters used \textbf{must} be valid in file names, since session names are used to create temporary files. The colon is also allowed, but it is replaced with a hyphen internally, so the sessions |code:1| and |code-1| are identical.
%
% In addition, all environments take |fancyvrb| settings as a second, optional argument. See the \href{http://www.ctan.org/tex-archive/macros/latex/contrib/fancyvrb}{|fancyvrb| documentation} for an explanation of accepted settings. This second optional argument \textbf{must} be preceeded by the first optional argument (session name). If a named session is not desired, the optional argument can be left empty (|default| session), but the square brackets |[]| must be present so that the second optional argument may be correctly identified:
% \begin{quote}
% |\begin{|\meta{environment}|}[]|\oarg{fancyvrb~settings}
% \end{quote}
%
%
% \subsubsection{Inline commands}
% \pytxtodo{Fix spacing around |\DescribeMacro|!}
% Inline commands are suitable for single lines of code that need to be executed within the body of a paragraph or within a larger body of text. The commands use arbitrary code delimiters (like |\verb| does), which allows the code to contain arbitrary characters. Note that this is only guaranteed to work properly when the inline commands are \textbf{not} inside other macros. If an inline command is used within another macro, the code will be read by the external macro before \pytex\ can read the special code characters (that is, \LaTeX\ will tokenize the code). The inline commands can work properly within other macros, but you should stick with curly braces for delimiters in this case and you may have trouble with the hash |#| and percent |%| characters.
%
% \DescribeMacro{\py\oarg{session}\meta{opening~delim}\meta{code}\meta{closing~delim}}
%
% This command is used for including variable values or other content that can be converted to a string. It is an alternative to including content via the |print| statement/function within other commands/environments.
%
% The |\py| command sends \meta{code} to Python, and Python returns a string representation of \meta{code}.\pytxtodo{Link to details about Python built-ins} \meta{opening~delim} and \meta{closing~delim} must be either a pair of identical, non-space characters, or a pair of curly braces. If curly braces are used as delimiters, then curly braces may only be used within \meta{code} if they are paired. Thus, |\py{1+1}| sends the code |1+1| to Python, Python evaluates the string representation of this code, and the result is returned to \LaTeX\ and included as |2|. The commands |\py#1+1#| and |\py@1+1@| would have the same effect. The command can also be used to access variable values. For example, if the code |a=1| had been executed previously, then |\py{a}| simply brings the string represantation of |a| back into the document as |1|.
%
% Assignment is \textbf{not} allowed using |\py|. For example, |\py{a=1}| is \textbf{not} valid. This is because assignment cannot be converted to a string.\footnote{It would be simple to allow any code within |\textbackslash py|, including assignment, by using a |try/except| statement. In this way, the functionality of |\textbackslash py| and |\textbackslash pyc| could be merged. While that would be simpler to use, it also has serious drawbacks. If |\textbackslash py| is not exclusively used to typeset string representations of \meta{code}, then it is no longer possible on the \LaTeX\ side to determine whether a command should return a string. Thus, it is harder to determine, from within a \TeX\ editor, whether |pythontex.py| needs to be run; warnings for missing Python content could not be issued, because the system wouldn't know (on the \LaTeX\ side) whether content was indeed missing.}
%
% The text returned by Python must be valid \LaTeX\ code. Verbatim and other special content is allowed under the pdfTeX and XeTeX engines (a known bug prevents it from working with LuaTeX). The primary reasons for using |\py| rather than |print| are (1) |\py| is more compact and (2) |print| requires an external file to be created for every command or environment in which it is used, while |\py| and equivalents for other families share a single external file. Thus, use of |\py| minimizes the creation of external files, which is a key design goal for \pytex.\footnote{For |\textbackslash py|, the text returned by Python is stored in macros and thus must be valid \LaTeX\ code, because \LaTeX\ interprets the returned content. The use of macros for storing returned content means that an external file need not be created for each use of |\textbackslash py|. Rather, all macros created by |\textbackslash py| and equivalent commands from other families are stored in a single file that is inputted. Note that even though the content is stored in macros, verbatim content is allowed, through the use of special macro definitions combined with \texttt{\string\scantokens}.} The main reason for using |print| rather than |\py| is if you need to include a very large amount of material; |print|'s use of external files won't use up \TeX's memory, and may give noticeably better performance once the material is sufficiently long.
%
% \DescribeMacro{\pyc\oarg{session}\meta{opening~delim}\meta{code}\meta{closing~delim}}
%
% This command is used for executing but not typesetting \meta{code}. The suffix |c| is an abbreviation of |code|. If the |print| statement/function is used within \meta{code}, printed content will be included automatically so long as the package |autoprint| option is set to true (the default setting).
%
% \DescribeMacro{\pyv\oarg{session}\meta{opening~delim}\meta{code}\meta{closing~delim}}
%
% This command is used for typesetting but not executing \meta{code}. The suffix |v| is an abbreviation for |verb|.
%
% \DescribeMacro{\pyb\oarg{session}\meta{opening~delim}\meta{code}\meta{closing~delim}}
%
% This command both executes and typesets \meta{code}. Since it is unlikely that the user would wish to typeset code and then \textbf{immediately} include any output of the code, printed content is \textbf{not} automatically included, even when the package |autoprint| option is set to true. Rather, any printed content is included at a user-designated location via the |\printpythontex| or |\stdoutpythontex| macros.
%
%
% \subsubsection{Environments}
%
% \DescribeEnv{pycode~\oarg{session}\oarg{fancyvrb~settings}}
%
% This environment encloses code that is executed but not typeset. The second optional argument \meta{fancyvrb~settings} is irrelevant since nothing is typeset, but it is accepted to maintain parallelism with the |verbatim| and |block| environments. If the |print| statement/function is used within the environment, printed content will be included automatically so long as the package |autoprint| option is set to true (the default setting).
%
%
% \DescribeEnv{pyverbatim~\oarg{session}\oarg{fancyvrb~settings}}
%
% This environment encloses code that is typeset but not executed.
%
%
% \DescribeEnv{pyblock~\oarg{session}\oarg{fancyvrb~settings}}
%
% This environment encloses code that is both executed and typeset. Since it is unlikely that the user would wish to typeset code and then \textbf{immediately} print any output of the code, printed content is \textbf{not} automatically included, even when the package |autoprint| option is set to true. Rather, any printed content is included at a user-designated location via the |\printpythontex| or |\stdoutpythontex| macros.
%
%
% \DescribeEnv{pyconsole~\oarg{session}\oarg{fancyvrb~settings}}
%
% This environment treats its contents as a series of commands passed to an interactive Python console. Python's \href{http://docs.python.org/3/library/code.html}{\texttt{code}} module is used to intersperse the commands with their output, to emulate an interactive Python interpreter. Unlike the other environments, |pyconsole| has no inline equivalent. Currently, non-ASCII characters are not supported in |console| environments under Python 2.\pytxtodo{edit?}
%
% When a multi-line command is entered (for example, a function definition), a blank line after the last line of the command may be necessary.
%
% Unlike other commands and environments, the console environment currently does not bring in any imports by default and does not load custom code. This functionality will probably be added in the near future.
%
%
% \subsubsection{Default families}
%
% By default, three command and environment families are defined.
% \begin{itemize}
% \item Python
% \begin{itemize}
% \item Base name |py|: |\py|, |\pyc|, |\pyv|, |\pyb|, |pycode|, |pyverbatim|, |pyblock|, |pyconsole|
% \item Imports: None.
% \end{itemize}
% \item Python + pylab (matplotlib module)
% \begin{itemize}
% \item Base name |pylab|: |\pylab|, |\pylabc|, |\pylabv|, |\pylabb|, |pylabcode|, |pylabverbatim|, |pylabblock|, |pylabconsole|
% \item Imports: matplotlib's pylab module, which provides access to much of matplotlib and NumPy within a single namespace. pylab content is brought in via |from pylab import *|.
% \item Additional notes: matplotlib added a \href{http://matplotlib.org/users/pgf.html}{\texttt{pgf} backend} in version 1.2. You will probably want to use this for creating most plots. However, this is not currently configured automatically because many users will want to customize font, \TeX\ engine, and other settings. Using \TeX\ to create plots also introduces a speed penalty.
% \end{itemize}
% \item Python + SymPy
% \begin{itemize}
% \item Base name |sympy|: |\sympy|, |\sympyc|, |\sympyv|, |\sympyb|, |sympycode|, |sympyverbatim|, |sympyblock|, |sympyconsole|
% \item Imports: SymPy via |from sympy import *|.
% \item Additional notes: By default, content brought in via |\sympy| is formatted using a context-sensitive interface to SymPy's |LatexPrinter| class, described below.
% \end{itemize}
% \end{itemize}
%
% Under Python 2.7, all families import |absolute_import|, |division|, and |print_function| from |__future__| by default. This may be changed using the package option |pyfuture|. Keep in mind that importing |unicode_literals| from |__future__| may break compatibility with some packages; this is why it is not imported by default. Imports from |__future__| are also possible without using the |pyfuture| option. You may use the |\pythontexcustomc| command or |pythontexcustomcode| environment (described below), or simply enter the import commands immediately at the beginning of a session.
%
%
% \subsubsection{Custom code}
%
% You may wish to customize the behavior of one or more families within a document by adding custom code to the beginning and end of each session. The custom code command and environment make this possible.
%
% If you wish to share these customizations among several documents, you can create your own document class or package containing custom code commands and environments.
%
% While custom code can be added anywhere in a document, it is probably best for organizational reasons to add it in the preamble or near the beginning of the document.
%
% Note that custom code is executed, but never typeset. Only code that is actually entered within a |block| (or |verbatim|) command or environment is ever typeset. This means that you should be careful about how you use custom code. For example, if you are documenting code, you probably want to show absolutely all code that is executed, and in that case using custom code might not be appropriate. If you are using \pytex\ to create figures or automate text, are using many sessions, and require many imports, then custom code could save some typing by centralizing the imports.
%
% Any errors or warnings due to custom code will be correctly synchronized with the document, just like normal errors and warnings. Any errors or warnings will be specifically identified as originating in custom code.
%
% Custom code is not allowed to print or write to stdout. It would be pointless for custom code at the beginning of a session to print, because all printed content would be identical since custom code at the beginning comes before any regular code that might make the output session-specific. In addition, it is not obvious where printed content from custom code would be included, especially for custom code at the end of a session. Furthermore, custom code may be in the preamble, where nothing can be typeset.
%
% If custom code does attempt to print, a warning is raised and the printed content is included in the \pytex\ run summary. This gives you access to the printed content, while not including it in the document. This can be useful in cases where you cannot control whether content prints (for example, if a library automatically prints debugging information).
%
% \DescribeMacro{\pythontexcustomc\oarg{position}\marg{family}\marg{code}}
%
% \pytxtodo{Look into options for setting custom code for an entire language at a time. It would be possible to have the family be optional, but while that would be good as long as only Python is supported, it would quickly start causing problems as soon as any additional languages are added. Basically, there needs to be a way to set custom code for all sessions sharing a language. Perhaps some kind of keyword system, like language:python being used for family.}
% This macro allows custom code to be added to all sessions within a command and environment family. \meta{position} should be either |begin| or |end|; it determines whether the custom code is executed at the beginning or end of each session. By default, custom code is executed at the beginning. \meta{code} should be a \textbf{single line} of code. For example, |\pythontexcustomc{py}{a=1; b=2}| would create the variables |a| and |b| within all sessions of the |py| family, by adding that line of code at the beginning of each session.
%
% If you need to add more than a single line of custom code, you could use the command multiple times, but it will be more efficient to use the |pythontexcustomcode| environment.
%
% \meta{code} may contain imports from |__future__|. These must be the first elements in any custom code command or environment, since |__future__| imports are only possible at the very beginning of a Python script and only the very beginning of custom code is checked for them. If imports from |__future__| are present at the beginning of both custom code and the user's code, all imports will work correctly; the presence of the imports in custom code, before user code, does not turn off checking for |__future__| imports at the very beginning of user code. However, it is probably best to keep all |__future__| imports in a single location.
%
% \DescribeEnv{pythontexcustomcode\oarg{position}\marg{family}}
%
% This is the environment equivalent of |\pythontexcustomc|. It is used for adding multi-line custom code to a command and environment family. In general, the environment should be preferrred to the command unless only a very small amount of custom code is needed. The environment has the same properties as the command, including the ability to contain imports from |__future__|.
%
%
% \subsubsection{\pytex\ utilities class}
%
% All families import |pythontex_utils*.py|, and create an instance of the \pytex\ utilities class called |pytex|. This provides various utilities for interfacing with \LaTeX\ and \pytex.
%
% The utilities class provides an interface for determining how Python objects are converted into strings in commands such as |\py|. The |pytex.set_formatter(|\meta{formatter}|)| method is used to set the conversion. Two formatters are provided:
% \begin{itemize}
% \item |'str'| converts Python objects to a string, using the |str()| function under Python 3 and the |unicode()| function under Python 2. (The use of |unicode()| under Python 2 should not cause problems, even if you have not imported |unicode_literals| and are not using unicode strings. All encoding issues should be taken care of automatically by the utilities class.)
% \item |'sympy_latex'| uses SymPy's |LatexPrinter| class to return context-sensitive \LaTeX\ representations of SymPy objects. Separate |LatexPrinter| settings may be created for the following contexts: |'display'| (displaystyle math), |'text'| (textstyle math), |'script'| (superscripts and subscripts), and |'scriptscript'| (superscripts and subscripts, of superscripts and subscripts). Settings are created via |pytex.set_sympy_latex(|\meta{context}|,|\meta{settings}|)|. For example, |pytex.set_sympy_latex('display', mul_symbol='times')| sets multiplication to use a multiplication symbol $\times$, but only when math is in displaystyle.\footnote{Internally, the |'sympy\_latex'| formatter uses the |\textbackslash mathchoice| macro to return multiple representations of a SymPy object, if needed by the current settings. Then |\textbackslash mathchoice| typesets the correct representation, based on context.} See the \href{http://docs.sympy.org/dev/modules/printing.html}{SymPy documentation} for a list of possible settings for the |LatexPrinter| class.
%
% By default, |'sympy_latex'| only treats matrices differently based on context. Matrices in displaystyle are typeset using |pmatrix|, while those in all other styles are typeset via |smallmatrix| with parentheses.
% \end{itemize}
%
% % The context-sensitive interface to SymPy's |LatexPrinter| is always available via |pytex.sympy_latex()|. The \pytex\ utilities formatter may also be set to a custom function that returns strings, simply by reassigning the |pytex.formatter()| method. For example, define a formatter function |my_func()|, and then |pytex.formatter=my_func|.
%
% The utilities class also provides methods for tracking dependencies and created files.
% \begin{itemize}
% \item |pytex.add_dependencies(|\meta{dependencies}|)| This adds \meta{dependencies} to a list. If any dependencies in the list change, code is re-executed, even if the code itself has not changed. (Changed dependencies are determined via either hash or mtime; see package option |hashdependencies| for details.) This method is useful for tracking changes in external data and similar files.
%
% \meta{dependencies} should be one or more strings, separated by commas, that are the file names of dependencies. Dependencies should be given with relative paths from the current working directory, with absolute paths, or with paths based on the user's home directory (that is, starting with a tilde |~|). Remember that by default, the working directory is the |pythontex-files-|\meta{jobname} directory where all \pytex\ temporary files are stored. This can be adjusted with |\setpythontexworkingdir|.
% \item |pytex.add_created(|\meta{created~files}|)| This adds \meta{created~files} to a list of files created by the current session. Any time the code for the current session is executed, \textbf{all of these files will be deleted}. Since this method deletes files, it should be used with care. It is intended for automating cleanup when code is modified. For example, if a figure's name is changed, the old figure would be deleted if its name had been added to the list. By default, \pytex\ can only clean up the temporary files it creates; it knows nothing about user-created files. This method allows user-created files to be specified, and thus added to \pytex's automatic cleanup.
%
% \meta{created~files} should be one or more strings, separated by commas, that are the file names of created files. Paths should be the same as for |pytex.add_dependencies()|: relative to the working directory, absolute, or based on the user's home directory.
%
% Depending on how you use \pytex, this method may not be very beneficial. If all of the output is contained in the default output directory, or a similar directory of your choosing, then manual cleanup may be simple enough that this method is not needed.
% \end{itemize}
% These two methods may be used manually. However, that is prone to errors, since you will have to modify both a \pytex\ utilities command and an open or save command every time you change a file name or add or remove a dependency or created file. It may be better to redefine your open and save commands, or define new ones, so that a single command opens (or saves) and adds a dependency (or adds a created file).
%
%
% \subsubsection{Formatting of typeset code}
%
% \DescribeMacro{\setpythontexfv\oarg{family}\marg{fancyvrb~settings}}
%
% This command sets the |fancyvrb| settings for all command and environment families. Alternatively, if an optional argument \meta{family} is supplied, the settings only apply to the family with that base name. The general command will override family-specific settings.
%
% Each time the command is used, it completely overwrites the previous settings. If you only need to change the settings for a few pieces of code, you should use the second optional argument in |block| and |verb| environments.
%
% Note that |\setpythontexfv| and |\setpygmentsfv| are equivalent when they are used without an optional argument; in that case, either may be used to determine the document-wide |fancyvrb| settings, because both use the same underlying macro.
%
%
% \DescribeMacro{\setpythontexprettyprinter\oarg{family}\marg{printer}}
%
% This should generally not be needed. It sets the pretty printing used by the document, or by \meta{family} if given. Valid options for \meta{printer} are |fancyvrb| and |pygments|. The option |auto| may be given for \meta{family}, in which case the formatter is inherited from the document-level settings. Using either of the other two options will force \meta{family} to use that printer, regardless of the document-level settings. By default, families use |auto|.
%
% Remember that Pygments has a |text| lexer and a |bw| style. These are an alternative to setting the formatter to |fancyvrb|.
%
%
% \DescribeMacro{\setpythontexpyglexer\oarg{family}\marg{pygments~lexer}}
%
% This allows the Pygments lexer to be set for \meta{family}. \meta{pygments~lexer} should use a form of the lexer name that does not involve any special characters. For example, you would want to use the lexer name |csharp| rather than |C#|. This will be a consideration primarily when using the Pygments commands and environments to typeset code of an arbitrary language.
%
% If a \meta{family} is not specified, the lexer is set for the entire document.
%
% \DescribeMacro{\setpythontexpygopt\oarg{family}\marg{pygments~options}}
%
% This allows the Pygments options for \meta{family} to be redefined. Note that any previous options are overwritten. The same Pygments options may be passed here as are available via the package |pygopt| option. Note that for each available option, individual family settings will be overridden by the package-level |pygopt| settings, if any are given.
%
% If a \meta{family} is not specified, the options are set for the entire document.
%
%
% \subsubsection{Access to printed content (stdout) and error messages (stderr)}
%
% The macros that allow access to printed content and any additional content written to stdout are provided in two identical forms: one based off of the word |print| and one based off of |stdout|. Macro choice depends on user preference. The |stdout| form provides parallelism with the macros that provide accesss to |stderr|.
%
% \DescribeMacro{\printpythontex\oarg{mode}\oarg{options}}
%
% \DescribeMacro{\stdoutpythontex\oarg{mode}\oarg{options}}
%
% Unless the package option |autoprint| is true, printed content from |code| commands and environments will not be automatically included. Even when the |autoprint| option is turned on, |block| commands and environments do not automatically include printed content, since we will generally not want printed content immediately after typeset code. This macro brings in any printed content from the \textbf{last} command or environment. It is reset after each command/environment, so its scope for accessing particular printed content is very limited. It will return an error if no printed content exists.
%
% \meta{mode} determines how printed content is handled. It may be |raw| (interpreted as \LaTeX), |verb| (inline verbatim), or |verbatim|; |raw| is the default. Verbatim content is brought in via |fancyvrb|. \meta{options} consists of |fancyvrb| settings.
%
%
% \DescribeMacro{\saveprintpythontex\marg{name}}
%
% \DescribeMacro{\savestdoutpythontex\marg{name}}
%
% \DescribeMacro{\useprintpythontex\oarg{verbatim~options}\oarg{fancyvrb~options}\marg{name}}
%
% \DescribeMacro{\usestdoutpythontex\oarg{verbatim~options}\oarg{fancyvrb~options}\marg{name}}
%
% We may wish to be able to access the printed content from a command or environment at any point after the code that prints it, not just before any additional commands or environments are used. In that case, we may save access to the content under \meta{name}, and access it later via |\useprintpythontex|\marg{name}. \meta{mode} must be |raw|, |verb|, or |verbatim|. If content is brought in verbatim, then \meta{fancyvrb~options} are applied.
%
% \DescribeMacro{\stderrpythontex\oarg{mode}\oarg{fancyvrb~options}}
%
% This brings in the stderr produced by the last command or environment. It is intended for typesetting incorrect code next to the errors that it produces. By default, stderr is brought in verbatim. \meta{mode} may be set to |raw|, |verb|, or |verbatim|. In general, bringing in stderr |raw| should be avoided, since stderr will typically include special characters that will make \TeX\ unhappy.
%
% The line number given in the |stderr| message will correctly align with the line numbering of the typeset code. Note that this only applies to |code| and |block| environments. Inline commands do not have line numbers, and as a result, they \textbf{do not} produce stderr content. \pytxtodo{Maybe allow stderr for inline, with line number set to 1?}
%
% By default, the file name given in the message will be in the form
% \begin{quote}
% \meta{family~name}|_|\meta{session}|_|\meta{group}|.|\meta{extension}
% \end{quote}
% For example, an error produced by a |pycode| environment, in the session |mysession|, using the default group (that is, the default |\restartpythontexsession| treatment), would be reported in |py_mysession_default.py|. The package option |stderrfilename| may be used to change the reported name to the following forms: |mysession.py|, |<file>|, |<script>|.
%
%
% \DescribeMacro{\savestderrpythontex\marg{name}}
%
% \DescribeMacro{\usestderrpythontex\oarg{mode}\oarg{fancyvrb~options}\marg{name}}
%
%
% Content written to |stderr| may be saved and accessed anywhere later in the document, just as |stdout| content may be. These commands should be used with care. Using Python-generated content at multiple locations within a document may often be appropriate. But an error message will usually be most meaningful in its context, next to the code that produced it.
%
% \DescribeMacro{\setpythontexautoprint\marg{boolean}}
%
% \DescribeMacro{\setpythontexautostdout\marg{boolean}}
%
% This allows autoprint behavior to be modified at various points within the document. The package-level |autoprint| option is also available for setting autoprint at the document level, but it is overridden by |\setpythontexautoprint|. \meta{boolean} should be |true| or |false|.
%
%
% \subsection{Pygments commands and environments}
%
% Although \pytex's goal is primarily the execution and typesetting of Python code from within \LaTeX, it also provides access to syntax highlighting for any language supported by Pygments.
%
% \DescribeMacro{\pygment\marg{lexer}\meta{opening~delim}\meta{code}\meta{closing~delim}}
%
% This command typesets \meta{code} in a suitable form for inline use within a paragraph, using the specified Pygments \meta{lexer}. Internally, it uses the same macros as the \pytex\ inline commands. \meta{opening~delim} and \meta{closing~delim} may be a pair of any characters except for the space character, or a matched set of curly braces |{}|.
%
% As with the inline commands for code typesetting and execution, there is not an optional argument for |fancyvrb| settings, since almost all of them are not relevant for inline usage, and the few that might be should probably be used document-wide if at all.
%
%
% \DescribeEnv{pygments~\oarg{fancyvrb~settings}\marg{lexer}}
%
% This environment typesets its contents using the specified Pygments \meta{lexer} and applying the \meta{fancyvrb~settings}.
%
%
% \DescribeMacro{\inputpygments\oarg{fancyvrb~settings}\marg{lexer}\marg{external~file}}
%
% This command brings in the contents of \meta{external~file}, highlights it using \meta{lexer}, and typesets it using \meta{fancyvrb~settings}.
%
%
% \DescribeMacro{\setpygmentsfv\oarg{lexer}\marg{fancyvrb~settings}}
%
% This command sets the \meta{fancyvrb~settings} for \meta{lexer}. If no \meta{lexer} is supplied, then it sets document-wide \meta{fancyvrb~settings}. In that case, it is equivalent to |\setpythontexfv|\marg{fancyvrb~settings}.
%
%
% \DescribeMacro{\setpygmentspygopt\oarg{lexer}\marg{pygments~options}}
%
% This sets \meta{lexer} to use \meta{pygments~options}. If there is any overlap between \meta{pygments~options} and the package-level |pygopt|, the package-level options override the lexer-specific options.
%
% If \meta{lexer} is not given, options are set for the entire document.
%
%
% \DescribeMacro{\setpygmentsprettyprinter\marg{printer}}
%
% This usually should not be needed. It allows the pretty printer for the document to be set; it is equivalent to using |\setpythontexprettyprinter| without an optional argument. Valid options for \meta{printer} are |fancyvrb| and |pygments|.
%
% Remember that Pygments has a |text| lexer and a |bw| style. These are an alternative to setting the formatter to use |fancyvrb|.
%
%
% \subsection{General code typesetting}
%
% \subsubsection{Listings float}
%
% \DescribeEnv{listing}
%
% \pytex\ will create a float environment |listing| for code listings, unless an environment with that name already exists. The |listing| environment is created using the |newfloat| package. Customization is possible through |newfloat|'s |\SetupFloatingEnvironment| command.
%
% \DescribeMacro{\setpythontexlistingenv\marg{alternate~listing~environment~name}}
%
% In the event that an environment named |listing| already exists for some other purpose, \pytex\ will not override it. Instead, you may set an alternate name for \pytex's |listing| environment, via |\setpythontexlistingenv|.
%
%
% \subsubsection{Background colors}
%
% \pytex\ uses |fancyvrb| internally to typeset all code. Even code that is highlighted with Pygments is typeset afterwards with |fancyvrb|. Using |fancyvrb|, it is possible to set background colors for individual lines of code, but not for entire blocks of code, using |\FancyVerbFormatLine| (you may also wish to consider the |formatcom| option). For example, the following command puts a green background behind all the characters in each line of code:
% \begin{verbatim}
% \renewcommand{\FancyVerbFormatLine}[1]{\colorbox{green}{#1}}
% \end{verbatim}
%
% If you need a completely solid colored background for an environment, or a highly customizable background, you should consider the |mdframed| package. Wrapping \pytex\ environments with |mdframed| frames works quite well. You can even automatically add a particular style of frame to all instances of an environment using the command
% \begin{quote}
% |\surroundwithmdframed|\oarg{frame~options}\marg{environment}
% \end{quote}
% Or you could consider using |etoolbox| to do the same thing with |mdframed| or another framing package of your choice, via |etoolbox|'s |\BeforeBeginEnvironment| and |\AfterEndEnvironment| macros.
%
%
% \subsubsection{Referencing code by line number}
%
% It is possible to reference individual lines of code, by line number. If code is typeset using pure |fancyvrb|, then \LaTeX\ labels can be included within comments. The labels will only operate correctly (that is, be treated as \LaTeX\ rather than verbatim content) if |fancyvrb|'s |commandchars| option is used. For example, |commandchars=\\\{\}| makes the backslash and the curly braces function normally \textbf{within} |fancyvrb| environments, allowing \LaTeX\ macros to work, including label definitions. Once a label is defined within a code comment, then referencing it will return the code line number.
%
% The disadvantage of the pure |fancyvrb| approach is that by making the backslash and curly braces command characters, we can produce conflicts if the code we are typesetting contains these characters for non-\LaTeX\ purposes. In such a case, it might be possible to make alternate characters command characters, but it would probably be better to use Pygments.
%
% If code is typeset using Pygments (which also ties into |fancyvrb|), then this problem is avoided. The Pygments option |texcomments=true| has Pygments look for \LaTeX\ code only within comments. Possible command character conflicts with the language being typeset are thus eliminated.
%
% Note that when labels are created within comments, the labes themselves will be invisible within the final document but the comment character(s) and any other text within comments will still be visible. For example, the following
% \begin{quote}
% |abc = 123 # An important line of code!\label{lst:important}|
% \end{quote}
% would appear as
% \begin{quote}
% |abc = 123 # An important line of code!|
% \end{quote}
% If a comment only contains the |\label| command, then only the comment character |#| would actually be visible in the typeset code. If you are typesetting code for instructional purposes, this may be less than ideal. Unfortunately, Pygments currently does not allow escaping to \LaTeX\ outside of comments (though this feature has been requested). At the same time, by only allowing references within comments, Pygments does force us to create code that would actually run. And in many cases, if a line is important enough to label, it is also important enough for a brief comment.
%
% \subsubsection{Beamer compatibility}
%
% \pytex\ is compatible with \href{http://www.ctan.org/pkg/beamer}{Beamer}. Since \pytex\ typesets code as verbatim content, Beamer's |fragile| option must be used for any frame that contains typeset code. Beamer's |fragile| option involves saving frame contents to an external file and bringing it back in. This use of an external file breaks \pytex's error line number synchronization, since the error line numbers will correspond to the temporary external file rather than to the actual document.
%
% If you need to typeset code with Beamer, but don't need to use overlays on the slides containing code, you should use the |fragile=singleslide| option. This allows verbatim content to be typeset without using an external file, so \pytex's error line syncronization will work correctly.
%
%
% \subsection{Advanced \pytex\ usage}
%
% \DescribeMacro{\restartpythontexsession\marg{counter~value(s)}}
%
% This macro determines when or if sessions are restarted (or ``subdivided''). Whenever \meta{counter~value(s)} change, the session will be restarted.
%
% By default, each session corresponds to a single code file that is executed. But sometimes it might be convenient if the code from each chapter or section or subsection were to run within its own file, as its own session. For example, we might want each chapter to execute separately, so that changing code within one chapter won't require that all the code from all the other chapters be executed. But we might not want to have to go to the bother and extra typing of defining a new session for every chapter (like |\py[ch1]{|\meta{code}|}|). To do that, we could use |\restartpythontexsession{\thechapter}|. This would cause all sessions to restart whenever the chapter counter changes. If we wanted sessions to restart at each section within a chapter, we would use |\restartpythontexsession{\thechapter|\meta{delim}|\thesection}|. \meta{delim} is needed to separate the counter values so that they are not ambiguous (for example, we need to distinguish chapter 11-1 from chapter 1-11). Usually \meta{delim} should be a hyphen or an underscore; it must be a character that is valid in file names.
%
% Note that \textbf{counter values}, and not counters themselves, must be supplied as the argument. Also note that the command applies to \textbf{all} sessions. If it did not, then we would have to keep track of which sessions restarted when, and the lack of uniformity could easily result in errors on the part of the user.
%
% Keep in mind that when a session is restarted, all continuity is lost. It is best not to restart sessions if you need continuity. If you must restart a session, but also need to keep some data, you could save the data before restarting the session and then load the saved data after the restart. This approach should be used with \textbf{extreme} caution, since it can result in unanticipated errors due to sessions not staying synchronized.\footnote{For example, suppose sessions are restarted based on chapter. |session-ch1| saves a data file, and |session-ch2| loads it and uses it. You write the code, and run \pytex. Then you realize that |session-ch1| needs to be modified and make some changes. The next time \pytex\ runs, it will only execute |session-ch1|, since it detects no code changes in |session-ch2|. This means that |session-ch2| is not updated, at least to the extent that it depends on the data from |session-ch1|. Again, saving and loading data between restarted sessions, or just between sessions in general, can produce unexpected behavior and should be avoided. (Note: the \texttt{pytex.add\_dependencies()} method does provide a workaround for this scenario.)}
%
% This command can only be used in the preamble.
%
% \DescribeMacro{\setpythontexoutputdir\marg{output~directory}}
%
% By default, \pytex\ saves all temporary files and automatically generated content in a directory called |pythontex-files-|\meta{sanitized jobname}, where \meta{sanitized jobname} is just |\jobname| with any space characters or asterisks replaced with hyphens. This directory will be created by |pythontex.py|. If we wish to specify another directory (for example, if |\jobname| is long and complex, and there is no danger of two files trying to use the same directory), then we can use the |\setpythontexoutputdir| macro to redefine the output directory.\footnote{In the rare event that both |\string\setpythontexoutputdir| is used and |\string\printpythontex| is needed in the preamble, |\string\setpythontexoutputdir| must be used first, so that |\string\printpythontex| will know where to look for output.}
%
% \DescribeMacro{\setpythontexworkingdir\marg{working~directory}}
%
% The \pytex\ working directory is the current working directory for \pytex\
%scripts. This is the directory in which any open or save operations will
%take
%place, unless a path is explicitly specified. By default, the working
%directory is the same as the output directory. For example, if you are
%writing |my_file.tex| and save a matplotlib figure with
%|savefig('my_figure.pdf')|, then |my_figure.pdf| will be created in the
%output
%directory |pythontex-files-my_file|. But maybe you have a directory called
%|plots| in your document root directory. In that case, you could leave the
%working directory unchanged, and simply specify the relative path to |plots|
%when saving. Or you could set the working directory to |plots| using
%|\setpythontexworkingdir{plots}|, so that all content would automatically be
%saved there. If you want your working directory to be the document root directory, you should use a period (|.|) for \meta{working~directory}: |\setpythontexworkingdir{.}|.
%
% Note that in typical use scenarios, you should be able to use the output directory as the working directory. |graphicx| will automatically look for images and figures in the output directory (this is set via |\graphicspath|).
%
% It is also possible to change the working directory from within Python code, via |os.chdir()|.
%
%
% \section{\texttt{depythontex}}
% \label{sec:depythontex}
%
% \pytex\ can greatly simplify the creation of documents. At the same time, by introducing dependence on non-\LaTeX\ external tools, it can constrain how these documents are used. For example, many publishers will not accept \LaTeX\ documents that require special packages or need special macros. To address this issue, the package includes a feature called |depythontex| that can convert a \pytex\ document into a plain \LaTeX\ document.
%
%
% \subsection{Preparing a document that will be converted}
%
% The conversion process should work flawlessly in most cases, with no special formatting required.
%
% For best results, keep the following in mind.
% \begin{itemize}
% \item The \pytex\ package should have its own |\usepackage|.
% \item If you need to insert content from Python in inline contexts, it is best to use |\py| or an equivalent command. If you use |print|, either directly (for example, from within |\pyc|) or via |\printpythontex|, make sure that the spacing following the printed content is correct. You may need to print an |\endinput| or |%| at the end of your content to prevent an extra trailing space. |depythontex| will attempt to reproduce the spacing of the original document, even if it is not ideal. See Section~\ref{sec:depythontex:technical-details} for additional details.
% \item Some \LaTeX\ environments, such as the |verbatim| environment from the |verbatim| package and the |Verbatim| environment from |fancyvrb|, do not allow text to follow the |\end{|\meta{environment}|}|. If you bring Python-generated content that ends with one of these environments into your document, using |print| or |\py|, make sure that the end-of-environment command is followed by a newline. For example, if you are assembling a |Verbatim| environment to bring in, the last line should be the string
% \begin{verbatim}
% '\\end{Verbatim}\n'
% \end{verbatim}
% Even if you neglect a final newline, |depythontex| will still function correctly in most cases. Whenever Python-generated content does not end with a newline, |depythontex| usually inserts one and gobbles spaces that follow the environment. This preserves the correct spacing while avoiding any issues produced by an end-of-environment command. But in some cases, |depythontex| cannot do this. For example, if |\py| is used to bring in a |Verbatim| environment, and there is text immediately after the |\py|, without any intervening space, |depythontex| cannot substitute a newline for spaces, because there are none. Because of the way that |print| and |\py| content is brought in, everything may still work correctly in the original \pytex\ document. But it would fail in the |depythontex| output.
% \item Do not create \pytex\ commands or environments on the Python side and |print| or otherwise bring them in. That is too many levels of complexity!
% \item |depythontex| is only designed to replace \pytex\ commands and environments that are actually in the main document file. Do not bring in anything that contains \pytex\ commands or environments via |\input|, |\include|, or |\usepackage|. The only exception is \pytex\ commands and environments that do not typeset anything (for example, |code| environments that don't print). If these are brought in via a package or external file, the command |\DepythontexOff| must come before them, and they must be followed by the command |\DepythontexOn|. Basically, |depythontex| must be disabled for commands and environments brought in via external files. This works so long as the commands and environments only provide code and settings, rather than any typeset content.
%
% Tools for automatically removing the |\usepackage| for packages that contain \pytex\ commands will be added soon; for now, these |\usepackage|'s must be removed manually in the |depythontex| output.
% \item Keep in mind that the file produced by |depythontex| will need to include any graphics that you create with \pytex. Make sure any graphics are saved in a location where they are easily accessible.
% \end{itemize}
%
% \subsection{Removing \pytex\ dependence}
%
% Converting a document requires three steps.
% \begin{enumerate}
% \item Turn on the package option |depythontex|. Then compile the document, run |pythontex.py|, and compile the document again. Depending on the document, additional compiles may be necessary (for example, to resolve references). Any syntax highlighting will be turned off automatically during this process, to remove dependence on Pygments.
%
% During compilation, an auxiliary file called \meta{jobname}|.depytx| is created. This file contains information about the location of the \pytex\ commands and environments that need to be replaced, and about the content with which they are to be replaced.
%
% \item Run the |depythontex.py| script. This takes the following arguments.
% \begin{itemize}
% \item |--encoding ENCODING| This is the encoding of the \LaTeX\ file and all related files. If an encoding is not specified, UTF-8 is assumed.
% \item |--overwrite| This turns off the user prompt in the event that a file already exists with the output name, making overwriting automatic.
% \item |--listing| This option specifies the commands and environments that are used for any typeset code. This can be |verbatim|, |fancyvrb|, |listings|, |minted|, or |pythontex|.\footnote{The \texttt{pythontex} option is included for completeness. In most cases, you would probably use \texttt{depythontex} to remove all dependence on \pytex. But sometimes it might be useful to remove all Python code while still using \pytex\ for syntax highlighting.} |verbatim| is used by default. An appropriate |\usepackage| command is automatically added to the output document's preamble.
%
% When code is typeset with any option other than |verbatim|, listing line numbering from the original document will be preserved. When code is typeset with any option other than |verbatim| and |fancyvrb|, syntax highlighting will also be preserved. The only exception is when |listings| is used, and |listings|'s language name does not correspond to Pygments' lexer name. In this case, you should use the |--lexer-dict| option to specify how the Pygments lexer is to be translated into a |listings| language.
% \item |--lexer-dict| This option is used to specify how Pygments lexers are converted to |listings| languages, when the two do not have the same name. It takes a comma-separated list of the form
% \begin{verbatim}
% "<Pygments lexer>:<listings language>, ..., ... "
% \end{verbatim}
% A Python-style dict will also be accepted.
% \item |--preamble| This option allows additional commands to be added to the output document's preamble. This is useful when you want the output document to load a package that was automatically loaded by \pytex, such as |upquote|.
% \item |TEXNAME| The name of the \LaTeX\ file whose \pytex\ dependence is to be removed.
% \item |[OUTFILE]| By default, the script takes a file |<filename>.<ext>| and creates a new file called |depythontex_<filename>.<ext>|. If a name is given for the output file, that is used instead.
% \end{itemize}
% \item Compile the |depythontex| file, and compare it to the original.
%
% The original and |depythontex| files should be nearly identical. All Python-generated content is substituted directly, so it should be unchanged. Usually, any differences will be due to changes in the way that code is typeset. For example, by default all code in the |depythontex| file is typeset with |\verb| and |verbatim|. But |\verb| is more fragile than the inline \pytex\ commands (it isn't allowed inside other commands), and |verbatim| does not support line numbering or syntax highlighting.
%
% Remember that the |depythontex| file will need to include any graphics created by \pytex. By default, these are saved in the \pytex\ |outputdir|, which is |pythontex-files-<jobname>| unless you have customized it. They may be in other locations if you have set a non-default |workingdir| or have specified a path when saving graphics. You may want to copy the graphics into the same directory as the |depythontex| file, or provide their location via |\graphicspath|.
%
% Depending on your needs, you may wish to customize |depythontex.py|. The actual substitutions are performed in a few functions that are defined at the beginning of the script.
% \end{enumerate}
%
%
% \subsection{Technical details}
% \label{sec:depythontex:technical-details}
%
% The |depythontex| process should go smoothly under most circumstances, and the document produced usually should not need manual tweaking. There are a few technical details that may be of interest.
% \begin{itemize}
% \item Content that is printed (actually printed, not from a command like |\py|) is always followed by a space when included as \LaTeX\ code rather than as verbatim. Usually this is only noticeable when the content is used inline, adjacent to other text. In such cases, you need to make sure that the spacing is correct in your original document, and need to be aware of how |depythontex| handles the conversion.
% This spacing behavior is due to \LaTeX's |\input|. When the file of printed content is brought in via |\input|, \LaTeX\ removes any newline characters (|\n|, |\r|, or |\r\n|) at the end of each line, and adds a space at the end of each line (even if there wasn't a newline character). Thus, when the printed content is brought in, a space is added to its end. Since this space is within the |\input|'s curly braces |{}|, it is not combined with any following spaces in the \LaTeX\ document to make a single space. Rather, if the printed content is followed by one or more spaces, two spaces will result; and if it is followed immediately by text, there will be a single space before the text.
%
% The space added by |\input| is often invisible, and even when it is not, it is sometimes desirable.\footnote{For example, |\string\printpythontex| behaves as a normal command, and gobbles following spaces, but the space from |\string\input| puts a space back. So you often get the space you want in inline contexts.} But this space can be an issue in some inline contexts. The simplest solution is to use a command like |\py| to bring in content inline.
%
% If a command like |\py| is not practical for some reason, there are at least three ways to deal with the space introduced by |\input|: by printing |\endinput| at the end of the printed content (ending the content before the final space), by printing |%| at the end of the printed content (commenting out the final space), or by using |\unskip| after the printed content (eating preceding spaces). |depythontex| will work with all three approaches, but only under a limited range of circumstances. In summary, |depythontex| works with |\endinput| and |%| only if they are the very last thing printed (before a final newline), and works with a following |\unskip|.\footnote{It would be possible to make \texttt{depythontex} work with \texttt{\string\endinput} and \texttt{\%} anywhere, not just at the very end of printed content. But doing so would require a lot of additional parsing, especially for \texttt{\string\endinput}, to be absolutely sure that we found an actual command rather than a string. Furthermore, there is no reason that there should be any content after an \texttt{\string\endinput} or \texttt{\%}, since such content would never be included in the document. Indeed, the current approach prevents any printed content from accidentally being eliminated in this manner.}
% \begin{itemize}
% \item |\endinput| cannot be left in the printed content that is substituted into the new document, because it would cause the new document to end immediately. |depythontex| checks the very end of printed content for |\endinput|, and removes it if it is there before substituting the content. The terminating |\endinput| is only removed if it is not a string, |\string\endinput|.
%
% If |\endinput| is anywhere else in the printed content, and it is not immediately preceded by |\string|, |depythontex| issues a warning.
% \item A terminating |%| cannot be left in the printed content that is substituted into the new document, because it would comment out any text in the remainder of the line into which it is substituted (in |\input|, its effect is limited to the print file). |depythontex| checks the very end of printed content for |%|, and removes it if it is there before substituting the content. |depythontex| only removes the terminating |%| if it is not a literal character |\%| or |\string%|.
%
% |depythontex| checks the last line of printed content for other |%| characters, and issues a warning if there are any |%| characters that are not part of |\%| or |\string%|.
%
% \item A following |\unskip| could be left in the new document, since it would not produce incorrect spacing. But it would be undesirable, since it was only there in the first place because of the way that \pytex\ was used. |depythontex| checks for |\unskip|, and if it is found, attempts to correct the spacing and remove the |\unskip|. This removal process is only possible if |\unskip| immediately follows a command (otherwise, it wouldn't work anyway) or is on the line immediately after the end of an environment.
%
% If |depythontex| finds |\unskip| following printed content, but cannot replace it (it doesn't immediately follow a command, or isn't on the line immediately after the end of an environment), a warning is issued. It is possible that the |\unskip| is not correctly positioned, and even if it produces the correct spacing, the user should know that due to its location it will survive in the converted document.
% \end{itemize}
%
% If one of the above approaches is not used to eliminate the space introduced by the final newline in printed content, |depythontex| still makes sure that the spacing in the new document matches that of the original document, even if that means forcing a double space. In the majority of cases, |depythontex| can create the correct spacing using actual spaces and newlines. But in a few instances, it will include a |\space{}| to ensure a double space that matches the original document. In those situations, a warning is issued in case the spacing was not intentional.
%
% \item Strings such as |\\}|, |\\{|, and |\string| can occur in \pytex\ content that is being replaced. It is possible that they might decrease performance somewhat in larger or more complex documents.
%
% \pytex\ commands for entering code allow the code to be delimited with either matched braces |{}| or with a repeated character such as |#| (as in |\verb|). Any verbatim code delimited by braces cannot \textbf{contain} any braces \textbf{unless} they are paired. So it is easy for |depythontex.py| to find the end of the delimited code.
%
% However, |depythontex.py| must also replace \pytex\ commands that take a normal, non-verbatim argument delimited by braces (for example, the various |\setpythontex...| commands). Finding the closing brace for these commands is usually straightforward, but it can be tricky because the argument might contain a literal brace such as |\}| or |\string}|. |depythontex.py| automatically accounts for |\}|. If it detects |\string|, it also accounts for it, but doing so requires more intense parsing. Similarly, |\\}| requires extra parsing, because depending on what comes before it, the first backslash |\| could be literal (for example, if preceded by |\string|), or the two backslashes |\\| could go together to indicate a new line.
% \end{itemize}
%
%
%
%
%
% \section{\LaTeX\ programming with \pytex}
%
% This section will be expanded in the future. For now, it offers a brief summary.
%
% \subsection{Macro programming with \pytex}
%
% In many situations, you can use \pytex\ commands inside macro definitions without any special consideration. For example, consider the following macro, for calculating powers.
% \newcommand{\pow}[2]{\py{#1**#2}}
% \begin{verbatim}
% \newcommand{\pow}[2]{\py{#1**#2}}
% \end{verbatim}
% Once this is defined, we can calculate |2**8| via |\pow{2}{8}|: \pow{2}{8}. Similarly, we can reverse a string.
% \newcommand{\reverse}[1]{\py{"#1"[::-1]}}
% \begin{verbatim}
% \newcommand{\reverse}[1]{\py{"#1"[::-1]}}
% \end{verbatim}