% \iffalse meta-comment
%
% Copyright (C) 2007 by
%    Joseph Wright <joseph.wright@morningstar2.co.uk>
%
% This work may be distributed and/or modified under the
% conditions of the LaTeX Project Public License, either
% version 1.3 of this license or (at your option) any later
% version. The latest version of this license is in
%    http://www.latex-project.org/lppl.txt
% and version 1.3 or later is part of all distributions of
% LaTeX version 2003/12/01 or later.
%
% This work has the LPPL maintenance status ``maintained.''
%
% The current maintainer of this work is Joseph Wright.
%
% This work consists of the source file notes2bib.dtx
%                 and the derived files notes2bb.ins,
%                                       notes2bib.sty and
%                                       notes2bib.pdf
%
% Unpacking:
%    (a) If notes2bib.ins is present:
%           tex notes2bib.ins
%    (b) Without notes2bib.ins:
%           tex notes2bib.dtx
%    (c) If you use LaTeX to generate files:
%           latex \let\install=y\input{notes2bib.dtx}
%
% Documentation:
%    (a) Without write18 enabled:
%          pdflatex notes2bib.dtx
%          bibtex8 --wolfgang notes2bib
%          makeindex -s gind.ist notes2bib.idx
%          makeindex -s gglo.ist -o notes2bib.gls  notes2bib.glo
%          pdflatex notes2bib.dtx
%          makeindex -s gind.ist notes2bib.idx
%          makeindex -s gglo.ist -o notes2bib.gls  notes2bib.glo
%          pdflatex notes2bib.dtx
%    (b) With write18 enabled:
%          pdflatex notes2bib.dtx
%          bibtex8 --wolfgang notes2bib
%          pdflatex notes2bib.dtx
%          pdflatex notes2bib.dtx
%  
% Installation:
%     Copy notes2bib.sty to a location searched by TeX, and
%     if required by your TeX installation, run the appropriate
%     command to build a hash of files (texhash, mpm --update-db, 
%     etc.)
% 
% Note:
%     The jawltxdoc.sty file is not needed for installation,
%     only for building the documentation.  It may be deleted.
%
%<*ignore>
% This is all taken verbatim from Heiko Oberdiek's packages
\begingroup
  \def\x{LaTeX2e}%
\expandafter\endgroup
\ifcase 0\ifx\install y1\fi\expandafter
         \ifx\csname processbatchFile\endcsname\relax\else1\fi
         \ifx\fmtname\x\else 1\fi\relax
\else\csname fi\endcsname
%</ignore>
%<*install>
\input docstrip.tex
\keepsilent
\askforoverwritefalse
\preamble
 ----------------------------------------------------------------
 note2bib --- Integrating notes into the bibliography
 Maintained by Joseph Wright
 E-mail: joseph.wright@morningstar2.co.uk
 Released under the LaTeX Project Public License v1.3 or later
 See http://www.latex-project.org/lppl.txt
 ----------------------------------------------------------------

\endpreamble
\Msg{Generating notes2bib files:}
\usedir{tex/latex/contib/notes2bib}
\generate{\file{\jobname.ins}{\from{\jobname.dtx}{install}}
          \file{\jobname.sty}{\from{\jobname.dtx}{package}}
          \file{jawltxdoc.sty}{\from{\jobname.dtx}{jawltxdoc}}
}
\endbatchfile
%</install>
%<*ignore>
\fi
% Will Robertson's trick
\immediate\write18{makeindex -s gind.ist -o \jobname.ind  \jobname.idx}
\immediate\write18{makeindex -s gglo.ist -o \jobname.gls  \jobname.glo}
%</ignore>
%<*driver>
\PassOptionsToClass{a4paper}{article}
\documentclass{ltxdoc}
\EnableCrossrefs
\CodelineIndex
\RecordChanges
%\OnlyDescription
% The various formatting commands used in this file are collected
% together in |jawltxdoc|.
\usepackage{jawltxdoc}
\begin{document}
  \DocInput{\jobname.dtx}
\end{document}
%</driver>
%\fi
%
%\CheckSum{433}
%
%\CharacterTable
%  {Upper-case    \A\B\C\D\E\F\G\H\I\J\K\L\M\N\O\P\Q\R\S\T\U\V\W\X\Y\Z
%   Lower-case    \a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\x\y\z
%   Digits        \0\1\2\3\4\5\6\7\8\9
%   Exclamation   \!     Double quote  \"     Hash (number) \#
%   Dollar        \$     Percent       \%     Ampersand     \&
%   Acute accent  \'     Left paren    \(     Right paren   \)
%   Asterisk      \*     Plus          \+     Comma         \,
%   Minus         \-     Point         \.     Solidus       \/
%   Colon         \:     Semicolon     \;     Less than     \<
%   Equals        \=     Greater than  \>     Question mark \?
%   Commercial at \@     Left bracket  \[     Backslash     \\
%   Right bracket \]     Circumflex    \^     Underscore    \_
%   Grave accent  \`     Left brace    \{     Vertical bar  \|
%   Right brace   \}     Tilde         \~}
%
%\GetFileInfo{\jobname.sty}
%
%\changes{v1.0}{2007/08/30}{Initial public release}
%\changes{v1.1}{2007/09/29}{License changed from GPL to LPPL}
%\changes{v1.1}{2007/09/29}{\cs{Percent} macro removed}
%\changes{v1.1}{2007/09/29}{Documentation improvements}
%\changes{v1.1}{2007/09/29}{Several code sections re-factored}
%\changes{v1.1}{2007/09/29}{Improvements to documentation and
%  \texttt{dtx} file}
%
%\DoNotIndex{\@fileswfalse,\@ifnextchar,\@ifpackageloaded}
%\DoNotIndex{\@ifundefined,\@nameuse,\AtBeginDocument,\AtEndDocument}
%\DoNotIndex{\begingroup,\bib@gadd,\bibliography,\blx@bibfiles,\cite}
%\DoNotIndex{\closeout,\csname,\DeclareOption,\def,\edef,\else}
%\DoNotIndex{\endcsname,\expandafter,\fi,\footnote,\footnotemark}
%\DoNotIndex{\footnotetext,\gdef,\global,\if@filesw,\ifnum,\ifx}
%\DoNotIndex{\immediate,\jobname,\let,\long,\MessageBreak}
%\DoNotIndex{\NeedsTeXFormat,\newcommand,\newcounter,\newif}
%\DoNotIndex{\newrobustcmd,\newwrite,\nocite,\openout,\PackageError}
%\DoNotIndex{\PackageInfo,\PackageWarning,\patchcmd}
%\DoNotIndex{\printbibliography,\ProcessOptions,\protect}
%\DoNotIndex{\ProvidesPackage,\relax,\renewcommand,\RequirePackage}
%\DoNotIndex{\space,\stepcounter,\string,\thanks,\the,\theendnotes}
%\DoNotIndex{\unexpanded,\value,\write,\xdef,\z@}
%
%
%\DoNotIndex{\NeedsTeXFormat}
%
%\title{\texttt{notes2bib} --- Integrating notes into the
%  bibliography%
%  \thanks{This file describes version \fileversion, last revised
%          \filedate.}}
%\author{Joseph Wright%
%  \thanks{E-mail: joseph.wright@morningstar2.co.uk}}
%\date{Released \filedate}
%
%\maketitle
%
%\begin{abstract}
% The |notes2bib| package defines a new type of note, |bibnote|,
% which will always be added to the bibliography.  The package allows
% footnotes and endnotes to be moved into the bibliography in the
% same way.  The package can be used with |natbib| and |biblatex| as
% well as plain LaTeX citations. Both sorted and unsorted
% bibliography styles are supported.
%\end{abstract}
%
%\begin{multicols}{2}
%\tableofcontents
%\end{multicols}
%
%\section{Background}
% In most subject areas, bibliographic citations and notes are
% separate entities. However, in some parts of the physical sciences
% (chemistry and physics) it is usual for references to the
% literature and notes to be given together in a ``References and
% Notes'' section.  By default, this requires that BibTeX users
% create a notes database for each document that they write.
%
% The |endnotes| package allows the user to create endnotes rather
% than footnotes.  However, this does not place the notes in the
% bibliography.  The \textsc{aps} have developed the REVTeX document
% class, which allows footnotes and endnotes to be added to the
% bibliography.  Notes can only be placed at the end of the
% bibliography using this system.  Furthermore, the code to achieve
% this effect is not available as a package separate from REVTeX.
%
% The aim of the |notes2bib| package is to make integration of notes
% into the bibliography easy.   Notes can be written as normal in the
% LaTeX source, and are automatically moved to the bibliography. The
% package is compatible with sorted and unsorted bibliography styles.
% The package has been designed for use with numerical citations,
% although it will work with other systems.
%
%\section{Basic use}
%\DescribeMacro{\bibnote}
% In the most basic form, the package can be used simply by loading
% it in the preamble as normal.  This adds a new type of note to the
% existing \cmd{\footnote} type: \cmd{\bibnote}. This can be used in
% exactly the same way as a footnote, taking one mandatory argument
% \marg{text}.  The \meta{text} will be made available as to the
% bibliography as a note (henceforth referred to as a bibnote).
%\begin{LaTeXexample}
% A very simple example of a bibliography note
% \bibnote{Note for the first example}.
%\end{LaTeXexample}
% By default, each bibnote is given an automatically-generated label
% (see Section \ref{custom} for details of modifying the automatic
% system).  However, \cmd{\bibnote} accepts an optional argument
% \oarg{label}, which can be used to over-ride this. This is
% particularly useful when a note will be referenced several times
% (The use of the \cmd{\citenote} command is covered in
% Section~\ref{subsec:cross-ref}).
%\begin{LaTeXexample}
% An example of a named note
% \bibnote[labelled-note]{Note for the second example}.
% The text can then continue and reference the
% note again later \citenote{labelled-note}.
%\end{LaTeXexample}
%
%\DescribeMacro{\bibnotemark}
%\DescribeMacro{\bibnotetext}
% In common with \cmd{\footnote}, the basic \cmd{\bibnote} macro has
% companion macros \cmd{\bibnotemark} and \cmd{\bibnotetext}. The
% text provided for each not is not ``fragile,'' and so it should not
% be necessary to use \cmd{\bibnotemark} directly.  It is needed when
% replacing footnotes by bibnotes.  Notice that there \emph{are}
% places where bibnotes will be problematic, for example in section
% headings which also appear in the Table of Contents. In these
% contexts, use \cmd{\citenote} to reference the note, or use an
% optional argument to the \cmd{\section}, \emph{etc.}
%\begin{LaTeXexample}
% It is hard to write a good example for this \bibnotemark!
% The text continues here \bibnotetext{Note for the
% third example}.
%\end{LaTeXexample}
%
%\subsection{Package options}
% The |notes2bib| package currently accepts a number of options. The
% |footnotes| option turns standard LaTeX footnotes into
% bibnotes.\footnote{The \cs{thanks} macro used in making titles uses
% the footnote mechanism.  This is unaffected by loading
% \texttt{notes2bib} even with the \texttt{footnote} option.}.  Thus,
% with the |footnotes| option enables, footnotes appear in the
% bibliography with no further user input.  The \cmd{\footnotemark}
% and \cmd{\footnotetext} macros are supported, and are aliased to
% \cmd{\bibnotemark} and \cmd{\bibnotetext}, respectively.
%
% The |endnotes| option works in the same way as the |footnotes| one,
% but in this case \cmd{\endnote} text is added to the bibliography.
% The \cmd{\endnote} command is defined by the |endnotes| package,
% but it is not necessary to load the |endnotes| package for this
% function to work in |notes2bib|.
%
% The |head| and |tail| options affect the placement of notes
% relative to ``real'' citations.  By default, all bibliographic
% citations are written in the order they appear in the source. Thus,
% with an unsorted bibliography style, they will appear in the order
% given.  The |tail| option will force all notes to appear after real
% citations, whereas the |head| option causes notes to come
% first.\footnote{The \texttt{head} option is provided primarily for
% consistency with the \texttt{tail} option.  The system used to give
% ``head'' notes is something of a hack, and is \emph{not} a core
% part of the package.} This has been designed to work with both
% sorted and unsorted bibliography styles.
%
%\subsection{Output of notes}
% Bibnotes are only printed when a bibliography is created.  This
% means that at the very least a \cmd{\bibliographystyle} command
% must appear in the source.  Under most circumstances, the user will
% be citing literature, and so will also include a
% \cmd{\bibliography} command in their source. Bibliography notes are
% automatically added to the citations to be printed.
%
%\DescribeMacro{\printbibnotes}
% If bibnotes are being used without any other citations, then the
% user cannot place \cmd{\bibliography} in the source.\footnote{LaTeX
% will complain if the user puts \cs{bibliography\{\}}.}  The package
% therefore provides the macro \cmd{\printbibnotes}, which will
% output only the notes.  If the |endnotes| package has been loaded,
% the \cmd{\theendnotes} macro is redefined to achieve the same
% effect.
%
%\subsection{Cross-referencing notes\label{subsec:cross-ref}}
%\DescribeMacro{\citenote}
% As explained above, each note is automatically assigned a label, or
% the user can provide one as an optional argument to the note.  In
% either case, notes may then be cross-referenced.  Notes are
% available to be cited directly using the \cmd{\cite} command.
% However, this can cause problems when using the |tail| option.  The
% \cmd{\citenote} command is therefore provided.  This is aware of
% the options, and will act correctly in all circumstances.
%\begin{LaTeXexample}
% Cross-references to the note labelled earlier
% using \cite{labelled-note} and using
% \citenote{labelled-note}.
%\end{LaTeXexample}
%
%\subsection{Interaction with other packages}
% |notes2bib| is designed to work well with as many other packages as
% possible. It tries to avoid changing anything which other packages
% may rely on.  That said, it is best to load |notes2bib|
% \emph{after} other packages that affect citations, footnotes or
% endnotes.  As usual, the |notes2bib| package should be loaded
% before |hyperref|.\footnote{It is usually the case that
% \texttt{hyperref} should be the very last package loaded in the
% preamble.}
%
% The |notes2bib| package is compatible with the current release of
% |biblatex| (v0.6).  As |biblatex| works very differently from other
% citation systems, it must be loaded \emph{before} |notes2bib|.
% This allows the package to adjust correctly for some important
% differences in operation of the bibliography environment.
%
%\section{Customisation\label{custom}}
% The |notes2bib| package provides a number of possibilities for
% customisation. Some of these will be useful only in somewhat
% unusual circumstances.  These more low-level macros all begin
% \cs{niib\dots}.
%
%\DescribeMacro{\bibnotename}
%\DescribeMacro{\thebibnote}
% Each note created by |notes2bib| is automatically given a label,
% unless one has been specified by user as an optional argument. By
% default, this is the text of \cmd{\bibnotename} (normally
% \bibnotename), followed by the note number (counted automatically).
% By redefining \cmd{\bibnotename} all notes can be given a new
% label, still bearing the note number.  More complex effects can
% be achieved by altering \cmd{\thebibnote}.  This is defined as
% |\bibnotename\the\value{bibnote}| by default.
%
%\DescribeMacro{\niibcite}
% The macro used to cite notes is set in \cmd{\niibcite}.  By default
% this is \cmd{\cite}, but can be altered, for example
% |\renewcommand{\niibcite}{\citep}| if using |natbib|.
%
%\DescribeMacro{\niibprefix}
% The temporary BibTeX database used to store the notes has the
% default name |niib-\jobname.bib|.  The prefix (``\niibprefix'') can
% be altered by redefining \cmd{\niibprefix}.
%
%\DescribeMacro{\niibrecord}
%\DescribeMacro{\niibfield}
% When the notes database is written, each record is saved as type
% \texttt{\niibrecord}, and the text is stored in a
% \texttt{\niibfield} field.  Both of these can be altered by
% redefining \cmd{\niibrecord} and \cmd{\niibfield}.  This could be
% useful with a bibliography style that has an explicit ``Notes''
% record type, for example.\footnote{The \texttt{rsc} and
% \texttt{achemso} packages contain styles of this type.}
%
% |notes2bib| attempts to maintain the correct ordering of notes with
% sorted bibliography styles.  This is done by setting up suitable
% information in the temporary database to ensure correct sorting.
% The mechanism for this is available for modification.
%
%\DescribeMacro{\niibkeyhead}
%\DescribeMacro{\niibkeynone}
%\DescribeMacro{\niibkeytail}
% For users of standard bibliography styles, this is achieved by
% generating a |key| field in the database, containing the label used
% for the note.  When using the |head| or |tail| option, this is
% prefixed by \texttt{\niibkeyhead} or \texttt{\niibkeytail},
% respectively. The prefix can be altered by redefining
% \cmd{\niibkeyhead} or \cmd{\niibkeytail}, for example when
% numerical labels need to be taken into account.  The package also
% provides a \cmd{\niibkeynone} macro, which defaults to an empty
% prefix.
%
%\DescribeMacro{\niibpresorthead}
%\DescribeMacro{\niibpresortnone}
%\DescribeMacro{\niibpresorttail}
% When using |biblatex|, the |presort| field can be used to control
% sorting of the citations.  Again, three macros
% \cmd{\niibpresorthead}, \cmd{\niibpresortnone} and
% \cmd{\niibpresorttail} are provided, which are used in the correct
% context.  The default values of \texttt{\niibpresorthead},
% \texttt{\niibpresortnone} and \texttt{\niibpresorttail},
% respectively, are designed to achieve the desired effect while
% allowing the user full control of sorting.
%
%\section{Special effects}
%
%\DescribeMacro{\flushcitestack}
% When using the |head| or |tail| options, citations are added to a
% stack as they are made.  This stack is then flushed to the |.aux|
% file at the end of the document.  If references are given by
% chapter (or other unit), this may not give the desired effect.  The
% \cmd{\flushcitestack} macro will cause all saved citations to be
% written at that point, and will reset the stack for continued use.
% This can therefore be used to control when citation occurs.
%
%\DescribeMacro{\delaycite}
% When using the |head| option, normal citations have to be saved to
% the stack described above.  This requires the modification of the
% citation commands.  By default, |notes2bib| modifies the
% \cmd{\cite} command and most of the standard citation commands of
% |natbib| and |biblatex|.\footnote{Notice that \bslash
% \texttt{nocite} is not modified}  However, if problems are
% encountered with citation order, the user can use the
% \cmd{\delaycite} macro to patch any arbitrary citation command.
% This macro takes a single argument \marg{macro-name}, which is the
% name of the citation command to modify \emph{minus} the leading
% backslash.  For example, the \cmd{\cite} command is patched using
% |\delaycite{cite}|.  The \cmd{\delaycite} macro checks that a
% citation command is not already modified, and so may be used again
% on the same command with no ill effects.
%
% If a sorted bibliography style is in use, and more than nine notes
% are created, the sort order will be incorrect.  This is because by
% default |notes2bib| does not pad the automatically-created labels
% with zeros.  To get the correct sort order, \cmd{\thebibnote}
% should be redefined:
%\begin{LaTeXexample}[\typesetcodeonly]
% \renewcommand*{\thebibnote}{%
%   \bibnotename%
%   \ifnum\value{bibnote} < 9 0\fi%
%   \the\value{bibnote}%
% }
%\end{LaTeXexample}
%
%\section{Known issues}
%
% From v1.1, the method for writing notes to the BibTeX database has
% been modified.  This means that bibnotes cannot contain verbatim
% text.\footnote{Actually, they can, but the spacing will go wrong.
% LaTeX will only complain if a note ends with verbatim text.
% However, verbatim text is not supported in bibnotes: don't do it!}
% This is the same as for normal footnotes, and so the usual
% work-arounds are applicable.
%\begin{LaTeXexample}
% The next note contains some awkward text
% \bibnote{Some \texttt{\textbackslash verb}-like output}.
%\end{LaTeXexample}
%
% Currently, when using the |head| option citations can take only one
% optional argument.  This is fine for normal citation styles, but
% means that |biblatex| users may have some issues.  The package
% author will look again at this if it is a serious problem.  A work
% around is to cite as follows (here assuming you wish to use the
% \cmd{\cite} command):
%\begin{LaTeXexample}[\typesetcodeonly]
% \makeatletter
%   \begingroup
%     \@fileswfalse
%     \niib@orig@cite[argument-one][argument-two]{citation}
%   \endgroup
%   \edef\niib@stack{\niib@stack,citation}
% \makeatother
%\end{LaTeXexample}
% Where ``argument-one,'' ``argument-two'' and ``citation'' should be
% altered to the desired information.
%
% The |cite| and |biblatex| packages move superscript citations after
% punctuation. When these packages are used with standard (not |head|
% or |tail|) mode of |notes2bib|, the same will occur for bibnote
% numbers.  Unfortunately, the |head| and |tail| options prevent this
% ``auto-magic'' operation on \emph{bibnote} numbers.
%
%\bibliographystyle{unsrt}
%\renewcommand*{\refname}{Notes}
%\StopEventually{\printbibnotes}
%
%\section{The mechanism}
% The mechanism for positioning notes in the bibliography is somewhat
% involved.  Rather than expect interested users to read all of the
% code that follows, a condensed overview is given here.  The
% thinking behind the system used is explained first, by considering
% the |endnotes| package and REVTeX class.  Both of these provided
% inspiration for this package.
%
%\subsection{The \texttt{endnotes} approach}
% The |endnotes| package\footnote{%
% \url{http://tug.ctan.org/macros/latex/contrib/misc/endnotes.sty}}
% allows the user to generate endnotes in the same way as footnotes.
% In |endnotes|, the text of the note is written to a |.ent| file.
% This is achieved in an unexpanded form using the \cmd{\meaning} TeX
% primitive.  To produce the list of endnotes, this file is read back
% into LaTeX, with the extra information \cmd{\meaning} also writes
% being stripped off in the process.
%
% This method is relativity simple in concept, but obviously does
% not integrate with BibTeX.  The use of \cmd{\meaning} for unexpanded
% output also means that information requires further processing before
% it can be included in the bibliography.
%
%\subsection{The REVTeX approach}
% REVTeX takes a similar approach to creating endnotes, but also
% allows footnotes to be converted into endnotes.  This results in a
% file containing all of the non-literature citations in a document
% in a single external file (in this case a |.end| file).  REVTeX
% also uses a different method to achieve unexpanded output, meaning
% that several macros are not ``active'' in notes.
%
% The second part of the REVTeX approach is to (optionally) read the
% notes back into the document.  This is achieved  by modifying the
% \cmd{\bibliography} environment to output each note in the
% bibliography. This takes place \emph{en masse}, after the normal
% citations.
%
% REVTeX makes a number of modifications to LaTeX, and is dependent
% on using |natbib|.  The method used is also not compatible with
% interspersing normal citations and notes.
%
%\subsection{The \texttt{notes2bib} approach}
%
% In |notes2bib|, notes are again written to an external file.
% However, in contrast to the methods those outlined above,
% |notes2bib| writes its output in the well-known BibTeX database
% format.  All of the note text is written almost completely
% unexpanded to the file, the only requirement being that the braces
% match within the argument.\footnote{Writing to the file uses the
% e-TeX \cs{unexpanded} primitive.}
%
%  Each note results in a citation being placed by |notes2bib| in the
% |.aux| file.  The  \cmd{\bibliography} command is also modified so
% that the new database will be used by BibTeX. After the BibTeX run,
% the note text will appear in the |.bbl| file, in the same way as
% any other citation.  Using an unsorted BibTeX style, this results
% in notes interspaced with the normal citations.  For sorted styles,
% |notes2bib| allows various methods for controlling the placement of
% notes, based on writing appropriate fields in the BibTeX database.
%
% The |head| and |tail| options use an additional technique.  Both
% delay writing of selected citations (either notes or real ones)
% into the |.aux| file, to control citation position in unsorted
% bibliographies.
%
%\iffalse
%<*package>
%\fi
%\section{The package code}
%
%\subsection{Package setup code}
%
% The package starts with the usual identification code.
%\changes{v1.1}{2007/09/29}{Removed use of \texttt{xspace}}
%    \begin{macrocode}
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{notes2bib}
  [2007/09/29 v1.1 Integrating notes into the bibliography]
%    \end{macrocode}
% The package requires e-TeX, so before going any further, this is
% tested.  This code is taken more-or-less verbatim from |biblatex|.
%\changes{v1.1}{2007/09/29}{Require e-TeX extensions}
%    \begin{macrocode}
\@ifundefined{eTeXversion}
  {\PackageError{notes2bib}
     {Not running under e-TeX}
     {This package requires e-TeX. Try compiling the document
      with\MessageBreak `elatex' instead of `latex'. When using
      pdfTeX, try `pdfelatex'\MessageBreak instead of `pdflatex'}%
   \endinput}
  {}
%    \end{macrocode}
% With that check out of the way, Philip Lehmann's |elatex| package
% is loaded to extend various LaTeX commands.  Early versions of
% |elatex| ues slightly different macro names, so a version check
% is needed.
%    \begin{macrocode}
\RequirePackage{elatex}[2007/07/13]
%    \end{macrocode}
%
% Option processing takes place.  Redefining \cmd{\footnote} or
% \cmd{\endnote} is delayed until the start of the document, to avoid
% the danger of other packages being loaded and overwriting this.
%    \begin{macrocode}
\newif\ifniib@fn\niib@fnfalse
\DeclareOption{footnotes}{%
  \niib@fntrue
  \AtBeginDocument{%
    \let\footnote\bibnote%
  \PackageInfo{notes2bib}%
    {Converting footnotes to bibnotes}%
}}
\DeclareOption{endnotes}{%
  \AtBeginDocument{%
    \let\endnote\bibnote%
    \let\endnotemark\bibnotemark%
    \let\endnotetext\bibnotetext%
%    \end{macrocode}
% If the user has used the |endnotes| package, they may still have
% \cmd{\theendnotes} commands in their source.  So this is defined to
% print out all of the bibnotes.
%    \begin{macrocode}
    \@ifpackageloaded{endnotes}%
      {\let\theendnotes\printbibnotes}{}%
    \PackageInfo{notes2bib}%
      {Converting endnotes to bibnotes}%
}}
%    \end{macrocode}
% Stephen Dalton suggested an option for all notes to come after
% ``real'' citations.  This is done here, along with a mirror options
% to have all for the citations come first.
%    \begin{macrocode}
\newif\ifniib@tail\niib@tailfalse
\newif\ifniib@head\niib@headfalse
\DeclareOption{tail}{\niib@tailtrue}
\DeclareOption{head}{\niib@headtrue}
%    \end{macrocode}
% Finally, the options are put into effect.
%    \begin{macrocode}
\ProcessOptions
%    \end{macrocode}
%
%\begin{macro}{\niib@fnmark}
%\begin{macro}{\niib@fntext}
%\begin{macro}{\niib@thanks}
% If the |footnote| option is active, there is some work to do
% because of the \cmd{\thanks} macro.  This is all done using the
% |elatex| package. Firstly, it is necessary to back up the original
% definitions for \cmd{\footnotetext}, \cmd{\footnotetext} and
% \cmd{\thanks}.
%    \begin{macrocode}
\ifniib@fn
  \let\niib@fnmark\footnotemark
  \let\niib@fntext\footnotetext
  \let\niib@thanks\thanks
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\end{macro}
%\begin{macro}{\thanks}
% Now the \cmd{\thanks} command is patched to use the saved
% definitions.  The patching is nested so that everything has to go
% right before things are finalised.
%    \begin{macrocode}
  \patchcmd{\thanks}{\footnotemark}{\niib@fnmark}{%
    \patchcmd{\thanks}{\footnotetext}{\niib@fntext}{%
      \AtBeginDocument{%
        \let\footnotemark\bibnotemark
        \let\footnotetext\bibnotetext
      }%
  \PackageInfo{notes2bib}%
    {Modifying \protect\thanks\space macro}%
    }{%
%    \end{macrocode}
% If the following is executed, then things have gone wrong in some
% way. The \cmd{\patchcmd} macro shouldn't mess up the definition of
% \cmd{\thanks}, but to be on the safe side the original version
% is restored here.
%    \begin{macrocode}
    \let\thanks\niib@thanks%
    \PackageWarning{notes2bib}%
      {Could not patch \protect\thanks}}%
  }{%
    \let\thanks\niib@thanks%
    \PackageWarning{notes2bib}%
      {Could not patch \protect\thanks}}%
\fi
%    \end{macrocode}
%\end{macro}
%
% The |head| and |tail| options are mutually exclusive, so a check is
% made that both have not been selected.  If they have, the package
% ignores both options after a suitable warning.
%    \begin{macrocode}
\ifniib@head
  \ifniib@tail
    \PackageWarning{notes2bib}
      {You've given both ``head'' and ``tail'' as
        options\MessageBreak  I'm ignoring both!}
    \niib@headfalse\niib@tailfalse
  \else
    \PackageInfo{notes2bib}%
      {bibnotes will ``head'' other citations}
  \fi
\else
  \PackageInfo{notes2bib}%
    {bibnotes will ``tail'' other citations}
\fi
%    \end{macrocode}
% For the |head| option, the normal citation commands are modified to
% get the necessary delay in writing to the |.aux| file.
%    \begin{macrocode}
\AtBeginDocument{%
  \ifniib@head
%    \end{macrocode}
% The real \cmd{\delaycite} is activated. The \cmd{\cite} command is
% always defined, so it can be redefined in all cases.
%    \begin{macrocode}
    \let\delaycite\niib@delaycite
    \delaycite{cite}%
%    \end{macrocode}
% If |natbib| is loaded, there a several citation commands that will
% definitely be defined.  They are all run through \cmd{\delaycite}.
%    \begin{macrocode}
    \@ifpackageloaded{natbib}{%
      \delaycite{citet}%
      \delaycite{citep}%
      \delaycite{citenum}%
      \delaycite{citealt}%
      \delaycite{citealp}%
      \delaycite{citetext}%
      \delaycite{citeauthor}%
      \delaycite{citeyear}%
      \delaycite{citeyearpar}%
      \delaycite{Citet}%
      \delaycite{Citep}%
      \delaycite{Citealt}%
      \delaycite{Citealp}%
      \delaycite{Citeauthor}%
    }{}%
%    \end{macrocode}
% For |biblatex|, some citation commands are always defined.
%    \begin{macrocode}
    \@ifpackageloaded{biblatex}{%
      \delaycite{Cite}%
      \delaycite{parencite}%
      \delaycite{Parencite}%
      \delaycite{footcite}%
      \delaycite{Footcite}%
      \delaycite{textcite}%
      \delaycite{Textcite}%
%    \end{macrocode}
% Now there are some citation commands that may be defined or not.
%    \begin{macrocode}
      \@ifundefined{autocite}{}%
        {\delaycite{autocite}}%
      \@ifundefined{supercite}{}%
        {\delaycite{supercite}}%
      }{}%
  \fi%
}
%    \end{macrocode}
%
%\subsection{User configuration macros}
%
% The |notes2bib| package makes quite a number of configuration
% defaults available as macros.  These are all set up here.  Most of
% these are of the form \cs{niib\dots}, as in the
% main they are unlikely to be altered by most users.
%
%\begin{macro}{\bibnotename}
% By default, all of the new citations take the prefix
% ``\bibnotename.'' The default can be altered, and this is set up
% here.
%    \begin{macrocode}
\newcommand*\bibnotename{Bibnote}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\thebibnote}
% A counter is needed for the notes created.  In analogy to other
% counters in LaTeX, this is given a \cs{the\dots} name.  The user
% should not really need to use this macro, but convention dictate
% that it has a user-space name.
%    \begin{macrocode}
\newcounter{bibnote}
\renewcommand*{\thebibnote}{\bibnotename\the\value{bibnote}}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\niibprefix}
% The package works by creating a new BibTeX database file containing
% the notes.  By default, this fix is called
% \texttt{\niibprefix}\cs{jobname.bib}, but the prefix may
% be altered by redefining \cmd{\niibprefix}.  The default follows
% the pattern used by the |biblatex| package (which uses |blx-|).
%    \begin{macrocode}
\newcommand*\niibprefix{niib-}
%    \end{macrocode}
%\end{macro}
%
%\begin{macro}{\niibrecord}
%\begin{macro}{\niibfield}
% When creating the temporary database of notes, the BibTeX records
% created are of record type \cmd{\niibrecord}, and the notes are
% stored in the \cmd{\niibfield} field type.  For some BibTeX styles,
% a better choice than the defaults (\texttt{\niibrecord} and
% \texttt{\niibfield}, respectively) may be available.  Thus the
% values used are definable.
%    \begin{macrocode}
\newcommand*\niibrecord{Misc}
\newcommand*\niibfield{note}
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\begin{macro}{\niibpresorthead}
%\begin{macro}{\niibpresortnone}
%\begin{macro}{\niibpresorttail}
% When using |biblatex|, sorting can be controlled using the
% |presort| field. Default values to be used are given here; these
% are ``soft'' as |biblatex| allows much more definite pushing to the
% top and bottom of the sorted list.
%    \begin{macrocode}
\newcommand*\niibpresorthead{ml}
\newcommand*\niibpresortnone{mm}
\newcommand*\niibpresorttail{mn}
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\end{macro}
%\begin{macro}{\niibkeyhead}
%\begin{macro}{\niibkeynone}
%\begin{macro}{\niibkeytail}
% For traditional BibTeX styles, the |key| field can be used to
% influence the sort order.  Default values to alter sorting are
% given here, but may need to be altered for other languages and so
% on.
%    \begin{macrocode}
\newcommand*\niibkeyhead{aaa}
\newcommand*\niibkeynone{}
\newcommand*\niibkeytail{zzz}
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\end{macro}
%
%\begin{macro}{\niibcite}
% Bibliography notes are marked by citations, like any other
% bibliography entry. The citation command use is controlled here.
%    \begin{macrocode}
\newcommand*\niibcite{\cite}
%    \end{macrocode}
%\end{macro}
%
%\subsection{User macros}
%
%\begin{macro}{\bibnote}
%\changes{v1.1}{2007/09/29}{Macro made robust}
% Each new bibnote increments the note counter, then checks for an
% optional label, before handing off to the internal macro
% \cmd{\niib@bibnote}.
%    \begin{macrocode}
\newrobustcmd*{\bibnote}{%
  \stepcounter{bibnote}%
  \@ifnextchar[%
    {\niib@bibnote}%
    {\niib@bibnote[\thebibnote]}%
}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\bibnotemark}
%\changes{v1.1}{2007/09/29}{Macro made robust}
% The \cmd{\bibnotemark} macro works in the same way as
% \cmd{\bibnote}, but calls \cmd{\niib@mark} rather than
% \cmd{\niib@bibnote}.
%    \begin{macrocode}
\newrobustcmd*{\bibnotemark}{%
  \stepcounter{bibnote}%
  \@ifnextchar[%
    {\niib@mark}%
    {\niib@mark[\thebibnote]}%
}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\bibnotetext}
%\changes{v1.1}{2007/09/29}{Macro made robust}
%\changes{v1.1}{2007/09/29}{Use \cs{newrobustcmd} rather than
%  \cs{@ifnextchar} for detecting optional argument}
% The text companion to the mark macro above, with no increment of
% the counter.
%    \begin{macrocode}
\newrobustcmd*{\bibnotetext}[1][\thebibnote]{%
  \niib@text{#1}%
}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\printbibnotes}
%\changes{v1.1}{2007/09/29}{Macro made robust}
% To allow for the possibility of there being no other notes, a
% command to print only notes is given.  In the |biblatex| case, the
% best that can be done is to issue \cmd{\printbibliography}.
%    \begin{macrocode}
\@ifpackageloaded{biblatex}{%
  \let\printbibnotes\printbibliography%
}{%
  \newrobustcmd*{\printbibnotes}{\niib@bib%
    {\niibprefix\jobname}}%
}%
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\flushcitestack}
%\changes{v1.1}{2007/09/29}{Macro made robust}
% In order to delay citations to the end of the bibliography (and
% thus force others to the start), a ``stack'' is created of
% citations which need to be written to the |.aux| file.  This
% is done here, and the stack is cleared so collection can begin
% again.
%    \begin{macrocode}
\newrobustcmd*{\flushcitestack}{%
  \ifx\niib@stack\relax\else%
    \expandafter\nocite\expandafter{\niib@stack}%
    \global\let\niib@stack\relax%
  \fi%
}
%    \end{macrocode}
%\end{macro}
%
%\begin{macro}{\delaycite}
%\changes{v1.1}{2007/09/29}{Initial definition prevents use in
%  preamble}
%    \begin{macrocode}
\newrobustcmd*{\delaycite}[1]{%
  \PackageWarning{notes2bib}{%
    \@nameuse{delaycite}can only be used in the document
    body\MessageBreak Not modifying citation macro \@nameuse{#1}}
}
%    \end{macrocode}
%\end{macro}
%
%\begin{macro}{\citenote}
%\changes{v1.0a}{2007/09/03}{New macro}
%\changes{v1.1}{2007/09/29}{Macro made robust}
% A ``mode aware'' command for referencing notes is needed (problems
% arise with \cmd{\cite} and the |tail| option.  Rather than overload
% \cmd{\cite} with all of the problems that can bring, a new command
% is provided that can be guaranteed to work.
%    \begin{macrocode}
\ifniib@tail
  \newrobustcmd*\citenote[2][\relax]{%
    \begingroup%
      \@fileswfalse%
%    \end{macrocode}
% \cmd{\relax} is used as a marker for an empty first argument.
%    \begin{macrocode}
      \ifx#1\relax%
        \niibcite{#2}%
      \else
        \niibcite[#1]{#2}%
      \fi
    \endgroup%
  }%
%    \end{macrocode}
% If |tail| is not active, then \cmd{\citenote} is simply an alias
% for the citation command used by |notes2bib|.
%    \begin{macrocode}
\else
  \newrobustcmd*\citenote{\niibcite}%
\fi
%    \end{macrocode}
%\end{macro}
%
%\subsection{Internal setup macros}
%
%\begin{macro}{\niib@keyname}
% If |biblatex| is in use, the key field in the BibTeX database
% should be called ``keysort,'' whereas otherwise it should be
% ``key.''
%    \begin{macrocode}
\@ifpackageloaded{biblatex}
  {\def\niib@keyname{keysort}}
  {\def\niib@keyname{key}}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\niib@presort}
%\begin{macro}{\niib@key}
% The values taken by \cmd{\niib@presort} and \cmd{\niib@key} depend
% on the desired positioning of notes in the bibliography.
%    \begin{macrocode}
\ifniib@head
  \def\niib@presort{\niibpresorthead}
  \def\niib@key{\niibkeyhead}
\else
  \ifniib@tail
    \def\niib@presort{\niibpresorttail}
    \def\niib@key{\niibkeytail}
  \else
    \def\niib@presort{\niibpresortnone}
    \def\niib@key{\niibkeynone}
  \fi
\fi
%    \end{macrocode}
%\end{macro}
%\end{macro}
%
%\begin{macro}{\niib@msg}
% To inform the user, the automatically-created BibTeX database needs
% to carry suitable information on its source.
%    \begin{macrocode}
\edef\niib@msg{%
  This is an auxiliary file used by the `notes2bib' package.^^J%
  This file may safely be deleted. It will be recreated as
  required.^^J}
%    \end{macrocode}
%\end{macro}
%
%\begin{macro}{\niib@stack}
% This macro is needed to store any citations at the end of the
% bibliography.  Initially, this expands to \cmd{\relax}.
%    \begin{macrocode}
\let\niib@stack\relax
%    \end{macrocode}
%\end{macro}
%
% A switch is needed to tell if a note is being cited when using
% ``head'' mode.
%    \begin{macrocode}
\newif\ifniib@cn\niib@cnfalse
%    \end{macrocode}
%
%\subsection{Internal macros}
%
%\begin{macro}{\niib@delaycite}
%\changes{v1.0a}{2007/09/03}{Fixed a flaw with checking for
%  existing redefinition}
%\changes{v1.1}{2007/09/29}{Improved logging of function}
%\changes{v1.1}{2007/09/29}{Added a sanity check on argument}
%\changes{v1.1}{2007/09/29}{Made internal to prevent execution
%  in preamble}
%\changes{v1.1}{2007/09/29}{Macro made robust}
% Normal citations have to be stacked up in the stack when in
% ``head'' mode. To do this, the citation command has to be modified
% to do this, while leaving note citations alone.  The trick used in
% this is to set \cmd{\@filesw} to false while the citation takes
% place.
%    \begin{macrocode}
\newrobustcmd*\niib@delaycite[1]{%
  \@ifundefined{#1}{%
  \PackageWarning{notes2bib}
    {Citation macro \@nameuse{#1}undefined\MessageBreak
    \protect\delaycite\space cannot operate on this macro}
  }{%
    \@ifundefined{niib@orig@#1}{%
      \expandafter\expandafter\expandafter\let\expandafter%
        \csname niib@orig@#1\expandafter\endcsname\csname #1\endcsname%
      \expandafter\renewcommand\csname #1\endcsname[2][\relax]{%
%    \end{macrocode}
% If a note is being cited, then there will be no optional argument,
% and |##1| will expand to \cmd{\relax}.
%    \begin{macrocode}
        \ifniib@cn%
          \csname niib@orig@#1\endcsname{##2}%
        \else%
          \begingroup%
            \@fileswfalse%
%    \end{macrocode}
% If an optional argument has been given, then |##1| will expand to
% something other than \cmd{\relax}.  So the original citation
% command is called with the optional argument.
%    \begin{macrocode}
            \ifx##1\relax%
              \csname niib@orig@#1\endcsname{##2}%
            \else%
              \csname niib@orig@#1\endcsname[##1]{##2}%
            \fi%
          \endgroup%
          \edef\niib@temp{##2}%
          \ifx\niib@stack\relax%
            \xdef\niib@stack{\niib@temp}%
          \else%
            \xdef\niib@stack{\niib@stack,\niib@temp}%
          \fi%
        \fi%
      }%
      \PackageInfo{notes2bib}%
        {Modifying citation type \@nameuse{#1}}%
    }{%
      \PackageInfo{notes2bib}%
        {Already delayed \@nameuse{#1}}%
    }%
  }
}
%    \end{macrocode}
%\end{macro}
%
%\begin{macro}{\niib@bibnote}
% Two steps are needed here, writing the text of the note to file
% (handled by \cmd{\niib@text}, and marking the citation (using
% \cmd{\niib@cite}).
%    \begin{macrocode}
\long\def\niib@bibnote[#1]#2{%
  \niib@text{#1}{#2}%
  \niib@cite{#1}%
}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\niib@mark}
% If only a mark is asked for, this is simply converted into a
% citation. This cannot be done directly as the optional has to be
% processed correctly.
%    \begin{macrocode}
\def\niib@mark[#1]{\niib@cite{#1}}
%    \end{macrocode}
%\end{macro}
%
%\begin{macro}{\niib@cite}
%\changes{v1.1}{2007/09/29}{Name change from \cs{niib@citenote}}
%\changes{v1.1}{2007/09/29}{Definition made option-specific}
% The internal macro used to cite notes depends on the package
% options in force.  First, for |head| mode, the modified real
% citation commands need to know that a note is being cited.  So the
% Boolean \cmd{\niib@cn} has to be set correctly before citation.
%    \begin{macrocode}
\ifniib@head%
  \def\niib@cite#1{%
    \niib@cntrue%
    \niibcite{#1}%
    \niib@cnfalse%
  }%
%    \end{macrocode}
% For |tail| mode, the citation has to be added to the stack for use
% later. The citation is then made with writing to the |.aux| file
% disabled.
%    \begin{macrocode}
\else%
  \ifniib@tail%
    \def\niib@cite#1{%
    \ifx\niib@stack\relax%
      \xdef\niib@stack{#1}%
    \else%
      \xdef\niib@stack{\niib@stack,#1}%
    \fi%
    \begingroup
      \@fileswfalse%
      \niibcite{#1}%
    \endgroup%
    }%
%    \end{macrocode}
% Without the |head| or |tail| options, none of these tricks are
% needed, and \cmd{\niib@cite} is simply an alias for
% \cmd{\niibcite}. That in turn may well just be an alias for
% \cmd{\cite}!
%    \begin{macrocode}
  \else%
    \def\niib@cite#1{\niibcite{#1}}%
  \fi%
\fi%
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\niib@text}
%\changes{v1.1}{2007/09/29}{Combined \cs{niib@text}
%  and \cs{niib@@text}}
%\changes{v1.1}{2007/09/29}{Improved awareness of files switch}
% The ``business end'' of writing the notes to file.
%    \begin{macrocode}
\long\def\niib@text#1#2{%
%    \end{macrocode}
%\begin{macro}{\niib@out}
%\begin{macro}{\niib@stream}
% If this is the first note, then a new output stream is needed,
% otherwise it will already be open.
%    \begin{macrocode}
  \@ifundefined{niib@out}{%
    \if@filesw%
      \newwrite\niib@out%
      \gdef\niib@stream{\niibprefix\jobname.bib}%
      \immediate\openout\niib@out\niib@stream\relax%
%    \end{macrocode}
% The new file starts with the message that it has been automatically
% generated by |notes2bib|.
%    \begin{macrocode}
      \immediate\write\niib@out{\niib@msg}%
    \fi}%
    {}%
%    \end{macrocode}
%\end{macro}
%\end{macro}
% The new record is now written to file.  The \cmd{\unexpanded} e-TeX
% primitive is used to avoid expansion of macros in the note text.
% The only issue with this is the addition of spaces after command
% names; this is the reason verbatim text cannot be used in bibnotes.
%    \begin{macrocode}
  \if@filesw%
    \immediate\write\niib@out{%
    @\niibrecord\string{#1,^^J%
    presort = \string{\niib@presort\string},^^J%
    \niib@keyname\space= \string{\niib@key#1\string},^^J%
    \niibfield\space= \string{\unexpanded{#2}\string}^^J%
    \string}^^J}%
  \fi%
}
%    \end{macrocode}
%\end{macro}
%
% The \cmd{\bibliography} macro is patached to ensure that when it is
% executed the note file is also processed.  |biblatex| does things
% very differently, but this actually makes it much easier to patch
% for.
%    \begin{macrocode}
\@ifpackageloaded{biblatex}{%
  \expandafter\bib@gadd\expandafter\blx@bibfiles\expandafter%
    {\niibprefix\jobname}%
  }{%
%    \end{macrocode}
%\begin{macro}{\niib@bib}
%\begin{macro}{\bibliography}
% The bibliography command is patched so that it will run on the
% automatically-generated BibTeX database.
%    \begin{macrocode}
  \let\niib@bib\bibliography%
  \renewcommand{\bibliography}[1]{%
    \ifnum\the\value{bibnote} > \z@%
      \niib@bib{\niibprefix\jobname,#1}%
    \else%
      \niib@bib{#1}%
    \fi}}%
%    \end{macrocode}
%\end{macro}
%\end{macro}
%%
% At the end of the document, any delayed citations are written to the
% |.aux| file, and the database file is closed cleanly.
%    \begin{macrocode}
\AtEndDocument{%
  \flushcitestack%
  \@ifundefined{niib@out}{}%
    {\immediate\closeout\niib@out}%
}
%    \end{macrocode}
%
%\iffalse
%</package>
%\fi
% \PrintChanges
% \PrintIndex
% \Finale
%\iffalse
%<*jawltxdoc>
% The following is convenient method for collecting together package
% loading, formatting commands and new macros used to format |dtx|
% files written by the current author.  It is based on the similar
% files provided by Will Robertson in his packages and Heiko Oberdiek
% as a stand-alone package.  Notice that it is not intended for other
% users: there is no error checking!  However, it is covered by the
% LPPL in the same way as the rest of this package.
%
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{jawltxdoc}
  [2007/09/28 v1.0]
% First of all, a number of support packages are loaded.
\usepackage[T1]{fontenc}
\usepackage[english,UKenglish]{babel}
\usepackage[scaled=0.95]{helvet}
\usepackage[version=3]{mhchem}
\usepackage[final]{microtype}
\usepackage{mathpazo,booktabs,array,url,graphicx,courier,unitsdef}
\usepackage{upgreek,ifpdf,listings}
% If using pdfLaTeX, the source will be attached to the PDF. This
% is basically the system used by Heiko Oberdiek, but with a check
% that PDF mode is enabled.
\ifpdf
  \usepackage{embedfile}
  \embedfile[%
    stringmethod=escape,%
    mimetype=plain/text,%
    desc={LaTeX docstrip source archive for package `\jobname'}%
    ]{\jobname.dtx}
\fi
\usepackage{\jobname}
\usepackage[numbered]{hypdoc}
%
% To typeset examples, a new environment is needed.  The code below
% is based on that in used by |listings|, but is modified to get
% better formatting for this context.  The formatting of the output
% is basically that in Will Robertson's |dtx-style| file.
\newlength\LaTeXwidth
\newlength\LaTeXoutdent
\newlength\LaTeXgap
\setlength\LaTeXgap{1em}
\setlength\LaTeXoutdent{-0.15\textwidth}
\def\typesetexampleandcode{
  \begin{list}{}{%
    \setlength\itemindent{0pt}
    \setlength\leftmargin\LaTeXoutdent
    \setlength\rightmargin{0pt}
  }
  \item
    \setlength\LaTeXoutdent{-0.15\textwidth}
    \begin{minipage}[c]{\textwidth-\LaTeXwidth-\LaTeXoutdent-\LaTeXgap}
      \lst@sampleInput
    \end{minipage}%
    \hfill%%
    \begin{minipage}[c]{\LaTeXwidth}%
      \hbox to\linewidth{\box\lst@samplebox\hss}%
    \end{minipage}%
  \end{list}
}
\def\typesetcodeonly{%
  \begin{list}{}{%
    \setlength\itemindent{0pt}
    \setlength\leftmargin{0pt}
    \setlength\rightmargin{0pt}
  }
  \item
    \begin{minipage}[c]{\LaTeXwidth}%
      \hbox to\linewidth{\box\lst@samplebox\hss}%
    \end{minipage}%
  \end{list}
}
\makeatletter
\lst@RequireAspects{writefile}
\newbox\lst@samplebox
\lstnewenvironment{LaTeXexample}[1][\typesetexampleandcode]{%
  \let\typesetexample#1
  \global\let\lst@intname\@empty
  \setbox\lst@samplebox=\hbox\bgroup
  \setkeys{lst}{language=[LaTeX]{TeX},tabsize=4,gobble=2,%
    breakindent=0pt,basicstyle=\small\ttfamily,basewidth=0.51em,%
    keywordstyle=\color{blue},%
% Notice that new keywords should be added here.
    morekeywords={bibnote,citenote,bibnotetext,bibnotemark,%
      thebibnote,bibnotename}}
  \lst@BeginAlsoWriteFile{\jobname.tmp}
}{%
  \lst@EndWriteFile\egroup
  \setlength\LaTeXwidth{\wd\lst@samplebox}
  \typesetexample%
}
\def\lst@sampleInput{%
  \MakePercentComment\catcode`\^^M=10\relax
  \small%
  {\setkeys{lst}{SelectCharTable=\lst@ReplaceInput{\^\^I}%
    {\lst@ProcessTabulator}}%
    \leavevmode \input{\jobname.tmp}}%
  \MakePercentIgnore%
}
\makeatother
%</jawltxdoc>
%\fi
