Define a new command in TikZ with optional argument

tikz-pgf

I write a command to help me draw circle easy:

\def\Tdot@i{circle (1mm)}
\def\Tdot@ii[#1]{circle (#1)}
\def\Tdot{%
    \@ifnextchar[%
    {\Tdot@ii}%
    {\Tdot@i}%
}

When I try, it works well:

\documentclass{minimal}

\makeatletter

\def\Tdot@i{circle (1mm)}
\def\Tdot@ii[#1]{circle (#1)}
\def\Tdot{%
    \@ifnextchar[%
    {\Tdot@ii}%
    {\Tdot@i}%
}

\makeatother

\begin{document}
\Tdot is circle (1mm),
\Tdot[5mm] is circle (5mm).
\end{document}

so I try to bring it to tikz, it raise some error:

% ...

\usepackage{tikz}

\begin{document}

\begin{tikzpicture}
    \draw (0, 0) circle (1mm); % goodA
    % Package tikz Error: Giving up on this path. Did you forget a semicolon?
    % \draw (0, 0) \Tdot; 
    % Package tikz Error: Giving up on this path. Did you forget a semicolon?
    % \draw (0, 0) \Tdot[5mm];
\end{tikzpicture}

\end{document}

Is the if-else bad for TikZ?

Best Answer

TikZ uses its own parser. You can't easily modify its behavior. The TikZ parser accepts external commands at the location of the coordinates but not between the coordinates (not as path operators).

As a workaround, you can use a to path style...

\documentclass[tikz]{standalone}

\tikzset{
  Tdot/.style={to path={circle[radius=#1]}},
  Tdot/.default=1mm,
}

\begin{document}
\begin{tikzpicture}
  \draw (0,0) to[Tdot] cycle to[Tdot=3mm] cycle;
  \draw[red] (1,0) to[Tdot=2mm] cycle ;
\end{tikzpicture}
\end{document}

enter image description here