定义新命令时出错

定义新命令时出错

我正在尝试在我的 Latex 文件中定义一个新命令,如下所示

\newcommand{\newchunk}[1][2]{\section{#2}\label{sec:#1}\quad}

但是在 Latex 编译后我得到以下错误

ERROR: Illegal parameter number in definition of \\newchunk.

--- TeX said ---
<to be read again> 
                   2
l.58 ...nk}[1][2]{\section{#2}\label{sec:#1}\quad}

--- HELP ---
This is probably caused by a \newcommand, \renewcommand,
\newenvironment, or \renewenvironment command in which a # is used
incorrectly.  A # character, except as part of the command name \#,
can be used only to indicate an argument parameter, as in #2, which
denotes the second argument. This error is also caused by nesting one
of the above four commands inside another, or by putting a parameter
like #2 in the last argument of a \newenvironment or \renewenvironment
command.

我们不是用来#2指代第二个参数吗?我哪里错了?

答案1

\newcommand{\newchunk}[1][2]{\section{#2}\label{sec:#1}\quad}

定义一个命令\newchunk,使其具有一个可选参数,该参数的默认值为2。看起来你正在定义一个可以接受包含 的可选参数的命令\label。这里有一个建议:

\documentclass{article}

\newcommand{\newchunk}[2][]{%
  \section{#2}%
  % https://tex.stackexchange.com/q/53068/5764
  \if\relax\detokenize{#1}\relax\else
    \label{sec:#1}%
  \fi
}

\begin{document}

\newchunk{First}

See section~\ref{sec:second}.

\newchunk[second]{Second}

\end{document}

上面的代码\newchunk有两个参数,第一个是可选的标签字符串,用于\label。将检查用户是否提供了任何内容。如果提供了内容,则将其用作\label,否则不\label发出任何内容。第二个参数是必需的,用作\section标题。

答案2

\newcommand{<command>}[<number of arguments>]{<what the command does>}

的第二个参数\newcommand需要命令所采用的参数数量。因此,您需要执行

\newcommand{\newchunk}[2]{\section{#2}\label{sec:#1}\quad}

相关内容