# Tikz fit library: fitting only one dimension and accumulating calls

The fit library is very useful for adjusting the size of a node to fit other nodes inside it. It is also useful in conjunction with shift to make a node span to the width/height of other nodes but saty beside them.

I feel this is a common enough situation to justify dedicated keys.

From the code defining the fit key, all four anchors north, south, west and east are always considered for fitting. This does make sense for genereal fitting but in some cases it would be useful to fit only in one dimension. This could be easily achieved by defining something like a fit width key considering only east and west anchors in its calculations.

Here's the question: is it possible to emulate this without duplicating the fit definition and with minimal hassle?

Additionally: if you use fit twice in a row, the second overrides the first; it would be great to provide an also fit key setting the max of the current size and the one fitting the given nodes.

This question is related but the answers avoid the use of the fit library.

-
Interesting proposal. I suggest you fill a feature request. – cjorssen May 17 '14 at 16:21
@cjorssen thanks for the feedback. I just posted a feature request hopefully this will be implemented. I tried some workarounds but they are quite cumbersome to use. If I come up with something feasible I'll post it here. – Bordaigorl May 17 '14 at 23:33

I have a working workaround for the also fit key which I share here for reference.

\documentclass[tikz]{standalone}
\usetikzlibrary{fit}
\pgfmathsetseed{200}
\begin{document}
\makeatletter
\begin{tikzpicture}[
nodes to fit/.initial={},
fit/.append style={nodes to fit=#1},
also fit/.style={
nodes to fit/.append={#1},
},
fit now/.code={
\xdef\@fitting@nodes{\pgfkeysvalueof{/tikz/nodes to fit}}
\ifx\@fitting@nodes\@empty
%%% do nothing
\else
\tikzset{fit={\@fitting@nodes}}
\fi
}
]
\foreach \i in {1,...,5}{
\node[draw] (n\i) at (2*rand,3*rand) {\i};
}

\node[draw=green, thick, fit={(n4) (n3)}] {};
\node[draw=red, thick, fit={(n1)}, also fit={(n4)}, also fit={(n2) (n3)}, fit now] {};
\node[draw=blue,also fit=(n1),also fit=(n2), fit now] {};
\end{tikzpicture}
\makeatother
\end{document}


The idea is simple: use an auxiliary key nodes to fit accumulating the list of coordinates/nodes to fit, the fit key will also set it, the also fit will add to it. To make the additions effective you'll need to add a fit now key after the also fit and fit keys.

The normal behaviour of fit` is otherwise unaffected.

It would still be good to have these features implemented in the main library, see the relevant feature request.

-