如何将未知键作为选项传递给 TikZ 图片?

如何将未知键作为选项传递给 TikZ 图片?

我尝试使用 pgfkeys 编写一个接受选项的命令。未知键以一种样式收集,我尝试将其用作 tikzpicture 环境的全局选项。一个最小的例子是:

\documentclass{article}
\usepackage{tikz}

\newif\ifsquare

\pgfqkeys{/test}{%
 square/.is if=square,
 square/.default=true,
% collect unknown keys in style 'remainingkeys':
 .unknown/.code={%
  \let\currname\pgfkeyscurrentname%
  \let\currval\pgfkeyscurrentvalue%
  \ifx#1\pgfkeysnovalue%
   \pgfqkeys{/tikz}{remainingkeys/.append style={\currname}}%
  \else%
   \pgfqkeys{/tikz}{remainingkeys/.append style={\currname=\currval}}%
  \fi%
 }%
}

\newcommand\myfigure[1][]{
% initialize:
 \pgfqkeys{/tikz}{remainingkeys/.style={}}
 \pgfqkeys{/test}{square}
% set user keys:
 \pgfqkeys{/test}{#1}
 \begin{tikzpicture}[/tikz/remainingkeys]
  \ifsquare
   \fill (0,0)rectangle(1,1);
  \else
   \fill (0,0)rectangle(1.2,.8);
  \fi
 \end{tikzpicture}
}

\begin{document}

 \myfigure[square,rotate=45]                % rotated 45 degs; ok
 \myfigure[square,fill=red]                 % red; ok
 \myfigure[square,rotate=45,fill=red]       % red, but doesn't rotate
 \myfigure[square=false]                    % not square
 \myfigure[square=false,fill=red,rotate=45] % not square, not red and rotated 90 degs!

\end{document} 

命令 \myfigure 只是绘制一个正方形或矩形,具体取决于“square”键的值。此键已正确处理。所有其他选项均由 .unknown/.code 处理程序处理并收集到样式“remainingkeys”中,最终传递给 \begin{tikzpicture}。第一次调用 \myfigure 确实绘制了一个正方形并旋转了它,但第三次调用却没有!不知何故,并非所有未知键都存储在“remainingkeys”中。在第五次调用中,甚至旋转角度也不正确。

我尝试了很多方法,但这是我能想到的最好的方法,至少没有产生任何 TeX 错误。我做错了什么,但是什么?我束手无策了……

答案1

您需要先扩展\currname\currval值。否则,您只是存储了这些宏,而这些宏的定义将会改变。因此,除了最后一个选项之外,您失去了所有其他选项,该选项重复多次,就像您示例中的双重旋转中看到的那样。

\documentclass{article}
\usepackage{tikz}

\newif\ifsquare

\pgfqkeys{/test}{%
 square/.is if=square,
 square/.default=true,
% collect unknown keys in style 'remainingkeys':
 .unknown/.code={%
  \let\currname\pgfkeyscurrentname%
  \let\currval\pgfkeyscurrentvalue%
  \ifx#1\pgfkeysnovalue%
   \pgfqkeys{/tikz}{remainingkeys/.append style/.expand once={\currname}}%
  \else%
   \pgfqkeys{/tikz}{remainingkeys/.append style/.expand twice={\expandafter\currname\expandafter=\currval}}%
  \fi%
 }%
}

\newcommand\myfigure[1][]{
% initialize:
 \pgfqkeys{/tikz}{remainingkeys/.style={}}
 \pgfqkeys{/test}{square}
% set user keys:
 \pgfqkeys{/test}{#1}
 \begin{tikzpicture}[/tikz/remainingkeys]
  \ifsquare
   \fill (0,0)rectangle(1,1);
  \else
   \fill (0,0)rectangle(1.2,.8);
  \fi
 \end{tikzpicture}
}

\begin{document}

 \myfigure[square,rotate=45]                % rotated 45 degs; ok
 \myfigure[square,fill=red]                 % red; ok
 \myfigure[square,rotate=45,fill=red]       % red, but doesn't rotate
 \myfigure[square=false]                    % not square
 \myfigure[square=false,fill=red,rotate=45] % not square, not red and rotated 90 degs!

\end{document} 

结果

相关内容