1# File: UseLATEX.cmake
2# CMAKE commands to actually use the LaTeX compiler
3# Version: 2.4.8
4# Author: Kenneth Moreland <kmorel@sandia.gov>
5#
6# Copyright 2004, 2015 Sandia Corporation.
7# Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
8# license for use of this work by or on behalf of the U.S. Government.
9#
10# This software is released under the BSD 3-Clause License.
11#
12# Redistribution and use in source and binary forms, with or without
13# modification, are permitted provided that the following conditions are
14# met:
15#
16# 1. Redistributions of source code must retain the above copyright notice,
17# this list of conditions and the following disclaimer.
18#
19# 2. Redistributions in binary form must reproduce the above copyright
20# notice, this list of conditions and the following disclaimer in the
21# documentation and/or other materials provided with the distribution.
22#
23# 3. Neither the name of the copyright holder nor the names of its
24# contributors may be used to endorse or promote products derived from this
25# software without specific prior written permission.
26#
27# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
28# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
29# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
30# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
31# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
32# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
33# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
34# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
35# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
36# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
37# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38#
39#
40# The following function is defined:
41#
42# add_latex_document(<tex_file>
43#                    [BIBFILES <bib_files>]
44#                    [INPUTS <input_tex_files>]
45#                    [IMAGE_DIRS] <image_directories>
46#                    [IMAGES] <image_files>
47#                    [CONFIGURE] <tex_files>
48#                    [DEPENDS] <tex_files>
49#                    [MULTIBIB_NEWCITES] <suffix_list>
50#                    [USE_BIBLATEX]
51#                    [USE_INDEX]
52#                    [INDEX_NAMES <index_names>]
53#                    [USE_GLOSSARY] [USE_NOMENCL]
54#                    [FORCE_PDF] [FORCE_DVI] [FORCE_HTML]
55#                    [TARGET_NAME] <name>
56#                    [EXCLUDE_FROM_ALL]
57#                    [EXCLUDE_FROM_DEFAULTS])
58#       Adds targets that compile <tex_file>.  The latex output is placed
59#       in LATEX_OUTPUT_PATH or CMAKE_CURRENT_BINARY_DIR if the former is
60#       not set.  The latex program is picky about where files are located,
61#       so all input files are copied from the source directory to the
62#       output directory.  This includes the target tex file, any tex file
63#       listed with the INPUTS option, the bibliography files listed with
64#       the BIBFILES option, and any .cls, .bst, .clo, .sty, .ist, and .fd
65#       files found in the current source directory.  Images found in the
66#       IMAGE_DIRS directories or listed by IMAGES are also copied to the
67#       output directory and converted to an appropriate format if necessary.
68#       Any tex files also listed with the CONFIGURE option are also processed
69#       with the CMake CONFIGURE_FILE command (with the @ONLY flag).  Any file
70#       listed in CONFIGURE but not the target tex file or listed with INPUTS
71#       has no effect. DEPENDS can be used to specify generated files that are
72#       needed to compile the latex target.
73#
74#       The following targets are made. The name prefix is based off of the
75#       base name of the tex file unless TARGET_NAME is specified. If
76#       TARGET_NAME is specified, then that name is used for the targets.
77#
78#               name_dvi: Makes <name>.dvi
79#               name_pdf: Makes <name>.pdf using pdflatex.
80#               name_safepdf: Makes <name>.pdf using ps2pdf.  If using the
81#                       default program arguments, this will ensure all fonts
82#                       are embedded and no lossy compression has been
83#                       performed on images.
84#               name_ps: Makes <name>.ps
85#               name_html: Makes <name>.html
86#               name_auxclean: Deletes <name>.aux and other auxiliary files.
87#                       This is sometimes necessary if a LaTeX error occurs
88#                       and writes a bad aux file.  Unlike the regular clean
89#                       target, it does not delete other input files, such as
90#                       converted images, to save time on the rebuild.
91#
92#       Unless the EXCLUDE_FROM_ALL option is given, one of these targets
93#       is added to the ALL target and built by default. Which target is
94#       determined by the LATEX_DEFAULT_BUILD CMake variable. See the
95#       documentation of that variable for more details.
96#
97#       Unless the EXCLUDE_FROM_DEFAULTS option is given, all these targets
98#       are added as dependencies to targets named dvi, pdf, safepdf, ps,
99#       html, and auxclean, respectively.
100#
101#       USE_BIBLATEX enables the use of biblatex/biber as an alternative to
102#       bibtex. Bibtex remains the default if USE_BIBLATEX is not
103#       specified.
104#
105#       If the argument USE_INDEX is given, then commands to build an index
106#       are made. If the argument INDEX_NAMES is given, an index file is
107#       generated for each name in this list. See the LaTeX package multind
108#       for more information about how to generate multiple indices.
109#
110#       If the argument USE_GLOSSARY is given, then commands to
111#       build a glossary are made.  If the argument MULTIBIB_NEWCITES is
112#       given, then additional bibtex calls are added to the build to
113#       support the extra auxiliary files created with the \newcite command
114#       in the multibib package.
115#
116# History:
117#
118# 2.4.8 Fix synctex issue with absolute paths not being converted.
119#
120# 2.4.7 Fix some issues with spaces in the path of the working directory where
121#       LaTeX is executed.
122#
123# 2.4.6 Fix parse issue with older versions of CMake.
124#
125# 2.4.5 Fix issues with files and paths containing spaces.
126#
127# 2.4.4 Improve error reporting message when LaTeX fails.
128#
129#       When LaTeX fails, delete the output file, which is invalid.
130#
131#       Add warnings for "missing characters." These usually mean that a
132#       non-ASCII character is in the document and will not be printed
133#       correctly.
134#
135# 2.4.3 Check for warnings from the natbib package. When using natbib,
136#       warnings for missing bibliography references look different. So
137#       far, natbib seems to be quiet unless something is important, so
138#       look for all natbib warnings. (We can change this later if
139#       necessary.)
140#
141# 2.4.2 Fix an issue where new versions of ImageMagick expect the order of
142#       options in command line execution of magick/convert. (See, for
143#       example, http://www.imagemagick.org/Usage/basics/#why.)
144#
145# 2.4.1 Add ability to dump LaTeX log file when using batch mode. Batch
146#       mode suppresses most output, often including error messages. To
147#       make sure critical error messages get displayed, show the full log
148#       on failures.
149#
150# 2.4.0 Remove "-r 600" from the default PDFTOPS_CONVERTER_FLAGS. The -r flag
151#       is available from the Poppler version of pdftops, but not the Xpdf
152#       version.
153#
154#       Fix an issue with the flags for the different programs not being
155#       properly separated.
156#
157#       Fix an issue on windows where the = character is not allowed for
158#       ps2pdf arguments.
159#
160#       Change default arguments for latex and pdflatex commands. Makes the
161#       output more quiet and prints out the file/line where errors occur.
162#       (Thanks to Nikos Koukis.)
163#
164#       After a LaTeX build, check the log file for warnings that are
165#       indicative of problems with the build.
166#
167#       Remove support for latex2html. Instead, use the htlatex program.
168#       This is now part of TeX Live and most other distributions. It also
169#       behaves much more like the other LaTeX programs. Also fixed some
170#       nasty issues with the htlatex arguments.
171#
172# 2.3.2 Declare LaTeX input files as sources for targets so that they show
173#       up in IDEs like QtCreator.
174#
175#       Fix issue where main tex files in subdirectories were creating
176#       invalid targets for building HTML. Just disable the HTML targets in
177#       this case.
178#
179# 2.3.1 Support use of magick command instead of convert command for
180#       ImageMagick 7.
181#
182# 2.3.0 Add USE_BIBLATEX option to support the biblatex package, which
183#       requires using the program biber as a replacement for bibtex
184#       (thanks to David Tracey).
185#
186# 2.2.1 Add STRINGS property to LATEX_DEFAULT_BUILD to make it easier to
187#       select the default build in the CMake GUI.
188#
189# 2.2.0 Add TARGET_NAME option.
190#
191# 2.1.1 Support for finding bmp, ppm, and other image files.
192#
193# 2.1.0 Fix an error where the pdf target and others were defined multiple
194#       times if UseLATEX.cmake was included multiple times.
195#
196#       Added INDEX_NAMES option to support multiple indexes in a single
197#       document from the multind package (thanks to Dan Lipsa).
198#
199# 2.0.0 First major revision of UseLATEX.cmake updates to more recent features
200#       of CMake and some non-backward compatible changes.
201#
202#       Changed all function and macro names to lower case. CMake's identifiers
203#       are case insensitive, but the convention moved from all upper case to
204#       all lower case somewhere around the release of CMake 2. (The original
205#       version of UseLATEX.cmake predates that.)
206#
207#       Remove condition matching in if statements. They are no longer necessary
208#       and are even discouraged (because else clauses get confusing).
209#
210#       Use "new" features available in CMake such as list and argument parsing.
211#
212#       Remove some code that has been deprecated for a while.
213#
214#       Mark variables for compiler and converter executables as advanced to
215#       match the more conventional CMake behavior.
216#
217#       Changed how default builds are specified and add the ability to force
218#       a particular build.
219#
220#       Made the base targets (pdf, dvi, etc.) global. add_latex_document
221#       always mangles its target names and these base targets depend on
222#       the targets with mangled names.
223#
224# 1.10.5 Fix for Window's convert check (thanks to Martin Baute).
225#
226# 1.10.4 Copy font files to binary directory for packages that come with
227#       their own fonts.
228#
229# 1.10.3 Check for Windows version of convert being used instead of
230#       ImageMagick's version (thanks to Martin Baute).
231#
232# 1.10.2 Use htlatex as a fallback when latex2html is not available (thanks
233#       to Tomasz Grzegurzko).
234#
235# 1.10.1 Make convert program mandatory only if actually used (thanks to
236#       Julien Schueller).
237#
238# 1.10.0 Added NO_DEFAULT and DEFAULT_PS options.
239#       Fixed issue with cleaning files for LaTeX documents originating in
240#       a subdirectory.
241#
242# 1.9.6 Fixed problem with LATEX_SMALL_IMAGES.
243#       Strengthened check to make sure the output directory does not contain
244#       the source files.
245#
246# 1.9.5 Add support for image types not directly supported by either latex
247#       or pdflatex.  (Thanks to Jorge Gerardo Pena Pastor for SVG support.)
248#
249# 1.9.4 Fix issues with filenames containing multiple periods.
250#
251# 1.9.3 Hide some variables that are now cached but should not show up in
252#       the ccmake list of variables.
253#
254# 1.9.2 Changed MACRO declarations to FUNCTION declarations.  The better
255#       FUNCTION scoping will hopefully avoid some common but subtle bugs.
256#       This implicitly increases the minimum CMake version to 4.6 (although
257#       I honestly only test it with the latest 4.8 version).
258#
259#       Since we are updating the minimum CMake version, I'm going to start
260#       using the builtin LIST commands that are now available.
261#
262#       Favor using pdftops from the Poppler package to convert from pdf to
263#       eps.  It does a much better job than ImageMagick or ghostscript.
264#
265# 1.9.1 Fixed typo that caused the LATEX_SMALL_IMAGES option to fail to
266#       activate.
267#
268# 1.9.0 Add support for the multibib package (thanks to Antonio LaTorre).
269#
270# 1.8.2 Fix corner case when an argument name was also a variable containing
271#       the text of an argument.  In this case, the CMake IF was matching
272#       the argument text with the contents of the variable with the same
273#       argument name.
274#
275# 1.8.1 Fix problem where ps2pdf was not getting the appropriate arguments.
276#
277# 1.8.0 Add support for synctex.
278#
279# 1.7.7 Support calling xindy when making glossaries.
280#
281#       Improved make clean support.
282#
283# 1.7.6 Add support for the nomencl package (thanks to Myles English).
284#
285# 1.7.5 Fix issue with bibfiles being copied two different ways, which causes
286#       Problems with dependencies (thanks to Edwin van Leeuwen).
287#
288# 1.7.4 Added the DEFAULT_SAFEPDF option (thanks to Raymond Wan).
289#
290#       Added warnings when image directories are not found (and were
291#       probably not given relative to the source directory).
292#
293# 1.7.3 Fix some issues with interactions between makeglossaries and bibtex
294#       (thanks to Mark de Wever).
295#
296# 1.7.2 Use ps2pdf to convert eps to pdf to get around the problem with
297#       ImageMagick dropping the bounding box (thanks to Lukasz Lis).
298#
299# 1.7.1 Fixed some dependency issues.
300#
301# 1.7.0 Added DEPENDS options (thanks to Theodore Papadopoulo).
302#
303# 1.6.1 Ported the makeglossaries command to CMake and embedded the port
304#       into UseLATEX.cmake.
305#
306# 1.6.0 Allow the use of the makeglossaries command.  Thanks to Oystein
307#       S. Haaland for the patch.
308#
309# 1.5.0 Allow any type of file in the INPUTS lists, not just tex file
310#       (suggested by Eric Noulard).  As a consequence, the ability to
311#       specify tex files without the .tex extension is removed.  The removed
312#       function is of dubious value anyway.
313#
314#       When copying input files, skip over any file that exists in the
315#       binary directory but does not exist in the source directory with the
316#       assumption that these files were added by some other mechanism.  I
317#       find this useful when creating large documents with multiple
318#       chapters that I want to build separately (for speed) as I work on
319#       them.  I use the same boilerplate as the starting point for all
320#       and just copy it with different configurations.  This was what the
321#       separate ADD_LATEX_DOCUMENT method was supposed to originally be for.
322#       Since its external use is pretty much deprecated, I removed that
323#       documentation.
324#
325# 1.4.1 Copy .sty files along with the other class and package files.
326#
327# 1.4.0 Added a MANGLE_TARGET_NAMES option that will mangle the target names.
328#
329#       Fixed problem with copying bib files that became apparent with
330#       CMake 2.4.
331#
332# 1.3.0 Added a LATEX_OUTPUT_PATH variable that allows you or the user to
333#       specify where the built latex documents to go.  This is especially
334#       handy if you want to do in-source builds.
335#
336#       Removed the ADD_LATEX_IMAGES macro and absorbed the functionality
337#       into ADD_LATEX_DOCUMENT.  The old interface was always kind of
338#       clunky anyway since you had to specify the image directory in both
339#       places.  It also made supporting LATEX_OUTPUT_PATH problematic.
340#
341#       Added support for jpeg files.
342#
343# 1.2.0 Changed the configuration options yet again.  Removed the NO_CONFIGURE
344#       Replaced it with a CONFIGURE option that lists input files for which
345#       configure should be run.
346#
347#       The pdf target no longer depends on the dvi target.  This allows you
348#       to build latex documents that require pdflatex.  Also added an option
349#       to make the pdf target the default one.
350#
351# 1.1.1 Added the NO_CONFIGURE option.  The @ character can be used when
352#       specifying table column separators.  If two or more are used, then
353#       will incorrectly substitute them.
354#
355# 1.1.0 Added ability include multiple bib files.  Added ability to do copy
356#       sub-tex files for multipart tex files.
357#
358# 1.0.0 If both ps and pdf type images exist, just copy the one that
359#       matches the current render mode.  Replaced a bunch of STRING
360#       commands with GET_FILENAME_COMPONENT commands that were made to do
361#       the desired function.
362#
363# 0.4.0 First version posted to CMake Wiki.
364#
365
366if(__USE_LATEX_INCLUDED)
367  return()
368endif()
369set(__USE_LATEX_INCLUDED TRUE)
370
371#############################################################################
372# Find the location of myself while originally executing.  If you do this
373# inside of a macro, it will recode where the macro was invoked.
374#############################################################################
375set(LATEX_USE_LATEX_LOCATION ${CMAKE_CURRENT_LIST_FILE}
376  CACHE INTERNAL "Location of UseLATEX.cmake file." FORCE
377  )
378
379#############################################################################
380# Generic helper functions
381#############################################################################
382
383include(CMakeParseArguments)
384
385function(latex_list_contains var value)
386  set(input_list ${ARGN})
387  list(FIND input_list "${value}" index)
388  if(index GREATER -1)
389    set(${var} TRUE PARENT_SCOPE)
390  else()
391    set(${var} PARENT_SCOPE)
392  endif()
393endfunction(latex_list_contains)
394
395# Match the contents of a file to a regular expression.
396function(latex_file_match variable filename regexp default)
397  # The FILE STRINGS command would be a bit better, but I'm not totally sure
398  # the match will always be to a whole line, and I don't want to break things.
399  file(READ ${filename} file_contents)
400  string(REGEX MATCHALL "${regexp}"
401    match_result ${file_contents}
402    )
403  if(match_result)
404    set(${variable} "${match_result}" PARENT_SCOPE)
405  else()
406    set(${variable} "${default}" PARENT_SCOPE)
407  endif()
408endfunction(latex_file_match)
409
410# A version of GET_FILENAME_COMPONENT that treats extensions after the last
411# period rather than the first.  To the best of my knowledge, all filenames
412# typically used by LaTeX, including image files, have small extensions
413# after the last dot.
414function(latex_get_filename_component varname filename type)
415  set(result)
416  if("${type}" STREQUAL "NAME_WE")
417    get_filename_component(name ${filename} NAME)
418    string(REGEX REPLACE "\\.[^.]*\$" "" result "${name}")
419  elseif("${type}" STREQUAL "EXT")
420    get_filename_component(name ${filename} NAME)
421    string(REGEX MATCH "\\.[^.]*\$" result "${name}")
422  else()
423    get_filename_component(result ${filename} ${type})
424  endif()
425  set(${varname} "${result}" PARENT_SCOPE)
426endfunction(latex_get_filename_component)
427
428#############################################################################
429# Functions that perform processing during a LaTeX build.
430#############################################################################
431function(latex_execute_latex)
432  if(NOT LATEX_TARGET)
433    message(SEND_ERROR "Need to define LATEX_TARGET")
434  endif()
435
436  if(NOT LATEX_WORKING_DIRECTORY)
437    message(SEND_ERROR "Need to define LATEX_WORKING_DIRECTORY")
438  endif()
439
440  if(NOT LATEX_FULL_COMMAND)
441    message(SEND_ERROR "Need to define LATEX_FULL_COMMAND")
442  endif()
443
444  if(NOT LATEX_OUTPUT_FILE)
445    message(SEND_ERROR "Need to define LATEX_OUTPUT_FILE")
446  endif()
447
448  set(full_command_original "${LATEX_FULL_COMMAND}")
449
450  # Chose the native method for parsing command arguments. Newer versions of
451  # CMake allow you to just use NATIVE_COMMAND.
452  if (CMAKE_VERSION VERSION_GREATER 3.8)
453    set(separate_arguments_mode NATIVE_COMMAND)
454  else()
455    if (WIN32)
456      set(separate_arguments_mode WINDOWS_COMMAND)
457    else()
458      set(separate_arguments_mode UNIX_COMMAND)
459    endif()
460  endif()
461
462  # Preps variables for use in execute_process.
463  # Even though we expect LATEX_WORKING_DIRECTORY to have a single "argument,"
464  # we also want to make sure that we strip out any escape characters that can
465  # foul up the WORKING_DIRECTORY argument.
466  separate_arguments(LATEX_FULL_COMMAND UNIX_COMMAND "${LATEX_FULL_COMMAND}")
467  separate_arguments(LATEX_WORKING_DIRECTORY_SEP UNIX_COMMAND "${LATEX_WORKING_DIRECTORY}")
468
469  execute_process(
470    COMMAND ${LATEX_FULL_COMMAND}
471    WORKING_DIRECTORY "${LATEX_WORKING_DIRECTORY_SEP}"
472    RESULT_VARIABLE execute_result
473    )
474
475  if(NOT ${execute_result} EQUAL 0)
476    # LaTeX tends to write a file when a failure happens. Delete that file so
477    # that LaTeX will run again.
478    file(REMOVE "${LATEX_WORKING_DIRECTORY}/${LATEX_OUTPUT_FILE}")
479
480    message("\n\nLaTeX command failed")
481    message("${full_command_original}")
482    message("Log output:")
483    file(READ "${LATEX_WORKING_DIRECTORY}/${LATEX_TARGET}.log" log_output)
484    message("${log_output}")
485    message(FATAL_ERROR
486      "Successfully executed LaTeX, but LaTeX returned an error.")
487  endif()
488endfunction(latex_execute_latex)
489
490function(latex_makeglossaries)
491  # This is really a bare bones port of the makeglossaries perl script into
492  # CMake scripting.
493  message("**************************** In makeglossaries")
494  if(NOT LATEX_TARGET)
495    message(SEND_ERROR "Need to define LATEX_TARGET")
496  endif()
497
498  set(aux_file ${LATEX_TARGET}.aux)
499
500  if(NOT EXISTS ${aux_file})
501    message(SEND_ERROR "${aux_file} does not exist.  Run latex on your target file.")
502  endif()
503
504  latex_file_match(newglossary_lines ${aux_file}
505    "@newglossary[ \t]*{([^}]*)}{([^}]*)}{([^}]*)}{([^}]*)}"
506    "@newglossary{main}{glg}{gls}{glo}"
507    )
508
509  latex_file_match(istfile_line ${aux_file}
510    "@istfilename[ \t]*{([^}]*)}"
511    "@istfilename{${LATEX_TARGET}.ist}"
512    )
513  string(REGEX REPLACE "@istfilename[ \t]*{([^}]*)}" "\\1"
514    istfile ${istfile_line}
515    )
516
517  string(REGEX MATCH ".*\\.xdy" use_xindy "${istfile}")
518  if(use_xindy)
519    message("*************** Using xindy")
520    if(NOT XINDY_COMPILER)
521      message(SEND_ERROR "Need to define XINDY_COMPILER")
522    endif()
523  else()
524    message("*************** Using makeindex")
525    if(NOT MAKEINDEX_COMPILER)
526      message(SEND_ERROR "Need to define MAKEINDEX_COMPILER")
527    endif()
528  endif()
529
530  foreach(newglossary ${newglossary_lines})
531    string(REGEX REPLACE
532      "@newglossary[ \t]*{([^}]*)}{([^}]*)}{([^}]*)}{([^}]*)}"
533      "\\1" glossary_name ${newglossary}
534      )
535    string(REGEX REPLACE
536      "@newglossary[ \t]*{([^}]*)}{([^}]*)}{([^}]*)}{([^}]*)}"
537      "${LATEX_TARGET}.\\2" glossary_log ${newglossary}
538      )
539    string(REGEX REPLACE
540      "@newglossary[ \t]*{([^}]*)}{([^}]*)}{([^}]*)}{([^}]*)}"
541      "${LATEX_TARGET}.\\3" glossary_out ${newglossary}
542      )
543    string(REGEX REPLACE
544      "@newglossary[ \t]*{([^}]*)}{([^}]*)}{([^}]*)}{([^}]*)}"
545      "${LATEX_TARGET}.\\4" glossary_in ${newglossary}
546      )
547
548    if(use_xindy)
549      latex_file_match(xdylanguage_line ${aux_file}
550        "@xdylanguage[ \t]*{${glossary_name}}{([^}]*)}"
551        "@xdylanguage{${glossary_name}}{english}"
552        )
553      string(REGEX REPLACE
554        "@xdylanguage[ \t]*{${glossary_name}}{([^}]*)}"
555        "\\1"
556        language
557        ${xdylanguage_line}
558        )
559      # What crazy person makes a LaTeX index generator that uses different
560      # identifiers for language than babel (or at least does not support
561      # the old ones)?
562      if(${language} STREQUAL "frenchb")
563        set(language "french")
564      elseif(${language} MATCHES "^n?germanb?$")
565        set(language "german")
566      elseif(${language} STREQUAL "magyar")
567        set(language "hungarian")
568      elseif(${language} STREQUAL "lsorbian")
569        set(language "lower-sorbian")
570      elseif(${language} STREQUAL "norsk")
571        set(language "norwegian")
572      elseif(${language} STREQUAL "portuges")
573        set(language "portuguese")
574      elseif(${language} STREQUAL "russianb")
575        set(language "russian")
576      elseif(${language} STREQUAL "slovene")
577        set(language "slovenian")
578      elseif(${language} STREQUAL "ukraineb")
579        set(language "ukrainian")
580      elseif(${language} STREQUAL "usorbian")
581        set(language "upper-sorbian")
582      endif()
583      if(language)
584        set(language_flags "-L ${language}")
585      else()
586        set(language_flags "")
587      endif()
588
589      latex_file_match(codepage_line ${aux_file}
590        "@gls@codepage[ \t]*{${glossary_name}}{([^}]*)}"
591        "@gls@codepage{${glossary_name}}{utf}"
592        )
593      string(REGEX REPLACE
594        "@gls@codepage[ \t]*{${glossary_name}}{([^}]*)}"
595        "\\1"
596        codepage
597        ${codepage_line}
598        )
599      if(codepage)
600        set(codepage_flags "-C ${codepage}")
601      else()
602        # Ideally, we would check that the language is compatible with the
603        # default codepage, but I'm hoping that distributions will be smart
604        # enough to specify their own codepage.  I know, it's asking a lot.
605        set(codepage_flags "")
606      endif()
607
608      message("${XINDY_COMPILER} ${MAKEGLOSSARIES_COMPILER_ARGS} ${language_flags} ${codepage_flags} -I xindy -M ${glossary_name} -t ${glossary_log} -o ${glossary_out} ${glossary_in}"
609        )
610      exec_program(${XINDY_COMPILER}
611        ARGS ${MAKEGLOSSARIES_COMPILER_ARGS}
612          ${language_flags}
613          ${codepage_flags}
614          -I xindy
615          -M ${glossary_name}
616          -t ${glossary_log}
617          -o ${glossary_out}
618          ${glossary_in}
619        OUTPUT_VARIABLE xindy_output
620        )
621      message("${xindy_output}")
622
623      # So, it is possible (perhaps common?) for aux files to specify a
624      # language and codepage that are incompatible with each other.  Check
625      # for that condition, and if it happens run again with the default
626      # codepage.
627      if("${xindy_output}" MATCHES "^Cannot locate xindy module for language (.+) in codepage (.+)\\.$")
628        message("*************** Retrying xindy with default codepage.")
629        exec_program(${XINDY_COMPILER}
630          ARGS ${MAKEGLOSSARIES_COMPILER_ARGS}
631            ${language_flags}
632            -I xindy
633            -M ${glossary_name}
634            -t ${glossary_log}
635            -o ${glossary_out}
636            ${glossary_in}
637          )
638      endif()
639
640    else()
641      message("${MAKEINDEX_COMPILER} ${MAKEGLOSSARIES_COMPILER_ARGS} -s ${istfile} -t ${glossary_log} -o ${glossary_out} ${glossary_in}")
642      exec_program(${MAKEINDEX_COMPILER} ARGS ${MAKEGLOSSARIES_COMPILER_ARGS}
643        -s ${istfile} -t ${glossary_log} -o ${glossary_out} ${glossary_in}
644        )
645    endif()
646
647  endforeach(newglossary)
648endfunction(latex_makeglossaries)
649
650function(latex_makenomenclature)
651  message("**************************** In makenomenclature")
652  if(NOT LATEX_TARGET)
653    message(SEND_ERROR "Need to define LATEX_TARGET")
654  endif()
655
656  if(NOT MAKEINDEX_COMPILER)
657    message(SEND_ERROR "Need to define MAKEINDEX_COMPILER")
658  endif()
659
660  set(nomencl_out ${LATEX_TARGET}.nls)
661  set(nomencl_in ${LATEX_TARGET}.nlo)
662
663  exec_program(${MAKEINDEX_COMPILER} ARGS ${MAKENOMENCLATURE_COMPILER_ARGS}
664    ${nomencl_in} -s "nomencl.ist" -o ${nomencl_out}
665    )
666endfunction(latex_makenomenclature)
667
668function(latex_correct_synctex)
669  message("**************************** In correct SyncTeX")
670  if(NOT LATEX_TARGET)
671    message(SEND_ERROR "Need to define LATEX_TARGET")
672  endif()
673
674  if(NOT GZIP)
675    message(SEND_ERROR "Need to define GZIP")
676  endif()
677
678  if(NOT LATEX_SOURCE_DIRECTORY)
679    message(SEND_ERROR "Need to define LATEX_SOURCE_DIRECTORY")
680  endif()
681
682  if(NOT LATEX_BINARY_DIRECTORY)
683    message(SEND_ERROR "Need to define LATEX_BINARY_DIRECTORY")
684  endif()
685  message("${LATEX_BINARY_DIRECTORY}")
686  message("${LATEX_SOURCE_DIRECTORY}")
687
688  set(synctex_file ${LATEX_BINARY_DIRECTORY}/${LATEX_TARGET}.synctex)
689  set(synctex_file_gz ${synctex_file}.gz)
690
691  if(EXISTS ${synctex_file_gz})
692
693    message("Making backup of synctex file.")
694    configure_file(${synctex_file_gz} ${synctex_file}.bak.gz COPYONLY)
695
696    message("Uncompressing synctex file.")
697    exec_program(${GZIP}
698      ARGS --decompress ${synctex_file_gz}
699      )
700
701    message("Reading synctex file.")
702    file(READ ${synctex_file} synctex_data)
703
704    message("Replacing output paths with input paths.")
705    foreach(extension tex cls bst clo sty ist fd)
706      # Relative paths
707      string(REGEX REPLACE
708        "(Input:[0-9]+:)([^/\n][^\n]\\.${extension}*)"
709        "\\1${LATEX_SOURCE_DIRECTORY}/\\2"
710        synctex_data
711        "${synctex_data}"
712        )
713
714      # Absolute paths
715      string(REGEX REPLACE
716        "(Input:[0-9]+:)${LATEX_BINARY_DIRECTORY}([^\n]*\\.${extension})"
717        "\\1${LATEX_SOURCE_DIRECTORY}\\2"
718        synctex_data
719        "${synctex_data}"
720        )
721    endforeach(extension)
722
723    message("Writing synctex file.")
724    file(WRITE ${synctex_file} "${synctex_data}")
725
726    message("Compressing synctex file.")
727    exec_program(${GZIP}
728      ARGS ${synctex_file}
729      )
730
731  else()
732
733    message(SEND_ERROR "File ${synctex_file_gz} not found.  Perhaps synctex is not supported by your LaTeX compiler.")
734
735  endif()
736
737endfunction(latex_correct_synctex)
738
739function(latex_check_important_warnings)
740  set(log_file ${LATEX_TARGET}.log)
741
742  message("\nChecking ${log_file} for important warnings.")
743  if(NOT LATEX_TARGET)
744    message(SEND_ERROR "Need to define LATEX_TARGET")
745  endif()
746
747  if(NOT EXISTS ${log_file})
748    message("Could not find log file: ${log_file}")
749    return()
750  endif()
751
752  set(found_error)
753
754  file(READ ${log_file} log)
755
756  # Check for undefined references
757  string(REGEX MATCHALL
758    "\n[^\n]*Reference[^\n]*undefined[^\n]*"
759    reference_warnings
760    "${log}")
761  if(reference_warnings)
762    set(found_error TRUE)
763    message("\nFound missing reference warnings.")
764    foreach(warning ${reference_warnings})
765      string(STRIP "${warning}" warning_no_newline)
766      message("${warning_no_newline}")
767    endforeach(warning)
768  endif()
769
770  # Check for natbib warnings
771  string(REGEX MATCHALL
772    "\nPackage natbib Warning:[^\n]*"
773    natbib_warnings
774    "${log}")
775  if(natbib_warnings)
776    set(found_error TRUE)
777    message("\nFound natbib package warnings.")
778    foreach(warning ${natbib_warnings})
779      string(STRIP "${warning}" warning_no_newline)
780      message("${warning_no_newline}")
781    endforeach(warning)
782  endif()
783
784  # Check for overfull
785  string(REGEX MATCHALL
786    "\nOverfull[^\n]*"
787    overfull_warnings
788    "${log}")
789  if(overfull_warnings)
790    set(found_error TRUE)
791    message("\nFound overfull warnings. These are indicative of layout errors.")
792    foreach(warning ${overfull_warnings})
793      string(STRIP "${warning}" warning_no_newline)
794      message("${warning_no_newline}")
795    endforeach(warning)
796  endif()
797
798  # Check for invalid characters
799  string(REGEX MATCHALL
800    "\nMissing character:[^\n]*"
801    invalid_character_warnings
802    "${log}")
803  if(invalid_character_warnings)
804    set(found_error TRUE)
805    message("\nFound invalid character warnings. These characters are likely not printed correctly.")
806    foreach(warning ${invalid_character_warnings})
807      string(STRIP "${warning}" warning_no_newline)
808      message("${warning_no_newline}")
809    endforeach(warning)
810  endif()
811
812  if(found_error)
813    latex_get_filename_component(log_file_path ${log_file} ABSOLUTE)
814    message("\nConsult ${log_file_path} for more information on LaTeX build.")
815  else()
816    message("No known important warnings found.")
817  endif(found_error)
818endfunction(latex_check_important_warnings)
819
820#############################################################################
821# Helper functions for establishing LaTeX build.
822#############################################################################
823
824function(latex_needit VAR NAME)
825  if(NOT ${VAR})
826    message(SEND_ERROR "I need the ${NAME} command.")
827  endif()
828endfunction(latex_needit)
829
830function(latex_wantit VAR NAME)
831  if(NOT ${VAR})
832    message(STATUS "I could not find the ${NAME} command.")
833  endif()
834endfunction(latex_wantit)
835
836function(latex_setup_variables)
837  set(LATEX_OUTPUT_PATH "${LATEX_OUTPUT_PATH}"
838    CACHE PATH "If non empty, specifies the location to place LaTeX output."
839    )
840
841  find_package(LATEX)
842
843  find_program(XINDY_COMPILER
844    NAME xindy
845    PATHS ${MIKTEX_BINARY_PATH} /usr/bin
846    )
847
848  find_package(UnixCommands)
849
850  find_program(PDFTOPS_CONVERTER
851    NAMES pdftops
852    DOC "The pdf to ps converter program from the Poppler package."
853    )
854
855  find_program(HTLATEX_COMPILER
856    NAMES htlatex
857    PATHS ${MIKTEX_BINARY_PATH}
858      /usr/bin
859    )
860
861  mark_as_advanced(
862    LATEX_COMPILER
863    PDFLATEX_COMPILER
864    BIBTEX_COMPILER
865    BIBER_COMPILER
866    MAKEINDEX_COMPILER
867    XINDY_COMPILER
868    DVIPS_CONVERTER
869    PS2PDF_CONVERTER
870    PDFTOPS_CONVERTER
871    LATEX2HTML_CONVERTER
872    HTLATEX_COMPILER
873    )
874
875  latex_needit(LATEX_COMPILER latex)
876  latex_wantit(PDFLATEX_COMPILER pdflatex)
877  latex_wantit(HTLATEX_COMPILER htlatex)
878  latex_needit(BIBTEX_COMPILER bibtex)
879  latex_wantit(BIBER_COMPILER biber)
880  latex_needit(MAKEINDEX_COMPILER makeindex)
881  latex_wantit(DVIPS_CONVERTER dvips)
882  latex_wantit(PS2PDF_CONVERTER ps2pdf)
883  latex_wantit(PDFTOPS_CONVERTER pdftops)
884
885  set(LATEX_COMPILER_FLAGS "-interaction=batchmode -file-line-error"
886    CACHE STRING "Flags passed to latex.")
887  set(PDFLATEX_COMPILER_FLAGS ${LATEX_COMPILER_FLAGS}
888    CACHE STRING "Flags passed to pdflatex.")
889  set(HTLATEX_COMPILER_TEX4HT_FLAGS "html"
890    CACHE STRING "Options for the tex4ht.sty and *.4ht style files.")
891  set(HTLATEX_COMPILER_TEX4HT_POSTPROCESSOR_FLAGS ""
892    CACHE STRING "Options for the text4ht postprocessor.")
893  set(HTLATEX_COMPILER_T4HT_POSTPROCESSOR_FLAGS ""
894    CACHE STRING "Options for the t4ht postprocessor.")
895  set(HTLATEX_COMPILER_LATEX_FLAGS ${LATEX_COMPILER_FLAGS}
896    CACHE STRING "Flags passed from htlatex to the LaTeX compiler.")
897  set(LATEX_SYNCTEX_FLAGS "-synctex=1"
898    CACHE STRING "latex/pdflatex flags used to create synctex file.")
899  set(BIBTEX_COMPILER_FLAGS ""
900    CACHE STRING "Flags passed to bibtex.")
901  set(BIBER_COMPILER_FLAGS ""
902    CACHE STRING "Flags passed to biber.")
903  set(MAKEINDEX_COMPILER_FLAGS ""
904    CACHE STRING "Flags passed to makeindex.")
905  set(MAKEGLOSSARIES_COMPILER_FLAGS ""
906    CACHE STRING "Flags passed to makeglossaries.")
907  set(MAKENOMENCLATURE_COMPILER_FLAGS ""
908    CACHE STRING "Flags passed to makenomenclature.")
909  set(DVIPS_CONVERTER_FLAGS "-Ppdf -G0 -t letter"
910    CACHE STRING "Flags passed to dvips.")
911  if(NOT WIN32)
912    set(PS2PDF_CONVERTER_FLAGS "-dMaxSubsetPct=100 -dCompatibilityLevel=1.3 -dSubsetFonts=true -dEmbedAllFonts=true -dAutoFilterColorImages=false -dAutoFilterGrayImages=false -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode -dMonoImageFilter=/FlateEncode"
913      CACHE STRING "Flags passed to ps2pdf.")
914  else()
915    # Most windows ports of ghostscript utilities use .bat files for ps2pdf
916    # commands. bat scripts interpret "=" as a special character and separate
917    # those arguments. To get around this, the ghostscript utilities also
918    # support using "#" in place of "=".
919    set(PS2PDF_CONVERTER_FLAGS "-dMaxSubsetPct#100 -dCompatibilityLevel#1.3 -dSubsetFonts#true -dEmbedAllFonts#true -dAutoFilterColorImages#false -dAutoFilterGrayImages#false -dColorImageFilter#/FlateEncode -dGrayImageFilter#/FlateEncode -dMonoImageFilter#/FlateEncode"
920      CACHE STRING "Flags passed to ps2pdf.")
921  endif()
922  set(PDFTOPS_CONVERTER_FLAGS ""
923    CACHE STRING "Flags passed to pdftops.")
924  mark_as_advanced(
925    LATEX_COMPILER_FLAGS
926    PDFLATEX_COMPILER_FLAGS
927    HTLATEX_COMPILER_TEX4HT_FLAGS
928    HTLATEX_COMPILER_TEX4HT_POSTPROCESSOR_FLAGS
929    HTLATEX_COMPILER_T4HT_POSTPROCESSOR_FLAGS
930    HTLATEX_COMPILER_LATEX_FLAGS
931    LATEX_SYNCTEX_FLAGS
932    BIBTEX_COMPILER_FLAGS
933    BIBER_COMPILER_FLAGS
934    MAKEINDEX_COMPILER_FLAGS
935    MAKEGLOSSARIES_COMPILER_FLAGS
936    MAKENOMENCLATURE_COMPILER_FLAGS
937    DVIPS_CONVERTER_FLAGS
938    PS2PDF_CONVERTER_FLAGS
939    PDFTOPS_CONVERTER_FLAGS
940    )
941
942  # Because it is easier to type, the flags variables are entered as
943  # space-separated strings much like you would in a shell. However, when
944  # using a CMake command to execute a program, it works better to hold the
945  # arguments in semicolon-separated lists (otherwise the whole string will
946  # be interpreted as a single argument). Use the separate_arguments to
947  # convert the space-separated strings to semicolon-separated lists.
948  separate_arguments(LATEX_COMPILER_FLAGS)
949  separate_arguments(PDFLATEX_COMPILER_FLAGS)
950  separate_arguments(HTLATEX_COMPILER_LATEX_FLAGS)
951  separate_arguments(LATEX_SYNCTEX_FLAGS)
952  separate_arguments(BIBTEX_COMPILER_FLAGS)
953  separate_arguments(BIBER_COMPILER_FLAGS)
954  separate_arguments(MAKEINDEX_COMPILER_FLAGS)
955  separate_arguments(MAKEGLOSSARIES_COMPILER_FLAGS)
956  separate_arguments(MAKENOMENCLATURE_COMPILER_FLAGS)
957  separate_arguments(DVIPS_CONVERTER_FLAGS)
958  separate_arguments(PS2PDF_CONVERTER_FLAGS)
959  separate_arguments(PDFTOPS_CONVERTER_FLAGS)
960
961  # Not quite done. When you call separate_arguments on a cache variable,
962  # the result is written to a local variable. That local variable goes
963  # away when this function returns (which is before any of them are used).
964  # So, copy these variables with local scope to cache variables with
965  # global scope.
966  set(LATEX_COMPILER_ARGS "${LATEX_COMPILER_FLAGS}" CACHE INTERNAL "")
967  set(PDFLATEX_COMPILER_ARGS "${PDFLATEX_COMPILER_FLAGS}" CACHE INTERNAL "")
968  set(HTLATEX_COMPILER_ARGS "${HTLATEX_COMPILER_LATEX_FLAGS}" CACHE INTERNAL "")
969  set(LATEX_SYNCTEX_ARGS "${LATEX_SYNCTEX_FLAGS}" CACHE INTERNAL "")
970  set(BIBTEX_COMPILER_ARGS "${BIBTEX_COMPILER_FLAGS}" CACHE INTERNAL "")
971  set(BIBER_COMPILER_ARGS "${BIBER_COMPILER_FLAGS}" CACHE INTERNAL "")
972  set(MAKEINDEX_COMPILER_ARGS "${MAKEINDEX_COMPILER_FLAGS}" CACHE INTERNAL "")
973  set(MAKEGLOSSARIES_COMPILER_ARGS "${MAKEGLOSSARIES_COMPILER_FLAGS}" CACHE INTERNAL "")
974  set(MAKENOMENCLATURE_COMPILER_ARGS "${MAKENOMENCLATURE_COMPILER_FLAGS}" CACHE INTERNAL "")
975  set(DVIPS_CONVERTER_ARGS "${DVIPS_CONVERTER_FLAGS}" CACHE INTERNAL "")
976  set(PS2PDF_CONVERTER_ARGS "${PS2PDF_CONVERTER_FLAGS}" CACHE INTERNAL "")
977  set(PDFTOPS_CONVERTER_ARGS "${PDFTOPS_CONVERTER_FLAGS}" CACHE INTERNAL "")
978
979  find_program(IMAGEMAGICK_CONVERT
980    NAMES magick convert
981    DOC "The convert program that comes with ImageMagick (available at http://www.imagemagick.org)."
982    )
983  mark_as_advanced(IMAGEMAGICK_CONVERT)
984
985  if(DEFINED ENV{LATEX_DEFAULT_BUILD})
986    set(default_build $ENV{LATEX_DEFAULT_BUILD})
987  else()
988    set(default_build pdf)
989  endif()
990
991  set(LATEX_DEFAULT_BUILD "${default_build}" CACHE STRING
992    "Choose the default type of LaTeX build. Valid options are pdf, dvi, ps, safepdf, html"
993    )
994  set_property(CACHE LATEX_DEFAULT_BUILD
995    PROPERTY STRINGS pdf dvi ps safepdf html
996    )
997
998  option(LATEX_USE_SYNCTEX
999    "If on, have LaTeX generate a synctex file, which WYSIWYG editors can use to correlate output files like dvi and pdf with the lines of LaTeX source that generates them.  In addition to adding the LATEX_SYNCTEX_FLAGS to the command line, this option also adds build commands that \"corrects\" the resulting synctex file to point to the original LaTeX files rather than those generated by UseLATEX.cmake."
1000    OFF
1001    )
1002
1003  option(LATEX_SMALL_IMAGES
1004    "If on, the raster images will be converted to 1/6 the original size.  This is because papers usually require 600 dpi images whereas most monitors only require at most 96 dpi.  Thus, smaller images make smaller files for web distribution and can make it faster to read dvi files."
1005    OFF)
1006  if(LATEX_SMALL_IMAGES)
1007    set(LATEX_RASTER_SCALE 16 PARENT_SCOPE)
1008    set(LATEX_OPPOSITE_RASTER_SCALE 100 PARENT_SCOPE)
1009  else()
1010    set(LATEX_RASTER_SCALE 100 PARENT_SCOPE)
1011    set(LATEX_OPPOSITE_RASTER_SCALE 16 PARENT_SCOPE)
1012  endif()
1013
1014  # Just holds extensions for known image types.  They should all be lower case.
1015  # For historical reasons, these are all declared in the global scope.
1016  set(LATEX_DVI_VECTOR_IMAGE_EXTENSIONS .eps CACHE INTERNAL "")
1017  set(LATEX_DVI_RASTER_IMAGE_EXTENSIONS CACHE INTERNAL "")
1018  set(LATEX_DVI_IMAGE_EXTENSIONS
1019    ${LATEX_DVI_VECTOR_IMAGE_EXTENSIONS}
1020    ${LATEX_DVI_RASTER_IMAGE_EXTENSIONS}
1021    CACHE INTERNAL ""
1022    )
1023
1024  set(LATEX_PDF_VECTOR_IMAGE_EXTENSIONS .pdf CACHE INTERNAL "")
1025  set(LATEX_PDF_RASTER_IMAGE_EXTENSIONS .jpeg .jpg .png CACHE INTERNAL "")
1026  set(LATEX_PDF_IMAGE_EXTENSIONS
1027    ${LATEX_PDF_VECTOR_IMAGE_EXTENSIONS}
1028    ${LATEX_PDF_RASTER_IMAGE_EXTENSIONS}
1029    CACHE INTERNAL ""
1030    )
1031
1032  set(LATEX_OTHER_VECTOR_IMAGE_EXTENSIONS .ai .dot .svg CACHE INTERNAL "")
1033  set(LATEX_OTHER_RASTER_IMAGE_EXTENSIONS
1034    .bmp .bmp2 .bmp3 .dcm .dcx .ico .gif .pict .ppm .tif .tiff
1035    CACHE INTERNAL "")
1036  set(LATEX_OTHER_IMAGE_EXTENSIONS
1037    ${LATEX_OTHER_VECTOR_IMAGE_EXTENSIONS}
1038    ${LATEX_OTHER_RASTER_IMAGE_EXTENSIONS}
1039    CACHE INTERNAL ""
1040    )
1041
1042  set(LATEX_VECTOR_IMAGE_EXTENSIONS
1043    ${LATEX_DVI_VECTOR_IMAGE_EXTENSIONS}
1044    ${LATEX_PDF_VECTOR_IMAGE_EXTENSIONS}
1045    ${LATEX_OTHER_VECTOR_IMAGE_EXTENSIONS}
1046    CACHE INTERNAL ""
1047    )
1048  set(LATEX_RASTER_IMAGE_EXTENSIONS
1049    ${LATEX_DVI_RASTER_IMAGE_EXTENSIONS}
1050    ${LATEX_PDF_RASTER_IMAGE_EXTENSIONS}
1051    ${LATEX_OTHER_RASTER_IMAGE_EXTENSIONS}
1052    CACHE INTERNAL ""
1053    )
1054  set(LATEX_IMAGE_EXTENSIONS
1055    ${LATEX_DVI_IMAGE_EXTENSIONS}
1056    ${LATEX_PDF_IMAGE_EXTENSIONS}
1057    ${LATEX_OTHER_IMAGE_EXTENSIONS}
1058    CACHE INTERNAL ""
1059    )
1060endfunction(latex_setup_variables)
1061
1062function(latex_setup_targets)
1063  if(NOT TARGET pdf)
1064    add_custom_target(pdf)
1065  endif()
1066  if(NOT TARGET dvi)
1067    add_custom_target(dvi)
1068  endif()
1069  if(NOT TARGET ps)
1070    add_custom_target(ps)
1071  endif()
1072  if(NOT TARGET safepdf)
1073    add_custom_target(safepdf)
1074  endif()
1075  if(NOT TARGET html)
1076    add_custom_target(html)
1077  endif()
1078  if(NOT TARGET auxclean)
1079    add_custom_target(auxclean)
1080  endif()
1081endfunction(latex_setup_targets)
1082
1083function(latex_get_output_path var)
1084  set(latex_output_path)
1085  if(LATEX_OUTPUT_PATH)
1086    get_filename_component(
1087      LATEX_OUTPUT_PATH_FULL "${LATEX_OUTPUT_PATH}" ABSOLUTE
1088      )
1089    if("${LATEX_OUTPUT_PATH_FULL}" STREQUAL "${CMAKE_CURRENT_SOURCE_DIR}")
1090      message(SEND_ERROR "You cannot set LATEX_OUTPUT_PATH to the same directory that contains LaTeX input files.")
1091    else()
1092      set(latex_output_path "${LATEX_OUTPUT_PATH_FULL}")
1093    endif()
1094  else()
1095    if("${CMAKE_CURRENT_BINARY_DIR}" STREQUAL "${CMAKE_CURRENT_SOURCE_DIR}")
1096      message(SEND_ERROR "LaTeX files must be built out of source or you must set LATEX_OUTPUT_PATH.")
1097    else()
1098      set(latex_output_path "${CMAKE_CURRENT_BINARY_DIR}")
1099    endif()
1100  endif()
1101  set(${var} ${latex_output_path} PARENT_SCOPE)
1102endfunction(latex_get_output_path)
1103
1104function(latex_add_convert_command
1105    output_path
1106    input_path
1107    output_extension
1108    input_extension
1109    flags
1110    )
1111  set(require_imagemagick_convert TRUE)
1112  set(convert_flags "")
1113  if(${input_extension} STREQUAL ".eps" AND ${output_extension} STREQUAL ".pdf")
1114    # ImageMagick has broken eps to pdf conversion
1115    # use ps2pdf instead
1116    if(PS2PDF_CONVERTER)
1117      set(require_imagemagick_convert FALSE)
1118      set(converter ${PS2PDF_CONVERTER})
1119      set(convert_flags -dEPSCrop ${PS2PDF_CONVERTER_ARGS})
1120    else()
1121      message(SEND_ERROR "Using postscript files with pdflatex requires ps2pdf for conversion.")
1122    endif()
1123  elseif(${input_extension} STREQUAL ".pdf" AND ${output_extension} STREQUAL ".eps")
1124    # ImageMagick can also be sketchy on pdf to eps conversion.  Not good with
1125    # color spaces and tends to unnecessarily rasterize.
1126    # use pdftops instead
1127    if(PDFTOPS_CONVERTER)
1128      set(require_imagemagick_convert FALSE)
1129      set(converter ${PDFTOPS_CONVERTER})
1130      set(convert_flags -eps ${PDFTOPS_CONVERTER_ARGS})
1131    else()
1132      message(STATUS "Consider getting pdftops from Poppler to convert PDF images to EPS images.")
1133      set(convert_flags ${flags})
1134    endif()
1135  else()
1136    set(convert_flags ${flags})
1137  endif()
1138
1139  if(require_imagemagick_convert)
1140    if(IMAGEMAGICK_CONVERT)
1141      string(TOLOWER ${IMAGEMAGICK_CONVERT} IMAGEMAGICK_CONVERT_LOWERCASE)
1142      if(${IMAGEMAGICK_CONVERT_LOWERCASE} MATCHES "system32[/\\\\]convert\\.exe")
1143        message(SEND_ERROR "IMAGEMAGICK_CONVERT set to Window's convert.exe for changing file systems rather than ImageMagick's convert for changing image formats. Please make sure ImageMagick is installed (available at http://www.imagemagick.org). If you have a recent version of ImageMagick (7.0 or higher), use the magick program instead of convert for IMAGEMAGICK_CONVERT.")
1144      else()
1145        set(converter ${IMAGEMAGICK_CONVERT})
1146        # ImageMagick requires a special order of arguments where resize and
1147        # arguments of that nature must be placed after the input image path.
1148        add_custom_command(OUTPUT ${output_path}
1149          COMMAND ${converter}
1150            ARGS ${input_path} ${convert_flags} ${output_path}
1151          DEPENDS ${input_path}
1152          )
1153      endif()
1154    else()
1155      message(SEND_ERROR "Could not find convert program. Please download ImageMagick from http://www.imagemagick.org and install.")
1156    endif()
1157  else() # Not ImageMagick convert
1158    add_custom_command(OUTPUT ${output_path}
1159      COMMAND ${converter}
1160        ARGS ${convert_flags} ${input_path} ${output_path}
1161      DEPENDS ${input_path}
1162      )
1163  endif()
1164endfunction(latex_add_convert_command)
1165
1166# Makes custom commands to convert a file to a particular type.
1167function(latex_convert_image
1168    output_files_var
1169    input_file
1170    output_extension
1171    convert_flags
1172    output_extensions
1173    other_files
1174    )
1175  set(output_file_list)
1176  set(input_dir ${CMAKE_CURRENT_SOURCE_DIR})
1177  latex_get_output_path(output_dir)
1178
1179  latex_get_filename_component(extension "${input_file}" EXT)
1180
1181  # Check input filename for potential problems with LaTeX.
1182  latex_get_filename_component(name "${input_file}" NAME_WE)
1183  set(suggested_name "${name}")
1184  if(suggested_name MATCHES ".*\\..*")
1185    string(REPLACE "." "-" suggested_name "${suggested_name}")
1186  endif()
1187  if(suggested_name MATCHES ".* .*")
1188    string(REPLACE " " "-" suggested_name "${suggested_name}")
1189  endif()
1190  if(NOT suggested_name STREQUAL name)
1191    message(WARNING "Some LaTeX distributions have problems with image file names with multiple extensions or spaces. Consider changing ${name}${extension} to something like ${suggested_name}${extension}.")
1192  endif()
1193
1194  string(REGEX REPLACE "\\.[^.]*\$" ${output_extension} output_file
1195    "${input_file}")
1196
1197  latex_list_contains(is_type ${extension} ${output_extensions})
1198  if(is_type)
1199    if(convert_flags)
1200      latex_add_convert_command(${output_dir}/${output_file}
1201        ${input_dir}/${input_file} ${output_extension} ${extension}
1202        "${convert_flags}")
1203      set(output_file_list ${output_dir}/${output_file})
1204    else()
1205      # As a shortcut, we can just copy the file.
1206      add_custom_command(OUTPUT ${output_dir}/${input_file}
1207        COMMAND ${CMAKE_COMMAND}
1208        ARGS -E copy ${input_dir}/${input_file} ${output_dir}/${input_file}
1209        DEPENDS ${input_dir}/${input_file}
1210        )
1211      set(output_file_list ${output_dir}/${input_file})
1212    endif()
1213  else()
1214    set(do_convert TRUE)
1215    # Check to see if there is another input file of the appropriate type.
1216    foreach(valid_extension ${output_extensions})
1217      string(REGEX REPLACE "\\.[^.]*\$" ${output_extension} try_file
1218        "${input_file}")
1219      latex_list_contains(has_native_file "${try_file}" ${other_files})
1220      if(has_native_file)
1221        set(do_convert FALSE)
1222      endif()
1223    endforeach(valid_extension)
1224
1225    # If we still need to convert, do it.
1226    if(do_convert)
1227      latex_add_convert_command(${output_dir}/${output_file}
1228        ${input_dir}/${input_file} ${output_extension} ${extension}
1229        "${convert_flags}")
1230      set(output_file_list ${output_dir}/${output_file})
1231    endif()
1232  endif()
1233
1234  set(${output_files_var} ${output_file_list} PARENT_SCOPE)
1235endfunction(latex_convert_image)
1236
1237# Adds custom commands to process the given files for dvi and pdf builds.
1238# Adds the output files to the given variables (does not replace).
1239function(latex_process_images dvi_outputs_var pdf_outputs_var)
1240  latex_get_output_path(output_dir)
1241  set(dvi_outputs)
1242  set(pdf_outputs)
1243  foreach(file ${ARGN})
1244    if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${file}")
1245      latex_get_filename_component(extension "${file}" EXT)
1246      set(convert_flags)
1247
1248      # Check to see if we need to downsample the image.
1249      latex_list_contains(is_raster "${extension}"
1250        ${LATEX_RASTER_IMAGE_EXTENSIONS})
1251      if(LATEX_SMALL_IMAGES)
1252        if(is_raster)
1253          set(convert_flags -resize ${LATEX_RASTER_SCALE}%)
1254        endif()
1255      endif()
1256
1257      # Make sure the output directory exists.
1258      latex_get_filename_component(path "${output_dir}/${file}" PATH)
1259      make_directory("${path}")
1260
1261      # Do conversions for dvi.
1262      latex_convert_image(output_files "${file}" .eps "${convert_flags}"
1263        "${LATEX_DVI_IMAGE_EXTENSIONS}" "${ARGN}")
1264      list(APPEND dvi_outputs ${output_files})
1265
1266      # Do conversions for pdf.
1267      if(is_raster)
1268        latex_convert_image(output_files "${file}" .png "${convert_flags}"
1269          "${LATEX_PDF_IMAGE_EXTENSIONS}" "${ARGN}")
1270        list(APPEND pdf_outputs ${output_files})
1271      else()
1272        latex_convert_image(output_files "${file}" .pdf "${convert_flags}"
1273          "${LATEX_PDF_IMAGE_EXTENSIONS}" "${ARGN}")
1274        list(APPEND pdf_outputs ${output_files})
1275      endif()
1276    else()
1277      message(WARNING "Could not find file ${CMAKE_CURRENT_SOURCE_DIR}/${file}.  Are you sure you gave relative paths to IMAGES?")
1278    endif()
1279  endforeach(file)
1280
1281  set(${dvi_outputs_var} ${dvi_outputs} PARENT_SCOPE)
1282  set(${pdf_outputs_var} ${pdf_outputs} PARENT_SCOPE)
1283endfunction(latex_process_images)
1284
1285function(latex_copy_globbed_files pattern dest)
1286  file(GLOB file_list ${pattern})
1287  foreach(in_file ${file_list})
1288    latex_get_filename_component(out_file ${in_file} NAME)
1289    configure_file(${in_file} ${dest}/${out_file} COPYONLY)
1290  endforeach(in_file)
1291endfunction(latex_copy_globbed_files)
1292
1293function(latex_copy_input_file file)
1294  latex_get_output_path(output_dir)
1295
1296  if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${file})
1297    latex_get_filename_component(path ${file} PATH)
1298    file(MAKE_DIRECTORY ${output_dir}/${path})
1299
1300    latex_list_contains(use_config ${file} ${LATEX_CONFIGURE})
1301    if(use_config)
1302      configure_file(${CMAKE_CURRENT_SOURCE_DIR}/${file}
1303        ${output_dir}/${file}
1304        @ONLY
1305        )
1306      add_custom_command(OUTPUT ${output_dir}/${file}
1307        COMMAND ${CMAKE_COMMAND}
1308        ARGS ${CMAKE_BINARY_DIR}
1309        DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${file}
1310        )
1311    else()
1312      add_custom_command(OUTPUT ${output_dir}/${file}
1313        COMMAND ${CMAKE_COMMAND}
1314        ARGS -E copy ${CMAKE_CURRENT_SOURCE_DIR}/${file} ${output_dir}/${file}
1315        DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${file}
1316        )
1317    endif()
1318  else()
1319    if(EXISTS ${output_dir}/${file})
1320      # Special case: output exists but input does not.  Assume that it was
1321      # created elsewhere and skip the input file copy.
1322    else()
1323      message("Could not find input file ${CMAKE_CURRENT_SOURCE_DIR}/${file}")
1324    endif()
1325  endif()
1326endfunction(latex_copy_input_file)
1327
1328#############################################################################
1329# Commands provided by the UseLATEX.cmake "package"
1330#############################################################################
1331
1332function(latex_usage command message)
1333  message(SEND_ERROR
1334      "${message}\n  Usage: ${command}(<tex_file>\n           [BIBFILES <bib_file> <bib_file> ...]\n           [INPUTS <tex_file> <tex_file> ...]\n           [IMAGE_DIRS <directory1> <directory2> ...]\n           [IMAGES <image_file1> <image_file2>\n           [CONFIGURE <tex_file> <tex_file> ...]\n           [DEPENDS <tex_file> <tex_file> ...]\n           [MULTIBIB_NEWCITES] <suffix_list>\n           [USE_BIBLATEX] [USE_INDEX] [USE_GLOSSARY] [USE_NOMENCL]\n           [FORCE_PDF] [FORCE_DVI] [FORCE_HTML]\n           [TARGET_NAME] <name>\n           [EXCLUDE_FROM_ALL]\n           [EXCLUDE_FROM_DEFAULTS])"
1335    )
1336endfunction(latex_usage command message)
1337
1338# Parses arguments to add_latex_document and ADD_LATEX_TARGETS and sets the
1339# variables LATEX_TARGET, LATEX_IMAGE_DIR, LATEX_BIBFILES, LATEX_DEPENDS, and
1340# LATEX_INPUTS.
1341function(parse_add_latex_arguments command latex_main_input)
1342  set(options
1343    USE_BIBLATEX
1344    USE_INDEX
1345    USE_GLOSSARY
1346    USE_NOMENCL
1347    FORCE_PDF
1348    FORCE_DVI
1349    FORCE_HTML
1350    EXCLUDE_FROM_ALL
1351    EXCLUDE_FROM_DEFAULTS
1352    # Deprecated options
1353    USE_GLOSSARIES
1354    DEFAULT_PDF
1355    DEFAULT_SAFEPDF
1356    DEFAULT_PS
1357    NO_DEFAULT
1358    MANGLE_TARGET_NAMES
1359    )
1360  set(oneValueArgs
1361    TARGET_NAME
1362    )
1363  set(multiValueArgs
1364    BIBFILES
1365    MULTIBIB_NEWCITES
1366    INPUTS
1367    IMAGE_DIRS
1368    IMAGES
1369    CONFIGURE
1370    DEPENDS
1371    INDEX_NAMES
1372    )
1373  cmake_parse_arguments(
1374    LATEX "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
1375
1376  # Handle invalid and deprecated arguments
1377  if(LATEX_UNPARSED_ARGUMENTS)
1378    latex_usage(${command} "Invalid or deprecated arguments: ${LATEX_UNPARSED_ARGUMENTS}")
1379  endif()
1380  if(LATEX_USE_GLOSSARIES)
1381    latex_usage(${command} "USE_GLOSSARIES option removed in version 1.6.1. Use USE_GLOSSARY instead.")
1382  endif()
1383  if(LATEX_DEFAULT_PDF)
1384    latex_usage(${command} "DEFAULT_PDF option removed in version 2.0. Use FORCE_PDF option or LATEX_DEFAULT_BUILD CMake variable instead.")
1385  endif()
1386  if(LATEX_DEFAULT_SAFEPDF)
1387    latex_usage(${command} "DEFAULT_SAFEPDF option removed in version 2.0. Use LATEX_DEFAULT_BUILD CMake variable instead.")
1388  endif()
1389  if(LATEX_DEFAULT_DVI)
1390    latex_usage(${command} "DEFAULT_DVI option removed in version 2.0. Use FORCE_DVI option or LATEX_DEFAULT_BUILD CMake variable instead.")
1391  endif()
1392  if(LATEX_NO_DEFAULT)
1393    latex_usage(${command} "NO_DEFAULT option removed in version 2.0. Use EXCLUDE_FROM_ALL instead.")
1394  endif()
1395  if(LATEX_MANGLE_TARGET_NAMES)
1396    latex_usage(${command} "MANGLE_TARGET_NAMES option removed in version 2.0. All LaTeX targets use mangled names now.")
1397  endif()
1398
1399  # Capture the first argument, which is the main LaTeX input.
1400  latex_get_filename_component(latex_target ${latex_main_input} NAME_WE)
1401  set(LATEX_MAIN_INPUT ${latex_main_input} PARENT_SCOPE)
1402  set(LATEX_TARGET ${latex_target} PARENT_SCOPE)
1403
1404  # Propagate the result variables to the caller
1405  foreach(arg_name ${options} ${oneValueArgs} ${multiValueArgs})
1406    set(var_name LATEX_${arg_name})
1407    set(${var_name} ${${var_name}} PARENT_SCOPE)
1408  endforeach(arg_name)
1409endfunction(parse_add_latex_arguments)
1410
1411function(add_latex_targets_internal)
1412  latex_get_output_path(output_dir)
1413
1414  if(LATEX_USE_SYNCTEX)
1415    set(synctex_flags ${LATEX_SYNCTEX_ARGS})
1416  else()
1417    set(synctex_flags)
1418  endif()
1419
1420  # The commands to run LaTeX.  They are repeated multiple times.
1421  set(latex_build_command
1422    ${LATEX_COMPILER} ${LATEX_COMPILER_ARGS} ${synctex_flags} ${LATEX_MAIN_INPUT}
1423    )
1424  if(LATEX_COMPILER_ARGS MATCHES ".*batchmode.*")
1425    # Wrap command in script that dumps the log file on error. This makes sure
1426    # errors can be seen.
1427    set(latex_build_command
1428      ${CMAKE_COMMAND}
1429        -D LATEX_BUILD_COMMAND=execute_latex
1430        -D LATEX_TARGET=${LATEX_TARGET}
1431        -D LATEX_WORKING_DIRECTORY="${output_dir}"
1432        -D LATEX_FULL_COMMAND="${latex_build_command}"
1433        -D LATEX_OUTPUT_FILE="${LATEX_TARGET}.dvi"
1434        -P "${LATEX_USE_LATEX_LOCATION}"
1435      )
1436  endif()
1437  set(pdflatex_build_command
1438    ${PDFLATEX_COMPILER} ${PDFLATEX_COMPILER_ARGS} ${synctex_flags} ${LATEX_MAIN_INPUT}
1439    )
1440  if(PDFLATEX_COMPILER_ARGS MATCHES ".*batchmode.*")
1441    # Wrap command in script that dumps the log file on error. This makes sure
1442    # errors can be seen.
1443    set(pdflatex_build_command
1444      ${CMAKE_COMMAND}
1445        -D LATEX_BUILD_COMMAND=execute_latex
1446        -D LATEX_TARGET=${LATEX_TARGET}
1447        -D LATEX_WORKING_DIRECTORY="${output_dir}"
1448        -D LATEX_FULL_COMMAND="${pdflatex_build_command}"
1449        -D LATEX_OUTPUT_FILE="${LATEX_TARGET}.pdf"
1450        -P "${LATEX_USE_LATEX_LOCATION}"
1451      )
1452  endif()
1453
1454  if(NOT LATEX_TARGET_NAME)
1455    # Use the main filename (minus the .tex) as the target name. Remove any
1456    # spaces since CMake cannot have spaces in its target names.
1457    string(REPLACE " " "_" LATEX_TARGET_NAME ${LATEX_TARGET})
1458  endif()
1459
1460  # Some LaTeX commands may need to be modified (or may not work) if the main
1461  # tex file is in a subdirectory. Make a flag for that.
1462  get_filename_component(LATEX_MAIN_INPUT_SUBDIR ${LATEX_MAIN_INPUT} DIRECTORY)
1463
1464  # Set up target names.
1465  set(dvi_target      ${LATEX_TARGET_NAME}_dvi)
1466  set(pdf_target      ${LATEX_TARGET_NAME}_pdf)
1467  set(ps_target       ${LATEX_TARGET_NAME}_ps)
1468  set(safepdf_target  ${LATEX_TARGET_NAME}_safepdf)
1469  set(html_target     ${LATEX_TARGET_NAME}_html)
1470  set(auxclean_target ${LATEX_TARGET_NAME}_auxclean)
1471
1472  # Probably not all of these will be generated, but they could be.
1473  # Note that the aux file is added later.
1474  set(auxiliary_clean_files
1475    ${output_dir}/${LATEX_TARGET}.aux
1476    ${output_dir}/${LATEX_TARGET}.bbl
1477    ${output_dir}/${LATEX_TARGET}.blg
1478    ${output_dir}/${LATEX_TARGET}-blx.bib
1479    ${output_dir}/${LATEX_TARGET}.glg
1480    ${output_dir}/${LATEX_TARGET}.glo
1481    ${output_dir}/${LATEX_TARGET}.gls
1482    ${output_dir}/${LATEX_TARGET}.idx
1483    ${output_dir}/${LATEX_TARGET}.ilg
1484    ${output_dir}/${LATEX_TARGET}.ind
1485    ${output_dir}/${LATEX_TARGET}.ist
1486    ${output_dir}/${LATEX_TARGET}.log
1487    ${output_dir}/${LATEX_TARGET}.out
1488    ${output_dir}/${LATEX_TARGET}.toc
1489    ${output_dir}/${LATEX_TARGET}.lof
1490    ${output_dir}/${LATEX_TARGET}.xdy
1491    ${output_dir}/${LATEX_TARGET}.synctex.gz
1492    ${output_dir}/${LATEX_TARGET}.synctex.bak.gz
1493    ${output_dir}/${LATEX_TARGET}.dvi
1494    ${output_dir}/${LATEX_TARGET}.ps
1495    ${output_dir}/${LATEX_TARGET}.pdf
1496    )
1497
1498  set(image_list ${LATEX_IMAGES})
1499
1500  # For each directory in LATEX_IMAGE_DIRS, glob all the image files and
1501  # place them in LATEX_IMAGES.
1502  foreach(dir ${LATEX_IMAGE_DIRS})
1503    if(NOT EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${dir})
1504      message(WARNING "Image directory ${CMAKE_CURRENT_SOURCE_DIR}/${dir} does not exist.  Are you sure you gave relative directories to IMAGE_DIRS?")
1505    endif()
1506    foreach(extension ${LATEX_IMAGE_EXTENSIONS})
1507      file(GLOB files ${CMAKE_CURRENT_SOURCE_DIR}/${dir}/*${extension})
1508      foreach(file ${files})
1509        latex_get_filename_component(filename ${file} NAME)
1510        list(APPEND image_list ${dir}/${filename})
1511      endforeach(file)
1512    endforeach(extension)
1513  endforeach(dir)
1514
1515  latex_process_images(dvi_images pdf_images ${image_list})
1516
1517  set(make_dvi_command
1518    ${CMAKE_COMMAND} -E chdir ${output_dir}
1519    ${latex_build_command})
1520  set(make_pdf_command
1521    ${CMAKE_COMMAND} -E chdir ${output_dir}
1522    ${pdflatex_build_command}
1523    )
1524
1525  set(make_dvi_depends ${LATEX_DEPENDS} ${dvi_images})
1526  set(make_pdf_depends ${LATEX_DEPENDS} ${pdf_images})
1527  foreach(input ${LATEX_MAIN_INPUT} ${LATEX_INPUTS})
1528    list(APPEND make_dvi_depends ${output_dir}/${input})
1529    list(APPEND make_pdf_depends ${output_dir}/${input})
1530    if(${input} MATCHES "\\.tex$")
1531      # Dependent .tex files might have their own .aux files created.  Make
1532      # sure these get cleaned as well.  This might replicate the cleaning
1533      # of the main .aux file, which is OK.
1534      string(REGEX REPLACE "\\.tex$" "" input_we ${input})
1535      list(APPEND auxiliary_clean_files
1536        ${output_dir}/${input_we}.aux
1537        ${output_dir}/${input}.aux
1538        )
1539    endif()
1540  endforeach(input)
1541
1542  set(all_latex_sources ${LATEX_MAIN_INPUT} ${LATEX_INPUTS} ${image_list})
1543
1544  if(LATEX_USE_GLOSSARY)
1545    foreach(dummy 0 1)   # Repeat these commands twice.
1546      set(make_dvi_command ${make_dvi_command}
1547        COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir}
1548        ${CMAKE_COMMAND}
1549        -D LATEX_BUILD_COMMAND=makeglossaries
1550        -D LATEX_TARGET=${LATEX_TARGET}
1551        -D MAKEINDEX_COMPILER=${MAKEINDEX_COMPILER}
1552        -D XINDY_COMPILER=${XINDY_COMPILER}
1553        -D MAKEGLOSSARIES_COMPILER_ARGS=${MAKEGLOSSARIES_COMPILER_ARGS}
1554        -P ${LATEX_USE_LATEX_LOCATION}
1555        COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir}
1556        ${latex_build_command}
1557        )
1558      set(make_pdf_command ${make_pdf_command}
1559        COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir}
1560        ${CMAKE_COMMAND}
1561        -D LATEX_BUILD_COMMAND=makeglossaries
1562        -D LATEX_TARGET=${LATEX_TARGET}
1563        -D MAKEINDEX_COMPILER=${MAKEINDEX_COMPILER}
1564        -D XINDY_COMPILER=${XINDY_COMPILER}
1565        -D MAKEGLOSSARIES_COMPILER_ARGS=${MAKEGLOSSARIES_COMPILER_ARGS}
1566        -P ${LATEX_USE_LATEX_LOCATION}
1567        COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir}
1568        ${pdflatex_build_command}
1569        )
1570    endforeach(dummy)
1571  endif()
1572
1573  if(LATEX_USE_NOMENCL)
1574    foreach(dummy 0 1)   # Repeat these commands twice.
1575      set(make_dvi_command ${make_dvi_command}
1576        COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir}
1577        ${CMAKE_COMMAND}
1578        -D LATEX_BUILD_COMMAND=makenomenclature
1579        -D LATEX_TARGET=${LATEX_TARGET}
1580        -D MAKEINDEX_COMPILER=${MAKEINDEX_COMPILER}
1581        -D MAKENOMENCLATURE_COMPILER_ARGS=${MAKENOMENCLATURE_COMPILER_ARGS}
1582        -P ${LATEX_USE_LATEX_LOCATION}
1583        COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir}
1584        ${latex_build_command}
1585        )
1586      set(make_pdf_command ${make_pdf_command}
1587        COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir}
1588        ${CMAKE_COMMAND}
1589        -D LATEX_BUILD_COMMAND=makenomenclature
1590        -D LATEX_TARGET=${LATEX_TARGET}
1591        -D MAKEINDEX_COMPILER=${MAKEINDEX_COMPILER}
1592        -D MAKENOMENCLATURE_COMPILER_ARGS=${MAKENOMENCLATURE_COMPILER_ARGS}
1593        -P ${LATEX_USE_LATEX_LOCATION}
1594        COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir}
1595        ${pdflatex_build_command}
1596        )
1597    endforeach(dummy)
1598  endif()
1599
1600  if(LATEX_BIBFILES)
1601    if(LATEX_USE_BIBLATEX)
1602      if(NOT BIBER_COMPILER)
1603        message(SEND_ERROR "I need the biber command.")
1604      endif()
1605      set(bib_compiler ${BIBER_COMPILER})
1606      set(bib_compiler_flags ${BIBER_COMPILER_ARGS})
1607    else()
1608      set(bib_compiler ${BIBTEX_COMPILER})
1609      set(bib_compiler_flags ${BIBTEX_COMPILER_ARGS})
1610    endif()
1611    if(LATEX_MULTIBIB_NEWCITES)
1612      foreach (multibib_auxfile ${LATEX_MULTIBIB_NEWCITES})
1613        latex_get_filename_component(multibib_target ${multibib_auxfile} NAME_WE)
1614        set(make_dvi_command ${make_dvi_command}
1615          COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir}
1616          ${bib_compiler} ${bib_compiler_flags} ${multibib_target})
1617        set(make_pdf_command ${make_pdf_command}
1618          COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir}
1619          ${bib_compiler} ${bib_compiler_flags} ${multibib_target})
1620        set(auxiliary_clean_files ${auxiliary_clean_files}
1621          ${output_dir}/${multibib_target}.aux)
1622      endforeach (multibib_auxfile ${LATEX_MULTIBIB_NEWCITES})
1623    else()
1624      set(make_dvi_command ${make_dvi_command}
1625        COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir}
1626        ${bib_compiler} ${bib_compiler_flags} ${LATEX_TARGET})
1627      set(make_pdf_command ${make_pdf_command}
1628        COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir}
1629        ${bib_compiler} ${bib_compiler_flags} ${LATEX_TARGET})
1630    endif()
1631
1632    foreach (bibfile ${LATEX_BIBFILES})
1633      list(APPEND make_dvi_depends ${output_dir}/${bibfile})
1634      list(APPEND make_pdf_depends ${output_dir}/${bibfile})
1635    endforeach (bibfile ${LATEX_BIBFILES})
1636  else()
1637    if(LATEX_MULTIBIB_NEWCITES)
1638      message(WARNING "MULTIBIB_NEWCITES has no effect without BIBFILES option.")
1639    endif()
1640  endif()
1641
1642  if(LATEX_USE_INDEX)
1643    if(LATEX_INDEX_NAMES)
1644      set(INDEX_NAMES ${LATEX_INDEX_NAMES})
1645    else()
1646      set(INDEX_NAMES ${LATEX_TARGET})
1647    endif()
1648    foreach(idx_name ${INDEX_NAMES})
1649      set(make_dvi_command ${make_dvi_command}
1650        COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir}
1651        ${latex_build_command}
1652        COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir}
1653        ${MAKEINDEX_COMPILER} ${MAKEINDEX_COMPILER_ARGS} ${idx_name}.idx)
1654      set(make_pdf_command ${make_pdf_command}
1655        COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir}
1656        ${pdflatex_build_command}
1657        COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir}
1658        ${MAKEINDEX_COMPILER} ${MAKEINDEX_COMPILER_ARGS} ${idx_name}.idx)
1659      set(auxiliary_clean_files ${auxiliary_clean_files}
1660        ${output_dir}/${idx_name}.idx
1661        ${output_dir}/${idx_name}.ilg
1662        ${output_dir}/${idx_name}.ind)
1663    endforeach()
1664  else()
1665    if(LATEX_INDEX_NAMES)
1666      message(WARNING "INDEX_NAMES has no effect without USE_INDEX option.")
1667    endif()
1668  endif()
1669
1670  set(make_dvi_command ${make_dvi_command}
1671    COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir}
1672    ${latex_build_command}
1673    COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir}
1674    ${latex_build_command})
1675  set(make_pdf_command ${make_pdf_command}
1676    COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir}
1677    ${pdflatex_build_command}
1678    COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir}
1679    ${pdflatex_build_command})
1680
1681  # Need to run one more time to remove biblatex' warning
1682  # about page breaks that have changed.
1683  if(LATEX_USE_BIBLATEX)
1684    set(make_dvi_command ${make_dvi_command}
1685      COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir}
1686      ${latex_build_command})
1687    set(make_pdf_command ${make_pdf_command}
1688      COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir}
1689      ${pdflatex_build_command})
1690  endif()
1691
1692  if(LATEX_USE_SYNCTEX)
1693    if(NOT GZIP)
1694      message(SEND_ERROR "UseLATEX.cmake: USE_SYNTEX option requires gzip program.  Set GZIP variable.")
1695    endif()
1696    set(make_dvi_command ${make_dvi_command}
1697      COMMAND ${CMAKE_COMMAND}
1698      -D LATEX_BUILD_COMMAND=correct_synctex
1699      -D LATEX_TARGET=${LATEX_TARGET}
1700      -D GZIP=${GZIP}
1701      -D "LATEX_SOURCE_DIRECTORY=${CMAKE_CURRENT_SOURCE_DIR}"
1702      -D "LATEX_BINARY_DIRECTORY=${output_dir}"
1703      -P ${LATEX_USE_LATEX_LOCATION}
1704      )
1705    set(make_pdf_command ${make_pdf_command}
1706      COMMAND ${CMAKE_COMMAND}
1707      -D LATEX_BUILD_COMMAND=correct_synctex
1708      -D LATEX_TARGET=${LATEX_TARGET}
1709      -D GZIP=${GZIP}
1710      -D "LATEX_SOURCE_DIRECTORY=${CMAKE_CURRENT_SOURCE_DIR}"
1711      -D "LATEX_BINARY_DIRECTORY=${output_dir}"
1712      -P ${LATEX_USE_LATEX_LOCATION}
1713      )
1714  endif()
1715
1716  # Check LaTeX output for important warnings at end of build
1717  set(make_dvi_command ${make_dvi_command}
1718    COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir}
1719    ${CMAKE_COMMAND}
1720      -D LATEX_BUILD_COMMAND=check_important_warnings
1721      -D LATEX_TARGET=${LATEX_TARGET}
1722      -P ${LATEX_USE_LATEX_LOCATION}
1723    )
1724  set(make_pdf_command ${make_pdf_command}
1725    COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir}
1726    ${CMAKE_COMMAND}
1727      -D LATEX_BUILD_COMMAND=check_important_warnings
1728      -D LATEX_TARGET=${LATEX_TARGET}
1729      -P ${LATEX_USE_LATEX_LOCATION}
1730    )
1731
1732  # Capture the default build.
1733  string(TOLOWER "${LATEX_DEFAULT_BUILD}" default_build)
1734
1735  if((NOT LATEX_FORCE_PDF) AND (NOT LATEX_FORCE_DVI) AND (NOT LATEX_FORCE_HTML))
1736    set(no_force TRUE)
1737  endif()
1738
1739  # Add commands and targets for building pdf outputs (with pdflatex).
1740  if(LATEX_FORCE_PDF OR no_force)
1741    if(LATEX_FORCE_PDF)
1742      set(default_build pdf)
1743    endif()
1744
1745    if(PDFLATEX_COMPILER)
1746      add_custom_command(OUTPUT ${output_dir}/${LATEX_TARGET}.pdf
1747        COMMAND ${make_pdf_command}
1748        DEPENDS ${make_pdf_depends}
1749        )
1750      add_custom_target(${pdf_target}
1751        DEPENDS ${output_dir}/${LATEX_TARGET}.pdf
1752        SOURCES ${all_latex_sources}
1753        )
1754      if(NOT LATEX_EXCLUDE_FROM_DEFAULTS)
1755        add_dependencies(pdf ${pdf_target})
1756      endif()
1757    endif()
1758  endif()
1759
1760  # Add commands and targets for building dvi outputs.
1761  if(LATEX_FORCE_DVI OR LATEX_FORCE_HTML OR no_force)
1762    if(LATEX_FORCE_DVI)
1763      if((NOT default_build STREQUAL dvi) AND
1764          (NOT default_build STREQUAL ps) AND
1765          (NOT default_build STREQUAL safepdf))
1766        set(default_build dvi)
1767      endif()
1768    endif()
1769
1770    add_custom_command(OUTPUT ${output_dir}/${LATEX_TARGET}.dvi
1771      COMMAND ${make_dvi_command}
1772      DEPENDS ${make_dvi_depends}
1773      )
1774    add_custom_target(${dvi_target}
1775      DEPENDS ${output_dir}/${LATEX_TARGET}.dvi
1776      SOURCES ${all_latex_sources}
1777      )
1778    if(NOT LATEX_EXCLUDE_FROM_DEFAULTS)
1779      add_dependencies(dvi ${dvi_target})
1780    endif()
1781
1782    if(DVIPS_CONVERTER)
1783      add_custom_command(OUTPUT ${output_dir}/${LATEX_TARGET}.ps
1784        COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir}
1785        ${DVIPS_CONVERTER} ${DVIPS_CONVERTER_ARGS} -o ${LATEX_TARGET}.ps ${LATEX_TARGET}.dvi
1786        DEPENDS ${output_dir}/${LATEX_TARGET}.dvi)
1787      add_custom_target(${ps_target}
1788        DEPENDS ${output_dir}/${LATEX_TARGET}.ps
1789        SOURCES ${all_latex_sources}
1790        )
1791      if(NOT LATEX_EXCLUDE_FROM_DEFAULTS)
1792        add_dependencies(ps ${ps_target})
1793      endif()
1794      if(PS2PDF_CONVERTER)
1795        # Since both the pdf and safepdf targets have the same output, we
1796        # cannot properly do the dependencies for both.  When selecting safepdf,
1797        # simply force a recompile every time.
1798        add_custom_target(${safepdf_target}
1799          ${CMAKE_COMMAND} -E chdir ${output_dir}
1800          ${PS2PDF_CONVERTER} ${PS2PDF_CONVERTER_ARGS} ${LATEX_TARGET}.ps ${LATEX_TARGET}.pdf
1801          DEPENDS ${ps_target}
1802          )
1803        if(NOT LATEX_EXCLUDE_FROM_DEFAULTS)
1804          add_dependencies(safepdf ${safepdf_target})
1805        endif()
1806      endif()
1807    endif()
1808  endif()
1809
1810  if(LATEX_FORCE_HTML OR no_force)
1811    if (LATEX_FORCE_HTML)
1812      set(default_build html)
1813    endif()
1814
1815    if(HTLATEX_COMPILER AND LATEX_MAIN_INPUT_SUBDIR)
1816      message(STATUS
1817        "Disabling HTML build for ${LATEX_TARGET_NAME}.tex because the main file is in subdirectory ${LATEX_MAIN_INPUT_SUBDIR}"
1818        )
1819      # The code below to run HTML assumes that LATEX_TARGET.tex is in the
1820      # current directory. I have tried to specify that LATEX_TARGET.tex is
1821      # in a subdirectory. That makes the build targets correct, but the
1822      # HTML build still fails (at least for htlatex) because files are not
1823      # generated where expected. I am getting around the problem by simply
1824      # disabling HTML in this case. If someone really cares, they can fix
1825      # this, but make sure it runs on many platforms and build programs.
1826    elseif(HTLATEX_COMPILER)
1827      # htlatex places the output in a different location
1828      set(HTML_OUTPUT "${output_dir}/${LATEX_TARGET}.html")
1829      add_custom_command(OUTPUT ${HTML_OUTPUT}
1830        COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir}
1831          ${HTLATEX_COMPILER} ${LATEX_MAIN_INPUT}
1832          "${HTLATEX_COMPILER_TEX4HT_FLAGS}"
1833          "${HTLATEX_COMPILER_TEX4HT_POSTPROCESSOR_FLAGS}"
1834          "${HTLATEX_COMPILER_T4HT_POSTPROCESSOR_FLAGS}"
1835          ${HTLATEX_COMPILER_ARGS}
1836        DEPENDS
1837          ${output_dir}/${LATEX_TARGET}.tex
1838          ${output_dir}/${LATEX_TARGET}.dvi
1839        VERBATIM
1840        )
1841      add_custom_target(${html_target}
1842        DEPENDS ${HTML_OUTPUT} ${dvi_target}
1843        SOURCES ${all_latex_sources}
1844        )
1845      if(NOT LATEX_EXCLUDE_FROM_DEFAULTS)
1846        add_dependencies(html ${html_target})
1847      endif()
1848    endif()
1849  endif()
1850
1851  # Set default targets.
1852  if("${default_build}" STREQUAL "pdf")
1853    add_custom_target(${LATEX_TARGET_NAME} DEPENDS ${pdf_target})
1854  elseif("${default_build}" STREQUAL "dvi")
1855    add_custom_target(${LATEX_TARGET_NAME} DEPENDS ${dvi_target})
1856  elseif("${default_build}" STREQUAL "ps")
1857    add_custom_target(${LATEX_TARGET_NAME} DEPENDS ${ps_target})
1858  elseif("${default_build}" STREQUAL "safepdf")
1859    add_custom_target(${LATEX_TARGET_NAME} DEPENDS ${safepdf_target})
1860  elseif("${default_build}" STREQUAL "html")
1861    add_custom_target(${LATEX_TARGET_NAME} DEPENDS ${html_target})
1862  else()
1863    message(SEND_ERROR "LATEX_DEFAULT_BUILD set to an invalid value. See the documentation for that variable.")
1864  endif()
1865
1866  if(NOT LATEX_EXCLUDE_FROM_ALL)
1867    add_custom_target(_${LATEX_TARGET_NAME} ALL DEPENDS ${LATEX_TARGET_NAME})
1868  endif()
1869
1870  set_directory_properties(.
1871    ADDITIONAL_MAKE_CLEAN_FILES "${auxiliary_clean_files}"
1872    )
1873
1874  add_custom_target(${auxclean_target}
1875    COMMENT "Cleaning auxiliary LaTeX files."
1876    COMMAND ${CMAKE_COMMAND} -E remove ${auxiliary_clean_files}
1877    )
1878  add_dependencies(auxclean ${auxclean_target})
1879endfunction(add_latex_targets_internal)
1880
1881function(add_latex_targets latex_main_input)
1882  latex_get_output_path(output_dir)
1883  parse_add_latex_arguments(ADD_LATEX_TARGETS ${latex_main_input} ${ARGN})
1884
1885  add_latex_targets_internal()
1886endfunction(add_latex_targets)
1887
1888function(add_latex_document latex_main_input)
1889  latex_get_output_path(output_dir)
1890  if(output_dir)
1891    parse_add_latex_arguments(add_latex_document ${latex_main_input} ${ARGN})
1892
1893    latex_copy_input_file(${LATEX_MAIN_INPUT})
1894
1895    foreach (bib_file ${LATEX_BIBFILES})
1896      latex_copy_input_file(${bib_file})
1897    endforeach (bib_file)
1898
1899    foreach (input ${LATEX_INPUTS})
1900      latex_copy_input_file(${input})
1901    endforeach(input)
1902
1903    latex_copy_globbed_files(${CMAKE_CURRENT_SOURCE_DIR}/*.cls ${output_dir})
1904    latex_copy_globbed_files(${CMAKE_CURRENT_SOURCE_DIR}/*.bst ${output_dir})
1905    latex_copy_globbed_files(${CMAKE_CURRENT_SOURCE_DIR}/*.clo ${output_dir})
1906    latex_copy_globbed_files(${CMAKE_CURRENT_SOURCE_DIR}/*.sty ${output_dir})
1907    latex_copy_globbed_files(${CMAKE_CURRENT_SOURCE_DIR}/*.ist ${output_dir})
1908    latex_copy_globbed_files(${CMAKE_CURRENT_SOURCE_DIR}/*.fd  ${output_dir})
1909
1910    add_latex_targets_internal()
1911  endif()
1912endfunction(add_latex_document)
1913
1914#############################################################################
1915# Actually do stuff
1916#############################################################################
1917
1918if(LATEX_BUILD_COMMAND)
1919  set(command_handled)
1920
1921  if("${LATEX_BUILD_COMMAND}" STREQUAL execute_latex)
1922    latex_execute_latex()
1923    set(command_handled TRUE)
1924  endif()
1925
1926  if("${LATEX_BUILD_COMMAND}" STREQUAL makeglossaries)
1927    latex_makeglossaries()
1928    set(command_handled TRUE)
1929  endif()
1930
1931  if("${LATEX_BUILD_COMMAND}" STREQUAL makenomenclature)
1932    latex_makenomenclature()
1933    set(command_handled TRUE)
1934  endif()
1935
1936  if("${LATEX_BUILD_COMMAND}" STREQUAL correct_synctex)
1937    latex_correct_synctex()
1938    set(command_handled TRUE)
1939  endif()
1940
1941  if("${LATEX_BUILD_COMMAND}" STREQUAL check_important_warnings)
1942    latex_check_important_warnings()
1943    set(command_handled TRUE)
1944  endif()
1945
1946  if(NOT command_handled)
1947    message(SEND_ERROR "Unknown command: ${LATEX_BUILD_COMMAND}")
1948  endif()
1949
1950else()
1951  # Must be part of the actual configure (included from CMakeLists.txt).
1952  latex_setup_variables()
1953  latex_setup_targets()
1954endif()
1955