1

I am writing on texstudio, and there is a part where I want to insert a code written by me. In another part of the text I want to quote that piece of code but I don't know how. The code is written in this way:

\section*{Matlab Code}
\begin{lstlisting}
 code
\end{lstlisting}
1

2 Answers 2

2
\documentclass{article}
\usepackage{listings}

\begin{document}

    \begin{lstlisting}[caption=Caption, label=lst:code]
    code
    \end{lstlisting}
    
    See Listing~\ref{lst:code}.

\end{document}

Set the caption and label as optional arguments to the lstlisting environment. This will produce code with the caption Listing 1:Caption and can be referenced later as \ref{lst:code}.

2

You can define the label you can later use with \autoref (or \ref, or whatever you use to reference):

\begin{lstlisting}[caption={caption_text}\label{lst:a_label}]
code
\end{lstlisting}

By the way, I'm in the process of migrating my TeX codebases away from lstlisting to minted, mostly for reasons of robustness, and because I like the underlying code formatting abilities better.

2
  • minted relies on a 3rd party application, right? Commented Mar 15, 2021 at 23:01
  • 1
    Yes, just like lstlisting depends on a third-party LaTeX module. The difference is that writing a parser for many languages is much easier in other languages than TeX these days, so that solution quickly comes desirable. Commented Mar 15, 2021 at 23:04

You must log in to answer this question.

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