[Tex/LaTex] generation of sty file from dtx fails

dtx

I have implemented a dtx file with listings code according to the answer of this question:
How to add listings environment to DTX files

where the listings code is placed in the dtx file as

% \iffalse
% <*example>
% \fi
\begin{lstlisting}%
\usepackage{test}
\end{lstlisting}
% \iffalse
% </example>
% \fi

This works well to generate a pdf file. However with this ins file:

\input docstrip.tex
\keepsilent
\askforoverwritefalse
\generate{%
  \file{test.sty}{\nopreamble\from{test.dtx}{test.sty}}%
}
\endbatchfile

I can not generate a valid sty file. It only contains:

\begin{lstlisting}%
\usepackage{test}
\end{lstlisting}

\endinput
%%
%% End of file `test.sty'.

where the dtx file is (for testing reduced to show the error) this one:

% \iffalse meta-comment
%
% \fi
%
% \iffalse
%<*driver>
\ProvidesFile{test.dtx}
%</driver>
%<package>\NeedsTeXFormat{LaTeX2e}[1999/12/01]
%<package>\ProvidesPackage{test}
%<*package>
[2011/10/01 0.1 enhanced table commands for configurable table layout]
%</package>
%
%<*driver>
\documentclass{ltxdoc}
%\usepackage{test}
\EnableCrossrefs
\CodelineIndex
\RecordChanges
%
\RequirePackage{listings}
\lstloadlanguages{[LaTeX]TeX}
\begin{document}
  \DocInput{test.dtx}
  \PrintChanges
  \PrintIndex
\end{document}
%</driver>
% \fi
%
% \GetFileInfo{test.dtx}
% \title{The \textsf{test} package}
% \author{Matthias Pospiech}
% \date{\fileversion~from \filedate}
%
% \maketitle
% \subsection{Loading}
% The package is loaded with
% \iffalse
% <*example>
% \fi

\begin{lstlisting}%
\usepackage{test}
\end{lstlisting}

% \iffalse
% </example>
% \fi
%
% \StopEventually{}
% \clearpage
% \section{Implementation}
%
% \iffalse
%<*package>
% \fi
%
%    \begin{macrocode}
\NeedsTeXFormat{LaTeX2e}[1994/12/01]
\ProvidesPackage{test}
          [2011/10/01 v0.1 test]
%    \end{macrocode}
%
% \iffalse
%</package>
% \fi
%
% \Finale
\endinput

so actually the sty file should contain:

\NeedsTeXFormat{LaTeX2e}[1994/12/01]
\ProvidesPackage{test}
     [2011/10/01 v0.1 test]

What is wrong ?

Best Answer

Change the lines

\generate{%
  \file{test.sty}{\nopreamble\from{test.dtx}{test.sty}}%
}

to

\generate{%
  \file{test.sty}{\nopreamble\from{test.dtx}{package}}%
}

The last argument of \from is the "guard" that determines which snippets of code to include, corresponding to the lines

%<*package>
...
%</package>

in your file.

Related Question