# tikz connection label and node distance

Is it possible to have tikz automatically determining the distance between two nodes based on a third node used to connect them?

For instance, in the following picture the arrow used to connect the nodes are too short. Can tikz calculate its length automatically so that its label fits it better?

\documentclass{standalone}

\usepackage{tikz}
\usetikzlibrary{positioning}

\begin{document}

\begin{tikzpicture}
\node [rectangle,draw] (a) {source program};
\node [rectangle,draw] (b) [right=of a] {token list};
\draw [->] (a.east) -- (b.west) node[above] {lexical analysis};
\end{tikzpicture}

\end{document}

-
... and after posting my answer, I've found the similar question I was thinking of: tex.stackexchange.com/q/20693/86 –  Loop Space Mar 5 '12 at 11:33
@AndrewStacey I would even say that it is a duplicate. –  percusse Mar 5 '12 at 11:38

(I feel certain that I've answered a similar question before, but I can't find it now.)

One solution is simply to change the order in which you draw things. Since the token list node's position should depend on the length of the lexical analysis node, draw the lexical analysis one first.

\documentclass{article}
%\url{http://tex.stackexchange.com/q/46842/86}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
\node [rectangle,draw] (a) {source program};
\node[above right] at (a.east) (l) {lexical analysis};
\draw[->] (l.south west) -- (l.south east);
\node [rectangle,draw,right] at (l.south east) (b) {token list};
\end{tikzpicture}
\end{document}

To put the lexical analysis and the node commands in the same command, you could write

\draw[->] node [
above right,
append after command={
(\tikzlastnode.south west) -- (\tikzlastnode.south east)
}
] at (a.east) (l) {lexical analysis};

Result:

-

You can also get the length of the argument using \pgfmathwidth or width with the use of \pgfmathparse

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning}
\begin{document}
\begin{tikzpicture}
\node [rectangle,draw] (a) {source program};
\pgfmathwidth{"Lexical Analysis"}
\node [rectangle,draw] (b) [right= \pgfmathresult pt of a] {token list};
\draw [->] (a.east) -- (b.west) node[midway,above] {lexical analysis};
\end{tikzpicture}
\end{document}

If the positioning is too tight you can further add some additional space.

-

you can use an intermediate node with \ phantom as shown below to calculate the width

\documentclass{standalone}

\usepackage{tikz}
\usetikzlibrary{positioning}

\begin{document}

\begin{tikzpicture}
\node [rectangle,draw] (a) {source program};
\node[right =0em of a](ph){\phantom{lexical analysis}};
\node [rectangle,draw] (b) [right=0em of ph] {token list};
\draw [->] (a.east) -- (b.west) node[midway,above] {lexical analysis};
\end{tikzpicture}

\end{document}

-