7

In tikz, the macro \draw accept a optical argument of parameters separated with comma, e.g.

\draw[->, red] (0, 0) -- (1, 1)

I have a self defined macro, in which I want to pass a macro as this optional parameter, i.e. sth like

\def\p{->, red}
\draw[\p] (0, 0) -- (1, 1)

However, I get a ERROR: Package pgf Error: Arrow end type ``>, red'' unknown. which is the same error with

\draw[{{->, red}}] (0, 0) -- (1, 1)

I think it is because the argument is passed as a single character and failed to be separated.

Is there a way to do it correctly? (i.e. "unquote" the curly bracket before passing it to the \draw macro.)

In my particular case, I use xkeyval package to define my macro according to this. Therefore I have to pass the argument through a macro.

(Any tikz specific work around is also helpful. THX)

1
  • THX, all the solutions works for me. I have chosen the answer that is the best for my case, although other answers were actually what I was planning to look for. =D
    – yuyichao
    Mar 27, 2012 at 22:08

3 Answers 3

10

You should use \tikzset{MyStyle/.style={->, red}} instead of a \def to define your own custom style to be applied:

\documentclass{article}
\usepackage{tikz}

\tikzset{MyStyle/.style={->, red}}

\begin{document}
\begin{tikzpicture}
    \draw[MyStyle] (0, 0) -- (1, 1);
\end{tikzpicture}
\end{document}
3
\documentclass[11pt]{scrartcl}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}

 \def\p{->, red}
\draw\expandafter[\p] (0, 0) -- (1, 1);

\end{tikzpicture}
\end{document} 

or with etex

\begin{tikzpicture} 
   \def\p{->, red}   
   \makeatletter
 \protected@edef\tmp{%
   \noexpand \draw[\p] (0, 0) -- (1, 1);}\tmp  
\end{tikzpicture} 
4
  • I guess that defining a new arrow style might be better.
    – egreg
    Mar 27, 2012 at 21:53
  • @egreg I agree with you but \protected@edef\tmp{ saves me in a lot of painful situations and if OP writes a package it's perhaps very useful. Mar 27, 2012 at 22:00
  • Oh, yes: I've suggested a few times something of the kind.
    – egreg
    Mar 27, 2012 at 22:02
  • @egreg It's difficult to understand that OP wants to use tikz with a macro and he doesn't know what is a style ! Mar 27, 2012 at 22:16
2

An immediate solution to your problem is

\expandafter\draw\expandafter[\p] 

But if you want to use this systematically, it will become awkward.

Anyway, whatever you do you need to make sure the content of [] is expanded before \draw is executed.

1
  • Yes, this (order of expansion) is what I was confusing about. THX.
    – yuyichao
    Mar 27, 2012 at 22:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .