# Semantic nesting error from underscores with listings while syntax is loaded

I use XeLaTeX and have TeXLive 2015 installed.

I want to use both the listings package for printing code and the syntax package for printing grammars. For code, I also want to expand certain symbols als literate mathematical strings, for example I want N0 to yield ‘N₀’, consuming two characters. To this end, one may use the literate facility of the listings package, see its documentation.

Now, here’s my problem: Running xelatex on

\documentclass{article}
\usepackage{
listings,
%   syntax,
}

\begin{document}

\lstset{
literate={N0}{{$N$}{$_0$}} 2
}

\begin{lstlisting}[mathescape]
N0 $N_0$
\end{lstlisting}

\end{document}


yields a result as expected, but uncommenting the line % syntax, to load the syntax package, will give a semantic nesting error on compiling:

! TeX capacity exceeded, sorry [semantic nest size=500].

l.16 ^^IN0
$N_0$
No pages of output.


I found out that the culprit is the mathematical underscore in literate={N0}{{$N$}{$_0$}} 2, and only in the literate part. Replacing this line by literate={N0}{{$N$}{$0$}} 2 (i.e. removing the underscore) will let xelatex compile again. Note that there still is a mathematical underscore in $N_0$ inside of the listing environment.

What is going on? Can I prevent this from happening?

Please, don't use the minimal class for testing, see Why should the minimal class be avoided?

You have two ways for avoiding the infinite loop: either doing \lstset in the preamble or using \sb instead of _.

## First way

\documentclass{article}
\usepackage{
fontspec,
unicode-math,
listings,
syntax,
}

\lstset{
literate={N0}{{$ℕ$}{$_0$}}2
}

\begin{document}

\begin{lstlisting}[mathescape]
N0 $ℕ_0$
\end{lstlisting}

\end{document}


## Second way

\documentclass{article}
\usepackage{
fontspec,
unicode-math,
listings,
syntax,
}

\begin{document}

\lstset{
literate={N0}{{$ℕ$}{$\sb0$}}2
}

\begin{lstlisting}[mathescape]
N0 $ℕ_0$
\end{lstlisting}

\end{document}


## Output for both

• This is, of course, already a completely satisfactory answer. I’m going with the second way. Thanks! It might be nice for some to actually see a hint for why the problem only occurs on loading the syntax package. I’m kinda curious myself, though I’m not sure I’ll understand it. But as said, I’m perfectly content either way. – k.stm Jun 4 '16 at 10:40
• @k.stm The reason is quite involved: the syntax package makes _ into an active character at begin document, but for its purposes listings considers it with its standard category code when evaluating options. Chaos ensues: groups are opened in series and the semantic nest size is exhausted, but it's essentially an infinite loop. – egreg Jun 4 '16 at 10:54