6

I'm trying to this:

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

But I keep getting this error:

Package Listings Warning: Text dropped after begin of listing

I'm calling \usepackage and all so, do any of you knows how to solve this?

6
  • 4
    You can't put verbatim material in the argument to another command and listings material is like verbatim.
    – egreg
    Jun 13, 2012 at 15:10
  • Is there any other way of doing it? Or do i have to do "manually" for my every piece of code?
    – Nuno
    Jun 13, 2012 at 15:14
  • Where's the convenience of \code{foo} with respect to \begin{lstlisting}foo\end{lstlisting}? Particularly when foo is several lines. If you need to get "inline" listings, consider the command \lstinline.
    – egreg
    Jun 13, 2012 at 15:15
  • It's more pratic writing it, that's all.
    – Nuno
    Jun 13, 2012 at 15:16
  • Welcome to TeX.SE. Jun 13, 2012 at 17:10

2 Answers 2

3

Inline Listings:

If you want inline listings you can use \lstinline{listing content}. If the content of the listings contains curly braces you could actually use a different character to delimit the start and end as in \lstinlinelisting content with {}`:

enter image description here

Code:

\documentclass{article}
\usepackage{listings}
\usepackage{xcolor}

\lstset{basicstyle=\ttfamily\small\color{blue}}

\begin{document}
To have inline listings use  \lstinline{listing content} to get the formatting.

To have inline listings use  \lstinline`listing content with {}` to get the formatting.
\end{document}

Displayed Listings:

For displayed listings, you need to use

\begin{lstlisting}
    ... code to be formatted ...
\end{lstlisting}

or you can define your own environment via \lstnewenvironment.

enter image description here

Code:

\documentclass{article}
\usepackage{listings}
\usepackage{xcolor}

\lstset{basicstyle=\ttfamily\small\color{blue}}

\begin{document}
\noindent
For displayed listings use  \verb|\begin{lstlisting} ... \end{lstlisting}|
\begin{lstlisting}
   listing content
\end{lstlisting}
to get the formatting.
\end{document}
3

use listings own definition for new environments:

\documentclass{article}
\usepackage{listings}
\usepackage{xcolor}
\lstnewenvironment{code}
  {\lstset{basicstyle=\ttfamily\small,keywordstyle=\color{blue},
           language=[LaTeX]{TeX},frame=single,backgroundcolor=\color{blue!20}}}
  {}
\begin{document}
\noindent foo
\begin{code}
\lstnewenvironment{code}{basicstyle=\ttfamily\small}
\end{code}
bar
\end{document}

enter image description here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .