Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

up vote 5 down vote accepted

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

share|improve this answer
    
"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

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;

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.