# TikZ: Defining and reusing complex objects?

(How) Is it possible to save some complex TikZ objects for reusing them (in the same and in different pictures)?

I know it's possible to define own styles, but I'm not sure if it's the right thing I'm looking for (styles seems to be only for properties not for complex and done objects). And that it's possible to save whole images with savebox, but can it be used to save portions of pictures?

Let's make an example: Someone's building several optical experiments. All experiments use the same kind of elements, like mirrors, lasers, polarizers, beam splitters and so on, but each experiment is in another configuration and setup. Each element has it's own picture (just like in electrical circuits where each type of element has it's own "icon").

How and where do I define my "kinds of elements" to be able to reuse them in my lots of TikZ pictures?

In the end I want ideally be able to draw my pictures similar (not neccerssarily exact) like

\begin{tikzpicture}
\mirror at (0,0);
\laser at (1,0);
\draw (1,0) --(0,0) --(0,1);
\end{tikzpicture}

-
 – Torbjørn T. Jan 15 at 15:07 Yeah, I saw that already (savebox hint my question), but I believe that's not what I need. – Foo Bar Jan 15 at 15:09 That is the job of libraries. You can create a library and then it can be used across the files. – Harish Kumar Jan 15 at 15:15 If you want some flexibility (for example, to be able to apply a particular style or to vary the size) then one option would be to define a suite of node shapes. They aren't all that difficult to do. – Andrew Stacey Jan 15 at 15:18 You can also read up the PGF Manual Section 67: Object-Oriented Programming for such use. – percusse Jan 15 at 15:23

One way you could address this is to define your own node shapes as described in the PGF/TikZ manual and then define e.g. \mirror as \node [shape=mirror] (the shape= part is optional, but I would recommend it here). However, unfortunately you need to define node shapes using PGF not TikZ commands, which makes the creation of them difficult and doesn't allow you to simply convert an existing TikZ picture into a node shape.

-
 Isn't this what Andrew Stacey suggested in his comment? – Marc van Dongen Jan 15 at 19:12 @MarcvanDongen: Yes, he also mentioned nodes, but I didn't read all comments before posting an answer. Anyway, there is nothing wrong when two users suggest the same basic idea but provide different information on it. – Martin Scharrer♦ Jan 15 at 20:19

The simplest way might be to simply define \mirror as a command.

\def\mirror at (#1,#2){\draw (#1,#2) rectangle ++(2,2);}
\begin{tikzpicture}
\mirror at (1,2)
\mirror at (2,4)
\end{tikzpicture}


unlike with TikZ commands though, you will have to be careful with the number of spaces though. It might be easier to remember if you simply define \def\mirror(#1,#2){..., but that is up to you.

-