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?

egreg
  • 1,121,712
Nuno
  • 61

2 Answers2

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 \lstinlinelisting 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}

Peter Grill
  • 223,288
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