# Writing a macro for an edge label in tikz-qtree

I'm attempting to make my code more readable by replacing a long bit of text I intend to use several times with a macro.

Before I use the macro, I have the following code:

\documentclass{minimal}
\usepackage{tikz-qtree}
\newcommand{\llabel}[1]{\edge node[auto=left]{#1};}
\begin{document}
\begin{tikzpicture}
\Tree [.$P_1$ [.$P_2$ ]
\edge node[auto=left]{1,2}; [.$P_2$ ] ]
\end{tikzpicture}
\end{document}


This produces the correct output:

When I replace the edge label with my macro, the following code produces the following error:

\documentclass{minimal}
\usepackage{tikz-qtree}
\newcommand{\llabel}[1]{\edge node[auto=left]{#1};}
\begin{document}
\begin{tikzpicture}
\Tree [.$P_1$ [.$P_2$ ]
\llabel{1,2} [.$P_2$ ] ]
\end{tikzpicture}
\end{document}

Undefined control sequence.
\llabel #1->\edge
node[auto=left]{#1};
l.8 \end
{tikzpicture}


Is there a way to do this?

• \edge seems to be unknown outside of \Tree -- there is a premature expansion, unfortunately, of \llabel, trying to execute the \edge macro before it can be handed over to \Tree → this must fail – user31729 Mar 17 '16 at 20:40

If a different package is an option, Forest can support something like this quite easily. Rather than a macro, it would make sense to use a style llabel in this case. It is also possible to drop the dollar signs by using math content for the tree, reducing visual clutter.

In this example, I use the linguistics library to set up some suitable defaults. The style my tree sets the content of nodes to maths mode and enables the llabel=<text> style.

\documentclass[tikz,border=10pt,multi]{standalone}
\usepackage[linguistics]{forest}
\forestset{%
my tree/.style={%
for tree={%
math content,
},
llabel/.style={%
edge label={node [midway, auto=left]{##1}}
}
}
}
\begin{document}
\begin{forest}
my tree
[P_1
[P_2]
[P_2, llabel={1,2}]
]
\end{forest}
\end{document}