5

Please consider the following MWE:

\documentclass{article}

\usepackage[T1]{fontenc}    
\usepackage[utf8]{inputenc}     

\usepackage{xcolor}
\usepackage{listings}

\lstdefinestyle{test}{%
    language={[latex]TeX},
    tabsize=2,
    breaklines,
    basicstyle=\footnotesize\ttfamily,
    texcsstyle=*\color{blue}\bfseries,
    keywordstyle=\color{red}\bfseries,
    morekeywords={environment},
    moretexcs={test},
    moredelim=**[is][\color{red}]{@}{@},
}

\lstset{style=test}

\begin{document}

\begin{lstlisting}
    \begin{environment}
        \test{foo}{bar}
    \end{environment}

    foo bar
\end{lstlisting}

\end{document}

How can I automatically color all text with {}? I tried to add "foo" and "bar" to the list of morekeywords but then they are also colored outside of {}.

The output should look like

enter image description here

I cannot use

\begin{lstlisting}
    \begin{environment}
        \test{@foo@}{@bar@}
    \end{environment}

    foo bar
\end{lstlisting}

because the in the real usage the content of the listing is automatically rendered and the @ signs would cause compilation error.

2
  • Does this answer suit your needs?
    – SDF
    Commented Aug 31, 2018 at 14:15
  • @SDF Yes, this is exactly what I was looking for! Would you be so kind to write a short answer so that the bounty is not wasted? (apparently I have to wait until after teh bounty to close this question as duplicate ...)
    – aloneprism
    Commented Aug 31, 2018 at 14:22

1 Answer 1

3
+50

This is a duplicate of Emphasize (color) contents between two delimiters in listings, but not the delimiters themselves.

I wrote this at the asker's request because of the bounty. All credit should go to jubobs (and/or David Carlisle).


You can do it this way:

\documentclass{article}

\usepackage[T1]{fontenc}    
\usepackage[utf8]{inputenc}     

\usepackage{xcolor}
\usepackage{listings}

\def\beginlstdelim#1#2#3%
{%
    \def\endlstdelim{#2\egroup}%
    \ttfamily#1\bgroup\color{#3}\aftergroup\endlstdelim%
}

\lstdefinestyle{test}{%
    language={[latex]TeX},
    tabsize=2,
    breaklines,
    basicstyle=\footnotesize\ttfamily,
    texcsstyle=*\color{blue}\bfseries,
    keywordstyle=\color{red}\bfseries,
    moretexcs={test},
    moredelim = **[is][\beginlstdelim{\{}{\}}{red}]{\{}{\}}
}

\lstset{style=test}

\begin{document}

\begin{lstlisting}
    \begin{environment}
        \test{foo}{bar}
    \end{environment}

    foo bar
\end{lstlisting}

\end{document}

Output:

colored output

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