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 Answers1

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}

egreg
  • 1,121,712