\label および \ref コマンドを再定義して、\caption または \captionof の隣でなくても機能するようにします。

\label および \ref コマンドを再定義して、\caption または \captionof の隣でなくても機能するようにします。

私は次のように、 nor の後に\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

\captionまたは の後にこのコマンドのペアを置くことなく\captionof、方程式、図、表など、通常参照するすべてのものを引き続き参照する機能を失わずに使用する方法はありますか?

答え1

コマンド\labelは、内部マクロに基づいてラベルの値を保存します\@currentlabel。このマクロは、 などのコマンド\sectionや などの環境によって設定されます\begin{figure}。ただし、自分で設定することもできます。その場合、次の\labelコマンドは指定した値を取得します。

\@currentlabelはシンボルを含む内部マクロであるため、マクロを使用するコードの前後にと が@必要です。次の MWE は (拡張定義) を使用してマクロに値を割り当て、カウンターが実際の値で表されるようにします。\makeatletter\makeatother\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}

結果 (ラベルを補助ファイルに書き込んで再度読み込む 2 回のコンパイル後):

ここに画像の説明を入力してください

上記のコードは、内部ラベル値を設定し、その後これを のようなラベルに割り当てるという原理を説明することを目的としています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}

ここに画像の説明を入力してください

関連情報