如何在环境内定义两个标签来计算环境跨越的页数?

如何在环境内定义两个标签来计算环境跨越的页数?

我想计算某个环境(名为 )所跨越的页数myenv。原则上,我设置了两个标签,一个在环境的开头,一个在环境的结尾。这些标签对于环境的每次调用都应该是唯一的,这是仍然失败的部分(.tex:19: Missing \endcsname inserted):

\documentclass{scrartcl}
\usepackage{blindtext}

% adapted from https://tex.stackexchange.com/questions/38139/how-can-i-calculate-the-difference-of-2-counters-pageref
\usepackage{refcount}
\newcommand{\pageRange}[2]{%
  \number\numexpr\getpagerefnumber{#2}-\getpagerefnumber{#1}+1\relax}

\newcounter{howOftenCalled}% counts how often the environment 'myenv' was called (to create unique labels)
\setcounter{howOftenCalled}{0}
\newenvironment{myenv}[1]{
  \stepcounter{howOftenCalled}% increase counter
  \label{startPage:\ref{howOftenCalled}}% define the first label
  {\LARGE The following text covers \pageRange{startPage:\ref{howOftenCalled}}{endPage:\ref{howOftenCalled}} pages:}\\% compute the number of pages between the first and the second label
  \blindtext[#1]
}{\label{endPage:\ref{howOftenCalled}}\clearpage}% defined the second label

\begin{document}
\begin{myenv}{8}
\end{myenv}
\clearpage
\begin{myenv}{15}
\end{myenv}
\end{document}

答案1

您的代码可以工作,只是您无法使用 检索计数器的值\ref{howOftenCalled}。如果您改用\number\value{howOftenCalled},则一切都会按预期工作。

\documentclass{scrartcl}
\usepackage{blindtext}

% adapted from https://tex.stackexchange.com/questions/38139/how-can-i-calculate-the-difference-of-2-counters-pageref
\usepackage{refcount}
\newcommand\NumberOfPages[1]{\edef\tmp{\number\numexpr\getpagerefnumber{endPage:#1}-\getpagerefnumber{startPage:#1}+1\relax}%
\ifnum\tmp=1\relax%
1 page%
\else%
\tmp\space pages%
\fi}

\newcounter{howOftenCalled}% counts how often the environment 'myenv' was called (to create unique labels)
\setcounter{howOftenCalled}{0}
\newenvironment{myenv}[1]{%
   \stepcounter{howOftenCalled}% increase counter
   \label{startPage:\number\value{howOftenCalled}}% define the first label
  {\LARGE The following text covers
  \NumberOfPages{\number\value{howOftenCalled}}:}\\% compute the number of pages between the first and the second label
  \blindtext[#1]
}{\label{endPage:\number\value{howOftenCalled}}\clearpage}% defined the second label

\begin{document}
\begin{myenv}{8}
\end{myenv}
\clearpage
\begin{myenv}{15}
\end{myenv}
\clearpage
\begin{myenv}{1}
\end{myenv}
\end{document}

第 1 页顶部:

在此处输入图片描述

第 3 页顶部:

[![在此处输入图片描述][2]][2]

第 7 页顶部:

在此处输入图片描述

致谢:非常感谢@Andrew 和@UlrikeFischer,他们提出了如何使代码更优雅和安全的建议!

相关内容