3

I want to change the numbers of a listing based on certain rules:

  • Line 10: no number
  • Line 11 onwards: the number that corresponds to the line+5

The displayed numbers should thus be: 1, 2, 3, 4, 5, 6, 7, 8, 9, , 16, 17, 18, etc.

The contents of the listing are obtained from a separate file.

So far, I am trying this out with if statements, but it is not working:

\renewcommand\thelstnumber{%
\ifnum\value{lstnumber}=10  \else \ifnum\value{lstnumber}>10 \arabic{lstnumber + 5} \else\arabic{lstnumber}\fi\fi

How can I accomplish this?

5

The main problem with your code is that you cannot perform arithmetic calculations within \arabic natively. For ease-of-use, use xfp to perform (expandable) integer calculations/evaluations using \inteval:

enter image description here

\documentclass{article}

\usepackage{listings,xfp}

\renewcommand\thelstnumber{%
  \ifnum\value{lstnumber}=10
  \else
    \ifnum\value{lstnumber}>10
      \inteval{\value{lstnumber} + 5}%
    \else
      \arabic{lstnumber}%
    \fi
  \fi
}

\begin{document}

\begin{lstlisting}[numbers = left]
Line A
Line B
Line C
Line D
Line E
Line F
Line G
Line H
Line I
Line J
Line K
Line L
Line M
Line N
Line O
Line P
Line Q
\end{lstlisting}

\end{document}

If you can't use xfp for whatever reason, you can use

\renewcommand\thelstnumber{%
  \ifnum\value{lstnumber}=10
  \else
    \ifnum\value{lstnumber}>10
      \the\numexpr\value{lstnumber} + 5\relax%
    \else
      \arabic{lstnumber}%
    \fi
  \fi
}
5
  • Thanks for the suggestion. I am using Overleaf for my project, and xfp is not natively supported. How should I install it?
    – erik
    Oct 29 '18 at 8:07
  • When copying+pasting your snippet in Overleaf, I get the following compiler error: ! LaTeX Error: File `xfp.sty' not found. l.4 ^^M
    – erik
    Oct 29 '18 at 8:08
  • I contacted Overleaf's customer support, and they replied the following: The xfp package is available on Overleaf V2, but the version of xfp we have does not provide the \inteval command yet, so that code snippet in the tex.sx answer would also fail. However the xfp package isn't necessary for what you're trying to achieve, as we can use \the\numexpr instead of \inteval
    – erik
    Oct 29 '18 at 9:34
  • Werner, I think your answer solves the issue, but maybe you could update it with the last feedback from Overleaf for the sake of completeness, and then it can be accepted?
    – erik
    Oct 29 '18 at 9:39
  • @tli: Yes. As mentioned, I use xfp due to the convenience and ease-of-use. I've updated my answer to highlight the alternative.
    – Werner
    Oct 29 '18 at 15:55

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.