latex - 在 tikzpictures 中使用宏?

标签 latex macros tikz

我试图压缩一个 tikzpicture使用以下 newcommand :

\newcommand{\tchild}[3]{ child { node{#2} #3 edge from parent node[above]{#1} } }
%intended usage: \tchild{edge label}{vertex label}{child nodes}

如果我将其应用于以下示例,则会得到一份工作文档。然而,在下面给出的例子中 pdflatex给出 Package pgf Error: No shape named is known. (注意“named”和“is”之间的双空格)。如果我手动展开第二个 tchild我也拿到了一份工作文件。任何想法这里出了什么问题?
\begin{tikzpicture}
    \node{0} [grow'=right]
        \tchild{0}{1}{}
        \tchild{1}{0}{};
\end{tikzpicture}

最佳答案

编辑:有关带有 TikZ 的 PerlTeX 的一些非常酷(和有效)的示例,请参阅此 TUGboat article !

我相信这是因为 TikZ 图片的语法通常比 LaTeX 更自由。我可以看到,在将 tikz 命令放入宏时,在 pgfmanual 中,宏包含 tikzpicture 环境(例如参见 pgfmanual.pdf 的第 223 页,即库部分 (IV) 的第一页)。

我知道我会成为一个破记录,但为了定义复杂的宏,我建议尽可能使用 PerlTeX。这允许定义更复杂的宏,并且还允许避免一些 expandafter 困惑。

编辑:下面(参见旧)不起作用,因为 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})。

关于latex - 在 tikzpictures 中使用宏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4117645/

相关文章:

svg - 使用 dvisvgm 问题将 DVI 转换为 SVG

latex - 在 R Markdown Beamer 中更改内联代码的颜色

r - 在 lyx 中使用 tikzDevice 不起作用

latex - 使用 pgf/tikz 创建欧元符号

c - 在另一个宏中使用字符串宏

c++ - 这个foreach宏实现有没有问题

macros - Julia 宏中的无效赋值错误

Tikz 思维导图覆盖特定节点的水平距离和同级角度

latex - LaTex 顶部的边距

r - 列表包中 R 代码块的颜色