\def\@dnode[#1]#2#3#4{\node(#2)at(#3){#4};}
的问题,#1
没有传进去,改为
\def\@dnode[#1]#2#3#4{\node[#1](#2)at(#3){#4};}
- LaTeX2e 提供了
\newcommand
命令可以定义一个带可选参数的命令,此外可以看看xparse
宏包,其基于LaTeX3
更加灵活
\makeatletter
\def\@dnode[#1]#2#3#4{\node[#1](#2)at(#3){#4};}
\def\dnode{\@ifnextchar[{\@dnode}{\@dnode[inner sep=2pt,fill=yellow]}}
\makeatother
\begin{tikzpicture}
\dnode{a}{1,2}{\LaTeX}
\dnode[draw,fill=red]{b}{3,2}{hello!}
\end{tikzpicture}
典型宏展开问题
报错信息如下
Package pgfkeys: I do not know the key '/tikz/\inns {2}' and I am going to ignore it. Perhaps you misspelled it.
也就是说 tikz
将 \inns{2}
(还没展开成 inner sep=2pt
) 当作了键值, 但是它无法识别,为此我们必须改变 \node
和 \inns
两个命令的展开顺序,做如下修改
- 不使用
\NewDocumentCommand
来定义要展开的命令,使用\def
或者\newcommand
\newcommand{\inns}[1]{inner sep=#1pt}
- 改变宏展开顺序
\expandafter\node\expandafter[\inns{2}](b)at(1,0){B};
mwe
\documentclass{article}
\usepackage{tikz}
\begin{document}
\NewDocumentCommand\tik{m}{
\begin{tikzpicture}
#1
\end{tikzpicture}
}
\newcommand{\inns}[1]{inner sep=#1pt}
\tik{
\node(a)at(0,0){A};
\expandafter\node\expandafter[\inns{2}](b)at(1,0){B};
\draw(a)--(b);
}
\end{document}
另外 \NewDocumentCommand
命令定义的命令是受保护的,但是 xparse 包也提供了 \NewExpandableDocumentCommand
,但经过测试失败,不知为何
问 关于自定义宏命令 \def 的可选参数的一个问题