pgf-tikz / pgf

A Portable Graphic Format for TeX
https://pgf-tikz.github.io/
1.12k stars 106 forks source link

pgfkeys: define keys with optional arguments #1308

Open stettberger opened 7 months ago

stettberger commented 7 months ago

Brief outline of the proposed feature

Dear PGF/TikZ developers, thank you for your tremendous work. In my daily work, pgfkeys have proven to be the sanest way to write TeX code. However, when creating my notebook templates, I felt the need for a way to define pgfkeys with an optional argument. I was inspired by /tikz/label and /tikz/pin, but discovered that there is no cannonical way to define such keys on your own.

Therefore, I built one. If you think this is worth the effort, I can create a pull request for this.

Usage example

\def\pgfkeysdefargopt#1#2#3{%
  \long\def\pgfkeys@temp{%
    \@ifnextchar[%
    {\pgfkeysvalueof{#1/.@body}}%
    {\pgfkeysvalueof{#1/.@body}[#2]}%
  }%
  \pgfkeyslet{#1/.@cmd}{\pgfkeys@temp}%
  \def\pgfkeys@temp[##1]##2\pgfeov{#3}%
  \pgfkeyslet{#1/.@body}{\pgfkeys@temp}%
}

\pgfkeysdefnargs{/handlers/.code 2 opt}{2}{%
  \edef\pgfkeys@temp{\pgfkeyscurrentpath}%
  \expandafter\pgfkeysdefargopt\expandafter{\pgfkeys@temp}{#1}{#2}}

\pgfkeys{/handlers/.style 2 opt/.code 2 args=\pgfkeys{\pgfkeyscurrentpath/.code 2 opt={#1}{\pgfkeysalso{#2}}}}