Well, the first version was a very preliminary draft! I polished it a bit and now the only restriction is to use the solutions in the same order as the exercises. If a solution is to be omitted the macro
\omitsolution
is used. As the code grew a bit I decided to make this a small package for you called
exnsols
. You should save the following code under the name
exnsols.sty
in your project folder.
Code: Select all
% package EXNSOLS
\ProvidesPackage{exnsols}[2012/09/04 v0.1 exercises and solutions]
% if hyperref is not loaded there shouldn't be errors:
\newcommand*\ex@hypertarget[2]{#2}
\newcommand*\ex@hyperlink[2]{#2}
\AtBeginDocument{
\@ifpackageloaded{hyperref}{}
{
\let\hypertarget\ex@hypertarget
\let\hyperlink\ex@hyperlink
}
}
% the exercise environment, counted sectionwise
\newcounter{exercise}[section]
\newcounter{exerciseID}
\renewcommand*\theexercise{\thesection.\arabic{exercise}}
\newenvironment{exercise}%
{%
\stepcounter{exercise}%
\refstepcounter{exerciseID}%
\hypertarget{ex:\theexerciseID}{}%
\expandafter\xdef\csname exercise\roman{exerciseID}\endcsname{\theexercise}%
\ifcsname solution\roman{exerciseID}\endcsname
\else
\let\hyperlink\ex@hyperlink
\fi
\small
\trivlist
\item[\llap{\textbf{\hyperlink{sol:\theexerciseID}{\theexercise}}}]%
}%
{\endtrivlist}
% the solution environment
\newcounter{solutionID}
\newenvironment{solution}%
{%
\refstepcounter{solutionID}%
\immediate\write\@auxout{%
\noexpand\global\noexpand\@namedef{solution\roman{solutionID}}{\thesolutionID}}%
\hypertarget{sol:\thesolutionID}{}%
\small
\trivlist
\item[\llap{\textbf{\hyperlink{ex:\thesolutionID}{\@nameuse{exercise\roman{solutionID}}}}}]%
}%
{\endtrivlist}
\newcommand*\omitsolution{\stepcounter{solutionID}}
\endinput
Now you can use it like follows. As it writes stuff to the aux file to check if there is a solution that can be referenced it needs two compiler runs.
Code: Select all
\documentclass[english]{article}
\usepackage{exnsols}
\usepackage{hyperref}
\usepackage{babel}
\usepackage{lipsum}% for dummy text
\begin{document}
\section{First section}
\begin{exercise}
Question: \lipsum[4]
\end{exercise}
\begin{exercise}
Question: \lipsum[4]
\end{exercise}
\begin{exercise}
Question: \lipsum[4]
\end{exercise}
\newpage
\appendix
\section{Solutions}
\begin{solution}
Answer: \lipsum[4]
\end{solution}
\omitsolution
\begin{solution}
Answer: \lipsum[4]
\end{solution}
\end{document}
Regards