3

As part of a different question (Detecting empty PGFKEYS), I posted a code fragment where I was told a space did not matter. I've been able to reproduce the case where it does. Can someone help me understand why a space is not allowed in the following code (see comment below)

MWE:

\documentclass{minimal}
\usepackage{pgfkeys}

\pgfkeys{
    /dir/.is family,
    /dir/akey/.code={do something}
}

\newcommand\test[1]{% Note, don't put a space between the , and the #1, why? I don
't know.
  \pgfkeys{/dir,#1}
}

\begin{document}
\test{
   akey
}

\end{document}

If you put a space after the comma in "/dir,#1", pdflatex rejects this code with the error "I don't know the key '/dir/ akey'". How come?

Hood Chatham
  • 5,467
  • 3
    This is because you accumulate too many spaces. If you remove the space in \distMarkup[ leftTailLabel = label number 1,, you can afford a space in \pgfkeys{/distMarkup, default, #1}. –  Jan 09 '20 at 14:05
  • Thanks. I don't know how to mark a question as answered when the answer is in a comment. Do you know how? – Christopher Donham Jan 09 '20 at 14:52

1 Answers1

4

What's happening here is this: latex normally combines as many spaces as it might see into one space: so latex automatically transforms a⎵⎵⎵b into a⎵b. So in particular, if you say \pgfkeys{ some key = some value } then it turns the spaces around the key into a single space. (Latex also transforms a single newline character into a space and combines it with neighboring spaces and ignores initial spaces in a line.) Then \pgfkeys removes a SINGLE space worth of padding around a key.

However, if you say \newcommand\somecommand[1]{#1 } and then say \somecommand{ } then this expands to two spaces next to each other. The removal of adjacent spaces is done at the time that the file is parsed, and these two spaces didn't start out next to each other.

In your example \pgfkeys sees "⎵⎵akey", turns that into "⎵akey" and then complains that "⎵akey" is an undefined key.

The spaces are removed from around the key by the command \pgfkeys@spdef which is used like \pgfkeys@spdef\somecommand{<some argument>} and defines \somecommand to be <some argument> with at most one space removed from the end and at most one space removed from the beginning. \pgfkeys@spdef is defined on line 466 of the file pgfkeys.code.tex.

The trimspaces package has a simpler approach to trimming spaces but it also only trims one space at the beginning and end of its argument.

Hood Chatham
  • 5,467
  • 1
    One can arrange to trim all spaces: see \tl_trim_spaces:n (or in 'classical' syntax https://tex.stackexchange.com/a/69771/73). – Joseph Wright Jan 09 '20 at 17:56
  • Thanks @JosephWright that's good to know. I hadn't realized until just now that trimspaces and \pgfkeys@spdef have this deficiency. LaTeX doesn't need more unusual edge case behavior. – Hood Chatham Jan 09 '20 at 19:33