9

What part of my code is causing the misalignment of the first column? The extra space seems to increase with the number of rows. (Part of my code is from How do I use the ampersand (&) inside a foreach or conditional (or other group/environment) when building tables?)

Code:

\documentclass{article}

\makeatletter
\newtoks\@tabtoks
\newcommand\addtabtoks[1]{\global\@tabtoks\expandafter{\the\@tabtoks#1}}
\newcommand\eaddtabtoks[1]{\edef\mytmp{#1}\expandafter\addtabtoks\expandafter{\mytmp}}
\newcommand*\resettabtoks{\global\@tabtoks{}}
\newcommand*\printtabtoks{\the\@tabtoks}
\makeatother

\newcommand{\topic}[2]{%
   \eaddtabtoks{Col 1 & Col 2 & Col 3 & #1 & #2}
   \addtabtoks{\\}
}

\newenvironment{mytabular}{%
   \resettabtoks
   \tabular{llrrl}
}{%
   \printtabtoks
   \endtabular
}

\begin{document}

\begin{mytabular}
   \topic{1.1}{LaTeX}
   \topic{1.2}{causes}
   \topic{1.3}{me}
   \topic{1.4}{lots}
   \topic{1.5}{of}
   \topic{1.6}{frustration}
\end{mytabular}

\end{document}

Output:

enter image description here

1 Answers1

8

As is often the case, the culprits are stray spaces introduced at the ends of lines. And because of the nature of the token list, which gets added to the tabular at the end of the process, all those stray spaces get added before the token list gets dumped, meaning, all are added as leading padding to cell (1,1).

In this case, the fix not only meant adding some % at line ends inside your macro definitions, but it also meant incorporating \ignorespaces into the definition of \topic, since every time you invoked \topic, stray spaces were introduced as part of your input stream, as well.

I also generalized mytabular to take the formatting as an argument.

\documentclass{article}
\usepackage[T1]{fontenc}
\makeatletter
\newtoks\@tabtoks
\newcommand\addtabtoks[1]{\global\@tabtoks\expandafter{\the\@tabtoks#1}}
\newcommand\eaddtabtoks[1]{\edef\mytmp{#1}\expandafter\addtabtoks\expandafter{\mytmp}}
\newcommand*\resettabtoks{\global\@tabtoks{}}
\newcommand*\printtabtoks{\the\@tabtoks}

\newcommand{\topic}[2]{%
   \eaddtabtoks{Col 1 & Col 2 & Col 3 & #1 & #2}%
   \addtabtoks{\\}%
   \ignorespaces
}

\newenvironment{mytabular}[1]{%
   \resettabtoks
   \noindent
   \begin{tabular}{#1}%
}{%
   \printtabtoks
   \end{tabular}
}
\makeatother

\begin{document}

\begin{mytabular}{llrrl}
   \topic{1.1}{LaTeX}
   \topic{1.2}{causes}
   \topic{1.3}{me}
   \topic{1.4}{lots}
   \topic{1.5}{of}
   \topic{1.6}{frustration}
\end{mytabular}

\end{document}

enter image description here

  • Thank you. Your specific suggestions solved my MWE, but not my original problem exactly. However, they led me in the right direction to find other stray spaces and deal with them accordingly. (I have other O/T reasons for not including the tabular formatting as an argument). – rogue.whistler May 03 '19 at 14:15
  • 1
    @rogue.whistler Happy to help.Welcome to the site. – Steven B. Segletes May 03 '19 at 14:16