I want to patch the \thepage in the \addcontentsline to 2*\c@page + 1 if some bool in preamble is true. I simplify my code to this:
\documentclass{article}
\usepackage{etoolbox}
\makeatletter
\ExplSyntaxOn
\AtEndPreamble
{
\bool_if:NT \c_true_bool
{\patchcmd{\addcontentsline}{\thepage}{\int_eval:n {2 * \c@page + 1}}{}{\fail}}
}
% \patchcmd{\addcontentsline}{\thepage}{\int_eval:n {2 * \c@page + 1}}{}{\fail}
\ExplSyntaxOff
\makeatother
\begin{document}
\tableofcontents
\section{test}
\end{document}
Things in .toc are
\contentsline {section}{\numberline {1}test}{\int _eval:n {2*\c@page +1}}{}%
We can see that \int _eval:n {2*\c@page +1} is broken and wasn't calculated to 3. However if I remove either \AtEndPreamble or \bool_if:NT \c_true_bool, I get
\contentsline {section}{\numberline {1}test}{1}{}%
1 is still 1. This seems that `\patchcmd' only works in group, is there a "global" version?
If I remove both commands and remove the group, 1 changes to 3, which is what I want.
My question is why would this happen and how can I fix it?
EDIT: In this example, @user202729 's method works. However, if I add hyperref, \thepage in \addcontentsline is unpatchable any more.
[debug] tracing \ifpatchable on input line 23
[debug] analyzing '\addcontentsline'
[debug] ++ control sequence is defined
[debug] ++ control sequence is a macro
[debug] -- macro cannot be retokenized cleanly
[debug] -> the macro may have been defined under a category
[debug] code regime different from the current one
[debug] -> the replacement text may contain special control
[debug] sequence tokens formed with \csname...\endcsname;
[debug] -> the replacement text may contain carriage return,
[debug] newline, or similar characters
Similar question: hyperref and \addcontentsline's patch in expl3 block
patchcmddoesn't detect the wrong catcode. (short fix, add\ExplSyntaxOnbefore\patchcmdand\ExplSyntaxOffafter it.) – user202729 Jul 14 '22 at 05:23\inteval(in older load the xfp package) instead of\int_eval:n. That removes the need for complicated catcode juggling. – Ulrike Fischer Jul 14 '22 at 07:06