\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のオプション引数を使用します。したがって、LaTeXはを最初に見つけたときのみ増加します。\subsection\stepcounter\refstepcounterlecCounter\subsection

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

脆弱なコマンドと移動する引数の問題については、ここでさらに詳しく説明されています。Fragile コマンドと Robust コマンドの違いは何ですか?

\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}

結果を表示しています

関連情報