How to automatically compile two versions of the same document, for example version without answers for the students and another version with answers for myself?
Asked
Active
Viewed 1,436 times
2 Answers
4
I have a small bash script to do a dual format.
function latex-ans () {
n=$(basename $1 .tex) # strip .tex in filename foo.tex -> foo
ln -s $n.tex $n-ans.tex # create a soft link (for instance foo-ans.tex -> foo.tex)
pdflatex '\def\withanswer{1} \input{'$n-ans'}' && pdflatex $n
% first format the version with answers and then the normal version
rm $n-ans.tex $n-ans.log
% remove useless files
}
If I have a file foo.tex, this commands formats both versions of the file and generates two pdf: foo.pdf and foo-ans.pdf. Thanks to the renaming of foo.tex through the ln -s
, it also keeps separate foo.aux and foo-ans.aux to preserve useful information on both versions.
At the latex level, I basically do the same and use the macro \withanswers to configure my packages.

samcarter_is_at_topanswers.xyz
- 33,336
- 5
- 41
- 62

Alain Merigot
- 10,667
- 3
- 18
- 31
-
Thanks for your answer. What do you mean with "More, you do not know which version of file is in a given pdf"? – samcarter_is_at_topanswers.xyz Jul 19 '19 at 12:27
-
If you have a file foo.pdf, is it generated from foo.tex with answers or from foo.tex without answers? – Alain Merigot Jul 19 '19 at 12:33
-
The one with answers is automatically called `foo_solution.pdf`, I don't see any risk to distribute the wrong one to students – samcarter_is_at_topanswers.xyz Jul 19 '19 at 12:35
-
Right. I missed that. First line of you program is too long! This should solve also the .aux problem. – Alain Merigot Jul 19 '19 at 12:37
-
As far as I know texstudio does not support line breaks in magic comments - not much that can be done about that – samcarter_is_at_topanswers.xyz Jul 19 '19 at 12:39
1
There are several packages that allow to conditionally exclude certain parts of the document, for example the exercise
package.
With TeXstudio, the following magic comment can be used to automatically compile both versions at once (including repeated compilation for cross-references, bibliographies, indices etc.):
% !TeX program = latexmk -pdf -pdflatex="pdflatex -synctex=1 -interaction=nonstopmode -shell-escape" -jobname=% -pretex="\newcommand{\version}{noanswer}" -usepretex % | latexmk -pdf -pdflatex="pdflatex -synctex=1 -interaction=nonstopmode -shell-escape" -jobname=%_solution -pretex="\newcommand{\version}{}" -usepretex % | txs:///view-pdf "?am)_solution.pdf"
\documentclass{article}
% setting a default value in case it is compiled without the magic comment
\ifdefined\version
\else
\def\version{noanswer}
\fi
\usepackage[\version]{exercise}
\begin{document}
\begin{Exercise}[title={Title},label=ex1]
question text
\end{Exercise}
\begin{Answer}[ref={ex1}]
solution
\end{Answer}
\end{document}

samcarter_is_at_topanswers.xyz
- 33,336
- 5
- 41
- 62