智能功能

智能功能

\emph命令很智能。它根据嵌套级别做出不同的行为。

\emph{Italics within \emph{italics within \emph{more italics} and} so on}.

输出:

斜体字斜体字内更多斜体很快

我如何重新定义\emph命令以使其表现如下:

  • 第一级:'单引号',
  • 第二级:小型大写字母,
  • 第三级:斜体

答案1

\documentclass{article}
\newcounter{emphlevel}
\renewcommand\emph[1]{\stepcounter{emphlevel}%
  \ifnum\value{emphlevel}=1`#1'\else
    \ifnum\value{emphlevel}=2\textsc{#1}\else
    \ifnum\value{emphlevel}=3\textit{#1}\else
  \fi\fi\fi\addtocounter{emphlevel}{-1}%
}
\begin{document}
\emph{Single quotes within \emph{Small Caps within \emph{more italics} and} so on}.
\end{document}

在此处输入图片描述

上述原始答案会截断第三级以外的级别。下面的变体会通过指定的重点重复循环。

\documentclass{article}
\newcounter{emphlevel}
\renewcommand\emph[1]{\stepcounter{emphlevel}%
  \ifnum\value{emphlevel}=1\textup{`#1'}\else
    \ifnum\value{emphlevel}=2\textsc{#1}\else
    \ifnum\value{emphlevel}=3\textit{#1}\else
      \addtocounter{emphlevel}{-4}\emph{#1}\addtocounter{emphlevel}{4}%
  \fi\fi\fi\addtocounter{emphlevel}{-1}%
}
\begin{document}
\emph{Single quotes within \emph{Small Caps within \emph{more italics
  within \emph{Single quotes within \emph{Small Caps within \emph{more italics} 
  and} so on}} and} so on}.

\emph{Aa \emph{Bb \emph{Cc \emph{Dd \emph{Ee \emph{Ff \emph{Gg}}}}}}}
\end{document}

在此处输入图片描述

答案2

分组的简单应用:

\documentclass{article}

\newcount\emphlevel
\DeclareRobustCommand{\emph}[1]{%
  \begingroup
  \normalfont
  \advance\emphlevel by 1
  \ifcase\emphlevel
  \or
    `\aftergroup'\normalfont
  \or
    \normalfont\expandafter\textsc
  \or
    \normalfont\expandafter\textit
  \else
    \normalfont!!!!\expandafter\textbf
  \fi
  {#1}%
  \endgroup
}

\begin{document}

Normal text.
\emph{Single quotes within \emph{Small Caps within \emph{more italics} and} so on}.
Again normal text.

\emph{Single quotes within \emph{Small Caps within \emph{more italics}}}.

\end{document}

在此处输入图片描述

答案3

我决定使用另一个命令名称,但可以使用计数器和条件来控制嵌套\ifcase...\fi

第 4 级将提供通常的\@ctrerr,但这可以转移到基本上任何级别。

\documentclass{article}


\newcounter{smartlevel}

\makeatletter
\newcommand{\smartcmd}[1]{%
  \stepcounter{smartlevel}%
  \ifcase\c@smartlevel
  \or'#1'\addtocounter{smartlevel}{-1}%
  \or\textsc{#1}\addtocounter{smartlevel}{-1}%
  \or\textit{#1}\addtocounter{smartlevel}{-1}%
  \else
  \@ctrerr% Too deeply nested
  \fi
}
\makeatother

\begin{document}

\smartcmd{First \smartcmd{Foo \smartcmd{inner} \smartcmd{inner again}}}

\smartcmd{First \smartcmd{Foo} \smartcmd{Foo level \smartcmd{inner again}}} 

\end{document}

在此处输入图片描述

相关内容