Define a macro to apply operation to text separated by \\

There is classical (and probably most simple) method based on TeX primitives:

\def\test#1{\testA#1\\\end\\}
\def\testA#1\\{\ifx\end#1\empty\else\action{#1}\expandafter\testA\fi}
\def\action#1{parameter is: #1\par}

\test{A\\B\\C}

If we need to insert something between actions, for example \actionbetween, then the macro is slightly more complicated but it is fully expandable too:

\def\test#1{\testA#1\\\end\\\\}
\def\testA#1\\#2\\{\ifx\end#1\empty 
   \else\action{#1}\ifx\end#2\empty \else \actionbetween \fi
   \afterfi{\testA#2\\}\fi}
\def\afterfi#1#2\fi{\fi#1}

\def\action#1{parameter is #1\par}
\def\actionbetween{\string\\}

\test{A\\B\\C}

\DeclareListParser from etoolbox is made for this, it allows you to define a list parser with a custom list separator. (EDIT: fixed a shortcoming, thanks to cgnieder!)

\documentclass{article}
\usepackage{etoolbox}
\DeclareListParser{\mydocsvlist}{\\}
\newif\ifFirstItem
\newcommand{\action}[1]{\textbf{#1}}
\newcommand{\test}[1]{\begingroup
\FirstItemtrue
\renewcommand*{\do}[1]{\ifFirstItem\FirstItemfalse\else\\\fi\action{##1}}%
\mydocsvlist{#1}%
\endgroup}
\parindent0pt
\begin{document}
\test{A\\B\\C} 

\renewcommand{\action}[1]{\emph{#1}!}%
\test{A\\B\\C} 
\end{document}

enter image description here


\documentclass{arlticle}
\usepackage{listofitems}
\newcommand\action[1]{%
  \setsepchar{\\}%
  \readlist\myparse{#1}%
  \foreachitem\z\in\myparse[]{%
    \expandafter\theaction\expandafter{\z}\myparsesep[\zcnt]%
  }%
}
\newcommand\theaction{\textit}
\begin{document}
\action{A\\B\\C plus more}

\renewcommand\theaction{\textsc}
\action{A\\B\\C plus more}
\end{document}

enter image description here

To make it even more general, you can set it up to specify the separator, as well. Note, in the 2nd example, the separator tokens are not subjected to the small caps action.

\documentclass{arlticle}
\usepackage{listofitems}
\newcommand\action[1]{%
  \readlist\myparse{#1}%
  \foreachitem\z\in\myparse[]{%
    \expandafter\theaction\expandafter{\z}\myparsesep[\zcnt]%
  }%
}
\setsepchar{\\}
\newcommand\theaction{\textit}
\begin{document}
\action{A\\B\\C plus more}

\renewcommand\theaction{\textsc}
\setsepchar{(Hi Mom)\\}
\action{A (Hi Mom)\\B (Hi Mom)\\C plus more}
\end{document}

enter image description here

Tags:

Macros