如何找出文档中最大的((sub)sub)节编号?

如何找出文档中最大的((sub)sub)节编号?

我想创建一个数字,a/b其中a表示当前部分(简单)和b文档中的最大部分编号(我正在努力解决)。对于子部分和子子部分也是如此。对于下面的示例,它应该是2/3.1/1.3/4。我如何找出文档中的最大((子)子)部分编号?

更新:在 David 的评论之后,我习惯于\label{}参考最后一个 ((sub)sub) 节。但是,对于子节和子子节,\ref{}也包括节或子节编号。如何避免这种情况?

\documentclass{article}

\usepackage{units}

\newcommand\sectionnum{\arabic{section}}
\newcommand\subsectionnum{\arabic{subsection}}
\newcommand\subsubsectionnum{\arabic{subsubsection}}

\begin{document}
\section{Section 1}
\section{Section 2}
\subsection{Subsection 2.1}\label{lastsubsec}
\subsubsection{Subsubsection 2.1.1}
\subsubsection{Subsubsection 2.1.2}
\subsubsection{Subsubsection 2.1.3}
Now we are in Section \nicefrac{\sectionnum}{\ref{lastsec}}.\nicefrac{\subsectionnum}{\ref{lastsubsec}}.\nicefrac{\subsubsectionnum}{\ref{lastsubsubsec}}
% should give 2/3.1/1.3/4
\subsubsection{Subsubsection 2.1.4}\label{lastsubsubsec}
\section{Section 3}\label{lastsec}
\end{document}

答案1

感谢 David 的评论和提示,以及这篇文章这里,我想出了以下解决方案:

\documentclass{article}

\usepackage{units}

% for referring to single subsection and subsubsection numbers
% see https://tex.stackexchange.com/questions/159299/ref-to-subsection-number-only/166676#166676
\makeatletter
\def\@firstoftwo@second#1#2{%
  \def\temp##1.##2\@nil{##2}%
   \temp#1\@nil}
\newcommand\sref[1]{\expandafter\@setref\csname r@#1\endcsname\@firstoftwo@second{#1}}
\def\@firstoftwo@third#1#2{%
  \def\temp##1.##2.##3\@nil{##3}%
   \temp#1\@nil}
\newcommand\ssref[1]{\expandafter\@setref\csname r@#1\endcsname\@firstoftwo@third{#1}}
\makeatother

\begin{document}
\section{Section 1}
\section{Section 2}
\subsection{Subsection 2.1}\label{lastsubsec}
\subsubsection{Subsubsection 2.1.1}
\subsubsection{Subsubsection 2.1.2}
\subsubsection{Subsubsection 2.1.3}
Now we are in Section \nicefrac{\arabic{section}}{\ref{lastsec}}.\nicefrac{\arabic{subsection}}{\sref{lastsubsec}}.\nicefrac{\arabic{subsubsection}}{\ssref{lastsubsubsec}}
% should give 2/3.1/1.3/4
\subsubsection{Subsubsection 2.1.4}\label{lastsubsubsec}
\section{Section 3}\label{lastsec}
\end{document}

相关内容