Monday, June 8, 2015

Python Code in LaTeX

In A Student’s Guide to Python for Physical Modeling, we used the Listings package for LaTeX to format our code samples. In this post, we describe how we used the package and provide our style files for others to use.

Typesetting Computer Code

The listings package makes it easy to format code for typesetting in LaTeX. It allows the author to adjust virtually every aspect of how code is displayed. We used the package to develop our own syntax highlighting scheme.
  • All code is displayed in a monospace (typewriter) font.
  • Built-in functions and reserved words are bold and green.
  • Python exceptions are bold and red.
  • Modules and functions from NumPy and PyPlot are bold and black.
  • Modules and functions from other modules are bold and blue.
  • Strings are red.
  • Keyword arguments to functions are italic.
  • Comments are blue italic.
This scheme is similar to the one used in Spyder. It allows a reader to distinguish built-in functions and modules from variable names and user-defined functions at a glance.

How to Use the Style Files

The bulk of the work lies in setting up an environment to display code the way you want. We’ve already done that for you!
To start producing formatted code, just download one of the LaTeX files below. Put it somewhere LaTeX can find it, then add this line to the preamble of your document:
\include{listings_py34}
Somewhere after \begin{document} and before your first code sample, type
\pysetup
This will set all the style parameters and create the list of keywords to be displayed in different fonts and colors. Now you are ready to start adding code to your document.

Examples

The listings package provides three ways to add code to your document. In some ways, these environments are similar to LaTeX’s native verbatim environment: Every character you type will be printed, including spaces, tabs, and line breaks.

Inline Code

Very short fragments can be displayed inline. To do this, use the \lstinline command.
To plot the data, type \lstinline!plt.plot(x,y)! at the command line.
You do not have to use exclamation points to enclose the code fragment. You can use almost any set of special symbols that do not appear in the code fragment itself.
\lstinline!print(x)!,  \lstinline&print(x)&, and \lstinline$print(x)$ all
produce the same output.

Code Environment

For longer code samples, you can place the code inside of an lstlisting environment.
\begin{lstlisting}
def hello():
    print("Hello, world!")
    return 0
\end{lstlisting}
This will typeset a function definition.

Include Source Code

You can also directly import entire programs using the \lstinputlisting{} command. The program text will be formatted according to the style specifications and displayed exactly as typed.
\lstinputlisting{code/hello.py}
This will display the program hello.py, located in the code/ directory, in the typeset document.

Swapping Keywords Between Lists

Sometimes a word plays multiple roles in Python. For instance, dtype is an attribute of a NumPy array. It is also a keyword argument to the function `np.array’. To properly display the same word in different contexts using the listings package, it must be transferred between lists of keywords. We have provided a simple macro to do this.
\swapKeyword{keyword}{old_list}{new_list}
will delete keyword from old_list (if it is a member) and add it to new_list. For the dtype example, you might type something like
\swapKeyword{dtype}{3}{5}
To create an floating point array, type \lstinline!x = np.array([1,2,3], dtype='float')!.
\swapKeyword{dtype}{5}{3}
We can check the data type of the array: \lstinline!x.dtype!.
dtype is transferred from keyword list 3 (NumPy and PyPlot methods) to keyword list 5 (function keyword arguments) for the first inline code sample, then back its original list for the second. Thus, it appears in italics in the first instance and in bold in the second.

Download the Files

We have prepared two versions of the header file — one for Python 2.7 and one for Python 3.4. These differ only in a few reserved words and keywords that are unique to one version of Python or the other. For example, xrange and raw_input are built-in functions in Python 2.7, but they are not present in Python 3.4. Click on the appropriate link to download the version of the file you want. sample.tex is a short LaTeX document that illustrates the use of the listings package, and sample.pdf is the final output.
listings_py27.tex
listings_py34.tex
sample.tex
sample.pdf

More Information

The listings package maintained by Jobst Hoffman. You can download the User’s Guide for the listings package here.
We have only described a small fraction of what is possible with this package, but we hope that it is a useful fraction for those who wish to write about Python!

No comments:

Post a Comment

Thank you for your input!
To avoid duplication, spam, and inappropriate content, we will review comments before posting them.


— Jesse & Phil