3

I'm creating a package for drawing sequence charts and make use of pgfkeys to keep default values for various parameters that I need. However, sometimes I wish to provide to my macros one or more pgfkeys key-value pairs that override the defaults stored in pgfkeys. The code below demonstrates a problem I'm having; it is stripped down to the bare minimum. There are many more keys in my original.

\documentclass{article}
\usepackage{tikz}
\newcount\x

\pgfkeys{/std/msg/width/.code=\def\msgwidth{#1}}
\pgfkeys{/std/msg/default/.style={
    /std/msg/width=0.7,
}}
\pgfkeys{/std/msg/default} % Set the defaults

\newcommand{\msgx}[3][]{
    \pgfkeys{/std/msg/.cd,#1} % Use provided optional params (or default)
    \draw[->] (\x,#2) -- (\x+\msgwidth,#3);
    \advance\x by 1
}

\begin{document}
\begin{tikzpicture}
\msgx{1}{2} \msgx{2}{1}
\msgx[width=0.3]{1}{3}
\msgx{1}{2} \msgx{2}{1}  % Uses width=0.3 (not the default)
\end{tikzpicture}
\end{document}

The problem with the example is that after setting width=0.3, it remains 0.3. I do want to be able to set it to something other than the default using an initialization macro (not shown), but I want the default/initialized values to be retained after the end of \msgx[width=0.3].

My questions is: What pgfkeys mechanism should I use to avoid that my optional params (#1) override the defaults?

  • 1
    Welcome to TeX.SX! You can have a look on our starter guide to familiarize yourself further with our format. – karlkoeller Jun 25 '13 at 19:24
  • The standard mechanism of pgfkeys is to rely on TeX grouping constructs, i.e. to add \begingroup ... \endgroup in your macro. In that case, \endgroup retains all macro values (including keys) which were present in \begingroup – Christian Feuersänger Jun 25 '13 at 19:26
5

You can keep the value changes local by introducing a group using {...}:

\documentclass{article}
\usepackage{tikz}
\newcount\x

\pgfkeys{/std/msg/width/.code=\def\msgwidth{#1}}
\pgfkeys{/std/msg/default/.style={
    /std/msg/width=0.7,
}}
\pgfkeys{/std/msg/default} % Set the defaults

\newcommand{\msgx}[3][]{
    {
            \pgfkeys{/std/msg/.cd,#1} % Use provided optional params (or default)
            \draw[->] (\x,#2) -- (\x+\msgwidth,#3);
    }
    \advance\x by 1
}

\begin{document}
\begin{tikzpicture}
\msgx{1}{2}
\msgx{2}{1}
\msgx[width=0.3]{1}{3}
\msgx{1}{2}
\msgx{2}{1}
\end{tikzpicture}
\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.