\message{as of 27jun98}%21feb98

% 27jun98 (make the writing immediate)
% 07jun98 (avoid macro expansion during writing, and make `\input index' set up
%          everything; also, remove useless stuff (now that I get it all :-))

% indexing (cf. pp.423-5 of Knuth)
% The idea is that anything of the form ^{...} appearing not in mathmode
% will also be entered, along with the current \pageno as encoded in

\def\forminx{!\chapterno.\folio.}

% in the file  \jobname.inx  while anything of the form ^^{...} will only be 
% entered in that file and not in the text.

% Be sure to \input index only after verbatim; also, don't mark anything 
% headed for headline/footline, or for the toc (use the silent version later
% instead).

\newif\ifindexmode\indexmodetrue
\newwrite\inx
\immediate\openout\inx=\jobname.inx % file for index items
\newtoks\writestuff

\newif\ifsilent
\def\specialhat{\ifmmode\def\next{^}\else\let\next=\beginxref\fi\next}
   % in mathmode, ^ is just that; otherwise it is eaten and index entry starts
\def\beginxref{\futurelet\next\beginxrefswitch} 
   % to start with, have to check whether there's a second ^ and do things
   % accordingly.
\def\beginxrefswitch{\ifx\next\specialhat\let\next=\silentxref
   \else\silentfalse\let\next=\xref\fi \next}

\catcode`\^=\active \let ^=\specialhat % time to make ^ an active character,
                         % and to give it the meaning of the macro \specialhat.
\def\silentxref^{\silenttrue\xref}  % At this point, ^ is an active character, 
                                    % hence, this zero-argument macro simply
                                    % eats that second ^ already known to be
                                    % there since only then is \silentxref used.

\def\xref#1{\writestuff={#1}\makexref}

\def\makexref{\ifindexmode\immediate\write\inx{\the\writestuff\forminx}\fi
   \ifsilent\ignorespaces\else\the\writestuff\fi}

% I have left out the recording of type definition, for the purpose of
% special typesetting and to make alphabetization easy for macro names and/or
% mathstuff, as well as something about hmode.

% One could add something about doing all this only in draft mode and also
% about marking indexed words or, perhaps, put them into the margin.

%% Also, in ala and other books, there is a somewhat simpler setup, as follows
%\newwrite\inx
%\newtoks\writestuff
%% use the following statement in file to designate appropriate file
%%\immediate\openout\inx=book.index % file for index items
%\newif\ifindexmode %this should be true if index stuff is to be put into
%                   %file. Use \indexmodetrue to make it so.
%\def\i#1{\unskip\lastbox\ifindexmode\writestuff={#1}\immediate\write\inx{\the\writestuff\space!\number\pageno.}\ifdraft\marginal{#1}\fi\fi}
%\def\ibf#1{{\bf #1}\i{#1}}
%\def\iit#1{{\it #1}\i{#1}}
%\def\iai#1{#1\i{#1}}
%\let\dword\ibf
