[Tex/LaTex] Extend a language with additional keywords

keywordslanguageslistings

I'm using listings and I want to extend a language with additional keywords for highlightning. I know there is an option morekeywords available, but that only works for a particular lstset declaration and I don't want to have to copy-paste all keywords into all listings. I've tried declaring the keywords as part of a command but that doesn't work (probably because the command is not expanded and I don't know how to fix that).

So is there any way of declaring a new language by copying an existing one and just adding more keywords?

Best Answer

You can define the keywords in a separate file and just include it in your preamble. Here is an example of adding for and downto as new keywords:

enter image description here

\documentclass{article}
\usepackage{listings}%
\usepackage{xcolor}

\lstset{%
    backgroundcolor=\color{yellow!20},%
    basicstyle=\small\ttfamily,%
    numbers=left, numberstyle=\tiny, stepnumber=2, numbersep=5pt,%
    }%

% Add your keywords here, and have this in a separate file
% and include it in your preamble
\lstset{emph={%  
    downto, for%
    },emphstyle={\color{red}\bfseries\underbar}%
}%

\begin{document}
\begin{lstlisting}
y = 0
for i = n downto 0
    y = a_i + x * y
\end{lstlisting}
\end{document}