编辑:对于带有 TikZ 的 PerlTeX 的一些非常酷(且有效)的示例,请参阅此TUGboat 文章!
我相信这是因为 TikZ 图片的语法通常比 LaTeX 更自由。我可以看到,在将 tikz 命令放入宏时,在 pgfmanual 中,宏包含 tikzpicture 环境(例如参见 pgfmanual.pdf 的第 223 页,即库部分 (IV) 的第一页)。
我知道我会打破记录,但对于定义复杂的宏,我建议尽可能使用 PerlTeX。这允许定义更复杂的宏,并且还允许避免一些扩展后的混乱。
编辑:下面的(见旧)不起作用,因为 PerlTeX 宏必须返回完整的 TikZ 命令,为此我模拟了这个版本。新的命令树采用三个参数,即根名称、根节点参数,然后是您最初拥有的三个命令,但设置不同。每个子命令用冒号 (:) 分隔,三个原始命令用逗号 (,) 分隔。也许更容易看到代码本身。同样,编译命令与 OLD 中的相同。
\documentclass{article}
\usepackage{perltex}
\usepackage{tikz}
\perlnewcommand{\tree}[3]{
my ($root,$root_opts,$children) = @_;
my @children = split(/\:/, $children);
my $return = '';
$return .= sprintf( "\\node{%s} \[%s\]\n", $root,$root_opts);
foreach my $child (@children) {
my ($edge, $vertex, $child_nodes) = split(/,/, $child);
$child_nodes ||= '';
$return .= sprintf("child { node{%s} %s edge from parent node[above]{%s} }\n",$vertex,$child_nodes,$edge);
}
$return .= "\;\n";
return $return;
}
\begin{document}
\begin{tikzpicture}
% \node{0} [grow'=right]
% child { node{1} edge from parent node[above]{0} }
% child { node{0} edge from parent node[above]{1} };
\tree{0}{grow'=right}{0,1:1,0}
\end{tikzpicture}
\end{document}
--- 从旧开始 ---
我试图一起破解一些东西,但它没有编译(可能是因为我从未使用过 TikZ 来制作树)。也就是说,也许问题在于没有让 PerlTeX 完成足够的 TikZ 命令。将 perl 哈希转换为 TikZ 树可能是一个非常酷的项目。无论如何它是。请注意,您使用以下命令编译它perltex --latex=pdflatex text.tex
:
\documentclass{article}
\usepackage{perltex}
\usepackage{tikz}
\perlnewcommand{\tchild}[3]{
my ($edge, $vertex, $child) = @_;
$child ||= '';
my $return = 'child { node{' . $vertex . '} ' . $child . ' edge from parent node[above]{' . $edge . '} }';
return $return;
}
\begin{document}
\begin{tikzpicture}
\node{0} [grow'=right]
\tchild{0}{1}{}
\tchild{1}{0}{}
;
\end{tikzpicture}
\end{document}
--- 结束旧 ---
说了这么多,也许你的问题是你如何对待可选的#3,也许如果你真的把那个可选而不是定义和清空它会更好(即,\tchild[]{0}{1})。