创建互斥的包选项并选择默认值

创建互斥的包选项并选择默认值

我想将一些我通常包含的代码自动化,以便将我的theorem environment功能设置到一个包中。因此,我这样做是为了控制我的定理在哪个计数器内编号:

\RequirePackage{filecontents}

\begin{filecontents}{mytheorems.sty}
    \RequirePackage{xkeyval}
    \RequirePackage{amsthm}

    \DeclareOptionX{numberwithin}{%
        \theoremstyle{plain}%
        \newtheorem{theorem}{Theorem}[#1]%
    }
    \DeclareOptionX{nonumberwithin}{%
        \theoremstyle{plain}%
        \newtheorem{theorem}{Theorem}%
    }
    \ProcessOptionsX

    \theoremstyle{plain}
    \newtheorem{lemma}[theorem]{Lemma}
\end{filecontents}

\documentclass{article}

\usepackage[nonumberwithin]{mytheorems}%or use option [numberwithin=section] for example

\begin{document}
    \begin{lemma}
        content...
    \end{lemma}
\end{document}

现在我想在[nonumberwithin]没有给出选项的情况下加载该包。但是,由于这两个选项发生冲突,因此\ExecuteOptionsX{nonumberwithin}无法[numberwithin=section]再添加包。那么我该怎么办?

答案1

我认为,numberwithin等选项应该设置一个\if...变量,并根据布尔值的状态推迟定理的定义。但是,必须存储\if@numberwithin的参数。numberwithin

LaTeX据我所知,这是标准类处理选项的相互排斥状态的方式。

\RequirePackage{filecontents}

\begin{filecontents}{mytheorems.sty}
    \RequirePackage{xkeyval}
    \RequirePackage{amsthm}

    \newif\if@numberwithin
    \def\@numberwithin{section}% Defining a default if needed        
    \DeclareOptionX{numberwithin}{%
      \@numberwithintrue
      \gdef\@numberwithin{#1}%
    }
    \DeclareOptionX{nonumberwithin}{%
      \@numberwithinfalse
    }
    \ExecuteOptionsX{nonumberwithin}
    \ProcessOptionsX

    \if@numberwithin
    \theoremstyle{plain}
    \newtheorem{theorem}{Theorem}[\@numberwithin]%
    \else
    \theoremstyle{plain}
    \newtheorem{theorem}{Theorem}%
    \fi

    \theoremstyle{plain}
    \newtheorem{lemma}[theorem]{Lemma}
\end{filecontents}

\documentclass{article}

%\usepackage[numberwithin=section]{mytheorems}%or use option [numberwithin=section] for example

\usepackage{mytheorems}%or use option [numberwithin=section] for example

\begin{document}
    \begin{lemma}
        content...
    \end{lemma}
\end{document}

答案2

添加一个默认选项numberwithin,以便调用

\usepackage[numberwithin]{mytheorems}

或者

\usepackage[numberwithin=section]{mytheorems}

将等效于 以及\usepackage{mytheorems},因为\ExecuteOptionsX{numberwithin}。然后在处理选项之后延迟计数器的关联。

\ProvidesPackage{mytheorems}
\RequirePackage{xkeyval}
\RequirePackage{amsmath}
\RequirePackage{amsthm}

\DeclareOptionX{numberwithin}[section]{%
  \def\mthm@numberwithin{#1}%
}
\DeclareOptionX{nonumberwithin}{%
  \def\mthm@numberwithin{}%
}
\ExecuteOptionsX{numberwithin}
\ProcessOptionsX

\theoremstyle{plain}
\newtheorem{theorem}{Theorem}

\ifx\mthm@numberwithin\@empty\else
  \numberwithin{theorem}{\mthm@numberwithin}
\fi

\newtheorem{lemma}[theorem]{Lemma}

相关内容