12.07.2015 Views

The memoir class - The UK TeX Archive

The memoir class - The UK TeX Archive

The memoir class - The UK TeX Archive

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

15. BOXES, VERBATIMS AND FILES\newcounter{question} \setcounter{question}{0}\renewcommand{\thequestion}{\arabic{question}}\newenvironment{question}[1]%{\refstepcounter{question}\par\noindent\textbf{Question \thequestion:}\label{#1}}%{\par}I have used \refstepcounter to increment the counter so that the \label will refer toit, and not some external counter.We will use a file, called \jobname.ans to collect the answers and this will be writtento by a stream. <strong>The</strong>re is also a convenience macro, \printanswers, for the user to call toprint the answers.\newoutputstream{ansout}A matching environment for answers is required. <strong>The</strong> argument to the environment isthe key of the question.In draft mode it is simple, just typeset the answer and no need to bother with any fileprinting (remember that \ifdraftdoc is true for a draft mode document).\ifdraftdoc% when in draft mode\newenvironment{answer}[1]%{\par\noindent\textbf{Answer \ref{#1}:}}%{\par}\newcommand{\printanswers}{}\else% when not in draft modeIn final mode the answer environment must write its contents verbatim to the ans filefor printing by \printanswers. Dealing with these in reverse order, this is the definitionof \printanswer when not in draft mode.\newcommand{\printanswers}{%\closeoutputstream{ansout}\input{\jobname.ans}}Now for the tricky bit, the answer environment. First define an environment thatmakes sure our output stream is open, and which then writes the answer title to the stream.\newenvironment{@nswer}[1]{\@bsphack\IfStreamOpen{ansout}{}{%\openoutputfile{\jobname.ans}{ansout}%}%\addtostream{ansout}{\par\noindent\textbf{Answer \ref{#1}:}}%}{\@esphack}<strong>The</strong> macros \@bsphack and \@esphack are La<strong>TeX</strong> kernel macros that will gobble extraneousspaces around the environment. In other words, this environment will take no spacein the typeset result. <strong>The</strong> \IfStreamOpen macro is used to test whether or not the streamis open, and if it isn’t then it opens it. <strong>The</strong> answer title is then written out to the stream.Now we can define the answer environment so that its contents get written out verbatim.292\newenvironment{answer}[1]%{\@bsphack\@nswer{#1}\writeverbatim{ansout}}%

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!