%D \module
%D   [       file=core-not,
%D        version=1997.09.15,
%D          title=\CONTEXT\ Core Macros,
%D       subtitle=Footnote Handling,
%D         author=Hans Hagen,
%D           date=\currentdate,
%D      copyright={PRAGMA / Hans Hagen \& Ton Otten}]
%C
%C This module is part of the \CONTEXT\ macro||package and is
%C therefore copyrighted by \PRAGMA. See mreadme.pdf for
%C details.

\writestatus{loading}{Context Core Macros / Footnote Handling}

%D BEWARE: THIS MODULE IS REPLACED BY A NEW VERSION (FOR IDRIS) 

%D Unfortunately we cannot force an even number of lines in
%D a two column footnote placement.

%D There are some (still) dutch core commands used in this
%D file.

\unprotect

% splitskips setten

%D Footnotes are can be characterized by three components:
%D
%D \startopsomming[opelkaar]
%D \som a small number \voetnoot{a footnote number} or
%D symbol {\stelvoetnotenin[conversie=set 2]\voetnoot{a
%D footnote}}
%D \som and a similar mark at the bottom of the page
%D \som followed by some additional text
%D \stopopsomming
%D
%D Because footnotes are declared at the location of their
%D reference. Footnotes can be seen as a special kind of
%D floating bodies. There placement is postponed but has to be
%D taken into account in the pagebreak calculations. This kind
%D of calculations are forced by using \type{\insert}.

\installinsertion\footins

%D \macros
%D   {setupfootnotes,setupfootnotedefinition}
%D
%D We can influence footnote typesetting with the setup
%D command:
%D
%D \showsetup{\y!setupfootnotes}
%D
%D It's sort of a custom to precede footnotes by a horizontal
%D rule and although fancy rules like
%D
%D \starttypen
%D \hbox to 10em{\hskip-3em\dotfill}
%D \stoptypen
%D
%D Are quite ligitimate, we default to a simple one 20\% of the
%D text width.
%D
%D When \type{n} exceeds~1, footnotes are typeset in
%D multi||columns, using the algoritm presented on page~397
%D of \TEX book. Footnotes can be places on a per page basis
%D or whereever suitable. When we set~\type{n} to~0, we get a
%D rearanged paragraph, typeset by the algoritms on pages 398
%D and~389. We definitely did not reinvent that wheel.

\newif\ifendnotes    \endnotesfalse
\newif\ifbottomnotes \bottomnotestrue

%D The footnoterule can be a graphic and therefore calling this
%D setup macro at every skipswitch is tricky (many many MP
%D runs). Let's just reserve a few points, that probably match
%D those of the stretch component.

\def\setupfootnotedefinition%
  {\steldoordefinierenin[\??vn\??vn]}

\doordefinieren
  [\??vn\??vn]
  [\c!plaats=\v!inlinker,
   \c!breedte=\v!passend,
   \c!kopletter=\@@vnletter,
   \c!kopkleur=\@@vnkleur,
   \c!voor=,
   \c!na=]

\presetlocalframed
  [\??vn]

%D The previous definitions indicate that we can frame
%D the footnote area. The footnotes themselves are treated as
%D definitions.
%D
%D \showsetup{\y!setupfootnotes}

\newif\ifcleverfootnotes % being [plaats=kolommen]

\def\setupfootnotes
  {\dosingleempty\dosetupfootnotes}

\def\dodofootnoterule
  {\ifvmode
     \color
       [\@@vnlijnkleur]
       {\hrule\!!width.2\hsize\!!height\@@vnlijndikte\!!depth\!!zeropoint}%
     \kern\strutdepth
   \fi}

%D The following switch can be used to disable limiting the
%D height of the footnote area, something that is needed in
%D multi column balancing. Use this switch with care.

\newif\iffootnotelimit \footnotelimittrue

\def\dosetupfootnotes[#1]%
  {\iffirstargument
     \getparameters[\??vn][#1]%
     \processaction
       [\@@vnlijn]
       [    \v!aan=>\let\dofootnoterule\dodofootnoterule,
            \v!uit=>\let\dofootnoterule\relax,
        \s!default=>\let\dofootnoterule\relax,
        \s!unknown=>\let\dofootnoterule\@@vnlijn]%
     \processaction
       [\@@vnsplitsen]
       [    \v!soepel=>\footnotepenalty\zeropoint,
            \v!streng=>\footnotepenalty9999,
        \v!zeerstreng=>\footnotepenalty\maxdimen,
           \s!default=>\footnotepenalty\zeropoint,
           \s!unknown=>\footnotepenalty\commalistelement]%
   \fi
   \setfootnotedistance
   \count\footins1000
   \ExpandBothAfter\doifinsetelse\v!kolommen\@@vnplaats
     {\cleverfootnotestrue % global ?
      \ifnum\@@kln=\zerocount
        \scratchcounter\plusone
      \else
        \scratchcounter\@@vnn
      \fi
      \global\endnotesfalse
      \global\bottomnotestrue
      \setcleverfootnotes}
     {\cleverfootnotesfalse
      \ifnum\@@vnn=\zerocount
        \settextfootnotes
        \scratchcounter\plusone
      \else
        \setcolumnfootnotes
        \scratchcounter\@@vnn
        \divide\count\footins \scratchcounter
      \fi
      \ExpandBothAfter\doifinsetelse\v!pagina\@@vnplaats
        {\global\endnotesfalse
         \ExpandBothAfter\doifinsetelse\v!hoog\@@vnplaats
           {\global\bottomnotesfalse}
           {\global\bottomnotestrue}}
        {\global\endnotestrue
         \global\bottomnotestrue
         \postponefootnotes}}%
   \iffootnotelimit
     \dimen\footins\@@vnhoogte
     \multiply\dimen\footins \scratchcounter
   \fi}

\def\checknotes{\setupfootnotes\relax} % will be replaced 

\def\setfootnotedistance
  {\setbox\scratchbox\vbox
     {\forgetall
      \@@vnvoor
      \dofootnoterule
      \@@vnna}%
   \global\skip\footins\ht\scratchbox
   \setbox\scratchbox\box\voidb@x} % scratchbox can be in use

\ifx\setfootnotehsize\undefined

  \def\setfootnotehsize{\hsize\@@vnbreedte} % can be overloaded

\fi

\def\setcleverfootnotes
  {\def\startpushfootnote  {\bgroup % wellicht ooit kopuitlijnen
                            \stelinmargein[\c!uitlijnen=\v!links]%
                            \getvalue{\e!start\??vn\??vn}}%
   \def\stoppushfootnote   {\getvalue{\e!stop\??vn\??vn}%
                            \egroup}%
   \let\startpopfootnotes  \donothing
   \let\stoppopfootnotes   \donothing}

\def\setcolumnfootnotes
  {\def\startpushfootnote  {\setfootnotehsize % possibly overloaded
                            \setrigidcolumnhsize\hsize\@@vnkolomafstand\@@vnn
                            \bgroup
                            \stelinmargein[\c!uitlijnen=\v!links]%
                            \getvalue{\e!start\??vn\??vn}}%
   \def\stoppushfootnote   {\getvalue{\e!stop\??vn\??vn}%
                            \egroup}%
   \def\startpopfootnotes  {\bgroup
                            \setfootnotehsize
                            \setrigidcolumnhsize\hsize\@@vnkolomafstand\@@vnn
                            \setbox0\vbox\bgroup}%
   \def\stoppopfootnotes   {\egroup
                            \setbox0\vbox
                              {\unvbox0\setbox0\lastbox
                               \ifvbox0\unvbox\else\box\fi0}%
                            \rigidcolumnbalance0\egroup}}

\def\settextfootnotes
  {\def\startpushfootnote  {\startvboxtohbox
                            \dostartattributes\??vn\c!letter\c!kleur{}}%
   \def\stoppushfootnote   {\hskip\@@vnkolomafstand % plus.5em minus.5em
                            \dostopattributes
                            \stopvboxtohbox}%
   \def\startpopfootnotes  {\vbox\bgroup
                            \doifnotinset\@@vnbreedte{\v!passend,\v!ruim}
                              {\setfootnotehsize}%
                            \beginofshapebox}%
   \def\stoppopfootnotes   {\endofshapebox
                            \reshapebox
                              {\ifhbox\shapebox\unhbox\else\box\fi\shapebox
                               \endgraf}%
                            \flushshapebox
                            \egroup}}

%D The formatting depends on the width of the table, so we
%D have to set \type {n} to zero.
%D
%D \starttypen
%D \startbuffer
%D \bTABLE
%D \bTR \bTD one \footnote{\dorecurse{10}{abcd }} \eTD \bTD two \eTD \eTR
%D \bTR \bTD three fout five six seven eight nine \eTD \bTD ten \eTD \eTR
%D \eTABLE
%D \stopbuffer
%D
%D \startlocalfootnotes[n=0,location={text,none}]
%D \placelegend[n=2]{\getbuffer}{\placelocalfootnotes}
%D \stoplocalfootnotes
%D \stoptypen

%D The numbers that accompany a footnote are generated using
%D the standard \CONTEXT\ numbering mechanism, and thereby can
%D be assigned on a per whatever sectioning basis.

\definieernummer
  [\v!voetnoot]
  [\c!wijze=\@@vnwijze,
   \c!sectienummer=\@@vnwijze,
   \c!conversie=\@@vnconversie]

%D Both these parameters are coupled to the setup command we
%D will implement in a moment. This means that, given a
%D suitable symbol set, symbols can be used instead of numbers,
%D by saying:
%D
%D \starttypen
%D \setupfootnotes[conversion=set 2]
%D \stoptypen

%D \macros
%D   {footnote}
%D
%D A footnote can have a reference as optional argument and
%D therefore its formal specification looks like:
%D
%D \showsetup{\y!footnote}
%D
%D This command has one optional command: the reference. By
%D saying \type{[-]} the number is omitted. The footnote
%D command is not that sensitive to spacing, so it's quite
%D legal to say:
%D
%D \startbuffer
%D Users of \CONTEXT\ must keep both feet \footnote{Given they
%D have two.} on the ground and not get confused \footnote{Or
%D even crazy.} by all those obscure \footnote{But fortunately
%D readable.} parameters.
%D \stopbuffer
%D
%D \typebuffer
%D
%D When setting the \type{conversion} to \type{set 2} we get
%D something like:
%D
%D \bgroup
%D \startsmaller
%D \stelvoetnotenin[conversie=set 1]
%D \haalbuffer
%D \stopsmaller
%D \egroup
%D
%D Typesetting footnotes is, at least for the moment, disabled
%D when reshaping boxes.
%D
%D The additional macro \type {\footnotetext} and the
%D associated \type {\note} macro were implemented at
%D request of users on the mailing list and a suggestion by
%D taco to split of the symbol placement. I decided to
%D merge this functionality with the existing \type {\note}
%D functionality.

\newif\iffootnotesymbol

\unexpanded\def\footnote    {\dodoubleempty\dofootnote[1]}
\unexpanded\def\footnotetext{\dodoubleempty\dofootnote[0]}

\def\dofootnote[#1][#2]%
  {\unskip
   \ifcase#1\relax
     \global\footnotesymbolfalse
   \else
     \global\footnotesymboltrue
   \fi
   \ifvisible
     \ifreshapingbox
       \@EAEAEA\gobbletwoarguments
     \else
       \@EAEAEA\dodofootnote
     \fi
   \else % todo: \iftrialtypesetting
     \@EA\gobbletwoarguments
   \fi{#2}}

%D \macros
%D   {footnotesenabled}
%D
%D Before we come to typesetting a footnote, we first check
%D if we have to typeset a number. When a \type{-} is passed
%D instead of a reference, no number is typeset. We can
%D temporary disable footnotes by saying
%D
%D \starttypen
%D \footnotesenabledfalse
%D \stoptypen
%D
%D which can be handy while for instance typesetting tables
%D of contents. The pagewise footnote numbering is dedicated
%D to Han The Thanh, who needed it first.

\newif\iffootnotesenabled \footnotesenabledtrue

\newconditional\pagewisefootnotes % saves two hash entries

\def\lastfootnotepage{1}

\def\domovednote#1#2%
  {\ifconditional\pagewisefootnotes
     \doifreferencefoundelse{\s!fnt:t:\internalfootreference}
       {\let\savedrealreference\currentrealreference
        \doifreferencefoundelse{\s!fnt:f:\internalfootreference}
          {\ifnum\savedrealreference<\currentrealreference\relax\symbol[#1]\else
           \ifnum\savedrealreference>\currentrealreference\relax\symbol[#2]\fi\fi}
          {}}
       {}
   \fi}

\def\dodofootnote
  {\iffootnotesenabled
     \iftrialtypesetting
       \@EAEAEA\nododofootnote
     \else
       \@EAEAEA\dododofootnote
     \fi
   \else
     \@EA\gobbletwoarguments
   \fi}

\def\nododofootnote#1%
  {\doifnot{#1}{-}{\kern.5em}% quick hack, approximation
   \gobbleoneargument}

\def\dododofootnote#1%
  {\doglobal\increment\internalfootreference
   \doifelse\@@vnwijze{\v!per\v!pagina}
     {\settrue \pagewisefootnotes}
     {\setfalse\pagewisefootnotes}%
   \doifelse{#1}{-}
     {\let\footnotenumber\empty}
     {\ifconditional\pagewisefootnotes
        \doifreferencefoundelse{\s!fnt:t:\internalfootreference}
          {\ifnum\currentrealreference>\lastfootnotepage\relax
             \global\let\lastfootnotepage\currentrealreference
             \resetnummer[\v!voetnoot]%
           \fi}
          {}%
      \fi
      \verhoognummer[\v!voetnoot]%
      \maakhetnummer[\v!voetnoot]%
      \rawreference\s!fnt{#1}{\hetnummer}%
      \let\footnotenumber\hetnummer}%
   \dostartfootnote}

%D The main typesetting routine is more or less the same as the
%D \PLAIN\ \TEX\ one, except that we only handle one type while
%D \PLAIN\ also has something \type{\v...}. In most cases
%D footnotes can be handled by a straight insert, but we do so
%D by using an indirect call to the \type{\insert} primitive.

\let\localfootinsert=\insert

%D Making footnote numbers active is not always that logical,
%D especially when we keep the reference and text at one page.
%D On the other hand we need interactivity when we refer to
%D previous notes or use end notes. Therefore we support
%D interactive footnote numbers in two ways \voetnoot{This
%D feature was implemented years after we were able to do so,
%D mainly because endnotes had to be supported.} that is,
%D automatically (vise versa) and by user supplied reference.

\newcounter\internalfootreference

\let\startpushfootnote = \relax
\let\stoppushfootnote  = \relax

\newsignal\footnotesignal
\newcount \footnotepenalty

\footnotepenalty=0 % needed in order to split in otrset

\def\dostartfootnote% nog gobble als in pagebody
  {\bgroup
  %\restorecatcodes % to be tested first
   \ifinregels % otherwise problems with \type <crlf> {xxx}
     \ignorelines % makes footnotes work in \startlines ... \stoplines
   \fi
   \iffootnotesymbol
     \dolastnotesymbol
   \else
     \unskip\unskip
     \global\let\lastnotesymbol\dolastnotesymbol
   \fi
   \ignorespaces
   \localfootinsert\footins\bgroup
     \penalty\footnotepenalty
     \forgetall
     \setfootnotebodyfont
     \redoconvertfont % to undo \undo calls in in headings etc
     \splittopskip\strutht  % not actually needed here
     \splitmaxdepth\strutdp % not actually needed here
     \iffixedlayoutdimensions % ugly hack, will change
       \linkermargeafstand\@@vnmargeafstand
       \rechtermargeafstand\linkermargeafstand
     \else
       \def\linkermargeafstand{\@@vnmargeafstand}%
       \let\rechtermargeafstand\linkermargeafstand
     \fi
     \ifcase\@@vnn\relax % new 31-07-99 ; always ?
       \doifnotinset\@@vnbreedte{\v!passend,\v!ruim}
         {\setfootnotehsize}%
     \fi
     \startpushfootnote
       {\ifx\footnotenumber\empty \else
\preparethenumber\??vn\footnotenumber\preparednumber
          \iflocation
            \naarbox{\@@vnnummercommando
%              {\footnotenumber\domovednote\v!volgendepagina\v!vorigepagina}}%
{\preparednumber\domovednote\v!volgendepagina\v!vorigepagina}}%
              [\s!fnt:f:\internalfootreference]%
          \else
            \@@vnnummercommando
%              {\footnotenumber\domovednote\v!volgendepagina\v!vorigepagina}%
{\preparednumber\domovednote\v!volgendepagina\v!vorigepagina}%
          \fi
        \fi
        \iflocation
          \rawreference\s!fnt{\s!fnt:t:\internalfootreference}{}%
        \else\ifconditional\pagewisefootnotes
          \rawreference\s!fnt{\s!fnt:t:\internalfootreference}{}%
        \fi\fi}%
     \bgroup
     \postponefootnotes
     \aftergroup\dostopfootnote
     \begstrut
     \let\next}

\def\dostopfootnote
  {\endstrut
   \stoppushfootnote
   \egroup
   \egroup
   \kern\footnotesignal\relax} % \relax is needed to honor spaces

\let\lastnotesymbol\empty

\def\dolastnotesymbol%
  {\unskip\unskip
   \ifdim\lastkern=\footnotesignal
     \high{\kern\@@vnafstand}% gets the font right, hack !
   \fi
   \nobreak
   \iflocation
     \naarbox
       {\high{\tx\footnotenumber\domovednote\v!vorigepagina\v!volgendepagina}}%
       [\s!fnt:t:\internalfootreference]%
     \rawreference\s!fnt{\s!fnt:f:\internalfootreference}{}%
   \else
     \high{\tx\footnotenumber\domovednote\v!vorigepagina\v!volgendepagina}%
     \ifconditional\pagewisefootnotes
       \rawreference\s!fnt{\s!fnt:f:\internalfootreference}{}%
     \fi
   \fi
   \global\let\lastnotesymbol\relax}

\let\lastnotesymbol\relax

%D \macros
%D   {note}
%D
%D Refering to a note is accomplished by the rather short
%D command:
%D
%D \showsetup{\y!note}
%D
%D This command is implemented rather straightforward as:

\definecomplexorsimple\note

\def\complexnote[#1]%
  {\iffootnotesenabled
     \ifx\lastnotesymbol\relax
       \bgroup
       \unskip
       \naarbox{\high{\tx\currenttextreference}}[#1]%
       \egroup
     \else
       \lastnotesymbol
     \fi
   \fi}

\def\simplenote%
  {\lastnotesymbol}

%D Normally footnotes are saved as inserts that are called upon
%D as soon as the pagebody is constructed. The footnote
%D insertion routine looks just like the \PLAIN\ \TEX\ one,
%D except that we check for the end note state.

\let\startpopfootnotes = \relax
\let\stoppopfootnotes  = \relax

\def\placefootnoteinserts
  {%\ifvoid\footins \else % unsafe, strange
   \ifdim\ht\footins>\zeropoint
     \ifendnotes \else
       \@@vnvoor
       \dofootnoterule  % alleen in ..mode
       \bgroup
       \setfootnotebodyfont
       \setbox0\hbox
         {\startpopfootnotes
          \setfootnotebodyfont
%          % this should be checked, smells like a mix-up
%          % does not split: \ifcase\@@vnn\unvbox\else\box\fi\footins
%          \ifcase\@@vnn
            \box\footins
%          \else
%            \unvbox\footins
%          \fi
          % this is too ugly actually
          \stoppopfootnotes}%
       \localframed
         [\??vn]
         [\c!breedte=\v!passend,
          \c!hoogte=\v!passend,
          \c!strut=\v!nee,
          \c!offset=\v!overlay]
         {\ifdim\dp0=\zeropoint            % this hack is needed because \vadjust
            \hbox{\lower\strutdp\box0}% % in margin number placement
          \else                             % hides the (always) present depth
            \box0
          \fi}%
       \egroup
       \@@vnna
     \fi
   \fi}

%D Supporting end notes is surprisingly easy. Even better, we
%D can combine this feature with solving the common \TEX\
%D problem of disappearing inserts when they're called for in
%D deeply nested boxes. The general case looks like:
%D
%D \starttypen
%D \postponefootnotes
%D \.box{whatever we want with footnotes}
%D \flushnotes
%D \stoptypen
%D
%D This alternative can be used in headings, captions, tables
%D etc. The latter one sometimes calls for notes local to
%D the table, which can be realized by saying
%D
%D \starttypen
%D \setlocalfootnotes
%D some kind of table with local footnotes
%D \placelocalfootnotes
%D \stoptypen
%D
%D Postponing is accomplished by simply redefining the (local)
%D insert operation. A not too robust method uses the
%D \type{\insert} primitive when possible. This method fails in
%D situations where it's not entirely clear in what mode \TEX\
%D is. Therefore the auto method can is to be overruled when
%D needed.

\newbox\postponedfootnotes

\def\autopostponefootnotes
  {\def\localfootinsert % not global 
     {\ifinner
        %\message{[postponed footnote]}%
        \global\setbox\postponedfootnotes\vbox\bgroup
          \ifvoid\postponedfootnotes\else
            \unvbox\postponedfootnotes
          \fi
          \expandafter\gobbletwoarguments
      \else
        %\message{[inserted footnote]}%
        \expandafter\insert
      \fi}}

\def\postponefootnotes
  {\let\autopostponefootnotes\postponefootnotes
   \let\postponefootnotes\relax % prevent loops
   \def\localfootinsert % not global 
     {%\message{[postponed footnote]}%
      \global\setbox\postponedfootnotes=\vbox\bgroup
        \unvbox\postponedfootnotes
        \gobbletwoarguments}}

\def\doflushnotes % also called directly, \ifvoid is needed !
  {\ifendnotes \else
     \ifvoid\postponedfootnotes
       \let\localfootinsert\insert % not global 
     \else
       \bgroup
         \ifdim\ht\postponedfootnotes>\zeropoint
           \scratchdimen\pagegoal
           \advance\scratchdimen -\pagetotal
           \ifdim\scratchdimen<\ht\postponedfootnotes
             \message{[moved footnote]}%
           \fi
         \fi
       \egroup
       \let\localfootinsert\insert % not global
       \insert\footins\bgroup\unvbox\postponedfootnotes\egroup
     \fi
   \fi}

\def\flushnotes
  {\ifvoid\postponedfootnotes \else
     \ifinner \else
       \ifendnotes \else
         \ifinpagebody \else
           %\ifvmode % less interference, but also less secure
              \doflushnotes
           %\fi
         \fi
       \fi
     \fi
   \fi}

%D This is a nasty and new secondary footnote flusher. It
%D can be hooked into \type {\everypar} like:
%D
%D \starttypen
%D \appendtoks \synchronizenotes \to \everypar
%D \stoptypen

\def\dosynchronizenotes
  {\insert\footins{\unvbox\footins}}

\def\synchronizenotes% indirect because of everypar
  {\ifvoid\footins\else\dosynchronizenotes\fi}

\def\placefootnotesintext#1%
  {\ifdim\ht#1>\zeropoint
     \endgraf
     \ifvmode
       \witruimte
       \@@vnvoor
     \fi
     \snaptogrid\hbox
       {\setfootnotebodyfont
        \setbox0\hbox
          {\startpopfootnotes
           \unvbox#1\endgraf\relax
           \stoppopfootnotes}%
        \doif\@@vnbreedte\v!passend % new, auto width
          {\setbox0\hbox            % uggly but ok.
             {\beginofshapebox
              \unhbox0\setbox0=\lastbox\unvbox0
              \endofshapebox
              \reshapebox{\hbox{\unhbox\shapebox}}%
              \vbox{\flushshapebox}}}%
        \localframed
          [\??vn]
          [\c!breedte=\v!passend,
            \c!hoogte=\v!passend,
             \c!strut=\v!nee,
            \c!offset=\v!overlay]
          {\ifdim\dp0=\zeropoint   % this hack is needed because \vadjust
             \hbox{\lower\strutdp\box0}% % in margin number placement
           \else                   % hides the (always) present depth
             \box0
           \fi}}%
     \ifvmode
       \@@vnna
     \fi
   \fi}

%D A stupid alternative is also provided:
%D
%D \starttypen
%D \setupfootnotes[location={text,none}]
%D \stoptypen

\def\placefootnotesasnone#1% is grouped already
  {\ifdim\ht#1>\zeropoint
     \@@vnvoor
     \setfootnotebodyfont
     \startpopfootnotes % make sure that fake height is killed
     \unvbox#1\endgraf
     \stoppopfootnotes
     \setbox0=\lastbox \ifvbox0 \unvbox0\else\box0\fi % enable columns
     \@@vnna
   \fi}

%D \macros
%D   {startlocalfootnotes,placelocalfootnotes}
%D
%D The next two macros can be used in for instance tables, as
%D we'll demonstrate later on.
%D
%D \showsetup{\y!startlocalfootnotes}
%D \showsetup{\y!placelocalfootnotes}

\def\defaultfootnotewidth{\zetbreedte}

\newbox\localpostponedfootnotes

\def\collectlocalfootnotes%
  {\def\localfootinsert##1% was \gdef, but never reset!
     {%\message{[local footnote]}%
      \global\setbox\localpostponedfootnotes\vbox\bgroup
        \ifvoid\localpostponedfootnotes \else
          \unvbox\localpostponedfootnotes
        \fi
        \let\next}}

\def\dostartlocalfootnotes[#1]%
  {\let\autopostponefootnotes\postponefootnotes
   \let\postponefootnotes\collectlocalfootnotes
   \def\defaultfootnotewidth
     {\ifdim\hsize<\zetbreedte\hsize\else\zetbreedte\fi}%
   \setupfootnotes[#1]%
   \savenumber[\v!voetnoot]%
   \resetnummer[\v!voetnoot]%
   \collectlocalfootnotes}

\def\startlocalfootnotes
  {\bgroup % here because we support \vbox\startlocalfootnotes
   \dosingleempty\dostartlocalfootnotes}

\def\stoplocalfootnotes
  {\restorenumber[\v!voetnoot]%
   \egroup
   \checknotes} % really needed, else wrong main settings

\def\doplacelocalfootnotes[#1]%
  {\bgroup
   \setupfootnotes[#1]%
   \ExpandBothAfter\doifinsetelse\v!geen\@@vnplaats
     {\placefootnotesasnone\localpostponedfootnotes}%
     {\placefootnotesintext\localpostponedfootnotes}%
   \egroup
   \checknotes}

\def\placelocalfootnotes
  {\dosingleempty\doplacelocalfootnotes}

%D These commands can be used like:
%D
%D \startbuffer
%D \startlocalfootnotes[breedte=.3\hsize,n=0]
%D   \plaatstabel
%D     {Some Table}
%D     \plaatsonderelkaar
%D       {\starttabel[|l|r|]
%D        \HL
%D        \VL Nota\voetnoot{Bene} \VL Bene\voetnoot{Nota} \VL\SR
%D        \VL Bene\voetnoot{Nota} \VL Nota\voetnoot{Bene} \VL\SR
%D        \HL
%D        \stoptabel}
%D       {\placelocalfootnotes}
%D \stoplocalfootnotes
%D \stopbuffer
%D
%D \typebuffer
%D
%D Because this table placement macro expect box content, and
%D thanks to the grouping of the local footnotes, we don't need
%D additional braces.
%D
%D \haalbuffer

%D \macros
%D   {placefootnotes, fakefootnotes}
%D
%D We still have no decent command for placing footnotes
%D somewhere else than at the bottom of the page (for which no
%D user action is needed). Footnotes (endnotes) can be
%D placed by using
%D
%D \showsetup{\y!placefootnotes}

\def\placefootnotes
  {\dosingleempty\doplacefootnotes}

\def\doplacefootnotes[#1]%
  {\bgroup
   \ifendnotes
     \ifinpagebody \else \ifdim\ht\postponedfootnotes>\zeropoint
       \iffirstargument\setupfootnotes[#1,\c!hoogte=\teksthoogte]\fi
       \ExpandBothAfter\doifinsetelse\v!geen\@@vnplaats
         \placefootnotesasnone\placefootnotesintext\postponedfootnotes
     \fi \fi
   \else \ifdim\ht\footins>\zeropoint
     \iffirstargument\setupfootnotes[#1,\c!hoogte=\teksthoogte]\fi
     \placefootnoteinserts
   \fi \fi
   \egroup}

\def\fakefootnotes
  {\ifhmode \endgraf \fi
   \ifvmode
     \calculatetotalnoteheight
     \ifdim\totalnoteheight>\zeropoint \kern\totalnoteheight \fi
   \fi}

\def\placebottomnotes{\placefootnotes}

\newdimen\totalnoteheight

\def\calculatetotalnoteheight
  {\totalnoteheight\zeropoint
   \ifdim\ht\footins>\zeropoint
     \advance\totalnoteheight\ht\footins
     \advance\totalnoteheight\skip\footins
   \fi}

\newif\ifnotespresent % global ?

\def\checknotepresence
  {\ifdim\ht\footins>\zeropoint
     \notespresenttrue
   \else
     \notespresentfalse
   \fi}

%D Now how can this mechanism be hooked into \CONTEXT\ without
%D explictly postponing footnotes? The solution turned out to
%D be rather simple:
%D
%D \starttypen
%D \everypar  {...\flushnotes...}
%D \neverypar {...\postponefootnoes}
%D \stoptypen
%D
%D and
%D
%D \starttypen
%D \def\ejectinsert%
%D   {...
%D    \flushnotes
%D    ...}
%D \stoptypen
%D
%D We can use \type{\neverypar} because in most commands
%D sensitive to footnote gobbling we disable \type{\everypar}
%D in favor for \type{\neverypar}. In fact, this footnote
%D implementation is the first to use this scheme.

%D When typesetting footnotes, we have to return to the
%D footnote specific bodyfont size, which is in most cases derived
%D from the global document bodyfont size. In the previous macros
%D we already used a footnote specific font setting macro.

\def\setfootnotebodyfont
  {\let\setfootnotebodyfont\relax
   \restoreglobalbodyfont
   \switchtobodyfont[\@@vnkorps]%
   \setuptolerance[\@@vntolerantie]%
   \setupalign[\@@vnuitlijnen]}

%D The footnote mechanism defaults to a traditional one
%D column way of showing them. By default we precede them by
%D a small line.

\setupfootnotes
  [\c!plaats=\v!pagina,
   \c!wijze=\v!per\v!deel,
   \c!sectienummer=\v!nee,
   \c!conversie=,
   \c!lijn=\v!aan,
   \c!voor=\blanko,
   \c!korps=\v!klein,
   \c!letter=,
   \c!kleur=,
   \c!na=,
   \c!lijnkleur=,
   \c!lijndikte=\linewidth,
   \c!kader=\v!uit,
   \c!margeafstand=.5em,
   \c!kolomafstand=1em,
   \c!afstand=.125em,
   \c!uitlijnen=\v!normaal,
   \c!tolerantie=\v!soepel,
   \c!splitsen=\v!soepel,
  %\c!breedte=\zetbreedte,
  %\c!breedte=\ifdim\hsize<\zetbreedte\hsize\else\zetbreedte\fi,
   \c!breedte=\defaultfootnotewidth,
   \c!hoogte=\teksthoogte,
   \c!nummercommando=\high,
   \c!scheider=\@@koscheider,
   \c!n=1]

\protect \endinput
