latex -\newcommand/\newenvironment-可选参数

标签 latex newenvironment renewcommand

我正在尝试自己的命令和环境,现在遇到了这些问题:


如何创建命令\foo{parameter}[optional]或称为\begin{bar}{parameter}[optional]的环境?
如何创建命令\foo[optional_1]...[optional_n]{parameter}


我试过了

\newcommand{\foo}[3][][]{#1#2#3}    - failed
\newcommand{\foo}[3][2][][]{#1#2#3} - failed


有人知道一些提示吗?非常感谢。

最佳答案

使用xparse软件包(LaTeX3开发工作的一部分):

\usepackage{xparse}
\NewDocumentCommand\foo{O{}O{}m}{%
  % Code with optional #1 and #2 with empty defaults
}
\NewDocumentCommand\foo{mO{}}{%
  % Code with optional #2 with empty default
}
\NewDocumentEnvironment{foo}{O{}}{%
% Start code with optional #1
}{%
%  End code with optional #1
}


可选参数在xparse中与\ newcommand有所不同。您可以检测是否给出了:

\NewDocumentCommand\foo{mo}{%
  \IfNoValueTF{#2}
   {Code without #2}
   {Code with #2}%
}


您会看到这通过使用小写字母'o'起作用,而大写字母'O'然后需要一个默认值(我通过包含一个空组将其设为空)。

关于latex -\newcommand/\newenvironment-可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2908908/

相关文章:

latex - 如何在 LaTeX 中将目录标题居中?

latex - 如何在 LaTeX 中对齐方程组?

matlab - 如何在 MATLAB 中的图形的 ylabel 上编写方程?

emacs - 通过emacs加载绘图程序

latex - 如何使用 LaTeX 在表格末尾创建带有标题的自定义表格环境?

latex - 在 LaTeX 中创建新环境的问题

latex - 如何重新定义带有参数的带星号的 LaTeX 命令?

latex - 如何使用\renewcommand 取回我的希腊字母?