%D \module
%D   [       file=xtag-exp,
%D        version=2001.08.20,
%D          title=\CONTEXT\ XML Macros,
%D       subtitle=Expansion,
%D         author=Hans Hagen,
%D           date=\currentdate,
%D      copyright={PRAGMA ADE \& \CONTEXT\ Development Team}]
%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 XML Macros / Expansion}

\ifnum\texengine=\luatexengine \endinput \fi

\unprotect

%D Files

\newcounter\XMLfilenesting \let\restoreXMLelements\relax

\def\startXMLreading
  {\increment \XMLfilenesting \relax
   \ifcase\XMLfilenesting\or
     \ifprocessingXML
       \let\restoreXMLelements\relax
     \else
       \let\restoreXMLelements\disableXMLelements
       \enableXMLelements
     \fi
   \fi}

\def\stopXMLreading
  {\ifcase\XMLfilenesting\or
     \restoreXMLelements
     \let\restoreXMLelements\relax
   \fi
   \decrement \XMLfilenesting \relax}

\ifnum\texengine=\luatexengine
    \def\enableXMLfiledata
      {\prependtoks \enableXMLelements      \to \mainoutput % brrr, will change
       \appendtoks  \forcefileexpansiontrue \to \everyenableXML
       \let\enableXMLfiledata\relax}
\else
    \def\enableXMLfiledata
      {\prependtoks \enableXMLelements      \to \mainoutput % brrr, will change
       \appendtoks  \startXMLreading        \to \everybeforeutilityread
       \appendtoks  \stopXMLreading         \to \everyafterutilityread
       \appendtoks  \forcefileexpansiontrue \to \everyenableXML
       \let\enableXMLfiledata\relax}
\fi

\setupXMLprocessing[\c!state=\v!start]

\appendtoks
  \ifproductionrun \enableXMLfiledata \fi
\to \aftersetupXMLprocessing

%D Here we overload the mark handler.

\ifnum\texengine=\luatexengine \else

    \def\XMLexpanded#1%
      {\bgroup
       \honorunexpanded
       \dontexpandencoding
       \xdef\@@globalexpanded{\noexpand#1}% why \noexpand?
       \egroup
       \@@globalexpanded}

    \let\normalsetnormalmark\setnormalmark

    \long\def\setnormalmark#1% overloaded
      {\ifprocessingXML
         \expandafter\setXMLexpandedmark
       \else
         \expandafter\normalsetnormalmark
       \fi#1}

    \def\setXMLexpandedmark#1#2% using a tok prevents unwanted expansion in mark
      {\XMLexpanded{\scratchtoks{\enableXMLelements#2}}%
       \setxvalue{\@@crk\string#1}{\the\scratchtoks}%
       \normalmarks#1{\the\scratchtoks}}

\fi

\protect \endinput
