0

I would like to redefine a short command (without \begin ... \end) for single line code examples using the listings package.

Here is what I tried:

\documentclass{article}
\usepackage{listings}

\newcommand{\my}[1]{
\begin{lstlisting}
#1
\end{lstlisting}
}

\begin{document}
\my{code}
\end{document}

However, it gives the following error:

! Emergency stop.
<*> example.tex
*** (job aborted, no legal \end found)

Using lstlisting directly works, though:

\documentclass{article}
\usepackage{listings}

\begin{document}
\begin{lstlisting}
code
\end{lstlisting}
\end{document}
  • 1
    You're trying to handle verbatim code (listing environment) inside an argument-- this does not work! In my opinion, such shorthands are not useful in 99.9 % of all cases anyway. They will prove as shoot in the foot in the long turn – user31729 Sep 7 '16 at 13:08
  • 1
    Short version: you can't do this. See e.g. Why can lstlisting not be saved in a command? – Torbjørn T. Sep 7 '16 at 13:08

Browse other questions tagged or ask your own question.