Skip to content
Snippets Groups Projects
LATEX.cmake 72.4 KiB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
# File: UseLATEX.cmake
# CMAKE commands to actually use the LaTeX compiler
# Version: 2.4.6
# Author: Kenneth Moreland <kmorel@sandia.gov>
#
# Copyright 2004, 2015 Sandia Corporation.
# Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
# license for use of this work by or on behalf of the U.S. Government.
#
# This software is released under the BSD 3-Clause License.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#
# The following function is defined:
#
# add_latex_document(<tex_file>
#                    [BIBFILES <bib_files>]
#                    [INPUTS <input_tex_files>]
#                    [IMAGE_DIRS] <image_directories>
#                    [IMAGES] <image_files>
#                    [CONFIGURE] <tex_files>
#                    [DEPENDS] <tex_files>
#                    [MULTIBIB_NEWCITES] <suffix_list>
#                    [USE_BIBLATEX]
#                    [USE_INDEX]
#                    [INDEX_NAMES <index_names>]
#                    [USE_GLOSSARY] [USE_NOMENCL]
#                    [FORCE_PDF] [FORCE_DVI] [FORCE_HTML]
#                    [TARGET_NAME] <name>
#                    [EXCLUDE_FROM_ALL]
#                    [EXCLUDE_FROM_DEFAULTS])
#       Adds targets that compile <tex_file>.  The latex output is placed
#       in LATEX_OUTPUT_PATH or CMAKE_CURRENT_BINARY_DIR if the former is
#       not set.  The latex program is picky about where files are located,
#       so all input files are copied from the source directory to the
#       output directory.  This includes the target tex file, any tex file
#       listed with the INPUTS option, the bibliography files listed with
#       the BIBFILES option, and any .cls, .bst, .clo, .sty, .ist, and .fd
#       files found in the current source directory.  Images found in the
#       IMAGE_DIRS directories or listed by IMAGES are also copied to the
#       output directory and converted to an appropriate format if necessary.
#       Any tex files also listed with the CONFIGURE option are also processed
#       with the CMake CONFIGURE_FILE command (with the @ONLY flag).  Any file
#       listed in CONFIGURE but not the target tex file or listed with INPUTS
#       has no effect. DEPENDS can be used to specify generated files that are
#       needed to compile the latex target.
#
#       The following targets are made. The name prefix is based off of the
#       base name of the tex file unless TARGET_NAME is specified. If
#       TARGET_NAME is specified, then that name is used for the targets.
#
#               name_dvi: Makes <name>.dvi
#               name_pdf: Makes <name>.pdf using pdflatex.
#               name_safepdf: Makes <name>.pdf using ps2pdf.  If using the
#                       default program arguments, this will ensure all fonts
#                       are embedded and no lossy compression has been
#                       performed on images.
#               name_ps: Makes <name>.ps
#               name_html: Makes <name>.html
#               name_auxclean: Deletes <name>.aux and other auxiliary files.
#                       This is sometimes necessary if a LaTeX error occurs
#                       and writes a bad aux file.  Unlike the regular clean
#                       target, it does not delete other input files, such as
#                       converted images, to save time on the rebuild.
#
#       Unless the EXCLUDE_FROM_ALL option is given, one of these targets
#       is added to the ALL target and built by default. Which target is
#       determined by the LATEX_DEFAULT_BUILD CMake variable. See the
#       documentation of that variable for more details.
#
#       Unless the EXCLUDE_FROM_DEFAULTS option is given, all these targets
#       are added as dependencies to targets named dvi, pdf, safepdf, ps,
#       html, and auxclean, respectively.
#
#       USE_BIBLATEX enables the use of biblatex/biber as an alternative to
#       bibtex. Bibtex remains the default if USE_BIBLATEX is not
#       specified.
#
#       If the argument USE_INDEX is given, then commands to build an index
#       are made. If the argument INDEX_NAMES is given, an index file is
#       generated for each name in this list. See the LaTeX package multind
#       for more information about how to generate multiple indices.
#
#       If the argument USE_GLOSSARY is given, then commands to
#       build a glossary are made.  If the argument MULTIBIB_NEWCITES is
#       given, then additional bibtex calls are added to the build to
#       support the extra auxiliary files created with the \newcite command
#       in the multibib package.
#
# History:
#
# 2.4.6 Fix parse issue with older versions of CMake.
#
# 2.4.5 Fix issues with files and paths containing spaces.
#
# 2.4.4 Improve error reporting message when LaTeX fails.
#
#       When LaTeX fails, delete the output file, which is invalid.
#
#       Add warnings for "missing characters." These usually mean that a
#       non-ASCII character is in the document and will not be printed
#       correctly.
#
# 2.4.3 Check for warnings from the natbib package. When using natbib,
#       warnings for missing bibliography references look different. So
#       far, natbib seems to be quiet unless something is important, so
#       look for all natbib warnings. (We can change this later if
#       necessary.)
#
# 2.4.2 Fix an issue where new versions of ImageMagick expect the order of
#       options in command line execution of magick/convert. (See, for
#       example, http://www.imagemagick.org/Usage/basics/#why.)
#
# 2.4.1 Add ability to dump LaTeX log file when using batch mode. Batch
#       mode suppresses most output, often including error messages. To
#       make sure critical error messages get displayed, show the full log
#       on failures.
#
# 2.4.0 Remove "-r 600" from the default PDFTOPS_CONVERTER_FLAGS. The -r flag
#       is available from the Poppler version of pdftops, but not the Xpdf
#       version.
#
#       Fix an issue with the flags for the different programs not being
#       properly separated.
#
#       Fix an issue on windows where the = character is not allowed for
#       ps2pdf arguments.
#
#       Change default arguments for latex and pdflatex commands. Makes the
#       output more quiet and prints out the file/line where errors occur.
#       (Thanks to Nikos Koukis.)
#
#       After a LaTeX build, check the log file for warnings that are
#       indicative of problems with the build.
#
#       Remove support for latex2html. Instead, use the htlatex program.
#       This is now part of TeX Live and most other distributions. It also
#       behaves much more like the other LaTeX programs. Also fixed some
#       nasty issues with the htlatex arguments.
#
# 2.3.2 Declare LaTeX input files as sources for targets so that they show
#       up in IDEs like QtCreator.
#
#       Fix issue where main tex files in subdirectories were creating
#       invalid targets for building HTML. Just disable the HTML targets in
#       this case.
#
# 2.3.1 Support use of magick command instead of convert command for
#       ImageMagick 7.
#
# 2.3.0 Add USE_BIBLATEX option to support the biblatex package, which
#       requires using the program biber as a replacement for bibtex
#       (thanks to David Tracey).
#
# 2.2.1 Add STRINGS property to LATEX_DEFAULT_BUILD to make it easier to
#       select the default build in the CMake GUI.
#
# 2.2.0 Add TARGET_NAME option.
#
# 2.1.1 Support for finding bmp, ppm, and other image files.
#
# 2.1.0 Fix an error where the pdf target and others were defined multiple
#       times if UseLATEX.cmake was included multiple times.
#
#       Added INDEX_NAMES option to support multiple indexes in a single
#       document from the multind package (thanks to Dan Lipsa).
#
# 2.0.0 First major revision of UseLATEX.cmake updates to more recent features
#       of CMake and some non-backward compatible changes.
#
#       Changed all function and macro names to lower case. CMake's identifiers
#       are case insensitive, but the convention moved from all upper case to
#       all lower case somewhere around the release of CMake 2. (The original
#       version of UseLATEX.cmake predates that.)
#
#       Remove condition matching in if statements. They are no longer necessary
#       and are even discouraged (because else clauses get confusing).
#
#       Use "new" features available in CMake such as list and argument parsing.
#
#       Remove some code that has been deprecated for a while.
#
#       Mark variables for compiler and converter executables as advanced to
#       match the more conventional CMake behavior.
#
#       Changed how default builds are specified and add the ability to force
#       a particular build.
#
#       Made the base targets (pdf, dvi, etc.) global. add_latex_document
#       always mangles its target names and these base targets depend on
#       the targets with mangled names.
#
# 1.10.5 Fix for Window's convert check (thanks to Martin Baute).
#
# 1.10.4 Copy font files to binary directory for packages that come with
#       their own fonts.
#
# 1.10.3 Check for Windows version of convert being used instead of
#       ImageMagick's version (thanks to Martin Baute).
#
# 1.10.2 Use htlatex as a fallback when latex2html is not available (thanks
#       to Tomasz Grzegurzko).
#
# 1.10.1 Make convert program mandatory only if actually used (thanks to
#       Julien Schueller).
#
# 1.10.0 Added NO_DEFAULT and DEFAULT_PS options.
#       Fixed issue with cleaning files for LaTeX documents originating in
#       a subdirectory.
#
# 1.9.6 Fixed problem with LATEX_SMALL_IMAGES.
#       Strengthened check to make sure the output directory does not contain
#       the source files.
#
# 1.9.5 Add support for image types not directly supported by either latex
#       or pdflatex.  (Thanks to Jorge Gerardo Pena Pastor for SVG support.)
#
# 1.9.4 Fix issues with filenames containing multiple periods.
#
# 1.9.3 Hide some variables that are now cached but should not show up in
#       the ccmake list of variables.
#
# 1.9.2 Changed MACRO declarations to FUNCTION declarations.  The better
#       FUNCTION scoping will hopefully avoid some common but subtle bugs.
#       This implicitly increases the minimum CMake version to 4.6 (although
#       I honestly only test it with the latest 4.8 version).
#
#       Since we are updating the minimum CMake version, I'm going to start
#       using the builtin LIST commands that are now available.
#
#       Favor using pdftops from the Poppler package to convert from pdf to
#       eps.  It does a much better job than ImageMagick or ghostscript.
#
# 1.9.1 Fixed typo that caused the LATEX_SMALL_IMAGES option to fail to
#       activate.
#
# 1.9.0 Add support for the multibib package (thanks to Antonio LaTorre).
#
# 1.8.2 Fix corner case when an argument name was also a variable containing
#       the text of an argument.  In this case, the CMake IF was matching
#       the argument text with the contents of the variable with the same
#       argument name.
#
# 1.8.1 Fix problem where ps2pdf was not getting the appropriate arguments.
#
# 1.8.0 Add support for synctex.
#
# 1.7.7 Support calling xindy when making glossaries.
#
#       Improved make clean support.
#
# 1.7.6 Add support for the nomencl package (thanks to Myles English).
#
# 1.7.5 Fix issue with bibfiles being copied two different ways, which causes
#       Problems with dependencies (thanks to Edwin van Leeuwen).
#
# 1.7.4 Added the DEFAULT_SAFEPDF option (thanks to Raymond Wan).
#
#       Added warnings when image directories are not found (and were
#       probably not given relative to the source directory).
#
# 1.7.3 Fix some issues with interactions between makeglossaries and bibtex
#       (thanks to Mark de Wever).
#
# 1.7.2 Use ps2pdf to convert eps to pdf to get around the problem with
#       ImageMagick dropping the bounding box (thanks to Lukasz Lis).
#
# 1.7.1 Fixed some dependency issues.
#
# 1.7.0 Added DEPENDS options (thanks to Theodore Papadopoulo).
#
# 1.6.1 Ported the makeglossaries command to CMake and embedded the port
#       into UseLATEX.cmake.
#
# 1.6.0 Allow the use of the makeglossaries command.  Thanks to Oystein
#       S. Haaland for the patch.
#
# 1.5.0 Allow any type of file in the INPUTS lists, not just tex file
#       (suggested by Eric Noulard).  As a consequence, the ability to
#       specify tex files without the .tex extension is removed.  The removed
#       function is of dubious value anyway.
#
#       When copying input files, skip over any file that exists in the
#       binary directory but does not exist in the source directory with the
#       assumption that these files were added by some other mechanism.  I
#       find this useful when creating large documents with multiple
#       chapters that I want to build separately (for speed) as I work on
#       them.  I use the same boilerplate as the starting point for all
#       and just copy it with different configurations.  This was what the
#       separate ADD_LATEX_DOCUMENT method was supposed to originally be for.
#       Since its external use is pretty much deprecated, I removed that
#       documentation.
#
# 1.4.1 Copy .sty files along with the other class and package files.
#
# 1.4.0 Added a MANGLE_TARGET_NAMES option that will mangle the target names.
#
#       Fixed problem with copying bib files that became apparent with
#       CMake 2.4.
#
# 1.3.0 Added a LATEX_OUTPUT_PATH variable that allows you or the user to
#       specify where the built latex documents to go.  This is especially
#       handy if you want to do in-source builds.
#
#       Removed the ADD_LATEX_IMAGES macro and absorbed the functionality
#       into ADD_LATEX_DOCUMENT.  The old interface was always kind of
#       clunky anyway since you had to specify the image directory in both
#       places.  It also made supporting LATEX_OUTPUT_PATH problematic.
#
#       Added support for jpeg files.
#
# 1.2.0 Changed the configuration options yet again.  Removed the NO_CONFIGURE
#       Replaced it with a CONFIGURE option that lists input files for which
#       configure should be run.
#
#       The pdf target no longer depends on the dvi target.  This allows you
#       to build latex documents that require pdflatex.  Also added an option
#       to make the pdf target the default one.
#
# 1.1.1 Added the NO_CONFIGURE option.  The @ character can be used when
#       specifying table column separators.  If two or more are used, then
#       will incorrectly substitute them.
#
# 1.1.0 Added ability include multiple bib files.  Added ability to do copy
#       sub-tex files for multipart tex files.
#
# 1.0.0 If both ps and pdf type images exist, just copy the one that
#       matches the current render mode.  Replaced a bunch of STRING
#       commands with GET_FILENAME_COMPONENT commands that were made to do
#       the desired function.
#
# 0.4.0 First version posted to CMake Wiki.
#

if(__USE_LATEX_INCLUDED)
  return()
endif()
set(__USE_LATEX_INCLUDED TRUE)

#############################################################################
# Find the location of myself while originally executing.  If you do this
# inside of a macro, it will recode where the macro was invoked.
#############################################################################
set(LATEX_USE_LATEX_LOCATION ${CMAKE_CURRENT_LIST_FILE}
  CACHE INTERNAL "Location of UseLATEX.cmake file." FORCE
  )

#############################################################################
# Generic helper functions
#############################################################################

include(CMakeParseArguments)

function(latex_list_contains var value)
  set(input_list ${ARGN})
  list(FIND input_list "${value}" index)
  if(index GREATER -1)
    set(${var} TRUE PARENT_SCOPE)
  else()
    set(${var} PARENT_SCOPE)
  endif()
endfunction(latex_list_contains)

# Match the contents of a file to a regular expression.
function(latex_file_match variable filename regexp default)
  # The FILE STRINGS command would be a bit better, but I'm not totally sure
  # the match will always be to a whole line, and I don't want to break things.
  file(READ ${filename} file_contents)
  string(REGEX MATCHALL "${regexp}"
    match_result ${file_contents}
    )
  if(match_result)
    set(${variable} "${match_result}" PARENT_SCOPE)
  else()
    set(${variable} "${default}" PARENT_SCOPE)
  endif()
endfunction(latex_file_match)

# A version of GET_FILENAME_COMPONENT that treats extensions after the last
# period rather than the first.  To the best of my knowledge, all filenames
# typically used by LaTeX, including image files, have small extensions
# after the last dot.
function(latex_get_filename_component varname filename type)
  set(result)
  if("${type}" STREQUAL "NAME_WE")
    get_filename_component(name ${filename} NAME)
    string(REGEX REPLACE "\\.[^.]*\$" "" result "${name}")
  elseif("${type}" STREQUAL "EXT")
    get_filename_component(name ${filename} NAME)
    string(REGEX MATCH "\\.[^.]*\$" result "${name}")
  else()
    get_filename_component(result ${filename} ${type})
  endif()
  set(${varname} "${result}" PARENT_SCOPE)
endfunction(latex_get_filename_component)

#############################################################################
# Functions that perform processing during a LaTeX build.
#############################################################################
function(latex_execute_latex)
  if(NOT LATEX_TARGET)
    message(SEND_ERROR "Need to define LATEX_TARGET")
  endif()

  if(NOT LATEX_WORKING_DIRECTORY)
    message(SEND_ERROR "Need to define LATEX_WORKING_DIRECTORY")
  endif()

  if(NOT LATEX_FULL_COMMAND)
    message(SEND_ERROR "Need to define LATEX_FULL_COMMAND")
  endif()

  if(NOT LATEX_OUTPUT_FILE)
    message(SEND_ERROR "Need to define LATEX_OUTPUT_FILE")
  endif()

  set(full_command_original "${LATEX_FULL_COMMAND}")

  # Chose the native method for parsing command arguments. Newer versions of
  # CMake allow you to just use NATIVE_COMMAND.
  if (CMAKE_VERSION VERSION_GREATER 3.8)
    set(separate_arguments_mode NATIVE_COMMAND)
  else()
    if (WIN32)
      set(separate_arguments_mode WINDOWS_COMMAND)
    else()
      set(separate_arguments_mode UNIX_COMMAND)
    endif()
  endif()

  # Preps variables for use in execute_process.
  # Even though we expect LATEX_WORKING_DIRECTORY to have a single "argument,"
  # we also want to make sure that we strip out any escape characters that can
  # foul up the WORKING_DIRECTORY argument.
  separate_arguments(LATEX_FULL_COMMAND UNIX_COMMAND "${LATEX_FULL_COMMAND}")
  separate_arguments(LATEX_WORKING_DIRECTORY UNIX_COMMAND "${LATEX_WORKING_DIRECTORY}")

  execute_process(
    COMMAND ${LATEX_FULL_COMMAND}
    WORKING_DIRECTORY ${LATEX_WORKING_DIRECTORY}
    RESULT_VARIABLE execute_result
    )

  if(NOT ${execute_result} EQUAL 0)
    # LaTeX tends to write a file when a failure happens. Delete that file so
    # that LaTeX will run again.
    file(REMOVE "${LATEX_WORKING_DIRECTORY}/${LATEX_OUTPUT_FILE}")

    message("\n\nLaTeX command failed")
    message("${full_command_original}")
    message("Log output:")
    file(READ ${LATEX_WORKING_DIRECTORY}/${LATEX_TARGET}.log log_output)
    message("${log_output}")
    message(FATAL_ERROR
      "Successfully executed LaTeX, but LaTeX returned an error.")
  endif()
endfunction(latex_execute_latex)

function(latex_makeglossaries)
  # This is really a bare bones port of the makeglossaries perl script into
  # CMake scripting.
  message("**************************** In makeglossaries")
  if(NOT LATEX_TARGET)
    message(SEND_ERROR "Need to define LATEX_TARGET")
  endif()

  set(aux_file ${LATEX_TARGET}.aux)

  if(NOT EXISTS ${aux_file})
    message(SEND_ERROR "${aux_file} does not exist.  Run latex on your target file.")
  endif()

  latex_file_match(newglossary_lines ${aux_file}
    "@newglossary[ \t]*{([^}]*)}{([^}]*)}{([^}]*)}{([^}]*)}"
    "@newglossary{main}{glg}{gls}{glo}"
    )

  latex_file_match(istfile_line ${aux_file}
    "@istfilename[ \t]*{([^}]*)}"
    "@istfilename{${LATEX_TARGET}.ist}"
    )
  string(REGEX REPLACE "@istfilename[ \t]*{([^}]*)}" "\\1"
    istfile ${istfile_line}
    )

  string(REGEX MATCH ".*\\.xdy" use_xindy "${istfile}")
  if(use_xindy)
    message("*************** Using xindy")
    if(NOT XINDY_COMPILER)
      message(SEND_ERROR "Need to define XINDY_COMPILER")
    endif()
  else()
    message("*************** Using makeindex")
    if(NOT MAKEINDEX_COMPILER)
      message(SEND_ERROR "Need to define MAKEINDEX_COMPILER")
    endif()
  endif()

  foreach(newglossary ${newglossary_lines})
    string(REGEX REPLACE
      "@newglossary[ \t]*{([^}]*)}{([^}]*)}{([^}]*)}{([^}]*)}"
      "\\1" glossary_name ${newglossary}
      )
    string(REGEX REPLACE
      "@newglossary[ \t]*{([^}]*)}{([^}]*)}{([^}]*)}{([^}]*)}"
      "${LATEX_TARGET}.\\2" glossary_log ${newglossary}
      )
    string(REGEX REPLACE
      "@newglossary[ \t]*{([^}]*)}{([^}]*)}{([^}]*)}{([^}]*)}"
      "${LATEX_TARGET}.\\3" glossary_out ${newglossary}
      )
    string(REGEX REPLACE
      "@newglossary[ \t]*{([^}]*)}{([^}]*)}{([^}]*)}{([^}]*)}"
      "${LATEX_TARGET}.\\4" glossary_in ${newglossary}
      )

    if(use_xindy)
      latex_file_match(xdylanguage_line ${aux_file}
        "@xdylanguage[ \t]*{${glossary_name}}{([^}]*)}"
        "@xdylanguage{${glossary_name}}{english}"
        )
      string(REGEX REPLACE
        "@xdylanguage[ \t]*{${glossary_name}}{([^}]*)}"
        "\\1"
        language
        ${xdylanguage_line}
        )
      # What crazy person makes a LaTeX index generator that uses different
      # identifiers for language than babel (or at least does not support
      # the old ones)?
      if(${language} STREQUAL "frenchb")
        set(language "french")
      elseif(${language} MATCHES "^n?germanb?$")
        set(language "german")
      elseif(${language} STREQUAL "magyar")
        set(language "hungarian")
      elseif(${language} STREQUAL "lsorbian")
        set(language "lower-sorbian")
      elseif(${language} STREQUAL "norsk")
        set(language "norwegian")
      elseif(${language} STREQUAL "portuges")
        set(language "portuguese")
      elseif(${language} STREQUAL "russianb")
        set(language "russian")
      elseif(${language} STREQUAL "slovene")
        set(language "slovenian")
      elseif(${language} STREQUAL "ukraineb")
        set(language "ukrainian")
      elseif(${language} STREQUAL "usorbian")
        set(language "upper-sorbian")
      endif()
      if(language)
        set(language_flags "-L ${language}")
      else()
        set(language_flags "")
      endif()

      latex_file_match(codepage_line ${aux_file}
        "@gls@codepage[ \t]*{${glossary_name}}{([^}]*)}"
        "@gls@codepage{${glossary_name}}{utf}"
        )
      string(REGEX REPLACE
        "@gls@codepage[ \t]*{${glossary_name}}{([^}]*)}"
        "\\1"
        codepage
        ${codepage_line}
        )
      if(codepage)
        set(codepage_flags "-C ${codepage}")
      else()
        # Ideally, we would check that the language is compatible with the
        # default codepage, but I'm hoping that distributions will be smart
        # enough to specify their own codepage.  I know, it's asking a lot.
        set(codepage_flags "")
      endif()

      message("${XINDY_COMPILER} ${MAKEGLOSSARIES_COMPILER_ARGS} ${language_flags} ${codepage_flags} -I xindy -M ${glossary_name} -t ${glossary_log} -o ${glossary_out} ${glossary_in}"
        )
      exec_program(${XINDY_COMPILER}
        ARGS ${MAKEGLOSSARIES_COMPILER_ARGS}
          ${language_flags}
          ${codepage_flags}
          -I xindy
          -M ${glossary_name}
          -t ${glossary_log}
          -o ${glossary_out}
          ${glossary_in}
        OUTPUT_VARIABLE xindy_output
        )
      message("${xindy_output}")

      # So, it is possible (perhaps common?) for aux files to specify a
      # language and codepage that are incompatible with each other.  Check
      # for that condition, and if it happens run again with the default
      # codepage.
      if("${xindy_output}" MATCHES "^Cannot locate xindy module for language (.+) in codepage (.+)\\.$")
        message("*************** Retrying xindy with default codepage.")
        exec_program(${XINDY_COMPILER}
          ARGS ${MAKEGLOSSARIES_COMPILER_ARGS}
            ${language_flags}
            -I xindy
            -M ${glossary_name}
            -t ${glossary_log}
            -o ${glossary_out}
            ${glossary_in}
          )
      endif()

    else()
      message("${MAKEINDEX_COMPILER} ${MAKEGLOSSARIES_COMPILER_ARGS} -s ${istfile} -t ${glossary_log} -o ${glossary_out} ${glossary_in}")
      exec_program(${MAKEINDEX_COMPILER} ARGS ${MAKEGLOSSARIES_COMPILER_ARGS}
        -s ${istfile} -t ${glossary_log} -o ${glossary_out} ${glossary_in}
        )
    endif()

  endforeach(newglossary)
endfunction(latex_makeglossaries)

function(latex_makenomenclature)
  message("**************************** In makenomenclature")
  if(NOT LATEX_TARGET)
    message(SEND_ERROR "Need to define LATEX_TARGET")
  endif()

  if(NOT MAKEINDEX_COMPILER)
    message(SEND_ERROR "Need to define MAKEINDEX_COMPILER")
  endif()

  set(nomencl_out ${LATEX_TARGET}.nls)
  set(nomencl_in ${LATEX_TARGET}.nlo)

  exec_program(${MAKEINDEX_COMPILER} ARGS ${MAKENOMENCLATURE_COMPILER_ARGS}
    ${nomencl_in} -s "nomencl.ist" -o ${nomencl_out}
    )
endfunction(latex_makenomenclature)

function(latex_correct_synctex)
  message("**************************** In correct SyncTeX")
  if(NOT LATEX_TARGET)
    message(SEND_ERROR "Need to define LATEX_TARGET")
  endif()

  if(NOT GZIP)
    message(SEND_ERROR "Need to define GZIP")
  endif()

  if(NOT LATEX_SOURCE_DIRECTORY)
    message(SEND_ERROR "Need to define LATEX_SOURCE_DIRECTORY")
  endif()

  if(NOT LATEX_BINARY_DIRECTORY)
    message(SEND_ERROR "Need to define LATEX_BINARY_DIRECTORY")
  endif()

  set(synctex_file ${LATEX_BINARY_DIRECTORY}/${LATEX_TARGET}.synctex)
  set(synctex_file_gz ${synctex_file}.gz)

  if(EXISTS ${synctex_file_gz})

    message("Making backup of synctex file.")
    configure_file(${synctex_file_gz} ${synctex_file}.bak.gz COPYONLY)

    message("Uncompressing synctex file.")
    exec_program(${GZIP}
      ARGS --decompress ${synctex_file_gz}
      )

    message("Reading synctex file.")
    file(READ ${synctex_file} synctex_data)

    message("Replacing relative with absolute paths.")
    string(REGEX REPLACE
      "(Input:[0-9]+:)([^/\n][^\n]*)"
      "\\1${LATEX_SOURCE_DIRECTORY}/\\2"
      synctex_data
      "${synctex_data}"
      )

    message("Writing synctex file.")
    file(WRITE ${synctex_file} "${synctex_data}")

    message("Compressing synctex file.")
    exec_program(${GZIP}
      ARGS ${synctex_file}
      )

  else()

    message(SEND_ERROR "File ${synctex_file_gz} not found.  Perhaps synctex is not supported by your LaTeX compiler.")

  endif()

endfunction(latex_correct_synctex)

function(latex_check_important_warnings)
  set(log_file ${LATEX_TARGET}.log)

  message("\nChecking ${log_file} for important warnings.")
  if(NOT LATEX_TARGET)
    message(SEND_ERROR "Need to define LATEX_TARGET")
  endif()

  if(NOT EXISTS ${log_file})
    message("Could not find log file: ${log_file}")
    return()
  endif()

  set(found_error)

  file(READ ${log_file} log)

  # Check for undefined references
  string(REGEX MATCHALL
    "\n[^\n]*Reference[^\n]*undefined[^\n]*"
    reference_warnings
    "${log}")
  if(reference_warnings)
    set(found_error TRUE)
    message("\nFound missing reference warnings.")
    foreach(warning ${reference_warnings})
      string(STRIP "${warning}" warning_no_newline)
      message("${warning_no_newline}")
    endforeach(warning)
  endif()

  # Check for natbib warnings
  string(REGEX MATCHALL
    "\nPackage natbib Warning:[^\n]*"
    natbib_warnings
    "${log}")
  if(natbib_warnings)
    set(found_error TRUE)
    message("\nFound natbib package warnings.")
    foreach(warning ${natbib_warnings})
      string(STRIP "${warning}" warning_no_newline)
      message("${warning_no_newline}")
    endforeach(warning)
  endif()

  # Check for overfull
  string(REGEX MATCHALL
    "\nOverfull[^\n]*"
    overfull_warnings
    "${log}")
  if(overfull_warnings)
    set(found_error TRUE)
    message("\nFound overfull warnings. These are indicative of layout errors.")
    foreach(warning ${overfull_warnings})
      string(STRIP "${warning}" warning_no_newline)
      message("${warning_no_newline}")
    endforeach(warning)
  endif()

  # Check for invalid characters
  string(REGEX MATCHALL
    "\nMissing character:[^\n]*"
    invalid_character_warnings
    "${log}")
  if(invalid_character_warnings)
    set(found_error TRUE)
    message("\nFound invalid character warnings. These characters are likely not printed correctly.")
    foreach(warning ${invalid_character_warnings})
      string(STRIP "${warning}" warning_no_newline)
      message("${warning_no_newline}")
    endforeach(warning)
  endif()

  if(found_error)
    latex_get_filename_component(log_file_path ${log_file} ABSOLUTE)
    message("\nConsult ${log_file_path} for more information on LaTeX build.")
  else()
    message("No known important warnings found.")
  endif(found_error)
endfunction(latex_check_important_warnings)

#############################################################################
# Helper functions for establishing LaTeX build.
#############################################################################

function(latex_needit VAR NAME)
  if(NOT ${VAR})
    message(SEND_ERROR "I need the ${NAME} command.")
  endif()
endfunction(latex_needit)

function(latex_wantit VAR NAME)
  if(NOT ${VAR})
    message(STATUS "I could not find the ${NAME} command.")
  endif()
endfunction(latex_wantit)

function(latex_setup_variables)
  set(LATEX_OUTPUT_PATH "${LATEX_OUTPUT_PATH}"
    CACHE PATH "If non empty, specifies the location to place LaTeX output."
    )

  find_package(LATEX)

  find_program(XINDY_COMPILER
    NAME xindy
    PATHS ${MIKTEX_BINARY_PATH} /usr/bin
    )

  find_package(UnixCommands)

  find_program(PDFTOPS_CONVERTER
    NAMES pdftops
    DOC "The pdf to ps converter program from the Poppler package."
    )

  find_program(HTLATEX_COMPILER
    NAMES htlatex
    PATHS ${MIKTEX_BINARY_PATH}
      /usr/bin
    )

  mark_as_advanced(
    LATEX_COMPILER
    PDFLATEX_COMPILER
    BIBTEX_COMPILER
    BIBER_COMPILER
    MAKEINDEX_COMPILER
    XINDY_COMPILER
    DVIPS_CONVERTER
    PS2PDF_CONVERTER
    PDFTOPS_CONVERTER
    LATEX2HTML_CONVERTER
    HTLATEX_COMPILER
    )

  latex_needit(LATEX_COMPILER latex)
  latex_wantit(PDFLATEX_COMPILER pdflatex)
  latex_wantit(HTLATEX_COMPILER htlatex)
  latex_needit(BIBTEX_COMPILER bibtex)
  latex_wantit(BIBER_COMPILER biber)
  latex_needit(MAKEINDEX_COMPILER makeindex)
  latex_wantit(DVIPS_CONVERTER dvips)
  latex_wantit(PS2PDF_CONVERTER ps2pdf)
  latex_wantit(PDFTOPS_CONVERTER pdftops)

  set(LATEX_COMPILER_FLAGS "-interaction=batchmode -file-line-error"
    CACHE STRING "Flags passed to latex.")
  set(PDFLATEX_COMPILER_FLAGS ${LATEX_COMPILER_FLAGS}
    CACHE STRING "Flags passed to pdflatex.")
  set(HTLATEX_COMPILER_TEX4HT_FLAGS "html"
    CACHE STRING "Options for the tex4ht.sty and *.4ht style files.")
  set(HTLATEX_COMPILER_TEX4HT_POSTPROCESSOR_FLAGS ""
    CACHE STRING "Options for the text4ht postprocessor.")
  set(HTLATEX_COMPILER_T4HT_POSTPROCESSOR_FLAGS ""
    CACHE STRING "Options for the t4ht postprocessor.")
  set(HTLATEX_COMPILER_LATEX_FLAGS ${LATEX_COMPILER_FLAGS}
    CACHE STRING "Flags passed from htlatex to the LaTeX compiler.")
  set(LATEX_SYNCTEX_FLAGS "-synctex=1"
    CACHE STRING "latex/pdflatex flags used to create synctex file.")
  set(BIBTEX_COMPILER_FLAGS ""
    CACHE STRING "Flags passed to bibtex.")
  set(BIBER_COMPILER_FLAGS ""
    CACHE STRING "Flags passed to biber.")
  set(MAKEINDEX_COMPILER_FLAGS ""
    CACHE STRING "Flags passed to makeindex.")
  set(MAKEGLOSSARIES_COMPILER_FLAGS ""
    CACHE STRING "Flags passed to makeglossaries.")
  set(MAKENOMENCLATURE_COMPILER_FLAGS ""
    CACHE STRING "Flags passed to makenomenclature.")
  set(DVIPS_CONVERTER_FLAGS "-Ppdf -G0 -t letter"
    CACHE STRING "Flags passed to dvips.")
  if(NOT WIN32)
    set(PS2PDF_CONVERTER_FLAGS "-dMaxSubsetPct=100 -dCompatibilityLevel=1.3 -dSubsetFonts=true -dEmbedAllFonts=true -dAutoFilterColorImages=false -dAutoFilterGrayImages=false -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode -dMonoImageFilter=/FlateEncode"
      CACHE STRING "Flags passed to ps2pdf.")
  else()
    # Most windows ports of ghostscript utilities use .bat files for ps2pdf
    # commands. bat scripts interpret "=" as a special character and separate
    # those arguments. To get around this, the ghostscript utilities also
    # support using "#" in place of "=".
    set(PS2PDF_CONVERTER_FLAGS "-dMaxSubsetPct#100 -dCompatibilityLevel#1.3 -dSubsetFonts#true -dEmbedAllFonts#true -dAutoFilterColorImages#false -dAutoFilterGrayImages#false -dColorImageFilter#/FlateEncode -dGrayImageFilter#/FlateEncode -dMonoImageFilter#/FlateEncode"
      CACHE STRING "Flags passed to ps2pdf.")
  endif()
  set(PDFTOPS_CONVERTER_FLAGS ""
    CACHE STRING "Flags passed to pdftops.")
  mark_as_advanced(
    LATEX_COMPILER_FLAGS
    PDFLATEX_COMPILER_FLAGS
    HTLATEX_COMPILER_TEX4HT_FLAGS
    HTLATEX_COMPILER_TEX4HT_POSTPROCESSOR_FLAGS
    HTLATEX_COMPILER_T4HT_POSTPROCESSOR_FLAGS
    HTLATEX_COMPILER_LATEX_FLAGS
    LATEX_SYNCTEX_FLAGS
    BIBTEX_COMPILER_FLAGS
    BIBER_COMPILER_FLAGS
    MAKEINDEX_COMPILER_FLAGS
    MAKEGLOSSARIES_COMPILER_FLAGS
    MAKENOMENCLATURE_COMPILER_FLAGS
    DVIPS_CONVERTER_FLAGS
    PS2PDF_CONVERTER_FLAGS
    PDFTOPS_CONVERTER_FLAGS
    )

  # Because it is easier to type, the flags variables are entered as
  # space-separated strings much like you would in a shell. However, when
  # using a CMake command to execute a program, it works better to hold the
  # arguments in semicolon-separated lists (otherwise the whole string will
  # be interpreted as a single argument). Use the separate_arguments to
  # convert the space-separated strings to semicolon-separated lists.
  separate_arguments(LATEX_COMPILER_FLAGS)
  separate_arguments(PDFLATEX_COMPILER_FLAGS)
  separate_arguments(HTLATEX_COMPILER_LATEX_FLAGS)
  separate_arguments(LATEX_SYNCTEX_FLAGS)
  separate_arguments(BIBTEX_COMPILER_FLAGS)
  separate_arguments(BIBER_COMPILER_FLAGS)
  separate_arguments(MAKEINDEX_COMPILER_FLAGS)
  separate_arguments(MAKEGLOSSARIES_COMPILER_FLAGS)
  separate_arguments(MAKENOMENCLATURE_COMPILER_FLAGS)
  separate_arguments(DVIPS_CONVERTER_FLAGS)
  separate_arguments(PS2PDF_CONVERTER_FLAGS)
  separate_arguments(PDFTOPS_CONVERTER_FLAGS)

  # Not quite done. When you call separate_arguments on a cache variable,
  # the result is written to a local variable. That local variable goes
  # away when this function returns (which is before any of them are used).
  # So, copy these variables with local scope to cache variables with
  # global scope.
  set(LATEX_COMPILER_ARGS "${LATEX_COMPILER_FLAGS}" CACHE INTERNAL "")
  set(PDFLATEX_COMPILER_ARGS "${PDFLATEX_COMPILER_FLAGS}" CACHE INTERNAL "")
  set(HTLATEX_COMPILER_ARGS "${HTLATEX_COMPILER_LATEX_FLAGS}" CACHE INTERNAL "")
  set(LATEX_SYNCTEX_ARGS "${LATEX_SYNCTEX_FLAGS}" CACHE INTERNAL "")
  set(BIBTEX_COMPILER_ARGS "${BIBTEX_COMPILER_FLAGS}" CACHE INTERNAL "")
  set(BIBER_COMPILER_ARGS "${BIBER_COMPILER_FLAGS}" CACHE INTERNAL "")
  set(MAKEINDEX_COMPILER_ARGS "${MAKEINDEX_COMPILER_FLAGS}" CACHE INTERNAL "")
  set(MAKEGLOSSARIES_COMPILER_ARGS "${MAKEGLOSSARIES_COMPILER_FLAGS}" CACHE INTERNAL "")
  set(MAKENOMENCLATURE_COMPILER_ARGS "${MAKENOMENCLATURE_COMPILER_FLAGS}" CACHE INTERNAL "")
  set(DVIPS_CONVERTER_ARGS "${DVIPS_CONVERTER_FLAGS}" CACHE INTERNAL "")
  set(PS2PDF_CONVERTER_ARGS "${PS2PDF_CONVERTER_FLAGS}" CACHE INTERNAL "")
  set(PDFTOPS_CONVERTER_ARGS "${PDFTOPS_CONVERTER_FLAGS}" CACHE INTERNAL "")

  find_program(IMAGEMAGICK_CONVERT
    NAMES magick convert
    DOC "The convert program that comes with ImageMagick (available at http://www.imagemagick.org)."
    )
  mark_as_advanced(IMAGEMAGICK_CONVERT)

  if(DEFINED ENV{LATEX_DEFAULT_BUILD})
    set(default_build $ENV{LATEX_DEFAULT_BUILD})
  else()
    set(default_build pdf)
  endif()

  set(LATEX_DEFAULT_BUILD "${default_build}" CACHE STRING
    "Choose the default type of LaTeX build. Valid options are pdf, dvi, ps, safepdf, html"
    )
  set_property(CACHE LATEX_DEFAULT_BUILD
    PROPERTY STRINGS pdf dvi ps safepdf html
    )

  option(LATEX_USE_SYNCTEX
    "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."
    OFF
    )

  option(LATEX_SMALL_IMAGES
    "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."
    OFF)
  if(LATEX_SMALL_IMAGES)
    set(LATEX_RASTER_SCALE 16 PARENT_SCOPE)
    set(LATEX_OPPOSITE_RASTER_SCALE 100 PARENT_SCOPE)
  else()
    set(LATEX_RASTER_SCALE 100 PARENT_SCOPE)
    set(LATEX_OPPOSITE_RASTER_SCALE 16 PARENT_SCOPE)
  endif()

  # Just holds extensions for known image types.  They should all be lower case.
  # For historical reasons, these are all declared in the global scope.
  set(LATEX_DVI_VECTOR_IMAGE_EXTENSIONS .eps CACHE INTERNAL "")
  set(LATEX_DVI_RASTER_IMAGE_EXTENSIONS CACHE INTERNAL "")
  set(LATEX_DVI_IMAGE_EXTENSIONS