4

Please consider this MWE:

\documentclass{article}

\usepackage{listings}
\usepackage{textcomp}
\usepackage{xcolor}

\lstset{
    columns=flexible,
    literate=
      {Public Class}{{Public Class\color{red}}}{12}
      {.Object}{{.\color{red}Object\color{black}}}{6}
}

\begin{document}

\begin{lstlisting}
Public Class Example

.Object = A
\end{lstlisting}

\end{document}

MWE output

I would like to have Example in red, but I am not able to do it.

I thought

{Public Class}{{Public Class\color{red}}}{12}

was going to fill any sequence of characters after Public Class, like

{.Object}{{.\color{red}Object}}{6}

enter image description here

(Note that I removed \color{black} and = A was filled with red.)

Important Example can be changed i.e. the red color should work for any sequence of characters of the same line of Public Class. This effect is removed in the next line.

EDIT Oh, I realized that the blank space of {Public Class} is the problem. I will search if this is a duplicate, though.

EDIT 2 I could not find a duplicate. I also edited the question because I forgot to add columns=flexible, which makes the things a bit more difficult, because as @Robert pointed out doing {Public\ Class} solves the problem, but adding columns=flexible does not work anymore.

  • {Public\ Class} ? – Robert Mar 8 '20 at 1:28
  • @Robert I thought the same; but there is a problem with the correct spacing, isn't it? – manooooh Mar 8 '20 at 1:32
  • yes, the whole string is printed as one token that is centred within the space given by the last argument, but this has nothing to do with the space, but is how the literate feature works -- try eg. {.IIIIII}{{.\color{red}IIIIII\color{black}}}{6} – Robert Mar 8 '20 at 1:59
  • @Robert there is another problem. In the document I am using columns=flexible which shrinks the characters width, so {Public\ Class} does not work anymore. – manooooh Mar 8 '20 at 15:20
  • 1
    yes, there's one more group involved in the case of flexible, so the color setting doesn't get carried over. Maybe instead of literate, you could use this: moredelim=**[il][\PublicClass]{Public\ Class} with \newcommand\PublicClass{Public Class\color{red}} – Robert Mar 8 '20 at 23:44
1

Instead of the literate key, you could use moredelim (building on this trick):

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

\lstset{
    columns=flexible,
    moredelim=**[il][\PublicClass]{Public\ Class},
}
\newcommand\PublicClass{Public Class\color{red}}

\begin{document}
\begin{lstlisting}
Public Class Example
\end{lstlisting}
\end{document}

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.