[Tex/LaTex] How to use angle brackets for a keyword in \listings

htmlkeywordslistings

I've got a code of a HTML website that I want to show in my LaTeX document. The problem is, that the HTML code has a tag called <canvas> and the JavaScript code inside the HTML document has a variable called canvas too.

If I set canvas as a keyword for the language that is used to style the code, then both words (the canvas tag and the canvas variable name) get highlighted. But I only want the tag to be blue.

So I thought, I can specify a keyword called <canvas to prevent that the word without angle brackets is highlighted. But morekeywords={<canvas} does not work.

MWE:

\documentclass{scrreprt}
\usepackage{color}
\usepackage{upquote}
\usepackage{listings}
\lstdefinelanguage{JavaScript}{
  morekeywords={var, function},
  morecomment=[s]{/*}{*/},%
  morecomment=[l]//,%
  morestring=[b]",%
  morestring=[b]'%
}

\lstdefinelanguage{HTML5}{
    language=html,
    sensitive=false,        
    morekeywords={<canvas},
    otherkeywords={<, >, !},
    tag=[s]
}

\lstset{%
    % Basic design
    basicstyle={\small\ttfamily},
    % Code design   
    keywordstyle=\color{blue}\bfseries,
    stringstyle=\color{red},
    % Code
    language=HTML5,
    alsolanguage=JavaScript,
    tabsize=2,
    showtabs=false,
    showspaces=false,
    showstringspaces=false,
    extendedchars=true,
    breaklines=true,
    alsodigit={.:;}
    % alsoletter={},
}
\begin{document}
    \begin{lstlisting}
<!DOCTYPE html>
<html>
  <head>
    <title>Canvas</title>
    <meta charset="UTF-8" />
  </head>
  <body>
    <canvas id="square" width="200" height="200"></canvas>
    <script>
            var canvas = document.createElement('canvas');
            canvas.width = 200;
            canvas.height = 200;

            var image = new Image();
            image.src = 'images/card.png';
            image.width = 114;
            image.height = 158;
            image.onload = window.setInterval(function() {
                rotation();
            }, 1000/60);
   </script>
  </body>
</html>
    \end{lstlisting}
\end{document}

Screenshot:

enter image description here

Can someone help me?

Best Answer

It seems that "other keywords" are processed first. So < is recognized as a keyword and not <canvas. This would help:

\lstdefinelanguage{HTML5}{
    language=html,
    sensitive=false,
    alsoletter={<},
    morekeywords={<canvas},
    %otherkeywords={<, >, !},
    tag=[s]
}

... but then you'd have to manually define all the possible tag names (or rather, <tagname) as keywords ;-(