[Tex/LaTex] Calling a previously named path in tikz


Using the intersections library, we are able to name a path. For example

\path[name path=line1] (0,0) -- (1,1);

Now, how can I later in the picture call upon this path with the name line1 and do things to it — such as drawing, marking etc.?

PS. I did look at answers to some other seemingly related questions (such as part drawing of a path etc.) but not able to find an answer.

Best Answer

Update 2022-07-12: The spath3 library now contains considerable facility for saving and manipulating and using paths and so supersedes this answer. See the documentation for details.

If you want to do serious stuff with reusing paths, then you might want to take a look at the spath part of the TeX-SX package. If you just want a quick way to (essentially) copy a previously defined path then the following code will work (though I haven't tested it in great detail). The point is that when you put the name path key on a path then TikZ really does save the path. So all that is needed is to sneak it back in at the right time. Turns out that there's a difference between the main path and a pre- or postaction path, but that's not hard to deal with.

Here's the code. The intersections library provides the name path key, the decorations.markings library is used purely for demonstration purposes.

% \url{http://tex.stackexchange.com/q/26382/86}

  use path for main/.code={%
      \expandafter\pgfsyssoftpath@setcurrentpath\csname tikz@intersect@path@name@#1\endcsname
  use path for actions/.code={%
    \expandafter\def\expandafter\tikz@preactions\expandafter{\tikz@preactions\expandafter\let\expandafter\tikz@actions@path\csname tikz@intersect@path@name@#1\endcsname}%
  use path/.style={%
    use path for main=#1,
    use path for actions=#1,

\draw[ultra thick,name path=mypath] (0,0) circle[radius=1cm];
\fill[blue,use path=mypath] (0,0) rectangle (1,1);
\draw[use path=mypath,postaction={decorate},decoration={markings,mark=at position .5 with {\arrow[orange,line width=5pt]{>};}}] (3,3) -- (4,4);

Here's the result:

using paths in TikZ

So neither the rectangle nor the line in the second two commands are used. What is worth pointing out is that while they aren't used, their size is used in computing the size of the TikZ picture. That's what accounts for the large space at the top and right of the circle. So choose the path to be thrown away carefully (or figure out a better place to do the path swap!).

Related Question