#StackBounty: #listings #highlighting #keywords Add keywords to listings in preamble or lstlang1.sty

Bounty: 50

Some keywords I want to add

I would like to add a few keywords for C, but am having difficulty. The keywords I would like to include are bool, simd, omp, restrict, etc. I would like these to be just for the C language.

Editing the style directly

I would like to ‘update’ these to the language style definition in the document’s preamble, but there doesn’t seem a nice interface to this. My current solution is to directly adjust the settings in
/usr/local/texlive/2019/texmf-dist/tex/latex/listings/lstlang1.sty
where I add them to the ANSI C definition around line 251 by adding these to the the morekeywords and otherkeywords such as:

lst@definelanguage[ANSI]{C}{%
morekeywords={auto,break,...etc...,volatile,while,omp,simd,restrict},%
otherkeywords={#pragma},% <-- Added to catch indented #pragma
...
}

This gives the desired output

enter image description here

for

documentclass{article}
usepackage{listings}
begin{document}
begin{lstlisting}[language=C]
#pragma omp simd
void foo(int * restrict a, int n, int n_simd)
{
    #pragma omp simd
    for (int i = 0; i < n; i++)
    {
        a[i] *= 2; /* Computation */
    }
}
end{lstlisting}
end{document}

Can something be put in the pramble?

Ultimately I would like something more portable that can just be put in the document’s preamble, but the following attempts haven’t succeeded:

lstset{otherkeywords={#pragma,omp,simd}}
lstdefinestyle{C}{morekeywords={restrict}}
lstset{%
    language={C},%
    morekeywords={auto,...
...
}

New environment/language/style

Preferably I would rather avoid creating a new language or style such as myC or similar, and would prefer just declaring language=C as this seems better practice and avoids having to refactor my code.

Related questions


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.