[Tex/LaTex] Compilation fails with “! Missing \endcsname inserted.”

compilinglistingsmacros

Hi I've got a strange problem. I've defined a new command to print Linux commands line in the document:

\documentclass[12pt,a4paper]{article}
\usepackage{listings}
\newcommand{\shellcmd}[1]
{
  \begin{lstlisting}
    {#1}
  \end{lstlisting}
}

\begin{document}
\shellcmd{gdb \textit{program core}}
\end{document}

If I don't use my own defined command but use \begin...\end then it compiles. If I however use the command then I get:

! Missing \endcsname inserted.
<to be read again> 
                   \protect 
l.11 \shellcmd{gdb \textit{program core}}

Not sure how to resolve this. I haven't seen a similar problem online.

Best Answer

LaTeX is not known for its transparent error messages, so this one has nothing to do with the actual problem. In fact, the issue is that the lstlisting environment is a form of "verbatim" text, which requires special care in being used as input. This is the subject of at least one previous question (actually, I found several; this one seemed similar to yours), and the reason is that such an environment needs its contents to be "pristine" and not previously scanned by TeX. As egreg suggests in his comment, you should use \lstinline instead; however, that too cannot be buried in another macro, for the same reason. Use it directly instead of \shellcmd.

Related Question