1

I want to change the color of some part of the code in listing. Here is the MWE I have tried:

\lstdefinestyle{mystyle}
  {escapechar=\%}
\lstset{style=mystyle}
\lstinputlisting{Pro/Code.java}

Inside of the Pro/Code.java:

public static int foo(String s1)
{
 %\color{light-gray}{int M = s1.length();}%
  ... // other stuff won't be highlighted
}

Now I am struggling to change the color of { and }, which seems to conflict with { (or }) in the macro %\color{light-gray}{....}%". What is the solution?

2 Answers 2

2

Since you're escaping to LaTeX, you need to escape { and } (as in \{ and \}) in order to print them explicitly.

enter image description here

\documentclass{article}

\usepackage{listings,xcolor}

\lstdefinestyle{mystyle}
    {escapechar=\%}
\lstset{style=mystyle}

\begin{document}

\begin{lstlisting}
public static int foo(String s1)
{
 %\color{black!50}\{ int M = s1.length();\}%
  ... // other stuff won't be highlighted
}
\end{lstlisting}

\end{document}
3

You shouldn't use an escape character to highlight individual parts of the code, because special characters need to be escaped by hand and the alignment of text will not correspond to the one of the rest of the listing (see also Aligning escaped text in listings).

Instead you could define a new delimited environment by

moredelim=[is][\color{gray}]{\%}{\%}

which will parse the text between %...% like usual but apply gray color to it. i makes the delimited characters invisible.

Full example:

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

\lstdefinestyle{mystyle}{
    moredelim=[is][\color{gray}]{\%}{\%}
}
\lstset{
    style=mystyle,
    basicstyle=\ttfamily
}

\begin{document}
\begin{lstlisting}
public static int foo(String s1)
{
 %{int M = s1.length();}%
  ... // other stuff won't be highlighted
}
\end{lstlisting}
\end{document}

outputs

enter image description here

You must log in to answer this question.

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