如何在 zref 命令中正确使用计数器值

如何在 zref 命令中正确使用计数器值

我正在尝试扩展答案这个问题以便自动创建位置标记zref

我想我缺少一些关于如何打印计数器的重要知识。所以我创建了一个计数器和两个命令,一个命令步进计数器并打印它,另一个命令重复计数器而不步进它。

\newcounter{xcnt}\setcounter{xcnt}{0}
\newcommand{\countxcnt}{\stepcounter{xcnt}A\thexcnt}
\newcommand{\repeatxcnt}{A\thexcnt}

当我通过将其放入\countxcnt \repeatxcnt \countxcnt \repeatxcnt文档正文中进行测试时,我得到的正是我想要的:A1A1A2A2 等等。现在我想以zref以下方式使用该输出(请参阅链接答案对于我需要这个的上下文,我在这里将其剥离以保持其较小):

\documentclass{article}
\usepackage[user,savepos]{zref}
\newcommand{\offset}[2]{%
\dimexpr\zposx{#2}sp-\zposx{#1}sp+1em\relax}
\newcommand{\overmk}[1]{\leavevmode\zsaveposx{#1}}

\newcounter{xcnt}\setcounter{xcnt}{0}
%\newcommand{\countxcnt}{\stepcounter{xcnt}A\thexcnt}
%\newcommand{\repeatxcnt}{A\thexcnt}

\begin{document}
\overmk{A}This is an example \overmk{\countxcnt}sentence.\par
\hspace{\offset{A}{\repeatxcnt}}This is another sentence.\par
This \overmk{\countxcnt}is a third sentence.\par
\hspace{\offset{A}{\repeatxcnt}}This is a fourth sentence.
\end{document}

失败并出现missing \endcsname错误。
仅供参考,这是手动提供标记,我想将其自动化,以便:

\begin{document}
\overmk{A}This is an example \overmk{A1}sentence.\par
\hspace{\offset{A}{A1}}This is another sentence.\par
This \overmk{A2}is a third sentence.\par
\hspace{\offset{A}{A2}}This is a fourth sentence.
\end{document}

我认为我还不太了解一些关于如何使用计数器的基本知识,我希望有人能给我指明正确的方向……

解决方案(感谢下面 egreg 的评论):

\overmk{A}This is an example \stepcounter{xcnt}\overmk{\thexcnt}sentence.\par
\hspace{\offset{A}{\thexcnt}}This is another sentence.\par
This \stepcounter{xcnt}\overmk{\thexcnt}is a third sentence.\par
\hspace{\offset{A}{\thexcnt}}This is a fourth sentence.

(并且简单地忽略上面注释掉的行,因为没有必要)

答案1

\stepcounter是不可扩展的,因为它正在执行分配,因此zsaveposx作为\stepcounter参数的一部分在这里不起作用。

解决方案:\stepcounter必须先完成宏\zsaveposx才能执行分配,然后才能检索该值。

该代码的真正目的有点不清楚,解决方案仅限于 OP 的基本风格。

\documentclass{article}
\usepackage[user,savepos]{zref}

\newcommand{\offset}[2]{%
  \dimexpr\zposx{#2}sp-\zposx{#1}sp+1em\relax%
}

\newcommand{\overmk}[1]{\stepcounter{xcnt}\ifnum1=\value{xcnt}\zsaveposx{#11}\else\zsaveposx{#1}\fi}

\newcounter{xcnt}
\newcommand{\countxcnt}{A\thexcnt}
\newcommand{\repeatxcnt}{A\thexcnt}

\begin{document}
\overmk{A}This is an example \overmk{\countxcnt}sentence.\par
\hspace{\offset{A}{\repeatxcnt}}This is another sentence.\par
This \overmk{\countxcnt}is a third sentence.\par
\hspace{\offset{A}{\repeatxcnt}}This is a fourth sentence.
\end{document}

相关内容