4

I'm having trouble using (the amazing) expl3 package with a tabular environment. Specifically, I'm getting a full extra row in my tabulars when creating rows using \seq_map_inline. I can avoid this behavior by not including the \cr in the last row (in the MWE below, this would involve a few more lines of code, but was not a huge deal in the original usage), and then including the \cr verbatim. In the MWE I purposely delete a lot of space “just in case” but it does not change anything (except make it harder to read, sorry). Another fix might be inserting negative spacing as in this question, but I'm confused why the kernel is inserting something into my table (it takes up no horizontal space at least, seen by add a Hi before the \end{tabular}).

Broken but should be right

\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\DeclareDocumentCommand \myTable {m} {
  \seq_set_split:Nnn \l_tmpa_seq {,} {#1}
  \begin{tabular}{|c|c|}\seq_map_inline:Nn \l_tmpa_seq {Entry&##1\cr}\end{tabular}
}
\ExplSyntaxOff
\begin{document}
\myTable{A,B,C,D}
\end{document}

Broken version: extra line

Works but more complicated

\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\DeclareDocumentCommand \myTable {m} {
  \seq_set_split:Nnn \l_tmpa_seq {,} {#1}
  \int_zero:N \l_tmpa_int
  \begin{tabular}{|c|c|}
    \seq_map_inline:Nn \l_tmpa_seq {Entry&##1
      \int_gincr:N \l_tmpa_int
      \int_compare:nNnTF{\l_tmpa_int}={\seq_count:N\l_tmpa_seq}{}{\cr}
     }
     \cr
  \end{tabular}
}
\ExplSyntaxOff
\begin{document}
\myTable{A,B,C,D}
\end{document}

Works: no extra line

Jack Schmidt
  • 1,137

2 Answers2

7

The problem is that the operation leaves something after the last \\ (or \cr) which starts a new cell (albeit producing no output). So operating in that way inside a tabular (aka as \halign) is dangerous; you'd better build the table in a token list variable and deliver it:

\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\DeclareDocumentCommand \myTable {m}
 {
  \seq_set_split:Nnn \l_tmpa_seq {,} {#1}
  \tl_set:Nn \l_tmpa_tl { \begin{tabular}{|c|c|} }
  \seq_map_inline:Nn \l_tmpa_seq
   {
    \tl_put_right:Nn \l_tmpa_tl { Entry & ##1 \\ }
   }
   \tl_put_right:Nn \l_tmpa_tl { \end{tabular} }
  \tl_use:N \l_tmpa_tl
 }
\ExplSyntaxOff
\begin{document}
\myTable{A,B,C,D}
\end{document}
egreg
  • 1,121,712
0

The problem disappears when you use an explicit function for the rows rather than an inline function. (By the way, the function could be taken out of the macro in this case, but I prefer to have it locally.)

\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\DeclareDocumentCommand \myTable {m} {
  \newcommand{\myrow}[1]{Entry&##1\cr}
  \seq_set_split:Nnn \l_tmpa_seq {,} {#1}
  \begin{tabular}{|c|c|}\seq_map_function:NN \l_tmpa_seq \myrow \end{tabular}
}
\ExplSyntaxOff
\begin{document}
\myTable{A,B,C,D}
\end{document}

enter image description here