5

I am using the listings package to typeset code. I have defined a custom style using \lstdefinestyle{verbo} and then typeset code in a lstlisting environment as in the following MWE.

\documentclass{article}

\usepackage[T1]{fontenc}  % to retain double quotes in lstlistings
\usepackage{listings}  % to typeset code
\usepackage{upquote}  % to retain single qutoes in lstlistings

\lstdefinestyle{verbo}{  % code typesetting optins
    basicstyle=\small\ttfamily,
    breaklines=true,
    breakatwhitespace=true,
    language=Python,
    tabsize=1,
    resetmargins=true,
    xleftmargin=0pt,
    frame=single,
    showstringspaces=false
}

\begin{document}

\begin{lstlisting}[style=verbo]
>>> print "Hello World!"
\end{lstlisting}

\end{document}

which produces Hello World

I would like to make the LaTeX code more readable by typing the following instead of the lstlisting environment but achieving the same result.

\begin{code}
>>> print "Hello World!"
\end{code}

I tried various things - defining a macro, a new command, a new environment - but all failed. Is there some way to do this?

Failed Attempts

Below are my failed attempts, all of which result in errors similar to the following

! Emergency stop.
<*> \input mwe-code.tex

!  ==> Fatal error occurred, no output PDF file produced!

Macro

\def\code{\begin{lstlisting}[style=verbo]}
\def\ecode{\end{lstlisting}}
  ...    
\code
>>> print "Hello World!"
\ecode

New command

\newcommand{\code}[1]{\begin{lstlisting}[style=verbo]#1\end{lstlisting}}
  ...
\code{
>>> print "Hello World!"
}

New environment

\newenvironment{code}
{\begin{lstlisting}[style=verbo]}
{\end{lstlisting}}
  ...
\begin{code}
>>> print "Hello World!"
\end{code}
9

There is \lstnewenvironment just for this:

\documentclass{article}

\usepackage[T1]{fontenc}  % to retain double quotes in lstlistings
\usepackage{listings}  % to typeset code
\usepackage{upquote}  % to retain single qutoes in lstlistings

\lstdefinestyle{verbo}{  % code typesetting optins
    basicstyle=\small\ttfamily,
    breaklines=true,
    breakatwhitespace=true,
    language=Python,
    tabsize=1,
    resetmargins=true,
    xleftmargin=0pt,
    frame=single,
    showstringspaces=false
}
\lstnewenvironment{code}[1][]
 {\lstset{style=verbo,#1}}
 {}

\begin{document}

\begin{code}
>>> print "Hello World!"
\end{code}

\begin{code}[columns=fullflexible]
>>> print "Hello World!"
\end{code}

\end{document}

I added the second one just to show how to add options to the code environment.

enter image description here

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.