While cfr's answer is very nice and general, I also ran into this problem and wanted to present a specific solution using one IDE, TeXstudio.
To accomplish this, I defined a user command (Preferences > Build > User Commands
) as
"/path/to/script/compile-exam.py" %.tex -f | txs:///pdflatex | mv %.pdf %Solutions.pdf | mv %.synctex.gz %Solutions.synctex.gz | "/path/to/script/compile-exam.py" %.tex | txs:///pdflatex | txs:///view-pdf-internal "?m)Solutions.pdf"
where compile-exam.py
is a python script I wrote (available here):
from argparse import ArgumentParser
import re
from shutil import copyfile
parser = ArgumentParser()
parser.add_argument('filename')
parser.add_argument('-f', '--forward', action='store_true')
args = parser.parse_args()
copyfile(args.filename, args.filename+'.bak')
basename = re.match(r".+(?=\.tex)", args.filename).group(0)
if args.forward:
contents = []
with open(args.filename, 'r') as in_file:
for line in in_file:
if r'\printanswers' in line:
contents.append('\printanswers\n')
else:
contents.append(line)
with open(args.filename, 'w') as out_file:
for line in contents:
out_file.write(line)
else:
contents = []
with open(args.filename, 'r') as in_file:
for line in in_file:
if r'\printanswers' in line:
contents.append('%\printanswers\n')
else:
contents.append(line)
with open(args.filename, 'w') as out_file:
for line in contents:
out_file.write(line)
From here, I define a keyboard shortcut to run the command (Preferences > Shortcuts > Tools > User
)
Using this keyboard shortcut, the compiler will produce exam1.pdf
and exam1Solutions.pdf
and display the Solutions file in the built-in viewer (still with the ability to scroll to the location of the last edit, etc.).
Also note, you will either need to call python
first or make the script executable and add something like #!/usr/bin/python
on the first line.
This is obviously not a general solution and does require calling an external program, but it works nicely and in a reasonable amount of time.
.tex
files with different names which call the main file, compiling the two wrappers to produce the two outputs. (2) Using a script rather than running the compilation directly either instead of, or in combination with, (1).color
andgraphicx
? Usually those packages are quite capable of detecting the right driver themselves...