受到答案的启发https://tex.stackexchange.com/a/37484,我尝试创建一个具有键值接口的表。\pgfkeys
仅在表格环境之外使用可以按预期工作,但如果在环境内部使用,它会像我的第一个和第二个方法一样开始一个额外的行:
\documentclass{article}
\usepackage{pgfkeys, pgffor}
% set up
\pgfkeys{table/.is family, table,
list of fields/.initial={foo, bar},
add field/.style={#1/.value required, #1/.initial={undefined}},
add field/.list/.expanded=\pgfkeysvalueof{/table/list of fields}
}
% first approach
\pgfkeys{table,
print row/.code = {#1 & \pgfkeysvalueof{/table/#1} \\\hline},
print table/.style = {print row/.list/.expanded = \pgfkeysvalueof{/table/list of fields}}
}
% second approach
\pgfkeys{table,
content/.initial={},
print content/.code=\pgfkeysvalueof{/table/content},
add row/.style = {
% 3 pairs of braces are needed if pgfkeys is called within a table
content/.append={{{#1 & \pgfkeysvalueof{/table/#1} \\\hline}}},
},
fill content/.style = {add row/.list/.expanded = \pgfkeysvalueof{/table/list of fields}},
create table/.style = {fill content, print content}
}
\parindent=0pt
\begin{document}
\pgfkeys{table, foo=1}
first approach:\\
\begin{tabular}{|l | l |}
\hline
\pgfkeys{table, print table}%
\end{tabular}
\bigskip
second approach:\\
\begin{tabular}{|l | l |}
\hline
\pgfkeys{table, create table}% here 3 braces are needed, see above
\end{tabular}
\bigskip
use key directly:\\
\pgfkeys{table, fill content}% would work with single pair of braces
\begin{tabular}{|l | l |}
\hline
\pgfkeysvalueof{/table/content}
\end{tabular}
\end{document}
是什么导致了多出的一行,又该如何删除它?另外,我想知道为什么在表格中附加一行需要三对括号,而通常只需一对括号就可以了。
编辑:
我意识到很多东西都可以在表格末尾添加新行,例如,
\begin{tabular}{|l|l|}
\hline
a & b \\\hline\relax
\end{tabular}
看起来下面的方法可行,但是我猜避开\pgfkeys
表格末尾是更简单的解决方案:
\pgfkeys{table,
print head/.code = {\begin{tabular}{|l | l |}\hline\bgroup},
print foot/.code = {\egroup\end{tabular}},
print row/.code = {\egroup#1 & \pgfkeysvalueof{/table/#1} \\\hline\noalign\bgroup},
print table/.style = {print head, print row/.list/.expanded = \pgfkeysvalueof{/table/list of fields}, print foot}
}
\pgfkeys{table, print table}
答案1
经过反复尝试,我了解到,除了空命令之外的所有命令,如果在表格环境的末尾调用,它们都会添加一个额外的行,即使它们对输出没有明显的影响。一个任意的例子是:
\begin{tabular}{|l | l |}
\hline
a & b \\\hline\stepcounter{count}
\end{tabular}
如果不想避免在最后一行末尾出现命令,\noalign
则可以用来抑制额外的行,例如,
\begin{tabular}{|l | l |}
\hline
a & b \\\hline\noalign{\stepcounter{count}}
\end{tabular}
这甚至可以从内部使用\pgfkeys
,请参阅我的问题的编辑。一个简单的例子是:
\pgfkeys{row/.code={a & b\\\noalign\bgroup}}
\begin{tabular}{|l | l |}
\hline
\pgfkeys{row}\egroup
\hline
\end{tabular}
我仍然对解释感兴趣,但目前我只能接受这是 (La)Tex 的另一个谜团。