TransWikia.com

Check if macro argument is a tikz pattern

TeX - LaTeX Asked on March 12, 2021

Is it possible to check if a given argument is a defined tikz pattern (using the pattern library)? I’d like to have a macro

IfPatternTF{#1}{executed if #1 is a pattern}{executed if #1 isn't a pattern}

Ideally, IfPatternTF would fully expand #1 before checking but I can probably manage that myself once I know how to check if it’s a pattern.

Note that I’d be equally happy being able to test if something is a color since I want this for the purpose of deciding to either do a fill= or a pattern= in the command. However, the answers for checking if xcolor colors are defined doesn’t help since that doesn’t tell me if it’s an acceptable argument for fill= in tikz.

One Answer

When a pattern foo is declared in the standard pattern library, the control sequence pgf@pattern@name@foo is defined; similarly, pgf@pattern@name@meta@foo if the pattern is declared with pgfdeclarepattern from the patterns.meta library.

documentclass{article}
usepackage{tikz}
usetikzlibrary{patterns,patterns.meta}

makeatletter
newcommand{IfPatternTF}[1]{%
  ifcsname pgf@pattern@name@#1endcsname
    % defined pattern
    expandafter@firstoftwo
  else
    ifcsname pgf@pattern@name@meta@#1endcsname
      % defined meta pattern
      expandafterexpandafterexpandafter@firstoftwo
    else
    % undefined pattern
    expandafterexpandafterexpandafter@secondoftwo
    fi
  fi
}
makeatother

% declare a pattern for testing; this is from the PGF/TikZ manual
pgfdeclarepattern{
  name=hatch,
  parameters={hatchsize,hatchangle,hatchlinewidth},
  bottom left={pgfpoint{-.1pt}{-.1pt}},
  top right={pgfpoint{hatchsize+.1pt}{hatchsize+.1pt}},
  tile size={pgfpoint{hatchsize}{hatchsize}},
  tile transformation={pgftransformrotate{hatchangle}},
  code={
    pgfsetlinewidth{hatchlinewidth}
    pgfpathmoveto{pgfpoint{-.1pt}{-.1pt}}
    pgfpathlineto{pgfpoint{hatchsize+.1pt}{hatchsize+.1pt}}
    pgfpathmoveto{pgfpoint{-.1pt}{hatchsize+.1pt}}
    pgfpathlineto{pgfpoint{hatchsize+.1pt}{-.1pt}}
    pgfusepath{stroke}
  }
}

begin{document}

IfPatternTF{horizontal lines}{existing pattern}{non existing pattern}

IfPatternTF{hatch}{existing pattern}{non existing pattern}

IfPatternTF{foo}{existing pattern}{non existing pattern}

end{document}

Beware that delving with internals is not guaranteed to work forever. You might make a feature request to the PGF/TikZ maintainers.

enter image description here

There's nothing to worry in case the name is stored in a macro, provided it is fully expandable. So newcommandfoo{horizontal lines} will make IfPatternTF{foo}{true}{false} do the right thing.

Correct answer by egreg on March 12, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP