1
  • I want to change the font color in a listing.
  • I want only several lines in the listing to change its color (e.g. 1, 2, 9, 10, 12, 13). That is, I want to apply the color to individual lines of the listing.
  • I want the line number that match the colored lines to be colored as well (e.g. 1, 2, 9, 10, 12, 13).
  • I want the color to be expressed in HTML (hexadecimal) format.
  • I am including the listing's content from a separate file.

How can I accomplish this?

This is my snippet (the included listing is now local for demonstration purposes):

\documentclass{article}

\usepackage{listings}

\usepackage{xcolor}

\definecolor{custom_grey}{HTML}{818181}

\lstdefinestyle{base}{
  moredelim=**[is][\color{custom_grey}]{@}{@},
}

\renewcommand\thelstnumber{%
  \ifnum\value{lstnumber}=10
  \else
    \ifnum\value{lstnumber}>10
      \the\numexpr\value{lstnumber} + 5\relax%
    \else
      \arabic{lstnumber}%
    \fi
  \fi
}

\begin{document}

\begin{lstlisting}[numbers = left, style=base]
@#First comment@
@...@
'YY-MM-DD HH:MM:SS.sss'
|Code line|
--------------------------------------------------------
========================================================
|Code :: line|
========================================================
@#Additional comment@
@...@
'YY-MM-DD HH:MM:SS.sss'
@#End comment@
@...@
\end{lstlisting}

\end{document}
2
  • When changing the lstlisting environment into a \lstinputlisting call, the code is formatted correctly for me (also with the red highlight). Could you be more clear about what exactly fails for you? Also, the syntax for RGB and HTML color schemes is defined in the xcolor manual.
    – siracusa
    Commented Oct 28, 2018 at 0:22
  • I just edited my question
    – jlnkls
    Commented Oct 29, 2018 at 10:06

1 Answer 1

2

Hope the below may help you:

\documentclass{article}

\usepackage{listings}

\usepackage{xcolor}

\definecolor{custom_grey}{HTML}{818181}

\lstdefinestyle{base}{
  moredelim=**[is][\color{custom_grey}]{@}{@},
}

\renewcommand\thelstnumber{%
  \ifnum\value{lstnumber}=1
{     \color{custom_grey}\arabic{lstnumber}}%
\else
  \ifnum\value{lstnumber}=9
{     \color{custom_grey}\arabic{lstnumber}}%
\else
  \ifnum\value{lstnumber}=12
{     \color{custom_grey}\arabic{lstnumber}}%
\else
\arabic{lstnumber}%
  \fi\fi\fi
}

\begin{document}

\begin{lstlisting}[numbers = left,
style=base]
@#First comment@
@...@
'YY-MM-DD HH:MM:SS.sss'
|Code line|
--------------------------------------------------------
========================================================
|Code :: line|
========================================================
@#Additional comment@
@...@
'YY-MM-DD HH:MM:SS.sss'
@#End comment@
@...@
\end{lstlisting}

\end{document}

Output:

enter image description here

1
  • Glad to know that my suggestion helps you...
    – MadyYuvi
    Commented Oct 31, 2018 at 14:05

You must log in to answer this question.

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