[Tex/LaTex] lstlisting `moredelim` doesn’t work with comments

listingsoverlays

I'm trying to add some overlays to a piece of code, and I'm defining it using moredelim. However, when I use it on comments within the code, the moredelim stops working.

What am I missing?

\documentclass{beamer}

\usepackage{listings}
\lstdefinestyle{cexample}{%
language=C++,
moredelim=**[is][\onslide<+->]{|}{|},
}

\begin{document}
\begin{frame}[fragile]{Work without comment}
\begin{lstlisting}[style=cexample]
char * const buffer[]; |comment 1|
char * const * buffer; |comment 2|
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]{Doesn't work with comments '//'}
\begin{lstlisting}[style=cexample]
char * const buffer[]; |//comment 1|
char * const * buffer; |//comment 2|
\end{lstlisting}
\end{frame}

\end{document}

enter image description here

Best Answer

The closing | is interpreted as part of the comment. Unfortunately, I know of no way to escape listings' one-line comment mode once it has started.

One workaround is to use a moredelim that requires only an opening delimiter and ends at the end of the current line.

enter image description here

\documentclass{beamer}

\usepackage{listings}
\lstdefinestyle{cexample}{%
language=C++,
moredelim=**[il][\onslide<+->]{|},
}

\begin{document}
\begin{frame}[fragile]{Work without comment}
\begin{lstlisting}[style=cexample]
char * const buffer[]; |comment 1
char * const * buffer; |comment 2
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]{Doesn't work with comments '//'}
\begin{lstlisting}[style=cexample]
char * const buffer[]; |//comment 1
char * const * buffer; |//comment 2
\end{lstlisting}
\end{frame}

\end{document}