2

I wanted to know if there were any methods that would allow me to reference lines in source code that was imported with the \inputminted macro from the minted package?

My assumption is that this is not possible given that it is an external file?

I am trying to avoid copying the contents of the file manually as I don't want to accidentally forget to update the code in my .tex file. So if anyone has any suggestions, I would love to hear them!

Thanks.

MWE:

\documentclass{report}

\usepackage{minted}
\setminted{
    linenos
}

\begin{document}
% Report contents
In \hyperref[code.m:30]{Line 30} we can find \dots

% Appendix
\inputminted{MATLAB}{code.m}
% The following LaTeX code is only for illustration purposes
\label{code.m:30}
\end{document}

1 Answer 1

4

You need to add a \label in the input file.

\begin{filecontents*}[overwrite]{\jobname.m}
Line
Line
Line
Line |\phantomsection\label{thisline}|
Line
Line
\end{filecontents*}

\documentclass{article}

\usepackage{minted}
\usepackage{hyperref}

\begin{document}

In \hyperref[thisline]{Line~\ref*{thisline}} we can find \dots

\clearpage

\inputminted[linenos,escapeinside=||]{MATLAB}{\jobname.m}

\end{document}

enter image description here

If you plan to use - in labels, or maybe other characters that may get wrongly interpreted by minted, you can use a workaround.

\begin{filecontents*}[overwrite]{\jobname.m}
Line
Line
Line
Line |\mintedlabel{this-line}|
Line
Line
\end{filecontents*}

\documentclass{article}

\usepackage{minted}
\usepackage{hyperref}

\newcommand{\mintedlabel}[1]{\phantomsection\label{\detokenize{#1}}}

\begin{document}

In \hyperref[this-line]{Line~\ref*{this-line}} we can find \dots

\clearpage

\inputminted[linenos,escapeinside=||]{MATLAB}{\jobname.m}

\end{document}
3
  • That's a great method! I didn't think you could overwrite files within LaTeX like that, thanks for the answer :) Commented Aug 18, 2022 at 1:34
  • Good solution! I found another similar solutions like this (e.g. here or here). But all solutions (included this) don't work if I use a - inside label (e.g. \label{this-line}). In particular I get ! Missing \endcsname inserted. and LaTeX Warning: Hyper reference `this-line' on page 1 undefined on input line 17.
    – miticollo
    Commented Mar 13, 2023 at 10:07
  • 1
    @LorenzoFerron I added a workaround.
    – egreg
    Commented Mar 13, 2023 at 10:29

You must log in to answer this question.

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