具有与计数器相关的可选参数的环境

具有与计数器相关的可选参数的环境

这个问题是基于我上一个问题而提出的:定义与计数器相关的自己的类选项。 在...的帮助下埃格尔,这里有一个类文件,其中有一个名为的环境exercise

\NeedsTeXFormat{LaTeX2e}
\ProvidesClass{class}

\newcounter{exercounter}

\DeclareOption{withinchap}{\def\exercounter@within{chapter}}
\DeclareOption{withinsec}{\def\exercounter@within{section}}
\DeclareOption*{\PassOptionsToClass{\CurrentOption}{report}}

\ExecuteOptions{withinchap}
\ProcessOptions\relax

\LoadClass{report} % should go after processing options

\RequirePackage{indentfirst}


\counterwithin*{exercounter}{\exercounter@within}

\newenvironment{exercise}%
    {\stepcounter{exercounter}\par\textbf{\theexercounter.}}%
    {\ignorespacesafterend}

现在我想exercise用一个可选参数(实际上是一个正整数)重写环境,即

\newenvironment{exercise}[1]{...

然后当我使用exercise这样的环境时:

\begin{exercise}[number]
...
\end{exercise}

当前练习的编号为number,下一个练习计数器从number+1 开始增加。有什么提示吗?

答案1

xparse您可以使用包定义环境

% .cls file
\NeedsTeXFormat{LaTeX2e}
\ProvidesClass{class}

\newcounter{exercounter}

\DeclareOption{withinchap}{\def\exercounter@within{chapter}}
\DeclareOption{withinsec}{\def\exercounter@within{section}}
\DeclareOption*{\PassOptionsToClass{\CurrentOption}{report}}

\ExecuteOptions{withinchap}
\ProcessOptions\relax

\LoadClass{report} % should go after processing options

\RequirePackage{indentfirst}
\RequirePackage{xparse}

% \newcounter{exercounter}
\counterwithin*{exercounter}{\exercounter@within}

% \newenvironment{exercise}%
%     {\stepcounter{exercounter}\par\textbf{\theexercounter.}}%
%     {\ignorespacesafterend}

\NewDocumentEnvironment{exercise}{o +b}
  {%
    \IfNoValueTF{#1}
      {\stepcounter{exercounter}}
      {\setcounter{exercounter}{#1}}
    \par\textbf{\theexercounter.}%
    #2
  }
  {\ignorespacesafterend}
% .tex file
\documentclass{class}

\begin{document}
\begin{exercise}
  test
\end{exercise}

\begin{exercise}[4]
  test
\end{exercise}

\begin{exercise}
  test
\end{exercise}

\begin{exercise}
  test
\end{exercise}
\end{document}

在此处输入图片描述

相关内容