3

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}
3

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}

enter image description here

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

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.