
我正在嘗試使用該包創建文檔內部連結hyperref
。在連結應指向的位置,我執行以下命令(作為 LaTeX 環境設定的一部分):
\edef\@currentlabel{LABEL}
之後,我用來\label{...}
創建引用和\ref{...}
.該hyperref
包\ref{...}
按預期將其轉換為超鏈接,但該鏈接指向錯誤的位置(在文本中更靠前的位置)。我如何知道hyperref
連結應該指向哪裡?
我無法使用,\refstepcounter
因為我的標籤是文字的並且不與 LaTeX 計數器關聯。
這是一個「最小」(好吧,「小」)的工作範例來說明問題:
\documentclass{article}
\usepackage{lipsum}
\usepackage{amsthm}
\usepackage{hyperref}
\newtheorem{theorem}{Theorem}[section]
\makeatletter
\newenvironment{algorithm}[2]%
{\medbreak
\edef\@currentlabel{#1}%
% more stuff here (put entry in table of algorithms, etc.)
\noindent
\textbf{Algorithm~\@currentlabel\ (#2)}\hfill\break
\ignorespaces}%
{\medbreak}
\makeatother
\begin{document}
\section{Test}
\begin{theorem}
\lipsum[1]
\end{theorem}
\begin{algorithm}{TEST}{Test Algorithm}\label{alg:TEST}%
\lipsum[2]
\end{algorithm}
The following link points to the theorem instead of the algorithm: \ref{alg:TEST}.
\end{document}
答案1
您需要在適當的位置設定錨點。這是在\refstepcounter
發出時自動完成的,但在設定時您必須手動執行此操作,而\@currentlabel
無需計數器的幫助。
可以設定一個錨點\phantomsection
(儘管這是一個壞名字)。
\makeatletter
\newenvironment{algorithm}[2]%
{\medbreak
\edef\@currentlabel{#1}%
% more stuff here (put entry in table of algorithms, etc.)
\noindent\phantomsection % <------------------------ add the anchor
\textbf{Algorithm~\@currentlabel\ (#2)}\hfill\break
\ignorespaces}%
{\medbreak}
\makeatother
答案2
您可以使用套件\hyperlink
和\hypertarget
巨集。它們不需要任何計數器、\refstepcounter
操作或重新定義\@currentlabel
。
插入
\hypertarget{<anchor name>}{<some text>}
位置到哪個讀者應該跳起來。插入
\hyperlink{<anchor name>}{<other text>}
一個或多個位置從中讀者應該跳到文件中其他地方透過\hypertarget
指令指定的位置。
一個非常簡單的例子:
\documentclass{article}
\usepackage[colorlinks=true,linkcolor=blue]{hyperref}
\begin{document}
\hypertarget{jump_destination}{\textbf{A wonderful tale}}
Once upon a time, \dots
\clearpage
If you want to read a wonderful tale, click \hyperlink{jump_destination}{here}.
\end{document}
第二頁上的「這裡」一詞將以藍色顯示,點擊它會轉到上一頁的「一個精彩的故事」行。
可以有多條指令指向同一個錨點名稱,但對於給定的錨點名稱\hyperlink
應該只有一條指令。\hypertarget
將這些想法應用到您的測試程式碼中,它可能如下所示:
\documentclass{article}
\usepackage{lipsum,amsthm,hyperref}
\newtheorem{theorem}{Theorem}[section]
\newenvironment{algorithm}[2]%
{\par\medbreak\noindent
% more stuff here (put entry in table of algorithms, etc.)
\hypertarget{#1}{\textbf{Algorithm~#1 (#2)}}%
\par\noindent\ignorespaces}%
{\medbreak}
\begin{document}
\section{Test}
\begin{theorem}
\lipsum[1]
\end{theorem}
\begin{algorithm}{TEST}{Test Algorithm}
\lipsum[2]
\end{algorithm}
\clearpage
The following link now points to the algorithm: \hyperlink{TEST}{here}.
\end{document}