根据引用出现的位置,在公式引用中包含/排除章节编号?

根据引用出现的位置,在公式引用中包含/排除章节编号?

我希望当公式在同一节中被引用时,引用该公式时不包括节号,但当公式在不同节中被引用时,包括节号。

下面是我尝试获取的一个示例: 期望结果 这是我尝试过的,并且我很清楚它的问题出在哪里:

\documentclass{article}
\usepackage[noabbrev]{cleveref}

\renewcommand{\thesection}{\Alph{section}}
\creflabelformat{equation}{#2(\thesection.#1)#3}

\begin{document}
\section{The first section}\label{first}

This is the some disussion in \cref{first}. This is the first equation:
\begin{equation}\label{A:1}
  1+1 = 2
\end{equation}
This is some more disussion. Here is a reference to \cref{A:1}.

\section{The second section}\label{second}
\setcounter{equation}{0}

This is some discussion in \cref{second} which references \cref{first}.
This is another equation:
\begin{equation}\label{B:1}
  2+2 = 4
\end{equation}
This is some discussion of \cref{B:1}, and a brief comment that it is
easily derived from equation \cref{A:1}.

\end{document}

第一次尝试

不幸的是,我不知道如何获得我想要的结果。

答案1

我只能同意张瑞熙的评论:这种格式常常让读者感到困惑,我强烈建议不要使用它。

如果仍要实现,则必须修改theequation而不是设置,creflabelformat因为creflabelformat只有在引用标签时才会进行评估。此时,方程式所在的原始部分已经丢失。

如果该节与包含参考的部分相同,则为了跳过该节,我定义了一个小宏。这目前仅适用于 pdfTeX,但\pdfstrcmp可以轻松替换为 ,expl3\str_if_eq_x:nnF兼容更多引擎。

\documentclass{article}
\usepackage[noabbrev]{cleveref}
\usepackage{etoolbox}

\DeclareRobustCommand\skipifequals[2]{%
  \ifnum\pdfstrcmp{#1}{#2}=0
  \else
    #2%
  \fi
}
\newcommand\skipifcurrent[1]{\protecting{\skipifequals{#1}}{#1}}
\renewcommand{\thesection}{\Alph{section}}
\creflabelformat{equation}{#2(#1)#3}
\renewcommand\theequation{\skipifcurrent{\thesection.}\arabic{equation}}

\begin{document}
\section{The first section}\label{first}

This is the some disussion in \cref{first}. This is the first equation:
\begin{equation}\label{A:1}
  1+1 = 2
\end{equation}
This is some more disussion. Here is a reference to \cref{A:1}.

\section{The second section}\label{second}
\setcounter{equation}{0}

This is some discussion in \cref{second} which references \cref{first}.
This is another equation:
\begin{equation}\label{B:1}
  2+2 = 4
\end{equation}
This is some discussion of \cref{B:1}, and a brief comment that it is
easily derived from equation \cref{A:1}.

\end{document}

在此处输入图片描述

答案2

我最终使用了expl3基于 Marcel Krüger 的答案的解决方案:

\ExplSyntaxOn
\cs_new_protected:Npn \ifsection #1#2#3 {
  \str_if_eq_x:nnTF{\thesection}{#1}{#2}{#3}
}
\cs_new:Npn \ifcurrentsection #1#2 { \ifsection{\thesection}{#1}{#2} } 

\renewcommand\theequation{
  \ifcurrentsection{}{\thesection.}\arabic{equation}
}  
\ExplSyntaxOff

这使我可以更加灵活,并根据引用是出现在当前部分还是其他部分来改变行为。

相关内容