0

I am trying to define a command that simplifies building tables. I want the last entry to be automatically preceded by a horizontal line. I tried to do a minimal working example, and it worked (surprisingly), but it does not work in my more elaborate code.

\documentclass{article}
\usepackage{xparse}

%%% Works

\newcommand{\foo}[2]{#1 & #2\\}

\newcommand{\foolast}[2]{\hline
    #1 & #2}

\newcounter{premn}
\setcounter{premn}{0}

%%% Does not work if \hline is present

\newcommand{\premform}{\arabic}

\NewDocumentCommand{\preml}{O{\premform{premn}} m o}{%
    \IfNoValueTF{#3}%
    {%
        \refstepcounter{premn}%
        (#1) & #2 & \\
    }
    {%
        \refstepcounter{premn}%
        (#1) & #2 & #3\\
    }
}

\NewDocumentCommand{\conl}{O{\premform{premn}} m o}{%
    \IfNoValueTF{#3}%
    {%\hline
        \refstepcounter{premn}%
        (#1) & #2 & %
        \setcounter{premn}{0}%
        \ignorespaces%
    }
    {%\hline
        \refstepcounter{premn}%
        (#1) & #2 & #3 %
        \setcounter{premn}{0}%
        \ignorespaces%
    }
}

%%% MWE

\begin{document}

\begin{tabular}{ll}
\foo{a}{b}
\foolast{a}{b}
\end{tabular}

\begin{tabular}{lll}
\preml{a}
\conl{b}
\end{tabular}
    
\end{document}

I am sure there is an answer to this, but it is beyond my knowledge.

1
  • You're supposed to give work that does not behave as you expect... if the code already works there's no question??? also briefly explain what you want the code to do, it's not obvious looking just at your code
    – user202729
    Apr 21, 2022 at 6:08

2 Answers 2

2

With the help of the tabularray package you can access the row number of each table row and also make sure that a horizontal lines is automatically drawn above the last row:

\documentclass{article}
\usepackage{tabularray}

\begin{document}

\begin{tblr}{colspec={>{(\arabic{rownum})\enspace}ll}, hline{Y}}
a & b \\
a & b \\
a & b \\
a & b \\
a & b \\
a & b \\
\end{tblr}
    
\end{document}
1
  • Perfect, this is more than I hoped for! Thanks a lot!
    – susypeti
    Apr 21, 2022 at 20:21
0

You can do that with {NiceTabular} of nicematrix and Tikz.

\documentclass{article}
\usepackage{nicematrix,tikz}

\begin{document}

\begin{NiceTabular}
  [code-after = { \tikz \draw (\arabic{iRow}-|1) -- (\arabic{iRow}-|last) ; } ]
  {>{(\arabic{iRow})\enspace}ll}
a & b \\
a & b \\
a & b \\
a & b \\
a & b \\
a & b \\
\end{NiceTabular}
    
\end{document}

You need several compilations (because nicematrix uses PGF/Tikz nodes under the hood).

Output of the above code

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .