How to set family keys with pgfkeys and a macro?

1.7k views Asked by At

I want to set 2 keys of a pgfkeys-family using a macro :

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{pgf}
\begin{document}
\pgfkeys{
    /keys/.is family,
    /keys/.cd,
    test 1/.store in=\testone,
    test 1=unset,
    test 2/.store in=\testtwo,
    test 2=unset,
}

\pgfkeys{/store/.code={\pgfkeys{/keys/.cd,#1}}}
\def\mykey{test 1=ONE,test 2=TWO}
\pgfkeys{/store=\mykey}
t1 : \testone,   
t2 : \testtwo.
\end{document}

I hope to get :

t1 : ONE, t2 : TWO.

And I get :

t1 : unset, t2 : unset

And an error message :

Package pgfkeys Error: I do not know the key '/keys/test 1=ONE,test 2=TWO'
and I am going to ignore it. Perhaps you misspelled it.

What did i miss ?

1

There are 1 answers

0
Andrew On

One way to do what you want is:

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{pgf}
\pgfkeys{
    /keys/.is family,
    /keys,
    test 1/.store in=\testone,
    test 1/.initial=unset,
    test 2/.store in=\testtwo,
    test 2/.initial=unset,
}
\newcommand\setkeys[1]{\pgfkeys{/keys,#1}}

\begin{document}
  \setkeys{test 1=ONE,test 2=TWO}
  t1 : \testone,
  t2 : \testtwo.
\end{document}

Points to note:

  • use the .initial handler to set the initial value of the key
  • you do not need the .cd handler for a family
  • I have defined the macro \setkeys to set the keys from a comma separated list
  • if you want to set the keys using a macro that is defined like \def\mykey{test 1=ONE,test 2=TWO} you run into some mildly painful expansion problems. One way around this is to use \edef\Addkey{\noexpand\pgfkeys{/keys, \mykey}}\Addkey
  • rather than using .store in you can let \pgfkeys store the values of the keys and use \pgfkeysvalueof{/keys/test 1} etc to print their values. I usually define a macro like \newcommand\Keys{\pgfkeysvalueof{/keys/#1}} to do this, which you would use as \Keys{test 1}.

Btw, you are better off posting TeX questions on tex.stackexchange.com.