% \iffalse meta-comment
%<*internal>
\iffalse
%</internal>
%<*readme>
---------------------------------------------------------------
The notes2bib bundle --- Integrating notes into the
  bibliography
Maintained by Joseph Wright
E-mail: joseph.wright@morningstar2.co.uk
Released under the LaTeX Project Public License v1.3c or later
See http://www.latex-project.org/lppl.txt
---------------------------------------------------------------

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.

The bundle includes both a current release version of the
package (notes2bib.sty) and an experimental re-implementation
using LaTeX3 syntax where possible (xnotes2bib.sty).
%</readme>
%<*internal>
\fi
\begingroup
%</internal>
%<*install>
\input docstrip.tex
\keepsilent
\askforoverwritefalse
\preamble
---------------------------------------------------------------
The notes2bib bundle --- Integrating notes into the
  bibliography
Maintained by Joseph Wright
E-mail: joseph.wright@morningstar2.co.uk
Released under the LaTeX Project Public License v1.3c or later
See http://www.latex-project.org/lppl.txt
---------------------------------------------------------------

\endpreamble
\postamble

Copyright (C) 2007-2008 by
  Joseph Wright <joseph.wright@morningstar2.co.uk>

It may be distributed and/or modified under the conditions of
the LaTeX Project Public License (LPPL), either version 1.3c of
this license or (at your option) any later version.  The latest
version of this license is in the file:

   http://www.latex-project.org/lppl.txt

This work is "maintained" (as per LPPL maintenance status) by
  Joseph Wright.

This work consists of the file  notes2bib.dtx
                                xnotes2bib.dtx
          and the derived files notes2bib.pdf,
                                notes2bib.sty,
                                notes2bib.ins,
                                xnotes2bib.pdf,
                                xnotes2bib.sty and
                                xnotes2bib.ins.

\endpostamble
\usedir{tex/latex/notes2bib}
\generate{
  \file{\jobname.sty}{\from{\jobname.dtx}{package}}
}
%</install>
%<install>\endbatchfile
%<*internal>
\usedir{source/latex/notes2bib}
\generate{
  \file{\jobname.ins}{\from{\jobname.dtx}{install}}
}
\nopreamble\nopostamble
\usedir{doc/latex/notes2bib}
\generate{
  \file{README.txt}{\from{\jobname.dtx}{readme}}
}
\def\destdir{}
\generate{
  \file{jawl3doc.sty}{\from{\jobname.dtx}{jawl3doc}}
}
\endgroup
\immediate
  \write18{makeindex -s gind.ist -o \jobname.ind \jobname.idx}
\immediate
  \write18{makeindex -s gglo.ist -o \jobname.gls \jobname.glo}
%</internal>
%<*package>
\RequirePackage{l3names}
\GetIdInfo$Id: xnotes2bib.dtx 6 2008-10-31 21:00:00Z joseph $
  {Integrating notes into the bibliography (expl3 version)}
%</package>
%<*driver>
\documentclass[full]{l3doc}
\EnableCrossrefs
\CodelineIndex
\RecordChanges
\usepackage{jawl3doc}
\begin{document}
  \DocInput{\jobname.dtx}
\end{document}
%</driver>
% \fi
%
%\CheckSum{466}
%
%\GetFileInfo{\jobname.sty}
%
%\title{\texorpdfstring{\currpkg}{\jobname} --- Integrating notes into
%  the bibliography^^A
%    \thanks{This file describes version \fileversion, last revised
%      \filedate.}}
%\author{Joseph Wright^^A
%  \thanks{E-mail: joseph.wright@morningstar2.co.uk}}
%\date{Released \filedate}
%
%\maketitle
%
%\begin{abstract}
% The \currpkg\ package is an \emph{experimental} re-implementation of
% \pkg{notes2bib} using \LaTeX3 commands internally (taken from the
% \pkg{expl3} bundle).  The user interface is almost identical to
% \pkg{notes2bib}.
%
% The \currpkg package defines a new type of note, \cs{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 \pkg{natbib} and \pkg{biblatex} as
% well as plain \LaTeX\ citations. Both sorted and unsorted
% bibliography styles are supported.
%\end{abstract}
%
%\begin{multicols}{2}
%  \tableofcontents
%\end{multicols}
%
%\section{Introduction}
% The new code syntax introduced by \LaTeX3 is very different from
% plain \TeX\ or \LaTeXe.  This means that converting packages to
% \LaTeX3 requires working from the ground up if the new ideas are to
% be exploited fully.  This package re-implements \pkg{notes2bib} using
% the experimental syntax for internal commands.
%
% The internal logic of the package remains broadly similar to that in
% \pkg{notes2bib}.  However, some opportunities to simplify the code or
% make the flow clearer have been taken. There is therefore no
% one-to-one correspondence between the internals of the two packages.
% In particular, this package does not guarantee backward-compatibility
% with \pkg{notes2bib} under all circumstances.  \LaTeX3 will require
% significant changes to documents, and so alterations to the logic of
% packages in order to make them more useful in the long term seem
% sensible.
%
%\section{Using the package}
%\subsection{Macros}
%\DescribeMacro{\bibnote}
%\DescribeMacro{\bibnotemark}
%\DescribeMacro{\bibnotetext}
%\DescribeMacro{\flushnotestack}
% The user macros of \currpkg\ are intended to work in the same way as
% those in \pkg{notes2bib}.  Please see \file{notes2bib.pdf} for
% details of:
%\begin{itemize}
%  \item \cs{bibnote}
%  \item \cs{bibnotemark}
%  \item \cs{bibnotetext}
%  \item \cs{flushnotestack}
%\end{itemize}
% The \cs{citenote} macro can be replaced by using \cs{bibnotemark} to
% cite the note for a second time.
%
%\subsection{Control values}
%\DescribeMacro{\niibsetup}
% The main user changes between \pkg{notes2bib} and \pkg{xnotes2bib}
% are in the user options.  These have been completely re-written here,
% to improve the logic of the interface and to remove unnecessary
% options. All package control is currently carried out using the
% \cs{niibsetup} macro, as the \LaTeXe\ kernel expands options and
% removes spaces. As in \pkg{notes2bib}, the \cs{niibsetup} macro
% accepts a key--value list as input.
%
% There are four types of control key.  Boolean keys take the values
% \opt{true} and \opt{false}.  If the key name alone is given, this is
% the same as giving the \opt{true} value. String keys save their value
% as a string for internal use: they can therefore take any input.
% Choice keys take one of a range of pre-determined values, in a
% similar way to Boolean options.  However, the list of possible values
% varies from key to key. Finally, macro keys require a macro as the
% value.
%
%\DescribeOption{convert~endnotes}
%\DescribeOption{convert~footnotes}
% To convert endnotes and footnotes into bibnotes, the options
% \opt{convert~endnotes} and \opt{convert~footnotes} are available.
% Both taken Boolean values, and are set to \opt{false} when loading
% \currpkg.  If endnotes are not defined elsewhere, the
% \opt{convert~endnotes} only defines them when set to \opt{true}.
%
%\DescribeOption{placement}
% The package is able to position notes in three ways in the
% bibliography. The standard method is to create the notes interspersed
% with ``real'' citations. The order in the source then determines the
% position in the bibliography. The package can also create notes such
% that they appear either before or after normal citations. The
% behaviour here is controlled by the \opt{placement} option, which
% takes a choice from the list \opt{after}, \opt{before} and
% \opt{mixed}. The \opt{after} option places notes after normal
% citations, \opt{before} places notes first and \opt{mixed} mixes
% notes and citations based on the order in the source.
%
%\newcommand*{\field}[1]{\texttt{#1}}
%\DescribeOption{key~after}
%\DescribeOption{key~before}
%\DescribeOption{key~mixed}
% Most sorted bibliography styles provide methods for controlling the
% sort order of entries.  With standard \BibTeX\ styles, the
% \field{key} field is used for this purpose. The options
% \opt{key~after}, \opt{key~before} and \opt{key~mixed} are used to set
% this up.  They contain an item to be added before the note label when
% creating the \field{key} field.  The standard values are \opt{aaa}
% for \opt{key~before} and \opt{zzz} for \opt{key~after}:
% \opt{key~mixed} is empty.
%\DescribeOption{presort~after}
%\DescribeOption{presort~before}
%\DescribeOption{presort~mixed}
% When using \pkg{biblatex}, \field{presort} field is available. The
% values used by \currpkg\ for this field are stored as
% \opt{presort~after}, \opt{presort~before} and \opt{presort~mixed},
% with default values \opt{mn}, \opt{ml} and \opt{mm}, respectively.
% The \opt{presort} system is described in the \pkg{biblatex} manual.
%
%\DescribeOption{write~key~field}
% When using the package with \pkg{natbib}, it may be necessary to avoid
% writing the \texttt{key} field to the temporary database.  This is
% seen with the style \texttt{unsrtnat}, for example.  The Boolean
% option \opt{write key field} is available to turn off writing the
% \texttt{key} field under these circumstances.
%
%\DescribeOption{cite}
% As \currpkg\ uses \BibTeX\ to create notes, it uses a citation
% command to mark the notes in the body of the text. The command used
% is controlled by the macro key \opt{cite}. The standard value is
% \cs{cite}.
%
%\DescribeOption{field}
%\DescribeOption{name}
%\DescribeOption{prefix}
%\DescribeOption{record}
% Four control values are available to affect low-level aspects of the
% creation of the notes database.  The \opt{prefix} option sets the
% string used by \currpkg\ to name the database, and is set to
% \opt{niib-} initially.  The \opt{field} and \opt{record} options
% contain the name of the field used for the note, and the \BibTeX\
% record type used. The standard values are \opt{note} and \opt{Misc},
% respectively.  Finally, the \opt{name} option sets the text used
% in addition to a number when automatically labelling notes.  This is
% set to \opt{Bibnote}: there is no space between this text and the
% number as this will confuse \BibTeX.
%
%\DescribeOption{debug}
% The \opt{debug} Boolean option is available for understanding what
% the package is doing.  When set to \opt{true}, the package writes
% additional information to the log to aid problem solving.
%
%\section{Testing the package}
%
% This release of \currpkg\ has several aims, all related to testing.
% Firstly, it provides a method to examine new ideas for
% \pkg{notes2bib}: feedback on the altered options is welcome.  Second,
% it is a test-bed for using \pkg{expl3} to create packages.  People
% familiar with the current \LaTeX3 ideas are encouraged to read the
% source and make suggestions. The new coding environment requires a
% more structured approach than \LaTeXe, and so it is possible ideas
% have been missed.
%
% The author wonders if this package could be implemented using the
% \pkg{template} system and \pkg{xfootnotes}.  Suggestions in this area
% are welcome!
%
% In order to use \currpkg, you will need an up-to-date \TeX\ system
% and recent copies of \pkg{expl3} and \pkg{xparse}. The package is
% tested with the current SVN release of the \LaTeX3 packages, but
% these may change on a day-to-day basis. So testers should be prepared
% for problems such as undefined macros from the new kernel! The \eTeX\
% extensions to \TeX\ are required by \currpkg.
%
% Due to the experimental nature of the package, it currently has no
% version number.  The package date should be used to check if versions
% are identical.  That said, the version of \pkg{notes2bib} will be
% stepped when new copies of \currpkg\ are created.
%
% While the package is experimental, it should work properly as a
% replacement for \pkg{notes2bib}, with the proviso that the options
% are very different.  Any problems of function should be reported as
% normal.
%
%\section{Installation}
%
% The entire bundle is supplied with the TDS-ready \ext{zip} file
% \file{notes2bib.tds.zip}.  Simply unzip this into your local texmf
% tree and run your hash program (\texttt{texhash} for \TeX{}Live or
% \texttt{initextmf -u} for MiK\TeX)
%
% To extract the package \file{xnotes2bib.sty} from
% \file{xnotes2bib.dtx}, run (pdf)\LaTeX\ on the later.  This will also
% create the documentation and \file{README.txt} file.  Three
% (pdf)\LaTeX\ runs with \cs{write18} enabled will also build the index
% and table of contents in the \ext{pdf}.
%
%\StopEventually{%
%  \PrintChanges
%  \PrintIndex}
%
%\section{Implementation}
%\subsection{Preliminaries}
%\changes{v0.0}{2008/09/09}{Replaced use of \cs{def_new:NNn}
%  and \cs{def:NNn} with \cs{def_new:Npn} and \cs{def:Npn},
%  respectively}
%\changes{v0.0}{2008/09/09}{Replaced \cs{cs_use:c} by
%  \cs{use:c}}
%\changes{v0.0}{2008/09/15}{Replaced \cs{token_to_string:N}
%  with \cs{token_to_str:N}}
%\changes{v0.0}{2008/09/15}{Removed \eTeX\ statement: this
% should be obvious to anyone using \pkg{expl3}}
%\changes{v0.0}{2008/09/24}{Moved options to \pkg{keys3}}
% The package starts by loading the basics of \pkg{expl3}. To
% keep things clear, first \pkg{l3names} is loaded to do the
% basic identification, and then everything else is started up.
% This is based on Morten H{\o}gholm's \pkg{xfrac} package
% lead-off.
%    \begin{macrocode}
%<*package>
\ProvidesExplPackage
  {\filename}{\filedate}{\fileversion}{\filedescription}
\RequirePackage {expl3,keys3,xparse}
%    \end{macrocode}
% As the \pkg{expl3} syntax is in use, there is no need to worry about
% white space in the code.  So there are very few |%| characters in the
% following. As far as possible, \pkg{expl3} or \pkg{xparse} macros are
% used here; however, a lot of the user-space \LaTeXe\ macros should
% still be valid in \LaTeX3.  There are also a few |@| macros where
% things are tidied closely to the \LaTeXe\ kernel at present (for
% example \cs{@filesw}).
%
%\changes{v0.0}{2008/09/15}{Moved errors to new system}
%\begin{macro}{\c_niib_err_tlp}
%\begin{macro}{\l_niib_packge_option_tlp}
% Error messages are created.
%    \begin{macrocode}
\err_file_new:Nn \c_niib_err_tlp {xnotes2bib.err}
\tlp_new:Nn \l_niib_err_option_tlp {option}
\err_interrupt_new:NNNnnn \c_niib_err_tlp \l_niib_err_option_tlp 0
  {All~package~control~should~be~given~using~the~\token_to_str:N~
   \niibsetup~\text_put_sp:~macro}
  {\err_help_return_or_X:}
  {}
\err_file_close:N \c_niib_err_tlp
%    \end{macrocode}
%\end{macro}
%\end{macro}
%
% As the \LaTeXe\ kernel expands package options, for the moment
% \currpkg\ does not accept any load-time options.
%    \begin{macrocode}
\DeclareOption* {
  \err_interrupt:NNw \c_niib_err_tlp \l_niib_err_option_tlp
}
\ProcessOptions \scan_stop:
%    \end{macrocode}
%
%\begin{macro}{\g_niib_note_int}
% A counter for the automatically-created notes is needed. This is a
% global value (life will get very complicated if not).
%    \begin{macrocode}
\int_new:N \g_niib_note_int
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\niib_thenote:}
% The counter needs to be expressed as a usable name. A check is made
% so that if there are more than ten notes then the number is padded.
%    \begin{macrocode}
\def_new:Npn \niib_thenote: {
  \l_niib_name_tlp
  \num_compare:nNnT {\g_niib_totalnotes_int} > {\c_nine} {
    \num_compare:nNnF {\g_niib_note_int} > {\c_nine} {
      0
    }
  }
  \int_to_arabic:n \g_niib_note_int
}
%    \end{macrocode}
%\end{macro}
%
%\subsection{User options}
%
%\begin{macro}{\l_niib_after_cite_bool}
%\changes{v0.0}{2008/09/09}{Renamed from
%  \cs{l_niib_after_bool}}
%\begin{macro}{\l_niib_before_cite_bool}
%\changes{v0.0}{2008/09/09}{Renamed from
%  \cs{l_niib_before_bool}}
% The \opt{placement} option needs two Boolean values.
%    \begin{macrocode}
\bool_new:N \l_niib_after_cite_bool
\bool_new:N \l_niib_before_cite_bool
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\begin{macro}{\niib_convert_endnotes:}
%\begin{macro}{\niib_convert_footnotes:}
% Some set up for other options.
%    \begin{macrocode}
\let_new:NN \niib_convert_endnotes: \scan_stop:
\let_new:NN \niib_convert_footnotes: \scan_stop:
%    \end{macrocode}
%\end{macro}
%\end{macro}
%
%\changes{v0.0}{2008/09/15}{Key management moved to \pkg{l3keys}}
%\begin{macro}{\niib_cite:n}
% The \opt{cite} key is stored.
%    \begin{macrocode}
\keys_manage_quick:n {
  niib/.cd:,
  cite/.store~in~tlp:N                     = \niib_cite:n,
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\niib_debug:n}
% The \opt{debug} option is implemented as a choice.
%    \begin{macrocode}
  debug/.choice:,
  debug/.default:n                = true,
  debug/true/.code:n              = {
    \def:Npn \niib_debug:n ##1 {
      \err_info:nn {##1} {(xnotes2bib) \text_put_four_sp:}
    }
  },
  debug/false/.code:n             = {
    \let:NN \niib_debug:n \use_none:n
  },
%    \end{macrocode}
%\end{macro}
% The \opt{convert footnotes} and \opt{convert endnotes} options work
% as choices.
%    \begin{macrocode}
  convert~endnotes/.choices:nn = {true,false} {
    \let:Nc \niib_convert_endnotes:
      {niib_convert_endnotes_ \l_keys_current_choice_tlp}
    },
  convert~endnotes/.default:n     = true,
  convert~footnotes/.choices:nn = {true,false} {
    \let:Nc \niib_convert_footnotes:
      {niib_convert_footnotes_ \l_keys_current_choice_tlp}
    },
  convert~footnotes/.default:n     = true,
%    \end{macrocode}
%\begin{macro}{\l_niib_field_tlp}
%\begin{macro}{\l_niib_key_after_tlp}
%\changes{v0.0}{2008/09/15}{Renamed from \cs{l_niib_key after_tlp}}
%\begin{macro}{\l_niib_key_before_tlp}
%\changes{v0.0}{2008/09/15}{Renamed from \cs{l_niib_key before_tlp}}
%\begin{macro}{\l_niib_key_mixed_tlp}
%\changes{v0.0}{2008/09/15}{Renamed from \cs{l_niib_key mixed_tlp}}
%\begin{macro}{\l_niib_keyword_tlp}
%\begin{macro}{\l_niib_name_tlp}
%\changes{v0.0}{2008/09/15}{Renamed from \cs{l_niib_notename_tlp}}
% Some storage macros.
%    \begin{macrocode}
  /keys/current~module:n          = niib,
  field/.store~in~tlp:c           = field,
  key~after/.store~in~tlp:c       = key_after,
  key~before/.store~in~tlp:c      = key_before,
  key~mixed/.store~in~tlp:c       = key_mixed,
  keyword/.store~in~tlp:c         = keyword,
  name/.store~in~tlp:c            = name,
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
% Another choice for placement.
%    \begin{macrocode}
  placement/.choice:              = \l_niib_placement_tlp,
  placement/.default:n            = mixed,
  placement/after/.code:n         = {
    \bool_set_true:N  \l_niib_after_cite_bool
    \bool_set_false:N \l_niib_before_cite_bool
  },
  placement/before/.code:n        = {
    \bool_set_false:N \l_niib_after_cite_bool
    \bool_set_true:N \l_niib_before_cite_bool
  },
  placement/mixed/.code:n         = {
    \bool_set_false:N \l_niib_after_cite_bool
    \bool_set_false:N \l_niib_before_cite_bool
  },
%    \end{macrocode}
%\begin{macro}{\l_niib_prefix_tlp}
%\begin{macro}{\l_niib_presort_after_tlp}
%\changes{v0.0}{2008/09/15}{Renamed from \cs{l_niib_presort after_tlp}}
%\begin{macro}{\l_niib_presort_before_tlp}
%\changes{v0.0}{2008/09/15}{Renamed from
%  \cs{l_niib_presort before_tlp}}
%\begin{macro}{\l_niib_presort_mixed_tlp}
%\changes{v0.0}{2008/09/15}{Renamed from \cs{l_niib_presort mixed_tlp}}
%\begin{macro}{\l_niib_record_tlp}
%\changes{v0.0}{2008/09/09}{Renamed and recoded from
%  \cs{niib_KV_string:n}}
%    \begin{macrocode}
  /keys/current~module:n          = niib,
  prefix/.store~in~tlp:c          = prefix,
  presort~after/.store~in~tlp:c   = presort_after,
  presort~before/.store~in~tlp:c  = presort_before,
  presort~mixed/.store~in~tlp:c   = presort_mixed,
  record/.store~in~tlp:c          = record,
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\begin{macro}{\l_niib_write_key_bool}
% One real Boolean key.
%    \begin{macrocode}
  write~key~field/.boolean:c      = write_key
}
%    \end{macrocode}
%\end{macro}
% All of the default values are set.
%    \begin{macrocode}
\keys_manage_quick:n{
  /niib/.cd:,
  cite            = \cite,
  debug           = false,
  field           = note,
  key~after       = zzz,
  key~before      = aaa,
  key~mixed       = {},
  name            = Bibnote,
  placement       = mixed,
  prefix          = niib-,
  presort~after   = mn,
  presort~before  = ml,
  presort~mixed   = mm,
  record          = Misc,
  write~key~field = true}
%    \end{macrocode}
%
%\subsection{User macros}
%\begin{macro}{\bibnote}
%\doarg{label}
%\darg{text}
% The main user macro has to check if the automatic note number is
% needed. If it is, the optional argument is note used to
% \cs{bibnotetext} as this automatically assumes the current value of
% \cs{niib_thenote:}.  The note text must be sorted out before the mark
% is made, as otherwise packages such as \pkg{cite} do not work
% correctly with punctuation. As the package is designed for \LaTeX3,
% it is assumed \eTeX\ is available and so \cs{exp_not:n} can be used
% on the mandatory argument. Hence everything is absorbed here without
% worrying about category codes.
%    \begin{macrocode}
\NewDocumentCommand {\bibnote} {o>{P}m} {
  \IfNoValueTF {#1} {
    \int_gincr:N \g_niib_note_int
    \bibnotetext {#2}
    \bibnotemark [\niib_thenote:]
  }{
    \bibnotetext [#1] {#2}
    \bibnotemark [#1]
  }
}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\bibnotemark}
%\doarg{label}
% As with \cs{bibnote}, if no optional argument is given the global
% note tracking counter is incremented before carrying out the
% citation.
%    \begin{macrocode}
\NewDocumentCommand {\bibnotemark} {o} {
  \IfNoValueTF {#1} {
    \int_gincr:N \g_niib_note_int
    \niib_notemark:n {\niib_thenote:}
  }{
    \niib_notemark:n {#1}
  }
}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\bibnotetext}
%\doarg{label}
%\darg{text}
% Writing the note text to the database should only occur if files are
% being written.  For the moment, this uses the \LaTeXe\ flag (and so
% the tradition syntax).
%    \begin{macrocode}
\NewDocumentCommand {\bibnotetext} {O{\niib_thenote:}>{P}m} {
  \if@filesw
%    \end{macrocode}
%\begin{macro}{\g_niib_out_stream}
% A new output stream may need to be created, if this is the first note
% to write. The \LaTeXe\ file switch is checked to see if this should
% occur.
%    \begin{macrocode}
    \cs_if_free:NT \g_niib_out_stream {
      \iow_new:N \g_niib_out_stream
      \iow_open:Nn \g_niib_out_stream
        {\l_niib_prefix_tlp \c_job_name_tlp.bib}
      \iow_expanded:Nn \g_niib_out_stream
        {This~is~an~auxiliary~file~used~by~the~`xnotes2bib'~package.^^J
         This~file~may~safely~be~deleted.^^J It~will~be~recreated~as~
         required.^^J}
    }
%    \end{macrocode}
%\changes{v0.0}{2008/09/15}{Replaced \cs{space} with \cs{text_put_sp:}}
% The writing macro works in expanded mode, as everything except the
% note text does need expansion. Notice that \cs{space} has to be used
% here after the macro names, as |~| does not work.
%    \begin{macrocode}
    \niib_debug:n {
      Writing~text:\MessageBreak #2\MessageBreak to~database~for~note~
      `#1'
    }
    \iow_expanded:Nn \g_niib_out_stream {
      @\l_niib_record_tlp{
        #1,^^J
        \text_put_sp: \text_put_sp: \l_niib_field_tlp \text_put_sp:
          =~{\exp_not:n{#2}},^^J
        \bool_if:NT \l_niib_write_key_bool {
          \text_put_sp: \text_put_sp: \l_niib_keyname_tlp \text_put_sp:
            =~{\niib_key:#1},^^J
        }
        \text_put_sp: \text_put_sp: keywords~
          =~{\l_niib_keyword_tlp},^^J
        \text_put_sp: \text_put_sp: presort~
          =~{\niib_presort:},^^J
      }^^J
    }
  \fi
}
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\begin{macro}{\flushnotestack}
% In order to delay citations to the end of the bibliography (and thus
% force others to the start), note citations are held in a clist until
% being added to the \ext{aux} file using \cs{flushnotestack}.  At that
% point, the stack is cleared so that collection can begin again.
%    \begin{macrocode}
\NewDocumentCommand {\flushnotestack} {} {
  \clist_if_empty:NF \g_niib_before_cite_clist {
    \if@filesw
      \iow_expanded:Nn \@auxout {
        \token_to_str:N \niibbeforecite {
          \g_niib_before_cite_clist
        }
      }
    \fi
  }
  \clist_if_empty:NF \g_niib_after_cite_clist {
    \nocite { \g_niib_after_cite_clist}
    \if@filesw
      \iow_expanded:Nn \@auxout {
        \token_to_str:N \niibaftercite {\g_niib_after_cite_clist}
      }
    \fi
  }
  \clist_gclear:N \g_niib_after_cite_clist
}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\niibsetup}
%\changes{v0.0}{2008/09/15}{Converted to \pkg{l3keys} method}
% The document-level command for settings.
%    \begin{macrocode}
\NewDocumentCommand {\niibsetup} {m} {\keys_manage:n {/niib/.cd:,#1}}
%    \end{macrocode}
%\end{macro}
%
%\subsection{Macros for the \texorpdfstring{\ext{aux}}{.aux}
%  file}
% To allow tracking of the need to re-run \LaTeX, each run writes the
% current out-of-order citations to the \ext{aux} file.  This requires
% two user-space macros, although it is not intended the user ever
% applies them!
%
%\begin{macro}{\g_niib_before_cite_old_clist}
%\changes{v0.0}{2008/09/09}{Renamed from
%  \cs{g_niib_oldbeforecite_clist}}
%\begin{macro}{\g_niib_after_cite_old_clist}
%\changes{v0.0}{2008/09/09}{Renamed from
%  \cs{g_niib_oldaftercite_clist}}
% Two lists are created to track the out-of-order citations written in
% the previous run to the \ext{aux} file.
%    \begin{macrocode}
\clist_new:N \g_niib_before_cite_old_clist
\clist_new:N \g_niib_after_cite_old_clist
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\begin{macro}{\g_niib_document_tlp}
%\changes{v0.0}{2008/09/15}{Changed \cs{tlp_put_right:Nn} to
%  \cs{tlp_gput_right:Nn}}
% A hook into the \cs{document} macro is needed by \cs{niibbeforecite};
% this needs to exist before \cs{document} is executed, hence needing a
% tlp for this.
%    \begin{macrocode}
\tlp_new:N \g_niib_document_tlp
\tlp_gput_right:Nn \document {\g_niib_document_tlp}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\niibbeforecite}
%\begin{macro}{\niibaftercite}
%\darg{citations}
% The macros themselves are quite simple. \cs{clist_gset_eq:Nc} is not
% used as the macros could appear more than once in the \ext{aux} file.
%    \begin{macrocode}
\NewDocumentCommand {\niibbeforecite} {m} {
  \clist_gput_right:Nn \g_niib_before_cite_old_clist {#1}
  \tlp_gput_right:Nn \g_niib_document_tlp {\nocite{#1}}
}
\NewDocumentCommand {\niibaftercite} {m} {
  \clist_gput_right:Nn \g_niib_after_cite_old_clist {#1}
}
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\begin{macro}{\g_niib_totalnotes_int}
% The total number of notes in the last run is needed
%    \begin{macrocode}
\int_new:N \g_niib_totalnotes_int
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\niibtotalnotes}
%\darg{number}
% The total number of notes created is stored for the next run.
%    \begin{macrocode}
\NewDocumentCommand {\niibtotalnotes} {m} {
  \int_gset:Nn \g_niib_totalnotes_int {#1}
}
%    \end{macrocode}
%\end{macro}
%
%\subsection{Internal macros}
%\begin{macro}{\niib_notemark:n}
%\changes{v0.0}{2008/09/09}{Replaced \cs{clist_put_right:Nx}
%  by \cs{clist_gput_right:Nx}}
% The citation command itself is in an internal macro, as it is called
% from a few places.  Both the \opt{before} and \opt{after} modes
% require some tracking of the citations.
%    \begin{macrocode}
\def_new:Npn \niib_notemark:n #1 {
  \niib_debug:n {Creating~citation~for~note~`#1'}
  \bool_if:NT \l_niib_before_cite_bool {
    \niib_debug:n {Note~`#1'~before~real~citations}
    \clist_gput_right:Nx \g_niib_before_cite_clist {#1}
  }
  \bool_if:NTF \l_niib_after_cite_bool {
    \niib_debug:n {Note~`#1'~after~real~citations}
    \clist_gput_right:Nx \g_niib_after_cite_clist {#1}
    \niib_after_cite:n {#1}
  }{
    \niib_cite:n {#1}
  }
}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\g_niib_before_cite_clist}
%\changes{v0.0}{2008/09/09}{Renamed from
%  \cs{g_niib_beforecite_clist}}
%\begin{macro}{\g_niib_after_cite_clist}
%\changes{v0.0}{2008/09/09}{Renamed from
%  \cs{g_niib_aftercite_clist}}
% Out-of-order citations in the current run are followed using
% two clists.
%    \begin{macrocode}
\clist_new:N \g_niib_before_cite_clist
\clist_new:N \g_niib_after_cite_clist
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\begin{macro}{\niib_key:}
%\begin{macro}{\niib_presort:}
% The key and presort information for the database needs to be
% created dynamically from the various keys.
%    \begin{macrocode}
\def_new:Npn \niib_key: {
  \bool_if:NTF \l_niib_before_cite_bool {
    \tlp_use:N \l_niib_key_before_tlp
  }{
    \bool_if:NTF \l_niib_after_cite_bool {
      \tlp_use:N \l_niib_key_after_tlp
    }{
      \tlp_use:N \l_niib_key_mixed_tlp
    }
  }
}
\def_new:Npn \niib_presort: {
  \bool_if:NTF \l_niib_before_cite_bool {
    \tlp_use:N \l_niib_presort_before_tlp
  }{
    \bool_if:NTF \l_niib_after_cite_bool {
      \tlp_use:N \l_niib_presort_after_tlp
    }{
      \tlp_use:N \l_niib_presort_mixed_tlp
    }
  }
}
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\begin{macro}{\niib_convert_endnotes_false:}
%\begin{macro}{\niib_convert_endnotes_true:}
%\begin{macro}{\niib_convert_footnotes_false:}
%\begin{macro}{\niib_convert_footnotes_true:}
% Conversion of footnotes and endnotes takes place using four dedicated
% macros, which can then be called by csname.
%    \begin{macrocode}
\def_new:Npn \niib_convert_endnotes_false: {
  \niib_debug:n {Restoring~normal~endnotes}
  \let:NN \endnote \niib_saved_endnote:
  \let:NN \endnotemark \niib_saved_endnotemark:
  \let:NN \endnotetext \niib_saved_endnotetext:
}
\def_new:Npn \niib_convert_endnotes_true: {
  \niib_debug:n {Converting~endnotes~to~bibnotes}
  \let:NN \endnote \bibnote
  \let:NN \endnotemark \bibnotemark
  \let:NN \endnotetext \bibnotetext
}
\def_new:Npn \niib_convert_footnotes_false: {
  \niib_debug:n {Restoring~normal~footnotes}
  \let:NN \footnote \niib_saved_footnote:
  \let:NN \footnotemark \niib_saved_footnotemark:
  \let:NN \footnotetext \niib_saved_footnotetext:
}
\def_new:Npn \niib_convert_footnotes_true: {
  \niib_debug:n {Converting~footnotes~to~bibnotes}
  \let:NN \footnote \bibnote
  \let:NN \footnotemark \bibnotemark
  \let:NN \footnotetext \bibnotetext
}
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\begin{macro}{\thanks}
% The \cs{thanks} macro has to be replaced by one that uses the
% original \cs{footnotemark} and \cs{footnotetext}.
%    \begin{macrocode}
\def:Npn \thanks #1 {
  \niib_saved_footnotemark:
  \protected@xdef \@thanks {
    \@thanks
    \protect \niib_saved_footnotetext: [\the\c@footnote] {#1}
  }
}
%    \end{macrocode}
%\end{macro}
%
%\subsection{Finalising}
%\begin{macro}{\l_niib_keyname_tlp}
%\changes{v0.0}{2008/09/09}{Renamed from \cs{niib_keyname:}}
% The name used for the \texttt{key} field is stored a little
% later.  The store is set up here.
%    \begin{macrocode}
\tlp_new:N \l_niib_keyname_tlp
%    \end{macrocode}
%\end{macro}
%
%\begin{macro}{\niib_biliography:n}
%\begin{macro}{\printbibnotes}
%\begin{macro}{\niib_after_cite:n}
%\changes{v0.0}{2008/09/09}{Renamed from
%  \cs{niib_aftercite:n}}
% Various macro definitions depend on the loading of other packages.
% When \pkg{biblatex} is in use, life is rather different to when the
% standard citation method is operational.  The \cs{niib_key:} macro is
% used to control sorting: \pkg{biblatex} uses a different macro name
% for this function than normal \LaTeX\ does.  The \cs{printbibnotes}
% user macro always prints the bibliography, using only the notes
% database if possible. The \cs{niib_after_cite:n} macro has to keep a
% track of the appropriate bibnotes and also fiddle with the
% \cs{@filesw} switch to prevent writing at the wrong time.
%    \begin{macrocode}
\AtBeginDocument{
  \err_info:nn {
    (xnotes2bib) \text_put_sp: Beginning~\token_to_str:N
    \AtBeginDocument \text_put_sp: tasks
  } {}
  \@ifpackageloaded {biblatex} {
    \tlp_set:Nn \l_niib_keyname_tlp {keysort}
    \gappto \blx@bibfiles {,\niib_prefix\c_job_name_tlp}
    \let_new:NN \printbibnotes \printbibliography
    \def_new:Npn \niib_after_cite:n #1 {
      \AtNextCite {\@fileswfalse}
      \niib_cite:n {#1}
    }
  }{
    \tlp_gset:Nn \l_niib_keyname_tlp {key}
    \let_new:NN \niib_biliography:n \bibliography
    \def:Npn \bibliography #1 {
      \int_compare:nNnTF {\g_niib_note_int} = {\c_zero} {
        \niib_biliography:n {#1}
      }{
        \niib_biliography:n {
          #1, \l_niib_prefix_tlp \c_job_name_tlp
        }
      }
    }
    \NewDocumentCommand {\printbibnotes} {} {
      \niib_biliography:n {\l_niib_prefix_tlp\c_job_name_tlp}
    }
%    \end{macrocode}
%\begin{macro}{\ifniib@filesw}
% There is a need to back-up the \cs{@filesw} switch.  As this is a
% \LaTeXe\ switch, the name and creation method used here are not
% \LaTeX3-based.
%    \begin{macrocode}
    \newif \ifniib@filesw
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\@restore@auxhandle}
%\changes{v0.0}{2008/09/09}{Moved patch code to after
%  \cs{AtBeginDocument}}
%\begin{macro}{\niib_auxhandle:}
% If \pkg{cite} is loaded, there is further trouble.
%    \begin{macrocode}
    \@ifpackageloaded {cite}{
      \def_new:Npn \niib_after_cite:n #1 {
         \let:NN \ifniib@filesw \if@filesw
         \@fileswfalse
         \def:Npn \niib_auxhandle: {
           \let:NN \if@filesw \ifniib@filesw
           \let:NN \niib_auxhandle: \scan_stop:
         }
         \niib_cite:n {#1}
      }
      \tlp_gput_right:Nn \g_niib_document_tlp {
        \cs_if_exist:NTF \@restore@auxhandle{
          \tlp_put_right:Nn \@restore@auxhandle {\niib_auxhandle:}
        }{
          \def_new:Npn \@restore@auxhandle {\niib_auxhandle:}
        }
      }
      \let_new:NN \niib_auxhandle: \scan_stop:
%    \end{macrocode}
%\end{macro}
%\end{macro}
% Life is slightly easier without \pkg{cite}.
%    \begin{macrocode}
    }{
      \def_new:Npn \niib_after_cite:n #1 {
         \let:NN \ifniib@filesw \if@filesw
         \@fileswfalse
         \niib_cite:n {#1}
         \let:NN \if@filesw \ifniib@filesw
      }
    }
  }
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\end{macro}
%\begin{macro}{\niib_saved_footnote:}
%\begin{macro}{\niib_saved_footnotemark:}
%\begin{macro}{\niib_saved_footnotetext:}
%\begin{macro}{\niib_saved_endnote:}
%\begin{macro}{\niib_saved_endnotemark:}
%\begin{macro}{\niib_saved_endnotetext:}
% The second thing to worry about is footnotes and endnotes. The
% definitions are saved here so that any other packages can have made
% their changes. No argument specifiers are given as these are saving
% user space macros.
%    \begin{macrocode}
  \let_new:NN \niib_saved_footnote: \footnote
  \let_new:NN \niib_saved_footnotemark: \footnotemark
  \let_new:NN \niib_saved_footnotetext: \footnotetext
  \let_new:NN \niib_saved_endnote: \endnote
  \let_new:NN \niib_saved_endnotemark: \endnotemark
  \let_new:NN \niib_saved_endnotetext: \endnotetext
%    \end{macrocode}
% Any conversion can now be applied, before the \opt{convert footnotes}
% and \opt{convert endnotes} options are redefined to work immediately.
%    \begin{macrocode}
  \niib_convert_endnotes:
  \niib_convert_footnotes:
  \keys_manage_quick:n {
    /niib/.cd:,
    convert~endnotes/true/.code:n   = {\niib_convert_endnotes_true:},
    convert~endnotes/false/.code:n  = {\niib_convert_endnotes_false:},
    convert~footnotes/true/.code:n  = {\niib_convert_footnotes_true:},
    convert~footnotes/false/.code:n = {\niib_convert_footnotes_false:},
  }
  \err_info:nn {
    (xnotes2bib) \text_put_sp: Finished~\token_to_str:N
    \AtBeginDocument \text_put_sp: tasks
  } {}
}
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\begin{macro}{\niib_rerun_check:n}
% If either of the out-of-order options are in use, then a comparison
% of the citations used with those used in the last run is needed.
% There are a couple of easy checks to make: if only one list is empty,
% there must be changes.  If both lists are occupied, a check of every
% item must be made.
%    \begin{macrocode}
\def_new:Npn \niib_rerun_check:n #1 {
  \clist_if_empty:cTF {g_niib_old#1cite_clist}{
    \clist_if_empty:cF {g_niib_#1cite_clist}{
      \niib_rerun_log:
    }
  }{
    \clist_if_empty:cTF {g_niib_#1cite_clist}{
      \niib_rerun_log:
%    \end{macrocode}
% If both lists are occupied by data, the total contents of each one
% have to be compared with the other.  This needs to be done both ways
% round.
%    \begin{macrocode}
    }{
      \bool_set_false:N \l_tmpa_bool
      \def:Npn \niib_rerun_test:n ##1 {
        \clist_if_in:cnTF {g_niib_old#1cite_clist} {##1} {
          \bool_set_true:N \l_tmpa_bool
          \clist_map_break:w
        }{
        }
      }
      \clist_map_function:cN {g_niib_#1cite_clist}
        \niib_rerun_test:n
      \def:Npn \niib_rerun_test:n ##1 {
        \clist_if_in:cnTF {g_niib_#1cite_clist} {##1} {
          \bool_set_true:N \l_tmpa_bool
          \clist_map_break:w
        }{
        }
      }
      \clist_map_function:cN {g_niib_old#1cite_clist}
        \niib_rerun_test:n
      \bool_if:NF \l_tmpa_bool {
        \niib_rerun_log:
      }
    }
  }
}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\niib_rerun_test:n}
% This is redefined in the above, but is made available here.
%    \begin{macrocode}
\let_new:NN \niib_rerun_test:n \use_none_i:n
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\niib_rerun_log:}
%\changes{v0.0}{2008/09/09}{Maximum of one message per run}
% The information message needs to be available in a few different
% places.
%    \begin{macrocode}
\def_new:Npn \niib_rerun_log: {
  \err_info:nn {
    (xnotes2bib) \text_put_sp: To~get~notes~in~the~correct~order,~
    please \err_newline: rerun~LaTeX,~(re)run~BibTeX~on~the~file~
    \c_job_name_tlp.aux \err_newline: and~rerun~LaTeX~again~afterwards
  } {(xnotes2bib) \text_put_sp:}
  \io_put_log:x {
    REQ:3:latex:REQ \iow_newline:
    REQ:2:bibtex:REQ \iow_newline:
    REQ:1:latex:REQ \iow_newline:
  }
  \let \niib_rerun_log: \scan_stop:
}
%    \end{macrocode}
%\end{macro}
%
% At the end of the document, the package should tidy up.
%    \begin{macrocode}
\AtEndDocument{
  \niib_rerun_check:n {before}
  \niib_rerun_check:n {after}
  \flushnotestack
  \iow_expanded:Nn \@auxout {
    \token_to_str:N \niibtotalnotes {\int_to_arabic:n \g_niib_note_int}
  }
  \num_compare:nNnF {\g_niib_totalnotes_int} = {\g_niib_note_int} {
    \niib_rerun_log:
  }
  \cs_if_free:NF \g_niib_out_stream {
    \iow_close:N \g_niib_out_stream
  }
}
%</package>
%    \end{macrocode}
%
%\Finale
%
%\iffalse
%<*jawl3doc>
\NeedsTeXFormat{LaTeX2e}
\RequirePackage{l3names}
\ProvidesExplPackage
  {jawl3doc}{2008/09/09}{0.0}
  {Additions to l3doc (JAW)}
\DeleteShortVerb\|
\DeleteShortVerb\"
\RequirePackage{expl3,xparse}
\MakeShortVerb\|
\IfFileExists{\c_job_name_tlp.sty}
  {\RequirePackage{\c_job_name_tlp}}{}
\RequirePackage{helvet,mathpazo}
\RequirePackage[final]{listings}

\NewDocumentCommand{\pkg}{m}{\textsf{#1}}
\NewDocumentCommand{\currpkg}{}{\pkg{\c_job_name_tlp}}
\NewDocumentCommand{\latin}{m}{\emph{#1}}
\NewDocumentCommand{\etc}{}{\latin{etc}}
\NewDocumentCommand{\ext}{m}{\file{.#1}}
\NewDocumentCommand{\opt}{m}{\texttt{#1}}

\int_new:N \g_jawldoc_arg_int
\def_new:Npn \jawldoc_thearg: {
  \int_to_arabic:n \g_jawldoc_arg_int
}
\NewDocumentCommand{\darg}{m}{
  \int_gincr:N \g_jawldoc_arg_int
  {\ttfamily\char`\#\jawldoc_thearg:~:~}#1
  \par\noindent\ignorespaces
}
\NewDocumentCommand{\doarg}{m}{
  \int_gincr:N \g_jawldoc_arg_int
  {\ttfamily\makebox[0pt][r]{[}
  \char`\#\jawldoc_thearg:]:~}#1
  \par\noindent\ignorespaces
}
\tlp_put_right:Nn\endmacro{\int_gzero:N\g_jawldoc_arg_int}
\NewDocumentCommand{\DescribeOption}{}{
  \leavevmode \@bsphack
  \group_begin:
  \MakePrivateLetters
  \Describe_Option:
}
\def_new:Npn \Describe_Option: #1 {
  \group_end:
  \marginpar{
    \raggedleft\PrintDescribeEnv{#1}
  }
  \SpecialOptionIndex{#1}
  \@esphack\ignorespaces
}
\NewDocumentCommand{\SpecialOptionIndex}{m}{
  \@bsphack
  \index{
    #1\actualchar{\protect\ttfamily#1}
    \space(option)\encapchar usage
  }
  \index{
    options:\levelchar#1\actualchar{\protect\ttfamily#1}
    \encapchar usage
  }
  \@esphack
}
%</jawl3doc>
%\fi
