\stepcounter 在小節標題中不起作用

\stepcounter 在小節標題中不起作用

我將一個新計數器定義為:

\newcounter{lecCounter}
\newcommand{\lecID}{\stepcounter{lecCounter}\thelecCounter}

我希望將其用作:

\subsection{Lecture \lecID }

但它給了錯誤:

! Missing \endcsname inserted.
<to be read again> 
                   \csname\endcsname
l.1 \subsection{Lecture \lecID }

? 

如果我把它放在Lecture \lecID外面\subsection{},那麼它就會編譯。

解決方法是什麼?

答案1

不要\stepcounter在 的參數中使用\subsection。即使\protect為了避免錯誤而在其前面加上 ,但在\tableofcontents使用時也會產生不良影響。下面的範例清楚地顯示了這一點(我使用了\section,但它與 完全相同\subsection,只要它出現在目錄中即可)。

\documentclass{article}

\newcounter{lecCounter}
\newcommand{\lecID}{\protect\stepcounter{lecCounter}\thelecCounter}

\begin{document}

\tableofcontents

\section{Lecture \lecID}

Text.

\end{document}

在此輸入影像描述

你應該做的是定義一個新指令:

\newcommand{\lecture}{%
  \stepcounter{lecCounter}%
  \subsection{Lecture \thelecCounter}%
}

可以根據您的需求進行微調;例如,如果您需要參考講座編號而不是小節編號。另一種可能性是為特定講座標題新增可選參數。如果需要更改,最好將所有這些編碼到命令中,而不是追逐到文件中。

範例文件可能是

\documentclass{article}

\newcounter{lecCounter}
\newcommand{\lecture}{%
  \stepcounter{lecCounter}%
  \subsection{Lecture \thelecCounter}%
}

\begin{document}

\tableofcontents

\section{Group of lectures}

\lecture

Text.

\lecture

Text.

\end{document}

答案2

該命令\stepcounter是一個脆弱的命令,這意味著當將其放入移動參數中時可能會導致錯誤。參數\section是移動參數,因為 LaTeX 也將節名(參數)放在目錄和其他地方。您需要“保護”\stepcounter以確保它不會作為脆弱命令而導致問題。我們可以在使用它時放在前面,或者只是通過 定義\lecID為一個健壯的命令。 (正如 Mico 指出的,我們定義了 ,以防您可能需要引用( ),以便它與相應的小節相匹配。):\protect\lecID\DeclareRobustCommand\lecId\refstepcounterlecCounter\lecCounter

\DeclareRobustCommand{\lecID}{\refstepcounter{lecCounter}\thelecCounter}

此外,由於\lecID每次出現時都會執行,lecCounter因此當它出現在其他地方時(例如使用\tableofcontents.因此,我們使用可選參數 來\subsection僅放入計數器,而不放入\stepcounter\refstepcounter來更改值。因此,LaTeX 只會在lecCounter第一次看到時遞增\subsection

\subsection[Lecture \thelecCounter]{Lecture \lecID }

這裡更徹底地解釋了脆弱指令和移動參數的問題:脆弱指令和魯棒指令有什麼差別?

\documentclass{article}
\usepackage[utf8]{inputenc}

\documentclass{article}
\usepackage[utf8]{inputenc}

\newcounter{lecCounter}
\DeclareRobustCommand{\lecID}{\refstepcounter{lecCounter}\thelecCounter}

\begin{document}

\tableofcontents

\subsection[Lecture \thelecCounter]{Lecture \lecID}

\subsection[Lecture \thelecCounter]{Lecture \lecID}

\end{document}

顯示結果

相關內容