TikZ provides the two keys execute at end picture={<code>} and execute at end scope={<code>} which can be used to execute any code at the end of the picture and of the current scope, respectively.
I now like to execute some code at the end of the picture if a TikZ key defined by me is used outside a scope environment, i.e. in the optional argument of tikzpicture or at the end of the scope if it is used inside the scope, i.e. in its optional argument. I also like to access the bounding box of that area, i.e. the complete one or only the one of the scope, respectively.
Is there am easy way to do this? Cascaded scopes should also be supported.
I don't see a possibility to detect if I'm inside a scope or not. In theory the whole tikzpicture is a scope by itself and execute at end scope seems to work but the manual explicitly states it should only be used in the optional argument of a scope environment.
I know about 'local bounding box' but then I would have to use it for every scope with a different name to avoid collisions.

local bounding box, TikZ doesn't keep track of bounding boxes in scopes. The description oflocal bounding boxsays that “excessive use of this option (keeping track of dozens of bounding boxes at the same time) will slow things down”. So I think TikZ isn't doing that if not explicitly wanted. – Caramdir May 6 '11 at 20:07tikzpicturepretty much starts with\scope[every picture,#1](passing the optional arguments fromtikzpicture, see line 1300 oftikz.code.tex). Interestingly, code fromexecute at end of pictureis executed beforeexecute at end of scope. Possibly code executed at the end of the scope does not affect the baseline and trimming (at least a superficial reading of the code seems to indicate that). – Caramdir May 6 '11 at 20:14execute at end of picturewas executed afterexecute at end of scope, at least the\node {A}in it was on top. – Martin Scharrer♦ May 6 '11 at 20:16\begin{tikzpicture}[execute at end picture={\node[fill=red] {P};}, execute at end scope={\node[fill=green] {S};}] \draw (0,0) -- (1,0); \end{tikzpicture}gives a green square. – Caramdir May 6 '11 at 20:23