3

I'd like to define a macro that expands to \hline and \cline inside the tabular environment depending on the next character:

\documentclass{standalone}           

\makeatletter
\def\mycline[#1]{\cline{#1}}
\def\myline{\@ifnextchar[{\mycline}{\hline}}      % Does not work. Either misplaced \noalign or \omit 
\makeatother

\begin{document}

\begin{tabular}{cc}
a1 & a2 \\
\myline
b1 & b2 \\
\myline[1-2] 
\end{tabular}

\end{document}

Unfortunately, this results in a misplaced \noalign or \omit (or both). It seems that \@ifnextchar doesn't get fully expanded in time. Any idea?

  • 2
    Due to how scanning for \noalign works, an unexpandable command (here \futurelet used by \@ifnextchar) starts a new alignment cell and it's too late for a line to be inserted. – egreg Feb 18 '15 at 17:34
2

Due to how scanning for \noalign works, an unexpandable command (here \futurelet used by \@ifnextchar) starts a new alignment cell and it's too late for a line to be inserted.

You have to do the scanning for the optional argument inside a \noalign group:

\documentclass{standalone}

\makeatletter
\def\myline{%
  \noalign\bgroup
  \@ifnextchar[%
    {\aftergroup\mycline\egroup}%
    {\aftergroup\hline\egroup}%
}
\def\mycline[#1]{\cline{#1}}
\makeatother

\begin{document}

\begin{tabular}{cc}
a1 & a2 \\
\myline
b1 & b2 \\
\myline[1-1]
c1 & c2
\end{tabular}

\end{document}

enter image description here

Why are you looking for trouble? ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.