You indeed get
\underline \begingroup Element1 \endgroup \underline \begingroup Element2\endgroup
but unfortunately \underline\begingroup Element1 \endgroup
is illegal, because \begingroup
and \endgroup
can't be used for delimiting a macro argument.
There are various tools for this; I'll show a solution based on expl3
, the programming layer of the future LaTeX3.
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\mylist}{ O{\underline} m }
{
% transfer control to an internal function
\porst_mylist:nn { #1 } { #2 }
}
\seq_new:N \l__porst_list_items_seq
\seq_new:N \l__porst_list_output_seq
\cs_new_protected:Npn \porst_mylist:nn #1 #2
{
% clear the output sequence
\seq_clear:N \l__porst_list_output_seq
% split the input at \and
\seq_set_split:Nnn \l__porst_list_items_seq { \and } { #2 }
% append each item to the output sequence
\seq_map_inline:Nn \l__porst_list_items_seq
{
% #1 is the given argument, ##1 represents the current item
\seq_put_right:Nn \l__porst_list_output_seq { #1 { ##1 } }
}
% output the sequence with something between items
\seq_use:Nn \l__porst_list_output_seq {,~} % adjust
}
\ExplSyntaxOff
\begin{document}
\mylist{Element1 \and Element2}
\mylist[\emph]{Element1 \and Element2}
\end{document}
The first step is splitting the input at the \and
tokens; trailing and leading spaces will be removed; the second step is storing the “formatted” items in another sequence, for using this one with some separator between the items.
Another possible tool is etoolbox
; but, as you see, it's much more complicated.
\documentclass{article}
\usepackage{etoolbox}
\makeatletter
\DeclareListParser*{\andlist@do}{\and}
\newcommand{\andlist@sep}{, }
\newcommand{\mylist}[2][\underline]{%
\def\andlist@output{\@gobble}%
\andlist@do{\andlist@handler{#1}}{#2}%
\andlist@output
}
\appto\nocorrlist{\andlist@sep}
\newcommand{\andlist@handler}[2]{%
\appto\andlist@output{\andlist@sep#1{#2\unskip}}%
}
\makeatother
\begin{document}
\mylist{Element1 \and Element2}
\mylist[\emph]{Element1\and Element2}
\end{document}
\underline\begingroup abc\endgroup
is illegal: you can't use\begingroup
and\endgroup
for delimiting the argument to a macro.etoolbox
orexpl3
.