Whether a macro is defined with \def
or \edef
is only important at definition time, not at usage time.
Thus, you don't want to \edef\SecWr
, which would fix forever the value of \ChaptNo
and \SecNo
to the value at definition time (which is zero).
If you want a macro that expands its argument at usage time you can exploit expl3
, that also works with Plain TeX, provided you run an e-TeX engine like pdftex
(not with Knuth TeX).
\input expl3-generic
\ExplSyntaxOn
\cs_new_protected:Nn \test_sec_wr:nn
{
\tocsection{#1}{#2}
}
\cs_generate_variant:Nn \test_sec_wr:nn { x }
\cs_set_eq:NN \SecWr \test_sec_wr:xn
\ExplSyntaxOff
\def\tocsection#1#2{%
\write0{%
\line{\hskip2em\hbox to2em{#1\hfil}#2\leaderfill\folio}%
}%
}
\def\Sec#1{\advance\SecNo by1 \SecWr{\the\ChaptNo.\the\SecNo}{#1}}
Here's a full example (with \leaderfill
defined as \relax
just for testing, as I don't know what's your definition).
\input expl3-generic
\ExplSyntaxOn
\cs_new_protected:Nn \test_sec_wr:nn
{
\tocsection{#1}{#2}
}
\cs_generate_variant:Nn \test_sec_wr:nn { x }
\cs_set_eq:NN \SecWr \test_sec_wr:xn
\ExplSyntaxOff
\def\tocsection#1#2{%
\write0{%
\line{\hskip2em\hbox to2em{#1\hfil}#2\leaderfill\folio}%
}%
}
\def\Sec#1{\advance\SecNo by1 \SecWr{\the\ChaptNo.\the\SecNo}{#1}}
\newcount\ChaptNo
\newcount\SecNo
\let\leaderfill\relax % just for testing
\ChaptNo=3 % just for testing
\Sec{Section Title}
\Sec{Section Title}
\Sec{Section Title}
\bye
The macro \test_sec_wr:nn
is defined as a normal macro, but then we define a variant that fully ex
pands its first argument and use it as \SecWr
. Here's the output on the terminal:
\hbox to\hsize {\hskip 2em\hbox to2em{3.1\hfil }Section Title\leaderfill 1}
\hbox to\hsize {\hskip 2em\hbox to2em{3.2\hfil }Section Title\leaderfill 1}
\hbox to\hsize {\hskip 2em\hbox to2em{3.3\hfil }Section Title\leaderfill 1}
\write
. By adding\immediate
before\write
, the write is not delayed, but you need the delayed writing for the page number, which is known at page shipout time and usually not before.\write{\the\ChapNo}
(this is not a useful example but a minimum one).\expandafter
can help:\expandafter\write\expandafter\handle\expandafter{\the\ChapNo}
. Or the whole\write
expression can be put inside an\edef
with protecting the page number from expansion, e.g.\noexpand\folio
.\expandafter\write0\expandafter\handle\expandafter{\line{\hskip2em\hbox to2em{\the\ChapNo.\the\SecNo\hfil}#1\leaderfill\the\pageno}}
which doesn't compile.\edef\Test#1{\write0{\line{\hskip2em\hbox to2em{\the\ChapNo.\the\SecNo\hfil}#1\leaderfill\the\noexpand\pageno}}}
and then\Test{#1}
inside my\section
macros does also not work.