%D \module
%D   [       file=cont-new,
%D        version=1995.10.10,
%D          title=\CONTEXT\ Miscellaneous Macros,
%D       subtitle=New Macros,
%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.

%D This file is loaded at runtime, thereby providing an
%D excellent place for hacks, patches, extensions and new
%D features.

\unprotect

\newbox\nestednextbox \prependtoks \let\nextbox\nestednextbox \to \everybeforepagebody

\def\dostartcolumnsetspan[#1][#2][#3]% [#3] gobbles space
  {\endgraf % else rubish output if forgotten
   \vskip \zeropoint % make sure otr is done, otherwise last line problems
   \bgroup
   \forgetall
   \ifnum\columnsetlevel>\zerocount\else
     % of course we needed a one-column fall back for tm
     \columnsetspanhsize\hsize
     \nofcolumns\plusone
     \mofcolumns\plusone
   \fi
   \setupframedtexts[cs:#1]
     [\c!breedte=\columnsetspanhsize,
      \c!regelcorrectie=\v!uit,
      \c!dieptecorrectie=\v!uit,
      #2]%
   % determine widths
   \!!countc\framedtextparameter{cs:#1}\c!n
    % \!!countd\numexpr(\nofcolumns-\mofcolumns+\plusone)%
   \!!countd\nofcolumns
   % n <= n of columns
   \ifnum\!!countc>\!!countd \!!countc\!!countd \fi
   \advance\!!countd -\mofcolumns
   \advance\!!countd \plusone
   % n <= n of available columns (alternative a)
   \doif{\framedtextparameter{cs:#1}\c!variant}\v!a
     {\ifnum\!!countc>\!!countd \!!countc\!!countd \fi}%
   % here it all starts
   \setcolumnsetspanhsize\mofcolumns\!!countc % a/b used
   \hsize\columnsetspanhsize
   \setbox\scratchbox\vbox\bgroup
     \dostartframedtext[cs:#1][\v!geen]% geen nils placement
     \vskip-\struttotal\par\verticalstrut\par
     \ifnum\columnsetlevel>\zerocount
       \framedtextparameter{cs:#1}\c!voor
     \fi
     \def\stopcolumnsetspan{\dostopcolumnsetspan{#1}}}

\def\dostopcolumnsetspan#1%
  {\par
   \verticalstrut
   \kern-2\struttotal
   \verticalstrut
   \ifnum\columnsetlevel>\zerocount
     \doifsomething{\framedtextparameter{cs:#1}\c!na}
       {\framedtextparameter{cs:#1}\c!na
        \kern\zeropoint}% otherwise blanks disappear, better be a switch
   \else
     \endgraf
   \fi
   \dostopframedtext
   \egroup
   % frozen keeps grid snapping okay
   \setbox\scratchbox\frozenhbox to \hsize
     {\dontcomplain
      \alignedline{\framedtextparameter{cs:#1}\c!plaats}\v!midden
        {\lower\strutdepth\box\scratchbox}}%
   \dp\scratchbox\zeropoint % else wrong snap insidefloat
%
% to be tested first:
%
% \setbox\scratchbox\frozenhbox to \hsize
%   {\dontcomplain
%    \chardef\alignstrutmode\zerocount
%    \alignedline{\framedtextparameter{cs:#1}\c!plaats}\v!midden
%      {\box\scratchbox}}%
%
   \ifinsidefloat
     \box\scratchbox
   \else\ifnum\columnsetlevel>\zerocount
     % we only set \columnsetspacing when asked for, else bottom problems
     % don't change this any more (test naw)
     \chardef\columnslotspacing\framedtextparameter{cs:#1}\c!nregels\relax
     % todo: nboven/onder & \chardef\columnslotlocation2
     %\OTRSETstoreincolumnslotHERE\scratchbox
     \edef\floatmethod{\framedtextparameter{cs:#1}\c!default}%
     \@EA\uppercasestring\floatmethod\to\floatmethod
     % todo : \v!hier -> here enzovoorts
     \OTRSETstoreincolumnslot\floatmethod\scratchbox
     % watch out: no \dochecknextindentation{tag}
     \checknextindentation[\framedtextparameter{cs:#1}\c!springvolgendein]
   \else
     % of course we needed a one-column fall back for tm; brrr, the box has now too
     % much height (try \ruledvbox); don't change this without testing techniek
     \scratchdimen\ht\scratchbox
     \advance\scratchdimen-\strutdp
     \ht\scratchbox\scratchdimen
     \framedtextparameter{cs:#1}\c!voor
     \snaptogrid\vbox{\box\scratchbox}%
     \framedtextparameter{cs:#1}\c!na
   \fi\fi
   \egroup
   \endgraf}

% will be a MyWay
%
% \setuplayout[grid=yes] \setupcaption[figure][inbetween=] \useMPlibrary[dum] \setupcolors[state=start]
%
% \starttext \showgrid \showstruts
%
% \input ward \placefigure{}{\externalfigure[dummy][width=.5\hsize,lines=1.4,grid=yes]}
% \input ward \placefigure{}{\externalfigure[dummy][width=.5\hsize,lines=1.4,grid=fit]}
% \input ward \placefigure{}{\externalfigure[dummy][width=.5\hsize,lines=1.4,grid=height]}
% \input ward
% \page
% \input ward \placefigure{}{\externalfigure[dummy][width=.5\hsize,lines=1.5,grid=yes]}
% \input ward \placefigure{}{\externalfigure[dummy][width=.5\hsize,lines=1.5,grid=fit]}
% \input ward \placefigure{}{\externalfigure[dummy][width=.5\hsize,lines=1.5,grid=height]}
% \input ward
% \page
% \input ward \placefigure{}{\externalfigure[dummy][width=.5\hsize,lines=1.6,grid=yes]}
% \input ward \placefigure{}{\externalfigure[dummy][width=.5\hsize,lines=1.6,grid=fit]}
% \input ward \placefigure{}{\externalfigure[dummy][width=.5\hsize,lines=1.6,grid=height]}
% \input ward
% \page
% \input ward \placefigure[none]{}{\externalfigure[dummy][width=.5\hsize,lines=1.4,grid=yes]}
% \input ward \placefigure[none]{}{\externalfigure[dummy][width=.5\hsize,lines=1.4,grid=fit]}
% \input ward \placefigure[none]{}{\externalfigure[dummy][width=.5\hsize,lines=1.4,grid=height]}
% \input ward
% \page
% \input ward \placefigure[none]{}{\externalfigure[dummy][width=.5\hsize,lines=1.5,grid=yes]}
% \input ward \placefigure[none]{}{\externalfigure[dummy][width=.5\hsize,lines=1.5,grid=fit]}
% \input ward \placefigure[none]{}{\externalfigure[dummy][width=.5\hsize,lines=1.5,grid=height]}
% \input ward
% \page
% \input ward \placefigure[none]{}{\externalfigure[dummy][width=.5\hsize,lines=1.6,grid=yes]}
% \input ward \placefigure[none]{}{\externalfigure[dummy][width=.5\hsize,lines=1.6,grid=fit]}
% \input ward \placefigure[none]{}{\externalfigure[dummy][width=.5\hsize,lines=1.6,grid=height]}
% \input ward
%
% \stoptext

\let\@@efgrid\empty

\def\dosetdimensionfiguresize#1#2#3%
  {#1\relax
   \doifsomething\@@efmaxbreedte
     {\ifdim\figwid>\@@efmaxbreedte\global\figwid\@@efmaxbreedte#2\relax\fi}%
   \doifsomething\@@efmaxhoogte
     {\ifdim\fighei>\@@efmaxhoogte \global\fighei\@@efmaxhoogte #3\relax\fi}%
   \processaction
     [\@@efgrid]
     [     \v!ja=>\getnoflines\fighei
                  \global\fighei\noflines\lineheight,
       \v!hoogte=>\getrawnoflines\fighei
                  \global\fighei\noflines\lineheight
                  \global\advance\fighei\strutdepth,
      \v!passend=>\getrawnoflines\fighei
                  \global\fighei\noflines\lineheight]}

\def\splittblbox#1% #1 <> 0/2
  {\ifinsidefloat
     \unvbox#1%
   \else
     % spacing between rows gets lost in split
     \setbox4\vbox
       {\doifsomething\tbltbltussenwit{\blank[\tbltbltussenwit]}}%
     \setbox2\vbox
       {}%
     \dorecurse\noftblheadlines
       {\setbox0\vsplit#1 to \lineheight
        \setbox2\vbox{\unvcopy2\unvcopy0}}%
     \ifcase\noftblheadlines\else\unvcopy2\fi
     \donefalse
     \doloop
       {\setbox0\vsplit#1 to \lineheight
        \ifdim\pagegoal<\maxdimen
          \setbox0\vbox{\unvbox0}%
          \dimen0\ht0
          \advance\dimen0\ht4
          \advance\dimen0\pagetotal
          \ifdim\dimen0>\pagegoal
            \bgroup \pagina \egroup % make sure that local vars are kept
            \ifcase\noftblheadlines\else\unvcopy2\fi
          \fi
        \fi
        \ifdone
          \doifsomething\tbltbltussenwit{\blank[\tbltbltussenwit]}%
        \fi
        \unvbox0
        %\allowbreak
        \bgroup
          \scratchcounter\recurselevel
          \advance\scratchcounter\noftblheadlines
          \setupTBLcell{\number\scratchcounter}1
          \ifx\@@tblsplitafter\relax
            \allowbreak
          \else
            \doifelsenothing\@@tblsplitafter
               \allowbreak
              {\scratchcounter\realpageno
               \@@tblsplitafter
               \ifnum\scratchcounter<\realpageno
                 \ifcase\noftblheadlines\else\unvcopy2\fi
               \fi}%
          \fi
        \egroup
        \ifvoid#1 \exitloop \else \donetrue \fi}%
   \fi}

% \bTABLE[split=repeat]
%   \bTABLEhead
%     \bTR \bTH lxxxeft \eTH\bTD right \eTD\eTR
%   \eTABLEhead
%   \bTABLEbody
%     \dorecurse{100}{\bTR[after={\pagina[bigpreference]}] \bTD left \eTD\bTD right \eTD\eTR}
%     \dorecurse{100}{\bTR\bTD left \eTD\bTD right \eTD\eTR}
%   \eTABLEbody
% \eTABLE

% new, continuous blocks, \som \par \startdoorlopendblok ...

\def\startdoorlopendblok % fo rspecial cases, don't change it too much
  {\ifhmode\endgraf\nobreak\fi % don't remove the \nobreak
   \dowithnextboxcontent
     {\setlocalhsize \hsize\localhsize \forgetall}
     {\bgroup
      \forgeteverypar
      \forgetparskip
      \scratchdimen\nextboxht
      \advance\scratchdimen\nextboxdp
      \getnoflines\scratchdimen
      \advance\scratchdimen-\strutheight
      \setbox\nextbox\hbox{\lower\scratchdimen\box\nextbox}%
      \ht\nextbox\strutheight
      \dp\nextbox\strutdepth
\setbox\nextbox\vbox
  {\indent\box\nextbox
   \endgraf
   \nobreak
   \advance\noflines\minusone
   \dorecurse\noflines{\crlf\nobreak}}%
\verticalstrut
\endgraf
\nobreak
\offinterlineskip
\kern-2\lineheight
\nobreak
\unvbox\nextbox
      \prevdepth\strutdepth
      % evt (eerst testen) een signal zodat een direct volgend blok goed gaat)
      \egroup}
     \vbox\bgroup
       \insidefloattrue
       \inhibitblank}

\def\stopdoorlopendblok
  {\egroup}

\def\disablelanguagespecifics{\def\installcompoundcharacter##1 ##2{}}

\appendtoks
  \disablelanguagespecifics
\to \everyenableXML

\installoutput\discardpage
  {\setbox\scratchbox\box\normalpagebox}

\unexpanded\def\referencepagenumber[#1]%
  {\doifelsenothing{#1}{?}% \prepare had got lost
     {\preparepaginaprefix\??rf\paginaprefix\??rf[#1]\translatednumber[#1]}}

\def\defineXMLstore {\doquadrupleargument\dodefineXMLstore[\saveXMLasdata]}
\def\defineXMLgstore{\doquadrupleargument\dodefineXMLstore[\gsaveXMLasdata]}

\def\dodefineXMLstore[#1][#2][#3][#4]% element attribute prefix % will become faster
  {\defineXMLargument[#2][#3=\s!dummy]{#1{#4:\XMLop{#3}}}}

\def\OTRONEsometopsfloat[#1]%
  {\ifdim\topinserted=\zeropoint
     \topofinserttrue
   \else
     \topofinsertfalse
   \fi
   \global\advance\topinserted \ht\floatbox
   \global\advance\topinserted \dp\floatbox
   \global\advance\topinserted \floatbottomskip
   \insert\topins
     {\forgetall
      \iftopofinsert
        \topskipcorrection % [xx] new: see icare topbleed
        \kern-\lineskip\par\prevdepth\maxdimen
      \else
        %\blanko[-\@@bknawit,\@@bkvoorwit]% inserts can't look back
        \betweenfloatblanko
      \fi
      \flushfloatbox
      \blanko[\@@bknawit]}%
   \doinsertfloatinfo}

\def\OTRONEdotopinsertions
  {\ifvoid\topins\else
     \ifgridsnapping
       \box\topins
       \vskip-\topskip \vskip\strutheight % [xx] new: see icare topbleed
     \else
       \unvbox\topins
     \fi
   \fi
   \global\topinserted\zeropoint}


\def\tightlayer[#1]%
  {\hbox
     {\def\currentlayer{#1}% todo: left/right
      \hsize\layerparameter\c!breedte
      \vsize\layerparameter\c!hoogte
      \composedlayer{#1}}}

\def\dodosetobject#1#2#3%
  {\bgroup
   \globalpushmacro\crossreferenceobject \objectreferenced
   \inobjecttrue
   \dowithnextbox
     {\globalpopmacro\crossreferenceobject
      \dododosetobject{#1}{#2}{#3}\egroup}}

% Just a simple and fast hanger, for usage in macros.

\def\setuphanging
  {\dodoubleempty\getparameters[\??ha]}

\setuphanging
  [\c!afstand=.5em]

\def\starthanging
  {\noindent\bgroup
   \dowithnextbox
     {\setbox\nextbox\hbox{\flushnextbox\hskip\@@haafstand}%
      \hangindent\nextboxwd
      \hangafter\plusone
      \flushnextbox\ignorespaces}
   \hbox}

\def\stophanging
  {\endgraf
   \egroup}

\def\doifdimensionelse#1%
  {\afterassignment\dodoifdimensionelse\scratchdimen#1pt\relax}

\def\dodoifdimensionelse#1%
  {\ifx#1\relax
     \expandafter\secondoftwoarguments
   \else % #1=p ... t\relax
     \expandafter\thirdoffourarguments
   \fi}

\def\definepushbutton % name optional setup
  {\dodoubleempty\dodefinepushbutton}

\def\dodefinepushbutton[#1][#2]% name setup
  {\dododefinepushbutton{#1}{n}{push}%
   \dododefinepushbutton{#1}{r}{\symbol[psym:#1:n]}%
   \dododefinepushbutton{#1}{d}{\symbol[psym:#1:r]}%
   \setvalue{pushbutton:#1}{\dohandlepushbutton{#1}{#2}}}

\def\dododefinepushbutton#1#2#3%
  {\doifsymboldefinedelse{psym:#1:#2}%
     \donothing{\definesymbol[psym:#1:#2][{#3}]}}

\def\definepushsymbol
  {\dotripleargument\dodefinepushsymbol}

\def\dodefinepushsymbol[#1][#2]% [#3]
  {\definesymbol[psym:#1:#2]}

\def\dopushbutton[#1][#2]%
  {\executeifdefined{pushbutton:#1}\gobbleoneargument{#2}}

\def\pushbutton
  {\dodoubleargument\dopushbutton}

\def\dohandlepushbutton#1#2#3% identifier setup script
  {\bgroup
   \nextsystemfield
   \setupfield
     [pushbutton]
     [\c!kader=\v!overlay,
      \c!offset=\v!overlay,
      \c!klikuit=#3,#2]%
   \definefield
     [\currentsystemfield]
     [push]
     [pushbutton]
     [psym:#1:n,psym:#1:r,psym:#1:d]%
   \fitfield
     [\currentsystemfield]%
   \egroup}

% \def\do@@ampsh
%   {\dodoubleargument\dodo@@ampsh}
%
% \def\dodo@@ampsh[#1][#2]#3\\%
%   {\txt\pushbutton[#1][#2]\\}%
%
%\appendtoks \let\psh\do@@ampsh \to \everysetmenucommands

\def\@@ampsh{\txt\pushbutton}

\appendtoks \let\psh\@@ampsh \to \everysetmenucommands

% \definepushbutton [reset]
%
% \definepushsymbol [reset] [n] [\uniqueMPgraphic{whatever}{color=green}]
% \definepushsymbol [reset] [r] [\uniqueMPgraphic{whatever}{color=white}]
%
% \startinteractionmenu[bottom]
%   \psh [reset] [JS(reset_something)] \\
% \stopinteractionmenu

\def\tabulaterule % to be redone, not correct
  {\dotabulaterule
     {\hrule\!!height.5\scratchdimen\!!depth.5\scratchdimen\relax
      \doifvalue{\??tt\currenttabulate\c!afstand}\v!grid
        {\kern-\scratchdimen}}} % experimental tm-prikkels

% todo: \setupinterlinespace[\c!regel=\v!vast] => ==\the\baselineskip

%%%%%%%% todo: \chardef\snapstruts=1 => d=l-h

\writestatus{\m!systems}{beware: some patches loaded from cont-new.tex!}

\def\useMPvariables
  {\dodoubleargument\douseMPvariables}

\def\douseMPvariables[#1][#2]%
  {\def\@@meta{#1:}%
   \prepareMPvariables{#2}}

\def\countXMLchildren[#1]#2%
  {\startnointerference
     \doglobal\newcounter\nofXMLchildren
     \defineXMLargument[#1]{\doglobal\increment\nofXMLchildren}%
     \startXMLignore
       #2%
     \stopXMLignore
   \stopnointerference}

\def\processlinetableXMLfile#1%
  {\bgroup
   \let\startlinetable\donothing
   \let\stoplinetable \donothing
   \startlinetableanalysis\processXMLfile{#1}\stoplinetableanalysis
   \startlinetablerun     \processXMLfile{#1}\stoplinetablerun
   \egroup}

\def\startlinetablepart
  {\global\linetablesubcol\zerocount
   \setbox\scratchbox\hbox\bgroup
   \doconvertfont{\linetablerparameter\c!letter}%
   \startcolor[\linetablerparameter\c!kleur]%
   \ignorespaces}

\def\stoplinetablepart
  {\ifnum\linetablepart>\zerocount
     \unskip \unskip % remove last intercolumn skip (distance+fill)
   \fi
   \stopcolor
   \egroup
   \iflinetablepreroll \else
     \ifcase\linetablepart
       % we're collecting the repeater
     \else
       \scratchdimen\hsize \advance\scratchdimen-\wd\scratchbox\relax
       \ifdim\scratchdimen>\linetableparameter\c!rek\else
         \setbox\scratchbox\hbox to \hsize{\unhbox\scratchbox}%
       \fi
     \fi
   \fi}

% experimental: \synchronizegrid bla bla bla

\newcounter\currentgridsync

\def\gridsynctag{grs:\currentgridsync}

\def\synchronizegrid
  {\doglobal\increment\currentgridsync
   \par\prevdepth\zeropoint
   \nointerlineskip
   \hpos\gridsynctag{\strut}\par
   \vskip-\lineheight
   \nointerlineskip
   % top of text
   \scratchdimen\MPy{\v!tekst:\MPp\gridsynctag}%
   \advance\scratchdimen\MPh{\v!tekst:\MPp\gridsynctag}%
   % move to first baseline
   \advance\scratchdimen-\topskip
   % subtract wrong baseline
   \advance\scratchdimen-\MPy\gridsynctag
   % get minimal number of lines
   \advance\scratchdimen\lineheight
   \getnoflines\scratchdimen
   % calculate difference
   \advance\scratchdimen-\noflines\lineheight\relax
   \scratchdimen-\scratchdimen\relax
   \ifdim\scratchdimen>\zeropoint
     \nointerlineskip
     \advance\scratchdimen-\lineheight
     \vskip\scratchdimen \dontleavehmode \quad \strut
     \par
  %\else
  %  \message{no grid correction: \the\scratchdimen}\wait
   \fi}

% needed for extreme

\definesystemvariable{ie}

% \def\definetest[#1]#2%
%   {\long\setvalue{\??ie#1}{#2}}

\def\definetest
  {\dodoubleempty\dodefinetest}

\def\dodefinetest[#1][#2]#3%
  {\setgvalue{\??ie#1}{#3}%
   \ifsecondargument
      \processaction
        [#2]
        [% first test true, rest depends
         \v!volgende=>\setgvalue{\??ie#1}{\setgvalue{\??ie#1}{#3}\firstoftwoarguments},
         % rest true if first true
         % \v!eerste=>\setgvalue{\??ie#1}{#3{\letgvalue{\??ie#1}%
         %              \firstoftwoarguments\firstoftwoarguments}%
         %              \secondoftwoarguments},
         % always true
               \v!ja=>\letgvalue{\??ie#1}\firstoftwoarguments,
         % always false
              \v!nee=>\letgvalue{\??ie#1}\secondoftwoarguments]%
   \fi}

\def\doperformtest#1%
  {\executeifdefined{\??ie#1}\secondoftwoarguments}

\def\definecolumnsethsize#1#2#3#4% will be improved/speed up
  {\bgroup
   \def\OTRSETidentifier{#1}%
   \ifcase\columnsetlevel\relax
     \mofcolumns\plusone
     \OTRSETinitializecolumns
     \OTRSETassignwidths
     \OTRSETsethsize
   \fi
   \!!counta#2\!!countb#3\docalculatecolumnsetspan
   \expandafter\egroup\expandafter\edef\expandafter
     #4\expandafter{\the\!!widtha}}

% so far

% test this prikkels/pascal margin text before heads (mode
% 1) as well as uitwerkingen (mode 2)

%chardef\graphicvadjustmode=0 % fake
%chardef\graphicvadjustmode=1 % normal
\chardef\graphicvadjustmode=2 % normal + compensate (== default)

\def\placemargintexts % to be documented and translated
  {\ifcase\margincontent\else
     \bgroup
       \chardef\graphicvadjustmode\zerocount
       \doflushmargincontents
     \egroup
   \fi}

\def\graphicvadjust % bad, those low level color calls here
  {\dowithnextboxcontent
     {\forgetall}
     {\ifcase\graphicvadjustmode \@EA \fakedvadjust \else \@EA\normalvadjust \fi
        {\dostartgraphicgroup
         \localstarttextcolor
         \unvbox\nextbox
         \localstoptextcolor
         \dostopgraphicgroup
         \ifcase\graphicvadjustmode \or \or
           % corrects for one line paragraphs
           \nointerlineskip
           \kern-\struttotal
           \nointerlineskip
           \verticalstrut
         \fi}}%
     \vbox}

\def\removefunnytabulateline
  {\ifhmode
     \strut\crcr
     \TABLEnoalign{\kern-\lineheight}%
   \fi}

\def\showexternalfigured
  {\bgroup
   \immediate\openout\scratchwrite=mpfigs.mp
   \def\presetfigure[##1][##2]%
     {\getfiguredimensionsonly[##1]% \pagefigure[##1]%
      \immediate\write\scratchwrite
         {registerfigure("##1",\figurewidth,\figureheight)}}
   \pushendofline
   \readjobfile\@@exfile\donothing\donothing
   \popendofline
   \immediate\closeout\scratchwrite
   \egroup}

% between alignment lines certain rules apply, and even a
% simple test can mess up a table, which is why we have a
% special test facility
%
% \ruledvbox
%   {\starttabulate[|l|p|]
%    \NC 1test \NC test \NC \NR
%    \tableifelse{\doifelse{a}{a}}{\NC Xtest \NC test \NC \NR}{}%
%    \stoptabulate}

\long \def\tableifelse#1%
  {\TABLEnoalign{#1%
     {\aftergroup \firstoftwoarguments}%
     {\aftergroup\secondoftwoarguments}}}

% \long \def\tableif#1% whow, this is real ugly
%   {\TABLEnoalign{\let\gnext\gobbleoneargument#1%
%      {\let\gnext\firstofoneargument}}\gnext}

\long \def\tableiftextelse#1{\tableifelse{\doiftextelse{#1}}}

\def\overloaded#1#2%
  {\appendtoks
     \writestatus\m!systems{overloaded: \string#2}%
   \to \everybye
   #1#2}

\def\expandifnonempty#1%
  {\@EA\ifx\csname#1\endcsname\empty
     \expandafter\secondoftwoarguments
   \else
     \expandafter\firstoftwoarguments
   \fi
   {\csname#1\endcsname}}

\def\@@sectiekoppeling#1%
  {\expandifnonempty{\??ko#1\c!koppeling}{#1}}

\def\@@sectiesectie#1%
  {\expandifnonempty{\??ko#1\c!sectie}{\@@sectiekoppeling{#1}}}

\def\sectioncountervalue#1%
  {\@@sectionvalue{\@@sectiesectie{#1}}}

% todo namespace \@@meta:#1:... ! ! ! ! ! !

\def\presetMPvariable
  {\dodoubleargument\dopresetMPvariable}

\def\dopresetMPvariable[#1][#2=#3]%
  {\doifundefined{#1:#2}{\setvalue{#1:#2}{#3}}}

% experiment, not yet to be used

\def\displaybreak
  {\ifhmode
     \removeunwantedspaces
     \ifcase\raggedstatus\hfill\fi
     \strut\penalty-9999 % \break fails on case (3)
   \fi}

\def\startdisplay{\displaybreak\ignorespaces\startopelkaar}
\def\stopdisplay {\stopopelkaar\displaybreak\ignorespaces}

\def\tightvbox
  {\dowithnextbox{\nextboxdp\zeropoint\flushnextbox}\vbox}

\def\tightvtop
  {\dowithnextbox{\nextboxht\zeropoint\flushnextbox}\vtop}

% pretty important (esp since we now ignore shipouts)
%
% actually we should nil all writes, marks, specials

\appendtoks \globallet\popcolor\relax \to \everylastshipout

\def\incrementvalue#1{\expandafter\increment\csname#1\endcsname}
\def\decrementvalue#1{\expandafter\decrement\csname#1\endcsname}

% \translateMPinput{il2-pl}
%
% \startMPenvironment[global]
%   \setupbodyfont[plr]
% \stopMPenvironment
%
% \TeX: ± ¶
%
% \startMPcode
% draw btex MetaPost: ± ¶ etex scaled 5 ;
% \stopMPcode

% \startcolumnset[two] \input tufte
% \startcolumnsetspan[two] \input tufte \stopcolumnsetspan
% \input tufte \stopcolumnset

% now in cont-loc.tex, for the sake of testing.
%
% %D When \type {\somecolor} is issued, we can savely assume
% %D grouping. Using \type {\groupedcommand} here (i.e.\ the
% %D definition of \type {\color}) is unsafe because in
% %D interferes with for instance switching attributes.
%
% \def\switchtocolor[#1]%
%   {\bgroup\startcolor[#1]
%    \aftergroup\stopcolor
%    \aftergroup\egroup}

% what is this stupid macro meant for:

\def\hyphenationpoint
  {\hskip\zeropoint}

\def\hyphenated#1%
  {\bgroup
   \!!counta\zerocount
   \def\hyphenated##1{\advance\!!counta\plusone}%
   \handletokens#1\with\hyphenated
   \!!countb\plusone
   \def\hyphenated##1%
     {##1%
      \advance\!!countb\plusone\relax
      \ifnum\!!countb>2 \ifnum\!!countb<\!!counta
        \hyphenationpoint
      \fi\fi}%
   \handletokens#1\with\hyphenated
   \egroup}

\def\obeysupersubletters
  {\let\super\normalsuper
   \let\suber\normalsuber
   \let\normalsuper\letterhat
   \let\normalsuber\letterunderscore
   \enablesupersub}

\def\obeysupersubmath
  {\let\normalsuper\letterhat
   \let\normalsuber\letterunderscore
   \enablesupersub}

%\let\normaltype\type
%
%\def\type#1%
%  {\expanded{\normaltype{\detokenize{#1}}}}

% {x123 \os x123} {\tfa x123 \os x123} {x123 \tx x123 \os x123}
% \definefontsynonym[OldStyle][Serif]
% {x123 \os x123} {\tfa x123 \os x123} {x123 \tx x123 \os x123}

% testen :
%
% \appendtoks
%   \let\registerparoptions\relax
% \to \everyforgetall

\def\startgridcorrection
  {\dosingleempty\dostartgridcorrection}

\def\dostartgridcorrection[#1]%
  {\ifgridsnapping
     \iffirstargument\doifsomething{#1}{\verplaatsopgrid[#1]}\fi
     \snaptogrid\vbox\bgroup
   \else
     \startbaselinecorrection
   \fi}

\def\stopgridcorrection
  {\ifgridsnapping
     \egroup
   \else
     \stopbaselinecorrection
   \fi}

\def\checkgridsnapping
  {\lineskip\ifgridsnapping\zeropoint\else\normallineskip\fi}

\def\startplaatsen
  {\dosingleempty\dostartplaatsen}

\def\dostartplaatsen[#1]% tzt n*links etc
  {\endgraf
   \noindent\bgroup
   \setlocalhsize
   \hbox to \localhsize\bgroup
     \doifnot{#1}\v!links\hss
     \def\stopplaatsen
       {\unskip\unskip\unskip
        \doifnot{#1}\v!rechts\hss
        \egroup
        \egroup
        \endgraf}%
     \gobblespacetokens}

% \startplaatsen[links] bla \stopplaatsen

% we don't register the paragraph characteristics, only the
% width

\appendtoks
  \setinnerparpositions % see "techniek" for application
\to \everytabulate

\appendtoks \checkcurrentlayout \to \everystarttext

\def\flushfootnotes  {\flushnotes}
\def\doflushfootnotes{\doflushnotes}

%D This alternative is slower, since it works on top of the
%D color (stack) mechanism, but it does provide nesting.

\def\dosetrastercolor#1%
  {\edef\@@cl@@s{#1}%
   \ifx\@@cl@@s\empty
     \let\@@cl@@s\@@rsraster
   \fi
   \setevalue{\??cr\??rs}{\colorSpattern}}

% beware, don't add extra grouping, else color in tables
% fails

\def\localstartraster[#1]%
  {\ifincolor\dosetrastercolor{#1}\localstartcolor[\??rs]\fi}

\def\startraster[#1]%
  {\ifincolor\dosetrastercolor{#1}\startcolor[\??rs]\fi}

\def\localstopraster{\ifincolor\localstopcolor\fi}
\def\stopraster     {\ifincolor\stopcolor\fi}

\def\fontclassname#1#2%
  {\ifcsname\??ff#1#2\endcsname
     \fontclassname{#1}{\csname\??ff#1#2\endcsname}%
   \else\ifcsname\??ff#2\endcsname
     \fontclassname{#1}{\csname\??ff#2\endcsname}%
   \else
     #2%
   \fi\fi}

\def\defineclassfontsynonym
  {\dotripleargument\dodefineclassfontsynonym}

\def\dodefineclassfontsynonym[#1][#2][#3]%
  {\definefontsynonym[#1][\fontclassname{#2}{#3}]}

%\definefontsynonym [KopFont] [\fontclassname{officina}{SerifBold}]
%
%\defineclassfontsynonym [KopFont] [officina] [SerifBold]

\def\startcolumnmakeup % don't change
  {\bgroup
   \getrawnoflines\teksthoogte % teksthoogte kan topskip hebben, dus raw
   \scratchdimen\noflines\lineheight
   \advance\scratchdimen-\lineheight
   \advance\scratchdimen\topskip
   \setbox\scratchbox
   \ifcase\showgridstate\vbox\else\ruledvbox\fi to \scratchdimen\bgroup
   \forgetall} % ! don't change

\def\stopcolumnmakeup
  {\egroup
   \dp\scratchbox\zeropoint
   \wd\scratchbox\tekstbreedte
   \box\scratchbox
   \egroup
   \synchronizehsize}

% todo : hoe komt box er uit

\long\def\startexternalfigure
  {\dotripleempty\dostartexternalfigure}

\long\def\dostartexternalfigure[#1][#2][#3]#4\stopexternalfigure
  {\gdef\figuredescription{#4}%
   \externalfigure[#1][#2][#3]%
   \globallet\figuredescription\empty}

\let\figuredescription\empty

\newtoks\everyfirstparagraphintro
\newtoks\everynextparagraphintro

\chardef\everyparagraphintro=0

\def\setupparagraphintro
  {\dodoubleempty\dosetupparagraphintro}

\def\dosetupparagraphintro[#1][#2]%
  {\processallactionsinset
     [#1]
     [   \v!reset=>\global\chardef\everyparagraphintro0
                   \global\everyfirstparagraphintro\emptytoks
                   \global\everynextparagraphintro \emptytoks,
        \v!eerste=>\global\chardef\everyparagraphintro1
                   \doglobal\appendtoks#2\to\everyfirstparagraphintro,
      \v!volgende=>\ifcase\everyparagraphintro\global\chardef\everyparagraphintro=2\fi
                   \doglobal\appendtoks#2\to\everynextparagraphintro,
           \v!elk=>\ifcase\everyparagraphintro\global\chardef\everyparagraphintro=2\fi
                   \doglobal\appendtoks#2\to\everyfirstparagraphintro
                   \doglobal\appendtoks#2\to\everynextparagraphintro]}

\def\doinsertparagraphintro
  {\ifcase\everyparagraphintro\relax
     % no data
   \or
     % first data
     \global\chardef\everyparagraphintro2
     \scratchtoks\everyfirstparagraphintro
     \global\everyfirstparagraphintro\emptytoks
   \or
     % next data
     \scratchtoks\everynextparagraphintro
   \fi
   \the\scratchtoks}

\def\insertparagraphintro
  {\ifcase\everyparagraphintro\else\@EA\doinsertparagraphintro\fi}

\appendtoks\insertparagraphintro\to\everypar

%D \starttypen
%D \setupparagraphintro[first][\hbox to 3.5em{\tt FIRST \hss}]
%D \setupparagraphintro[first][\hbox to 3.5em{\tt TSRIF \hss}]
%D \setupparagraphintro[next] [\hbox to 3.5em{\tt NEXT  \hss}]
%D \setupparagraphintro[next] [\hbox to 3.5em{\tt TXEN  \hss}]
%D \setupparagraphintro[each] [\hbox to 3.0em{\tt EACH  \hss}]
%D \setupparagraphintro[each] [\hbox to 3.0em{\tt HCEA  \hss}]
%D
%D some paragraph \par
%D some paragraph \par
%D some paragraph \par
%D
%D \definelabel[parnumber]
%D
%D \setupparagraphintro[reset,each][\inleft{\slxx\parnumber}]
%D
%D some paragraph \par
%D some paragraph \par
%D some paragraph \par
%D \stoptypen

% wrong names

\newif\ifpagechanged \let\lastchangedpage\empty

\def\checkpagechange#1%
  {\gettwopassdata\s!paragraph
   \pagechangedfalse
   \iftwopassdatafound
     \ifnum\twopassdata>0\getvalue{\s!paragraph:p:#1}\relax
       \pagechangedtrue
     \fi
   \fi
   \ifpagechanged
     \letgvalue{\s!paragraph:p:#1}\twopassdata
     \globallet\lastchangedpage\twopassdata
   \else
     \globallet\lastchangedpage\realfolio
   \fi
   \doparagraphreference}

\def\changedpage#1%
  {\getvalue{\s!paragraph:p:#1}}

% incomplete, will be a special case of float placement

\def\startfixed{\dosingleempty\dostartfixed}

\long\def\dostartfixed[#1]%
  {\expanded{\dowithnextbox{\noexpand\dodofixed{\ifhmode0\else1\fi}{#1}}}%
   \vbox\bgroup
   \setlocalhsize}

\def\stopfixed
  {\egroup}

\def\dodofixed#1#2%
  {\ifcase#1\relax
     \processaction
       [#2]
       [   \v!hoog=>\bbox   {\flushnextbox},
           \v!laag=>\tbox   {\flushnextbox},
         \v!midden=>\vcenter{\flushnextbox},
           \v!laho=>\vcenter{\flushnextbox},
        \s!unknown=>\tbox   {\flushnextbox},
        \s!default=>\tbox   {\flushnextbox}]%
   \else
     \startbaselinecorrection
     \noindent\flushnextbox
     \stopbaselinecorrection
   \fi}

% \startitemize
%
% \item \externalfigure[koe][height=2cm]
% \item \externalfigure[koe][height=2cm]
% \item \externalfigure[koe][height=2cm]
% \item \externalfigure[koe][height=2cm]
%
% \page
%
% \item \startfixed      \externalfigure[koe][height=2cm]\stopfixed
% \item \startfixed[high]\externalfigure[koe][height=2cm]\stopfixed
% \item \startfixed[low] \externalfigure[koe][height=2cm]\stopfixed
% \item \startfixed[lohi]\externalfigure[koe][height=2cm]\stopfixed
%
% \page
%
% \item test \startfixed      \externalfigure[koe][height=2cm]\stopfixed
% \item test \startfixed[high]\externalfigure[koe][height=2cm]\stopfixed
% \item test \startfixed[low] \externalfigure[koe][height=2cm]\stopfixed
% \item test \startfixed[lohi]\externalfigure[koe][height=2cm]\stopfixed
%
% \page
%
% \item test \par \startfixed      \externalfigure[koe][height=2cm]\stopfixed
% \item test \par \startfixed[high]\externalfigure[koe][height=2cm]\stopfixed
% \item test \par \startfixed[low] \externalfigure[koe][height=2cm]\stopfixed
% \item test \par \startfixed[lohi]\externalfigure[koe][height=2cm]\stopfixed
%
% \stopitemize

% \def\docalculatefigurenorm#1#2%
%   {\dodocalculatefigurenorm{#1}[#2\empty\empty]}
%
% \def\dodocalculatefigurenorm#1[#2#3#4]#5#6#7%
%   {\ExpandFirstAfter\processaction
%       [#2#3#4]
%       [     \v!max=>\global#1=#6\relax,
%           \v!kolom=>\global#1=#6\relax,
%           \v!tekst=>\global#1=#6\relax,
%         \v!passend=>\global#1=#7\relax,
%            \v!ruim=>\global#1=#7\relax
%                     \global\advance #1 -4\@@exkorps\relax,
%        #2*\v!kolom=>\global#1=#6\relax
%                     \ifbinnenkolommen
%                       \global\advance#1 \intercolumnwidth
%                       \global\multiply#1 #2\relax
%                       \global\advance#1 -\intercolumnwidth
%                     \fi,
%        #2*\v!tekst=>\global#1=\zetbreedte
%                     \global\advance#1 \papierbreedte,
%         \s!default=>\doifsomething{#5}{\global#1=#5\relax},
%         \s!unknown=>\global#1=\@@exkorps\relax
%                     \global\divide#1 \!!ten\relax
%                     \global\multiply#1 #2#3#4\relax]}

\def\complexTableTB[#1]{\TABLEnoalign{\blanko[#1]}}
\def\simpleTableTB     {\TABLEnoalign{\blanko}}

\def\TabulateTB
  {\complexorsimpleTable{TB}}

\def\doTableinterline% #1
  {\ifnum\currentTABLEcolumn>\maxTABLEcolumn
     \chuckTABLEautorow
   \else\ifnum\currentTABLEcolumn=\zerocount
     \TABLEnoalign
       {\globalletempty\checkTABLEautorow
        \globalletempty\chuckTABLEautorow}%
   \else
     \setTABLEerror\TABLEmissingcolumn
     \handleTABLEerror
   \fi\fi
   \complexorsimpleTable} % {#1}

\def\TableHL{\doTableinterline{HL}}
\def\TableTB{\doTableinterline{TB}}

\appendtoks\let\TB\TableTB   \to\everytable
\appendtoks\let\TB\TabulateTB\to\everytabulate

% \starttabulate
% \NC text \NC text \NC \NR
% \TB[small]
% \NC text \NC text \NC \NR
% \TB[4*big]
% \NC text \NC text \NC \NR
% \stoptabulate
%
% \starttable[|||]
% \VL text \VL text \VL \AR
% \TB[small]
% \VL text \VL text \VL \AR
% \TB[4*big]
% \VL text \VL text \VL \AR
% \stoptable

% still needed for uguide

\let\placefloatlabel          \placefloatcaption
\let\placefloatlabeltext      \placefloatcaptiontext
\let\placefloatlabelreference \placefloatcaptionreference

\def\obeyfollowingtoken{{}}  % end \cs scanning

\def\gobbleparameters{\doquadrupleempty\dogobbleparameters}
\def\dogobbleparameters[#1][#2][#3][#4]{}

\def\defineTABLEdivisions
  {\global\TABLEdivisionfalse % in start
   \let\DL\TableDL
   \let\DC\TableDC
   \let\DV\TableDV
   \let\DR\TableDR}

\def\defineTABLErules
  {\let\VL\TableVL
   \let\VC\TableVC
   \let\HL\TableHL
   \let\HC\TableHC
   \let\VS\TableVS
   \let\VD\TableVD
   \let\VT\TableVT}

\def\TableVS{\gdef\@VLn{1}\VL}
\def\TableVD{\gdef\@VLn{2}\VL}
\def\TableVT{\gdef\@VLn{3}\VL}

\def\@VLn{1}
\def\@VLd{.125em}

\def\do!ttInsertVrule % will be merged in 2005
  {\vrule \!thWidth
   \ifnum\!tgCode=1
     \ifx\!tgValue\empty
       \LineThicknessFactor
     \else
       \!tgValue
     \fi
     \LineThicknessUnit
   \else
     \!tgValue
   \fi
   \hskip\@VLd}

\def\!ttInsertVrule%
  {\hfil
   \TABLEbeforebar % added
   \startglobalTABLEcolor % added
   % we could do without this speedup, some day merge 'm
   \ifcase\@VLn\or
     \do!ttInsertVrule
     \unskip
   \else
     \dorecurse\@VLn\do!ttInsertVrule
     \gdef\@VLn{1}%
     \unskip
   \fi
   \stopglobalTABLEcolor % added
   \TABLEafterbar % added
   \hfil
   &}

% \starttable[|||]
% \HL
% \VL test \VS test \VL \FR
% \VL test \VD test \VL \MR
% \VL test \VT test \VL \LR
% \HL
% \stoptable

%D To be documented, \type {\includemenu[menu]}.
%D To be documented, \type {\emphbf} cum suis.

%D A prelude to strategies. Note for myself: overloads
%D previous stuff from local pragma test files.

\def\s!strategy{strategy}

\def\currentstrategypass    {1}
\def\currentstrategyvariable{0}
\def\maximumstrategypass    {8}

\newconditional\strategypassneeded
\newconditional\strategypassforced

\definetwopasslist{\s!strategy}

\def\registerstrategypass%
  {\ifnum\currentstrategypass>\maximumstrategypass \else
     \ifconditional\strategypassforced
       \doglobal\increment\currentstrategypass
     \else%\ifconditional\strategypassneeded
       %\doglobal\increment\currentstrategypass
     \fi%\fi
   \fi
   \savecurrentvalue\currentstrategypass{\currentstrategypass}}

\appendtoks \registerstrategypass \to \everybye % \everylastshipout

\def\setstrategyvariable#1#2% key value
  {%\doifnotstrategyvariable{#1}{\global\settrue\strategypassneeded}%
   \doglobal\increment\currentstrategyvariable
   \expanded{\immediatewriteutilitycommand{\noexpand
     \twopassentry{\s!strategy}{\currentstrategyvariable}{#1::#2}}}}

\def\doifstrategyvariableelse#1#2#3%
  {\getstrategyvariable{#1}\iftwopassdatafound#2\else#3\fi}

\def\getstrategyvariable#1% key
  {\findtwopassdata{\s!strategy}{#1::}%
   \setxvalue{\s!strategy:#1}{\twopassdata}}

\def\retainstrategyvariable#1% key
  {\expanded{\setstrategyvariable{#1}{\strategyvariable{#1}}}}

\def\strategyvariable#1% key
  {\csname\s!strategy:#1\endcsname}

\let\stratvar\strategyvariable

\def\forcestrategy{\global\settrue \strategypassforced}
\def\abortstrategy{\global\setfalse\strategypassforced}

\def\doifstrategyvariableelse#1#2#3%
  {\getstrategyvariable{#1}\iftwopassdatafound#2\else#3\fi}

\def\doifstrategyvariable   #1#2{\doifstrategyvariableelse{#1}{#2}{}}
\def\doifnotstrategyvariable#1#2{\doifstrategyvariableelse{#1}{}{#2}}

%D New: only at start of columns; may change ! Rather
%D interwoven and therefore to be integrated when the multi
%D column modules are merged.

%  already taken care of: \definesystemvariable{ks}

% is buggy now and does not work any longer

\def\setupcolumnspan[#1]%
  {\getparameters[\??ks][#1]}

\presetlocalframed
  [\??ks]

\setupcolumnspan
  [\c!n=2,
   \c!offset=\v!overlay,
   \c!kader=\v!uit]

\newbox\columnspanbox \let\postprocesscolumnspanbox\gobbleoneargument

\def\dostartcolumnspan[#1]%
  {\bgroup
   \setupcolumnspan[#1]%
   \forgetall
   \ifbinnenkolommen
     \advance\hsize \intercolumnwidth
     \hsize\@@ksn\hsize
     \advance\hsize -\intercolumnwidth
   \fi
   \dowithnextbox
     {\setbox\columnspanbox\flushnextbox
      \ifbinnenkolommen\wd\columnspanbox\hsize\fi
      \postprocesscolumnspanbox\columnspanbox
      \scratchdimen\ht\columnspanbox
      \setbox\columnspanbox\hbox % depth to be checked, probably option!
        {\localframed[\??ks][\c!offset=\v!overlay]{\box\columnspanbox}}%
      \ht\columnspanbox\scratchdimen
      \dp\columnspanbox\strutdp
      \wd\columnspanbox\hsize
      \ifbinnenkolommen
        \ifnum\@@ksn>1
          \setvsize
          \dohandleallcolumns
            {\ifnum\currentcolumn>\@@ksn\else
               \global\setbox\currenttopcolumnbox=\vbox
                 {\ifnum\currentcolumn=1
                    \snaptogrid\vbox{\copy\columnspanbox}
                  \else
                    \snaptogrid\vbox{\vphantom{\copy\columnspanbox}}
                  \fi}%
               \wd\currenttopcolumnbox\hsize
               \global\advance\vsize -\ht\currenttopcolumnbox
             \fi}
          \global\pagegoal\vsize
        \else
          \snaptogrid\vbox{\box\columnspanbox}
        \fi
      \else
        \snaptogrid\vbox{\box\columnspanbox}
      \fi
      \endgraf
      \prevdepth\strutdp
      \egroup}
     \vbox\bgroup
      %\topskipcorrection % becomes an option !
       \EveryPar{\begstrut\EveryPar{}}} % also !

\def\startcolumnspan
  {\dosingleempty\dostartcolumnspan}

\def\stopcolumnspan
  {\egroup}

%D For Ton. To be documented.

\def\plaatsexterndocument[#1]%
  {\def\doexternaldocument[##1][##2][##3]%
     {\readlocfile{##2}\donothing\donothing}%
   \getvalue{\v!file:::#1}}

%D Far from complete.

\def\startgeheel
  {\startregelcorrectie
   \insidefloattrue}

\def\stopgeheel
  {\stopregelcorrectie}

%D No more news.

\protect

%D A few local optimizations and new features, if defined:

\readfile {cont-loc} {} {}

\endinput