%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.

% todo: mp-new
\unprotect

\writestatus{\m!systems}{beware: some patches loaded from cont-new.tex!}

% todo : test low level translation (nl->en) and optimize script

% \readfile{cont-exp}\donothing\donothing % speed up (5-20%)

\def\doiffontcharelse#1#2%
  {\bgroup
   \definedfont[#1]%
   \iffontchar\font#2\relax
     \egroup\expandafter\firstoftwoarguments
   \else
     \egroup\expandafter\secondoftwoarguments
   \fi}

\unexpanded\def\asciistr#1{\convertargument#1\to\ascii{\verbatimfont\ascii}}

\def\shapedhbox                  % lines with non strutted dimensions have
  {\expanded{\dowithnextbox      % interlineskip so if we want the original
     {\nextboxht\the\ht\shapebox % spacing, we need to preserve the original
      \nextboxdp\the\dp\shapebox % height and depth which is definitely
      \noexpand\flushnextbox}}   % needed if we apply struts to the 'new'
   \normalhbox}                  % box or do something that changed ist size

\def\inrightmargin#1% new: hsize correction
  {\pushindentation
   \rlap
     {\hskip\tekstbreedte
      %\hskip-\hsize
      %\hskip\hsize
      \hskip-\rightskip
      \hskip\rechtermargeafstand
      \hsize\rechtermargebreedte
      #1}%
   \popindentation
   \ignorespaces}

\def\rechtermargetekstblok#1% new: hsize correction
  {\maakmargetekstblok \rightmargintextwidth \v!rechts \v!links
     {\hskip\margetekstafstand\hskip\tekstbreedte\hskip-\hsize }{\rlap{\plaatsmargetekstscheider}}
     {#1}}

\def\douniqueMPpagegraphic#1#2%
  {\blabelgroup
   \let\overlaystamp\overlaypagestamp
   \setupMPvariables[\MPpageprefix#1][#2]% prefix is new here
   \getvalue{\@@MPG\MPpageprefix#1}{}%
   \elabelgroup}

\prependtoks \setnormalcatcodes  \to \everyTEXinputmode
\appendtoks  \processingXMLfalse \to \everyTEXinputmode

\let\normalenableXML\enableXML % some day we move the normal \enableXML into the toks

\prependtoks \normalenableXML    \to \everyXMLinputmode
\appendtoks  \processingXMLtrue  \to \everyXMLinputmode

\def\enableXML {\setinputmode[XML]}
\def\disableXML{\setinputmode[TEX]}

\def\checkvariables
  {\dodoubleargument\docheckvariables}

\def\docheckvariables
  {\dogetparameters\docheckrawvalue}

\def\docheckrawvalue#1#2#3%
  {\doifundefined   {\??vars:#1:#2}{\setvalue{\??vars:#1:#2}{#3}}
  {\doifvaluenothing{\??vars:#1:#2}{\setvalue{\??vars:#1:#2}{#3}}}}

\beginTEX

  % else the skip aborts the reshape process

  \def\shapefill{\vskip\onepoint\!!plus\lineheight\!!minus\lineheight\relax}

\endTEX

\beginETEX

  \def\shapefill{\vskip\zeropoint\!!plus\lineheight\!!minus\lineheight\relax}

\endETEX

\beginETEX \lastnodetype

\def\dodoreshapebox#1#2#3#4% \shapebox, \shapepenalty, \shapekern, \shapeskip
  {\ifnum\lastnodetype=\@@gluenode % \ifcase\lastskip % \ifdim\lastskip=\zeropoint\relax
     \shapeskip\lastskip
     \global\setbox\tmpshapebox\normalvbox{#4\unvbox\tmpshapebox}%
     \unskip
   \else\ifnum\lastnodetype=\@@kernnode % \ifcase\lastkern % \ifdim\lastkern=\zeropoint\relax
     \shapekern\lastkern
     \global\setbox\tmpshapebox\normalvbox{#3\unvbox\tmpshapebox}%
     \unkern
   \else\ifnum\lastnodetype=\@@penaltynode % \ifcase\lastpenalty % \ifnum\lastpenalty=\zerocount
     \shapepenalty\lastpenalty
     \global\setbox\tmpshapebox\normalvbox{#2\unvbox\tmpshapebox}%
     \unpenalty
   \else
     \setbox\shapebox\lastbox
     \ifvoid\shapebox
       \unskip\unpenalty\unkern
     \else
       \ifdim\wd\shapebox=\shapesignal\relax
         \exitloop
       \else
         \shapecounter\zerocount
         \global\setbox\tmpshapebox\normalvbox{#1\unvbox\tmpshapebox}%
       \fi
     \fi
   \fi\fi\fi
   \ifnum\shapecounter>100 % can be less
     \message{<<forced exit from shapebox>>}%
     \global\setbox\tmpshapebox\copy\oldshapebox
     \exitloop
   \else
     \advance\shapecounter \plusone
   \fi}

\endETEX

\let\normaltype\type

\beginTEX

  \unexpanded\def\retype#1{\bgroup\convertargument#1\to\ascii\@EA\normaltype\@EA{\ascii}\egroup}

\endTEX

\beginETEX

  \unexpanded\def\retype#1{\scantokens{\normaltype{#1}}}

\endETEX

\def\simplifytype{\let\type\retype}

% \ruledhbox
%   {\startignorespaces
%      \def\oeps{a}
%      \startignorespaces
%        \def\oeps{a}
%      \stopignorespaces
%      \def\oeps{a}
%    \stopignorespaces
%    \oeps}

\newsignal\boissignal
\newcount \boislevel

\long\def\startignorespaces
  {\advance\boislevel\plusone
   \ifcase\boislevel\or \ifhmode
     \hskip\boissignal
   \fi \fi
   \ignorespaces}

\long\def\stopignorespaces
  {\ifcase\boislevel\or \ifhmode
    \doloop
      {\ifdim\lastskip=\zeropoint
         \exitloop
       \else\ifdim\lastskip=\boissignal
         \unskip
         \exitloop
       \else
         \unskip
       \fi\fi}%
   \fi \fi
   \advance\boislevel\minusone}

\defineblankmethod [\v!synchroniseer] {\verticalstrut\vskip-2\lineheight\verticalstrut}

% \vtop{\blank[synchronize]\blank[line]test}

\def\minimalhbox#1#%
  {\dowithnextbox
     {\bgroup
      \setbox\scratchbox\hbox#1{\hss}%
      \ifdim\nextboxwd<\wd\scratchbox\nextboxwd\wd\scratchbox\fi
      \flushnextbox
      \egroup}
     \hbox}

% manual
%
% externfiguur     -> grid        =ja|hoogte|diepte|halveregel|passend -> helemaal in details
% stelplaatsblokin -> zijuitlijnen=hoogte|diepte|regel|halveregel|grid -> halveregel in 'details'

% TODO: TEST FIRST, NO CORRECTION NEEDED IN GRID MODE, EVT OPTION

\def\OTRONEsomeherefloat[#1]% spacing between two successive must be better
  {\baselinecorrection                           % not really needed in grid mode:
  %\ifgridsnapping \else \baselinecorrection \fi % ! ! ! test test test ! ! ! !
   \doplacefloatbox
   \doinsertfloatinfo
   \dochecknextindentation\??bk}

% todo: switch koppelen aan par scheelt pos

% to be documented: \startspread .. \stopspread

% to be documented primarydef p crossed d
% to be documented PlainTextArea

% manual
%
% Sometimes the demands are getting pretty weird:
%
% \startitemize
%   \item test
%   \item test
%   \headsym{xx} test \par test
% \stopitemize

\beginETEX \lastnodetype

\def\removeunwantedspaces
  {\ifhmode
     \doloop{\ifnum\lastnodetype=\@@gluenode\unskip\else\exitloop\fi}%
   \fi}

\endETEX

% \def\dodimchoice#1#2#3%
%   {\ifx#3\relax
%      #1\@EA\gobbleuntilrelax
%    \else\ifdim#1#2%
%      #3\@EAEAEA\gobbleuntilrelax
%    \else
%      \@EAEAEA\dodimchoice
%    \fi\fi{#1}}

% \def\donumchoice#1#2#3%
%   {\ifx#3\relax
%      #1\@EA\gobbleuntilrelax
%    \else\ifnum#1#2%
%      #3\@EAEAEA\gobbleuntilrelax
%    \else
%      \@EAEAEA\dodimchoice
%    \fi\fi{#1}}

% \def\dimchoice#1#2{\dodimchoice{#1}#2\empty\relax}
% \def\numchoice#1#2{\donumchoice{#1}#2\empty\relax}

\def\gobbleuntilempty#1\empty{}

\def\dodimchoice#1#2#3%
  {\ifdim#1#2%
     #3\@EA\gobbleuntilempty
   \else
     \@EA\dodimchoice
   \fi{#1}}

\def\donumchoice#1#2#3%
  {\ifnum#1#2%
     #3\@EA\gobbleuntilempty
   \else
     \@EA\dodimchoice
   \fi{#1}}

\def\dimchoice#1#2{\dodimchoice{#1}#2{=#1}{#1}\empty}
\def\numchoice#1#2{\donumchoice{#1}#2{=#1}{#1}\empty}

% \the\dimexpr(\dimchoice {7pt}{{<10pt}{8pt}{<12pt}{9pt}{<15pt}{10pt}{=11pt}{12pt}})
% \the\dimexpr(\dimchoice{11pt}{{<10pt}{8pt}{<12pt}{9pt}{<15pt}{10pt}{=11pt}{12pt}})
% \the\dimexpr(\dimchoice{14pt}{{<10pt}{8pt}{<12pt}{9pt}{<15pt}{10pt}{=11pt}{12pt}})

\def\showsetupsdefinition[#1]{\showvalue{\??su:#1}} % temp hack for debugging

% documentation : \setupregister[alternative=a|b|A|B]

\def\pushXMLmeaning#1%
  {\@EA\pushmacro\csname\@@XMLelement:#1/\endcsname
   \@EA\pushmacro\csname\@@XMLelement:#1\endcsname
   \@EA\pushmacro\csname\@@XMLelement:/#1\endcsname}

\def\popXMLmeaning#1%
  {\@EA\popmacro\csname\@@XMLelement:#1/\endcsname
   \@EA\popmacro\csname\@@XMLelement:#1\endcsname
   \@EA\popmacro\csname\@@XMLelement:/#1\endcsname}

\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\countXMLchildren[#1]#2%
  {\startnointerference
     \doglobal\newcounter\nofXMLchildren
     \defineXMLargument[#1]{\doglobal\increment\nofXMLchildren}%
     \startXMLignore
       #2%
     \stopXMLignore
   \stopnointerference}

\unprotected \def\traceposstring#1#2#3%
  {\iftracepositions
     \smashedhbox%
       {#1{\infofont#2#3}%
        \scratchdimen.5\points
        \kern-2\scratchdimen
        \vrule\!!width4\scratchdimen\!!height\scratchdimen\!!depth\scratchdimen}%
   \fi}

% 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

% new, continuous blocks, \som \par \startdoorlopendblok ...

% \startitemize
%   \item                                      bagger
%   \item                                      bagger
%   \item          \startdoorlopendblok        bagger \stopdoorlopendblok
%   \item \endgraf \startdoorlopendblok        bagger \stopdoorlopendblok
%   \item \endgraf \startdoorlopendblok \strut bagger \stopdoorlopendblok
%   \item \startdoorlopendblok
%         \starttabulate
%         \NC test \NC test \NC \NR
%         \NC test \NC test \NC \NR
%         \NC test \NC test \NC \NR
%         \stoptabulate
%         \stopdoorlopendblok
%   \item test
% \stopitemize

\def\startdoorlopendblok % for special cases, don't change it too much and don't rely on it
  {\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 % 2\lineheight when no vertical struts in main \vbox
      \nobreak
      \unvbox\nextbox
      \prevdepth\strutdepth
      % evt (eerst testen) een signal zodat een direct volgend blok goed gaat)
      \egroup}
     \vbox\bgroup
       \vskip-\lineheight \verticalstrut\endgraf
       \insidefloattrue
       \doinhibitblank} % beware, no \inhibitblank ! ! ! ! ! !

\def\stopdoorlopendblok
  {\endgraf\verticalstrut\endgraf\kern-2\lineheight
   \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\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

\def\useMPvariables
  {\dodoubleargument\douseMPvariables}

\def\douseMPvariables[#1][#2]%
  {\def\@@meta{#1:}%
   \prepareMPvariables{#2}}

\def\processlinetableXMLfile#1%
  {\bgroup
   \let\startlinetable\donothing
   \let\stoplinetable \donothing
   \startlinetableanalysis\processXMLfile{#1}\stoplinetableanalysis
   \startlinetablerun     \processXMLfile{#1}\stoplinetablerun
   \egroup}

% 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

% 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]}

% 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]{}

% documentation

% \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