如何使用 \ref{} 以格式化方式引用多個計數器?

如何使用 \ref{} 以格式化方式引用多個計數器?

我的文檔中有兩個計數器,counterA並且counterB.

我希望將\ref{}文檔中的引用列印為1.a)2.等,其中數字指的是counterA,字母為counterB

是否可以?我該怎麼做?

\documentclass{article}
\begin{document}

\newcounter{counterA} 
\setcounter{counterA}{0}

\newcounter{counterB}
\setcounter{counterB}{0}


\refstepcounter{counterA}
\refstepcounter{counterB}
\label{First_Label}

I get: \ref{Second_Label}. I would like \textbf{2.}\,b)

Vestibulum lectus metus, tincidunt at fermentum non, pellentesque at lorem. Vivamus nisl sem, tempor ac mi et, elementum feugiat justo. Pellentesque tristique consequat molestie.


\bigskip
\refstepcounter{counterA}
\refstepcounter{counterB}
\label{Second_Label}

I get: \ref{First_Label}. I would like \textbf{1.}\,a)

Morbi nec nibh nulla. Cras posuere erat vitae lacus convallis, ut consequat urna dignissim. 
\end{document}

在此輸入影像描述

答案1

每次counterB使用\newcounter指令建立一個名為 的計數器變數時,LaTeX 都會設定一個名為 的宏,\p@counterB該宏可用於在標籤上「新增」一些其他信息,以便建立交叉引用。即,你可以輸入

\makeatletter
\renewcommand\p@counterB{\thecounterA.}
\makeatother

將目前值的 LaTeX 表示形式counterA加上 a.前綴到 的值的 LaTeX 表示形式counterB

完整的 MWE:

在此輸入影像描述

\documentclass{article}
\newcounter{counterA}
\newcounter{counterB}
\renewcommand\thecounterA{\arabic{counterA}} % arabic numbering
\renewcommand\thecounterB{\alph{counterB})}  % alphabetic numbering
\makeatletter
\renewcommand\p@counterB{\thecounterA.}
\makeatother
\begin{document}
% need to increment the counters via \refstepcounter
\refstepcounter{counterA} \label{refA}
\refstepcounter{counterB} \label{refB}
Here's a cross-reference to item \ref{refB}.
\end{document}

答案2

您可以使用以下命令:

\renewcommand{\thecounterB}{\textbf{\thecounterA}.\alph{counterB})}

這是一個完整的 MWE:

% arara: pdflatex
\documentclass{article}

\newcounter{counterA} 
\setcounter{counterA}{0}

\newcounter{counterB}
\setcounter{counterB}{0}

\renewcommand{\thecounterB}{\textbf{\thecounterA}.\alph{counterB})}
\begin{document}

\refstepcounter{counterA}
\refstepcounter{counterB}
\label{First_Label}

I get: \ref{Second_Label}. I would like \textbf{2.}\,b)

Vestibulum lectus metus, tincidunt at fermentum non, pellentesque at lorem. Vivamus nisl sem, tempor ac mi et, elementum feugiat justo. Pellentesque tristique consequat molestie.


\bigskip
\refstepcounter{counterA}
\refstepcounter{counterB}
\label{Second_Label}

I get: \ref{First_Label}. I would like \textbf{1.}\,a)

Morbi nec nibh nulla. Cras posuere erat vitae lacus convallis, ut consequat urna dignissim. 
\end{document}

相關內容