pgf-tikz / pgfplots

pgfplots - A TeX package to draw normal and/or logarithmic plots directly in TeX in two and three dimensions with a user-friendly interface and pgfplotstable - a TeX package to round and format numerical tables. Examples in manuals and/or on web site.
http://pgfplots.sourceforge.net/
198 stars 33 forks source link

Extend `\pgfplotsforeachungrouped` to accept a macro as `<list>` #462

Open muzimuzhi opened 1 year ago

muzimuzhi commented 1 year ago

From https://tex.stackexchange.com/q/687866

\foreach supports both

\foreach \x in {1,2,3,0} {<loop body>}
% and
\def\mylist{1,2,3,0}
\foreach \x in \mylist {<loop body>}

but the simpler \pgfplotsforeachungrouped doesn't support the second syntax.

Adding support for this seems not expensive, for example

\documentclass{article}

\usepackage{pgfplots}
\pgfplotsset{compat=1.18}

\makeatletter
\long\def\pgfplotsforeachungrouped@#1/#2in{%
    \pgfutil@ifnextchar\bgroup{%
        \pgfplotsforeachungrouped@@{#1}{#2}%
    }{%
%       \pgfplots@error{Found unexpected characters: expected 'in '.}%
    \pgfplotsforeachungrouped@@@{#1}{#2}%
    }%
}

\long\def\pgfplotsforeachungrouped@@@#1#2#3{%
  \pgfkeys@expanded{\pgfutil@unexpanded{\pgfplotsforeachungrouped@@{#1}{#2}}{\pgfutil@unexpanded\expandafter{#3}}}%
}
\makeatother

\begin{document}
\setlength\parindent{0pt}
\newcommand{\xlabelsol}{0/0,1/1,2/2}

\foreach  \x/\y in \xlabelsol { (\x)(\y) \\ }
\pgfplotsforeachungrouped \x/\y in \xlabelsol { (\x)(\y) \\ }
\end{document}

Output is two copies of

(0)(0)
(1)(1)
(2)(2)

Use of \pgfkeys@expanded and \pgfutil@unexpanded (corresponding to primitives \expanded and \unexpanded) can be replaced with argument swapping and normal \expandafter tricks, at the cost of less readability.