我发现了 jfbu 的一段很棒的代码:
\documentclass{article}
\usepackage{color}
\usepackage{etoolbox}
\begingroup
\lccode`~`-
\lowercase{%
\endgroup\pretocmd{\tabular}{\catcode`~\active\def~{\color{red}-}}{}{}}
\begin{document}
Not colored here: -12, But colored within the tabular
\begin{tabular}{ l c r }
1 & 2 & 3 \\
-4 & 5 & 6 \\
7 & 8 & -9 \\
\end{tabular}
and again not colored here: -12.
\end{document}
我想知道是否有一种方法可以修改此代码,以格式化单元格中的所有文本,如果在单元格中有一个特定的符号(例如'*')结尾细胞。你知道如何完成这个任务吗?
答案1
这将*
任何地方都视为红色,而不仅仅是在末尾。
\documentclass{article}
\usepackage{color}
\usepackage{array}
{\catcode`\*=\active
\gdef\zz#1{%
\mathcode`\*="8000
\gdef\foo{}%
\def*{\gdef\foo{\color{red}}}%
\setbox0\hbox\bgroup$}
}
\def\zzz{$\egroup\foo{\box0}}
\begin{document}
Not colored here: $-12$, But colored within the tabular
\begin{tabular}{
>{\zz}l<{\zzz}
>{\zz}c<{\zzz}
>{\zz}r<{\zzz}
}
1 & 2 & 3 \\
-4* & 5 & 6 \\
7 & 8* & -9* \\
\end{tabular}
and again not colored here: $-12$.
\end{document}
答案2
您还可以使用包裹collcell
它允许您检查tabular
/array
单元格内容并对其执行任何所需的操作:
笔记:
- 所有数学内容都应该永远在数学模式下排版。
-12
(错误)和$-12$
(正确)是有区别的。因此我使用array
而不是。如果您有混合内容,那么您可以在或tabular
的宏中编码数学模式。\ColCellNegative
\ColEndWithAsterix
代码
\documentclass{article}
\usepackage{color}
\usepackage{array}
\usepackage{collcell}
\usepackage{xstring}
\newcolumntype{L}{>{\collectcell\ColCell}l<{\endcollectcell}}
\newcolumntype{C}{>{\collectcell\ColCell}c<{\endcollectcell}}
\newcolumntype{R}{>{\collectcell\ColCell}r<{\endcollectcell}}
\newcommand\ColCellNegative[1]{%
%% Any conditional expression here can be used.
\IfBeginWith{#1}{-}{%
\color{red}#1
}{%
#1
}%
}
\newcommand\ColEndWithAsterix[1]{%
%% Any conditional expression here can be used.
\IfEndWith{#1}{*}{%
\StrBefore{#1}{*}[\ValueBeforeAsterix]% <-- if don't want the asterix
%\def\ValueBeforeAsterix{#1}% <-- if want to keep the asterix
\color{red}\ValueBeforeAsterix
}{%
#1
}%
}
\let\ColCell\ColCellNegative% Use this if want cells colored red if they are negative
%\let\ColCell\ColEndWithAsterix% Use this if want cells colored red if they end with an asterix
\begin{document}
Colored red if cell is negative:
$\begin{array}{ L C R }
1 & 2 & 3 \\
-4 & 5 & 6 \\
7 & 8 & -9 \\
\end{array}$
\medskip
Colored red if cell ends in asterix:
\let\ColCell\ColEndWithAsterix% Use this if want cells colored red if they end with an asterix
$\begin{array}{ L C R }
1 & 2 & 3 \\
-4 & 5 & 6 \\
7 & 8 & -9* \\
\end{array}$
\end{document}