2

I have a library that contains code snippets formatted with the listings package. This library is used in two different documents, with slight variations depending on the document. I've been using conditionals to achieve these document-specific changes.

However, when I try to combine the listings-formatted snippets with a conditional, the LaTeX compiler (xelatex) outputs the following warning and the text is swallowed up:

"Package Listings Warning: Text dropped after begin of listing on input line XYZ."

Why am I getting this error/what do I need to do to be able to use listings inside a condition?

I've included an MWE below that shows what I'm trying to do (the filename is MWE.tex):

\documentclass[a4paper]{article}

\usepackage{listings}
\usepackage{xstring}

\lstset{basicstyle=\ttfamily,breaklines=true}

\begin{document}

Here is lstlisting without condition:

\begin{lstlisting}
    This is sample code. 
\end{lstlisting}

Here is lstlisting within a conditional:

\IfSubStr{\jobname}{\detokenize{MWE}}%
  {\begin{lstlisting}
    This is sample code. 
   \end{lstlisting}}%true
  {FALSE}%false

\end{document}

1 Answer 1

2

Using fragile content in the argument of a macro is not a good idea. You can avoid this problem e.g. by using an \if case:

\documentclass[a4paper]{article}

\newif\ifmwe
\usepackage{listings}
\usepackage{xstring}


\lstset{basicstyle=\ttfamily,breaklines=true}

\begin{document}

Here is lstlisting without condition:

\begin{lstlisting}
    This is sample code. 
\end{lstlisting}

Here is lstlisting within a conditional:

\IfSubStr{\jobname}{\detokenize{MWE}}%
  {\mwetrue}%true
  {\mwefalse}%false
  
\ifmwe
  \begin{lstlisting}
      This is sample code. 
     \end{lstlisting}  
\else
 fasle
\fi  
  

\end{document}
5
  • Oh wow, thanks so much for your reply! This works perfectly!
    – serval
    Jun 29, 2023 at 14:17
  • @serval You're welcome! Jun 29, 2023 at 14:20
  • One more question, if I may... is there a way to make the solution you showed me reusable? As in, can I define it in such a way that I can use it as an input template? Because currently I have defined the switch code from my MWE as a reusable: \NewDocumentCommand{\ifjobnamecontains}{ m +m +m } {% \IfSubStr{\jobname}{\detokenize{#1}}% {#2}% {#3}% } Is it possible to package the \if case in a similar way?
    – serval
    Jun 30, 2023 at 6:10
  • @serval If you have a new question, please ask a new question. More people will see it and be able to help you. Jun 30, 2023 at 7:53
  • To set the value of the mwe conditional, use \mwetrue or \mwefalse.
    – Paul Wintz
    Feb 10 at 10:59

You must log in to answer this question.

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