Home > Software design >  Is there a way to label Python code in LaTeX?
Is there a way to label Python code in LaTeX?

Time:12-16

We have made a few examples of code in Python and inserted them into a LaTeX/overleaf document. We are currently looking into making a label for them, so they can be referenced at various points, however using the \begin(python) doesn't seem to allow us to add a \label{}, which works and can be referenced. A similar example of what we are looking for would be

\documentclass[11pt,a4paper,twoside,openany,english]{book}
\usepackage{pythonhighlight}

\begin{python}\label{SO-test}
    value_a = 1                   
    value_b = 2                    
    print(value_a   value_b)     
\end{python}

Any tips or tricks are appreciated.

CodePudding user response:

Behind the scenes the pythonhighlight uses the much more common listings package. The listings package allows you to add a caption and label as optional argument of the lstlistings environment.

However even though the pythonhighlight sets up its python environment with the possibility to add an optional argument, it never uses this argument. Thus the information is never forwarded to the lstlistings environment.

To work around this, you can set up your own environment:

\documentclass[11pt,a4paper,twoside,openany,english]{book}
\usepackage{pythonhighlight}

\lstnewenvironment{mypython}[1][]{\lstset{style=mypython,#1}}{}

\begin{document}

\begin{mypython}[caption={some text to produce a caption},label=SO-test]
    value_a = 1                   
    value_b = 2                    
    print(value_a   value_b)     
\end{mypython}

Reference: \ref{SO-test}

\end{document}

enter image description here

CodePudding user response:

I tried to just include this in a comment, but I'm too new to stack overflow.

Have you tried just using regular verbatim instead of making it explicitly python? Is there something wrong with that?

\begin{verbatim}
Text enclosed inside \texttt{verbatim} environment 
is printed directly 
and all \LaTeX{} commands are ignored.
\end{verbatim}

I also saw this thing about minted in their library.

It makes a reference to \begin{minted}{python}

https://www.overleaf.com/learn/latex/Code_Highlighting_with_minted

  • Related