如何定义以 []{} 而不是 {}{} 作为参数的 newcommand?

如何定义以 []{} 而不是 {}{} 作为参数的 newcommand?

我发现自己做了很多类似下面这样的事情,以便为 pdf 和 tex4ht 编译文档

\ifdefined\HCode
  \includegraphics[width=0.5\paperwidth]{foo.eps}
\else
  \includegraphics[width=0.5\paperwidth]{foo.pdf}
\fi

于是我突然想,为什么不写一个命令\includegraphicsX并在其中实现这个逻辑呢?所以代码将如下所示:

\includegraphicsX[width=0.5\paperwidth]{foo}

问题是 \newcommand只喜欢使用接受参数{}{},所以我不得不\newcommand像这样写:(MWE)

\documentclass[11pt,notitlepage]{article}%
\usepackage{graphicx}
\newcommand{\includegraphicsX}[2]
{
\ifdefined\HCode
  \includegraphics[#1]{#2.eps}
\else
  \includegraphics[#1]{#2.pdf}
\fi
}
\begin{document}
\includegraphicsX{width=0.1\paperwidth}{1_pic}
\end{document}

上述操作可行。但我更喜欢使用以下命令调用命令

    \includegraphicsX[width=0.1\paperwidth]{1_pic}

而不是像 MWE 中显示的那样

   \includegraphicsX{width=0.1\paperwidth}{1_pic}

原因是,如果我稍后改变主意(我改变了主意)并且不想再使用宏,那么我只需要使用编辑器查找/替换从调用中删除一个字母“X”,而不是同时更改第一个参数周围的括号,因为这很难自动更改。

是否有一个技巧可以在 Latex 中定义一个命令,该命令接受[]作为第一个参数而不是作为{}

使用 Tl 2015

答案1

用于\newcommand\commandname[2][]{<code>}标准\commandname[<optional arg>]{<required arg>}语法。

\documentclass[11pt,notitlepage]{article}%
\usepackage{graphicx}
\newcommand{\includegraphicsX}[2][]
{%
\ifdefined\HCode
  \includegraphics[#1]{#2.eps}%
\else
  \includegraphics[#1]{#2.pdf}%
\fi
}
\begin{document}
\includegraphicsX[width=0.1\paperwidth]{1_pic}
\end{document}

我的答案关于创建命令和环境的更普遍的问题可能会引起人们的兴趣。

请注意,你可能只需要使用

\newcommand\includegraphicsX[2][]{%
  \includegraphics[#1]{#2}}

其中,曼努埃尔指出\includegraphicsX[]{}相当于\includegraphics[]{},所以您实际上根本不需要为此用途创建新命令。如果您的实际定义更复杂,显然您仍然需要它,但也许可以使用上面的方法稍微简化它。

graphicx可以根据所使用的引擎等找出适当的扩展,通常最好不要明确指定这些。

答案2

这是xparse定义带有可选参数的命令的样式,这里带有默认的空可选参数。

\documentclass[11pt,notitlepage]{article}%
\usepackage{xparse}
\usepackage{graphicx}
\NewDocumentCommand{\includegraphicsX}{O{}m}{%
  \ifdefined\HCode
  \includegraphics[#1]{#2.eps}
  \else%
  \includegraphics[#1]{#2.pdf}
  \fi%
}
\begin{document}
\includegraphicsX[width=0.1\paperwidth]{1_pic}
\end{document}

相关内容