沒有標籤的參考章節或章節?

沒有標籤的參考章節或章節?

是否可以引用文件的章節,而無需手動標記每個章節和小節?

我有大約 8 章和幾十個縮排的章節/小節,為每個章節加上標籤是相當乏味的。

有沒有更快、更方便的方法呢?

答案1

這是可以做到的,但可能有風險;在下面的範例中,每次呼叫 或 時\chapter,都會採用每個章節的第一個單字來自動建立標籤\sectiontitlesec以其explicit選項被用來搶奪頭銜;使用xstring,提取第一個單字:

\documentclass[10pt]{book}
\usepackage[explicit]{titlesec}
\usepackage{xstring}

\titleformat{\chapter}[display]
{\normalfont\huge\bfseries}{\chaptertitlename\ \thechapter}{20pt}{\Huge\StrBefore{#1}{ }[\mlabel]#1\label{\mlabel}}
\titleformat{\section}
{\normalfont\Large\bfseries}{\thesection}{1em}{\StrBefore{#1}{ }[\mlabel]#1\label{\mlabel}}

\begin{document}

Some references to chapters: \ref{Some} and \ref{Other} and some references to sections: \ref{A} and \ref{Another}
\chapter{Some Chapter}
\section{A Test Section}
\chapter{Other Chapter}
\section{Another Test Section}

\end{document}

在此輸入影像描述

如果兩個分割單元的標題中具有相同的首字母,則此操作將會失敗,但您可以選擇不同的字串來建立標籤。

在我最初的解決方案中,我假設標題至少包含一個空格,但可以使用另一個字串;例如(如尼古拉·羅斯托夫的答案)部門單位的全名。在這種情況下,不再需要 xstring 包,可以簡單地說

\documentclass[10pt]{book}
\usepackage[explicit]{titlesec}

\titleformat{\chapter}[display]
{\normalfont\huge\bfseries}{\chaptertitlename\ \thechapter}{20pt}{\Huge#1\label{#1}}
\titleformat{\section}
{\normalfont\Large\bfseries}{\thesection}{1em}{#1\label{#1}}

\begin{document}

Some references to chapters: \ref{Some Chapter} and \ref{Other Chapter} and some references to sections: \ref{A Test Section} and \ref{Another Test Section}
\chapter{Some Chapter}
\section{A Test Section}
\chapter{Other Chapter}
\section{Another Test Section}

\end{document}

我的例子只展示了章節和章節的機制,但它可以很容易地擴展到其他章節單元。

答案2

您可以使用完整標題將章節或章節作為標籤,並透過它們自己的標題來引用它們。

\documentclass{book}

\let\origchapter=\chapter
\let\origsection=\section

\renewcommand\chapter[1]{\origchapter{#1}\label{#1}}    
\renewcommand\section[1]{\origsection{#1}\label{#1}}

\begin{document}

\chapter{My first chapter}

\section{My first section}

I said in section~\ref{My first section} at the
beginning of chapter~\ref{My first chapter} that

\end{document}

答案3

您可以自動化標籤建立流程。一個非常基本的 Perl 腳本就可以做到這一點。 Perl 腳本必須全域化所有.tex文件,並逐一對它們執行替換正規表示式。以下是您應該使用的正規表示式的範例:

my $input_str = do{ local $/; <> };
$input_str =~ s/(\\section{(.*?)}(?!\s*\\label))/$1\n\\label{sec:$2}/mg;
$input_str =~ s/(\\chapter{(.*?)}(?!\s*\\label))/$1\n\\label{chap:$2}/mg;
print $input_str;

這兩個正規表示式將簡單地在您的 tex 程式碼中找到每個\chapter{Chapter Title}和。\section{Section Name}如果之後定義了標籤,腳本將忽略它們。如果沒有,腳本將在新行中為它們添加一個標籤語句,內容為\label{chap:Chapter Title}\label{sec:Section Name}。您可以建立此 perl 腳本並在建立新的章節/章節時執行它。

免責聲明:對於您在文件上運行正則表達式時可能遇到的任何資料遺失,我不承擔任何責任.tex。雖然我測試了上面的正規表示式,但我故意不包含完整的 perl 腳本的程式碼,以避免這種風險。如果您將我的 Perl 程式碼剪下並貼上到腳本中,然後在檔案上執行,您仍然可以查看正在運行的 Perl 程式碼.tex。它將運行並在螢幕上列印結果,而無需修改您的檔案。確保編寫您自己的 Perl 腳本並在虛擬.tex文件上測試它。另外,請確保在運行此類腳本之前始終獲取您的工作副本。

相關內容