以字体颜色为条件

以字体颜色为条件

我想根据当前的字体颜色更改文本。

我可以测试针对字体系列的论点

\documentclass[a4paper,12pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[svgnames]{xcolor}
\usepackage[scaled=0.84]{beramono}
\usepackage{pdftexcmds}

\makeatletter
\newcommand{\MyChange}[1]{%
\ifnum\pdf@strcmp{\f@family}{\ttdefault}=\z@%
{\bfseries #1}%
\else%
{\sffamily #1}%
\fi%
}%
\makeatother

\begin{document}
\noindent       First:\MyChange{Normal should become SF}\\
{\color{red}    Second:\MyChange{Red should become SF}}\\
{\tt            Third:\MyChange{tt should be bold}}\\
{\tt\color{red} Fourth:\MyChange{Red tt should be bold}}
\end{document}

我希望我能有这样的东西

\makeatletter
\newcommand{\MyChange}[1]{%
\ifnum\pdf@strcmp{\f@color}{red}=\z@%
{\bfseries\large #1}%
\else%
{\sffamily\scriptsize #1}%
\fi%
}%
\makeatother

但我得到了错误

! Undefined control sequence.
\MyChange #1->\ifnum \pdf@strcmp {\f@color 
                                           }{red}=\z@ {\bfseries \large #1}\...
l.19 ...  First:\MyChange{Normal should become SF}
                                                  \\

答案1

xcolor可以在宏中提取颜色定义:\extractcolorspec{<color>}{<macro>}。这可用于定义测试以将当前颜色.与以下内容进行比较red

\documentclass[a4paper,12pt]{article}
\usepackage[T1]{fontenc}
\usepackage[svgnames]{xcolor}
\usepackage[scaled=0.84]{beramono}

\makeatletter
\newcommand{\MyChange}[1]{%
  \extractcolorspec{.}\MyChange@CurrentColor
  \extractcolorspec{red}\MyChange@TestColor
  \ifx\MyChange@CurrentColor\MyChange@TestColor
    {\bfseries\large #1}%
  \else
    {\sffamily\scriptsize #1}%
  \fi%
}
\makeatother

\begin{document}
\noindent       First: \MyChange{Normal should become SF and small}\\
{\color{red}    Second: \MyChange{Red should become bold and large}}\\
{\tt            Third: \MyChange{tt should be SF and small}}\\
{\tt\color{red} Fourth: \MyChange{Red tt should be bold and large}}
\end{document}

结果

答案2

你可以利用颜色定义保存在宏中的事实

\csname\string\color@<colorname>\endcsname

您可以使用.for检查当前颜色<colorname>,如https://tex.stackexchange.com/a/36163/4427

\documentclass[a4paper,12pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[svgnames]{xcolor}
\usepackage[scaled=0.84]{beramono}
\usepackage{pdftexcmds}

\makeatletter
\newcommand{\color@check}[1]{%
  \expandafter\meaning\csname\string\color@#1\endcsname
}
\newcommand{\MyChange}[1]{%
  \ifnum\pdf@strcmp{\color@check{.}}{\color@check{red}}=\z@
    {\bfseries\large #1}%
  \else
    {\sffamily\scriptsize #1}%
  \fi
}
\makeatother

\begin{document}
\noindent       First:\MyChange{Normal should become SF}\\
{\color{red}    Second:\MyChange{Red should become bold and large}}\\
{\tt            Third:\MyChange{tt should be SF}}\\
{\tt\color{red} Fourth:\MyChange{Red tt should be bold and large}}
\end{document}

在此处输入图片描述

相关内容