% Copyright 2006 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Free Documentation License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.


\section{Key Management}
\label{section-keys}

This section describes the package |pgfkeys|. It is loaded automatically by
both \pgfname\ and \tikzname.

\begin{package}{pgfkeys}
    This package can be used independently of \pgfname. Note that no
    other package of \pgfname\ needs to be loaded (so neither the
    emulation layer nor the system layer is needed). The Con\TeX t
    abbreviation is |pgfkey| \todosp{pgfkey --> pgfkeys?} if |pgfmod| is not loaded.
\end{package}


\subsection{Introduction}

\subsubsection{Comparison to Other Packages}

The |pgfkeys| package defines a key--value management system that is in some
sense similar to the more light-weight |keyval| system and the improved
|xkeyval| system. However, |pgfkeys| uses a slightly different philosophy than
these systems and it will coexist peacefully with both of them.

The main differences between |pgfkeys| and |xkeyval| are the following:
%
\begin{itemize}
    \item |pgfkeys| organizes keys in a tree, while |keyval| and |xkeyval|
        use families. In |pgfkeys| the families correspond to the root
        entries of the key tree.
    \item |pgfkeys| has no save-stack impact (you will have to read the \TeX
        Book very carefully to appreciate this).
    \item |pgfkeys| is slightly slower than |keyval|, but not much.
    \item |pgfkeys| supports styles. This means that keys can just stand for
        other keys (which can stand for other keys in turn or which can also
        just execute some code). \tikzname\ uses this mechanism heavily.
    \item |pgfkeys| supports multi-argument key code. This can, however, be
        emulated in |keyval|.
    \item |pgfkeys| supports handlers. These are call-backs that are called
        when a key is not known. They are very flexible, in fact even
        defining keys in different ways is handled by, well, handlers.
\end{itemize}


\subsubsection{Quick Guide to Using the Key Mechanism}

The following quick guide to \pgfname's key mechanism only treats the most
commonly used features. For an in-depth discussion of what is going on, please
consult the remainder of this section.

Keys are organized in a large tree that is reminiscent of the Unix file tree. A
typical key might be, say, |/tikz/coordinate system/x| or just |/x|. Again as
in Unix, when you specify keys you can provide the complete path of the key,
but you usually just provide the name of the key (corresponding to the file
name without any path) and the path is added automatically.

Typically (but not necessarily) some code is associated with a key. To execute
this code, you use the |\pgfkeys| command. This command takes a list of
so-called key--value pairs. Each pair is of the form \meta{key}|=|\meta{value}.
For each pair the |\pgfkeys| command will execute the code stored for the
\meta{key} with its parameter set to \meta{value}.

Here is a typical example of how the |\pgfkeys| command is used:
%
\begin{codeexample}[code only]
\pgfkeys{/my key=hallo,/your keys/main key=something\strange,
         key name without path=something else}
\end{codeexample}

Now, to set the code that is stored in a key you do not need to learn a new
command. Rather, the |\pgfkeys| command can also be used to set the code of a
key. This is done using so-called \emph{handlers}. They look like keys whose
names look like ``hidden files in Unix'' since they start with a dot. The
handler for setting the code of a key is appropriately called |/.code| and it
is used as follows:
%
\begin{codeexample}[]
\pgfkeys{/my key/.code=The value is '#1'.}
\pgfkeys{/my key=hi!}
\end{codeexample}
%
As you can see, in the first line we defined the code for the key |/my key|. In
the second line we executed this code with the parameter set to |hi!|.

There are numerous handlers for defining a key. For instance, we can also
define a key whose value actually consists of more than one parameter.
%
\begin{codeexample}[]
\pgfkeys{/my key/.code 2 args=The values are '#1' and '#2'.}
\pgfkeys{/my key={a1}{a2}}
\end{codeexample}

We often want to have keys where the code is called with some default value if
the user does not provide a value. Not surprisingly, this is also done using a
handler, this time called |/.default|.
%
\begin{codeexample}[]
\pgfkeys{/my key/.code=(#1)}
\pgfkeys{/my key/.default=hello}
\pgfkeys{/my key=hallo,/my key}
\end{codeexample}

The other way round, it is also possible to specify that a value \emph{must} be
specified, using a handler called |/.value required|. Finally, you can also
require that no value \emph{may} be specified using |/.value forbidden|.

All keys for a package like, say, \tikzname\ start with the path |/tikz|. We
obviously do not like to write this path down every time we use a key (so we do
not have to write things like |\draw[/tikz/line width=1cm]|). What we need is
to somehow ``change the default path to a specific location''. This is done
using the handler |/.cd| (for ``change directory''). Once this handler has been
used on a key, all subsequent keys {\itshape in the current call of |\pgfkeys|
only} are automatically prefixed with this path, if necessary.

Here is an example:
%
\begin{codeexample}[code only]
\pgfkeys{/tikz/.cd,line width=1cm,line cap=round}
\end{codeexample}
%
This makes it easy to define commands like |\tikzset|, which could be defined
as follows (the actual definition is a bit faster, but the effect is the same):
%
\begin{codeexample}[code only]
\def\tikzset#1{\pgfkeys{/tikz/.cd,#1}}
\end{codeexample}

When a key is handled, instead of executing some code, the key can also cause
further keys to be executed. Such keys will be called \emph{styles}. A style
is, in essence, just a key list that should be executed whenever the style is
executed. Here is an example:
%
\begin{codeexample}[]
\pgfkeys{/a/.code=(a:#1)}
\pgfkeys{/b/.code=(b:#1)}
\pgfkeys{/my style/.style={/a=foo,/b=bar,/a=#1}}
\pgfkeys{/my style=wow}
\end{codeexample}
%
As the above example shows, styles can also be parameterized, just like the
normal code keys.

As a typical use of styles, suppose we wish to set up the key |/tikz| so that
it will change the default path to |/tikz|. This can be achieved as follows:
%
\begin{codeexample}[code only]
\pgfkeys{/tikz/.style=/tikz/.cd}
\pgfkeys{tikz,line width=1cm,draw=red}
\end{codeexample}

Note that when |\pgfkeys| is executed, the default path is set to~|/|. This
means that the first |tikz| will be completed to |/tikz|. Then |/tikz| is a
style and, thus, replaced by |/tikz/.cd|, which changes the default path to
|/tikz|. Thus, the |line width| is correctly prefixed with |/tikz|.


\subsection{The Key Tree}

The |pgfkeys| package organizes keys in a so-called \emph{key tree}. This tree
will be familiar to anyone who has used a Unix operating system: A key is
addressed by a path, which consists of different parts separated by slashes. A
typical key might be |/tikz/line width| or just |/tikz| or something more
complicated like |/tikz/cs/x/.store in|.

Let us fix some further terminology: Given a key like |/a/b/c|, we call the
part leading up the last slash (|/a/b|) the \emph{path} of the key. We call
everything after the last slash (|c|) the \emph{name} of the key (in a file
system this would be the file name).

We do not always wish to specify keys completely. Instead, we usually specify
only part of a key (typically only the name) and the \emph{default path} is
then added to the key at the front. So, when the default path is |/tikz| and
you refer to the (partial) key |line width|, the actual key that is used is
|/tikz/line width|. There is a simple rule for deciding whether a key is a
partial key or a full key: If it starts with a slash, then it is a full key and
it is not modified; if it does not start with a slash, then the default path is
automatically prefixed.

Note that the default path is not the same as a search path. In particular, the
default path is just a single path. When a partial key is given, only this
single default path is prefixed; |pgfkeys| does not try to look up the key in
different parts of a search path. It is, however, possible to emulate search
paths, but a much more complicated mechanism must be used.

When you set keys (to be explained in a moment), you can freely mix partial and
full keys and you can change the default path. This makes it possible to
temporarily use keys from another part of the key tree (this turns out to be a
very useful feature).

Each key (may) store some \emph{tokens} and there exist commands, described
below, for setting, getting, and changing the tokens stored in a key. However,
you will only very seldom use these commands directly. Rather, the standard way
of using keys is the |\pgfkeys| command or some command that uses it internally
like, say, |\tikzset|. So, you may wish to skip the following commands and
continue with the next subsection.

\begin{command}{\pgfkeyssetvalue\marg{full key}\marg{token text}}
    Stores the \meta{token text} in the \meta{full key}. The \meta{full key}
    may not be a partial key, so no default-path-adding is done. The
    \meta{token text} can be arbitrary tokens and may even contain things like
    |#| or unbalanced \TeX-ifs.
    %
\begin{codeexample}[]
\pgfkeyssetvalue{/my family/my key}{Hello, world!}
\pgfkeysvalueof{/my family/my key}
\end{codeexample}

    The setting of a key is always local to the current \TeX\ group.
\end{command}

\begin{command}{\pgfkeyslet\marg{full key}\marg{macro}}
    Performs a |\let| statement so the \meta{full key} points to the contents
    of \meta{macro}.
    %
\begin{codeexample}[]
\def\helloworld{Hello, world!}
\pgfkeyslet{/my family/my key}{\helloworld}
\pgfkeysvalueof{/my family/my key}
\end{codeexample}
    %
    You should never let a key be equal to |\relax|. Such a key may or may not
    be indistinguishable from an undefined key.
\end{command}

\begin{command}{\pgfkeysgetvalue\marg{full key}\marg{macro}}
    Retrieves the tokens stored in the \meta{full key} and lets \meta{macro} be
    equal to these tokens. If the key has not been set, the \meta{macro} will
    be equal to |\relax|.
    %
\begin{codeexample}[]
\pgfkeyssetvalue{/my family/my key}{Hello, world!}
\pgfkeysgetvalue{/my family/my key}{\helloworld}
\helloworld
\end{codeexample}
    %
\end{command}

\begin{command}{\pgfkeysvalueof\marg{full key}}
    Inserts the value stored in \meta{full key} at the current position into
    the text.
    %
\begin{codeexample}[]
\pgfkeyssetvalue{/my family/my key}{Hello, world!}
\pgfkeysvalueof{/my family/my key}
\end{codeexample}
    %
\end{command}

\begin{command}{\pgfkeysifdefined\marg{full key}\marg{if}\marg{else}}
    Checks whether this key was previously set using either |\pgfkeyssetvalue|
    or |\pgfkeyslet|. If so, the code in \meta{if} is executed, otherwise the
    code in \meta{else}.

    This command will use e\TeX's |\ifcsname| command, if available, for
    efficiency. This means, however, that it may behave differently for \TeX\
    and for e\TeX\ when you set keys to |\relax|. For this reason you should
    not do so.
    %
\begin{codeexample}[]
\pgfkeyssetvalue{/my family/my key}{Hello, world!}
\pgfkeysifdefined{/my family/my key}{yes}{no}
\end{codeexample}
    %
\end{command}


\subsection{Setting Keys}

Settings keys is done using a powerful command called |\pgfkeys|. This command
takes a list of so-called \emph{key--value pairs}. These are pairs of the form
\meta{key}|=|\meta{value}. The principle idea is the following: For each pair
in the list, some \emph{action} is taken. This action can be one of the
following:
%
\begin{enumerate}
    \item A command is executed whose argument(s) are \meta{value}. This
        command is stored in a special subkey of \meta{key}.
    \item The \meta{value} is stored in the \meta{key} itself.
    \item If the key's name (the part after the last slash) is a known
        \emph{handler}, then this handler will take care of the key.
    \item If the key is totally unknown, one of several possible \emph{unknown
        key handlers} is called.
\end{enumerate}

Additionally, if the \meta{value} is missing, a default value may or may not be
substituted. Before we plunge into all the details, let us have a quick look at
the command itself.

\begin{command}{\pgfkeys\marg{key list}}
    The \meta{key list} should be a list of key--value pairs, separated by
    commas. A key--value pair can have the following two forms:
    \meta{key}|=|\meta{value} or just \meta{key}. Any spaces around the
    \meta{key} or around the \meta{value} are removed. It is permissible to
    surround both the \meta{key} or the \meta{value} in curly braces, which are
    also removed. Especially putting the \meta{value} in curly braces needs to
    be done quite often, namely whenever the \meta{value} contains an
    equal-sign or a comma.

    The key--value pairs in the list are handled in the order they appear. How
    this handling is done, exactly, is described in the rest of this section.

    If a \meta{key} is a partial key, the current value of the default path is
    prefixed to the \meta{key} and this ``upgraded'' key is then used. The
    default path is just the root path |/| when the first key is handled, but
    it may change later on. At the end of the command, the default path is
    reset to the value it had before this command was executed.

    Calls of this command may be nested. Thus, it is permissible to call
    |\pgfkeys| inside the code that is executed for a key. Since the default
    path is restored after a call of |\pgfkeys|, the default path will not
    change when you call |\pgfkeys| while executing code for a key (which is
    exactly what you want).
\end{command}

\begin{command}{\pgfqkeys\marg{default path}\marg{key list}}
    This command has the same effect as |\pgfkeys{|\meta{default
    path}|/.cd,|\meta{key list}|}|, it is only marginally quicker. This command
    should not be used in user code, but rather in commands like |\tikzset| or
    |\pgfset| that get called very often.
\end{command}

\begin{command}{\pgfkeysalso\marg{key list}}
    This command has exactly the same effect as |\pgfkeys|, only the default
    path is not modified before or after the keys are being set. This command
    is mainly intended to be called by the code that is being processed for a
    key.
\end{command}

\begin{command}{\pgfqkeysalso\marg{default path}\marg{key list}}
    This command has the same effect as |\pgfkeysalso{|\meta{default
    path}|/.cd,|\meta{key list}|}|, it is only quicker. Changing the default
    path inside a |\pgfkeyalso| is dangerous, so use with care. A rather safe
    place to call this command is at the beginning of a \TeX\ group.
\end{command}


\subsubsection{First Char Syntax Detection}
\label{sec:pgf:first:char:syntax}

Usually, keys are of the form \meta{key}|=|\meta{value} and how such keys are
handled is discussed in the rest of this section. However, it is also possible
to setup a different syntax for certain parts of the input to |\pgfkeys|. Since
this is a rather advanced option, most readers may wish to skip the following
discussion upon first reading; it is discussed here because this special syntax
detection is the very first thing that is done when a key is processed, before
any of the following operations are performed.

The |\pgfkeys| command and its variants decompose their input into a list of
\meta{string}s that are separated by commas. By default, each such
\meta{string} must either have the form \meta{key}|=|\meta{value} or of the
form \meta{key} with the value-part missing. However, you might wish to
interpret some of these strings differently. For instance, when a \meta{string}
has the form |"|\meta{text}|"|, you might wish the \meta{string} to be
interpreted as if one had written |label text={|\meta{text}|}|. Then, people
could write
%
\begin{codeexample}[code only]
\myset{red, "main valve", thick}
\end{codeexample}
%
instead of the more cumbersome
%
\begin{codeexample}[code only]
\myset{red, label text=main valve, thick}
\end{codeexample}
%
An example where such a syntax reinterpretation is done is the |quotes|
library, which allows you to write things like
%
\begin{codeexample}[]
\tikz \graph { a ->["1" red] b ->["0"] c };
\end{codeexample}
%
\noindent instead of the somewhat longer
%
\begin{codeexample}[]
\tikz \graph { a ->[edge node={node[red,auto]{1}}] b ->[edge label=0] c };
\end{codeexample}

In order to detect whether a \meta{string} has a special syntax, you can
request that the \emph{first character} of \meta{string} is analysed by the key
parser. If this first character matches a character that has been flagged as a
special character, the \meta{string} is not interpreted as a usual key--value
pair. Instead, \meta{string} is passed as a parameter to a special macro that
should take care of the \meta{string}. After this macro has finished, the
parsing continues with the \meta{next string} in the list.

In order to setup a special syntax handling for \meta{strings} that begin with
a certain character, two things need to be done:
%
\begin{enumerate}
    \item First, the whole first char syntax detection must be ``switched on'',
        since, by default, it is turned off for efficiency reasons (the
        overhead is rather small, however). This is done by setting the
        following key:
        %
        \begin{key}{/handlers/first char syntax=\opt{\meta{true or false}} (default true, initially false)}
        \end{key}
    \item Second, in order to handle strings starting with a certain
        \meta{character} in a special way, you need to store a macro in the
        following key:
        %
        \begin{key}{/handlers/first char syntax/\meta{meaning of character}}
            The \meta{meaning of character} should be the text that \TeX's
            command |\meaning| returns for a macro that has been |\let| to the
            \meta{character}. For instance, when strings starting with |"|
            should be treated in a special way, the \meta{meaning of character}
            would be the string |the character "| since this is what \TeX\
            writes when you say
            %
\begin{codeexample}[]
\let\mycharacter="
\meaning\mycharacter
\end{codeexample}
            %
            Now, the key |/handlers/first char syntax/|\meta{meaning of
            character} should be setup (using |\pgfkeyssetvalue| or using the
            |.initial| handler) to store a \meta{macro name}.

            If this is the case and if \meta{string} starts with the
            \meta{character} (blanks at the beginning of \meta{string} are
            deleted prior to this test), then \meta{macro name} is called with
            \meta{string} as its argument.
  \end{key}
\end{enumerate}

Let us now have a look at an example. We install two handlers, one for strings
starting with |"| and one for strings starting with |<|.
%
\begin{codeexample}[]
\pgfkeys{
  /handlers/first char syntax=true,
  /handlers/first char syntax/the character "/.initial=\myquotemacro,
  /handlers/first char syntax/the character </.initial=\mypointedmacro,
}

\def\myquotemacro#1{Quoted: #1. }
\def\mypointedmacro#1{Pointed: #1. }

\ttfamily \pgfkeys{"foo", <bar>}
\end{codeexample}

Naturally, in the above examples, the two handling macros did not do something
particularly exciting. In the next example, we setup a more elaborate macro
that mimics a small part the behaviour of the |quotes| library, only for single
quotes:
%
\begin{codeexample}[]
\pgfkeys{
  /handlers/first char syntax=true,
  /handlers/first char syntax/the character '/.initial=\mysinglequotemacro
}

\def\mysinglequotemacro#1{\pgfkeysalso{label={#1}}}

\tikz \node [circle, 'foo', draw] {bar};
\end{codeexample}

Note that in the above example, the macro |\mysinglequotemacro| gets passed the
complete string, including the single quotes. It is the job of the macro to get
rid of them, if this is necessary.

The first char syntax detection allows you to perform rather powerful
transformations on the syntax of keys -- provided you can ``pin down'' the
syntax on the first character. In the following example, you can write
expressions in parentheses in front of a key--value pair and the pair will only
be executed when the expression evaluates to true:
%
\begin{codeexample}[]
\pgfkeys{
  /handlers/first char syntax=true,
  /handlers/first char syntax/the character (/.initial=\myparamacro
}

\def\myparamacro#1{\myparaparser#1\someendtext}
\def\myparaparser(#1)#2\someendtext{
  \pgfmathparse{#1}
  \ifx\pgfmathresult\onetext
    \pgfkeysalso{#2}
  \fi
}
\def\onetext{1}

\foreach \i in {1,...,4}
  \tikz \node [draw, thick, rectangle, (pi>\i) circle, (pi>\i*2) draw=red] {x};
\end{codeexample}


\subsubsection{Default Arguments}

The arguments of the |\pgfkeys| command can either be of the form
\meta{key}|=|\meta{value} or of the form \meta{key} with the value-part
missing. In the second case, the |\pgfkeys| will try to provide a \emph{default
value} for the \meta{value}. If such a default value is defined, it will be
used as if you had written \meta{key}|=|\meta{default value}.

In the following, the details of how default values are determined is
described; however, you should normally use the handlers |/.default| and
|/.value required| as described in Section~\ref{section-default-handlers} and
you may wish to skip the following details.

When |\pgfkeys| encounters a \meta{key} without an equal-sign, the following
happens:
%
\begin{enumerate}
    \item The input is replaced by \meta{key}|=\pgfkeysnovalue|. In particular,
        the commands |\pgfkeys{my key}| and
        % FIXME: there is a bug in the pretty printer ... fix it and get rid of '||' here:
        |\pgfkeys{my key=||\pgfkeysnovalue}| have exactly the same effect and
        you can ``simulate'' a missing value by providing the value
        |\pgfkeysnovalue|, which is sometimes useful.
    \item If the \meta{value} is |\pgfkeysnovalue|, then it is checked whether
        the subkey \meta{key}|/.@def| exists. For instance, if you write
        |\pgfkeys{/my key}|, then it is checked whether the key |/my key/.@def|
        exists.
    \item If the key \meta{key}|/.@def| exists, then the tokens stored in this
        key are used as \meta{value}.
    \item If the key does not exist, then |\pgfkeysnovalue| is used as the
        \meta{value}.
    \item At the end, if the \meta{value} is now equal to
        |\pgfkeysvaluerequired|, then the code (or something fairly equivalent)
        |\pgfkeys{/errors/value required=|\meta{key}|{}}| is executed. Thus, by
        changing this key you can change the error message that is printed or
        you can handle the missing value in some other way.
\end{enumerate}


\subsubsection{Keys That Execute Commands}
\label{section-key-code}

After the transformation process described in the previous subsection, we
arrive at a key of the form \meta{key}=\meta{value}, where \meta{key} is a full
key. Different things can now happen, but always the macro |\pgfkeyscurrentkey|
will have been set up to expand to the text of the \meta{key} that is currently
being processed.

The first things that is tested is whether the key \meta{key}|/.@cmd| exists.
If this is the case, then it is assumed that this key stores the code of a
macro and this macro is executed. The argument of this macro is \meta{value}
directly followed by |\pgfeov|, which stands for ``end of value''. The
\meta{value} is not surrounded by braces. After this code has been executed,
|\pgfkeys| continues with the next key in the \meta{key list}.

It may seem quite peculiar that the macro stored in the key \meta{key}|/.@cmd|
is not simply executed with the argument |{|\meta{value}|}|. However, the
approach taken in the |pgfkeys| packages allows for more flexibility. For
instance, assume that you have a key that expects a \meta{value} of the form
``\meta{text}|+|\meta{more text}'' and wishes to store \meta{text} and
\meta{more text} in two different macros. This can be achieved as follows:
%
\begin{codeexample}[]
\def\mystore#1+#2\pgfeov{\def\a{#1}\def\b{#2}}
\pgfkeyslet{/my key/.@cmd}{\mystore}
\pgfkeys{/my key=hello+world}

|\a| is \a, |\b| is \b.
\end{codeexample}

Naturally, defining the code to be stored in a key in the above manner is too
awkward. The following commands simplify things a bit, but the usual manner of
setting up code for a key is to use one of the handlers described in
Section~\ref{section-code-handlers}.

\begin{command}{\pgfkeysdef\marg{key}\marg{code}}
    This command temporarily defines a \TeX-macro with the argument list
    |#1\pgfeov| and then lets \meta{key}|/.@cmd| be equal to this macro. The
    net effect of all this is that you have then set up code for the key
    \meta{key} so that when you write |\pgfkeys{|\meta{key}|=|\meta{value}|}|,
    then the \meta{code} is executed with all occurrences of |#1| in
    \meta{code} being replaced by \meta{value}. (This behaviour is quite
    similar to the |\define@key| command of |keyval| and |xkeyval|).
    %
\begin{codeexample}[]
\pgfkeysdef{/my key}{#1, #1.}
\pgfkeys{/my key=hello}
\end{codeexample}
\end{command}

\begin{command}{\pgfkeysedef\marg{key}\marg{code}}
    This command works like |\pgfkeysdef|, but it uses |\edef| rather than
    |\def| when defining the key macro. If you do not know the difference
    between the two, then you will not need this command; and if you know the
    difference, then you will know when you need this command.
\end{command}

\begin{command}{\pgfkeysdefnargs\marg{key}\marg{argument count}\marg{code}}
    This command works like |\pgfkeysdef|, but it allows you to provide an
    arbitrary \meta{argument count} between $0$ and $9$ (inclusive).
    %
\begin{codeexample}[]
\pgfkeysdefnargs{/my key}{2}{\def\a{#1}\def\b{#2}}
\pgfkeys{/my key=
    {hello}
    {world}}

|\a| is `\a', |\b| is `\b'.
\end{codeexample}
    %
    The resulting key will expect exactly \marg{argument count} arguments.
\end{command}
%
\begin{command}{\pgfkeysedefnargs\marg{key}\marg{argument count}\marg{code}}
    The |\edef| version of |\pgfkeysdefnargs|.
\end{command}

\begin{command}{\pgfkeysdefargs\marg{key}\marg{argument pattern}\marg{code}}
    This command works like |\pgfkeysdefnargs|, but it allows you to provide an
    arbitrary \meta{argument pattern} rather than just a number of arguments.
    %
\begin{codeexample}[]
\pgfkeysdefargs{/my key}{#1+#2}{\def\a{#1}\def\b{#2}}
\pgfkeys{/my key=hello+world}

|\a| is \a, |\b| is \b.
\end{codeexample}
    %
    Note that |\pgfkeysdefnargs| is \emph{better} when it comes to simple
    argument \emph{counts}\footnote{When the resulting keys are used, the
    \texttt{defnargs} variant allows spaces between arguments whereas the
    \texttt{defargs} variant does not; it considers the spaces as part of the
    argument.}.
\end{command}

\begin{command}{\pgfkeysedefargs\marg{key}\marg{argument pattern}\marg{code}}
    The |\edef| version of |\pgfkeysdefargs|.
\end{command}


\subsubsection{Keys That Store Values}

Let us continue with what happens when |\pgfkeys| processes the current key and
the subkey \meta{key}|/.@cmd| is not defined. Then it is checked whether the
\meta{key} itself exists (has been previously assigned a value using, for
instance, |\pgfkeyssetvalue|). In this case, the tokens stored in \meta{key}
are replaced by \meta{value} and |\pgfkeys| proceeds with the next key in the
\meta{key list}.


\subsubsection{Keys That Are Handled}
\label{section-key-handlers}

If neither the \meta{key} itself nor the subkey \meta{key}|/.@cmd| are defined,
then the \meta{key} cannot be processed ``all by itself''. Rather, a
\meta{handler} is needed for this key. Most of the power of |pgfkeys| comes
from the proper use of such handlers.

Recall that the \meta{key} is always a full key (if it was not originally, it
has already been upgraded at this point to a full key). It decomposed into two
parts:

\begin{enumerate}
    \item The \meta{path} of \meta{key} (everything before the last slash) is
        stored in the macro |\pgfkeyscurrentpath|.
    \item The \meta{name} of \meta{key} (everything after the last slash) is
        stored in the macro |\pgfkeyscurrentname|.

        It is recommended (but not necessary) that the name of a handler starts
        with a dot (but not with |.@|), so that they are easy to detect for the
        reader.
\end{enumerate}

(For efficiency reasons, these two macros are only set up at this point; so
when code is executed for a key in the ``usual'' manner then these macros are
not set up.)

The |\pgfkeys| command now checks whether the key
|/handlers/|\meta{name}|/.@cmd| exists. If so, it should store a command and
this command is executed exactly in the same manner as described in
Section~\ref{section-key-code}. Thus, this code gets the \meta{value} that was
originally intended for \meta{key} as its argument, followed by |\pgfeov|. It
is the job of the handlers to do something useful with the \meta{value}.

For an example, let us write a handler that will output the value stored in a
key to the log file. We call this handler |/.print to log|. The idea is that
when someone tries to use the key |/my key/.print to log|, then this key will
not be defined and the handler gets executed. The handler will then have access
to the path-part of the key, which is |/my key|, via the macro
|\pgfkeyscurrentpath|. It can then lookup which value is stored in this key and
print it.
%
\begin{codeexample}[code only]
\pgfkeysdef{/handlers/.print to log}
{%
  \pgfkeysgetvalue{\pgfkeyscurrentpath}{\temp}
  \writetolog{\temp}
}
\pgfkeyssetvalue{/my key}{Hi!}
...
\pgfkeys{/my key/.print to log}
\end{codeexample}
%
The above code will print |Hi!| in the log, provided the macro |\writetolog| is
set up appropriately.

For a more interesting handler, let us program a handler that will set up a key
so that when the key is used, some code is executed. This code is given as
\meta{value}. All the handler must do is to call |\pgfkeysdef| for the path of
the key (which misses the handler's name) and assign the parameter value to it.
%
\begin{codeexample}[]
\pgfkeysdef{/handlers/.my code}{\pgfkeysdef{\pgfkeyscurrentpath}{#1}}
\pgfkeys{/my key/.my code=(#1)}
\pgfkeys{/my key=hallo}
\end{codeexample}

There are some parameters for handled keys which prove to be useful in some
(possibly rare) special cases:
%
\begin{key}{/handler config=\mchoice{all,only existing,full or existing} (initially all)}
    Changes the initial configuration how key handlers will be used.

    This configuration is for advanced users and rarely necessary.
    %
    \begin{description}
        \item[\texttt{all}] The preconfigured setting |all| works as described
            above and imposes no restriction on the key setting process.
        \item[\texttt{only existing}] The value |only existing| modifies the
            algorithm for handled keys as follows: a handler \meta{key
            name}|/.|\meta{handler} will be executed only if \meta{key name} is
            either a key which stores its value directly or a command key for
            which |/.@cmd| exists. If \meta{key name} does \emph{not} exist
            already, the complete string \meta{key name}|/.|\meta{handler} is
            considered to be an unknown key and the procedure described in the
            next section applies (for the path of \meta{key name}).
            %
\begin{codeexample}[]
% Define a test key and error handlers:
\pgfkeys{/the/key/.code={Initial definition. }}
\pgfkeys{/handlers/.unknown/.code={Unknown key `\pgfkeyscurrentkey'. }}

% calling the test key yields 'Initial definition. ':
\pgfkeys{/the/key}

% Change configuration:
\pgfkeys{/handler config=only existing}

% allowed: key *re*-definition:
\pgfkeys{/the/key/.code={Re-Definition. }}
% calling the key yields 'Re-Definition. ':
\pgfkeys{/the/key}

% not allowed: definition of new keys:
% this checks for '/the/other key/.unknown'
% and '/handlers/.unknown'
% and yields finally
% 'Unknown key `/the/other key/.code`'
\pgfkeys{/the/other key/.code={New definition. }}
\end{codeexample}
            %
            It is necessary to exclude some key handlers from this procedure.
            Altogether, the detailed procedure is as follows:
            %
            \begin{enumerate}
                \item If a handled key like |/a path/a key/.a handler=value| is
                    encountered, it is checked whether the handler should be
                    invoked. This is the case if
                    %
                    \begin{itemize}
                        \item An exception from |only existing| for this key
                            exists (see below),
                        \item The key |/a path/a key| exists already -- either
                            directly as storage key or with the |.@cmd| suffix.
                    \end{itemize}
                    %
                \item If the check passes, everything works as before.
                \item If the check fails, the complete key will be considered
                    to be unknown. In that case, the handling of unknown keys
                    as described in the next section applies. There, the
                    current key path will be set to |/a path| and the current
                    key's name to |key/.a handler|.
            \end{enumerate}

            A consequence of this configuration is to provide more meaningful
            processing of handled keys if a search path for keys is in effect,
            see section~\ref{sec:pgf:unknown:keys} for an example.
        \item[\texttt{full or existing}] Finally, the choice |full or existing|
            is a variant of |only existing|: it works in the same way for keys
            which do not have a full key path. For example, the style

            |\pgfkeys{/my path/.cd,key/.style={|$\dotsc$|}}|

            can only be redefined: it doesn't have a full path, so the
            |only existing| mechanism applies. But the style

            |\pgfkeys{/my path/key/.style={|$\dotsc$|}}|

            will still work. This allows users to override the |only existing|
            feature if they know what they're doing (and provide full key
            paths).
    \end{description}
\end{key}

\begin{key}{/handler config/only existing/add exception=\marg{key handler name}}
    Allows to add exceptions to the |/handler config=only existing| feature.
    Initially exceptions for the key handlers |/.cd|, |/.try|, |/.retry|,
    |/.lastretry| and |/.unknown| are defined. The value \marg{key handler
    name} should be the name of a key handler.
\end{key}


\subsubsection{Keys That Are Unknown}
\label{sec:pgf:unknown:keys}

For some keys, neither the key, nor its |.@cmd| subkey nor a handler is
defined. In this case, it is checked whether the key \meta{current
path}|/.unknown/.@cmd| exists. Thus, when you try to use the key
|/tikz/strange|, then it is checked whether |/tikz/.unknown/.@cmd| exists. If
this key exists (which it does), it is executed. This code can then try to make
sense of the key. For instance, the handler for \tikzname\ will try to
interpret the key's name as a color or as an arrow specification or as a
\pgfname\ option.

You can set up unknown key handlers for your own keys by simply setting the
code of the key \meta{my path prefix}|/.unknown|. This also allows you to set
up ``search paths''. The idea is that you would like keys to be searched not
only in a single default path, but in several. Suppose, for instance, that you
would like keys to be searched for in |/a|, |/b|, and |/b/c|. We set up a key
|/my search path| for this:
%
\begin{codeexample}[code only]
\pgfkeys{/my search path/.unknown/.code=
  {%
    \let\searchname=\pgfkeyscurrentname%
    \pgfkeysalso{%
      /a/\searchname/.try=#1,
      /b/\searchname/.retry=#1,
      /b/c/\searchname/.retry=#1%
    }%
  }%
}
\pgfkeys{/my search path/.cd,foo,bar}
\end{codeexample}
%
In the above code, |foo| and |bar| will be searched for in the three
directories  |/a|, |/b|, and |/b/c|. Before you start implementing search paths
using this pattern, consider the |/.search also| handler discussed below.

If the key \meta{current path}|/.unknown/.@cmd| does not exist, the handler
|/handlers/.unknown| is invoked instead, which is always defined and which
prints an error message by default.


\subsubsection{Search Paths And Handled Keys}

There is one special case which occurs in the search path example above. What
happens if we want to change a style? For example,
%
\begin{codeexample}[code only]
\pgfkeys{/my search path/.cd,custom/.style={variables}}
\end{codeexample}
%
\noindent could mean a style in |/my search path/|, |/a/|, |/b/| or even
|/b/c/|!

Due to the rules for handled keys, the answer is
|/my search path/custom/.style={variables}|. It may be useful to modify this
default behavior. One useful thing would be to search for \emph{existing}
styles named |custom| and redefine them. For example, if a style |/b/custom|
exists, the assignment |custom/.style={variables}| should probably redefine
|/b/custom| instead of |/my search path/custom|. This can be done using
|handler config|:
%
\begin{codeexample}[]
\pgfkeys{/my search path/.unknown/.code=
  {%
    \let\searchname=\pgfkeyscurrentname%
    \pgfkeysalso{%
      /a/\searchname/.try=#1,
      /b/\searchname/.retry=#1,
      /b/c/\searchname/.retry=#1%
    }%
  }%
}

% Let's define /b/custom here:
\pgfkeys{/b/custom/.code={This is `\pgfkeyscurrentkey'. }}

% Reconfigure treatment of key handlers:
\pgfkeys{/handler config=only existing}

% The search path procedure will find /b/custom
% -> leads to This is `/b/custom'
\pgfkeys{/my search path/.cd,custom}

% Due to the reconfiguration, this will find /b/custom instead of
% defining /my search path/custom:
\pgfkeys{/my search path/.cd,custom/.append code={Modified. }}

% So using the search path, we again find /b/custom which
% leads to This is `/b/custom' Modified
\pgfkeys{/my search path/.cd,custom}
\end{codeexample}

A slightly different approach to search paths can be realized using the
|/.search also| key handler, see below.


\subsection{Key Handlers}

We now describe which key handlers are defined by default. You can also define
new ones as described in Section~\ref{section-key-handlers}.


\subsubsection{Handlers for Path Management}

\begin{handler}{{.cd}}
    This handler causes the default path to be set to \meta{key}. Note that the
    default path is reset at the beginning of each call to |\pgfkeys| to be
    equal to~|/|.

    \example |\pgfkeys{/tikz/.cd,...}|
\end{handler}

\begin{handler}{{.is family}}
\label{section-is family-handler}
    This handler sets up things such that when \meta{key} is executed, then the
    current path is set to \meta{key}. A typical use is the following:
    %
\begin{codeexample}[code only]
\pgfkeys{/tikz/.is family}
\pgfkeys{tikz,line width=1cm}
\end{codeexample}
    %
    The effect of this handler is the same as if you had written
    \meta{key}|/.style=|\meta{key}|/.cd|, only the code produced by the
    |/.is family| handler is quicker.
\end{handler}


\subsubsection{Setting Defaults}
\label{section-default-handlers}

\begin{handler}{{.default}|=|\meta{value}}
    Sets the default value of \meta{key} to \meta{value}. This means that
    whenever no value is provided in a call to |\pgfkeys|, then this
    \meta{value} will be used instead.

    \example |\pgfkeys{/width/.default=1cm}|
\end{handler}

\begin{handler}{{.value required}}
    This handler causes the error message key |/erros/value required| to be
    issued whenever the \meta{key} is used without a value.

    \example |\pgfkeys{/width/.value required}|
\end{handler}

\begin{handler}{{.value forbidden}}
    This handler causes the error message key |/erros/value forbidden| to be
    issued whenever the \meta{key} is used with a value.

    This handler works be adding code to the code of the key. This means that
    you have to define the key first before you can use this handler.
    %
\begin{codeexample}[code only]
\pgfkeys{/my key/.code=I do not want an argument!}
\pgfkeys{/my key/.value forbidden}

\pgfkeys{/my key}     % Ok
\pgfkeys{/my key=foo} % Error
\end{codeexample}
    %
\end{handler}


\subsubsection{Defining Key Codes}
\label{section-code-handlers}

A number of handlers exist for defining the code of keys.

\begin{handler}{{.code}|=|\meta{code}}
    This handler executes |\pgfkeysdef| with the parameters \meta{key} and
    \meta{code}. This means that, afterwards, whenever the \meta{key} is used,
    the \meta{code} gets executed. More precisely, when
    \meta{key}|=|\meta{value} is encountered in a key list, \meta{code} is
    executed with any occurrence of |#1| replaced by \meta{value}. As always,
    if no \meta{value} is given, the default value is used, if defined, or the
    special value |\pgfkeysnovalue|.

    It is permissible that \meta{code} calls the command |\pgfkeys|. It is also
    permissible the \meta{code} calls the command |\pgfkeysalso|, which is
    useful for styles, see below.
    %
\begin{codeexample}[code only]
\pgfkeys{/par indent/.code={\parindent=#1},/par indent/.default=2em}
\pgfkeys{/par indent=1cm}
...
\pgfkeys{/par indent}
\end{codeexample}
    %
\end{handler}

\begin{handler}{{.ecode}|=|\meta{code}}
    This handler works like |/.code|, only the command |\pgfkeysedef| is used.
\end{handler}

\begin{handler}{{.code 2 args}|=|\meta{code}}
    This handler works like |/.code|, only two arguments rather than one are
    expected when the \meta{code} is executed. This means that when
    \meta{key}|=|\meta{value} is encountered in a key list, the \meta{value}
    should consist of two arguments. For instance, \meta{value} could be
    |{first}{second}|. Then \meta{code} is executed with any occurrence of |#1|
    replaced |first| and any occurrence of |#2| replaced by |second|.
    %
\begin{codeexample}[code only]
\pgfkeys{/page size/.code 2 args={\paperheight=#2\paperwidth=#1}}
\pgfkeys{/page size={30cm}{20cm}}
\end{codeexample}
    %
    The second argument is optional: if it is not provided, it will be the
    empty string.

    Because of the special way the \meta{value} is parsed, if you set
    \meta{value} to, for instance, |first| (without any braces), then |#1| will
    be set to |f| and |#2| will be set to |irst|.
\end{handler}

\begin{handler}{{.ecode 2 args}|=|\meta{code}}
    This handler works like |/.code 2 args|, only an |\edef| is used rather
    than a |\def| to define the macro.
\end{handler}

\begin{handler}{{.code n args}|=|\marg{argument count}\marg{code}}
    This handler also works like |/.code|, but you can now specify a number of
    arguments between $0$ and $9$ (inclusive).
    %
\begin{codeexample}[]
\pgfkeys{/a key/.code n args={2}{First=`#1', Second=`#2'}}
\pgfkeys{/a key={A}{B}}
\end{codeexample}
    %
    In contrast to |/.code 2 args|, there must be exactly \meta{argument count}
    arguments, not more and not less and these arguments should be properly
    delimited.
\end{handler}

\begin{handler}{{.ecode n args}|=|\marg{argument count}\marg{code}}
    This handler works like |/.code n args|, only an |\edef| is used rather
    than a |\def| to define the macro.
\end{handler}

\begin{handler}{{.code args}|=|\marg{argument pattern}\marg{code}}
    This handler is the most flexible way to define a |/.code| key: you can now
    specify an arbitrary \meta{argument pattern}. Such a pattern is a usual
    \TeX\ macro pattern. For instance, suppose \meta{argument pattern} is
    |(#1/#2)| and \meta{key}|=|\meta{value} is encountered in a key list with
    \meta{value} being |(first/second)|. Then \meta{code} is executed with any
    occurrence of |#1| replaced |first| and any occurrence of |#2| replaced by
    |second|. So, the actual \meta{value} is matched against the \meta{argument
    pattern} in the standard \TeX\ way.
    %
\begin{codeexample}[code only]
\pgfkeys{/page size/.code args={#1 and #2}{\paperheight=#2\paperwidth=#1}}
\pgfkeys{/page size=30cm and 20cm}
\end{codeexample}

    Note that |/.code n args| should be preferred in case you need just a
    number of arguments (when the resulting keys are used, |/.code n args|
    gobbles spaces between the arguments whereas |/.code args| considers spaces
    to be part of the argument).
\end{handler}

\begin{handler}{{.ecode args}|=|\marg{argument pattern}\marg{code}}
    This handler works like |/.code args|, only an |\edef| is used rather than
    a |\def| to define the macro.
\end{handler}

There are also handlers for modifying existing keys.

\begin{handler}{{.add code}|=|\marg{prefix code}\marg{append code}}
    This handler adds code to an existing key. The \meta{prefix code} is added
    to the code stored in \meta{key}|/.@cmd| at the beginning, the \meta{append
    code} is added to this code at the end. Either can be empty. The argument
    list of \meta{code} cannot be changed using this handler. Note that both
    \meta{prefix code} and \meta{append code} may contain parameters like |#2|.
    %
\begin{codeexample}[code only]
\pgfkeys{/par indent/.code={\parindent=#1}}
\newdimen\myparindent
\pgfkeys{/par indent/.add code={}{\myparindent=#1}}
...
\pgfkeys{/par indent=1cm} % This will set both \parindent and
                          % \myparindent to 1cm
\end{codeexample}
    %
\end{handler}

\begin{handler}{{.prefix code}|=|\meta{prefix code}}
    This handler is a shortcut for \meta{key}|/.add code={|\meta{prefix
    code}|}{}|. That is, this handler adds the \meta{prefix code} at the
    beginning of the code stored in \meta{key}|/.@cmd|.
\end{handler}

\begin{handler}{{.append code}|=|\meta{append code}}
    This handler is a shortcut for \meta{key}|/.add code={}{|\meta{append
    code}|}{}|.
\end{handler}


\subsubsection{Defining Styles}

The following handlers allow you to define \emph{styles}. A style is a key list
that is processed whenever the style is given as a key in a key list. Thus, a
style ``stands for'' a certain key value list. Styles can be parameterized just
like normal code.

\begin{handler}{{.style}|=|\meta{key list}}
    This handler sets things up so that whenever \meta{key}|=|\meta{value} is
    encountered in a key list, then the \meta{key list}, with every occurrence
    of |#1| replaced by \meta{value}, is processed instead. As always, if no
    \meta{value} is given, the default value is used, if defined, or the
    special value |\pgfkeysnovalue|.

    You can achieve the same effect by writing
    \meta{key}|/.code=\pgfkeysalso{|\meta{key list}|}|. This means, in
    particular, that the code of a key could also first execute some normal
    code and only then process some further keys.
    %
\begin{codeexample}[code only]
\pgfkeys{/par indent/.code={\parindent=#1}}
\pgfkeys{/no indent/.style={/par indent=0pt}}
\pgfkeys{/normal indent/.style={/par indent=2em}}
\pgfkeys{/no indent}
...
\pgfkeys{/normal indent}
\end{codeexample}
    %
    The following example shows a parameterized style ``in action''.
    %
\begin{codeexample}[]
\begin{tikzpicture}[outline/.style={draw=#1,fill=#1!20}]
  \node [outline=red]            {red box};
  \node [outline=blue] at (0,-1) {blue box};
\end{tikzpicture}
\end{codeexample}
    %
\end{handler}

\begin{handler}{{.estyle}|=|\meta{key list}}
    This handler works like |/.style|, only the \meta{code} is set using
    |\edef| rather than |\def|. Thus, all macros in the \meta{code} are
    expanded prior to saving the style.
\end{handler}

For styles the corresponding handlers as for normal code exist:

\begin{handler}{{.style 2 args}|=|\meta{key list}}
    This handler works like |/.code 2 args|, only for styles. Thus, the
    \meta{key list} may contain occurrences of both |#1| and |#2| and when the
    style is used, two parameters must be given as \meta{value}.
    %
\begin{codeexample}[code only]
\pgfkeys{/paper height/.code={\paperheight=#1},/paper width/.code={\paperwidth=#1}}
\pgfkeys{/page size/.style 2 args={/paper height=#1,/paper width=#2}}
\pgfkeys{/page size={30cm}{20cm}}
\end{codeexample}
    %
\end{handler}

\begin{handler}{{.estyle 2 args}|=|\meta{key list}}
    This handler works like |/.style 2 args|, only an |\edef| is used rather
    than a |\def| to define the macro.
\end{handler}

\begin{handler}{{.style args}|=|\marg{argument pattern}\marg{key list}}
    This handler works like |/.code args|, only for styles.
\end{handler}

\begin{handler}{{.estyle args}|=|\marg{argument pattern}\marg{code}}
    This handler works like |/.ecode args|, only for styles.
\end{handler}

\begin{handler}{{.style n args}|=|\marg{argument count}\meta{key list}}
    This handler works like |/.code n args|, only for styles. Here, \meta{key
    list} may depend on all \meta{argument count} parameters.
\end{handler}

\begin{handler}{{.add style}|=|\marg{prefix key list}\marg{append key list}}
    This handler works like |/.add code|, only for styles. However, it is
    permissible to add styles to keys that have previously been set using
    |/.code|. (It is also permissible to add normal \meta{code} to a key that
    has previously been set using |/.style|). When you add a style to a key
    that was previously set using |/.code|, the following happens: When
    \meta{key} is processed, the \meta{prefix key list} will be processed
    first, then the \meta{code} that was previously stored in
    \meta{key}|/.@cmd|, and then the keys in \meta{append key list} are
    processed.
    %
\begin{codeexample}[code only]
\pgfkeys{/par indent/.code={\parindent=#1}}
\pgfkeys{/par indent/.add style={}{/my key=#1}}
...
\pgfkeys{/par indent=1cm} % This will set \parindent and
                          % then execute /my key=#1
\end{codeexample}
    %
\end{handler}

\begin{handler}{{.prefix style}|=|\meta{prefix key list}}
    Works like |/.add style|, but only for the prefix key list.
\end{handler}

\begin{handler}{{.append style}|=|\meta{append key list}}
    Works like |/.add style|, but only for the append key list.
\end{handler}


\subsubsection{Defining Value-, Macro-, If- and Choice-Keys}

For some keys, the code that should be executed for them is rather
``specialized''. For instance, it happens often that the code for a key just
sets a certain \TeX-if to true or false. For these cases, predefined handlers
make it easier to install the necessary code.

However, we start with some handlers that are used to manage the value that is
directly stored in a key.

\begin{handler}{{.initial}|=|\meta{value}}
    This handler sets the value of \meta{key} to \meta{value}. Note that no
    subkeys are involved. After this handler has been used, by the rules
    governing keys, you can subsequently change the value of the \meta{key} by
    just writing \meta{key}|=|\meta{value}. Thus, this handler is used to set
    the initial value of key.
    %
\begin{codeexample}[code only]
\pgfkeys{/my key/.initial=red}
% "/my key" now stores the value "red"
\pgfkeys{/my key=blue}
% "/my key" now stores the value "blue"
\end{codeexample}

    Note that with this configuration, writing |\pgfkeys{/my key}| will not
    have the effect you might expect (namely that |blue| is inserted into the
    main text). Rather, |/my key| will be promoted to |/my key=\pgfkeysnovalue|
    and, thus, |\pgfkeysnovalue| will be stored in |/my key|.

    To retrieve the value stored in a key, the handler |/.get| is used.
\end{handler}

\begin{handler}{{.get}|=|\meta{macro}}
    Executes a |\let| command so that \meta{macro} contains the contents stored
    in \meta{key}.
    %
\begin{codeexample}[]
\pgfkeys{/my key/.initial=red}
\pgfkeys{/my key=blue}
\pgfkeys{/my key/.get=\mymacro}
\mymacro
\end{codeexample}
    %
\end{handler}

\begin{handler}{{.add}|=|\marg{prefix value}\marg{append value}}
    Adds the \meta{prefix value} and the beginning and the \meta{append value}
    at the end of the value stored in \meta{key}.
\end{handler}

\begin{handler}{{.prefix}|=|\marg{prefix value}}
    Adds the \meta{prefix value} and the beginning of the value stored in
    \meta{key}.
\end{handler}

\begin{handler}{{.append}|=|\marg{append value}}
    Adds the \meta{append value} at the end of the value stored in \meta{key}.
\end{handler}

\begin{handler}{{.link}|=|\meta{another key}}
    Stores the value |\pgfkeysvalueof{|\meta{another key}|}| in the \meta{key}.
    The idea is that when you expand the \meta{key}, the value of \meta{another
    key} is expanded instead. This corresponds loosely to the notion of soft
    links in Unix, hence the name.
\end{handler}

The next handler is useful for the common situation where
\meta{key}|=|\meta{value} should cause the \meta{value} to be stored in some
macro. Note that, typically, you could just as well store the value in the key
itself.

\begin{handler}{{.store in}|=|\meta{macro}}
    This handler has the following effect: When you write
    \meta{key}|=|\meta{value}, the code |\def|\meta{macro}|{|\meta{value}|}| is
    executed. Thus, the given value is ``stored'' in the \meta{macro}.
    %
\begin{codeexample}[]
\pgfkeys{/text/.store in=\mytext}
\def\a{world}
\pgfkeys{/text=Hello \a!}
\def\a{Gruffalo}
\mytext
\end{codeexample}
    %
\end{handler}

\begin{handler}{{.estore in}|=|\meta{macro}}
    This handler is similar to |/.store in|, only the code
    |\edef|\meta{macro}|{|\meta{value}|}| is used. Thus, the macro-expanded
    version of \meta{value} is stored in the \meta{macro}.
    %
\begin{codeexample}[]
\pgfkeys{/text/.estore in=\mytext}
\def\a{world}
\pgfkeys{/text=Hello \a!}
\def\a{Gruffalo}
\mytext
\end{codeexample}
    %
\end{handler}

In another common situation a key is used to set a \TeX-if to true or false.

\begin{handler}{{.is if}|=|\meta{\TeX-if name}}
    This handler has the following effect: When you write
    \meta{key}|=|\meta{value}, it is first checked that \meta{value} is |true|
    or |false| (the default is |true| if no \meta{value} is given). If this is
    not the case, the error key |/errors/boolean expected| is executed.
    Otherwise, the code |\|\meta{\TeX-if name}\meta{value} is executed, which
    sets the \TeX-if accordingly.
    %
\begin{codeexample}[]
\newif\iftheworldisflat
\pgfkeys{/flat world/.is if=theworldisflat}
\pgfkeys{/flat world=false}
\iftheworldisflat
  Flat
\else
  Round?
\fi
\end{codeexample}
    %
\end{handler}

The next handler deals with the problem when a \meta{key}|=|\meta{value} makes
sense only for a small set of possible \meta{value}s. For instance, the line
cap can only be |rounded| or |rect| or |butt|, but nothing else. For this
situation the following handler is useful.

\begin{handler}{{.is choice}}
    This handler sets things up so that writing \meta{key}|=|\meta{value} will
    cause the subkey \meta{key}|/|\meta{value} to be executed. So, each of the
    different possible choices should be given by a subkey of \meta{key}.
    %
\begin{codeexample}[code only]
\pgfkeys{/line cap/.is choice}
\pgfkeys{/line cap/round/.style={\pgfsetbuttcap}}
\pgfkeys{/line cap/butt/.style={\pgfsetroundcap}}
\pgfkeys{/line cap/rect/.style={\pgfsetrectcap}}
\pgfkeys{/line cap/rectangle/.style={/line cap=rect}}
...
\draw [/line cap=butt] ...
\end{codeexample}
    %
    If the subkey \meta{key}|/|\meta{value} does not exist, the error key
    |/errors/unknown choice value| is executed.
\end{handler}


\subsubsection{Expanded and Multiple Values}

When you write \meta{key}|=|\meta{value}, you usually wish to use the
\meta{value} ``as is''. Indeed, great care is taken to ensure that you can even
use things like |#1| or unbalanced \TeX-ifs inside \meta{value}. However,
sometimes you want the \meta{value} to be expanded before it is used. For
instance, \meta{value} might be a macro name like |\mymacro| and you do not
want |\mymacro| to be used as the macro, but rather the \emph{contents} of
|\mymacro|. Thus, instead of using \meta{value}, you wish to use whatever
\meta{value} expands to. Instead of using some fancy |\expandafter| hackery,
you can use the following handlers:

\begin{handler}{{.expand once}|=|\meta{value}}
    This handler expands \meta{value} once (more precisely, it executes an
    |\expandafter| command on the first token of \meta{value}) and then process
    the resulting \meta{result} as if you had written
    \meta{key}|=|\meta{result}. Note that if \meta{key} contains a handler
    itself, this handler will be called normally.
    %
\begin{codeexample}[]
\def\a{bottom}
\def\b{\a}
\def\c{\b}

\pgfkeys{/key1/.initial=\c}
\pgfkeys{/key2/.initial/.expand once=\c}
\pgfkeys{/key3/.initial/.expand twice=\c}
\pgfkeys{/key4/.initial/.expanded=\c}

\def\a{{\ttfamily\string\a}}
\def\b{{\ttfamily\string\b}}
\def\c{{\ttfamily\string\c}}

\begin{tabular}{ll}
Key 1:& \pgfkeys{/key1} \\
Key 2:& \pgfkeys{/key2} \\
Key 3:& \pgfkeys{/key3} \\
Key 4:& \pgfkeys{/key4}
\end{tabular}
\end{codeexample}
    %
\end{handler}

\begin{handler}{{.expand twice}|=|\meta{value}}
    This handler works like saying
    \meta{key}|/.expand once/.expand once=|\meta{value}.
\end{handler}

\begin{handler}{{.expanded}|=|\meta{value}}
    This handler will completely expand \meta{value} (using |\edef|) before
    processing \meta{key}|=|\meta{result}.
\end{handler}

\begin{handler}{{.list}|=|\meta{comma-separated list of values}}
    This handler causes the key to be used repeatedly, namely once for every
    element of the list of values. Note that the list of values should
    typically be surrounded by braces since, otherwise, \TeX\ will not be able
    to tell whether a comma starts a new key or a new value.

    The \meta{list of values} is processed using the |\foreach| statement, so
    you can use the |...| notation.
    %
\begin{codeexample}[]
\pgfkeys{/foo/.code=(#1)}
\pgfkeys{/foo/.list={a,b,0,1,...,5}}
\end{codeexample}
    %
\end{handler}


\subsubsection{Handlers for Forwarding}

\begin{handler}{{.forward to}|=|\meta{another key}}
    This handler causes the \meta{key} to ``forward'' its argument to
    \meta{another key}. When the \meta{key} is used, its normal code will be
    executed first. Then, the value is (additionally) passed to \meta{another
    key}. If the \meta{key} has not yet been defined prior to the use of
    |.forward to|, it will be defined then (and do nothing by itself, expect
    for forwarding it to \meta{key name}). The \meta{another key} must be a
    fully qualified key name.
    %
\begin{codeexample}[]
\pgfkeys{
  /a/.code=(a:#1),
  /b/.code=(b:#1),
  /b/.forward to=/a,
  /c/.forward to=/a
}
\pgfkeys{/b=1} \pgfkeys{/c=2}
\end{codeexample}
    %
\end{handler}

\begin{handler}{{.search also}=\marg{path list}}
    A style which installs a |/.unknown| handler into \meta{key}. This
    |/.unknown| handler will then search for unknown keys in every path
    provided in \marg{path list}.
    %
\begin{codeexample}[]
% define a key:
\pgfkeys{/secondary path/option/.code={Invoking /secondary path/option with `#1'}}

% set up a search path:
\pgfkeys{/main path/.search also={/secondary path}}

% try searching for `option=value' in '/main path':
% -> this finds `/secondary path/option'!
\pgfkeys{/main path/.cd,option=value}
\end{codeexample}

    The |/.search also| handler follows the strategy
    %
    \begin{enumerate}
        \item If a user provides a fully qualified key which could not be
            found, for example the full string |/main path/option|, it assume
            that the user knew what she is doing -- and does \emph{not}
            continue searching for |an option| in \marg{path list}.
        \item If a user provides only the key's name, for example |option| and
            |option| cannot be found in the current default path (which is
            |/main path| in our example above), the current default path is set
            to the next element in \marg{path list} (which is |/secondary path|
            here) and |\pgfkeys| will be restarted.

            This will be iterated until either a match has been found or all
            elements in \marg{path list} have been tested. \item If all
            elements in \marg{path list} have been checked and the key is still
            unknown, the fall-back handler |/handlers/.unknown| will be
            invoked.
    \end{enumerate}
    %
\begin{codeexample}[]
% define a key:
\pgfkeys{/secondary path/option/.code={Invoking /secondary path/option with `#1'}}

% set up a search path:
\pgfkeys{/main path/.search also={/secondary path}}

% try searching for `option=value' in '/main path':
% -> this finds `/secondary path/option'!
\pgfkeys{/main path/.cd,option=value}

% negative example:
% try searching for fully qualified key /main path/option.
% This won't be handled by .search also.
\pgfkeys{/handlers/.unknown/.code={Found unknown option \pgfkeyscurrentkeyRAW={#1}!}}%
\pgfkeys{/main path/.cd,/main path/option=value}
\end{codeexample}

    Please note that the strategy of |/.search also| is different from the
    first example provided in section~\ref{sec:pgf:unknown:keys} ``Unknown
    Keys'' because |/.search also| only applies to keys that are not fully
    qualified.

    For those who are familiar with |\pgfkeys|, the actual implementation of
    |/.search also| might be interesting:
    %
    \begin{enumerate}
        \item |\pgfkeys{/path/.search also={/tikz}}| is equivalent to
            %
\begin{codeexample}[code only]
\pgfkeys{/path/.unknown/.code={%
        \ifpgfkeysaddeddefaultpath
            % only process keys for which no full path has been
            % provided:
            \pgfkeyssuccessfalse
            \let\pgfkeys@searchalso@name =\pgfkeyscurrentkeyRAW
            \ifpgfkeyssuccess
            \else
                % search with /tikz as default path:
                \pgfqkeys{/tikz}{\pgfkeys@searchalso@name={#1}}%
            \fi
        \else
            \def\pgfutilnext{\pgfkeysvalueof {/handlers/.unknown/.@cmd}#1\pgfeov}%
            \pgfutilnext
        \fi
    }
}
\end{codeexample}
            %
        \item |\pgfkeys{/path/.search also={/tikz,/pgf}}| is equivalent to
            %
\begin{codeexample}[code only]
\pgfkeys{/path/.unknown/.code={%
        \ifpgfkeysaddeddefaultpath
            \pgfkeyssuccessfalse
            \let\pgfkeys@searchalso@name=\pgfkeyscurrentkeyRAW
            \ifpgfkeyssuccess
            \else
                % step 1: search in /tikz with .try:
                \pgfqkeys{/tikz}{\pgfkeys@searchalso@name/.try={#1}}%
            \fi
            \ifpgfkeyssuccess
            \else
                % step 2: search in /pgf (without .try!):
                \pgfqkeys{/pgf}{\pgfkeys@searchalso@name={#1}}%
            \fi
        \else
            \def\pgfutilnext{\pgfkeysvalueof {/handlers/.unknown/.@cmd}#1\pgfeov}%
            \pgfutilnext
        \fi
    }
}
\end{codeexample}
    \end{enumerate}

    To also enable searching for styles (or other handled keys), consider
    changing the configuration for handled keys to
    |/hander config=full or existing| when you use |/.search also|, that is,
    use
    %
\begin{codeexample}[code only]
\pgfkeys{
   /main path/.search also={/secondary path},
   /handler config=full or existing}
\end{codeexample}
    %
\end{handler}


\subsubsection{Handlers for Testing Keys}

\begin{handler}{{.try}|=|\meta{value}}
    This handler causes the same things to be done as if
    \meta{key}|=|\meta{value} had been written instead. However, if neither
    \meta{key}|/.@cmd| nor the key itself is defined, no handlers will be
    called. Instead, the execution of the key just stops. Thus, this handler
    will ``try'' to use the key, but no further action is taken when the key is
    not defined.

    The \TeX-if |\||ifpgfkeyssuccess| will be set according to whether the
    \meta{key} was successfully executed or not.
    %
\begin{codeexample}[]
\pgfkeys{/a/.code=(a:#1)}
\pgfkeys{/b/.code=(b:#1)}
\pgfkeys{/x/.try=hmm,/a/.try=hallo,/b/.try=welt}
\end{codeexample}
    %
\end{handler}

\begin{handler}{{.retry}|=|\meta{value}}
    This handler works just like |/.try|, only it will not do anything if
    |\||ifpgfkeyssuccess| is false. Thus, this handler will only retry to set a
    key if ``the last attempt failed''.
    %
\begin{codeexample}[]
\pgfkeys{/a/.code=(a:#1)}
\pgfkeys{/b/.code=(b:#1)}
\pgfkeys{/x/.try=hmm,/a/.retry=hallo,/b/.retry=welt}
\end{codeexample}
    %
\end{handler}

\begin{handler}{{.lastretry}|=|\meta{value}}
    This handler works like |/.retry|, only it will invoke the usual handlers
    for unknowns keys if |\||ifpgfkeyssuccess| is false. Thus, this handler
    will only try to set a key if ``the last attempt failed''. Furthermore,
    this here is the last such attempt.
\end{handler}


\subsubsection{Handlers for Key Inspection}

\begin{handler}{{.show value}}
    This handler executes a |\show| command on the value stored in \meta{key}.
    This is useful mostly for debugging.

    \example |\pgfkeys{/my/obscure key/.show value}|
\end{handler}

\begin{handler}{{.show code}}
    This handler executes a |\show| command on the code stored in
    \meta{key}|/.@cmd|. This is useful mostly for debugging.

    \example |\pgfkeys{/my/obscure key/.show code}|
\end{handler}

The following key is not a handler, but it also commonly used for inspecting
things:
%
\begin{key}{/utils/exec=\meta{code}}
    This key will simply execute the given \meta{code}.

    % FIXME: there is a bug in the pretty printer ... fix it!
    \example \verb|\pgfkeys{some key=some value,/utils/exec=\show\hallo,obscure key=obscure}|
\end{key}


\subsection{Error Keys}

In certain situations errors can occur, like using an undefined key. In these
situations error keys are executed. They should store a macro that gets two
arguments: The first is the offending key (possibly only after macro
expansion), the second is the value that was passed as a parameter (also
possibly only after macro expansion).

Currently, error keys are simply executed. In the future it might be a good
idea to have different subkeys that are executed depending on the language
currently set so that users get a localized error message.

\begin{key}{/errors/value required=\marg{offending key}\marg{value}}
    This key is executed whenever an \meta{offending key} is used without a
    value when a value is actually required.
\end{key}

\begin{key}{/errors/value forbidden=\marg{offending key}\marg{value}}
    This key is executed whenever a key is used with a value when a value is
    actually forbidden.
\end{key}

\begin{key}{/errors/boolean expected=\marg{offending key}\marg{value}}
    This key is executed whenever a key set up using |/.is if| gets called with
    a \meta{value} other than |true| or |false|.
\end{key}

\begin{key}{/errors/unknown choice value=\marg{offending key}\marg{value}}
    This key is executed whenever a choice is used as a \meta{value} for a key
    set up using the |/.is choice| handler that is not defined.
\end{key}

\begin{key}{/errors/unknown key=\marg{offending key}\marg{value}}
    This key is executed whenever a key is unknown and no specific |/.unknown|
    handler is found.
\end{key}


\input{pgfmanual-en-pgfkeysfiltered.tex}
