0

This question is on the basis of my last question: Define own class options relating to counter. With the help of egreg, here is a class file in which there is an environment named 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}

Now I want to rewrite the exercise environment with an optional argument (in fact an positive integer), i.e.

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

And then when I use exercise environment like this:

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

The number of the current exercise is number and the following exercise counter increases from number+1. Any hint?

1 Answer 1

4

You can define the environment with xparse package

% .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}

enter image description here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .