7

I would like to force the listings package to be more selective when highlighting keywords. I'm currently including C source files in my document, and while I'm happy that occurrences of the float keyword are properly highlighted, I'd like the following line to appear as

#include <float.h>

instead of the current

#include <float.h>

In a similar spirit, else is fine, but #else should be typeset instead of #else.

I tried solutions like using deletekeywords={float.}, but to no avail (unsurprisingly, according to the documentation: "(...) by default some characters are not allowed inside keywords, for example ‘-’, ‘:’, ‘.’, and so on. (...)"). Playing with deletedirectives led nowhere either.

8

The keyword is float without dot, not float.:

\documentclass{article}
\usepackage{listings}
\begin{document}
\begin{lstlisting}[language=C, deletekeywords={float}]
#include <float.h>
\end{lstlisting}
\end{document}

Result

It is more difficult to have both. The literate feature seems to do the trick:

\documentclass{article}
\usepackage{listings}
\begin{document}
\begin{lstlisting}[
  language=C,
  literate={float.}{float.}6,
]
#include <float.h>
float a = 1.0;
\end{lstlisting}
\end{document}

Result

If you do not want a special formatting of directives, it can be disabled by an empty directivestyle:

\documentclass{article}
\usepackage{listings}
\begin{document}
\begin{lstlisting}[
  language=C,
  directivestyle={},
  literate={float.}{float.}6,
  columns=flexible,
]
#include <float.h>
float a = 1.0;
#ifdef foo
#else
#endif
\end{lstlisting}
\end{document}

Result

  • "The keyword is float without dot, not float. (...)": yes, but the one with the dot was the one I wanted to remove. Other than that, the literate trick works perfectly, thanks! – Anthony Labarre May 14 '13 at 17:29
2

The solution to this problem turned out to be subtle.

\lstset{
    language=C,
    directivestyle=\color[HTML]{006E28},
    deletedelim=*[directive]\#,
    moredelim=[directive][directivestyle]\#,
}

From the listings manual:

moredelim=[\*[*]] [<type>] [[<style>]]<delimiter(s)>

If you use one optional star, the package will detect keywords, comments, and strings inside the delimited code. With both optional stars, aditionally the style is applied cumulatively;

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.