4

Here's my cute little forest: enter image description here

Code:

\documentclass[11pt,a4paper]{article}
\usepackage{forest}
\usepackage{hyperref}

\begin{document}
  \begin{forest}
    [Link to Country 
      [Link to United States]
      [Link to United Kingdom]
    ]
  \end{forest}

  \section{Country}
  \label{sec:country}
  \subsection{United States}
  \label{sec:country:us}
  \subsection{United Kingdom}
  \label{sec:country:ul}
\end{document}

Now I want to \hyperref the forest's leaves to the corresponding section and subsections, such that when you click on Link to Country you'll get directed to the section Country and so forth. This is what I have tried:

...
\begin{forest}
  [\hyperref[sec:country]{Link to Country}
    [\hyperref[sec:country:us]{Link to United States}]
    [\hyperref[sec:country:uk]{Link to United Kingdom}]
  ]
\end{forest}
...

Unfortunately I got a bunch of errors and the code didn't produce anything. My guess is that the macro hyperref expands into something that breaks either Tikz or forest's syntax. But I don't know much about Latex to find the solution myself.

When I use hyperref outside of the forest, it works fine. So obviously no problem with the packages.

\ref{...} appears to work fine so obviously it must be possible to have link inside a Tikz/forest.

How should I fix it?

5

You have just to make the optional argument to \hyperref “invisible” to forest: use braces.

\documentclass[11pt,a4paper]{article}
\usepackage{forest}
\usepackage{hyperref}

\begin{document}

\begin{forest}
  [{\hyperref[sec:country]{Link to Country}}
    [{\hyperref[sec:country:us]{Link to United States}}]
    [{\hyperref[sec:country:uk]{Link to United Kingdom}}]
  ]
\end{forest}

\section{Country}
\label{sec:country}
\subsection{United States}
\label{sec:country:us}
\subsection{United Kingdom}
\label{sec:country:uk}

\end{document}
2

Here's a convenience wrapper based on egreg's code which makes the tree specification a bit less cumbersome.

\documentclass[11pt,a4paper]{article}
\usepackage{forest}
\usepackage{hyperref}
\forestset{
  declare toks={country link}{},
  declare toks={country link label}{},
  country links/.style={
    before typesetting nodes={
      where content={}{}{
        split option={content}{|}{country link,country link label},
        delay={
          content/.process={OOw2}{country link}{country link label}{\hyperref[sec:##1]{##2}},
        }
      },
    },
  },
}
\begin{document}
\begin{forest}
  country links
  [country|Link to Country
    [country:us|Link to United States]
    [country:uk|Link to United Kingdom]
  ]
\end{forest}
\section{Country}
\label{sec:country}
\subsection{United States}
\label{sec:country:us}
\subsection{United Kingdom}
\label{sec:country:uk}
\end{document}

country links

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.