Skip to content

declare function: Spaces not allowed in function's arg list #1123

@muzimuzhi

Description

@muzimuzhi

Brief outline of the bug

When declaring functions through key /pgf/declare function, spaces are not allowed in the arg list. For example func(\x,\y)=...; works well but func(\x,<space>\y) doesn't.

Minimal working example (MWE)

\documentclass{article}
\usepackage{pgfmath}

\pgfkeys{/pgf/declare function={
  funcA(\x,\y) = sqrt(\x^2+\y^2);
  funcB(\x, \y) = sqrt(\x^2+\y^2); 
}}

\makeatletter
% expected: #1#2->\pgfmathparse {sqrt(#1^2+#2^2)}
% actual:   #1#2->\pgfmathparse {sqrt(#1^2+\y ^2)}, note the `\y`
\show\pgfmathfuncB@
\makeatother

\begin{document}
\end{document}

Discussion

The pgfmanual examples use not a single space in such arg lists, but users are not as lucky as the manual. When declare function is used with plotting, it becomes even harder to find the cause. See TeX-SX questions https://tex.stackexchange.com/q/469153 and the ones linked to it (on TeX-SX).

This should either be documented or fixed. For a possible fix,

diff --git a/tex/generic/pgf/math/pgfmathfunctions.code.tex b/tex/generic/pgf/math/pgfmathfunctions.code.tex
index 6e5d079c..e3db1ed0 100644
--- a/tex/generic/pgf/math/pgfmathfunctions.code.tex
+++ b/tex/generic/pgf/math/pgfmathfunctions.code.tex
@@ -204,14 +204,18 @@
 
 \def\pgfmath@local@function@@body#1,{%
     \def\pgfmath@local@test{#1}%
+    % strip spaces in case #1 starts with a space, e.g., #1 is ` \y` 
+    % which comes from `func(\x, \y)=...;`
+    \expandafter\pgfkeys@spdef\expandafter\pgfmath@local@test\expandafter{\pgfmath@local@test}%
     \ifx\pgfmath@local@test\pgfutil@empty%
         \let\pgfmath@local@next=\relax%
     \else%
-        \edef\pgfmath@local@var@string{@\expandafter\pgfmath@local@gobbleone\string#1}%
+        \edef\pgfmath@local@var@string{%
+          @\expandafter\expandafter\expandafter\pgfmath@local@gobbleone\expandafter\string\pgfmath@local@test}%
         \advance\c@pgf@counta by1\relax%
         \expandafter\expandafter\expandafter\pgfmath@toks\expandafter\expandafter\expandafter=%
             \expandafter\expandafter\expandafter{\expandafter\pgfmath@char@hash\the\c@pgf@counta}%
-        \edef#1{\the\pgfmath@toks}%
+        \expandafter\edef\pgfmath@local@test{\the\pgfmath@toks}%
         \pgfmath@toks={}%
         \expandafter\pgfmath@local@function@@@body\pgfmath@local@body @%
         \edef\pgfmath@local@body{\the\pgfmath@toks}%

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions