# Lecture notes with embedded exercises and separate keys

I have a collection of lecture notes which have exercises scattered throughout them. I would like to provide a key to these exercises that is a separate file from the compiled notes, but whose corresponding TeX code is in the same code as the notes and refers to the chapter/section which the exercise is from.

For example, if the code for the lectures looked like this:

\begin{document}
\chapter{Lecture 1}
...
\begin{exercise}
What is 2 + 2?
\end{exercise}
\begin{solution}
4
\end{solution}
...
\begin{exercise}
What is 2 * 3?
\end{exercise}
\begin{solution}
6
\end{solution}
\chapter{Lecture 2}
...
\begin{exercise}
How many Canadian provinces are there?
\end{exercise}
\begin{solution}
10
\end{solution}
...
\begin{exercise}
What is the capital of Nova Scotia?
\end{exercise}
\begin{solution}
Halifax
\end{solution}
\end{document}


Then the corresponding PDF for the lecture notes would have Lectures 1 and 2 with the exercises, sans solutions, but separate PDF's containing the solutions to the exercises from lecture 1, another PDF for the solutions from lecture 2, and those PDF's would know the displayed solution was from Exercise 2 in Lecture 1, and so on.

The most obvious solution I can think of is to use etoolbox's toggles to show just the notes with exercises or just the solutions, but then I'd have \iftoggle everywhere and have to manually create the PDF of each lecture's solutions which will quickly get tedious if there are several lectures or if I need to go back and make changes that change the numbering of a problem or lecture.

(Non-TeX solutions involving shell scripts would be okay with me if there isn't a good way to do this in LaTeX.)

Here is a way using answers package and \includeonly

the main (driver) file myfile.tex

\documentclass{book}

\newtheorem{exercise}{Exercise}[chapter]
\Newassociation{solution}{Soln}{mycor}

\includeonly{Lectures}
%\includeonly{Lecture1}
%\includeonly{Lecture2}

\begin{document}
\include{Lectures}
\include{Lecture1}
\include{Lecture2}
\end{document}


the main (source) file Lectures.tex

\Opensolutionfile{mycor}[Lecture1]
\chapter{Lecture 1}
...
\begin{exercise}
What is 2 + 2?
\begin{solution}
4
\end{solution}
\end{exercise}
...
\begin{exercise}
What is 2 * 3?
\begin{solution}
6
\end{solution}
\end{exercise}
\Closesolutionfile{mycor}
\Opensolutionfile{mycor}[Lecture2]
\chapter{Lecture 2}
...
\begin{exercise}
How many Canadian provinces are there?
\begin{solution}
10
\end{solution}
\end{exercise}
...
\begin{exercise}
What is the capital of Nova Scotia?
\begin{solution}
Halifax
\end{solution}
\end{exercise}
\Closesolutionfile{mycor}

• Thanks, this is pretty much exactly what I was looking for! – cjohnson Jun 11 '16 at 12:25
• @cjohnson Glad it helped – touhami Jun 11 '16 at 15:17