I am using the Latex Listings package to include code in a document. I need to implemented syntax highlighting similar to what you see in a standard IDE.
I've been able to assign colors to comments, keywords, and strings, but I am having some trouble figuring out how to color the numbers properly.
Here's an example of how it should look:
As you can see, anytime a word after the equals sign starts with a digit, all following characters until (but not including) the next semicolon or space are colored. When a word starts with a digit, all characters in the word should be colored, even if they are not digits. Otherwise, none of the digits are colored.
As of right now, I cannot think of a case where a word before the equals sign would start with a digit, so it will probably be acceptable to find a solution that colors all words starting with a digit.
In this case, digits are: 0-9.
Here's an MWE in Latex, but as you can see it doesn't have any coloring for the numbers.
\documentclass[pdftex]{report}
\usepackage{listings}
\usepackage[usenames,dvipsnames,svgnames,table]{xcolor}
\definecolor{Code}{rgb}{0,0,0}
\definecolor{Keywords}{rgb}{255,0,0}
\definecolor{Strings}{rgb}{255,0,255}
\definecolor{Comments}{rgb}{0,0,255}
\definecolor{Numbers}{rgb}{255,128,0}
\lstdefinestyle{mycode}{
language=C,
% Comments
commentstyle=\color{Comments}\slshape,
% Strings
stringstyle=\color{Strings},
% keywords
keywordstyle={\color{Keywords}\bfseries}
}
\begin{document}
\begin{lstlisting}[style=mycode]
int main ()
{
//this is an example
a1 = 0;
a2 = a1;
a3 = 16hxFF;
a4 = 16 + a1;
return 0;
}
\end{lstlisting}
\end{document}
Best Answer
Here is an adaptation of Coloring digits with the listings package:
Notes:
newtoggle
from theetoolbox
package as I prefer that syntax versus the\newif
syntax. But if you don't want to include an additional package it should be pretty straightforward to adapt this to use\newif
or some other conditional methods.Further Enhancements:
16hxFF
will not be properly displayed, but16x
(with trailing space) is fine.Code: