Generallstlisting in NewDocumentEnvironment

LaTeX specific issues not fitting into one of the other forums of this category.
Post Reply
weltio
Posts: 6
Joined: Tue Dec 25, 2012 3:52 am

lstlisting in NewDocumentEnvironment

Post by weltio »

Hello
is it possible to create a lstlisting environment which is numbered and where I get a listof command?

My try:

Code: Select all

\documentclass{book}
\usepackage{xparse,tocloft,listings}


\newcommand{\codelist}{Codelist}
\newlistof{code}{cod}{\codelist}
\NewDocumentEnvironment{code}{m}
{
	\begin{lstlisting}
	\refstepcounter{code}
	\addcontentsline{cod}{code}
	{\protect\numberline{\thechapter.\thecode}#1}\par
}
{\caption{#1}\end{lstlisting}}

\begin{document}
\begin{code}{Caption}
Some Code
\end{code}
\listofcode

\end{document}
But this doesnt work since i get:
! Missing \endcsname inserted.
<to be read again>
\global
l.17 \begin{code}{Caption}
Does anybody has an idea to fix it or an alternative?

Recommended reading 2024:

LaTeXguide.org • LaTeX-Cookbook.net • TikZ.org

NEW: TikZ book now 40% off at Amazon.com for a short time.

And: Currently, Packt sells ebooks for $4.99 each if you buy 5 of their over 1000 ebooks. If you choose only a single one, $9.99. How about combining 3 LaTeX books with Python, gnuplot, mathplotlib, Matlab, ChatGPT or other AI books? Epub and PDF. Bundle (3 books, add more for higher discount): https://packt.link/MDH5p

cgnieder
Site Moderator
Posts: 2000
Joined: Sat Apr 16, 2011 7:27 pm

lstlisting in NewDocumentEnvironment

Post by cgnieder »

Why don't you just use »listings« own mechanism?

Code: Select all

\documentclass{book}
\usepackage{listings}

\lstnewenvironment{code}[1]
  {%
    \lstset{
      float,caption=#1,
      basicstyle=\ttfamily,
      numbers=left,
      numberstyle=\footnotesize
    }%
  }
  {}

\begin{document}

\lstlistoflistings

\begin{code}{Caption}
 Some Code
\end{code}

\begin{code}{Some Other Caption}
 more code
 on two lines
\end{code}

\end{document}
Regards
site moderator & package author
weltio
Posts: 6
Joined: Tue Dec 25, 2012 3:52 am

lstlisting in NewDocumentEnvironment

Post by weltio »

Why don't you just use »listings« own mechanism?
Just because I'm stupid. Your solution works perfectly. Thank you!
Post Reply