3

This is a followup to a question addressing the corresponding issue with listings from external files.

The ideal solution would be extending the lastline key to accept negative values and count omitted lines from the end, just like the answer to the linked question.

The main reason for desiring a redefinition of lastline instead of some new environment (that might be easier to implement) is the ease of integration with other packages, e.g. tcolorbox.

A non-working minimal example would be

\documentclass{article}
\usepackage{listings}
\begin{document}
\begin{lstlisting}[lastline=-2]
first
second
third
fourth
\end{lstlisting}
\end{document}

where only the first and second line of the listing would be in the output.

The core trick of the linked answer consists of setting the listing a first time in a box, getting the value of the line counter (still holding the index of the last line) and setting the listing a second time calculating the correct value for lastline. I tried adapting it to this situation without success, as I don't know the innards of listings well enough. Can it be done?

  • Would you like to export the content to an external file and apply the existing solution? – Symbol 1 Oct 26 '16 at 17:47
  • Not what I had in mind, but I guess it'd be an acceptable solution! Apart from not breaking any feature of listings, I only care about having a seamless integration into the lastline key so it can be effortlessly used coupled with other packages like showexpland tcolorbox. – Paolo Brasolin Oct 26 '16 at 17:59
4

If you intend to use this feature for tcolorbox, as you wrote, there is an easy way. The tcblistings environment saves the listings content into a file and reloads it again. Therefore, the patch from How to omit the last four lines of a sample code in listing can be applied:

\documentclass{article}
\usepackage[most]{tcolorbox}

\makeatletter
\lst@Key{lastline}\relax{\ifnumcomp{#1}{<}{0}{%
  \let\mylst@file\lst@intname\sbox0{\lstinputlisting{\mylst@file}}%
  \def\lst@lastline{\the\numexpr#1+\value{lstnumber}-1\relax}}%
  {\def\lst@lastline{#1\relax}}}
\makeatother

\begin{document}
\begin{tcblisting}{listing options={lastline=-2}}
first
second
third
fourth
\end{tcblisting}

\begin{tcblisting}{listing only,listing options={lastline=-2}}
first
second
third
fourth
\end{tcblisting}

\begin{tcblisting}{blankest,listing only,listing options={lastline=-2}}
first
second
third
fourth
\end{tcblisting}
\end{document}

enter image description here

  • Since nobody chimed in with a completely general solution I'll accept the answer, as it perfectly fits my use case. (Thanks for the awesome tcolorbox package!) – Paolo Brasolin Oct 31 '16 at 16:13

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.