# Why are amsmath \xleftarrow & friends not working in listings?

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?

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}{}\$