TeX - LaTeX Asked on May 14, 2021
I have a macro written as newcommand
which contains a complete new tikz-environment.
How could one make a macro out of this that only contains the content of the tikz-environment, so that if one wants to have this drawing multiple times, it is drawn in one single tikz-environment?
I know I could simply strip the declaration of the tikz-environment in my macro, but that would let me use the macro outside a tikz-environment too.
Examples:
I have a macro similar to the following one:
newcommand{myTikzMacro}{
begin{tikzpicture}
draw (0,0) rectangle (1,1);
draw (1,1) rectangle (2,0);
end{tikzpicture}
Now I could use the macro multiple times after each other like this:
myTikzMacro
myTikzMacro
But then multiple tikz-environments would be used. To avoid that I’d be able to make this macro:
newcommand{myTikzMacro2}{
draw (0,0) rectangle (1,1);
draw (1,1) rectangle (2,0);
And use it as followed:
begin{tikzpicture}
myTikzMacro2
myTikzMacro2
end{tikzpicture}
But this would enable me to use the macro outside a tikzpicture
environment too which I’d like to avoid too.
Is there a way to declare macros only available/visible within tikzpicture environments? (maybe with pgfkeys)
According to How can I check if the current code is inside a tikzpicture? tikz
provides the macro
tikzifinpicture{true branch}{false branch}
for testing whether one is in a tikzpicture
; the comments in its definition seem however to throw some doubts on its correctness. (I believe it might fail in nested pictures.) Assuming that it works in most simple cases you can define
newcommand*{myTikzPicture}
{tikzifinpicture
{%
draw (0,0) rectangle (1,1);
draw (1,1) rectangle (2,0);
}%
{%
GenericError{}{Unallowed command}
{stringmyTikzPicturespace can be used only inside a tikz picture.}{}%
}%
}
I used here GenericError
. If the command will go into a custom package, using PackageError
will be more appropriate.
Correct answer by campa on May 14, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP