定義相同的 \label 兩次

定義相同的 \label 兩次

我正在創建一個文檔(主),其中經常調用其他文檔(其他)的部分。我遇到的問題是,當使用交叉引用時,\label每次將(其他)部分再次呼叫到(主)時,都會重寫,因為相同的命令出現在不同的(進一步的)部分中。有沒有解決的辦法?\ref\label\label

例如,下面的程式碼給出了以下圖像,這是我不想要的:

\documentclass{article}
\usepackage{catchfilebetweentags}

\begin{document}

Hello there.

\ExecuteMetaData[example2]{tag}

\ExecuteMetaData[example2]{tag}

Hello there. 

\end{document}

其中另一個檔案 example2 是:

\documentclass{article}
\usepackage{catchfilebetweentags}
\begin{document}

This is some text to fill space. This is some text to fill space.

%<*tag>
\section{Hello}
\subsection{Hello There}\label{1}
\subsubsection{Hello There, as seen in \ref{1}.}
%</tag>

\end{document}

在此輸入影像描述

這就是我想要的:

在此輸入影像描述

我不能每次都更改標籤,因為我只想回憶同一個文件。我想到的一個解決方案是在每個文件中使用不同的標籤導入重複的文件,但我寧願不這樣做(全部更新它們會很乏味)。

答案1

下面的程式碼提供了\newdocumentimport新增一個字首到每個\label\ref(and \pageref) 是連續的。這樣,您\newdocumentimport就可以在匯入新文件之前調用,所有\label文件和\ref文件都將添加字首。您也可以使用強制使用固定前綴\setfixedprefix{<prefix>}

在此輸入影像描述

\documentclass{article}

% Counter to keep track of new document imports
\newcounter{newdocumentimport}

\AtBeginDocument{
  \let\oldlabel\label% Store \label in \oldlabel
  \let\oldref\ref% Store \ref in \oldref
  \let\oldpageref\pageref% Store \pageref in \oldpageref
}

% Establish a new document import
\newcommand{\newdocumentimport}{%
  \stepcounter{newdocumentimport}%
  \renewcommand{\label}[1]{\oldlabel{\thenewdocumentimport-##1}}%
  \renewcommand{\ref}[1]{\oldref{\thenewdocumentimport-##1}}%
  \renewcommand{\pageref}[1]{\oldpageref{\thenewdocumentimport-##1}}%
}
\newcommand{\setfixedprefix}[1]{%
  \renewcommand{\label}[1]{\oldlabel{#1-##1}}%
  \renewcommand{\ref}[1]{\oldref{#1-##1}}%
  \renewcommand{\pageref}[1]{\oldpageref{#1-##1}}%
}

\begin{document}

\section{Hello}
\subsection{Hello There}\label{1}
\subsubsection{Hey There, as seen in \ref{1}.}

%same document imported again
\newdocumentimport

\section{Hello}
\subsection{Hello There}\label{1}
\subsubsection{Hey There, as seen in \ref{1}.}

\end{document}

上述選項也應該適用於hyperref,自 儲存起\label\ref\pageref延遲至\AtBeginDocument


用於自動化處理方式全部使用導入的文件catchfilebetweentags,您可以在序言中使用以下內容:

\usepackage{catchfilebetweentags}
\let\oldExecuteMetaData\ExecuteMetaData
\renewcommand{\ExecuteMetaData}{\newdocumentimport\oldExecuteMetaData}

這將放在\newdocumentimport前面每一個 \ExecuteMetaData,允許您的程式碼保持原樣,而無需更改任何內容。

相關內容