我正在尝试快速为所有表格添加彩色背景,colorbox
如下图所示这个答案。虽然我可以手动更新所有 TeX,但我正在尝试修补环境tabular
以使 TeX 内容尽可能“干净”(并且有 200 多个表需要更新)。
我尝试了两种不同的方法,但它们给出了相同的错误:
! Extra }, or forgotten \endgroup.
\color@b@x ...hbox {\kern \fboxsep {\set@color #3}
\kern \fboxsep }\dimen@ \h...
l.22 \begin{tabular}
{ll}
特克斯:
\documentclass[10pt,twoside,letterpaper,openright]{scrbook}
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage{booktabs}
% Method One:
\usepackage{etoolbox}
\BeforeBeginEnvironment{tabular}{\colorbox{gray}\begingroup}
\AfterEndEnvironment{tabular}{\endgroup}
% Method Two
%\usepackage{xpatch}
%xpretocmd{\tabular}{\begingroup\setlength{\fboxsep}{0pt}\colorbox{gray}\begingroup}{}{\patchfailed}
%xapptocmd{\endtabular}{\endgroup\endgroup}{}{\patchfailed}
\begin{document}
\chapter{Lorem Ipsum}
\begin{table}[h]
\caption{Test Table}
\label{testtable}
\begin{tabular}{ll}
\toprule
Test 1 & Test 2 \\
Test 3 & Test 4 \\
\bottomrule
\end{tabular}
\end{table}
\end{document}
答案1
我会小心地重新定义整个tabular
环境,因为它可能用于与表格不同的上下文中(例如排版作者姓名和地址)。由于您想要添加背景颜色的表格可能位于table
环境中,因此我们将仅修补这些表格。
\documentclass[10pt,twoside,letterpaper,openright]{scrbook}
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage{booktabs}
\usepackage{xpatch,letltxmacro}
%% A storage bin
\newsavebox{\tabularbox}
%% We patch the tabular environments only inside table
\AtBeginEnvironment{table}{%
\LetLtxMacro\tabular\colortabular
\LetLtxMacro\endtabular\endcolortabular
}
%% Start: save a copy of \tabular and \endtabular
\LetLtxMacro\colortabular\tabular
\LetLtxMacro\endcolortabular\endtabular
%% Patch the copies
\xpretocmd{\colortabular}
{\setbox\tabularbox=\hbox\bgroup} % start building a box
{}{}
\xapptocmd{\endcolortabular}
{%
\egroup % finish the box
\begingroup
\fboxsep=0pt % no padding
\colorbox{black!30}{\box\tabularbox}% typeset the box on a background
\endgroup
}
{}{}
\begin{document}
\chapter{Lorem Ipsum}
\begin{table}[h]
\centering
\caption{Test Table}\label{testtable}
\begin{tabular}{ll}
\toprule
Test 1 & Test 2 \\
Test 3 & Test 4 \\
\bottomrule
\end{tabular}
\end{table}
\end{document}
答案2
Tabular
使用相同参数设置的新环境
\documentclass[parskip=half*]{scrbook}
\usepackage{xcolor,varwidth}
\usepackage{booktabs}
\newsavebox\TBox
\newenvironment{Tabular}
{\begin{lrbox}{\TBox}\varwidth{\linewidth}\tabular}
{\endtabular\endvarwidth\end{lrbox}%
\fboxsep=1pt\colorbox{black!20}{\usebox\TBox}}
\begin{document}
\chapter{Lorem Ipsum}
\begin{Tabular}{ll}\toprule
Test 1 & Test 2 \\
Test 3 & Test 4 \\\bottomrule
\end{Tabular}
\begin{tabular}{ll}\toprule
Test 1 & Test 2 \\
Test 3 & Test 4 \\\bottomrule
\end{tabular}
\end{document}