#ifdef in Latex documents


Consider the case where you want to generate slightly different versions of a document out of single latex file. This could be needed when using different document templates or if you want to switch on/off commentary in your document. You may want different introduction or order of chapters based on each particular case. A way to do it is using conditionals that exists available in plain TeX. For example

\documentclass{article}
\newif\ifanswers
%\answerstrue 
\begin{document}

question : what is the expected complexity of quicksort for an array of integers ?
\vspace{1cm}

\ifanswers
answer $o(n\log n)$ where $n$ is the numer of integers.
\fi
\vspace{1cm}

question : give the definition of an abelian group .
\vspace{1cm}

\ifanswers
answer : an abelian group is a set, $a$, together with an operation $\cdot$ that ...
\vspace{1cm}
\fi
\end{document}

Enabling conditionals can be achieved by commenting/uncommenting the 3rd line either by hand or using a makefile:

LATEX=pdflatex
#LATEX=latexmk -pdf
plain:
	$(LATEX) main.tex

with_answers:
	cp main.tex main_with_answers.tex
	sed -i 's|%\\answerstrue|\\answerstrue|' main_with_answers.tex
	$(LATEX) main_with_answers.tex

both: plain with_answers

source