diff options
author | Karl Berry <karl@freefriends.org> | 2014-07-14 22:39:29 +0000 |
---|---|---|
committer | Karl Berry <karl@freefriends.org> | 2014-07-14 22:39:29 +0000 |
commit | 91e62921c8f6d17fb3a1b701c0b5f99cfeadd408 (patch) | |
tree | 8ba1865818a69de5220113ae92b7c54f849fb5f3 /Master/texmf-dist/source | |
parent | 5dae7a4d678252feb9eda590f0c6a547a5bcc4d9 (diff) |
pythontex (14jul14)
git-svn-id: svn://tug.org/texlive/trunk@34605 c570f23f-e606-0410-a88d-b1316a301751
Diffstat (limited to 'Master/texmf-dist/source')
4 files changed, 366 insertions, 75 deletions
diff --git a/Master/texmf-dist/source/latex/pythontex/depythontex.bat b/Master/texmf-dist/source/latex/pythontex/depythontex.bat new file mode 100755 index 00000000000..77fe1ec6366 --- /dev/null +++ b/Master/texmf-dist/source/latex/pythontex/depythontex.bat @@ -0,0 +1,2 @@ +@echo off
+depythontex.py %*
diff --git a/Master/texmf-dist/source/latex/pythontex/pythontex.bat b/Master/texmf-dist/source/latex/pythontex/pythontex.bat index 0dfa442b4f7..f200d2e9f6b 100755 --- a/Master/texmf-dist/source/latex/pythontex/pythontex.bat +++ b/Master/texmf-dist/source/latex/pythontex/pythontex.bat @@ -1,2 +1,2 @@ -@echo off -pythontex.py %* +@echo off
+pythontex.py %*
diff --git a/Master/texmf-dist/source/latex/pythontex/pythontex.dtx b/Master/texmf-dist/source/latex/pythontex/pythontex.dtx index a7da1010aeb..cdba66cae41 100644 --- a/Master/texmf-dist/source/latex/pythontex/pythontex.dtx +++ b/Master/texmf-dist/source/latex/pythontex/pythontex.dtx @@ -26,7 +26,7 @@ %<package>\NeedsTeXFormat{LaTeX2e}[1999/12/01] %<package>\ProvidesPackage{pythontex} %<*package> - [2013/08/26 Version~0.12] + [2014/07/14 Version~0.13 ] %</package> % %<*driver> @@ -34,6 +34,7 @@ \makeatletter \usepackage[T1]{fontenc} \usepackage[utf8]{inputenc} +\usepackage{lmodern} \usepackage{textcomp} \usepackage[svgnames]{xcolor} \usepackage{environ} @@ -45,16 +46,14 @@ %\newcommand{\pytxtodo}[1]{\textcolor{red}{TO~DO: \scantokens{#1}}} \newcommand{\changestext}{} \NewEnviron{changelog}[2]{% - \g@addto@macro\changestext{\item[#1] (#2) \begin{itemize}}% + \g@addto@macro\changestext{\subsection*{\textbf{#1} (#2)}}% \expandafter\g@addto@macro\expandafter\changestext\expandafter{\BODY}% - \g@addto@macro\changestext{\end{itemize}}% + \g@addto@macro\changestext{}% } \newcommand{\PrintChangelog}{% \addcontentsline{toc}{section}{Version History} \section*{Version History}% - \begin{description}% \changestext - \end{description}% } \EnableCrossrefs \CodelineIndex @@ -68,7 +67,7 @@ %</driver> % \fi % -% \CheckSum{2928} +% \CheckSum{3010} % % \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 @@ -87,8 +86,61 @@ % Right brace \} Tilde \~} % % +% \begin{changelog}{v0.13}{2014/07/14} +% \textbf{New features} +% \begin{itemize} +% \item Added \texttt{-{}-interactive} command-line option. This runs a single session in interactive mode, allowing user input. Among other things, this is useful when working with debuggers. +% \item Added \texttt{-{}-debug} command-line option. This runs a single session with the default debugger in interactive mode. Currently, only standard (non-console) Python sessions are supported. The default Python debugger is the new \texttt{syncpdb}, which wraps \texttt{pdb} and synchronizes code line numbers with document line numbers. All \texttt{pdb} commands that take a line number or filename:lineno as an argument will refer to document files and line numbers when the argument has a percent symbol (\texttt{\%}) as a prefix. For example, \texttt{list \%50} lists code that came from around line 50 in the document. The \texttt{-{}-debug} option will support other languages and provide for customization in the future. +% \item Added command-line option \texttt{-{}-jobs}, which allows the maximum number of concurrent processes to be specified (\#35). +% \item Added support for GNU Octave, via the \texttt{octave} family of commands and environments (\#36). Parsing of Octave stderr is not ideal, though synchronization works in most cases; this will be addressed by a future rewrite of the stderr parser. +% \item Installer now automatically works with MiKTeX, not just TeX Live. +% \item The PythonTeX utilities class has a new \texttt{open()} method that opens files and automatically tracks dependencies/created files. +% \item When \texttt{pythontex2.py} and \texttt{pythontex3.py} are run directly, the Python interpreter is automatically set to a reasonable default (\texttt{py -2} or \texttt{py -3} under Windows, using the Python 3.3+ wrapper; \texttt{python2} or \texttt{python3} under other systems). +% \item The installer now creates symlinks for the numbered scripts \texttt{pythontex*.py} and \texttt{depythontex*.py}. +% \item Added Python version checking to all numbered scripts. +% \item Under Python, the type of data passed via \texttt{\string\setpythontexcontext} may now be set using YAML-style tags (\texttt{!!str}, \texttt{!!int}, \texttt{!!float}). For example, \texttt{\string\setpythontexcontext\{myint=!!int 123\}}. +% \item The \texttt{fancyvrb} options \texttt{firstline} and \texttt{lastline} now work with the \texttt{pygments} environment and \texttt{\string\inputpygments} command. This required some additional patching of \texttt{fancyvrb}. +% \item The \texttt{pytx@Verbatim} and \texttt{pytx@SaveVerbatim} environments are now used for typesetting verbatim code. These are copies of the \texttt{fancyvrb} environments. This prevents conflicts when literal \texttt{Verbatim} and \texttt{SaveVerbatim} environments need to be typeset. +% \item Improved \texttt{latexmk} compatibility (\#40). Added discussion of \texttt{latexmk} usage to documentation. +% \item Tildes \texttt{\string~} may now be used in \texttt{outputdir} and \texttt{workingdir} to refer to the user's home directory, even under Windows. +% \end{itemize} +% \textbf{Bugfixes} +% \begin{itemize} +% \item Fixed a bug that prevented created files from being cleaned up when the working directory was not the document root directory and the full path to the files was not provided. +% \item Fixed a bug that prevented the \texttt{fvextfile} option from working when external files were highlighted. +% \end{itemize} +% \end{changelog} +% +% \begin{changelog}{v0.13-beta}{2014/02/06} +% \textbf{New features} +% \begin{itemize} +% \item Switching to GitHub's Releases for downloads. +% \item TeX information such as page dimensions may now be easily passed to the programming-language side, using the new \texttt{\string\setpythontexcontext} command. Contextual information is stored in the \texttt{context} attribute of the utilities class, which is a dictionary (and also has attributes in Python). +% \item The utilities class now has \texttt{pt\_to\_in()}, \texttt{pt\_to\_cm()}, and \texttt{pt\_to\_mm()} methods for converting units of TeX points into inches, centimeters, and millimeters. These work with integers and floats, as well as strings that consist of numbers and optionally end in ``pt''. There is also a \texttt{pt\_to\_bp()} for converting TeX points (1/72.27 inch) into big (DTP or PostScript) points (1/72 inch). +% \item Expanded Quickstart. Quickstart is now compatible with all LaTeX engines. Quickstart now avoids \texttt{microtype} issues on some systems (\#32). +% \item Added information on citing PythonTeX (\#28). +% \item Utilities class has a new attribute \texttt{id}, which is a string that joins the command family name, session name, and session restart parameters with underscores. This may be used in creating files that need a name that contains a unique, session-based identifier (for example, names for figures that are saved automatically). +% \end{itemize} +% \textbf{Backward-incompatible changes} +% \begin{itemize} +% \item All utilities-class attributes with names of the form \texttt{input\_*} have been renamed with the ``\texttt{input\_}'' removed. Among other things, this makes it easier to access the \texttt{context} attribute (\texttt{pytex.context} vs.\ \texttt{pytex.input\_context}). +% \item \texttt{depythontex} now has \texttt{-o} and \texttt{-{}-output} command-line options for specifying the name of the output file. If an output file is not specified, then output is written to \texttt{stdout}. This allows \texttt{depythontex} output to be piped to another program. +% \item All scripts \texttt{*2.py} now have shebangs with \texttt{env python2}, and all scripts \texttt{*3.py} now have shebangs with \texttt{env python3}. This allows the wrapper scripts (\texttt{env python} shebang) to be used with the default Python installation, and the numbered scripts to be used with specific versions. Remember that except for console content, the \texttt{-{}-interpreter} option is what determines the Python version that actually executes code. The version of Python used to launch \texttt{pythontex.py} merely determines the version that manages code execution. (\texttt{-{}-interpreter} support for console content is coming.) +% \item Changed the template style used in the \texttt{CodeEngine} class. Replacement fields are now surrounded by single curly braces (as in Python's format string syntax), rather than double curly braces. Literal curly braces are obtained by doubling braces. This allows the use of literal adjacent double braces in templates, which was not possible previously. +% \item The Julia template now uses the new \texttt{in()} function, replacing \texttt{contains()}. This requires Julia v0.2.0+. +% \end{itemize} +% \textbf{Bugfixes} +% \begin{itemize} +% \item Modified test for LuaTeX, so that \texttt{\string\directlua} is not \texttt{\string\let} to \texttt{\string\relax} if it does not exist. This was causing incompatibility with \texttt{babel} under pdfTeX and XeTeX (\#33). +% \item Added missing shebangs to \texttt{depythontex*.py}. Handling of \texttt{utilspath} is now more forgiving, so that \texttt{pythontex\_utils.py} can be installed in alternate locations (\#23). +% \item \texttt{depythontex} no longer leaves a blank line where \texttt{\string\usepackage\{pythontex\}} was removed. +% \item Console environments typeset with \texttt{fancyvrb} no longer end with an unnecessary empty line. +% \item Fixed bug in installer when \texttt{kpsewhich} was not found (\#21). +% \end{itemize} +% \end{changelog} % % \begin{changelog}{v0.12}{2013/08/26} +% \begin{itemize} % \item Added support for the Julia language, with the \texttt{julia} and \texttt{jl} families of commands and environments. (Note that Pygments only added Julia support in version 1.6.) % \item Warnings and errors are now synchronized with the line numbers of files brought in via \texttt{\string\input}, \texttt{\string\include}, etc. This is accomplished using the \texttt{currfile} package. % \item Added package option \texttt{gobble}. When \texttt{gobble=auto}, all code is dedented before being executed and/or typeset. The current implementation is functional but basic; it will be improved and extended in the future. @@ -101,9 +153,11 @@ % \item Fixed a bug with counters that caused errors when content spanning multiple columns was created within a \texttt{tabular} environment. % \item Added checking for compatible Python versions in \texttt{pythontex.py}. % \item Improved execution of \texttt{*.bat} and \texttt{*.cmd} files under Windows. The solution from v0.12beta allowed \texttt{*.bat} and \texttt{*.cmd} to be found and executed when the extension was not given, but did not give correct return codes. +% \end{itemize} % \end{changelog} % % \begin{changelog}{v0.12beta}{2013/06/24} +% \begin{itemize} % \item Merged \texttt{pythontex\_types*.py} into a single replacement \texttt{pythontex\_engines.py} compatible with both Python 2 and 3. It is now much simpler to add support for additional languages. % \item Added support for the Ruby language as a demonstration of new capabilities. The \texttt{ruby} and \texttt{rb} families of commands and environments may be enabled via the new \texttt{usefamily} package option. Support for additional languages is coming soon. See the new section in the documentation on support for other languages for more information. % \item Reimplemented treatment of Pygments content for better efficiency. Now a Pygments process only runs if there is content to highlight. Eliminated redundant highlighting of unmodified code. @@ -136,9 +190,11 @@ % \item At the end of each run, data and macros are only saved if modified, improving efficiency. % \item The number of temporary files required by each process was reduced by one. All macros for commands like \texttt{\string\py} are now returned within stdout, rather than in their own file. % \item Fixed a bug with \texttt{\string\stderrpythontex}; it was defaulting to \texttt{verb} rather than \texttt{verbatim} mode. +% \end{itemize} % \end{changelog} % % \begin{changelog}{v0.11}{2013/04/21} +% \begin{itemize} % \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. @@ -159,9 +215,11 @@ % \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{itemize} % \end{changelog} % % \begin{changelog}{v0.11beta}{2013/02/17} +% \begin{itemize} % \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. @@ -170,9 +228,11 @@ % \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{itemize} % \end{changelog} % % \begin{changelog}{v0.10beta2}{2013/01/23} +% \begin{itemize} % \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}. @@ -181,9 +241,11 @@ % \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{itemize} % \end{changelog} % % \begin{changelog}{v0.10beta}{2013/01/09} +% \begin{itemize} % \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. @@ -212,9 +274,11 @@ % \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{itemize} % \end{changelog} % % \begin{changelog}{v0.9beta3}{2012/07/17} +% \begin{itemize} % \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. @@ -224,14 +288,19 @@ % \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{itemize} % \end{changelog} % % \begin{changelog}{v0.9beta2}{2012/05/09} +% \begin{itemize} % \item Changed Python output extension to .stdout. +% \end{itemize} % \end{changelog} % % \begin{changelog}{v0.9beta}{2012/04/27} +% \begin{itemize} % \item Initial public beta release. +% \end{itemize} % \end{changelog} % % @@ -258,7 +327,7 @@ % % 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, adding basic support for an additional language is usually as simple as creating a new class instance and a few templates, usually totaling less than 100 lines of code. The following languages are already have built-in support: Ruby. +% While Python is the focus of \pytex, adding basic support for an additional language is usually as simple as creating a new class instance and a few templates, usually totaling less than 100 lines of code. The following languages already have built-in support: Ruby and Julia. % \end{abstract} % % @@ -310,13 +379,21 @@ % 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! In many cases, adding support for additional languages is relatively simple (see Section~\ref{sec:other-languages}). % % +% \section{Citing \pytex} +% \label{sec:citing} +% +% If you use \pytex\ in your writing and research, please consider citing it in any resulting publications. Currently, the best paper to cite is the one published in the 2013 SciPy proceedings. Several additional papers about \pytex\ are now under review or in preparation; this list will be edited when they are published. +% \begin{itemize} +% \item ``Reproducible Documents with PythonTeX,'' Geoffrey M.\ Poore. \textit{Proceedings of the 12th Python in Science Conference} (2013), pp.\ 73--79. Full text and Bib\TeX\ entry available at \url{http://conference.scipy.org/proceedings/scipy2013/poore.html}. +% \end{itemize} +% % % \section{Installing and running} % \label{sec:installing-and-running} % % \subsection{Installing \pytex} % -% \pytex\ requires a \TeX\ installation. It has been tested with \href{http://www.tug.org/texlive/}{\TeX\ Live} and \href{http://miktex.org/}{MiK\TeX}, but should work with other distributions. The following \LaTeX\ packages, with their dependencies, are required: |fancyvrb|, |etex|, |etoolbox|, |xstring|, |pgfopts|, |newfloat|, |currfile|, and |color| or |xcolor|. A current \TeX\ installation is recommended, since some features require recent versions of the packages. If you are creating and including graphics, 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 alternatives. +% \pytex\ requires a \TeX\ installation. It has been tested with \href{http://www.tug.org/texlive/}{\TeX\ Live} and \href{http://miktex.org/}{MiK\TeX}, but should work with other distributions. The following \LaTeX\ packages, with their dependencies, are required: |fancyvrb|, |etex|, |etoolbox|, |xstring|, |pgfopts|, |newfloat| (part of the |caption| bundle), |currfile|, and |color| or |xcolor|. A current \TeX\ installation is recommended, since some features require recent versions of the packages. If you are creating and including graphics, 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 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. \pytex\ is compatible with Python 2.7 and 3.2+. 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 |pythontex_gallery.tex|, 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}. % @@ -330,18 +407,23 @@ % \item Language definitions |pythontex_engines.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 Synchronized Python Debugger |syncpdb.py| % \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 installation script |pythontex_install.py| for \TeX\ Live and MiKTeX % \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. \textbf{Note that for a typical \TeX\ setup under Linux, you may need to run the script with elevated privileges, and may need to run it with the user's PATH.} This can be necessary when you are using a Linux distribution that includes an outdated version of \TeX\ Live, and have installed a new version manually. \textbf{If you are installing \pytex\ on a machine with multiple version of \TeX, make sure you install \pytex\ for the correct version.} For example, under Ubuntu Linux, you will probably need the following command if you have installed the latest version of \TeX\ Live manually: +% 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 and MiKTeX. 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. +% +% \textbf{For a MiKTeX installation, you may need administrator privileges; running \texttt{pythontex\_install.bat} as administrator may be simplest.} +% +% \textbf{Note that for a typical \TeX\ setup under Linux, you may need to run the script with elevated privileges, and may need to run it with the user's PATH.} This can be necessary when you are using a Linux distribution that includes an outdated version of \TeX\ Live, and have installed a new version manually. \textbf{If you are installing \pytex\ on a machine with multiple versions of \TeX, make sure you install \pytex\ for the correct version.} For example, under Ubuntu Linux, you will probably need the following command if you have installed the latest version of \TeX\ Live manually: % \begin{verbatim} -% sudo env PATH=$PATH python pythontex_install_texlive.py +% sudo env PATH=$PATH python pythontex_install.py % \end{verbatim} % % The installer creates the following files. It will offer to create the paths if they do not exist. If you are installing in TEXMFLOCAL, the paths will have an additional |local/| at the end. @@ -361,6 +443,7 @@ % \item |pythontex_engines.py| % \item |pythontex_utils.py| % \item |depythontex.py|, |depythontex2.py| and |depythontex3.py| +% \item |syncpdb.py| % \end{itemize} % \item \meta{\TeX\ tree root}|/source/latex/pythontex/| % \begin{itemize} @@ -376,6 +459,7 @@ % % % \subsection{Compiling documents using \pytex} +% \label{sec:installing-and-running:compiling} % % Compiling a document with \pytex\ involves three steps: running a \LaTeX-compatible \TeX\ engine (binary executable), 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. % @@ -405,6 +489,8 @@ % 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 checked for changes via their hashes or modification times. By default, mtime is used, since it is faster. The package option |hashdependencies| is equivalent. % +% \item |--jobs| This sets the maximum number of concurrent processes. By default, this will be Python's |multiprocessing.cpu_count()|, which is the number of CPUs in the system. It may be useful to set a smaller value when some jobs are particularly resource intensive or themselves use subprocesses. +% % \item |--verbose| This gives more verbose output, including a list of all processes that are launched. % % \item |--interpreter| This allows the interpreter for a given language to be specified. The argument should be in the form @@ -414,6 +500,33 @@ % where |<interpreter>| is |python|, |ruby|, etc., and |<command>| is the command for invoking the desired interpreter. The argument to |--interpreter| may also be in the form of a Python dictionary. The argument need not be enclosed in quotation marks if it contains no spaces. % % For example, by default Python code is executed with whatever interpreter the |python| command invokes. But Python 3 could be specified using |--interpreter python:python3| (many Linux distributions) or |--interpreter "python:py -3"| (Windows, with Python 3.3 installed so that the |py| wrapper is available). +% +% \item |--interactive [<family>:<session>:<restart>]| This is used to run a single session in interactive mode. This allows user input. Code output is written to stdout. Interactive mode is particularly useful when working with debuggers (but also see the |--debug| option). +% +% |[<family>:<session>:<restart>]| is optional; if it is not provided, the default session is executed. For non-default sessions (or if there are multiple default sessions, due to the use of multiple families of commands), simply supplying the session name is usually sufficient (for example, |--debug session|). The full combination of |[<family>:<session>:<restart>]| (for example, |py:session:default|) is only necessary when the session name alone would be ambiguous. +% +% Note that when a session is run in interactive mode, it will \emph{not} save printed content in a form that may be brought back into the document. You will have to run the session again in normal mode to complete document compilation. +% +% Code that requires user input will cause \pytex\ to ``hang'' when \pytex\ is not running in interactive mode. This is because the code will request user input, but no input is possible given the way that the code is being executed, so the code will wait for input forever. It is inefficient constantly to add and then delete interactive code as you switch between normal and interactive modes. To avoid this, you can conditionally invoke code that requires input. In interactive mode, the temporary script that is executed is given the command-line argument |--interactive|. You can check for the presence of this argument, and only invoke interactive code if it is present. For example, under Python you could start the |pdb| debugger, only when the code is being executed in interactive mode, using commands such as the following. +%\begin{verbatim} +%import pdb +%import sys +%if '--interactive' in sys.argv[1:]: +% pdb.set_trace() +%\end{verbatim} +% +% This option is currently not compatible with Python console commands and environments. +% +% \item |--debug [<family>:<session>:<restart>]| This is used to run a single session with the default debugger in interactive mode. Currently, only standard Python sessions are supported. (Python console commands and environments are not supported.) Support for other languages and support for customization will be added in the future. +% +% |[<family>:<session>:<restart>]| is optional; if it is not provided, the default session is executed. For non-default sessions (or if there are multiple default sessions, due to the use of multiple families of commands), simply supplying the session name is usually sufficient (for example, |--debug session|). The full combination of |[<family>:<session>:<restart>]| (for example, |py:session:default|) is only necessary when the session name alone would be ambiguous. +% +% Note that when a session is run in debug mode, it will \emph{not} save printed content in a form that may be brought back into the document. You will have to run the session again in normal mode to complete document compilation. +% +% The default Python debugger is |syncpdb|, the Synchronized Python Debugger. It provides a wrapper around |pdb| that is aware of the connection between the code and the \LaTeX\ document from which it was extracted. All |pdb| commands function normally. In addition, commands that take a line number or filename:lineno as an argument will also take these same values with a percent symbol |%| prefix. If the percent symbol is present, then |syncpdb| interprets the filename and line number as referring to the document, rather than to the code that is executed. It will translate the filename and line number to the corresponding code equivalents, and then pass these to the standard |pdb| internals. For example, the |pdb| command |list 50| would list the code that is being executed, centered around line 50. |syncpdb| allows the command |list %10|, which would list the code that is being executed, centered around the code that came from line 10 in the main \LaTeX\ document. (If no file name is given, then the main \LaTeX\ document is assumed.) If the code instead came from an inputed file |input.tex|, then |list %input.tex:10| could be used. Further details are provided at \href{https://github.com/gpoore/syncpdb}{github.com/gpoore/syncpdb}. +% +% The temporary script that is executed is given the command-line argument |--interactive| when run in debug mode. You can check for the presence of this argument if you wish to invoke code that requires user input conditionally. See the |--interactive| command-line option for more details. +% % \end{itemize} % % \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. @@ -437,7 +550,7 @@ % % \DescribeMacro{usefamily=\meta{basename}/\marg{basename1,~basename2,~...}} % -% By default, only the |py|, |sympy|, and |pylab| families of commands and environments are defined, to prevent possible package conflicts.\footnote{For example, a \texttt{\string\ruby} command for Ruby code, and the \texttt{\string\ruby} command defined by the Ruby package in the \href{http://www.ctan.org/pkg/cjk}{CJK package}.} This option defines preconfigured families for other available languages. It takes either a single language base name, or a list of comma-separated names enclosed in curly braces. Currently, the Ruby families |rb| and |ruby| may be created. +% By default, only the |py|, |sympy|, and |pylab| families of commands and environments are defined, to prevent possible package conflicts.\footnote{For example, a \texttt{\string\ruby} command for Ruby code, and the \texttt{\string\ruby} command defined by the Ruby package in the \href{http://www.ctan.org/pkg/cjk}{CJK package}.} This option defines preconfigured families for other available languages. It takes either a single language base name, or a list of comma-separated names enclosed in curly braces. Currently, the Ruby families |rb| and |ruby|, the Julia families |jl| and |julia|, and the Octave family |octave| may be created. % % % \DescribeMacro{gobble=none/auto default:none} @@ -758,6 +871,8 @@ % % All non-|console| 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 has an attribute |context|. This is a dictionary that can contain contextual information, such as page dimensions, from the \TeX\ side. Values may also be accessed as attributes rather than as dictionary keys. To determine what contextual information is available, and for additional details, see |\setpythontexcontext| under Section~\ref{sec:usage:advanced-usage}. For working with contextual data, the utilities class provides |pt_to_in()|, |pt_to_cm()|, |pt_to_mm()|, and |pt_to_bp()| methods for converting from \TeX\ points to other units. +% % 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.) @@ -768,7 +883,7 @@ % The context-sensitive interface to SymPy's |LatexPrinter| is always available via |pytex.sympy_latex()|. % \end{itemize} % -% The \pytex\ utilities formatter may 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 \pytex\ utilities formatter may 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| within a |pycode| or |pythontexcustomcode| environment. Any subsequent uses of |\py| will then use |my_func()| to perform formatting. % % The utilities class also provides methods for tracking dependencies and created files. % \begin{itemize} @@ -776,7 +891,7 @@ % % \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 |~|). Paths can use a forward slash ``|/|'' even under Windows. 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|. % -% It is possible that a dependency of one session might be modified by another session while \pytex\ runs. The first session might not be executed during the \pytex\ run because its dependency was unmodified at the beginning. A more serious case occurs when the first session does run, but we don't know whether it accessed the dependency before or after the dependency was updated (remember, sessions run in parallel). \pytex\ keeps track of the time at which it started. Any sessions with dependencies that were modified after that time are set to re-execute on the next run. A warning is also issued to indicated that this is the case. +% It is possible that a dependency of one session might be modified by another session while \pytex\ runs. The first session might not be executed during the \pytex\ run because its dependency was unmodified at the beginning. A more serious case occurs when the first session does run, but we don't know whether it accessed the dependency before or after the dependency was updated (remember, sessions run in parallel). \pytex\ keeps track of the time at which it started. Any sessions with dependencies that were modified after that time are set to re-execute on the next run. A warning is also issued to indicate that this is the case. % % \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. % @@ -785,20 +900,28 @@ % 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 for tracking files 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). For example, the following would create a version of the standard |open()| that automatically tracks dependencies and created files. +% These two methods for tracking files 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). For this reason, the \pytex\ utilities class provides an |open()| method that automatically tracks dependencies and created files. +% \begin{itemize} +% \item |pytex.open(|\meta{file}|, |\meta{mode}|, |\meta{args}|, | \meta{kwargs}|)| This method automatically tracks all files opened for reading (text or binary mode) as dependencies. It automatically tracks all files opened for writing (text or binary mode) as created files. Files opened for updating and appending will raise a warning, since it is not necessarily obvious how these files should be treated. The general form of the custom |open()| function is shown below. % \begin{verbatim} -%def track_open(file, mode='r', *args, **kwargs): -% if mode in ('r', 'rb'): -% pytex.add_dependencies(file) -% elif mode in ('w', 'wb'): -% pytex.add_created(file) -% return open(file, mode, *args, **kwargs) -%pytex.open = track_open +%def track_open(name, mode='r', *args, **kwargs): +% if mode in ('r', 'rt', 'rb'): +% pytex.add_dependencies(name) +% elif mode in ('w', 'wt', 'wb'): +% pytex.add_created(name) +% else: +% warnings.warn('Unsupported mode {0} for file tracking'.format(mode)) +% return open(name, mode, *args, **kwargs) % \end{verbatim} -% Notice that this approach does not deal with files opened for appending or updating; such cases require more complex logic. +% \textbf{Unicode note for Python 2:} By default, |pytex.open()| call the standard Python 2 |open()|. If more than 3 positional arguments are used, or if the |encoding| keyword is used, then \href{https://docs.python.org/2/library/io.html}{\texttt{io.open()}} will be called instead. So if you are working with Unicode, make sure to specify an encoding in |pytex.open()| so that |io.open()| will be used, or manually encode/decode everything. +% \end{itemize} % % The utilities class provides a pair of methods, |before()| and |after()|, that are called immediately before and after each chunk of user code. These may be redefined to customize the output of user code. For example, \LaTeX\ commands could be printed at the beginning and end of each command or environment, wrapping any content printed by the user. Or any matplotlib figures that were created in the chunk of code could be detected and saved, and \LaTeX\ commands to include them in the document could be printed. Or stdout could be redirected to a StringIO stream in |before()|, then processed in |after()| before being sent to the original stdout. % +% The |before()| and |after()| methods may be redefined in any code or block command or environment, using the techniques described below. Once they have been redefined, the new methods will be called for all subsequent commands and environments. When redefining these methods, it is important to realize that the order of redefinition may be important. For example, if the new |before()| and |after()| depend upon one another, then you should call the old |after()| (if it does anything), then redefine the methods, and finally call the new |before()|. This is necessary because |after()| will be called after the end of the command or environment in which redefinition takes place. If |after()| has been redefined so that it depends on the new |before()|, and the new |before()| has not yet been called, errors will likely result. Other methods of dealing with this scenario, involving disabling |before()| and |after()| for a given command or environment, are being considered as potential features for a future release. +% +% When redefining |before()| and |after()|, you may wish to have behavior that is command- or environment-specific. Information about the current command or environment is available in |pytex.command|. The string |i| corresponds to an inline command such as |\py|; |b|, to an inline block such as |\pyb|; |c|, to inline code such as |\pyc|. Similarly, |code| corresponds to a code environment and |block| to a block environment. +% % You may redefine |before()| and |after()| at the class level. For example, % \begin{verbatim} %def open(self): @@ -823,8 +946,7 @@ % An example of using the |after()| method to automatically save and include all matplotlib figures created in a command or environment is shown below. This example is designed for the |pylab| family of commands, or when |from pylab import *| is used. If |pyplot| is imported as |plt| instead, then |plt.get_fignums()|, |plt.figure()|, |plt.savefig()|, |plt.close()|, etc., would be needed. % \begin{verbatim} %# Basename for figures that will be created -%pytex.basename = '_'.join([pytex.input_type, pytex.input_session, -% pytex.input_restart]) +%pytex.basename = '_'.join([pytex.family, pytex.session, pytex.restart]) % %# Need to keep track of total number of figures in each session %pytex.fignum = 0 @@ -1020,6 +1142,29 @@ % % % \subsection{Advanced \pytex\ usage} +% \label{sec:usage:advanced-usage} +% +% \DescribeMacro{\setpythontexcontext\marg{key-value~pairs}} +% +% This macro is used for passing contextual information such as page dimensions from the \TeX\ side to the Python/other language side. \meta{key-value~pairs} is a set of comma-delimited key-value pairs. An evaluated version of \meta{key-value~pairs} is passed to the programming language, wrapped in quotation marks to become a string. Thus, \meta{key-value~pairs} should \emph{not} contain quotation marks, backslashes, or other characters that would prevent the evaluated contents from being the body of a normal, quoted string. +% +% As an example, the following would pass the values of |\textwidth| and |\textheight| to the Python side. +%\begin{verbatim} +%\setpythontexcontext{textwidth=\the\textwidth, textheight=\the\textheight} +%\end{verbatim} +% Python would receive a string something like |"textwidth=390pt, textheight=592pt"|. This string would be parsed into key-value pairs, and the results stored in the |pytex.context| dictionary. For Python, the keys also become the names of attributes of |pytex.context|. Thus, the values may be accessed on the Python side via |pytex.context['textwidth']|, |pytex.context.textwidth|, etc. +% +% All contextual data is available as strings on the Python/other language side. For convenience, the utilities class provides unit conversion methods for converting from \TeX\ points to inches, centimeters, millimeters, and big (DTP or PostScript) points. These methods take integers, floats, or strings that consist of digits (optionally ending in ``pt''), and return floats. For example, |pytex.pt_to_in()|, |pytex.pt_to_cm()|, |pytex.pt_to_mm()|, |pytex.pt_to_bp()|. Keep in mind that the units of \TeX\ points are \href{http://tex.stackexchange.com/questions/41370/what-are-the-possible-dimensions-sizes-units-latex-understands}{$1/72.27$} of an inch, \emph{not} $1/72$ of an inch (which is a bp). +% +% There is also a type system for Python that allows the types of \meta{values} to be specified. Any \meta{value} beginning with |!!int| will become an integer; with |!!float|, a float; with |!!str|, a string. This notation is borrowed from \href{http://yaml.org/}{YAML}. For example, +%\begin{verbatim} +%\setpythontexcontext{a=!!int 42, b=!!float 42, c=!!str 42} +%\end{verbatim} +% \textbf{This type system is still under development and is subject to change in the future.} Once the system stabilizes, it will be extended to non-Python languages. Comments on the type system are welcome. +% +% The context may only be set in the preamble. +% +% Technical note: Contextual data is cached, so the dictionary (and its attributes, if applicable) is only updated when contextual data changes. This largely eliminates any potential overhead from contextual data. % % \DescribeMacro{\restartpythontexsession\marg{counter~value(s)}} % @@ -1037,13 +1182,13 @@ % % 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.} % -% Any slashes in \meta{output~directory} should be forward slashes ``|/|'' (even under Windows). +% Any slashes in \meta{output~directory} should be forward slashes ``|/|'' (even under Windows). Tildes |~| may be used to refer to the user's home directory, including under Windows. % % \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{.}|. % -% Any slashes in \meta{working~directory} should be forward slashes ``|/|'' (even under Windows). +% Any slashes in \meta{working~directory} should be forward slashes ``|/|'' (even under Windows). Tildes |~| may be used to refer to the user's home directory, including under Windows. % % The working directory is automatically added to Python's |sys.path|, so that code in the working directory there may be imported without a path being specified. % @@ -1052,6 +1197,28 @@ % It is also possible to change the working directory from within Python code, via |os.chdir()|. % % +% \subsection{Working with other programs} +% +% \subsubsection{\texttt{latexmk}} +% +% \pytex\ is compatible with |latexmk|. If you are compiling in the same location as the document source (if you are \emph{not} using |-auxdir|, |-outdir|, or |$out_dir|, or alternatively |TEXINPUTS|), then adding a simple rule such as the following to your |.latexmkrc| should usually be sufficient. +%\begin{verbatim} +%add_cus_dep('pytxcode', 'tex', 0, 'pythontex'); +%sub pythontex { return system("pythontex \"$_[0]\""); } +%\end{verbatim} +% This tells |latexmk| that the document (|tex|) depends on the file of code extracted from the document (|pytxcode|).\footnote{This is a slightly atypical use, if not a ``misuse,'' of \texttt{add\_cus\_dep()}. In the standard usage, the first argument is the extension of a file that is used to create another file with the extension given in the second argument, via the rule named in the fourth argument. In this case, we just want to run the rule whenever files with the first extension are modified. The extension given in the second argument is irrelevant, so long as a file with the document name and that extension exists. Since the \texttt{tex} file itself will exist, its extension is a logical choice for the second argument.} Whenever the document is compiled, the file of code is updated. If |latexmk| detects that the code changed, then it will run \pytex. When \pytex\ runs, it will modify at least one file that is brought into the document. |latexmk| will detect this modification, and automatically recompile the document. +% +% If you are compiling to a different directory (using |-auxdir|, |-outdir|, or |$out_dir|, or alternatively |TEXINPUTS|), then this rule may fail due to the different directory configuration. In that case, you should use |\setpythontexoutputdir{.}| so that \pytex\ will store its output in the current default location, rather than in a subdirectory, to ensure that |latexmk| will locate the output files. Since the |tex| source is no longer in the location of the compiled output, you also need a different dependency specification. It is probably simplest to use the |pytxmcr| file that \pytex\ always generates. +%\begin{verbatim} +%add_cus_dep('pytxcode','pytxmcr',0,'pythontex'); +%sub pythontex { return system("pythontex.py \"$_[0]\""); } +%\end{verbatim} +% Note that this configuration should \emph{always} work, but has the disadvantage of requiring that \pytex\ not use a subdirectory to isolate the files it automatically generates. +% +% If you are using the |rerun=always| setting, the above rules will fail to run \pytex\ on each and every compile; in that situation, you should configure your |.latexmkrc| so that \pytex\ always runs after the first \LaTeX\ run. +% +% +% % \section{\texttt{depythontex}} % \label{sec:depythontex} % @@ -1089,7 +1256,7 @@ % % \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 |--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. % @@ -1101,8 +1268,8 @@ % 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 |--graphicspath| This option adds the |outputdir| to any existing graphics path defined by |\graphicspath|, or adds a |\graphicspath| command if one does not already exist. This causes the |depythontex| document to automatically look in the |outputdir| for graphics. Only use this option if you want to continue using the |outputdir| with the |depythontex| document. Graphics are further discussed below. +% \item |-o| |--output| The name of the output file. If no name is given, the converted file is written to |stdout|. % \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. % @@ -1213,7 +1380,7 @@ % % Support for Ruby was added in v0.12. Ruby support should be almost at the same level as that for Python. % -% The utilities class is called |RubyTeXUtils|, and the class instance is |rbtex|. The variables and methods are the same as those for Python (Section~\ref{sec:usage:commands:utilities-class}), except that there is not currently a |set_formatter()| method. (The Python utilities class has the special SymPy formatter, but there aren't yet any specialized formatters for Ruby.) +% The utilities class is called |RubyTeXUtils|, and the class instance is |rbtex|. The variables and methods are the same as those for Python (Section~\ref{sec:usage:commands:utilities-class}), except that there is not currently a |set_formatter()| or an |open()| method. (The Python utilities class has the special SymPy formatter, but there aren't yet any specialized formatters for Ruby.) % % A family of commands and environments for Ruby is not created by default. Two base names are provided for families: |ruby| and |rb|. Preconfigured families for these names may be created via the |usefamily| package option. Keep in mind that a |ruby| command is defined as part of the Ruby package in the \href{http://www.ctan.org/pkg/cjk}{CJK package}. I am unaware of a package that provides an |\rb| command. % @@ -1224,13 +1391,29 @@ % % Support for Julia was added in v0.12. Julia support should be at almost the same level as that for Python. The format of Julia stderr is somethat different from that of Python and Ruby. This required a modified parsing and synchronization algorithm. The current system is functional but will likely change somewhat in the future. % -% The utilities class is called |JuliaTeXUtils|, and the class instance is |jltex|. The variables and methods are the same as those for Python (Section~\ref{sec:usage:commands:utilities-class}), except that there is not currently a |set_formatter()| method. (The Python utilities class has the special SymPy formatter, but there aren't yet any specialized formatters for Julia.) +% The utilities ``class'' is called |JuliaTeXUtils| (it is actually a composite type, very similar to a struct), and the ``class'' instance is |jltex|. The variables and methods are the same as those for Python (Section~\ref{sec:usage:commands:utilities-class}), except that there is not currently a |set_formatter()| method or an |open()| method. (The Python utilities class has the special SymPy formatter, but there aren't yet any specialized formatters for Julia.) % -% A family of commands and environments for Ruby is not created by default. Two base names are provided for families: |julia| and |jl|. Preconfigured families for these names may be created via the |usefamily| package option. Keep in mind that Pygments only added Julia support in version 1.6, so you may need to update your Pygments installation, or just change the default lexer. +% A family of commands and environments for Julia is not created by default. Two base names are provided for families: |julia| and |jl|. Preconfigured families for these names may be created via the |usefamily| package option. Keep in mind that Pygments only added Julia support in version 1.6, so you may need to update your Pygments installation, or just change the default lexer. % % Julia exceptions are synchronized with the document, but the line numbering does not always correspond to the Python equivalent. This is because Julia allows expressions to be continued on subsequent lines in ways that Python does not. % % +% \subsection{Octave} +% +% Support for Octave was added in v0.13. Octave support should be at almost the same level as that for Python. Parsing of stderr for synchronization is successful in most cases but not ideal; this will be improved in a future release by a rewrite of the stderr parser. +% +% Octave does not have a genuine utilities class, since it only supports |@CLASS| classes and does not yet support newer MATLAB-style |classdef|. As a result of this limited support for classes, there is a struct |octavetex| rather than a utilities class instance |octavetex|. What would have been attributes of a utilities class instance are instead fields of the struct. What would have been methods of a class are instead anonymous functions. This allows |octavetex| to be used in most respects as if it were a class instance, especially insofar as syntax is concerned. +% +% There are no |set_formatter()| or |open()| methods. +% +% If any ``methods'' need to be overwritten, the simplest approach is probably to define a function and then set the appropriate struct field to an anonymous function that will call that function. For example, to replace the default |octavetex.before()|, we might define a function |before()|, and then use the command |octavetex.before = @() before();|. Of course, if the function is sufficiently short, it will be simpler just to put everything in the anonymous function: |octavetex.before = @() <expression>;| +% +% A family of commands and environments for Octave is not created by default; the base name |octave| is provided. +% +% When |\setpythontexcontext| is used, it must be accessed as struct fields, of the form |octavetex.context.<name>|. +% +% +% % \subsection{Adding support for a new language} % % Adding support for an additional language involves creating two templates, creating a new instance of a class, and using a \pytex\ macro. In some cases, additional changes may be necessary for full support. The information below does not deal with creating |console| families; additional support for user-defined |console| families will be added in the future. @@ -1241,13 +1424,13 @@ % % \subsubsection{Template} % -% \pytex\ executes user code by inserting it in a script template. Replacement fields in the template are indicated by double curly braces: |{{|\meta{field}|}}|. Space between \meta{field} and the braces is allowed; |{{ |\meta{field}| }}| is valid. Replacement fields (\textbf{including} the braces) should be surrounded by quotation marks or equivalent when the replacement is to be a string rather than literal code. +% \pytex\ executes user code by inserting it in a script template. Replacement fields in the template are indicated by curly braces: |{|\meta{field}|}|.\footnote{This follows Python's \href{http://docs.python.org/2/library/string.html\#formatstrings}{format string syntax}. Literal curly braces are obtained by doubling.} Space between \meta{field} and the braces is not allowed. Replacement fields (\textbf{including} the braces) should be surrounded by quotation marks or equivalent when the replacement is to be a string rather than literal code. % % The template should perform the following tasks. % \begin{itemize} -% \item Set the script encoding. The |{{encoding}}| field will be replaced with a user-specified encoding or the default |UTF-8|. If you are not using anything beyond ASCII, this is not strictly necessary. -% \item Python templates should have a |{{future}}| field at the beginning, for compability with Python 2 and the package option |pyfuture|.\footnote{The beginning of user code is parsed for imports from \texttt{\_\_future\_\_}. Any imports are collected and inserted into the \texttt{\{\{future\}\}} field.} -% \item Set the |stdout| and |stderr| encoding, again using |{{encoding}}|. As before, this is not strictly necessary when only ASCII support is needed. +% \item Set the script encoding. The |{encoding}| field will be replaced with a user-specified encoding or the default |UTF-8|. If you are not using anything beyond ASCII, this is not strictly necessary. +% \item Python templates should have a |{future}| field at the beginning, for compability with Python 2 and the package option |pyfuture|.\footnote{The beginning of user code is parsed for imports from \texttt{\_\_future\_\_}. Any imports are collected and inserted into the \texttt{\{\{future\}\}} field.} +% \item Set the |stdout| and |stderr| encoding, again using |{encoding}|. As before, this is not strictly necessary when only ASCII support is needed. % \item Create a language-specific equivalent of the \pytex\ utilities class.\footnote{Python templates can import the \pytex\ utilities class. In that case, \texttt{sys.path.append('\{\{utilspath\}\}')} is needed before the import, so that the location of the utilities class is known.} Create an instance of this class. It is recommended that the class be called \meta{language~name}|TeXUtils| and the instance \meta{language~extension}|tex|, by analogy with the Python case.\footnote{The class could be called \meta{language~name}\texttt{TeX}. In that case, the class and the instance would have the very same name (except for capitalization) in cases where the language name and extension are the same (for example, Lua). That is probably not desirable, and besides, \texttt{Utils} adds additional clarity. The instance name \meta{language~extension}\texttt{tex} is recommended because it will be short and easily remembered. Plain \texttt{tex} could be used instead, but that would be less descriptive (it lacks the interface connotations) and would not remind the user of the language currently in use (which could be beneficial in a document combining multiple languages, each with its own slightly different utilities class).} When the \meta{language~extension} is only a single character or is shared by multiple languages, it may be better to use the full \meta{language~name} or an abbreviation in the name of the class instance. % % For full \pytex\ support, the utilities class should provide the following methods: @@ -1255,26 +1438,28 @@ % \item |formatter()|: For formatting content for inline commands equivalent to |\py|. This should take a single argument of any type. By default, it should return a standard string representation of its argument. % \item |before()| and |after()|: Initially, these should do nothing; they are provided to be redefined by the user. They should take no arguments. % \item |add_dependencies()| and |add_created()|: These should accept an arbitrary number of comma-separated strings (if supported by the language). Each method should append its arguments to a list or equivalent data structure, for later use. -% \item |cleanup()|: This prints a dependencies delimiter string |{{dependencies_delim}}| to |stdout|, then prints all dependencies (one per line), then prints a created files delimiter string |{{created_delim}}|, then prints all created files (one per line). The delimiters should be printed even if there are no dependencies or created files. The delimiters contain no backslashes or quotes. +% \item |cleanup()|: This prints a dependencies delimiter string |{dependencies_delim}| to |stdout|, then prints all dependencies (one per line), then prints a created files delimiter string |{created_delim}|, then prints the names of all created files (one per line). The delimiters should be printed even if there are no dependencies or created files. The delimiters contain no backslashes or quotes. % \end{itemize} % The utilities class should also provide several variables, as described below. -% \item Attempt to change to the working directory |{{workingdir}}|. Raise an error and exit if this is not possible. For convenience, the script should check for a |--manual| command line argument. If this argument is present, the script should proceed even if the working directory cannot be found. This allows the user to manually invoke the script for debugging (the script can be saved via |keeptemps|). +% \item Attempt to change to the working directory |{workingdir}|. Raise an error and exit if this is not possible. For convenience, the script should check for a |--manual| command line argument. If this argument is present, the script should proceed even if the working directory cannot be found. This allows the user to manually invoke the script for debugging (the script can be saved via |keeptemps|). % % The working directory should be added to the module search path (Python |sys.path|, Ruby |$:| or |$LOAD_PATH|, etc.), unless it is the same as the document root directory or is otherwise already on the module search path. -% \item For full compatibility, the template should have an |{{extend}}| field where additional module imports or other code may be inserted. This allows a basic template to be a created for each language. The basic template may then be customized for specific purposes. The |{{extend}}| field should be after the utilities class instance has been created, so that the workings of the utilities class (|formatter()|, |before()|, |after()|, etc.) may be customized by it. -% \item \LaTeX-related variables of the utilities class instance that do not change should be set. These use the fields |{{input_family}}|, |{{input_session}}|, and |{{input_restart}}|; all should be strings. These variables should be named after the fields if possible (for example, |pytex.input_family|). These variables are not strictly necessary, but they allow user code to access information about its \LaTeX\ context. -% \item There should be a |{{body}}| field where the body of the script is inserted. +% \item For full compatibility, the template should have an |{extend}| field where additional module imports or other code may be inserted. This allows a basic template to be a created for each language. The basic template may then be customized for specific purposes. The |{extend}| field should be after the utilities class instance has been created, so that the workings of the utilities class (|formatter()|, |before()|, |after()|, etc.) may be customized by it. +% \item \LaTeX-related variables of the utilities class instance that do not change should be set. These use the fields |{family}|, |{session}|, and |{restart}|; all should be strings. These variables should be named after the fields if possible (for example, |pytex.family|). These variables are not strictly necessary, but they allow user code to access information about its origin on the \TeX\ side. +% \item There should be a |{body}| field where the body of the script is inserted. % \item The script should end by calling the |cleanup()| method. % \end{itemize} % % \subsubsection{Wrapper} % Each chunk of user code is inserted into a wrapper template. This performs the following tasks. % \begin{itemize} -% \item Set additional \LaTeX-related utilities variables: |{{input_command}}|, |{{input_context}}|, |{{input_args}}|, |{{input_instance}}|, |{{input_line}}|. All of these should be strings. They are not required, but make possible closer \LaTeX\ integration. |{{input_context}}| and |{{input_args}}| are not yet supported on the \LaTeX\ side, but will allow information about the \LaTeX\ context (for example, page width) and arguments from \LaTeX\ commands to be passed to user code. -% \item Write a delimiter |{{stdout_delim}}| to |stdout| and a delimiter |{{stderr_delim}}| to |stderr|. Both delimiters should be strings. Both should be written in such a way that the delimiter is followed by a newline; the delimiters that are inserted in the wrapper template \textbf{do not} contain a newline. For example, something like |"{{stderr_delim}}\n"| might be necessary. The delimiters contain no backslashes or quotation marks. +% \item Set additional \LaTeX-related utilities variables: |{command}|, |{context}|, |{args}|, |{instance}|, |{line}|. They are not required, but make possible closer \LaTeX\ integration. |{args}| is not yet supported on the \LaTeX\ side, but will allow arguments from \LaTeX\ commands to be passed to user code. +% +% All utilities variables should be stored as strings, except for |context| and |args|. If possible, these should be dictionaries or equivalent associative arrays of string keys that point to string values. The dictionaries should be created by processing |{context}| and |{args}| into comma-separated lists of key-value pairs. For example, if |{context}| is the string ``|k1=v1, k2=v2|'', then |pytex.context| should be a dictionary, and |pytex.context['k1']| should yield the string ``|v1|''. The key-value pairs may optionally be accessed as attributes, when this is possible with a given language. For example, |pytex.context.k1| could yield the string ``|v1|''. +% \item Write a delimiter |{stdoutdelim}| to |stdout| and a delimiter |{stderrdelim}| to |stderr|. Both delimiters should be strings. Both should be written in such a way that the delimiter is followed by a newline; the delimiters that are inserted in the wrapper template \textbf{do not} contain a newline.\footnote{This way, we don't have to assume that all languages will use \texttt{\string\n} for the newline character.} For example, something like |"{stderrdelim}\n"| might be necessary. The delimiters contain no backslashes or quotation marks. % \item Call |before()|. -% \item Have a |{{code}}| field into which the current chunk of user code is inserted. -% \item Call |after()|. For languages like Ruby that allow statements to continue onto subsequent lines, without enclosing parentheses or other delimiters, the call to |after()| should immediately follow user code, without any intervenening empty lines. That way, any syntax errors from the last line of user code will be caught as early as possible, and the corresponding line numbers will be more meaningful. +% \item Have a |{code}| field into which the current chunk of user code is inserted. +% \item Call |after()|. % \end{itemize} % % \subsubsection{The \texttt{CodeEngine} class} @@ -1285,28 +1470,28 @@ % \item The instance name. This will be the base name for commands and environments that use the instance. For example, |\py|, |\pyc|, |pycode|, etc., rely on the |py| instance of the |CodeEngine| class. % \item The name of the language. In some cases, this may be the same as the instance name. % \item The filename extension for scripts (with or without a period). -% \item The command for running scripts. The script that is executed should be referred to as ``|{{file}}.|\meta{extension}'' (without the quotes).\footnote{It might seem that the extension is redundant, since it is specified separately. The command is specified in this form to simplify cases where there may be intermediary files in the execution process.} The interpreter may be hardcoded (|python {{file}}.py|), but it is best to leave it as a substitution field (|{{python}} {{file}}.py|) so that the |--interpreter| command-line option can be used to provide a specific interpreter. +% \item The command for running scripts. The script that is executed should be referred to as ``|{file}.|\meta{extension}'' (without the quotes).\footnote{It might seem that the extension is redundant, since it is specified separately. The command is specified in this form to simplify cases where there may be intermediary files in the execution process.} The interpreter may be hardcoded (|python {file}.py|), but it is best to leave it as a substitution field (|{python} {file}.py|) so that the |--interpreter| command-line option can be used to provide a specific interpreter. % \item The script template. % \item The wrapper template. -% \item A template that specifies how code from commands like |\py| should be inserted into a call to the |formatter()| method. The user code is specified by |{{code}}|. The output of the |formatter()| method should be written to |stdout|, so something like |'print(pytex.formatter({{code}}))'| is needed. +% \item A template that specifies how code from commands like |\py| should be inserted into a call to the |formatter()| method. The user code is specified by |{code}|. The output of the |formatter()| method should be written to |stdout|, so something like |'print(pytex.formatter({code}))'| is needed. % \item An optional list of strings (or an individual string) that gives patterns for identifying error messages. % \item An optional list of strings (or an individual string) that gives patterns for identifying warning messages. -% \item An optional list of strings (or an individual string) that gives patterns for identifying code line numbers in |stderr|. These patterns use the field |{{number}}|. These patterns are searched for in any line of |stderr| that contains the name of the script that was executed. +% \item An optional list of strings (or an individual string) that gives patterns for identifying code line numbers in |stderr|. These patterns use the field |{number}|. These patterns are searched for in any line of |stderr| that contains the name of the script that was executed. % \item An optional boolean that specifies whether the engine emulates an interactive console. Currently, user-defined engines that emulate consoles are not supported. % \item An optional string of startup commands for engines that emulate consoles. -% \item An optional list of strings (or an individual string) that specifies any files created during execution, beyond the script |{{file}}.|\meta{extension}. The field |{{file}}| may be used in file names. +% \item An optional list of strings (or an individual string) that specifies any files created during execution, beyond the script |{file}.|\meta{extension}. The field |{file}| may be used in file names, if files are created with the same base name as the script; this could be useful with compiled languages, which might have a |{file}.|\meta{extension} that ultimately results in a |{file}.out|, |{file}.exe|, etc. % \end{itemize} % % An example of creating the |py| engine is shown below. The |python_template| and |python_wrapper| are long enough that they are defined separately. % \begin{verbatim} -%CodeEngine('py', 'python', '.py', 'python {{file}}.py', -% python_template, python_wrapper, -% 'print(pytex.formatter({{code}}))', -% 'Error:', 'Warning:', ['line {{number}}', ':{{number}}:']) +%CodeEngine('py', 'python', '.py', 'python {file}.py', +% python_template, python_wrapper, +% 'print(pytex.formatter({code}))', +% 'Error:', 'Warning:', ['line {number}', ':{number}:']) % \end{verbatim} % The script template and wrapper templates may be defined with Python's triple-quoted strings. All content within such a string may be indented for clarity, as can be seen in |pythontex_engines.py|. Strings are automatically dedented when |CodeEngine| instances are created. % -% In addition to the |CodeEngine| class, there is also a |SubCodeEngine| class. It allows a new engine to be created based on an existing engine. It requires the name of the engine from which to inherit and the name of the new engine. All of the other arguments listed above are optional; if any are provided, they overwrite the inherited arguments. The class also takes one additional optional argument, |extend|. This is a string that specifies additional code to be entered in the inherited template, in the |{{extend}}| field. Subengines of subengines may be created; in that case, any |extend|s are cumulative. +% In addition to the |CodeEngine| class, there is also a |SubCodeEngine| class. It allows a new engine to be created based on an existing engine. It requires the name of the engine from which to inherit and the name of the new engine. All of the other arguments listed above are optional; if any are provided, they overwrite the inherited arguments. The class also takes one additional optional argument, |extend|. This is a string that specifies additional code to be entered in the inherited template, in the |{extend}| field. Subengines of subengines may be created; in that case, any |extend|s are cumulative. % % \subsubsection{Creating the \LaTeX\ interface} % Once a new engine has been created, access from the \LaTeX\ side must be provided. \pytex\ provides a macro for this purpose. @@ -1324,9 +1509,63 @@ % \label{sec:troubleshooting} % % \begin{itemize} -% \item If a \pytex\ document will not compile, you may want to delete the directory in which \pytex\ content is stored and try compiling from scratch. It is possible for \pytex\ to become stuck in an unrecoverable loop. Suppose you tell Python to print some \LaTeX\ code back to your \LaTeX\ document, but make a fatal \LaTeX\ syntax error in the printed content. This syntax error prevents \LaTeX\ from compiling. Now suppose you realize what happened and correct the syntax error. The problem is that the corrected code cannot be executed until \LaTeX\ correctly compiles and saves the code externally, but \LaTeX\ cannot compile until the corrected code has already been executed. One solution in such cases is to correct the code, delete all files in the \pytex\ directory, compile the \LaTeX\ document, and then run \pytex\ from scratch. You can also disable the inclusion of printed content using the |debug| package options. +% \item If a \pytex\ document will not compile, you may want to delete the directory in which \pytex\ content is stored and try compiling from scratch. It is possible for \pytex\ to become stuck in an unrecoverable loop. Suppose you tell Python to print some \LaTeX\ code back to your \LaTeX\ document, but make a fatal \LaTeX\ syntax error in the printed content. This syntax error prevents \LaTeX\ from compiling. Now suppose you realize what happened and correct the syntax error. The problem is that the corrected code cannot be executed until \LaTeX\ correctly compiles and saves the code externally, but \LaTeX\ cannot compile until the corrected code has already been executed. One solution in such cases is to correct the code, delete all files in the \pytex\ directory, compile the \LaTeX\ document, and then run \pytex\ from scratch. You can also disable the inclusion of printed content using the |debug| package option. +% +% You may also run \pytex\ with the |--debug| option to launch the default debugger, or use the debugger of your choice by adding code that launches a debugger and then running \pytex\ with the |--interactive| option. See Section~\ref{sec:installing-and-running:compiling} for more details. % % \item Dollar signs \$ may appear as \textsterling\ in italic code comments typeset by Pygments. This is a font-related issue. One fix is to |\usepackage[T1]{fontenc}|. +% +% \item The |tabular| environment can conflict with \pytex\ under some circumstances, due to how |tabular| functions. Among other things, printing within a |tabular| environment can cause errors, because printing involves bringing in external content via |\InputIfFileExists|, but that macro is not expandable.\footnote{For more information, see \href{http://tex.stackexchange.com/questions/50820/expandable-version-of-inputiffileexists-or-iffileexists}{this}, \href{http://tex.stackexchange.com/questions/50828/execute-non-expandable-code-inside-a-tabular-environment}{this}, and \href{http://tex.stackexchange.com/questions/50694/cannot-use-toprule-when-doing-input-inside-tabular-why}{this}.} There are a few different ways to work around the limitations of |tabular|. +% \begin{itemize} +%\item Put the printed content in a macro definition, and use the macro in |tabular|. You will have to create a dummy version of the macro, to avoid errors before the macro is defined by \pytex. An example is given below. The |\global\def| is needed so that the macro is defined outside of the |pycode| environment. +%\begin{verbatim} +%\let\row\relax +%\begin{pycode} +%print("\\global\\def\\row{a & b & c & d & e \\\\}") +%\end{pycode} +% +%\begin{tabular}{|c|c|c|c|c|} +%\row +%\end{tabular} +%\end{verbatim} +% +% \item Use |\py|. The end-of-row |\\| must be outside of the command. Example: +%\begin{verbatim} +%\begin{tabular}{|c|c|c|c|c|} +%\py{"a & b & c & d & e"} \\ +%\end{tabular} +%\end{verbatim} +% \end{itemize} +% \item \pytex\ commands like |\py| won't work inside |siunitx| macros, because |\py| and company aren't fully expandable.\footnote{For more details, see \href{http://tex.stackexchange.com/questions/35039/why-isnt-everything-expandable}{this}, \href{http://tex.stackexchange.com/questions/66118/advantages-and-disadvantages-of-fully-expandable-macros}{this}, and \href{http://tex.stackexchange.com/questions/164918/how-do-i-use-ifstreqcase-within-a-siunitx-command}{this}.} There are different ways to work around this; some examples are shown below. +%\begin{verbatim} +%\documentclass{article} +%\usepackage{siunitx} +%\usepackage{pythontex} +% +%\begin{pycode} +%def SI(var, unit): +% return '\\SI{' + str(var) + '}{' + unit + '}' +%\end{pycode} +% +%\newcommand{\pySI}[2]{\py{'\\SI{' + str(#1) + '}{#2}'}} +% +%\begin{document} +%\pyc{y = 4} +% +%The value of y is \py{SI(y, r'\metre')}. +% +%The value of y is \pySI{y}{\metre}. +% +%\end{document} +%\end{verbatim} +% Another example, this time using SymPy: +%\begin{verbatim} +%\newcommand{\sympySI}[2]{\sympy{SI(#1,r"#2")}} +%\begin{sympycode} +%def SI(var, unit): +% return '\\SI{{{0}}}{{{1}}}'.format(N(var, 4), unit) +%\end{sympycode} +%\end{verbatim} % \end{itemize} % % @@ -1350,7 +1589,7 @@ % \item Improved testing framework. % \item It might nice to include some methods in the \pytex\ utilities for formatting numbers (especially with SymPy and Pylab). % \item Test the behavior of files brought in via |\input| and |\include| that contain \pytex\ content. -% \item Continue adding support for additional languages. In preparation: Julia. Under consideration: Perl, Lua, MATLAB, Mathematica, Sage, R, Octave. +% \item Continue adding support for additional languages. Under consideration: Perl, Lua, MATLAB, Mathematica, Sage, R, Octave. % \end{itemize} % % \subsubsection{Modifications to consider} @@ -1399,7 +1638,7 @@ % We store the name of the package in a macro for later use in warnings and error messages. % \begin{macrocode} \newcommand{\pytx@packagename}{PythonTeX} -\newcommand{\pytx@packageversion}{v0.12} +\newcommand{\pytx@packageversion}{v0.13} % \end{macrocode} % % \subsection{Required packages} @@ -1833,7 +2072,7 @@ % % This prevents the creation of unnecessary files, but it also has a significant drawback: only some content can be saved in a standard macro. In particular, verbatim content using |\verb| and |verbatim| will not work. So we need a way to save anything in a macro. The solution is to create a special macro that captures its argument verbatim. The argument is then tokenized when it is used via |\scantokens|. All of this requires a certain amount of catcode trickery. % -% While this approach works with the XeTeX and pdfTeX engines, it does not work with the LuaTeX engine, which has a known bug in its implementation of |\scantokens|.\footnote{\url{http://tracker.luatex.org/view.php?id=733}} So we provide a separate version for Lua\TeX\ that does not support verbatim. The space after the |#1| is intentional, so that the newline at the beginning of the macro definition is gobbled, and the macro content will start with text rather than leading whitespace. +% While this approach works with the XeTeX and pdfTeX engines, it does not work with the LuaTeX engine, which has a known bug in its implementation of |\scantokens|.\footnote{\url{http://tracker.luatex.org/view.php?id=733}} So we provide a separate version for Lua\TeX\ that does not support verbatim. The space after the |#1| is intentional, so that the newline at the beginning of the macro definition is gobbled, and the macro content will start with text rather than leading whitespace. Two separate tests for LuaTeX are performed: comparison with an undefined macro |\pytx@undefined|, which will work under most circumstances, and comparison with |\relax|, which serves as a backup in case a test for LuaTeX by another package |\let|'s |\directlua| to |\relax| (for example, an |\expandafter\ifx\csname directlua\endcsname\relax| test). % % \begin{macrocode} \def\pytx@SVMCR#1{% @@ -1851,7 +2090,15 @@ !expandafter!scantokens!expandafter{#1!empty}}% }% !endgroup -\expandafter\ifx\csname directlua\endcsname\relax\else +\ifx\directlua\pytx@undefined\else +\def\pytx@SVMCR#1 {% + \edef\pytx@tmp{\csname #1\endcsname}% + \pytx@SVMCR@i} +\long\def\pytx@SVMCR@i#1\endpytx@SVMCR{% + \expandafter\gdef\pytx@tmp{#1}% +} +\fi +\ifx\directlua\relax\else \def\pytx@SVMCR#1 {% \edef\pytx@tmp{\csname #1\endcsname}% \pytx@SVMCR@i} @@ -1861,22 +2108,32 @@ \fi % \end{macrocode}\end{macro} % +% \begin{macro}{pytx@Verbatim} +% \begin{macro}{pytx@SaveVerbatim} +% We need custom versions of |fancyvrb|'s |Verbatim| and |SaveVerbatim| environments, because we don't want to have to worry about the possibility of these environments containing literal |Verbatim| and |SaveVerbatim| environments. +% \begin{macrocode} +\DefineVerbatimEnvironment{pytx@Verbatim}{Verbatim}{} +\DefineVerbatimEnvironment{pytx@SaveVerbatim}{SaveVerbatim}{} +% \end{macrocode} +% \end{macro}\end{macro} +% % % \subsubsection{Code context} -% \begin{macro}{\pytx@context}\begin{macro}{\pytx@SetContext}\begin{macro}{\definepythontexcontext} +% \begin{macro}{\pytx@context}\begin{macro}{\pytx@SetContext}\begin{macro}{\setpythontexcontext} % It would be nice if when our code is executed, we could know something about its context, such as the style of its surroundings or information about page size. % -% By default, no contextual information is passed to \LaTeX. There is a wide variety of information that could be passed, but most use cases would only need a very specific subset. Instead, the user can customize what information is passed to \LaTeX. The |\definepythontexcontext| macro defines what is passed. It creates the |\pytx@SetContext| macro, which creates |\pytx@context|, in which the expanded context information is stored. The context should only be defined in the preamble, so that it is consistent throughout the document. +% By default, no contextual information is passed to \LaTeX. There is a wide variety of information that could be passed, but most use cases would only need a very specific subset. Instead, the user can customize what information is passed to \LaTeX. The |\setpythontexcontext| macro defines what is passed. It creates the |\pytx@SetContext| macro, which creates |\pytx@context|, in which the expanded context information is stored. The context should only be defined in the preamble, so that it is consistent throughout the document. % % If you are interested in typesetting mathematics based on math styles, you should use the |\mathchoice| macro rather than attempting to pass contextual information. % \begin{macrocode} -\newcommand{\definepythontexcontext}[1]{% +\newcommand{\setpythontexcontext}[1]{% + \Depythontex{cmd:setpythontexcontext:m:n}% \def\pytx@SetContext{% \edef\pytx@context{#1}% }% } -\definepythontexcontext{} -\@onlypreamble\definepythontexcontext +\setpythontexcontext{} +\@onlypreamble\setpythontexcontext % \end{macrocode} % \end{macro}\end{macro}\end{macro} % @@ -2003,7 +2260,14 @@ % \begin{macrocode} \AtBeginDocument{% \makeatletter - \InputIfFileExists{\pytx@outputdir/\pytx@jobname.pytxmcr}{}{}% + \InputIfFileExists{\pytx@outputdir/\pytx@jobname.pytxmcr}{}% + {\ifstrempty{\pytx@outputdir}% + {\typeout{No file \pytx@jobname.pytxmcr.}}% + {}% + \IfStrEq{\pytx@outputdir}{.}% + {\typeout{No file \pytx@jobname.pytxmcr.}}% + {\typeout{No file \pytx@outputdir/\pytx@jobname.pytxmcr.}}% + \typeout{Run \pytx@packagename\space to create it.}}% \makeatother } % \end{macrocode} @@ -2064,7 +2328,7 @@ % \end{macrocode} % % \begin{macro}{\pytx@WriteCodefileInfo}\begin{macro}{\pytx@WriteCodefileInfoExt} -% Later, we will frequently need to write \pytex\ information to the code file in standardized form. We create a macro to simplify that process. We also create an alternate form, for use with external files that must be inputted or read in by \pytex\ and processed. While the standard form employs a counter that is incremented elsewhere, the version for external files substitutes a zero (0) for the counter, because each external file must be unique in name and thus numbering via a counter is redundant.\footnote{The external-file form also takes an optional argument. This corresponds to a command-line argument that is passed to an external file during the file's execution. Currently, executing external files, with or without arguments, is not implemented. But this feature is under consideration, and the macro retains the optional argument for the potential future compatibility.} +% Later, we will frequently need to write \pytex\ information to the code file in standardized form. We create a macro to simplify that process. We also create an alternate form, for use with external files that must be inputted or read in by \pytex\ and processed.\footnote{The external-file form also takes an optional argument. This corresponds to a command-line argument that is passed to an external file during the file's execution. Currently, executing external files, with or without arguments, is not implemented. But this feature is under consideration, and the macro retains the optional argument for the potential future compatibility. Originally, the external version used a fixed instance, but that conflicted with the \texttt{fancyvrb} options \texttt{firstline} and \texttt{lastline}, so instances had to be added.} % \begin{macrocode} \def\pytx@argsrun{} \def\pytx@argspprint{} @@ -2084,7 +2348,7 @@ {\let\pytx@currfile\@empty}{\let\pytx@currfile\currfilename}% \immediate\write\pytx@codefile{\pytx@delim\pytx@type\pytx@delimchar% \pytx@session\pytx@delimchar\pytx@group\pytx@delimchar% - 0\pytx@delimchar\pytx@cmd\pytx@delimchar% + \arabic{\pytx@counter}\pytx@delimchar\pytx@cmd\pytx@delimchar% \pytx@context\pytx@delimchar\pytx@argsrun\pytx@delimchar% \pytx@argspprint\pytx@delimchar% \pytx@currfile\pytx@delimchar% @@ -2138,6 +2402,8 @@ % \begin{macro}{pytx@FancyVerbLineTemp} % |fancyvrb|'s |SaveVerbatim| environment will be used extensively to include code highlighted by Pygments and other processed content. Unfortunately, when the saved content is included in a document with the corresponding |UseVerbatim|, line numbering does not work correctly. Based on a web search, this appears to be a known bug in |fancyvrb|. We begin by fixing this, which requires patching |fancyvrb|'s |\FVB@SaveVerbatim| and |\FVE@SaveVerbatim|. We create a patched |\pytx@FVB@SaveVerbatim| by inserting |\FV@StepLineNo| and |\FV@CodeLineNo=1| at appropriate locations. We also delete an unnecessary |\gdef\SaveVerbatim@Name{#1}|. Then we create a |\pytx@FVE@SaveVerbatim|, and add code so that the two macros work together to prevent |FancyVerbLine| from incorrectly being incremented within the |SaveVerbatim| environment. This involves using the counter |pytx@FancyVerbLineTemp| to temporarily store the value of |FancyVerbLine|, so that it may be restored to its original value after verbatim content has been saved. % +% There is an additional line-numbering issue when the |firstline| option is used with |SaveVerbatim|. This is fixed by globally reseting |\FV@CodeLineNo| to zero. That was originally done in |fancyvrb|, via |\FV@FormattingPrep|, but this macro is commented out in the current version of |fancyvrb|, which throws off line numbering. +% % Typically, we |\let| our own custom macros to the corresponding macros within |fancyvrb|, but only within a command or environment. In this case, however, we are fixing behavior that should be considered a bug even for normal |fancyvrb| usage. So we let the buggy macros to the patched macros immediately after defining the patched versions. % \begin{macrocode} \newcounter{pytx@FancyVerbLineTemp} @@ -2145,6 +2411,7 @@ % \begin{macrocode} \def\pytx@FVB@SaveVerbatim#1{% \setcounter{pytx@FancyVerbLineTemp}{\value{FancyVerbLine}}% + \global\FV@CodeLineNo\z@ \@bsphack \begingroup \FV@UseKeyValues @@ -3084,6 +3351,7 @@ % \begin{macrocode} \def\pytx@BeginEnvPyg@i[#1]{% \def\pytx@fvopttmp{#1}% + \def\pytx@argspprint{#1}% \setcounter{pytx@FancyVerbLineTemp}{\value{FancyVerbLine}}% \let\FVB@VerbatimOut\pytx@FVB@VerbatimOut \let\FVE@VerbatimOut\pytx@FVE@VerbatimOut @@ -3308,6 +3576,7 @@ % \begin{macrocode} \def\pytx@BeginConsEnvFV@i[#1]{% \def\pytx@fvopttmp{#1}% + \def\pytx@argspprint{#1}% \setcounter{pytx@FancyVerbLineTemp}{\value{FancyVerbLine}}% \let\FVB@VerbatimOut\pytx@FVB@VerbatimOut \let\FVE@VerbatimOut\pytx@FVE@VerbatimOut @@ -3523,6 +3792,8 @@ \ifstrequal{#1}{rb}{\makepythontexfamily[pyglexer=ruby]{rb}}{}% \ifstrequal{#1}{julia}{\makepythontexfamily[pyglexer=julia]{julia}}{}% \ifstrequal{#1}{jl}{\makepythontexfamily[pyglexer=julia]{jl}}{}% + \ifstrequal{#1}{matlab}{\makepythontexfamily[pyglexer=matlab]{matlab}}{}% + \ifstrequal{#1}{octave}{\makepythontexfamily[pyglexer=octave]{octave}}{}% } \expandafter\docsvlist\expandafter{\pytx@families} % \end{macrocode} @@ -3557,7 +3828,7 @@ {\PackageWarning{\pytx@packagename}% {A "listing" environment already exists \MessageBreak \pytx@packagename\space will not create one \MessageBreak - Use \string\setpythontexlistingenv to create a custom listing environment}}% + Use \string\setpythontexlistingenv\space to create a custom listing environment}}% \else \ifbool{pytx@listingenv}{}{\DeclareFloatingEnvironment[fileext=lopytx]{listing}} \fi @@ -3663,6 +3934,7 @@ % \begin{macrocode} \def\pytx@BEPygmentsFV[#1]{% \def\pytx@fvopttmp{#1}% + \def\pytx@argspprint{#1}% \begingroup \obeylines \pytx@BEPygmentsFV@i @@ -3733,6 +4005,7 @@ % \begin{macrocode} \def\pytx@BEPygmentsPyg[#1]{% \def\pytx@fvopttmp{#1}% + \def\pytx@argspprint{#1}% \begingroup \obeylines \pytx@BEPygmentsPyg@i @@ -3769,7 +4042,7 @@ % % \begin{macro}{\pytx@MakePygmentsInputFV} % \begin{macro}{\pytx@MakePygmentsInputPyg} -% For completeness, we need to be able to read in a file and highlight it. This is done through some trickery with the current system. We define the type as |PYG|\meta{lexer}, and the command as |verb|. We set the context for consistency. We set the session as |EXT:|\meta{file~name}.\footnote{There is no possibility of this session being confused with a user-defined session, because colons are substituted for hyphens in all user-defined sessions, before they are written to the code file.} Next we define a |fancyvrb| settings macro for the type if it does not already exist. We write info to the code file using |\pytx@WriteCodefileInfoExt|, which writes the standard info to the code file but uses zero for the instance, since external files that are not executed can only have one instance. +% For completeness, we need to be able to read in a file and highlight it. This is done through some trickery with the current system. We define the type as |PYG|\meta{lexer}, and the command as |verb|. We set the context for consistency. We set the session as |EXT:|\meta{file~name}.\footnote{There is no possibility of this session being confused with a user-defined session, because colons are substituted for hyphens in all user-defined sessions, before they are written to the code file.} Next we define a |fancyvrb| settings macro for the type if it does not already exist. We write info to the code file using |\pytx@WriteCodefileInfoExt|. % % Then we check to see if the file actually exists, and issue a warning if not. This saves the user from running |pythontex.py| to get the same error. We perform our typical |FancyVerbLine| trickery. Next we make use of the saved content in the same way as the |pygments| environment. Note that we do not create a counter for the line numbers. This is because under typical usage an external file should have its lines numbered beginning with 1. We also encourage this by setting |firstnumber=auto| before bringing in the content. % @@ -3786,6 +4059,8 @@ \pytx@SetGroupVerb \edef\pytx@session{EXT:##3}% \pytx@CheckPygmentsInit{##2}% + \xdef\pytx@counter{pytx@\pytx@type @\pytx@session @\pytx@group}% + \pytx@CheckCounter{\pytx@counter}% \setcounter{pytx@FancyVerbLineTemp}{\value{FancyVerbLine}}% \begingroup \DepyListing %Always must be in a group @@ -3796,32 +4071,42 @@ {\PackageWarning{\pytx@packagename}{Input file <##3> doesn't exist}}% \endgroup \setcounter{FancyVerbLine}{\value{pytx@FancyVerbLineTemp}}% + \stepcounter{\pytx@counter}% }% } \def\pytx@MakePygmentsInputPyg{ \newcommand{\inputpygments}[3][]{% + \begingroup \edef\pytx@type{PYG##2}% \edef\pytx@cmd{verbatim}% \pytx@SetContext \pytx@SetGroupVerb + \def\pytx@argspprint{##1}% \edef\pytx@session{EXT:##3}% \pytx@CheckPygmentsInit{##2}% + \xdef\pytx@counter{pytx@\pytx@type @\pytx@session @\pytx@group}% + \pytx@CheckCounter{\pytx@counter}% \pytx@WriteCodefileInfoExt \IfFileExists{##3}{}{\PackageWarning{\pytx@packagename}% - {Input file <##3> does not exist}} + {Input file <##3> does not exist}}% \setcounter{pytx@FancyVerbLineTemp}{\value{FancyVerbLine}}% \begingroup \pytx@FVSet \fvset{firstnumber=auto}% - \ifcsname FV@SV@pytx@\pytx@type @\pytx@session @\pytx@group @0\endcsname - \UseVerbatim[##1]{pytx@\pytx@type @\pytx@session @\pytx@group @0}% + \ifcsname FV@SV@pytx@\pytx@type @\pytx@session @\pytx@group + @\arabic{\pytx@counter}\endcsname + \UseVerbatim[##1]{pytx@\pytx@type @\pytx@session @\pytx@group + @\arabic{\pytx@counter}}% \else - \InputIfFileExists{\pytx@outputdir/##3_##2.pygtex}{}% + \InputIfFileExists{\pytx@outputdir/\pytx@type_##3_\pytx@group + _\arabic{\pytx@counter}.pygtex}{}% {\textbf{??~\pytx@packagename~??}% \PackageWarning{\pytx@packagename}{Non-existent Pygments content}}% \fi \endgroup \setcounter{FancyVerbLine}{\value{pytx@FancyVerbLineTemp}}% + \stepcounter{\pytx@counter}% + \endgroup }% } % \end{macrocode} diff --git a/Master/texmf-dist/source/latex/pythontex/pythontex_install.bat b/Master/texmf-dist/source/latex/pythontex/pythontex_install.bat new file mode 100755 index 00000000000..e32fa0ba210 --- /dev/null +++ b/Master/texmf-dist/source/latex/pythontex/pythontex_install.bat @@ -0,0 +1,4 @@ +@echo off
+@setlocal enableextensions
+@cd /d "%~dp0"
+pythontex_install.py %*
|