[Tex/LaTex] Tikz: redefinition of patterns

pgf-coretikz-pgf

I save my TikZ figures in separate files containing all the necessary definitions, so it's easy to reuse them.

In some cases I defined a new pattern, e.g. by

\pgfdeclarepatternformonly{wide lines}{\pgfqpoint{-1pt}{-1pt}}{\pgfqpoint{12pt}{12pt}}{\pgfqpoint{9pt}{9pt}}%
{
  \pgfsetlinewidth{0.4pt}
  \pgfpathmoveto{\pgfqpoint{0pt}{0pt}}
  \pgfpathlineto{\pgfqpoint{9pt}{9pt}}
  \pgfusepath{stroke}
}

However, if I use two such figures in the same document, pdflatex complains about the already defined pattern. Is there any way that I can check if a pattern with that name is already defined, and if yes, just skip my definition?

I looked a bit in the pgf source codes but didn't really understand it.

Best Answer

As mentioned in the comments, I would put the pattern definitions in a separate file and import the definitions file. That way the definitions are kept consistent.

However, if you do not want to do that you could use \providepgfdeclarepatternformonly instead of \pgfdeclarepatternformonly using this definition:

\makeatletter
\newcommand{\providepgfdeclarepatternformonly}[4][]{%
    \pgfutil@ifundefined{pgf@pattern@name@#1}{
        \pgfdeclarepatternformonly{#1}{#2}{#3}{#4}
    }{%
        %Pattern already defined, so don't redefine it
    }%
}
\makeatother

Similar to providecommand, if the pattern is already defined the attempt to redefine it is ignored. Here is the test case where using providepgfdeclarepatternformonly compiles, but pgfdeclarepatternformonly gives the error about pattern already being defined.

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{patterns}

\makeatletter
\newcommand{\providepgfdeclarepatternformonly}[5]{%
    \pgfutil@ifundefined{pgf@pattern@name@#1}{%
        \pgfdeclarepatternformonly{#1}{#2}{#3}{#4}{#5}%
    }{%
        %Pattern already defined, so don't redefine it
    }%
}
\makeatother

\begin{document}

\providepgfdeclarepatternformonly{wide lines}{\pgfqpoint{-1pt}{-1pt}}{\pgfqpoint{12pt}{12pt}}{\pgfqpoint{9pt}{9pt}}%
{
  \pgfsetlinewidth{0.4pt}
  \pgfpathmoveto{\pgfqpoint{0pt}{0pt}}
  \pgfpathlineto{\pgfqpoint{9pt}{9pt}}
  \pgfusepath{stroke}
}

\begin{tikzpicture}
\providepgfdeclarepatternformonly{wide lines}{\pgfqpoint{-1pt}{-1pt}}{\pgfqpoint{12pt}{12pt}}{\pgfqpoint{9pt}{9pt}}%
{
  \pgfsetlinewidth{0.4pt}
  \pgfpathmoveto{\pgfqpoint{0pt}{0pt}}
  \pgfpathlineto{\pgfqpoint{9pt}{9pt}}
  \pgfusepath{stroke}
}

\filldraw[pattern=wide lines] (0,0) rectangle (2,2);
\end{tikzpicture}
\end{document}
Related Question