[Tex/LaTex] Adding keywords to multiple languages in `listings` package

keywordslistings

I have a pdflatex project where I need both Python and SQL listings. The listings package works great, I was able to add and reformat the extra keywords for Python with the following code:

\lstset{
    language=python,
    basicstyle=\small,
    identifierstyle=\ttfamily,
    keywordstyle=\bfseries\ttfamily\color[rgb]{0,0,1},
    stringstyle=\ttfamily\color[rgb]{0.627,0.126,0.941},
    morekeywords={cls,self,abstractmethod,classmethod,
                  __call__,__import__,__init__, __nonzero__,None}
}

However, I need to add extra SQL keywords as well, that are not valid in Python, like REFERENCES. How do I add keywords for different languages?

Thank you.

Best Answer

You can define two separate styles, or even two separate environments.

\documentclass[]{article}

\usepackage{xcolor}
\usepackage{listings}


\lstdefinestyle{Python}
{
    language=python,
    basicstyle=\small,
    identifierstyle=\ttfamily,
    keywordstyle=\bfseries\ttfamily\color[rgb]{0,0,1},
    stringstyle=\ttfamily\color[rgb]{0.627,0.126,0.941},
    morekeywords={cls,self,abstractmethod,classmethod,
                  __call__,__import__,__init__, __nonzero__,None}
}

\lstdefinestyle{Sql}
{
    language=SQL,
    basicstyle=\small,
    identifierstyle=\ttfamily,
    keywordstyle=\bfseries\ttfamily\color[rgb]{0,0,1},
    stringstyle=\ttfamily\color[rgb]{0.627,0.126,0.941},
    morekeywords={REFERENCES}
}


\lstnewenvironment{sql}
{\lstset{style=Sql}}
{}

\lstnewenvironment{python}
{\lstset{style=Python}}
{}

\begin{document}


\begin{python}
    parents, babies = (1, 1)
     while babies < 100:
    print 'This generation has {0} babies'.format(babies)
    parents, babies = (babies, parents + babies)
\end{python}

\begin{sql}
  CREATE TABLE STATION
(ID INTEGER PRIMARY KEY,
CITY CHAR(20),
STATE CHAR(2),
LAT_N REAL,
LONG_W REAL);
REFERENCES
\end{sql}
\end{document}

enter image description here

Related Question