1

Consider this MWE:

\documentclass{article}
\usepackage{xcolor}
\usepackage{listings}
\lstdefinelanguage{XML}{
  commentstyle=\color{gray},
  breaklines=true,
  morestring=[b]",
  morestring=[s]{>}{<},
  morecomment=[s]{<!--}{-->},
  stringstyle=\color{black},
  identifierstyle=\color{red},
  keywordstyle=\color{cyan},
}

\begin{document}


\begin{lstlisting}[language=xml]
<baz>foo <b>foo</b> foo
<!-- a comment -->
  bar bar bar.</baz>
\end{lstlisting}

\end{document}

which gives this result (TL2016)

xml formatting result

The problem here is that the comment should be gray, but instead it is not distinguishable from the other markup. Any way to keep the text 'foo' black and get the comment gray at the same time? When I remove line 8 (the second morestrings line), I get the comments as I want, but the text red.

3

I don't find it very sane to define everything not in a tag as a string. It would be better to set the tag color to red. The problem with this approach is that listings colors the delimiters in the style of the content. If you want black delimiters you could try this patch (I did use a XMLnew language in my tests to avoid side-effects from the existing xml, but I don't know if it is really necessary):

\documentclass{article}
\usepackage{xcolor}
\usepackage{listings}

\makeatletter
\def\lst@DelimPrint#1#2{%
      #1%
      \begingroup
        \lst@mode\lst@nomode \lst@modetrue
        #2\delimstyle\lst@XPrintToken%
      \endgroup
      \lst@ResetToken
    \fi}
\makeatother
\newcommand\delimstyle{}

\lstdefinelanguage{XMLnew}{
  tag=**[s][\color{red}\renewcommand\delimstyle{\color{black}}]<>,
  commentstyle=\color{gray},
  breaklines=true,
  morestring=[b]",
  morecomment=[s]{<!--}{-->},
  keywordstyle=\color{cyan},
}[keywords,comments,strings,html]%



\begin{document}


\begin{lstlisting}[language=XMLnew]
<baz>foo <b>foo</b> foo
<!-- a comment -->
  bar bar bar.</baz>
\end{lstlisting}

\end{document}

enter image description here

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.