6

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}

connection too small for its label

5

(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:

positioning nodes in the right order

7

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}

enter image description here

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

5

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}


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.