1

The goal of the program below is to apply certain modification to the values of certain keys within a cs list. It works fine, except for removing the leading comma. Try with/out lines A and B.

\documentclass{report}
\usepackage{xparse}

%https://tex.stackexchange.com/questions/523083/keyval-parse-for-dummies/523085#523085

\ExplSyntaxOn
\cs_new_protected:Npn \my_keyval_parser:nn #1 #2
{

  \group_begin:

  \str_clear:N \l_tmpa_str

  \str_case:nnTF { #1 }
  {
    { foo } {,\tl_put_right:Nn \l_tmpa_str {#1=(#2)}}
    { bar } {,\tl_put_right:Nn \l_tmpa_str {#1=[#2]}}
  }
  {} 
  {\tl_put_right:Nn \l_tmpa_str{#1=#2}}

%  \exp_args:NV \str_tail:n\l_tmpa_str
\l_tmpa_str

  \group_end:

}

\cs_new_protected:Npn \my_key_parser:n #1
  {
    \str_case:nnTF { #1 }
      {
        { qux } {,QUX}
      }
      {}
      {}
  }


\begin{document}

\exp_args:Nf % A
\str_tail:n  % B
{
  \keyval_parse:NNn
  \my_key_parser:n
  \my_keyval_parser:nn
  {
    foo=World,
    bar=Universe,
    qux
  }
}%WANTED: foo=(World),bar=[Universe],QUX

\ExplSyntaxOff

\end{document}

enter image description here

enter image description here

Erwann
  • 2,100

1 Answers1

0

There are a few problems with your code. Here's a functioning version, comments will be added later.

\documentclass{report}
\usepackage{xparse}

\ExplSyntaxOn

\NewDocumentCommand{\test}{m}
 {
  \seq_clear:N \l_tmpa_seq
  \keyval_parse:NNn \my_key_parser:n \my_keyval_parser:nn { #1 }
  \seq_use:Nn \l_tmpa_seq { , }
 }

\cs_new_protected:Npn \my_keyval_parser:nn #1 #2
 {
  \str_case:nnF { #1 }
   {
    { foo } {\seq_put_right:Nn \l_tmpa_seq {#1=(#2)}}
    { bar } {\seq_put_right:Nn \l_tmpa_seq {#1=[#2]}}
   }
  {\seq_put_right:Nn \l_tmpa_seq {#1=#2}}
 }

\cs_new_protected:Npn \my_key_parser:n #1
 {
  \str_case:nn { #1 }
   {
    { qux } {\seq_put_right:Nn \l_tmpa_seq {QUX}}
   }
 }

\ExplSyntaxOff

\begin{document}

\test{
  foo=World,
  bar=Universe,
  qux
}

\end{document}

First problem: \keyval_parse:NNn is not expandable, so \exp_args:Nf does nothing really useful with it.

Second, it's easier to add commas rather than removing them, which I do with the help of \seq_use:Nn.

You shouldn't mix strings and token lists.

Here I use the command \test just for outputting the massaged set of options. In your case you'll probably pass it for processing to some other function.

enter image description here

egreg
  • 1,121,712