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.

  • escapeinside uses single characters as delimiters! – Paul Gaborit Jan 26 '17 at 0:28
1

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}
  • Thank you very much, this was the problem. Thought escapeinside would be different than escapechar. – stkr Jan 26 '17 at 0:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.