#
# Required version of omake
#
OMakeVersion(0.9.6, 0.9.6)

########################################################################
# Building LaTeX documents.
#
# Copyright (C) 2003-2005 Jason Hickey and Mojave Group
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this file, to deal in the File without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the File, and to permit persons to whom the File
# is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the File.
#
# THE FILE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# FILE OR THE USE OR OTHER DEALINGS IN THE FILE.

include $(STDLIB)/build/Common


########################################################################
# LaTeX Section
#

#
# LaTeX config
#
# \begin{doc}
# \section{Building \LaTeX\ programs}
#
# \subsection{Configuration variables}
#
# The following variables can be modified in your project.
# \begin{description}
# \item[LATEX] The \LaTeX\ command (default \verb+latex+).
# \item[TETEX2\_ENABLED] Flag indicating whether to use advanced \LaTeX\ options
# present in TeTeX v.2 (default value is determined the first time omake reads \verb+LaTeX.src+
# and depends on the version of \LaTeX\ you have installed).
# \item[LATEXFLAGS] The \LaTeX\ flags (defaults depend on the \verb+TETEX2_ENABLED+ variable)
# \item[BIBTEX] The BibTeX command (default \verb+bibtex+).
# \item[MAKEINDEX] The command to build an index (default \verb+makeindex+).
# \item[DVIPS] The \verb+.dvi+ to PostScript converter (default \verb+dvips+).
# \item[DVIPSFLAGS] Flags to pass to \verb+dvips+ (default \verb+-t letter+).
# \item[DVIPDFM] The \verb+.dvi+ to \verb+.pdf+ converter (default \verb+dvipdfm+).
# \item[DVIPDFMFLAGS] Flags to pass to \verb+dvipdfm+ (default \verb+-p letter+).
# \item[PDFLATEX] The \verb+.latex+ to \verb+.pdf+ converter (default \verb+pdflatex+).
# \item[PDFLATEXFLAGS] Flags to pass to pdflatex (default is empty).
# \item[USEPDFLATEX] Flag indicating whether to use pdflatex instead of dvipdfm
# to generate the \verb+.pdf+ document (default \verb+false+).
# \end{description}
# \end{doc}
#
BIBTEX = bibtex
MAKEINDEX = makeindex
DVIPS = dvips
DVIPSFLAGS = -t letter
DVIPDFM = dvipdfm
DVIPDFMFLAGS = -p letter
PDFLATEX = pdflatex
PDFLATEXFLAGS =
USEPDFLATEX = false
LATEX = latex
LATEXFLAGS =
    BASE = -output-comment="LaTeX Output (built with OMake)"
    value $`(if $(TETEX2_ENABLED), -file-line-error-style $,(BASE), -interaction=errorstopmode $,(BASE))

#
# Configure LaTeX by checking whether some LaTeX options exist.
#
TETEX2_ENABLED = false
static. =
    print(--- Testing for LaTeX... )
    if $(where $(LATEX))
        println($'(latex found)')
        print(--- Configuring LaTeX defaults... )

        # Look through the -help info for tetex2 options
        TETEX_CONFIG_TMP = $(tmpfile tetex)
        $(LATEX) -help > $(TETEX_CONFIG_TMP)
        TETEX2_ENABLED = $(and $(grep q, ^-recorder, $(TETEX_CONFIG_TMP)), $(grep q, ^-file-line-error-style, $(TETEX_CONFIG_TMP)))
        rm $(TETEX_CONFIG_TMP)
        if $(TETEX2_ENABLED)
            println($'(tetex2 enabled)')
        else
            println($'(tetex2 disabled)')
        export TETEX2_ENABLED
    else
        println($'(latex not found)')

#
# Dynamically defined list of files that the TeX source depends on.
#
TEXDEPS =

#
# Directories in the search path.
# Split them at colons to get a directory list.
#
TEXINPUTS = $(split $(PATHSEP), $(getenv TEXINPUTS, .))

#
# TeX can log its inputs and outputs into an .fls file.  We use the internal awk
# to turn an .fls file into in appropriate dependency file format.
#
Shell. +=
    builtin-tex-deps(argv) =
        private. =
            f =
        foreach(f, $(argv))
            DEPS[] =
            WRITES[] = $(file $f.bbl $f.ind)
            DEPDIR = $(dir .)
            awk($f.fls)
            case PWD
                DEPDIR = $(dir $2)
                export
            case INPUT
                DEPS += $(cd $(DEPDIR), $(file $2))
                export
            case OUTPUT
                WRITES += $(cd $(DEPDIR), $(file $2))
                export
            FS=$'[{}]'
            awk($f.aux)
            case $'\\bibdata\{.*\}'
               BIBS = $(split \,, $2)
               BIBS[] = $(BIBS) $(addsuffix .bib, $(BIBS))
               DEPS += $(find-in-path-optional $(split \:, $(getenv BIBINPUTS)), $(BIBS))
               export DEPS
            DEPS = $(string $(set-diff $(DEPS), $(WRITES)))
            println($f.dvi: $(DEPS))
            if $(USEPDFLATEX)
                println($f.pdf: $(DEPS))

    stdout-to-err(argv) =
        stdout = $(stderr)
        $(argv)

    run-latex(argv) =
        if $(mem -file-line-error-style, $(argv))
            if $(not $(shell-success $(argv)))
                private.f = $(replacesuffixes .tex, $(string $(EMPTY)), $(last $(argv)))
                eprintln(*** Errors detected while running LaTeX on $(private.f).tex:)
                stdout-to-err grep ':[1-9][0-9]*: ' $(private.f).log
                exit 1
        else
            $(argv)

#
# Rules for building TeX documents.
#
# name: the name of the document
# texfiles: the TeX source files, without suffix
#
# Dynamic variables:
#    TEXINPUTS: extra directories to include in the search path
#    TEXDEPS: files that are implicitly included, including suffixes
#
# \begin{doc}
# \subsection{LaTeXDocument}
#
# The \verb+LaTeXDocument+ produces a \LaTeX\ document.
#
# \verb+LaTeXDocument(<name>, <texfiles>)+
#
# The document \verb+<name>+ and \verb+<texfiles>+ are listed without suffixes.
#
# Additional variables used:
# \begin{description}
# \item[TEXINPUTS] The \LaTeX\ search path.
# \item[TEXDEPS] Additional files this document depends on.
# \end{description}
# \end{doc}

#
# Make sure generated files are built before scanning
#
.PHONY: TeXGeneratedFilesTarget

TeXGeneratedFiles(files) =
    TeXGeneratedFilesTarget: $(files)

LocalTeXGeneratedFiles(files) =
    .SCANNER: scan-tex-%: $(files)
    export

LaTeXDocument(name, texfiles) =
    #
    # TeX files all have the .tex suffix
    #
    TEXFILES = $(name).tex $(addsuffix .tex, $(texfiles))

    #
    # Setting the proper TEXINPUTS environment
    #
    INPUTS = $(concat $(PATHSEP), $(TEXINPUTS))$(PATHSEP)
    setenv(TEXINPUTS, $(INPUTS))
    setenv(BIBINPUTS, $(INPUTS))

    SCANNER =

    #
    # TeTeX2 has the ability to compute dependencies for us
    #
    if $(TETEX2_ENABLED)
        .SCANNER: scan-tex-$(name).tex: $(name).tex $(TEXDEPS) $(TEXFILES) TeXGeneratedFilesTarget\
            :value: $(USEPDFLATEX) $(find-in-path-optional $(INPUTS), $&)\
            :effects: $(name).aux $(name).log $(name).ind $(name).out $(name).dvi $(name).fls
               echo | run-latex stdout-to-err $(LATEX) $(LATEXFLAGS) -recorder $<
               builtin-tex-deps $(name)

        SCANNER = scan-tex-$(name).tex

        export

    Rule(prog, ext) =
        $(name).$(ext): $(TEXDEPS) $(TEXFILES) :effects: $(name).aux $(name).log $(name).ind $(name).out :scanner: $(SCANNER)
            echo "Enviroment variables TEXINPUT and BIBINPUTS set to $(getenv TEXINPUTS)"
            run-latex $(prog) $(LATEXFLAGS) $(name)
            if $(and $(grep q, $'\\citation', $(name).aux), $(grep q, $'\\bibdata', $(name).aux))
                $(BIBTEX) $(name)
                run-latex $(prog) $(LATEXFLAGS) $(name)
            if $(and $(file-exists $(name).idx), $(grep q, $'\\indexentry', $(name).idx))
                $(MAKEINDEX) $(name)
                run-latex $(prog) $(LATEXFLAGS) $(name)
            if $(grep q, $'Label.s. may have changed', $(name).log)
                run-latex $(prog) $(LATEXFLAGS) $(name)
            if $(grep q, $'Label.s. may have changed', $(name).log)
                run-latex $(prog) $(LATEXFLAGS) $(name)
            if $(grep q, $'Label.s. may have changed', $(name).log)
                run-latex $(prog) $(LATEXFLAGS) $(name)

    Rule($(LATEX), dvi)

    if $(USEPDFLATEX)
        Rule($(PDFLATEX), pdf)
    else
       $(name).pdf: $(name).dvi
           $(DVIPDFM) $(DVIPDFMFLAGS) -o $@ $(name).dvi

    $(name).ps: $(name).dvi
        $(DVIPS) $(DVIPSFLAGS) -o $@ $(name).dvi

#
# Copy the document to a library directory
#
# \begin{doc}
# \subsection{LaTeXDocumentCopy}
#
# The \verb+LaTeXDocumentCopy+ copies the document to an install location.
#
# \verb+LaTeXDocumentCopy(<tag>, <libdir>, <installname>, <docname>)+
#
# This function copies just the \verb+.pdf+ and \verb+.ps+ files.
# \end{doc}
#
LaTeXDocumentCopy(tag, lib, dst, src) =
    $(lib)/$(dst).pdf: $(src).pdf
        cp $< $@

    $(lib)/$(dst).ps: $(src).ps
        cp $< $@

    $(tag): $(lib)/$(dst).pdf $(lib)/$(dst).ps

#
# Build the document and copy it
#
# \begin{doc}
# \subsection{LaTeXDocumentInstall}
#
# The \verb+LaTeXDocumentInstall+ builds a document and copies it to an
# install location in one step.
#
# \verb+LaTeXDocumentInstall(<tag>, <libdir>, <installname>, <docname>, <files>)+
# \end{doc}
#
LaTeXDocumentInstall(tag, lib, dst, src, texfiles) =
    LaTeXDocument($(src), $(texfiles))
    LaTeXDocumentCopy($(tag), $(lib), $(dst), $(src))

