# Add key for new Listings environment

I'm trying to add a new key to a custom listings environment. I have tried to modify this example.

My problem is that the value I am attempting to pass through in the document for the key does not seem to be used.

Here is an MWE:

\documentclass{article}

\usepackage{listings}

\makeatletter
\lst@Key{pagewidth}{\linewidth}{\def\LSTwidth{#1}}
\makeatother

\lstnewenvironment{mylisting}[1][]{%
\noindent
\minipage{\LSTwidth}
\lstset{#1}
}
{\endminipage}

\begin{document}

\centering
\begin{mylisting}[pagewidth=0.5\linewidth, frame=lrtb]
NOT IMPORTANT NOT IMPORTANT
NOT IMPORTANT NOT IMPORTANT
\end{mylisting}

\end{document}

-

## 1 Answer

Move the line \lstset{#1} before the minipage:

\documentclass{article}
\usepackage{listings}

\makeatletter
\lst@Key{pagewidth}{\linewidth}{\def\LSTwidth{#1}}
\makeatother

\lstnewenvironment{mylisting}[1][]{%
\noindent
\lstset{#1}
\minipage{\LSTwidth}
}
{\endminipage}

\begin{document}

\hrulefill

\centering
\begin{mylisting}[pagewidth=0.5\linewidth, frame=lrtb]
NOT IMPORTANT NOT IMPORTANT
NOT IMPORTANT NOT IMPORTANT
\end{mylisting}

\end{document}


I added a horizontal rule just for visualization purposes.

By the way, listings already has a linewidth key with a similar functionality.

-
Thanks! I have a very superficial understanding of how this works. Is the key only available after #1 is expanded? –  Thomas Apr 16 '13 at 17:19
@Thomas You're welcome. As you had it, minipage was not aware of the change to its width, because the change was being made after the initial value (\linewidth) had been used as the width for the minipage. –  Gonzalo Medina Apr 16 '13 at 17:29