1

update: Arun's answer, below, works for me, since I'm not using syntax highlighting anyway. Thanks!

Here's my original question:

I use the following setting to allow me to mark text as bold within an lstlisting environment by putting three asterisks at the beginning and end of the bolded section:

 \lstset{moredelim=[is][\bfseries]{***}{***}}

This works find most of the time, but fails when I try to use it within quoted text. For example, the following works:

 \begin{lstlisting}
 this is a ***test***!
 \end{lstlisting}

but the following doesn't:

 \begin{lstlisting}
 "this is a ***test***!"
 \end{lstlisting}

The second form simply prints literal asterisks. Is there a way to turn off the special behaviour of lstlisting when within quotes?

Bryan

edit: I've added a complete minimal example below.

\documentclass{article}

\usepackage{listings}
\lstset{ % Set options for ``listing'':
language=C++,
commentstyle=,
keywordstyle=,
identifierstyle=,
basicstyle=\ttfamily,
breaklines=false,
frame=,
showstringspaces=false
}
\lstset{moredelim=[is][\bfseries]{***}{***}}

\begin{document}

This works:

 \begin{lstlisting}
 this is a ***test***!
 \end{lstlisting}

This doesn't:

 \begin{lstlisting}
 "this is a ***test***!"
 \end{lstlisting}

\end{document}
1
  • 1
    If the solution works then it's usual not only to accept the answer, but also to upvote it ;-)
    – user31729
    Jan 9, 2016 at 13:46

1 Answer 1

3

A possible solution is to add morestring=*[b]" to your \lstset. This redeclares the "..." string syntax, but the asterisk means that listings still applies its formatting inside of these strings.

Here's my code; since LaTeX doesn't have a bold typewriter font by default, I used italics instead.

\documentclass{article}
\usepackage{listings}
\lstset{ % Set options for ``listing'':
    language=C++,
    % ... same options ... 
    showstringspaces=false,
    morestring=*[b]"
}
\lstset{moredelim=[is][\itshape]{***}{***}}
\begin{document}
\begin{lstlisting}
this is a ***test***!
\end{lstlisting}
With quotes:
\begin{lstlisting}
"this is a ***test***!"
\end{lstlisting}
\end{document}

enter image description here

However, there is a caveat: this redefinition means that listings applies all formatting inside strings, not just your new delimiter. For example, this is a C++ keyword, so if you use \lstset{keywordstyle=\color{blue}}, then this is colored inside quotes as well:

enter image description here

This might not be desired behavior. If so, you'll probably have to use something other than moredelim, such as escapeinside.

You must log in to answer this question.

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