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 am using the listings package, which is mostly formatting things nicely. However, it fails to syntax highlight indented preprocessor commands correctly.

For example,

\documentclass{article}
\usepackage{listings}
\begin{document}
\lstset{language=C}
\begin{lstlisting}
#if SYSTEM == SYSV
#    define HDR "sysv.h"
#if SYSTEM == SYSV
    #define HDR "sysv.h"
\end{lstlisting}
\end{document}

The first #define keyword is highlighted properly, but the second #define keyword is not highlighted at all. For old compilers, the # symbol had to the be first character of preprocessor commands, but modern style prefers the latter system for indentation. So, I would prefer to indent the # symbol.

enter image description here

Are there any ways I can indent this symbol and have the syntax highlighting come out correctly in the listings package?

share|improve this question
    
The first #define does not seem to be highlighted. –  Peter Grill May 16 '12 at 20:08
    
It is not in color by default, but it is bolded. The second one is not bolded. –  Dan May 16 '12 at 20:10
    
Sorry, you are right. I had indents on every line. There should only be indents on the fourth line of the lstlisting. –  Dan May 16 '12 at 20:13
add comment

1 Answer

up vote 5 down vote accepted

If you add \lstset{otherkeywords={define,\# }}, then the output should be what you are looking for:

enter image description here

It appears that the # and if are highlighted separately. You can see that if you attempt to use #ifx, then the # is still highlighted, but not the ifx. So by specifying that define is to be treated as a keyword, you get the desired results.

Code:

\documentclass{article}
\usepackage{listings}
\begin{document}
\lstset{language=C}
\lstset{otherkeywords={define,\# }}%

\begin{lstlisting}
#if SYSTEM == SYSV
#    define HDR "sysv.h"
#if SYSTEM == SYSV
    #define HDR "sysv.h"
\end{lstlisting}
\end{document}
share|improve this answer
    
Thanks, Peter. This works and my code is highlighted correctly now. Interestingly, you cannot define # as a keyword using morekeywords={\#}, but you can define it as a keyword using otherkeywords{\#}. –  Dan May 16 '12 at 21:19
add comment

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.