[Tex/LaTex] Why are amsmath \xleftarrow & friends not working in listings

amsmathlistings

I would like to use literate= to substitute \xleftarrow (and custom variants thereof) for some listing elements. See the example.

\begin{filecontents*}{\jobname.rule}
A <*>  B
A <== B
\end{filecontents*}

\documentclass{article}

\usepackage{listings}

\usepackage{amsmath}

\makeatletter
\newcommand{\xLeftrightarrow}[2][]{\ext@arrow 0359\Leftrightarrowfill@{#1}{#2}}
\makeatother


\begin{document}

\lstinputlisting[
    label=lst:rules,
    caption={Rules},
    literate={<*>}{$\xLeftrightarrow{*}{}$}3{<==}{$\xleftarrow{x}{}$}3
]{\jobname.rule}

$\xLeftrightarrow{*}{}$
$\xleftarrow{x}{}$

\end{document}

The text supposed to flow above the arrows, in the listing only, becomes appended. Can this be fixed? Alternatives compatible with listings?

Best Answer

From the listings manual, p. 50:

Each 'printing unit' in <replacement text> must be in braces unless it’s a single character.

So in this case you need literate={<*>}{{$\xLeftrightarrow{*}{}$}}3{<==}{{$\xleftarrow{x}{}$}}3 with extra braces around the $\xLeftrightarrow{*}{}$ and \xLeftrightarrow{x}{}$.

MWE:

\begin{filecontents*}{\jobname.rule}
A <*>  B
A <== B
\end{filecontents*}

\documentclass{article}

\usepackage{listings}

\usepackage{amsmath}

\makeatletter
\newcommand{\xLeftrightarrow}[2][]{\ext@arrow 0359\Leftrightarrowfill@{#1}{#2}}
\makeatother


\begin{document}

\lstinputlisting[
    label=lst:rules,
    caption={Rules},
    literate={<*>}{{$\xLeftrightarrow{*}{}$}}3{<==}{{$\xleftarrow{x}{}$}}3
]{\jobname.rule}

$\xLeftrightarrow{*}{}$
$\xleftarrow{x}{}$

\end{document}

Result:

enter image description here

Related Question