4

I want to do numbering certain lines in minted and refer it through cross-reference.

Here's my code:

\documentclass{article}
\usepackage{minted}

\newcommand*{\lnumformat}[1]{$\quad\leftarrow$ <#1>}
\newcounter{lnum}
\newcommand{\lnum}[1]{\refstepcounter{lnum}\lnumformat{\arabic{lnum}}\label{#1}}
\newcommand{\lref}[1]{\lnumformat{\ref{#1}}}

\begin{document}

\begin{minted}[breaklines=true,linenos=true,escapeinside=@@]{cpp}
int main() { 
    printf("hello, world"); @\lnum{line1}@
    return 0; @\lnum{line3}@
}
\end{minted}

\end{document}

And, here's the result:

result

As you can see, the counter number increases by two not one. How can I fix it to increase by one?

  • Just to help the next one who will try to help... The code works fine if we use it in lstlisting environment and the counter increases by one this way... Your problem has to do with minted package... but unfortunatelly I don;t think I can help – koleygr Jun 21 '17 at 16:53
  • I also tryed to install mintec on debian 9 and it doesn't compile not even the documentations simpler examples... Sorry... but I can't help... Good luck! – koleygr Jun 21 '17 at 17:13
5

The code in @...@ is executed twice, apparently because of breaklines=true.

You can make \lnum do the stepping only once by executing it in the second pass; in the first pass we only add a phantom.

\documentclass{article}
\usepackage{minted}

\newcommand*{\lnumformat}[1]{\mbox{$\quad\leftarrow$ <#1>}}
\newcounter{lnum}
\newcommand{\lnum}[1]{%
  \ifcsname used@#1\endcsname
    \refstepcounter{lnum}\lnumformat{\arabic{lnum}}\label{#1}%
  \else
    \leavevmode\phantom{\lnumformat{\the\numexpr\value{lnum}+1}}%
    \expandafter\gdef\csname used@#1\endcsname{}%
  \fi
}
\newcommand{\lref}[1]{\lnumformat{\ref{#1}}}

\begin{document}

\begin{minted}[breaklines=true,linenos=true,escapeinside=@@]{cpp}
int main() { 
    printf("hello, world"); @\lnum{line1}@
    return 0; @\lnum{line3}@
}
\end{minted}

\end{document}

enter image description here

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.