[Tex/LaTex] Ampersand inside new command, tabular environment

ampersandtablesxstring

I'm trying to define a macro for table headers but unfortunately I'm far from a TeX expert. I should split a list that is delimited with ampersands, format the entries and concatenate it again with ampersands. Splitting the list works but I can't concatenate it with ampersands.

\documentclass{article}
\usepackage{xstring}

\newcommand{\DLbase}[1]% #1 = comma delimited keywords
{{\saveexpandmode\expandarg%
\StrCut{\noexpand#1}{&}\DLleft\DLright%
\loop% extract keywords from list
\StrCut{\DLright}{&}\DLnext\DLright%
\textbf\DLleft\DLsep%
\edef\DLleft{\DLnext}%
\if\DLright\relax\else\repeat%
\textbf{\DLleft}%
\restoreexpandmode}}

\newcommand{\tabhead}[1]{\def\DLsep{&}\DLbase{#1}\\}

\begin{document}

\begin{table}[ht]
  \begin{center}
    \caption{Command / Purposes}
    \begin{tabular}{|p{0.3\textwidth}|p{0.6\textwidth}|}
      \hline
      \tabhead{Command & Purpose}
      \hline
      cd & change directory \\
      rm & remove files 
      \hline
    \end{tabular}
  \end{center}
\end{table}
\end{document}

I copied most of the code from here and here.

How do I have to define \DLbase and \DLsep that this works?

Best Answer

The problem is always to output all the row before TeX “sees” &. It's easy with expl3, with \seq_use:Nn, that delivers its result “at once”.

The \tabhead command has an optional argument for the formatting command, default \bfseries. It splits its argument at &, then adds the optional argument before items, separating them with &, with a trailing \\.

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\tabhead}{ O{\bfseries} m }
 {
  \seq_set_split:Nnn \l_tmpa_seq { & } { #2 }
  #1 \seq_use:Nn \l_tmpa_seq { & #1 } \\
 }
\ExplSyntaxOff

\begin{document}

\begin{table}[htp]
\centering
\caption{Command / Purposes}

\begin{tabular}{|p{0.3\textwidth}|p{0.6\textwidth}|}
\hline
\tabhead{Command & Purpose}
\hline
cd & change directory \\
rm & remove files \\
\hline
\end{tabular}

\bigskip

\begin{tabular}{|p{0.3\textwidth}|p{0.6\textwidth}|}
\hline
\tabhead[\itshape]{Command & Purpose}
\hline
cd & change directory \\
rm & remove files \\
\hline
\end{tabular}

\end{table}

\end{document}

enter image description here