在定理环境周围包裹新环境

在定理环境周围包裹新环境

我正在尝试创建一个新环境,该环境环绕包newtheorem中定义的定理环境amsthm。但是,将可选参数传入环境,然后传入定理环境会创建一个空括号。以下是我所看到的一个非常简单的示例

\documentclass[12pt, letter]{article}

\usepackage{lipsum}
\usepackage{xcolor}

\newtheorem{thm}{Theorem}

\newenvironment{thm2}[1][]{
    % The following line doesn't work???
    %\ifx&#1&{\begin{thm}}\else{\begin{thm}}\fi
    % However, the following does work but has issues
    \begin{thm}[#1]
}
{
    \end{thm}
}

\begin{document}

\begin{thm2}[Optional Argument] 
    This one looks a little better. 
\end{thm2}

\begin{thm2}
    What's up with the empty argument?
\end{thm2}

\end{document}

在此处输入图片描述 在网上查找后,我发现我可以测试 #1 是否为空,但测试这个似乎没什么用,因为\ifx&#1&{\begin{thm}}\else{\begin{thm}}\fi根本无法编译。我该如何解决这个问题?

答案1

您可以\ifstremptyetoolbox包中使用:

在此处输入图片描述

代码:

\documentclass[12pt, letter]{article}

\usepackage{lipsum}
\usepackage{xcolor}
\usepackage{etoolbox}

\newtheorem{thm}{Theorem}

\newenvironment{thm2}[1][]{%
    % The following line now works?
    \ifstrempty{#1}{\begin{thm}}{\begin{thm}[#1]}%
}
{%
    \end{thm}%
}

\begin{document}

\begin{thm2}[Optional Argument] 
    This one looks a little better. 
\end{thm2}

\begin{thm2}
    This also look good now as there is no empty argument.
\end{thm2}

\end{document}

答案2

只需展开\else\fi在发布之前\begin{thm}

\makeatletter
\newenvironment{thm2}[1][]
  {\if\relax\detokenize{#1}\relax % test for emptiness
     \expandafter\@firstoftwo
   \else
     \expandafter\@secondoftwo
   \fi
   {\begin{thm}}{\begin{thm}[1]}%
  }
  {\end{thm}}
\makeatother

另一方面,使用以下方法会更容易一些xparse

\usepackage{xparse}

\NewDocumentEnvironment{thm2}{o}
 {\IfNoValueTF{#1}{\begin{thm}}{\begin{thm}[#1]}
 {\end{thm}}

相关内容