2
  • I would like to put code from an outside file into a LaTeX document.
    • This code is able to run on its own.
    • Equation labels from the document are referenced in the comments of this code.
  • I would like to see these equations updated and referenced in the final document, with a caption, label, in a box, numbered lines, etc..

Example latex document with a labelled equation:

%doc.tex
\documentclass[]{article}
\usepackage{amsmath}
\usepackage{hyperref}
\usepackage{listings}
\begin{document}
    \begin{align}
    \label{eq:my equation}
    y = \sin(x) \cos(x)
    \end{align}
    \lstinputlisting[caption={Code},
        frame=single,
        numbers=left,
        escapeinside={tex:}{:tex}
    ]{code.py}
\end{document}

Example code to be included in the document:

#code.py
import math
def y(x):
    return math.sin(x)*math.cos(x) #tex: Equation \ref{eq:my equation} :tex
print y(math.pi/4)

However, using \lstinputlisting produces errors. How can I reference equations like this?

Thank you very much.

1
  • escapeinside uses single characters as delimiters! Commented Jan 26, 2017 at 0:28

1 Answer 1

2

escapeinside uses single characters as delimiters!

\documentclass[]{article}
\usepackage{filecontents}
\begin{filecontents*}{\jobname.py}
#code.py
import math
def y(x):
    return math.sin(x)*math.cos(x) # % Equation \ref{eq:my equation} %
print y(math.pi/4)
\end{filecontents*}
\usepackage{amsmath}
\usepackage{hyperref}
\usepackage{listings}
\begin{document}
\begin{align}
  \label{eq:my equation}
  y = \sin(x) \cos(x)
\end{align}

\lstinputlisting[caption={Code},
frame=single,
numbers=left,
escapeinside=\%\%
]{\jobname.py}

\end{document}
1
  • Thank you very much, this was the problem. Thought escapeinside would be different than escapechar.
    – stkr
    Commented Jan 26, 2017 at 0:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .