
새 카운터를 다음과 같이 정의했습니다.
\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가 언급했듯이 ( )를 참조하여 해당 하위 섹션과 일치 해야 할 경우를 대비하여 with를 정의합니다 .):\protect
\lecID
\DeclareRobustCommand
\lecId
\refstepcounter
lecCounter
\lecCounter
\DeclareRobustCommand{\lecID}{\refstepcounter{lecCounter}\thelecCounter}
게다가, after는 \lecID
나타날 때마다 실행되며, lecCounter
with와 같은 다른 곳에 나타날 때 부적절하게 증가됩니다 \tableofcontents
. 따라서 선택적 인수인 of를 사용하여 \subsection
카운터 없이 카운터만 넣고 값을 변경합니다 \stepcounter
. 따라서 LaTeX는 처음 볼 때만 \refstepcounter
증가합니다 .lecCounter
\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}