有没有什么办法可以让表格自动获得行号?
例如,如果我将表内容定义为
\begin{tabular} % black magic column definition
\rownumber & foo\\
\rownumber & bar\\
\rownumber & baz\\
\end{tabular}
并得到类似
1 | foo
2 | bar
3 | baz
答案1
\documentclass{article}
\usepackage{array,etoolbox}
\preto\tabular{\setcounter{magicrownumbers}{0}}
\newcounter{magicrownumbers}
\newcommand\rownumber{\stepcounter{magicrownumbers}\arabic{magicrownumbers}}
\begin{document}
\begin{tabular}{@{\makebox[3em][r]{\rownumber\space}} | r}
Something \\
Other stuff \\
MAGIC!
\end{tabular}
\end{document}
输出
\documentclass{article}
\usepackage{array,etoolbox}
\preto\tabular{\setcounter{magicrownumbers}{0}}
\newcounter{magicrownumbers}
\def\rownumber{}
\begin{document}
\begin{tabular}{@{\makebox[3em][r]{\rownumber\space}} | r}
Something
\gdef\rownumber{\stepcounter{magicrownumbers}\arabic{magicrownumbers}} \\
Other stuff \\
MAGIC!
\end{tabular}
\end{document}
如果想要列标题,请使用:
\documentclass{article}
\usepackage{array,etoolbox}
\preto\tabular{\setcounter{magicrownumbers}{0}}
\newcounter{magicrownumbers}
\newcommand\rownumber{\stepcounter{magicrownumbers}\arabic{magicrownumbers}}
\begin{document}
\begin{tabular}{@{\makebox[3em][r]{\rownumber\space}} | r}
\multicolumn{1}{@{\makebox[3em][r]{ID~}} | r}{\emph{whatever}}\\
Something \\
Other stuff \\
MAGIC!
\end{tabular}
\end{document}
答案2
答案3
答案4
为了完整性,还提供快速的纯格式版本:
\newcount\rowcount
\def\myhalign#1{\halign{\global\advance\rowcount by 1 \the\rowcount\quad##}\rowcount=0}
% Yes, yes, next up in *sniping*: "One problem: you can't use repeating preamble"...
\myhalign{#\hfil\cr
blah\cr
foo\cr}
\halign{#\hfil\cr
bar\cr
baz\cr}
\myhalign{&#\hfil\cr
asdf&asdf&asdf\cr
sdfg&asdf&dfgh\cr}
\myhalign{#\hfil&&\hfil#\cr
doesn't&work\cr
boo&hoo\cr}
\bye