I have a document with several TikZ pictures in it. I generally use simple names for the nodes such as:
\node (A) at .....
\node (B) at .....
and so forth. Because of this I have name clashes between the various pictures. That's generally not a problem. However I find myself in a position where I may or may not have defined a certain node within a given picture. So I use the following snippet to test whether the node has been defined:
\makeatletter
\long\def\ifnodedefined#1#2#3{%%
\@ifundefined{pgf@sh@ns@#1}{#3}{#2}}
\makeatother
Unfortunately this fails if I've already created a node by the same name in another picture.
Is there a way to scope the definitions of nodes or is there a way to undefine nodes once you no longer need them?
P.S.
I'm aware that I could embed each picture in a standalone file and import it using \includegraphics. Unfortunately, this approach will not work for the document I'm creating.
MWE
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\makeatletter
\long\def\ifnodedefined#1#2#3{%%
\@ifundefined{pgf@sh@ns@#1}{#3}{#2}}
\makeatother
\setlength{\parindent}{0pt}
\pagestyle{empty}
\begin{document}
There's no node \textbf{D} here, so I draw a triangle:\par
\begin{tikzpicture}
\coordinate (A) at (0,0);
\coordinate (B) at (1,0);
\coordinate (C) at (1,1);
% \coordinate (D) at (0,1);
\ifnodedefined{D}
{ \draw (A) foreach \myn in {B,C,D} { -- (\myn) } --cycle; }
{ \draw (A) foreach \myn in {B,C} { -- (\myn) } --cycle; }
\end{tikzpicture}
There is a node \textbf{D} here, so I draw a square:\par
\begin{tikzpicture}
\coordinate (A) at (0,0);
\coordinate (B) at (1,0);
\coordinate (C) at (1,1);
\coordinate (D) at (0,1);
\ifnodedefined{D}
{ \draw (A) foreach \myn in {B,C,D} { -- (\myn) } --cycle; }
{ \draw (A) foreach \myn in {B,C} { -- (\myn) } --cycle; }
\end{tikzpicture}
There isn't supposed to be a node \textbf{D} here. I'm expecting a
triangle, but get a square.\par
\begin{tikzpicture}
\coordinate (A) at (0,0);
\coordinate (B) at (1,0);
\coordinate (C) at (1,1);
% \coordinate (D) at (0,1);
\ifnodedefined{D}
{ \draw (A) foreach \myn in {B,C,D} { -- (\myn) } --cycle; }
{ \draw (A) foreach \myn in {B,C} { -- (\myn) } --cycle; }
\end{tikzpicture}
\end{document}
produces:


myothernodeleft of the firstmynodeand the secondmyothernoderight of the secondmynode, it still all works. – cfr May 17 '14 at 20:11tikzto remember between pictures and that the default was to forget. – cfr May 17 '14 at 20:15is ambiguous. Did you mean: that command says the node *is* defined if it is defined in a different picture but not the present one, whereas you want it to say it is defined only if it is defined in the present one? If you put it in astandalonefile and\inputthe file, does that avoid the problem? (That is, not using\includegraphicsbut the waystandalone` handles things by default.) – cfr May 17 '14 at 20:19tikzskills are similar to a bored snail's. No offence meant to bored snails.) – cfr May 17 '14 at 20:43