许多接口使用可变数量的参数,例如在 CSS 中
margin:1pt 1pt 1pt 1pt
图形包的剪辑函数也有类似的例子。
使用 PGF 密钥可以实现这一点吗?
请注意不应该是一个逗号分隔的列表。
\documentclass{article}
\usepackage{pgfkeys}
\begin{document}
\pgfkeyssetvalue{/test/test}{1pt 2pt 3pt 4pt}
\pgfkeysgetvalue{/test/test}{\test}
\end{document}
本质上我正在寻找一个解析器来获取可变数量的参数并将它们放置在单独的宏中。
答案1
有几种方法……
可能是最简单的:
\documentclass[varwidth, border=5]{standalone}
\usepackage{tikz}
\tikzset{%
border/.style args={#1 #2 #3}{
border width=#1,
border style=#2,
border color=#3,
},
border width/.store in=\borderwidth,
border style/.store in=\borderstyle,
border color/.store in=\bordercolor,
}
\begin{document}
\ttfamily
\tikzset{border=20pt solid blue}
border: \borderwidth\ \borderstyle\ \bordercolor;
\tikzset{border=5pt dotted green}
border: \borderwidth\ \borderstyle\ \bordercolor;
\tikzset{border=15pt dashed red}
border: \borderwidth\ \borderstyle\ \bordercolor;
\end{document}
有点复杂,但允许部分指定......
\documentclass[varwidth, border=5]{standalone}
\usepackage{tikz}
\def\empty{}
\pgfkeys{utils/.cd,
set if not empty/.code 2 args={%
\def\arg{#2}%
\ifx\arg\empty%
\else%
\pgfkeys{#1={#2}}%
\fi%
}
}
\tikzset{%
border/.style={border ..=#1 {} {} {}},
border ../.style args={#1 #2 #3 #4}{
/utils/set if not empty={/tikz/border width}{#1},
/utils/set if not empty={/tikz/border style}{#2},
/utils/set if not empty={/tikz/border color}{#3}%,
},
border width/.store in=\borderwidth,
border style/.store in=\borderstyle,
border color/.store in=\bordercolor,
}
\def\borderwidth{1pt}
\def\borderstyle{solid}
\def\bordercolor{blue}
\begin{document}
\ttfamily
\tikzset{border=20pt}
border: \borderwidth\ \borderstyle\ \bordercolor;
\tikzset{border=5pt dotted}
border: \borderwidth\ \borderstyle\ \bordercolor;
\tikzset{border=15pt dotted red}
border: \borderwidth\ \borderstyle\ \bordercolor;
\end{document}
这个最终版本可能并不完全符合要求但无论如何却说明了一种将空格分隔的值提取到单独的键中的通用方法...
\documentclass[varwidth, border=5]{standalone}
\usepackage{tikz}
\def\at{@}
\pgfkeys{/utils/.cd,
set keys/.style 2 args={
/utils/set keys ..={{0}{#1}#2 @ @}
},
set keys ../.code args={#1#2#3 #4}{%
\def\tmp{#3}%
\ifx\tmp\at%
\pgfkeys{#2\space n/.initial=\pgfmathresult}%
\else%
\pgfmathparse{int(#1+1)}%
\pgfkeys{#2\space\pgfmathresult/.initial=#3}%
\pgfkeys{/utils/set keys ..={\pgfmathresult}{#2}#4}%
\fi%
}
}
\tikzset{
test/.style={/utils/set keys={/tikz/test}{#1}}
}
\begin{document}
\tikzset{test={20pt 30pt 40pt 100pt}}
\pgfkeysgetvalue{/tikz/test n}\n
There were \n\ values
\foreach \i in {1,...,\n}{
\par\leavevmode
The value of `test \i' is \pgfkeysvalueof{/tikz/test \i}
}
\end{document}
得出: