Перекрестная ссылка не закреплена должным образом

Перекрестная ссылка не закреплена должным образом

У меня есть написанный код, подобный этому.

\documentclass[8pt,a4paper,dvipsnames]{article}
\usepackage[utf8]{inputenc}
\usepackage[a4paper,hmargin=2cm,vmargin={2cm,2.5cm}]{geometry}
\usepackage[colorlinks=false]{hyperref}
\hypersetup{
    pdftitle={...},
    pdfauthor={...},
    pdfsubject={...},
    pdfkeywords={...},
}
\usepackage{enumitem}
\usepackage{chngcntr}
\usepackage{cleveref}
\usepackage{etoolbox,cancel,mathtools,physics}

\counterwithin*{equation}{section}
\counterwithin*{equation}{subsection}
\counterwithin*{equation}{enumi}

\newif\ifinenumerate
\AtBeginEnvironment{enumerate}{\inenumeratetrue}

\makeatletter
\renewcommand\theequation{%
  \ifnum\value{subsection}>0 \thesubsection.\else
  \ifnum\value{section}>0 \thesection.\fi\fi
  \ifinenumerate \theenumi\fi
  \arabic{equation}}
\makeatother

\begin{document}
\section{Test 1}
\subsection{Test 1.1}
\begin{enumerate}[label=\alph*.]
\item item a
    \begin{itemize}
        \item item a case 1         
        \begin{equation*}
        a = b
        \end{equation*}             
        \begin{itemize}
        \item item a case 1 subcase 1       
        \begin{equation}
        a = b \label{eq:Eq1.1.a.1}
        \end{equation}
        \end{itemize}
    \end{itemize}
    \begin{equation}
    a = b \label{eq:Eq1.1.a.2}
    \end{equation}
\end{enumerate}
\subsection{Test 1.2}
\begin{equation} 
\underbrace{
            \cancel{\pdv{t}\delta n}
            }_{
               \mathclap{\substack{\text{stationary} \\ \text{case}}}
              } 
              + 
\underbrace{
            \cancel{\mu^*\va{E}\grad_{\va{r}}{\var n}}
            }_{
               \substack{\mu^* = 0 \\ \text{if} \\ n_0 = p_0 = n_i}
              } 
              - 
D^*\laplacian_{\va{r}}\delta n 
              - 
\underbrace{
            \frac{\delta n}{\tau^*}
            }_{
               \mathclap{\substack{\text{it vanishes for} \\ \text{lengths less than}\ L}}
              } 
              - 
g_L = 0 \label{eq:AmbipEq}
\end{equation}
\subsection{Test 1.3}
Cross reference to \eqref{eq:AmbipEq} which is not properly anchored 
\end{document}

И я хотел бы узнать, почему eq:AmbipEqон не закреплен должным образом, может быть, это из-за \mathclapизноса \substack? Большое спасибо!

решение1

При тестировании вашего примера я получил строку

\newlabel{eq:AmbipEq}{{1.2.1}{1}{Test 1.2}{equation.1.1}{}}

в .aux-файл.

Это означает, что ссылка на метку eq:AmbipEqприводит к «печати» номера 1.2.1при переходе на якорь с именем equation.1.1.

Файл .log содержит несколько предупреждений. Одно из них:

pdfTeX warning (ext4): destination with the same identifier (name{equation.1.1}) has been already used, duplicate ignored

Это означает, что по какой-то причине было две попытки разместить якорь с именем equation.1.1.
Каждая гиперссылка ссылается на то место в output-file/.pdf-file, которое соответствует месту в .TeX-input-file/source-file, где попытка разместить этот якорь имела место в первый раз.

Что является причиной этого?:

Макрос \theequationиспользуется для указания способа «печати» значения счетчика уравнения.

При использовании hyperref-package, помимо вывода значения, возникает еще одна проблема:

Когда в выходной файл (pdf-файл) помещается новый экземпляр пронумерованного "элемента рубрификации", т. е. пронумерованный заголовок раздела, или подпись пронумерованной картинки, или подпись пронумерованной таблицы, или номер формулы/уравнения, печатается как значение соответствующего счетчика, так и размещается якорь для гиперссылок. Этот якорь должен иметь имя, уникальное в пределах всего документа.

Макрос \theHequationиспользуется для указания способа, которым имена якорей, связанные с номерами уравнений, будут автоматически генерироваться при использовании пакета hyperref.

Макрос \theHequationдолжен быть указан таким образом, чтобы обеспечивалась уникальность имен якорей.

При переопределении/изменении вам \theequation, вероятно, также придется скорректировать/переопределить \theHequation, чтобы обеспечить уникальность имен якорей.

Поэтому я предлагаю параллельно размещать

\renewcommand\theequation{%
  \ifnum\value{subsection}>0 \thesubsection.\else
  \ifnum\value{section}>0 \thesection.\fi\fi
  \ifinenumerate \csname theenum\romannumeral\the\@enumdepth\endcsname\fi
  \arabic{equation}%
}

поместив что-то вроде

\AtBeginDocument{%
  \renewcommand\theHequation{%
    \ifnum\value{subsection}>0 \theHsubsection.\else
    \ifnum\value{section}>0 \theHsection.\fi\fi
    \ifinenumerate \csname theHenum\romannumeral\the\@enumdepth\endcsname.\fi
    \arabic{equation}%
  }%
}

в преамбулу вашего документа.

(Для обоих создаваемых фрагментов кода предполагается @буква (→ ).)\makeatletter..\makeatother

При этом я получаю в .aux-файле запись

\newlabel{eq:AmbipEq}{{1.2.1}{1}{Test 1.2}{equation.1.2.1}{}} 

это означает, что ссылка на метку eq:AmbipEqприводит к «печати» номера 1.2.1 при переходе на якорь с именем equation.1.2.1.

Соответствующее предупреждение pdfTeX о назначении с тем же идентификатором не появляется в файле .log.

\documentclass[8pt,a4paper,dvipsnames]{article}
\usepackage[utf8]{inputenc}
\usepackage[a4paper,hmargin=2cm,vmargin={2cm,2.5cm}]{geometry}
\usepackage[colorlinks=false]{hyperref}
\hypersetup{
    pdftitle={...},
    pdfauthor={...},
    pdfsubject={...},
    pdfkeywords={...},
}
\usepackage{enumitem}
\usepackage{chngcntr}
\usepackage{cleveref}
\usepackage{etoolbox,cancel,mathtools,physics}

\counterwithin*{equation}{section}
\counterwithin*{equation}{subsection}
\counterwithin*{equation}{enumi}

\newif\ifinenumerate
\AtBeginEnvironment{enumerate}{\inenumeratetrue}

\newcommand{\prr}{\\[0.5cm]} %

\makeatletter
\renewcommand\theequation{%
  \ifnum\value{subsection}>0 \thesubsection.\else
  \ifnum\value{section}>0 \thesection.\fi\fi
  \ifinenumerate \csname theenum\romannumeral\the\@enumdepth\endcsname\fi
  \arabic{equation}%
}
\AtBeginDocument{%
  \renewcommand\theHequation{%
    \ifnum\value{subsection}>0 \theHsubsection.\else
    \ifnum\value{section}>0 \theHsection.\fi\fi
    \ifinenumerate \csname theHenum\romannumeral\the\@enumdepth\endcsname.\fi
    \arabic{equation}%
  }%
}
\makeatother

\begin{document}
\section{Test 1}
\subsection{Test 1.1}
\begin{enumerate}[label=\alph*.]
\item item a
    \begin{itemize}
        \item item a case 1
        \begin{equation*}
        a = b
        \end{equation*}
        \begin{itemize}
        \item item a case 1 subcase 1
        \begin{equation}
        a = b \label{eq:Eq1.1.a.1}
        \end{equation}
        \end{itemize}
    \end{itemize}
    \begin{equation}
    a = b \label{eq:Eq1.1.a.2}
    \end{equation}
\end{enumerate}
\subsection{Test 1.2}
\begin{equation}
\underbrace{
            \cancel{\pdv{t}\delta n}
            }_{
               \mathclap{\substack{\text{stationary} \\ \text{case}}}
              }
              +
\underbrace{
            \cancel{\mu^*\va{E}\grad_{\va{r}}{\var n}}
            }_{
               \substack{\mu^* = 0 \\ \text{if} \\ n_0 = p_0 = n_i}
              }
              -
D^*\laplacian_{\va{r}}\delta n
              -
\underbrace{
            \frac{\delta n}{\tau^*}
            }_{
               \mathclap{\substack{\text{it vanishes for} \\ \text{lengths less than}\ L}}
              }
              -
g_L = 0 \label{eq:AmbipEq}
\end{equation}
\begin{align}
n &= N_C e^{\left(\frac{E_F-E_C}{K_B T}\right)} \nonumber
\prr
\frac{N_D^+}{N_D^0} &= \frac{1}{g_D}e^{\left(\frac{E_D-E_F}{K_BT}\right)} \label{eq:EqToLabeling}
\end{align}
\subsection{Test 1.3}
Cross reference to \eqref{eq:AmbipEq} which is hopefully properly anchored

Cross reference to \eqref{eq:EqToLabeling} which is hopefully properly anchored as well.
\end{document}

Кстати:

Я думаю, важно узнать о считывающем аппарате (La)TeX и об обстоятельствах, при которых (La)TeX будет создавать пробелы (давая горизонтальный пробел в выходном файле) при столкновении с символом пробела во входном файле.
Например, символ пробела во входном файле после открывающей фигурной скобки или после закрывающей фигурной скобки даст пробел, ведущий к горизонтальному пробелу в выходном файле (если этот пробел встречается, когда (La)TeX не находится в одном из своих вертикальных режимов).
Например, перенос строки после открывающей фигурной скобки или после закрывающей фигурной скобки также даст пробел. Это потому, что при чтении входных данных (La)TeX вставляет пробел в конце каждой строки — это связано с целочисленным параметром \endlinechar.

Рассмотрите возможность использования символа комментария %после открывающих фигурных скобок в конце строк и после закрывающих фигурных скобок в конце строк, т. е. {%или }%, чтобы избежать нежелательного горизонтального пространства в выходном файле/pdf-файле.

\documentclass{article}

\newcommand\TeXA{\TeX{
}\TeX}

\newcommand\TeXB{\TeX{}
\TeX}

\newcommand\TeXC{\TeX{%
}\TeX}

\newcommand\TeXD{\TeX{}%
\TeX}

\begin{document}

\noindent There are subtle differences in spacing:

\noindent \TeXA

\noindent \TeXB

\noindent \TeXC

\noindent \TeXD

\end{document}

Связанный контент