重新定義 \label 和 \ref 指令,以便它們也可以運作而不必位於 \caption 或 \captionof 旁邊

重新定義 \label 和 \ref 指令,以便它們也可以運作而不必位於 \caption 或 \captionof 旁邊

我一直在嘗試在or之後使用\labeland ,如下所示:\ref\caption\captionof

Figure \Roman{chapter}.\arabic{figure}: The caption % A manually created caption
\label{fig:the_ref_name} % the ref that sould ref the \Roman{chapter}.\arabic{figure} number

有沒有一種方法可以使用這對命令,而無需將它們放在\captionor之後\captionof,但這樣我就不會失去繼續引用方程式、圖形、表格以及您通常會做的所有內容的能力?

答案1

\label命令根據內部巨集儲存標籤的值\@currentlabel。該宏由諸如 之類的命令\section和諸如 之類的環境設定\begin{figure}。不過,您也可以自己設置,然後下一個\label命令將採用您指定的值。

因為\@currentlabel是包含該符號的內部宏@,所以您需要使用該宏的程式碼周圍的\makeatletter和。\makeatother以下 MWE 使用\edef(擴充定義)為巨集指派一個值,這可確保計數器由實際值表示。

\documentclass{report}
\begin{document}
\chapter{My chapter}
\setcounter{figure}{8} % set the figure counter to some number for illustration purposes
Figure \Roman{chapter}.\arabic{figure}: The caption % A manually created caption
\makeatletter\edef\@currentlabel{\Roman{chapter}.\arabic{figure}}\makeatother% set value for use by \label
\label{fig:the_ref_name} % assign the label
\section{New section}
As we have seen in Figure \ref{fig:the_ref_name}, figures can have captions.
\end{document}

結果(經過兩次編譯將標籤寫入輔助文件並讀回):

在此輸入影像描述

上面的程式碼旨在說明設定內部標籤值並隨後將其指派給類似 的標籤的原理fig:the_ref_name。然而,這當然不太實用。您可以編寫一個小宏來產生標題並同時設定標籤值:

\documentclass{report}
\makeatletter
\newcommand{\customfigcaption}[1]{%
Figure \Roman{chapter}.\arabic{figure}: #1%
\edef\@currentlabel{\Roman{chapter}.\arabic{figure}}%
}
\makeatother

\begin{document}
\chapter{My chapter}
\setcounter{figure}{8}
\customfigcaption{The caption}
\label{fig:the_ref_name} % assign the label
\section{New section}
As we have seen in Figure \ref{fig:the_ref_name}, figures can have captions.
\end{document}

輸出與上面相同。

最後的補充是添加一個幻影部分,允許透過以下方式引用標籤hyperref

\documentclass{report}
\usepackage{hyperref}
\makeatletter
\newcommand{\customfigcaption}[1]{%
Figure \Roman{chapter}.\arabic{figure}: #1%
\csname phantomsection\endcsname%
\edef\@currentlabel{\Roman{chapter}.\arabic{figure}}%
}
\makeatother

\begin{document}
\chapter{My chapter}
\setcounter{figure}{5}
\customfigcaption{The caption}
\label{fig:the_ref_name} % assign the label
\section{New section}
As we have seen in Figure \ref{fig:the_ref_name}, figures can have captions.
\end{document}

在此輸入影像描述

相關內容