[Tex/LaTex] forest “every leaf node” and “every tree node” like syntax

foresttikz-qtreetikz-styles

I was seeing around that the forest package is better at drawing trees than tikz-qtree. I want to migrate my drawings, however, I can't find a way to easily format the tree.

I see that there are ways of defining styles and applying them to each node individually (like {Tikz}{Tree} How to reduce leaves placement). However, I want a syntax similar to tikz-qtree where you can say every leaf node or every tree node and that automatically all the nodes are formatted.

\documentclass[convert]{standalone}

\usepackage{tikz}
\usepackage{tikz-qtree}
\usepackage{forest}

\tikzset{
every leaf node/.style={draw=cyan, fill=cyan!50, ellipse, text width=1cm},
every tree node/.style={draw=blue, fill=blue!50, rectangle, text width=2cm, align=center, font=\ttfamily}
}

\begin{document}
\begin{tikzpicture}
\Tree [./
  [.usr 
    [.mji
      \texttt{sh.c}
    ]
  ]
  [.bin 
    \texttt{sh}
    \texttt{ls}
  ]
  ]
\end{tikzpicture}

\begin{forest}
  % insert here a similar "every leaf node"
  % insert here a similar "every tree node"
  [/
  [usr 
    [mji
      \texttt{sh.c}
    ]
  ]
  [bin 
    \texttt{sh}
    \texttt{ls}
  ]
  ]
\end{forest}

\end{document}

enter image description here

Best Answer

You can use

if n children={0}
  {<style(s) when no children are present>}
  {<style(s) when children are present>}

or the more customizable

if={n_children==0}
  {<style(s) when no children are present>}
  {<style(s) when children are present>}

The first argument of if will be evaluated by PGFmath. If the result ist 0 (false) the third argument will be executed, otherwise the second argument.

Code

\documentclass[tikz]{standalone}
\usepackage{forest}
\tikzset{
  every leaf node/.style={draw=cyan, fill=cyan!50, ellipse, text width=1cm, align=center},
  every tree node/.style={draw=blue, fill=blue!50, rectangle,
    text width=2cm, align=center, font=\ttfamily},
  tt/.style={font=\ttfamily},
}
\forestset{tikzQtree/.style={for tree={if n children=0{
        node options=every leaf node/.try}{node options=every tree node/.try}}}}
\begin{document}
\begin{forest} tikzQtree, % for tree={parent anchor=south, child anchor=north}
[/
  [usr 
    [mji
      [sh.c, tt]
    ]
  ]
  [bin 
    [sh, tt]
    [ls, tt]
  ]
]
\end{forest}
\end{document}
Related Question