1

I was trying to get edge labels to automatically appear to the left or the right of edges, depending on whether the corresponding node in the tree was a left or a right daughter. When I insert the code manually it works, but when I write a macro for it, I get an error message ('I do not know the key '/tikz/if n', to which you passed [...] and I am going to ignore it.') This is a MWE:

\documentclass{article}
\usepackage{forest}

\newcommand{\edgelab}[1]{if n=1{edge label={node[midway,left]{#1}}}{edge label={node [midway, right]{#1}}}}

\title{}
\author{}
\date{}

\begin{document}
\maketitle

\begin{forest}
[S
    [A, if n=1{edge label={node[midway,left]{a}}}{edge label={node [midway, right]{b}}}]
    [B, \edgelab{b}]
]
\end{forest}

\end{document}

The definition of \edgelab should - apart from the argument - be identical to the code I put after the A node (because I copypasted it.) This is my output:

enter image description here

So, what did I do wrong? (And, if you know, is there a way to put the if-clause within the node[]?)

Edit: Made my code more clearly reflect that I want to be able to give the edges individual labels.

1 Answer 1

3

You should write a style, a macro.

\documentclass{article}
\usepackage{forest}

\forestset{
  edgelab/.style={if n=1{edge label={node[midway,left]{#1}}}{edge label={node [midway, right]{#1}}}}
}

\title{}
\author{}
\date{}

\begin{document}
\maketitle

\begin{forest}
[S
    [A, if n=1{edge label={node[midway,left]{a}}}{edge label={node [midway, right]{b}}}]
    [B, edgelab=b]
]
\end{forest}

\end{document}
3
  • Would you know why it isn't possible to do the same with \newcommand? Shouldn't it behave the same as if I simply wrote that code wherever I use it?
    – sgf
    Commented Jul 14, 2016 at 14:23
  • The answer lies in the details of how pgfkeys works. While your macro gets expanded, pgfkeys thinks it's a key name (it searches for = before the expansion). For instructions on how to use pgfkeys, see section 82 of PGF manual. Commented Jul 15, 2016 at 0:01
  • Thanks! I was hoping I could get away without learning how to do pgf and tikz :) Thanks for forest anyways, it's a great package (powerful while letting you do the basics without having a clue how the thing works)!
    – sgf
    Commented Jul 15, 2016 at 17:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .