config

Personal configuration.
git clone git://code.dwrz.net/config
Log | Files | Refs

ox-latex.el (180075B)


      1 ;;; ox-latex.el --- LaTeX Backend for Org Export Engine -*- lexical-binding: t; -*-
      2 
      3 ;; Copyright (C) 2011-2024 Free Software Foundation, Inc.
      4 
      5 ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
      6 ;; Maintainer: Daniel Fleischer <danflscr@gmail.com>
      7 ;; Keywords: outlines, hypermedia, calendar, text
      8 
      9 ;; This file is part of GNU Emacs.
     10 
     11 ;; GNU Emacs is free software: you can redistribute it and/or modify
     12 ;; it under the terms of the GNU General Public License as published by
     13 ;; the Free Software Foundation, either version 3 of the License, or
     14 ;; (at your option) any later version.
     15 
     16 ;; GNU Emacs is distributed in the hope that it will be useful,
     17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
     18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     19 ;; GNU General Public License for more details.
     20 
     21 ;; You should have received a copy of the GNU General Public License
     22 ;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
     23 
     24 ;;; Commentary:
     25 ;;
     26 ;; See Org manual for details.
     27 
     28 ;;; Code:
     29 
     30 (require 'org-macs)
     31 (org-assert-version)
     32 
     33 (require 'cl-lib)
     34 (require 'ox)
     35 (require 'ox-publish)
     36 
     37 ;;; Function Declarations
     38 
     39 (defvar org-latex-default-packages-alist)
     40 (defvar org-latex-packages-alist)
     41 (defvar orgtbl-exp-regexp)
     42 
     43 (declare-function engrave-faces-latex-gen-preamble "ext:engrave-faces-latex")
     44 (declare-function engrave-faces-latex-buffer "ext:engrave-faces-latex")
     45 (declare-function engrave-faces-latex-gen-preamble-line "ext:engrave-faces-latex")
     46 (declare-function engrave-faces-get-theme "ext:engrave-faces")
     47 
     48 (defvar engrave-faces-latex-output-style)
     49 (defvar engrave-faces-current-preset-style)
     50 (defvar engrave-faces-latex-mathescape)
     51 
     52 
     53 ;;; Define Backend
     54 
     55 (org-export-define-backend 'latex
     56   '((bold . org-latex-bold)
     57     (center-block . org-latex-center-block)
     58     (clock . org-latex-clock)
     59     (code . org-latex-code)
     60     (drawer . org-latex-drawer)
     61     (dynamic-block . org-latex-dynamic-block)
     62     (entity . org-latex-entity)
     63     (example-block . org-latex-example-block)
     64     (export-block . org-latex-export-block)
     65     (export-snippet . org-latex-export-snippet)
     66     (fixed-width . org-latex-fixed-width)
     67     (footnote-definition . org-latex-footnote-definition)
     68     (footnote-reference . org-latex-footnote-reference)
     69     (headline . org-latex-headline)
     70     (horizontal-rule . org-latex-horizontal-rule)
     71     (inline-src-block . org-latex-inline-src-block)
     72     (inlinetask . org-latex-inlinetask)
     73     (italic . org-latex-italic)
     74     (item . org-latex-item)
     75     (keyword . org-latex-keyword)
     76     (latex-environment . org-latex-latex-environment)
     77     (latex-fragment . org-latex-latex-fragment)
     78     (line-break . org-latex-line-break)
     79     (link . org-latex-link)
     80     (node-property . org-latex-node-property)
     81     (paragraph . org-latex-paragraph)
     82     (plain-list . org-latex-plain-list)
     83     (plain-text . org-latex-plain-text)
     84     (planning . org-latex-planning)
     85     (property-drawer . org-latex-property-drawer)
     86     (quote-block . org-latex-quote-block)
     87     (radio-target . org-latex-radio-target)
     88     (section . org-latex-section)
     89     (special-block . org-latex-special-block)
     90     (src-block . org-latex-src-block)
     91     (statistics-cookie . org-latex-statistics-cookie)
     92     (strike-through . org-latex-strike-through)
     93     (subscript . org-latex-subscript)
     94     (superscript . org-latex-superscript)
     95     (table . org-latex-table)
     96     (table-cell . org-latex-table-cell)
     97     (table-row . org-latex-table-row)
     98     (target . org-latex-target)
     99     (template . org-latex-template)
    100     (timestamp . org-latex-timestamp)
    101     (underline . org-latex-underline)
    102     (verbatim . org-latex-verbatim)
    103     (verse-block . org-latex-verse-block)
    104     ;; Pseudo objects and elements.
    105     (latex-math-block . org-latex-math-block)
    106     (latex-matrices . org-latex-matrices))
    107   :menu-entry
    108   '(?l "Export to LaTeX"
    109        ((?L "As LaTeX buffer" org-latex-export-as-latex)
    110 	(?l "As LaTeX file" org-latex-export-to-latex)
    111 	(?p "As PDF file" org-latex-export-to-pdf)
    112 	(?o "As PDF file and open"
    113 	    (lambda (a s v b)
    114 	      (if a (org-latex-export-to-pdf t s v b)
    115 		(org-open-file (org-latex-export-to-pdf nil s v b)))))))
    116   :filters-alist '((:filter-options . org-latex-math-block-options-filter)
    117 		   (:filter-paragraph . org-latex-clean-invalid-line-breaks)
    118 		   (:filter-parse-tree org-latex-math-block-tree-filter
    119 				       org-latex-matrices-tree-filter
    120 				       org-latex-image-link-filter)
    121 		   (:filter-verse-block . org-latex-clean-invalid-line-breaks))
    122   :options-alist
    123   '((:latex-class "LATEX_CLASS" nil org-latex-default-class t)
    124     (:latex-class-options "LATEX_CLASS_OPTIONS" nil nil t)
    125     (:latex-header "LATEX_HEADER" nil nil newline)
    126     (:latex-header-extra "LATEX_HEADER_EXTRA" nil nil newline)
    127     (:description "DESCRIPTION" nil nil parse)
    128     (:keywords "KEYWORDS" nil nil parse)
    129     (:subtitle "SUBTITLE" nil nil parse)
    130     ;; Other variables.
    131     (:latex-active-timestamp-format nil nil org-latex-active-timestamp-format)
    132     (:latex-caption-above nil nil org-latex-caption-above)
    133     (:latex-classes nil nil org-latex-classes)
    134     (:latex-default-figure-position nil nil org-latex-default-figure-position)
    135     (:latex-default-table-environment nil nil org-latex-default-table-environment)
    136     (:latex-default-quote-environment nil nil org-latex-default-quote-environment)
    137     (:latex-default-table-mode nil nil org-latex-default-table-mode)
    138     (:latex-default-footnote-command "LATEX_FOOTNOTE_COMMAND" nil org-latex-default-footnote-command)
    139     (:latex-diary-timestamp-format nil nil org-latex-diary-timestamp-format)
    140     (:latex-engraved-options nil nil org-latex-engraved-options)
    141     (:latex-engraved-preamble nil nil org-latex-engraved-preamble)
    142     (:latex-engraved-theme "LATEX_ENGRAVED_THEME" nil org-latex-engraved-theme)
    143     (:latex-footnote-defined-format nil nil org-latex-footnote-defined-format)
    144     (:latex-footnote-separator nil nil org-latex-footnote-separator)
    145     (:latex-format-drawer-function nil nil org-latex-format-drawer-function)
    146     (:latex-format-headline-function nil nil org-latex-format-headline-function)
    147     (:latex-format-inlinetask-function nil nil org-latex-format-inlinetask-function)
    148     (:latex-hyperref-template nil nil org-latex-hyperref-template t)
    149     (:latex-image-default-scale nil nil org-latex-image-default-scale)
    150     (:latex-image-default-height nil nil org-latex-image-default-height)
    151     (:latex-image-default-option nil nil org-latex-image-default-option)
    152     (:latex-image-default-width nil nil org-latex-image-default-width)
    153     (:latex-images-centered nil nil org-latex-images-centered)
    154     (:latex-inactive-timestamp-format nil nil org-latex-inactive-timestamp-format)
    155     (:latex-inline-image-rules nil nil org-latex-inline-image-rules)
    156     (:latex-link-with-unknown-path-format nil nil org-latex-link-with-unknown-path-format)
    157     (:latex-src-block-backend nil nil org-latex-src-block-backend)
    158     (:latex-listings-langs nil nil org-latex-listings-langs)
    159     (:latex-listings-options nil nil org-latex-listings-options)
    160     (:latex-listings-src-omit-language nil nil org-latex-listings-src-omit-language)
    161     (:latex-minted-langs nil nil org-latex-minted-langs)
    162     (:latex-minted-options nil nil org-latex-minted-options)
    163     (:latex-prefer-user-labels nil nil org-latex-prefer-user-labels)
    164     (:latex-subtitle-format nil nil org-latex-subtitle-format)
    165     (:latex-subtitle-separate nil nil org-latex-subtitle-separate)
    166     (:latex-table-scientific-notation nil nil org-latex-table-scientific-notation)
    167     (:latex-tables-booktabs nil nil org-latex-tables-booktabs)
    168     (:latex-tables-centered nil nil org-latex-tables-centered)
    169     (:latex-text-markup-alist nil nil org-latex-text-markup-alist)
    170     (:latex-title-command nil nil org-latex-title-command)
    171     (:latex-toc-command nil nil org-latex-toc-command)
    172     (:latex-compiler "LATEX_COMPILER" nil org-latex-compiler)
    173     ;; Redefine regular options.
    174     (:date "DATE" nil "\\today" parse)))
    175 
    176 
    177 
    178 ;;; Internal Variables
    179 
    180 (defconst org-latex-language-alist
    181   (let ((de-default-plist '(:babel "ngerman" :babel-ini-alt "german" :polyglossia "german" :polyglossia-variant "german" :lang-name "German" :script "latin" :script-tag "latn"))
    182         (zh-default-plist '(:babel-ini-only "chinese" :polyglossia "chinese" :polyglossia-variant "simplified" :lang-name "Chinese Simplified" :script "hans" :script-tag "hans")))
    183     `(("af" :babel "afrikaans" :polyglossia "afrikaans" :lang-name "Afrikaans" :script "latin" :script-tag "latn")
    184       ("am" :babel-ini-only "amharic" :polyglossia "amharic" :lang-name "Amharic" :script "ethiopic" :script-tag "ethi")
    185       ("ar" :babel-ini-only "arabic" :polyglossia "arabic" :lang-name "Arabic" :script "arabic" :script-tag "arab")
    186       ("ast" :babel-ini-only "asturian" :polyglossia "asturian" :lang-name "Asturian" :script "latin" :script-tag "latn")
    187       ("bg"  :babel "bulgarian" :polyglossia "bulgarian" :lang-name "Bulgarian" :script "cyrillic" :script-tag "cyrl")
    188       ("bn"  :babel-ini-only "bengali" :polyglossia "bengali" :lang-name "Bengali" :script "bengali" :script-tag: "beng")
    189       ("bo"  :babel-ini-only "tibetan" :polyglossia "tibetan" :lang-name "Tibetan" :script "tibetan" :script-tag "tib")
    190       ("br"  :babel "breton" :polyglossia "breton" :lang-name "Breton" :script "latin" :script-tag "latn")
    191       ("ca"  :babel "catalan" :polyglossia "catalan" :lang-name "Catalan" :script "latin" :script-tag "latn")
    192       ("cop"  :babel-ini-only "coptic" :polyglossia "coptic" :lang-name "Coptic" :script "coptic" :script-tag "copt")
    193       ("cs"  :babel "czech" :polyglossia "czech" :lang-name "Czech" :script "latin" :script-tag "latn")
    194       ("cy"  :babel "welsh" :polyglossia "welsh" :lang-name "Welsh" :script "latin" :script-tag "latn")
    195       ("da"  :babel "danish" :polyglossia "danish" :lang-name "Danish" :script "latin" :script-tag "latn")
    196       ("de" ,@de-default-plist)
    197       ("de-de" ,@de-default-plist)
    198       ("de-at" :babel "naustrian" :babel-ini-alt "german-austria" :polyglossia "german" :polyglossia-variant "austrian" :lang-name "German" :script "latin" :script-tag "latn")
    199       ("dsb" :babel "lowersorbian" :babel-ini-alt "lsorbian" :polyglossia "sorbian" :polyglossia-variant "lower" :lang-name "Lower Sorbian" :script "latin" :script-tag "latn")
    200       ("dv" :polyglossia "divehi" :lang-name "Dhivehi" :script "latin" :script-tag "latn")
    201       ("el" :babel "greek" :polyglossia "greek" :lang-name "Greek" :script "greek" :script-tag "grek")
    202       ("el-polyton"  :babel "polutonikogreek" :babel-ini-alt "polytonicgreek" :polyglossia "greek" :polyglossia-variant "polytonic" :lang-name "Polytonic Greek" :script "greek" :script-tag "grek")
    203       ("grc" :babel "greek.ancient" :babel-ini-alt "ancientgreek" :polyglossia "greek" :polyglossia-variant "ancient" :lang-name "Ancient Greek" :script "greek" :script-tag "grek")
    204       ("en" :babel "english" :polyglossia "english" :polyglossia-variant "usmax" :lang-name "English" :script "latin" :script-tag "latn")
    205       ("en-au" :babel "australian" :polyglossia "english" :polyglossia-variant "australian" :lang-name "English" :script "latin" :script-tag "latn")
    206       ("en-ca" :babel "canadian" :polyglossia "english" :polyglossia-variant "canadian" :lang-name "English" :script "latin" :script-tag "latn")
    207       ("en-gb" :babel "british" :polyglossia "english" :polyglossia-variant "uk" :lang-name "English" :script "latin" :script-tag "latn")
    208       ("en-nz" :babel "newzealand" :polyglossia "english" :polyglossia-variant "newzealand" :lang-name "English" :script "latin" :script-tag "latn")
    209       ("en-us" :babel "american" :polyglossia "english" :polyglossia-variant "usmax" :lang-name "English" :script "latin" :script-tag "latn")
    210       ("eo" :babel "esperanto" :polyglossia "esperanto" :lang-name "Esperanto" :script "latin" :script-tag "latn")
    211       ("es" :babel "spanish" :polyglossia "spanish" :lang-name "Spanish" :script "latin" :script-tag "latn")
    212       ("es-mx" :babel "spanishmx" :polyglossia "spanish" :polyglossia-variant "mexican" :lang-name "Spanish" :script "latin" :script-tag "latn")
    213       ("et" :babel "estonian" :polyglossia "estonian" :lang-name "Estonian" :script "latin" :script-tag "latn")
    214       ("eu" :babel "basque" :polyglossia "basque" :lang-name "Basque" :script "latin" :script-tag "latn")
    215       ("fa" :babel "persian" :polyglossia "persian" :lang-name "Persian" :script "arabic" :script-tag "arab")
    216       ("fi" :babel "finnish" :polyglossia "finnish" :lang-name "Finnish" :script "latin" :script-tag "latn")
    217       ("fr" :babel "french" :polyglossia "french" :lang-name "French" :script "latin" :script-tag "latn")
    218       ("fr-ca" :babel "canadien" :babel-ini-alt "canadian" :polyglossia "french" :polyglossia-variant "canadian" :lang-name "French" :script "latin" :script-tag "latn")
    219       ("fur" :babel "friulian" :polyglossia "friulian" :lang-name "Friulian" :script "latin" :script-tag "latn")
    220       ("ga" :babel "irish" :polyglossia "gaelic" :polyglossia-variant "irish" :lang-name "Irish Gaelic" :script "latin" :script-tag "latn")
    221       ("gd" :babel "scottish" :polyglossia "gaelic" :polyglossia-variant "scottish" :lang-name "Scottish Gaelic" :script "latin" :script-tag "latn")
    222       ("gl" :babel "galician" :polyglossia "galician" :lang-name "Galician" :script "latin" :script-tag "latn")
    223       ("he" :babel "hebrew" :polyglossia "hebrew" :lang-name "Hebrew" :script "hebrew" :script-tag "hebr")
    224       ("hi" :babel "hindi" :polyglossia "hindi" :lang-name "Hindi" :script "devanagari" :script-tag "deva")
    225       ("hr" :babel "croatian" :polyglossia "croatian" :lang-name "Croatian" :script "latin" :script-tag "latn")
    226       ("hsb" :babel "uppersorbian" :polyglossia "sorbian" :polyglossia-variant "upper" :lang-name "Upper Sorbian" :script "latin" :script-tag "latn")
    227       ("hu" :babel "magyar" :polyglossia "magyar" :lang-name "Magyar" :script "latin" :script-tag "latn")
    228       ("hy" :babel-ini-only "armenian" :polyglossia "armenian" :lang-name "Armenian" :script "armenian" :script-tag "armn")
    229       ("ia" :babel "interlingua" :polyglossia "interlingua" :lang-name "Interlingua" :script "latin" :script-tag "latn")
    230       ("id" :babel "indonesian" :polyglossia "malay" :polyglossia-variant "indonesian" :lang-name "Indonesian" :script "latin" :script-tag "latn")
    231       ("is" :babel "icelandic" :polyglossia "icelandic" :lang-name "Icelandic" :script "latin" :script-tag "latn")
    232       ("it" :babel "italian" :polyglossia "italian" :lang-name "Italian" :script "latin" :script-tag "latn")
    233       ("kn" :babel-ini-only "kannada" :polyglossia "kannada" :lang-name "Kannada" :script "kannada" :script-tag "knda")
    234       ("la" :babel "latin" :polyglossia "latin" :lang-name "Latin" :script "latin" :script-tag "latn")
    235       ("la-classic"  :babel "classiclatin" :polyglossia "latin" :polyglossia-variant "classic" :lang-name "Classic Latin" :script "latin" :script-tag "latn")
    236       ("la-medieval"  :babel "medievallatin" :polyglossia "latin" :polyglossia-variant "medieval" :lang-name "Medieval Latin" :script "latin" :script-tag "latn")
    237       ("la-ecclesiastic"  :babel "ecclesiasticlatin" :polyglossia "latin" :polyglossia-variant "ecclesiastic" :lang-name "Ecclesiastic Latin" :script "latin" :script-tag "latn")
    238       ("lo" :babel-ini-only "lao" :polyglossia "lao" :lang-name "Lao" :script "lao" :script-tag "lao")
    239       ("lt" :babel "lithuanian" :polyglossia "lithuanian" :lang-name "Lithuanian" :script "latin" :script-tag "latn")
    240       ("lv" :babel "latvian" :polyglossia "latvian" :lang-name "Latvian" :script "latin" :script-tag "latn")
    241       ("ml" :babel-ini-only "malayalam" :polyglossia "malayalam" :lang-name "Malayalam" :script "malayalam" :script-tag "mlym")
    242       ("mr" :babel-ini-only "marathi" :polyglossia "marathi" :lang-name "Marathi" :script "devanagari" :script-tag "deva")
    243       ("ms" :babel "malay" :polyglossia "malay" :polyglossia-variant "malaysian" :lang-name "Malay" :script "latin" :script-tag "latn")
    244       ("nb" :babel "norsk" :polyglossia "norwegian" :polyglossia-variant "bokmal" :lang-name "Norwegian Bokmål" :script "latin" :script-tag "latn")
    245       ("nl" :babel "dutch" :polyglossia "dutch" :lang-name "Dutch" :script "latin" :script-tag "latn")
    246       ("nn" :babel "nynorsk" :polyglossia "norwegian" :polyglossia-variant "nynorsk" :lang-name "Norwegian Nynorsk" :script "latin" :script-tag "latn")
    247       ("no" :babel "norsk" :polyglossia "norsk" :lang-name "Norwegian" :script "latin" :script-tag "latn")
    248       ("oc" :babel "occitan" :polyglossia "occitan" :lang-name "Occitan" :script "latin" :script-tag "latn")
    249       ("pl" :babel "polish" :polyglossia "polish" :lang-name "Polish" :script "latin" :script-tag "latn")
    250       ("pms" :babel "piedmontese" :polyglossia "piedmontese" :lang-name "Piedmontese" :script "latin" :script-tag "latn")
    251       ("pt"  :babel "portuges" :polyglossia "portuges" :lang-name "Portuges" :script "latin" :script-tag "latn")
    252       ("pt-br" :babel "brazilian" :polyglossia "brazilian" :lang-name "Portuges" :script "latin" :script-tag "latn")
    253       ("rm" :babel-ini-only "romansh" :polyglossia "romansh" :lang-name "Romansh" :script "latin" :script-tag "latn")
    254       ("ro" :babel "romanian" :polyglossia "romanian" :lang-name "Romanian" :script "latin" :script-tag "latn")
    255       ("ru" :babel "russian" :polyglossia "russian" :lang-name "Russian" :script "cyrillic" :script-tag "cyrl")
    256       ("sa" :babel-ini-only "sanskrit" :polyglossia "sanskrit" :lang-name "Sanskrit" :script "devanagari" :script-tag "deva")
    257       ("sk" :babel "slovak" :polyglossia "slovak" :lang-name "Slovak" :script "latin" :script-tag "latn")
    258       ("sl" :babel "slovene" :polyglossia "slovene" :lang-name "Slovene" :script "latin" :script-tag "latn")
    259       ("sq" :babel "albanian" :polyglossia "albanian" :lang-name "Albanian" :script "latin" :script-tag "latn")
    260       ("sr" :babel "serbian" :polyglossia "serbian" :lang-name "Serbian" :script "latin" :script-tag "latn")
    261       ("sr-cyrl" :babel-ini-only "serbian-cyrl" :polyglossia "serbian" :lang-name "Serbian" :script "cyrillic" :script-tag "cyrl")
    262       ("sr-latn" :babel-ini-only "serbian-latin" :polyglossia "serbian" :lang-name "Serbian" :script "latin" :script-tag "latn")
    263       ("sv"  :babel "swedish" :polyglossia "swedish" :lang-name "Swedish" :script "latin" :script-tag "latn")
    264       ("syr" :babel-ini-only "syriac" :polyglossia "syriac" :lang-name "Syriac" :script "syriac" :script-tag "syrc")
    265       ("ta" :babel-ini-only "tamil" :polyglossia "tamil" :lang-name "Tamil" :script "tamil" :script-tag "taml")
    266       ("te" :babel-ini-only "telugu" :polyglossia "telugu" :lang-name "Telugu" :script "telugu" :script-tag "telu")
    267       ("th" :babel "thai" :polyglossia "thai" :lang-name "Thai" :script "thai" :script-tag "thai")
    268       ("tk" :babel "turkmen" :polyglossia "turkmen" :lang-name "Turkmen" :script "latin" :script-tag "latn")
    269       ("tr" :babel "turkish" :polyglossia "turkish" :lang-name "Turkish" :script "latin" :script-tag "latn")
    270       ("uk" :babel "ukrainian" :polyglossia "ukrainian" :lang-name "Ukrainian" :script "cyrillic" :script-tag "cyrl")
    271       ("ur" :babel-ini-only "urdu" :polyglossia "urdu" :lang-name "Urdu" :script "arabic" :script-tag "arab")
    272       ("vi" :babel "vietnamese" :polyglossia "vietnamese" :lang-name "Vietnamese" :script "latin" :script-tag "latn")
    273       ("zh" ,@zh-default-plist)
    274       ("zh-cn" ,@zh-default-plist)
    275       ("zh-tw" :babel-ini-only "chinese-traditional" :polyglossia "chinese" :polyglossia-variant "traditional" :lang-name "Chinese Traditional" :script "hant" :script-tag "hant")))
    276   "Alist between language code and its properties for LaTeX export.
    277 
    278 In each element of the list car is always the language code and
    279 cdr is a property list.  Valid keywords for this list can be:
    280 
    281 - `:babel' the name of the language loaded by the Babel LaTeX package
    282 
    283 - `:polyglossia' the name of the language loaded by the Polyglossia
    284   LaTeX package
    285 
    286 - `:babel-ini-only' the name of the language loaded by Babel
    287  exclusively through the new ini files method.  See
    288  `http://mirrors.ctan.org/macros/latex/required/babel/base/babel.pdf'
    289 
    290 - `:babel-ini-alt' an alternative language name when it is loaded
    291   using ini files
    292 
    293 - `:polyglossia-variant' the language variant loaded by Polyglossia
    294 
    295 - `:lang-name' the actual name of the language
    296 
    297 - `:script' the script name
    298 
    299 - `:script-tag' the script otf tag.")
    300 
    301 
    302 
    303 (defconst org-latex-table-matrix-macros '(("bordermatrix" . "\\cr")
    304 					  ("qbordermatrix" . "\\cr")
    305 					  ("kbordermatrix" . "\\\\"))
    306   "Alist between matrix macros and their row ending.")
    307 
    308 (defconst org-latex-math-environments-re
    309   (format
    310    "\\`[ \t]*\\\\begin{%s\\*?}"
    311    (regexp-opt
    312     '("equation" "eqnarray" "math" "displaymath"
    313       "align"  "gather" "multline" "flalign"  "alignat"
    314       "xalignat" "xxalignat"
    315       "subequations"
    316       ;; breqn
    317       "dmath" "dseries" "dgroup" "darray"
    318       ;; empheq
    319       "empheq")))
    320   "Regexp of LaTeX math environments.")
    321 
    322 
    323 ;;; User Configurable Variables
    324 
    325 (defgroup org-export-latex nil
    326   "Options for exporting Org mode files to LaTeX."
    327   :tag "Org Export LaTeX"
    328   :group 'org-export)
    329 
    330 ;;;; Generic
    331 
    332 (defcustom org-latex-caption-above '(table)
    333   "When non-nil, place caption string at the beginning of elements.
    334 Otherwise, place it near the end.  When value is a list of
    335 symbols, put caption above selected elements only.  Allowed
    336 symbols are: `image', `table', `src-block' and `special-block'."
    337   :group 'org-export-latex
    338   :version "26.1"
    339   :package-version '(Org . "8.3")
    340   :type '(choice
    341 	  (const :tag "For all elements" t)
    342 	  (const :tag "For no element" nil)
    343 	  (set :tag "For the following elements only" :greedy t
    344 	       (const :tag "Images" image)
    345 	       (const :tag "Tables" table)
    346 	       (const :tag "Source code" src-block)
    347 	       (const :tag "Special blocks" special-block))))
    348 
    349 (defcustom org-latex-prefer-user-labels nil
    350   "Use user-provided labels instead of internal ones when non-nil.
    351 
    352 When this variable is non-nil, Org will use the value of
    353 CUSTOM_ID property, NAME keyword or Org target as the key for the
    354 \\label commands generated.
    355 
    356 By default, Org generates its own internal labels during LaTeX
    357 export.  This process ensures that the \\label keys are unique
    358 and valid, but it means the keys are not available in advance of
    359 the export process.
    360 
    361 Setting this variable gives you control over how Org generates
    362 labels during LaTeX export, so that you may know their keys in
    363 advance.  One reason to do this is that it allows you to refer to
    364 various elements using a single label both in Org's link syntax
    365 and in embedded LaTeX code.
    366 
    367 For example, when this variable is non-nil, a headline like this:
    368 
    369   ** Some section
    370      :PROPERTIES:
    371      :CUSTOM_ID: sec:foo
    372      :END:
    373   This is section [[#sec:foo]].
    374   #+BEGIN_EXPORT latex
    375   And this is still section \\ref{sec:foo}.
    376   #+END_EXPORT
    377 
    378 will be exported to LaTeX as:
    379 
    380   \\subsection{Some section}
    381   \\label{sec:foo}
    382   This is section \\ref{sec:foo}.
    383   And this is still section \\ref{sec:foo}.
    384 
    385 A non-default value of `org-latex-reference-command' will change the
    386 command (\\ref by default) used to create label references.
    387 
    388 Note, however, that setting this variable introduces a limitation
    389 on the possible values for CUSTOM_ID and NAME.  When this
    390 variable is non-nil, Org passes their value to \\label unchanged.
    391 You are responsible for ensuring that the value is a valid LaTeX
    392 \\label key, and that no other \\label commands with the same key
    393 appear elsewhere in your document.  (Keys may contain letters,
    394 numbers, and the following punctuation: `_' `.' `-' `:'.)  There
    395 are no such limitations on CUSTOM_ID and NAME when this variable
    396 is nil.
    397 
    398 For headlines that do not define the CUSTOM_ID property or
    399 elements without a NAME, Org will continue to use its default
    400 labeling scheme to generate labels and resolve links into proper
    401 references."
    402   :group 'org-export-latex
    403   :type 'boolean
    404   :version "26.1"
    405   :package-version '(Org . "8.3")
    406   :safe #'booleanp)
    407 
    408 (defcustom org-latex-reference-command "\\ref{%s}"
    409   "Format string that takes a reference to produce a LaTeX reference command.
    410 
    411 The reference is a label such as sec:intro.  A format string of \"\\ref{%s}\"
    412 produces numbered references and will always work.  It may be desirable to make
    413 use of a package such as hyperref or cleveref and then change the format string
    414 to \"\\autoref{%s}\" or \"\\cref{%s}\" for example."
    415   :group 'org-export-latex
    416   :type 'string
    417   :package-version '(Org . "9.5"))
    418 
    419 ;;;; Preamble
    420 
    421 (defcustom org-latex-default-class "article"
    422   "The default LaTeX class."
    423   :group 'org-export-latex
    424   :type '(string :tag "LaTeX class"))
    425 
    426 (defcustom org-latex-classes
    427   '(("article"
    428      "\\documentclass[11pt]{article}"
    429      ("\\section{%s}" . "\\section*{%s}")
    430      ("\\subsection{%s}" . "\\subsection*{%s}")
    431      ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
    432      ("\\paragraph{%s}" . "\\paragraph*{%s}")
    433      ("\\subparagraph{%s}" . "\\subparagraph*{%s}"))
    434     ("report"
    435      "\\documentclass[11pt]{report}"
    436      ("\\part{%s}" . "\\part*{%s}")
    437      ("\\chapter{%s}" . "\\chapter*{%s}")
    438      ("\\section{%s}" . "\\section*{%s}")
    439      ("\\subsection{%s}" . "\\subsection*{%s}")
    440      ("\\subsubsection{%s}" . "\\subsubsection*{%s}"))
    441     ("book"
    442      "\\documentclass[11pt]{book}"
    443      ("\\part{%s}" . "\\part*{%s}")
    444      ("\\chapter{%s}" . "\\chapter*{%s}")
    445      ("\\section{%s}" . "\\section*{%s}")
    446      ("\\subsection{%s}" . "\\subsection*{%s}")
    447      ("\\subsubsection{%s}" . "\\subsubsection*{%s}")))
    448   "Alist of LaTeX classes and associated header and structure.
    449 If #+LATEX_CLASS is set in the buffer, use its value and the
    450 associated information.  Here is the structure of each cell:
    451 
    452   (class-name
    453     header-string
    454     (numbered-section . unnumbered-section)
    455     ...)
    456 
    457 The header string
    458 -----------------
    459 
    460 The HEADER-STRING is the header that will be inserted into the
    461 LaTeX file.  It should contain the \\documentclass macro, and
    462 anything else that is needed for this setup.  To this header, the
    463 following commands will be added:
    464 
    465 - Calls to \\usepackage for all packages mentioned in the
    466   variables `org-latex-default-packages-alist' and
    467   `org-latex-packages-alist'.  Thus, your header definitions
    468   should avoid to also request these packages.
    469 
    470 - Lines specified via \"#+LATEX_HEADER:\" and
    471   \"#+LATEX_HEADER_EXTRA:\" keywords.
    472 
    473 If you need more control about the sequence in which the header
    474 is built up, or if you want to exclude one of these building
    475 blocks for a particular class, you can use the following
    476 macro-like placeholders.
    477 
    478  [DEFAULT-PACKAGES]      \\usepackage statements for default packages
    479  [NO-DEFAULT-PACKAGES]   do not include any of the default packages
    480  [PACKAGES]              \\usepackage statements for packages
    481  [NO-PACKAGES]           do not include the packages
    482  [EXTRA]                 the stuff from #+LATEX_HEADER(_EXTRA)
    483  [NO-EXTRA]              do not include #+LATEX_HEADER(_EXTRA) stuff
    484 
    485 So a header like
    486 
    487   \\documentclass{article}
    488   [NO-DEFAULT-PACKAGES]
    489   [EXTRA]
    490   \\providecommand{\\alert}[1]{\\textbf{#1}}
    491   [PACKAGES]
    492 
    493 will omit the default packages, and will include the
    494 #+LATEX_HEADER and #+LATEX_HEADER_EXTRA lines, then have a call
    495 to \\providecommand, and then place \\usepackage commands based
    496 on the content of `org-latex-packages-alist'.
    497 
    498 If your header, `org-latex-default-packages-alist' or
    499 `org-latex-packages-alist' inserts \"\\usepackage[AUTO]{inputenc}\",
    500 AUTO will automatically be replaced with a coding system derived
    501 from `buffer-file-coding-system'.  See also the variable
    502 `org-latex-inputenc-alist' for a way to influence this mechanism.
    503 
    504 Likewise, if your header contains \"\\usepackage[AUTO]{babel}\"
    505 or \"\\usepackage[AUTO]{polyglossia}\", AUTO will be replaced
    506 with the language related to the language code specified by
    507 `org-export-default-language'.  Note that constructions such as
    508 \"\\usepackage[french,AUTO,english]{babel}\" are permitted.  For
    509 Polyglossia the language will be set via the macros
    510 \"\\setmainlanguage\" and \"\\setotherlanguage\".  See also
    511 `org-latex-guess-babel-language' and
    512 `org-latex-guess-polyglossia-language'.
    513 
    514 The sectioning structure
    515 ------------------------
    516 
    517 The sectioning structure of the class is given by the elements
    518 following the header string.  For each sectioning level, a number
    519 of strings is specified.  A %s formatter is mandatory in each
    520 section string and will be replaced by the title of the section.
    521 
    522 Instead of a cons cell (numbered . unnumbered), you can also
    523 provide a list of 2 or 4 elements,
    524 
    525   (numbered-open numbered-close)
    526 
    527 or
    528 
    529   (numbered-open numbered-close unnumbered-open unnumbered-close)
    530 
    531 providing opening and closing strings for a LaTeX environment
    532 that should represent the document section.  The opening clause
    533 should have a %s to represent the section title.
    534 
    535 Instead of a list of sectioning commands, you can also specify
    536 a function name.  That function will be called with two
    537 parameters, the (reduced) level of the headline, and a predicate
    538 non-nil when the headline should be numbered.  It must return
    539 a format string in which the section title will be added."
    540   :group 'org-export-latex
    541   :type '(repeat
    542 	  (list (string :tag "LaTeX class")
    543 		(string :tag "LaTeX header")
    544 		(repeat :tag "Levels" :inline t
    545 			(choice
    546 			 (cons :tag "Heading"
    547 			       (string :tag "  numbered")
    548 			       (string :tag "unnumbered"))
    549 			 (list :tag "Environment"
    550 			       (string :tag "Opening   (numbered)")
    551 			       (string :tag "Closing   (numbered)")
    552 			       (string :tag "Opening (unnumbered)")
    553 			       (string :tag "Closing (unnumbered)"))
    554 			 (function :tag "Hook computing sectioning"))))))
    555 
    556 (defcustom org-latex-inputenc-alist nil
    557   "Alist of inputenc coding system names, and what should really be used.
    558 For example, adding an entry
    559 
    560       (\"utf8\" . \"utf8x\")
    561 
    562 will cause \\usepackage[utf8x]{inputenc} to be used for buffers that
    563 are written as utf8 files."
    564   :group 'org-export-latex
    565   :type '(repeat
    566 	  (cons
    567 	   (string :tag "Derived from buffer")
    568 	   (string :tag "Use this instead"))))
    569 
    570 (defcustom org-latex-title-command "\\maketitle"
    571   "The command used to insert the title just after \\begin{document}.
    572 
    573 This format string may contain these elements:
    574 
    575   %a for AUTHOR keyword
    576   %t for TITLE keyword
    577   %s for SUBTITLE keyword
    578   %k for KEYWORDS line
    579   %d for DESCRIPTION line
    580   %c for CREATOR line
    581   %l for Language keyword
    582   %L for capitalized language keyword
    583   %D for DATE keyword
    584 
    585 If you need to use a \"%\" character, you need to escape it
    586 like that: \"%%\".
    587 
    588 Setting :latex-title-command in publishing projects will take
    589 precedence over this variable."
    590   :group 'org-export-latex
    591   :type '(string :tag "Format string"))
    592 
    593 (defcustom org-latex-subtitle-format "\\\\\\medskip\n\\large %s"
    594   "Format string used for transcoded subtitle.
    595 The format string should have at most one \"%s\"-expression,
    596 which is replaced with the subtitle."
    597   :group 'org-export-latex
    598   :version "26.1"
    599   :package-version '(Org . "8.3")
    600   :type '(string :tag "Format string"))
    601 
    602 (defcustom org-latex-subtitle-separate nil
    603   "Non-nil means the subtitle is not typeset as part of title."
    604   :group 'org-export-latex
    605   :version "26.1"
    606   :package-version '(Org . "8.3")
    607   :type 'boolean)
    608 
    609 (defcustom org-latex-toc-command "\\tableofcontents\n\n"
    610   "LaTeX command to set the table of contents, list of figures, etc.
    611 This command only applies to the table of contents generated with the
    612 toc:t, toc:1, toc:2, toc:3, ... options, not to those generated with
    613 the #+TOC keyword."
    614   :group 'org-export-latex
    615   :type 'string)
    616 
    617 (defcustom org-latex-hyperref-template
    618   "\\hypersetup{\n pdfauthor={%a},\n pdftitle={%t},\n pdfkeywords={%k},
    619  pdfsubject={%d},\n pdfcreator={%c}, \n pdflang={%L}}\n"
    620   "Template for hyperref package options.
    621 
    622 This format string may contain these elements:
    623 
    624   %a for AUTHOR keyword
    625   %t for TITLE keyword
    626   %s for SUBTITLE keyword
    627   %k for KEYWORDS line
    628   %d for DESCRIPTION line
    629   %c for CREATOR line
    630   %l for Language keyword
    631   %L for capitalized language keyword
    632   %D for DATE keyword
    633 
    634 If you need to use a \"%\" character, you need to escape it
    635 like that: \"%%\".
    636 
    637 As a special case, a nil value prevents template from being
    638 inserted.
    639 
    640 Setting :latex-hyperref-template in publishing projects will take
    641 precedence over this variable."
    642   :group 'org-export-latex
    643   :version "26.1"
    644   :package-version '(Org . "8.3")
    645   :type '(choice (const :tag "No template" nil)
    646 		 (string :tag "Format string")))
    647 
    648 ;;;; Headline
    649 
    650 (defcustom org-latex-format-headline-function
    651   'org-latex-format-headline-default-function
    652   "Function for formatting the headline's text.
    653 
    654 This function will be called with six arguments:
    655 TODO      the todo keyword (string or nil)
    656 TODO-TYPE the type of todo (symbol: `todo', `done', nil)
    657 PRIORITY  the priority of the headline (integer or nil)
    658 TEXT      the main headline text (string)
    659 TAGS      the tags (list of strings or nil)
    660 INFO      the export options (plist)
    661 
    662 The function result will be used in the section format string."
    663   :group 'org-export-latex
    664   :version "24.4"
    665   :package-version '(Org . "8.0")
    666   :type 'function)
    667 
    668 
    669 ;;;; Footnotes
    670 
    671 (defcustom org-latex-default-footnote-command "\\footnote{%s%s}"
    672   "Default command used to insert footnotes.
    673 Customize this command if the LaTeX class provides a different
    674 command like \"\\sidenote{%s%s}\" that you want to use.
    675 The value will be passed as an argument to `format' as the following
    676   (format org-latex-default-footnote-command
    677      footnote-description footnote-label)"
    678   :group 'org-export-latex
    679   :package-version '(Org . "9.7")
    680   :type 'string)
    681 
    682 (defcustom org-latex-footnote-separator "\\textsuperscript{,}\\,"
    683   "Text used to separate footnotes."
    684   :group 'org-export-latex
    685   :type 'string)
    686 
    687 (defcustom org-latex-footnote-defined-format "\\textsuperscript{\\ref{%s}}"
    688   "Format string used to format reference to footnote already defined.
    689 %s will be replaced by the label of the referred footnote."
    690   :group 'org-export-latex
    691   :type '(choice
    692 	  (const :tag "Use plain superscript (default)" "\\textsuperscript{\\ref{%s}}")
    693 	  (const :tag "Use Memoir/KOMA-Script footref" "\\footref{%s}")
    694 	  (string :tag "Other format string"))
    695   :version "26.1"
    696   :package-version '(Org . "9.0"))
    697 
    698 ;;;; Timestamps
    699 
    700 (defcustom org-latex-active-timestamp-format "\\textit{%s}"
    701   "A printf format string to be applied to active timestamps."
    702   :group 'org-export-latex
    703   :type 'string)
    704 
    705 (defcustom org-latex-inactive-timestamp-format "\\textit{%s}"
    706   "A printf format string to be applied to inactive timestamps."
    707   :group 'org-export-latex
    708   :type 'string)
    709 
    710 (defcustom org-latex-diary-timestamp-format "\\textit{%s}"
    711   "A printf format string to be applied to diary timestamps."
    712   :group 'org-export-latex
    713   :type 'string)
    714 
    715 
    716 ;;;; Links
    717 
    718 (defcustom org-latex-images-centered t
    719   "When non-nil, images are centered."
    720   :group 'org-export-latex
    721   :version "26.1"
    722   :package-version '(Org . "9.0")
    723   :type 'boolean
    724   :safe #'booleanp)
    725 
    726 (defcustom org-latex-image-default-option ""
    727   "Default option for images."
    728   :group 'org-export-latex
    729   :version "24.4"
    730   :package-version '(Org . "8.0")
    731   :type 'string)
    732 
    733 (defcustom org-latex-image-default-width ".9\\linewidth"
    734   "Default width for images.
    735 This value will not be used if a height is provided."
    736   :group 'org-export-latex
    737   :version "24.4"
    738   :package-version '(Org . "8.0")
    739   :type 'string)
    740 
    741 (defcustom org-latex-image-default-scale ""
    742   "Default scale for images.
    743 This value will not be used if a width or a scale is provided,
    744 or if the image is wrapped within a \"wrapfigure\" environment.
    745 Scale overrides width and height."
    746   :group 'org-export-latex
    747   :package-version '(Org . "9.3")
    748   :type 'string)
    749 
    750 (defcustom org-latex-image-default-height ""
    751   "Default height for images.
    752 This value will not be used if a width is provided, or if the
    753 image is wrapped within a \"figure\" or \"wrapfigure\"
    754 environment."
    755   :group 'org-export-latex
    756   :version "24.4"
    757   :package-version '(Org . "8.0")
    758   :type 'string)
    759 
    760 (defcustom org-latex-default-figure-position "htbp"
    761   "Default position for LaTeX figures."
    762   :group 'org-export-latex
    763   :type 'string
    764   :version "26.1"
    765   :package-version '(Org . "9.0"))
    766 
    767 (defcustom org-latex-inline-image-rules
    768   `(("file" . ,(rx "."
    769                    (or "pdf" "jpeg" "jpg" "png" "ps" "eps" "tikz" "pgf" "svg")
    770                    eos))
    771     ("https" . ,(rx "."
    772                     (or "jpeg" "jpg" "png" "ps" "eps" "tikz" "pgf" "svg")
    773                     eos)))
    774   "Rules characterizing image files that can be inlined into LaTeX.
    775 
    776 A rule consists in an association whose key is the type of link
    777 to consider, and value is a regexp that will be matched against
    778 link's path.
    779 
    780 Note that, by default, the image extension *actually* allowed
    781 depend on the way the LaTeX file is processed.  When used with
    782 pdflatex, pdf, jpg and png images are OK.  When processing
    783 through dvi to Postscript, only ps and eps are allowed.  The
    784 default we use here encompasses both."
    785   :group 'org-export-latex
    786   :package-version '(Org . "9.6")
    787   :type '(alist :key-type (string :tag "Type")
    788 		:value-type (regexp :tag "Path")))
    789 
    790 (defcustom org-latex-link-with-unknown-path-format "\\texttt{%s}"
    791   "Format string for links with unknown path type."
    792   :group 'org-export-latex
    793   :type 'string)
    794 
    795 ;;;; Tables
    796 
    797 (defcustom org-latex-default-table-environment "tabular"
    798   "Default environment used to build tables."
    799   :group 'org-export-latex
    800   :version "24.4"
    801   :package-version '(Org . "8.0")
    802   :type 'string)
    803 
    804 (defcustom org-latex-default-quote-environment "quote"
    805   "Default environment used to `quote' blocks."
    806   :group 'org-export-latex
    807   :package-version '(Org . "9.5")
    808   :type 'string)
    809 
    810 (defcustom org-latex-default-table-mode 'table
    811   "Default mode for tables.
    812 
    813 Value can be a symbol among:
    814 
    815   `table' Regular LaTeX table.
    816 
    817   `math' In this mode, every cell is considered as being in math
    818      mode and the complete table will be wrapped within a math
    819      environment.  It is particularly useful to write matrices.
    820 
    821   `inline-math' This mode is almost the same as `math', but the
    822      math environment will be inlined.
    823 
    824   `verbatim' The table is exported as it appears in the Org
    825      buffer, within a verbatim environment.
    826 
    827 This value can be overridden locally with, i.e. \":mode math\" in
    828 LaTeX attributes.
    829 
    830 When modifying this variable, it may be useful to change
    831 `org-latex-default-table-environment' accordingly."
    832   :group 'org-export-latex
    833   :version "24.4"
    834   :package-version '(Org . "8.0")
    835   :type '(choice (const :tag "Table" table)
    836 		 (const :tag "Matrix" math)
    837 		 (const :tag "Inline matrix" inline-math)
    838 		 (const :tag "Verbatim" verbatim))
    839   :safe (lambda (s) (memq s '(table math inline-math verbatim))))
    840 
    841 (defcustom org-latex-tables-centered t
    842   "When non-nil, tables are exported in a center environment."
    843   :group 'org-export-latex
    844   :type 'boolean
    845   :safe #'booleanp)
    846 
    847 (defcustom org-latex-tables-booktabs nil
    848   "When non-nil, display tables in a formal \"booktabs\" style.
    849 This option assumes that the \"booktabs\" package is properly
    850 loaded in the header of the document.  This value can be ignored
    851 locally with \":booktabs t\" and \":booktabs nil\" LaTeX
    852 attributes."
    853   :group 'org-export-latex
    854   :version "24.4"
    855   :package-version '(Org . "8.0")
    856   :type 'boolean
    857   :safe #'booleanp)
    858 
    859 (defcustom org-latex-table-scientific-notation nil
    860   "Format string to display numbers in scientific notation.
    861 
    862 The format should have \"%s\" twice, for mantissa and exponent
    863 \(i.e., \"%s\\\\times10^{%s}\").
    864 
    865 When nil, no transformation is made."
    866   :group 'org-export-latex
    867   :version "24.4"
    868   :package-version '(Org . "8.0")
    869   :type '(choice
    870 	  (string :tag "Format string")
    871 	  (const :tag "No formatting" nil)))
    872 
    873 ;;;; Text markup
    874 
    875 (defcustom org-latex-text-markup-alist '((bold . "\\textbf{%s}")
    876 					 (code . protectedtexttt)
    877 					 (italic . "\\emph{%s}")
    878 					 (strike-through . "\\sout{%s}")
    879 					 (underline . "\\uline{%s}")
    880 					 (verbatim . protectedtexttt))
    881   "Alist of LaTeX expressions to convert text markup.
    882 
    883 The key must be a symbol among `bold', `code', `italic',
    884 `strike-through', `underline' and `verbatim'.  The value is
    885 a formatting string to wrap fontified text with.
    886 
    887 Value can also be set to the following symbols: `verb' and
    888 `protectedtexttt'.  For the former, Org will use \"\\verb\" to
    889 create a format string and select a delimiter character that
    890 isn't in the string.  For the latter, Org will use \"\\texttt\"
    891 to typeset and try to protect special characters.
    892 
    893 If no association can be found for a given markup, text will be
    894 returned as-is."
    895   :group 'org-export-latex
    896   :version "26.1"
    897   :package-version '(Org . "8.3")
    898   :type 'alist
    899   :options '(bold code italic strike-through underline verbatim))
    900 
    901 
    902 ;;;; Drawers
    903 
    904 (defcustom org-latex-format-drawer-function (lambda (_ contents) contents)
    905   "Function called to format a drawer in LaTeX code.
    906 
    907 The function must accept two parameters:
    908   NAME      the drawer name, like \"LOGBOOK\"
    909   CONTENTS  the contents of the drawer.
    910 
    911 The function should return the string to be exported.
    912 
    913 The default function simply returns the value of CONTENTS."
    914   :group 'org-export-latex
    915   :version "26.1"
    916   :package-version '(Org . "8.3")
    917   :type 'function)
    918 
    919 
    920 ;;;; Inlinetasks
    921 
    922 (defcustom org-latex-format-inlinetask-function
    923   'org-latex-format-inlinetask-default-function
    924   "Function called to format an inlinetask in LaTeX code.
    925 
    926 The function must accept seven parameters:
    927   TODO      the todo keyword (string or nil)
    928   TODO-TYPE the todo type (symbol: `todo', `done', nil)
    929   PRIORITY  the inlinetask priority (integer or nil)
    930   NAME      the inlinetask name (string)
    931   TAGS      the inlinetask tags (list of strings or nil)
    932   CONTENTS  the contents of the inlinetask (string or nil)
    933   INFO      the export options (plist)
    934 
    935 The function should return the string to be exported."
    936   :group 'org-export-latex
    937   :type 'function
    938   :version "26.1"
    939   :package-version '(Org . "8.3"))
    940 
    941 
    942 ;; Src blocks
    943 
    944 (defcustom org-latex-src-block-backend 'verbatim
    945   "Backend used to generate source code listings.
    946 
    947 This sets the behavior for fontifying source code, possibly even with
    948 color.  There are four implementations of this functionality you may
    949 choose from (ordered from least to most capable):
    950 1. Verbatim
    951 2. Listings
    952 3. Minted
    953 4. Engraved
    954 
    955 The first two options provide basic syntax
    956 highlighting (listings), or none at all (verbatim).
    957 
    958 When using listings, you also need to make use of LaTeX package
    959 \"listings\".  The \"color\" LaTeX package is also needed if you
    960 would like color too.  These can simply be added to
    961 `org-latex-packages-alist', using customize or something like:
    962 
    963   (require \\='ox-latex)
    964   (add-to-list \\='org-latex-packages-alist \\='(\"\" \"listings\"))
    965   (add-to-list \\='org-latex-packages-alist \\='(\"\" \"color\"))
    966 
    967 There are two further options for more comprehensive
    968 fontification.  The first can be set with,
    969 
    970   (setq org-latex-src-block-backend \\='minted)
    971 
    972 which causes source code to be exported using the LaTeX package
    973 minted as opposed to listings.  If you want to use minted, you
    974 need to add the minted package to `org-latex-packages-alist', for
    975 example using customize, or with
    976 
    977   (require \\='ox-latex)
    978   (add-to-list \\='org-latex-packages-alist \\='(\"newfloat\" \"minted\"))
    979 
    980 In addition, it is necessary to install pygments
    981 \(URL `https://pygments.org>'), and to configure the variable
    982 `org-latex-pdf-process' so that the -shell-escape option is
    983 passed to pdflatex.
    984 
    985 The minted choice has possible repercussions on the preview of
    986 latex fragments (see `org-preview-latex-fragment').  If you run
    987 into previewing problems, please consult
    988 URL `https://orgmode.org/worg/org-tutorials/org-latex-preview.html'.
    989 
    990 The most comprehensive option can be set with,
    991 
    992   (setq org-latex-src-block-backend \\='engraved)
    993 
    994 which causes source code to be run through
    995 `engrave-faces-latex-buffer', which generates colorings using
    996 Emacs's font-lock information.  This requires the Emacs package
    997 engrave-faces (available from GNU ELPA), and the LaTeX package
    998 fvextra be installed.
    999 
   1000 The styling of the engraved result can be customized with
   1001 `org-latex-engraved-preamble' and `org-latex-engraved-options'.
   1002 The default preamble also uses the LaTeX package tcolorbox in
   1003 addition to fvextra."
   1004   :group 'org-export-latex
   1005   :package-version '(Org . "9.6")
   1006   :type '(choice
   1007 	  (const :tag "Use listings" listings)
   1008 	  (const :tag "Use minted" minted)
   1009 	  (const :tag "Use engrave-faces-latex" engraved)
   1010 	  (const :tag "Export verbatim" verbatim))
   1011   :safe (lambda (s) (memq s '(listings minted engraved verbatim))))
   1012 
   1013 (defcustom org-latex-listings-langs
   1014   '((emacs-lisp "Lisp") (lisp "Lisp") (clojure "Lisp")
   1015     (c "C") (cc "C++")
   1016     (fortran "fortran")
   1017     (perl "Perl") (cperl "Perl") (python "Python") (ruby "Ruby")
   1018     (html "HTML") (xml "XML")
   1019     (tex "TeX") (latex "[LaTeX]TeX")
   1020     (shell-script "bash")
   1021     (gnuplot "Gnuplot")
   1022     (ocaml "[Objective]Caml") (caml "Caml")
   1023     (sql "SQL") (sqlite "sql")
   1024     (makefile "make")
   1025     (R "r"))
   1026   "Alist mapping languages to their listing language counterpart.
   1027 The key is a symbol, the major mode symbol without the \"-mode\".
   1028 The value is the string that should be inserted as the language
   1029 parameter for the listings package.  If the mode name and the
   1030 listings name are the same, the language does not need an entry
   1031 in this list - but it does not hurt if it is present."
   1032   :group 'org-export-latex
   1033   :version "26.1"
   1034   :package-version '(Org . "8.3")
   1035   :type '(repeat
   1036 	  (list
   1037 	   (symbol :tag "Major mode       ")
   1038 	   (string :tag "Listings language"))))
   1039 
   1040 (defcustom org-latex-listings-src-omit-language nil
   1041   "Discard src block language parameter in listings.
   1042 
   1043 Set this option to t to omit the \"language=\" in the parameters to
   1044 \"lstlisting\" environments when exporting an src block.
   1045 
   1046 This is necessary, for example, when the \"fancyvrb\" package is used
   1047 instead of \"listings\":
   1048 
   1049 #+LATEX_HEADER: \\RequirePackage{fancyvrb}
   1050 #+LATEX_HEADER: \\DefineVerbatimEnvironment{verbatim}{Verbatim}{...}
   1051 #+LATEX_HEADER: \\DefineVerbatimEnvironment{lstlisting}{Verbatim}{...}"
   1052   :group 'org-export-latex
   1053   :package-version '(Org . "9.7")
   1054   :type 'boolean
   1055   :safe #'booleanp)
   1056 
   1057 (defcustom org-latex-listings-options nil
   1058   "Association list of options for the latex listings package.
   1059 
   1060 These options are supplied as a comma-separated list to the
   1061 \\lstlisting command.  Each element of the association list should be
   1062 a list or cons cell containing two strings: the name of the
   1063 option, and the value.  For example,
   1064 
   1065   (setq org-latex-listings-options
   1066     \\='((\"basicstyle\" \"\\\\small\")
   1067       (\"keywordstyle\" \"\\\\color{black}\\\\bfseries\\\\underbar\")))
   1068   ; or
   1069   (setq org-latex-listings-options
   1070     \\='((\"basicstyle\" . \"\\\\small\")
   1071       (\"keywordstyle\" . \"\\\\color{black}\\\\bfseries\\\\underbar\")))
   1072 
   1073 will typeset the code in a small size font with underlined, bold
   1074 black keywords.
   1075 
   1076 Note that the same options will be applied to blocks of all
   1077 languages.  If you need block-specific options, you may use the
   1078 following syntax:
   1079 
   1080   #+ATTR_LATEX: :options key1=value1,key2=value2
   1081   #+BEGIN_SRC <LANG>
   1082   ...
   1083   #+END_SRC"
   1084   :group 'org-export-latex
   1085   :type '(repeat
   1086 	  (list
   1087 	   (string :tag "Listings option name ")
   1088 	   (string :tag "Listings option value"))))
   1089 
   1090 (defcustom org-latex-minted-langs
   1091   '((emacs-lisp "common-lisp")
   1092     (cc "c++")
   1093     (cperl "perl")
   1094     (shell-script "bash")
   1095     (caml "ocaml"))
   1096   "Alist mapping languages to their minted language counterpart.
   1097 The key is a symbol, the major mode symbol without the \"-mode\".
   1098 The value is the string that should be inserted as the language
   1099 parameter for the minted package.  If the mode name and the
   1100 listings name are the same, the language does not need an entry
   1101 in this list - but it does not hurt if it is present.
   1102 
   1103 Note that minted uses all lower case for language identifiers,
   1104 and that the full list of language identifiers can be obtained
   1105 with:
   1106 
   1107   pygmentize -L lexers"
   1108   :group 'org-export-latex
   1109   :type '(repeat
   1110 	  (list
   1111 	   (symbol :tag "Major mode     ")
   1112 	   (string :tag "Minted language"))))
   1113 
   1114 (defcustom org-latex-minted-options nil
   1115   "Association list of options for the latex minted package.
   1116 
   1117 These options are supplied within square brackets in
   1118 \\begin{minted} environments.  Each element of the alist should
   1119 be a list or cons cell containing two strings: the name of the
   1120 option, and the value.  For example,
   1121 
   1122   (setq org-latex-minted-options
   1123     \\='((\"bgcolor\" \"bg\") (\"frame\" \"lines\")))
   1124   ; or
   1125   (setq org-latex-minted-options
   1126     \\='((\"bgcolor\" . \"bg\") (\"frame\" . \"lines\")))
   1127 
   1128 will result in source blocks being exported with
   1129 
   1130 \\begin{minted}[bgcolor=bg,frame=lines]{<LANG>}
   1131 
   1132 as the start of the minted environment. Note that the same
   1133 options will be applied to blocks of all languages.  If you need
   1134 block-specific options, you may use the following syntax:
   1135 
   1136   #+ATTR_LATEX: :options key1=value1,key2=value2
   1137   #+BEGIN_SRC <LANG>
   1138   ...
   1139   #+END_SRC"
   1140   :group 'org-export-latex
   1141   :type '(repeat
   1142 	  (list
   1143 	   (string :tag "Minted option name ")
   1144 	   (string :tag "Minted option value"))))
   1145 
   1146 (defcustom org-latex-custom-lang-environments nil
   1147   "Alist mapping languages to language-specific LaTeX environments.
   1148 
   1149 It is used during export of source blocks by the listings and
   1150 minted LaTeX packages.  The environment may be a simple string,
   1151 composed of only letters and numbers.  In this case, the string
   1152 is directly the name of the LaTeX environment to use.  The
   1153 environment may also be a format string.  In this case the format
   1154 string will be directly exported.  This format string may contain
   1155 these elements:
   1156 
   1157   %s for the formatted source
   1158   %c for the caption
   1159   %f for the float attribute
   1160   %l for an appropriate label
   1161   %o for the LaTeX attributes
   1162 
   1163 For example,
   1164 
   1165   (setq org-latex-custom-lang-environments
   1166      \\='((python \"pythoncode\")
   1167        (ocaml \"\\\\begin{listing}
   1168 \\\\begin{minted}[%o]{ocaml}
   1169 %s\\\\end{minted}
   1170 \\\\caption{%c}
   1171 \\\\label{%l}\")))
   1172 
   1173 would have the effect that if Org encounters a Python source block
   1174 during LaTeX export it will produce
   1175 
   1176   \\begin{pythoncode}
   1177   <source block body>
   1178   \\end{pythoncode}
   1179 
   1180 and if Org encounters an Ocaml source block during LaTeX export it
   1181 will produce
   1182 
   1183   \\begin{listing}
   1184   \\begin{minted}[<attr_latex options>]{ocaml}
   1185   <source block body>
   1186   \\end{minted}
   1187   \\caption{<caption>}
   1188   \\label{<label>}
   1189   \\end{listing}"
   1190   :group 'org-export-latex
   1191   :type '(repeat
   1192 	  (list
   1193 	   (symbol :tag "Language name                    ")
   1194 	   (string :tag "Environment name or format string")))
   1195   :version "26.1"
   1196   :package-version '(Org . "9.0"))
   1197 
   1198 (defcustom org-latex-engraved-preamble
   1199   "\\usepackage{fvextra}
   1200 
   1201 [FVEXTRA-SETUP]
   1202 
   1203 % Make line numbers smaller and grey.
   1204 \\renewcommand\\theFancyVerbLine{\\footnotesize\\color{black!40!white}\\arabic{FancyVerbLine}}
   1205 
   1206 \\usepackage{xcolor}
   1207 
   1208 % In case engrave-faces-latex-gen-preamble has not been run.
   1209 \\providecolor{EfD}{HTML}{f7f7f7}
   1210 \\providecolor{EFD}{HTML}{28292e}
   1211 
   1212 % Define a Code environment to prettily wrap the fontified code.
   1213 \\usepackage[breakable,xparse]{tcolorbox}
   1214 \\DeclareTColorBox[]{Code}{o}%
   1215 {colback=EfD!98!EFD, colframe=EfD!95!EFD,
   1216   fontupper=\\footnotesize\\setlength{\\fboxsep}{0pt},
   1217   colupper=EFD,
   1218   IfNoValueTF={#1}%
   1219   {boxsep=2pt, arc=2.5pt, outer arc=2.5pt,
   1220     boxrule=0.5pt, left=2pt}%
   1221   {boxsep=2.5pt, arc=0pt, outer arc=0pt,
   1222     boxrule=0pt, leftrule=1.5pt, left=0.5pt},
   1223   right=2pt, top=1pt, bottom=0.5pt,
   1224   breakable}
   1225 
   1226 [LISTINGS-SETUP]"
   1227   "Preamble content injected when using engrave-faces-latex for source blocks.
   1228 This is relevant when `org-latex-src-block-backend' is set to `engraved'.
   1229 
   1230 There is quite a lot of flexibility in what this preamble can be,
   1231 as long as it:
   1232 - Loads the fvextra package.
   1233 - Loads the package xcolor (if it is not already loaded elsewhere).
   1234 - Defines a \"Code\" environment (note the capital C), which all
   1235   \"Verbatim\" environments (provided by fvextra) will be wrapped with.
   1236 
   1237 In the default value the colors \"EFD\" and \"EfD\" are provided
   1238 as they are respectively the foreground and background colors,
   1239 just in case they aren't provided by the generated preamble, so
   1240 we can assume they are always set.
   1241 
   1242 Within this preamble there are two recognized macro-like placeholders:
   1243 
   1244   [FVEXTRA-SETUP]
   1245 
   1246   [LISTINGS-SETUP]
   1247 
   1248 Unless you have a very good reason, both of these placeholders
   1249 should be included in the preamble.
   1250 
   1251 FVEXTRA-SETUP sets fvextra's defaults according to
   1252 `org-latex-engraved-options', and LISTINGS-SETUP creates the
   1253 listings environment used for captioned or floating code blocks,
   1254 as well as defining \\listoflistings."
   1255   :group 'org-export-latex
   1256   :type 'string
   1257   :package-version '(Org . "9.6"))
   1258 
   1259 (defcustom org-latex-engraved-options
   1260   '(("commandchars" . "\\\\\\{\\}")
   1261     ("highlightcolor" . "white!95!black!80!blue")
   1262     ("breaklines" . "true")
   1263     ("breaksymbol" . "\\color{white!60!black}\\tiny\\ensuremath{\\hookrightarrow}"))
   1264   "Association list of options for the latex fvextra package when engraving code.
   1265 
   1266 These options are set using \\fvset{...} in the preamble of the
   1267 LaTeX export.  Each element of the alist should be a list or cons
   1268 cell containing two strings: the name of the option, and the
   1269 value.  For example,
   1270 
   1271   (setq org-latex-engraved-options
   1272     \\='((\"highlightcolor\" \"green\") (\"frame\" \"lines\")))
   1273   ; or
   1274   (setq org-latex-engraved-options
   1275     \\='((\"highlightcolor\" . \"green\") (\"frame\" . \"lines\")))
   1276 
   1277 will result in the following LaTeX in the preamble
   1278 
   1279 \\fvset{%
   1280   bgcolor=bg,
   1281   frame=lines}
   1282 
   1283 This will affect all fvextra environments.  Note that the same
   1284 options will be applied to all blocks.  If you need
   1285 block-specific options, you may use the following syntax:
   1286 
   1287   #+ATTR_LATEX: :options key1=value1,key2=value2
   1288   #+BEGIN_SRC <LANG>
   1289   ...
   1290   #+END_SRC"
   1291   :group 'org-export-latex
   1292   :package-version '(Org . "9.6")
   1293   :type '(alist :key-type (string :tag "option")
   1294                 :value-type (string :tag "value")))
   1295 
   1296 (defcustom org-latex-engraved-theme nil
   1297   "The theme that should be used for engraved code, when non-nil.
   1298 This can be set to any theme defined in `engrave-faces-themes'
   1299 (from the engrave-faces package) or loadable by Emacs.  When set
   1300 to t, the current Emacs theme is used.  When nil, no theme is
   1301 applied."
   1302   :group 'org-export-latex
   1303   :package-version '(Org . "9.6")
   1304   :type 'symbol)
   1305 
   1306 (defun org-latex-generate-engraved-preamble (info)
   1307   "Generate the preamble to setup engraved code.
   1308 The result is constructed from the :latex-engraved-preamble and
   1309 :latex-engraved-options export options (passed via INFO plist), the
   1310 default values of which are given by `org-latex-engraved-preamble' and
   1311 `org-latex-engraved-options' respectively."
   1312   (let* ((engraved-options
   1313           (plist-get info :latex-engraved-options))
   1314          (engraved-preamble (plist-get info :latex-engraved-preamble))
   1315          (engraved-theme (plist-get info :latex-engraved-theme))
   1316          (engraved-themes
   1317           (mapcar
   1318            #'intern
   1319            (cl-delete-duplicates
   1320             (org-element-map
   1321                 (plist-get info :parse-tree)
   1322                 '(src-block inline-src-block)
   1323               (lambda (src)
   1324                 (plist-get
   1325                  (org-export-read-attribute :attr_latex src)
   1326                  :engraved-theme))
   1327               info))))
   1328          (gen-theme-spec
   1329           (lambda (theme)
   1330             (if (eq engrave-faces-latex-output-style 'preset)
   1331                 (engrave-faces-latex-gen-preamble theme)
   1332               (engrave-faces-latex-gen-preamble-line
   1333                'default
   1334                (alist-get 'default
   1335                           (if theme
   1336                               (engrave-faces-get-theme (intern theme))
   1337                             engrave-faces-current-preset-style)))))))
   1338     (when (stringp engraved-theme)
   1339       (setq engraved-theme (intern engraved-theme)))
   1340     (when (string-match "^[ \t]*\\[FVEXTRA-SETUP\\][ \t]*\n?" engraved-preamble)
   1341       (setq engraved-preamble
   1342             (replace-match
   1343              (concat
   1344               "\\fvset{%\n  "
   1345               (org-latex--make-option-string engraved-options ",\n  ")
   1346               "}\n")
   1347              t t
   1348              engraved-preamble)))
   1349     (when (string-match "^[ \t]*\\[LISTINGS-SETUP\\][ \t]*\n?" engraved-preamble)
   1350       (setq engraved-preamble
   1351             (replace-match
   1352              (format
   1353               "%% Support listings with captions
   1354 \\usepackage{float}
   1355 \\floatstyle{%s}
   1356 \\newfloat{listing}{htbp}{lst}
   1357 \\newcommand{\\listingsname}{Listing}
   1358 \\floatname{listing}{\\listingsname}
   1359 \\newcommand{\\listoflistingsname}{List of Listings}
   1360 \\providecommand{\\listoflistings}{\\listof{listing}{\\listoflistingsname}}\n"
   1361               (if (org-latex--caption-above-p
   1362                    (org-element-create 'src-block) info)
   1363                   "plaintop" "plain"))
   1364              t t
   1365              engraved-preamble)))
   1366     (concat
   1367      "\n% Setup for code blocks [1/2]\n\n"
   1368      engraved-preamble
   1369      "\n\n% Setup for code blocks [2/2]: syntax highlighting colors\n\n"
   1370      (if (require 'engrave-faces-latex nil t)
   1371          (if engraved-themes
   1372              (concat
   1373               (mapconcat
   1374                (lambda (theme)
   1375                  (format
   1376                   "\n\\newcommand{\\engravedtheme%s}{%%\n%s\n}"
   1377                   (replace-regexp-in-string "[^A-Za-z]" "" (symbol-name theme))
   1378                   (replace-regexp-in-string
   1379                    "newcommand" "renewcommand"
   1380                    (replace-regexp-in-string
   1381                     "#" "##"
   1382                     (funcall gen-theme-spec theme)))))
   1383                engraved-themes
   1384                "\n")
   1385               "\n\n"
   1386               (cond
   1387                ((memq engraved-theme engraved-themes)
   1388                 (concat "\\engravedtheme"
   1389                         (replace-regexp-in-string
   1390                          "[^A-Za-z]" "" engraved-theme)
   1391                         "\n"))
   1392                (t (funcall gen-theme-spec engraved-theme))))
   1393            (funcall gen-theme-spec engraved-theme))
   1394        (warn "Cannot engrave source blocks.  Consider installing `engrave-faces'.")
   1395        "% WARNING syntax highlighting unavailable as engrave-faces-latex was missing.\n")
   1396      "\n")))
   1397 
   1398 ;;;; Compilation
   1399 
   1400 (defcustom org-latex-compiler-file-string "%% Intended LaTeX compiler: %s\n"
   1401   "LaTeX compiler format-string.
   1402 See also `org-latex-compiler'."
   1403   :group 'org-export-latex
   1404   :type '(choice
   1405 	  (const :tag "Comment" "%% Intended LaTeX compiler: %s\n")
   1406 	  (const :tag "latex-mode file variable" "%% -*- latex-run-command: %s -*-\n")
   1407 	  (const :tag "AUCTeX file variable" "%% -*- LaTeX-command: %s -*-\n")
   1408 	  (string :tag "custom format" "%% %s"))
   1409   :version "26.1"
   1410   :package-version '(Org . "9.0"))
   1411 
   1412 (defcustom org-latex-compiler "pdflatex"
   1413   "LaTeX compiler to use.
   1414 
   1415 Must be an element in `org-latex-compilers' or the empty quote.
   1416 Can also be set in buffers via #+LATEX_COMPILER.  See also
   1417 `org-latex-compiler-file-string'."
   1418   :group 'org-export-latex
   1419   :type '(choice
   1420 	  (const :tag "pdfLaTeX" "pdflatex")
   1421 	  (const :tag "XeLaTeX"  "xelatex")
   1422 	  (const :tag "LuaLaTeX" "lualatex")
   1423 	  (const :tag "Unset" ""))
   1424   :version "26.1"
   1425   :package-version '(Org . "9.0"))
   1426 
   1427 (defconst org-latex-compilers '("pdflatex" "xelatex" "lualatex")
   1428   "Known LaTeX compilers.
   1429 See also `org-latex-compiler'.")
   1430 
   1431 (defcustom org-latex-bib-compiler "bibtex"
   1432   "Command to process a LaTeX file's bibliography.
   1433 
   1434 The shorthand %bib in `org-latex-pdf-process' is replaced with
   1435 this value.
   1436 
   1437 A better approach is to use a compiler suit such as `latexmk'."
   1438   :group 'org-export-latex
   1439   :type '(choice (const :tag "BibTeX" "bibtex")
   1440 		 (const :tag "Biber" "biber")
   1441 		 (string :tag "Other process"))
   1442   :version "26.1"
   1443   :package-version '(Org . "9.0"))
   1444 
   1445 (defcustom org-latex-pdf-process
   1446   (if (executable-find "latexmk")
   1447       '("latexmk -f -pdf -%latex -interaction=nonstopmode -output-directory=%o %f")
   1448     '("%latex -interaction nonstopmode -output-directory %o %f"
   1449       "%latex -interaction nonstopmode -output-directory %o %f"
   1450       "%latex -interaction nonstopmode -output-directory %o %f"))
   1451   "Commands to process a LaTeX file to a PDF file.
   1452 
   1453 The command output will be parsed to extract compilation errors and
   1454 warnings according to `org-latex-known-warnings'.
   1455 
   1456 This is a list of strings, each of them will be given to the
   1457 shell as a command.  %f in the command will be replaced by the
   1458 relative file name, %F by the absolute file name, %b by the file
   1459 base name (i.e. without directory and extension parts), %o by the
   1460 base directory of the file, %O by the absolute file name of the
   1461 output file, %latex is the LaTeX compiler (see
   1462 `org-latex-compiler'), and %bib is the BibTeX-like compiler (see
   1463 `org-latex-bib-compiler').
   1464 
   1465 The reason why this is a list is that it usually takes several
   1466 runs of `pdflatex', maybe mixed with a call to `bibtex'.  Org
   1467 does not have a clever mechanism to detect which of these
   1468 commands have to be run to get to a stable result, and it also
   1469 does not do any error checking.
   1470 
   1471 Consider a smart LaTeX compiler such as `texi2dvi' or `latexmk',
   1472 which calls the \"correct\" combinations of auxiliary programs.
   1473 
   1474 Alternatively, this may be a Lisp function that does the
   1475 processing, so you could use this to apply the machinery of
   1476 AUCTeX or the Emacs LaTeX mode.  This function should accept the
   1477 file name as its single argument."
   1478   :group 'org-export-latex
   1479   :type '(choice
   1480 	  (repeat :tag "Shell command sequence"
   1481 		  (string :tag "Shell command"))
   1482 	  (const :tag "2 runs of latex"
   1483 		 ("%latex -interaction nonstopmode -output-directory %o %f"
   1484 		  "%latex -interaction nonstopmode -output-directory %o %f"))
   1485 	  (const :tag "3 runs of latex"
   1486 		 ("%latex -interaction nonstopmode -output-directory %o %f"
   1487 		  "%latex -interaction nonstopmode -output-directory %o %f"
   1488 		  "%latex -interaction nonstopmode -output-directory %o %f"))
   1489 	  (const :tag "latex,bibtex,latex,latex"
   1490 		 ("%latex -interaction nonstopmode -output-directory %o %f"
   1491 		  "%bib %b"
   1492 		  "%latex -interaction nonstopmode -output-directory %o %f"
   1493 		  "%latex -interaction nonstopmode -output-directory %o %f"))
   1494 	  (const :tag "texi2dvi"
   1495 		 ("cd %o; LATEX=\"%latex\" texi2dvi -p -b -V %b.tex"))
   1496 	  (const :tag "latexmk"
   1497 		 ("latexmk -f -pdf -%latex -interaction=nonstopmode -output-directory=%o %f"))
   1498 	  (function)))
   1499 
   1500 (defcustom org-latex-logfiles-extensions
   1501   '("aux" "bcf" "blg" "fdb_latexmk" "fls" "figlist" "idx" "log" "nav" "out"
   1502     "ptc" "run.xml" "snm" "toc" "vrb" "xdv")
   1503   "The list of file extensions to consider as LaTeX logfiles.
   1504 The logfiles will be removed if `org-latex-remove-logfiles' is
   1505 non-nil."
   1506   :group 'org-export-latex
   1507   :version "26.1"
   1508   :package-version '(Org . "8.3")
   1509   :type '(repeat (string :tag "Extension")))
   1510 
   1511 (defcustom org-latex-remove-logfiles t
   1512   "Non-nil means remove the logfiles produced by PDF production.
   1513 By default, logfiles are files with these extensions: .aux, .idx,
   1514 .log, .out, .toc, .nav, .snm and .vrb.  To define the set of
   1515 logfiles to remove, set `org-latex-logfiles-extensions'."
   1516   :group 'org-export-latex
   1517   :type 'boolean)
   1518 
   1519 (defcustom org-latex-known-warnings
   1520   '(("Reference.*?undefined" . "[undefined reference]")
   1521     ("Runaway argument" . "[runaway argument]")
   1522     ("Underfull \\hbox" . "[underfull hbox]")
   1523     ("Overfull \\hbox" . "[overfull hbox]")
   1524     ("Citation.*?undefined" . "[undefined citation]")
   1525     ("^!.+Unicode character" . "[unicode character(s) not set up for use with pdflatex. You can run lualatex or xelatex instead]")
   1526     ("Missing character: There is no" . "[Missing character(s): please load an appropriate font with the fontspec package]")
   1527     ("Undefined control sequence" . "[undefined control sequence]"))
   1528   "Alist of regular expressions and associated messages for the user.
   1529 The regular expressions are used to find possible warnings in the
   1530 log of a LaTeX-run.  These warnings will be reported after
   1531 calling `org-latex-compile'."
   1532   :group 'org-export-latex
   1533   :package-version '(Org . "9.7")
   1534   :type '(repeat
   1535 	  (cons
   1536 	   (regexp :tag "Regexp")
   1537 	   (string :tag "Message"))))
   1538 
   1539 
   1540 
   1541 ;;; Internal Functions
   1542 
   1543 (defun org-latex--caption-above-p (element info)
   1544   "Non-nil when caption is expected to be located above ELEMENT.
   1545 INFO is a plist holding contextual information."
   1546   (let ((above (plist-get info :latex-caption-above)))
   1547     (if (symbolp above) above
   1548       (let ((type (org-element-type element)))
   1549 	(memq (if (eq type 'link) 'image type) above)))))
   1550 
   1551 (defun org-latex--label (datum info &optional force full)
   1552   "Return an appropriate label for DATUM.
   1553 DATUM is an element or a `target' type object.  INFO is the
   1554 current export state, as a plist.
   1555 
   1556 Return nil if element DATUM has no NAME or VALUE affiliated
   1557 keyword or no CUSTOM_ID property, unless FORCE is non-nil.  In
   1558 this case always return a unique label.
   1559 
   1560 Eventually, if FULL is non-nil, wrap label within \"\\label{}\"."
   1561   (let* ((type (org-element-type datum))
   1562 	 (user-label
   1563           (cl-case type
   1564 	    ((headline inlinetask) (org-element-property :CUSTOM_ID datum))
   1565 	    (target (org-element-property :value datum))
   1566 	    (otherwise (or (org-element-property :name datum)
   1567                            (car (org-element-property :results datum))))))
   1568 	 (label
   1569 	  (and (or user-label force)
   1570 	       (if (and user-label (plist-get info :latex-prefer-user-labels))
   1571 		   user-label
   1572 		 (concat (pcase type
   1573 			   (`headline "sec:")
   1574 			   (`table "tab:")
   1575 			   (`latex-environment
   1576 			    (and (string-match-p
   1577 				  org-latex-math-environments-re
   1578 				  (org-element-property :value datum))
   1579 				 "eq:"))
   1580 			   (`latex-matrices "eq:")
   1581 			   (`paragraph
   1582 			    (and (org-element-property :caption datum)
   1583 				 "fig:"))
   1584                            (`src-block "lst:")
   1585 			   (_ nil))
   1586 			 (org-export-get-reference datum info))))))
   1587     (cond ((not full) label)
   1588 	  (label (format "\\label{%s}%s"
   1589 			 label
   1590 			 (if (eq type 'target) "" "\n")))
   1591 	  (t ""))))
   1592 
   1593 (defun org-latex--caption/label-string (element info)
   1594   "Return caption and label LaTeX string for ELEMENT.
   1595 
   1596 INFO is a plist holding contextual information.  If there's no
   1597 caption nor label, return the empty string.
   1598 
   1599 For non-floats, see `org-latex--wrap-label'."
   1600   (let* ((label (org-latex--label element info nil t))
   1601 	 (main (org-export-get-caption element))
   1602 	 (attr (org-export-read-attribute :attr_latex element))
   1603 	 (type (org-element-type element))
   1604 	 (nonfloat (or (and (plist-member attr :float)
   1605 			    (not (plist-get attr :float))
   1606 			    main)
   1607 		       (and (eq type 'src-block)
   1608 			    (not (plist-get attr :float))
   1609 			    (memq (plist-get info :latex-src-block-backend)
   1610                                   '(verbatim nil)))))
   1611 	 (short (org-export-get-caption element t))
   1612 	 (caption-from-attr-latex (plist-get attr :caption)))
   1613     (cond
   1614      ((org-string-nw-p caption-from-attr-latex)
   1615       (concat caption-from-attr-latex "\n"))
   1616      ((and (not main) (equal label "")) "")
   1617      ((not main) label)
   1618      ;; Option caption format with short name.
   1619      (t
   1620       (format (if nonfloat "\\captionof{%s}%s{%s%s}\n"
   1621 		"\\caption%s%s{%s%s}\n")
   1622 	      (let ((type* (if (eq type 'latex-environment)
   1623 			       (org-latex--environment-type element)
   1624 			     type)))
   1625                 ;; \captionof{%s}
   1626                 ;; %s must be a registered LaTeX environment.
   1627                 ;; figure is always there, while listing is defined by
   1628                 ;; additional packages.
   1629                 ;; See https://list.orgmode.org/orgmode/87twtovkjh.fsf@gmx.us/
   1630 		(if nonfloat
   1631 		    (cl-case type*
   1632 		      (paragraph "figure")
   1633 		      (image "figure")
   1634 		      (special-block "figure")
   1635 		      (src-block (if (not (memq (plist-get info :latex-src-block-backend)
   1636                                                 '(verbatim nil)))
   1637 				     "listing"
   1638 				   "figure"))
   1639 		      (t (symbol-name type*)))
   1640 		  ""))
   1641 	      (if short (format "[%s]" (org-export-data short info)) "")
   1642 	      (org-trim label)
   1643 	      (org-export-data main info))))))
   1644 
   1645 (defun org-latex-guess-inputenc (header)
   1646   "Set the coding system in inputenc to what the buffer is.
   1647 
   1648 HEADER is the LaTeX header string.  This function only applies
   1649 when specified inputenc option is \"AUTO\".
   1650 
   1651 Return the new header, as a string."
   1652   (let* ((cs (or (ignore-errors
   1653 		   (latexenc-coding-system-to-inputenc
   1654 		    (or org-export-coding-system buffer-file-coding-system)))
   1655 		 "utf8")))
   1656     (if (not cs) header
   1657       ;; First translate if that is requested.
   1658       (setq cs (or (cdr (assoc cs org-latex-inputenc-alist)) cs))
   1659       ;; Then find the \usepackage statement and replace the option.
   1660       (replace-regexp-in-string "\\\\usepackage\\[\\(AUTO\\)\\]{inputenc}"
   1661 				cs header t nil 1))))
   1662 
   1663 (defun org-latex-guess-babel-language (header info)
   1664   "Set Babel's language according to LANGUAGE keyword.
   1665 
   1666 HEADER is the LaTeX header string.  INFO is the plist used as
   1667 a communication channel.
   1668 
   1669 Insertion of guessed language only happens when Babel package has
   1670 explicitly been loaded.  Then it is added to the rest of
   1671 package's options.
   1672 
   1673 The optional argument to Babel or the mandatory argument to
   1674 `\\babelprovide' command may be \"AUTO\" which is then replaced
   1675 with the language of the document or
   1676 `org-export-default-language' unless language in question is
   1677 already loaded.
   1678 
   1679 Return the new header."
   1680   (let* ((language-code (plist-get info :language))
   1681 	 (plist (cdr
   1682 		 (assoc language-code org-latex-language-alist)))
   1683 	 (language (plist-get plist :babel))
   1684 	 (language-ini-only (plist-get plist :babel-ini-only))
   1685          (language-ini-alt (plist-get plist :babel-ini-alt))
   1686 	 ;; If no language is set, or Babel package is not loaded, or
   1687 	 ;; LANGUAGE keyword value is a language served by Babel
   1688 	 ;; exclusively through ini files, return HEADER as-is.
   1689 	 (header (if (or language-ini-only
   1690 			 (not (stringp language-code))
   1691 			 (not (string-match "\\\\usepackage\\[\\(.*\\)\\]{babel}" header)))
   1692 		     header
   1693 		   (let ((options (save-match-data
   1694 				    (org-split-string (match-string 1 header) ",[ \t]*"))))
   1695 		     ;; If LANGUAGE is already loaded, return header
   1696 		     ;; without AUTO.  Otherwise, replace AUTO with language or
   1697 		     ;; append language if AUTO is not present.  Languages that are
   1698 		     ;; served in Babel exclusively through ini files are not added
   1699 		     ;; to the babel argument, and must be loaded using
   1700 		     ;; `\babelprovide'.
   1701 		     (replace-match
   1702 		      (mapconcat (lambda (option) (if (equal "AUTO" option) language option))
   1703 				 (cond ((member language options) (delete "AUTO" options))
   1704 				       ((member "AUTO" options) options)
   1705 				       (t (append options (list language))))
   1706 				 ", ")
   1707 		      t nil header 1)))))
   1708     ;; If `\babelprovide[args]{AUTO}' is present, AUTO is
   1709     ;; replaced by LANGUAGE.
   1710     (if (not (string-match "\\\\babelprovide\\[.*\\]{\\(.+\\)}" header))
   1711 	header
   1712       (let ((prov (match-string 1 header)))
   1713 	(if (equal "AUTO" prov)
   1714 	    (replace-regexp-in-string (format
   1715 				       "\\(\\\\babelprovide\\[.*\\]\\)\\({\\)%s}" prov)
   1716 				      (format "\\1\\2%s}"
   1717 					      (if language-ini-alt language-ini-alt
   1718                                                 (or language language-ini-only)))
   1719 				      header t)
   1720 	  header)))))
   1721 
   1722 (defun org-latex-guess-polyglossia-language (header info)
   1723   "Set the Polyglossia language according to the LANGUAGE keyword.
   1724 
   1725 HEADER is the LaTeX header string.  INFO is the plist used as
   1726 a communication channel.
   1727 
   1728 Insertion of guessed language only happens when the Polyglossia
   1729 package has been explicitly loaded.
   1730 
   1731 The argument to Polyglossia may be \"AUTO\" which is then
   1732 replaced with the language of the document or
   1733 `org-export-default-language'.  Note, the language is really set
   1734 using \setdefaultlanguage and not as an option to the package.
   1735 
   1736 Return the new header."
   1737   (let* ((language (plist-get info :language)))
   1738     ;; If no language is set or Polyglossia is not loaded, return
   1739     ;; HEADER as-is.
   1740     (if (or (not (stringp language))
   1741 	    (not (string-match
   1742 		  "\\\\usepackage\\(?:\\[\\([^]]+?\\)\\]\\){polyglossia}\n"
   1743 		  header)))
   1744 	header
   1745       (let* ((options (org-string-nw-p (match-string 1 header)))
   1746 	     (languages (and options
   1747 			     ;; Reverse as the last loaded language is
   1748 			     ;; the main language.
   1749 			     (nreverse
   1750 			      (delete-dups
   1751 			       (save-match-data
   1752 				 (org-split-string
   1753 				  (replace-regexp-in-string
   1754 				   "AUTO" language options t)
   1755 				  ",[ \t]*"))))))
   1756 	     (main-language-set
   1757 	      (string-match-p "\\\\setmainlanguage{.*?}" header)))
   1758 	(replace-match
   1759 	 (concat "\\usepackage{polyglossia}\n"
   1760 		 (mapconcat
   1761 		  (lambda (l)
   1762 		    (let* ((plist (cdr
   1763 				   (assoc language org-latex-language-alist)))
   1764 			   (polyglossia-variant (plist-get plist :polyglossia-variant))
   1765 			   (polyglossia-lang (plist-get plist :polyglossia))
   1766 			   (l (if (equal l language)
   1767 				  polyglossia-lang
   1768 				l)))
   1769 		      (format (if main-language-set (format "\\setotherlanguage{%s}\n" l)
   1770 				(setq main-language-set t)
   1771 				"\\setmainlanguage%s{%s}\n")
   1772 			      (if polyglossia-variant
   1773 				  (format "[variant=%s]" polyglossia-variant)
   1774 				"")
   1775 			      l)))
   1776 		  languages
   1777 		  ""))
   1778 	 t t header 0)))))
   1779 
   1780 (defun org-latex--remove-packages (pkg-alist info)
   1781   "Remove packages based on the current LaTeX compiler.
   1782 
   1783 PKG-ALIST is a list of packages, as in `org-latex-packages-alist'
   1784 and `org-latex-default-packages-alist'.  If the fourth argument
   1785 of a package is neither nil nor a member of the LaTeX compiler
   1786 associated to the document, the package is removed.
   1787 
   1788 LaTeX compiler is defined in :latex-compiler INFO plist entry.
   1789 
   1790 Return new list of packages."
   1791   (let ((compiler (or (plist-get info :latex-compiler) "")))
   1792     (if (not (member-ignore-case compiler org-latex-compilers)) pkg-alist
   1793       (cl-remove-if-not
   1794        (lambda (package)
   1795 	 (pcase package
   1796 	   (`(,_ ,_ ,_ nil) t)
   1797 	   (`(,_ ,_ ,_ ,compilers) (member-ignore-case compiler compilers))
   1798 	   (_ t)))
   1799        pkg-alist))))
   1800 
   1801 (defun org-latex--find-verb-separator (s)
   1802   "Return a character not used in string S.
   1803 This is used to choose a separator for constructs like \\verb."
   1804   (let ((ll "~,./?;':\"|!@#%^&-_=+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ<>()[]{}"))
   1805     (cl-loop for c across ll
   1806 	     when (not (string-match (regexp-quote (char-to-string c)) s))
   1807 	     return (char-to-string c))))
   1808 
   1809 (defun org-latex--make-option-string (options &optional separator)
   1810   "Return a comma or SEPARATOR separated string of keywords and values.
   1811 OPTIONS is an alist where the key is the options keyword as
   1812 a string, and the value a list containing the keyword value, or
   1813 nil."
   1814   (mapconcat (lambda (pair)
   1815                (let ((keyword (car pair))
   1816                      (value (pcase (cdr pair)
   1817                               ((pred stringp) (cdr pair))
   1818                               ((pred consp) (cadr pair)))))
   1819                  (concat keyword
   1820                          (when value
   1821                            (concat "="
   1822                                    (if (string-match-p (rx (any "[]")) value)
   1823                                        (format "{%s}" value)
   1824                                      value))))))
   1825              options
   1826              (or separator ",")))
   1827 
   1828 (defun org-latex--wrap-label (element output info)
   1829   "Wrap label associated to ELEMENT around OUTPUT, if appropriate.
   1830 INFO is the current export state, as a plist.  This function
   1831 should not be used for floats.  See
   1832 `org-latex--caption/label-string'."
   1833   (let ((label (org-latex--label element info)))
   1834     (if (not (and (org-string-nw-p output) label))
   1835         output
   1836       (concat (format "\\phantomsection\n\\label{%s}\n" label)
   1837 	      output))))
   1838 
   1839 (defun org-latex--protect-text (text)
   1840   "Protect special characters in string TEXT and return it."
   1841   (replace-regexp-in-string "[\\{}$%&_#~^]" "\\\\\\&" text))
   1842 
   1843 (defun org-latex--text-markup (text markup info)
   1844   "Format TEXT depending on MARKUP text markup.
   1845 INFO is a plist used as a communication channel.  See
   1846 `org-latex-text-markup-alist' for details."
   1847   (let ((fmt (cdr (assq markup (plist-get info :latex-text-markup-alist)))))
   1848     (cl-case fmt
   1849       ;; No format string: Return raw text.
   1850       ((nil) text)
   1851       ;; Handle the `verb' special case: Find an appropriate separator
   1852       ;; and use "\\verb" command.
   1853       (verb
   1854        (let ((separator (org-latex--find-verb-separator text)))
   1855 	 (concat "\\verb"
   1856 		 separator
   1857 		 (replace-regexp-in-string "\n" " " text)
   1858 		 separator)))
   1859       (protectedtexttt (org-latex--protect-texttt text))
   1860       ;; Else use format string.
   1861       (t (format fmt text)))))
   1862 
   1863 (defun org-latex--protect-texttt (text)
   1864   "Protect special chars, then wrap TEXT in \"\\texttt{}\"."
   1865   (format "\\texttt{%s}"
   1866           (replace-regexp-in-string
   1867            "--\\|<<\\|>>\\|[\\{}$%&_#~^]"
   1868            (lambda (m)
   1869              (cond ((equal m "--") "-{}-{}")
   1870                    ((equal m "<<") "<{}<{}")
   1871                    ((equal m ">>") ">{}>{}")
   1872                    ((equal m "\\") "\\textbackslash{}")
   1873                    ((equal m "~") "\\textasciitilde{}")
   1874                    ((equal m "^") "\\textasciicircum{}")
   1875                    (t (org-latex--protect-text m))))
   1876            text nil t)))
   1877 
   1878 (defun org-latex--delayed-footnotes-definitions (element info)
   1879   "Return footnotes definitions in ELEMENT as a string.
   1880 
   1881 INFO is a plist used as a communication channel.
   1882 
   1883 Footnotes definitions are returned within \"\\footnotetext{}\"
   1884 commands.
   1885 
   1886 This function is used within constructs that don't support
   1887 \"\\footnote{}\" command (e.g., an item tag).  In that case,
   1888 \"\\footnotemark\" is used within the construct and the function
   1889 just outside of it."
   1890   (mapconcat
   1891    (lambda (ref)
   1892      (let ((def (org-export-get-footnote-definition ref info)))
   1893        (format "\\footnotetext[%d]{%s%s}"
   1894 	       (org-export-get-footnote-number ref info)
   1895 	       (org-trim (org-latex--label def info t t))
   1896 	       (org-trim (org-export-data def info)))))
   1897    ;; Find every footnote reference in ELEMENT.
   1898    (letrec ((all-refs nil)
   1899 	    (search-refs
   1900 	     (lambda (data)
   1901 	       ;; Return a list of all footnote references never seen
   1902 	       ;; before in DATA.
   1903 	       (org-element-map data 'footnote-reference
   1904 		 (lambda (ref)
   1905 		   (when (org-export-footnote-first-reference-p ref info)
   1906 		     (push ref all-refs)
   1907 		     (when (eq (org-element-property :type ref) 'standard)
   1908 		       (funcall search-refs
   1909 				(org-export-get-footnote-definition ref info)))))
   1910 		 info)
   1911 	       (reverse all-refs))))
   1912      (funcall search-refs element))
   1913    ""))
   1914 
   1915 (defun org-latex--translate (s info)
   1916   "Translate string S according to specified language.
   1917 INFO is a plist used as a communication channel."
   1918   (org-export-translate s :latex info))
   1919 
   1920 (defun org-latex--format-spec (info)
   1921   "Create a format spec for document meta-data.
   1922 INFO is a plist used as a communication channel."
   1923   (let ((language (let* ((lang (plist-get info :language))
   1924 		         (plist (cdr
   1925 			         (assoc lang org-latex-language-alist))))
   1926                     ;; Here the actual name of the LANGUAGE or LANG is used.
   1927 		    (or (plist-get plist :lang-name)
   1928 		        lang))))
   1929     `((?a . ,(org-export-data (plist-get info :author) info))
   1930       (?t . ,(org-export-data (plist-get info :title) info))
   1931       (?s . ,(org-export-data (plist-get info :subtitle) info))
   1932       (?k . ,(org-export-data (org-latex--wrap-latex-math-block
   1933 			       (plist-get info :keywords) info)
   1934 			      info))
   1935       (?d . ,(org-export-data (org-latex--wrap-latex-math-block
   1936 			       (plist-get info :description) info)
   1937 			      info))
   1938       (?c . ,(plist-get info :creator))
   1939       (?l . ,language)
   1940       (?L . ,(capitalize language))
   1941       (?D . ,(org-export-data (org-export-get-date info) info)))))
   1942 
   1943 (defun org-latex--insert-compiler (info)
   1944   "Insert LaTeX_compiler info into the document.
   1945 INFO is a plist used as a communication channel."
   1946   (let ((compiler (plist-get info :latex-compiler)))
   1947     (and (org-string-nw-p org-latex-compiler-file-string)
   1948 	 (member (or compiler "") org-latex-compilers)
   1949 	 (format org-latex-compiler-file-string compiler))))
   1950 
   1951 
   1952 ;;; Filters
   1953 
   1954 (defun org-latex-matrices-tree-filter (tree _backend info)
   1955   (org-latex--wrap-latex-matrices tree info))
   1956 
   1957 (defun org-latex-math-block-tree-filter (tree _backend info)
   1958   (org-latex--wrap-latex-math-block tree info))
   1959 
   1960 (defun org-latex-math-block-options-filter (info _backend)
   1961   (dolist (prop '(:author :date :title) info)
   1962     (plist-put info prop
   1963 	       (org-latex--wrap-latex-math-block (plist-get info prop) info))))
   1964 
   1965 (defun org-latex-clean-invalid-line-breaks (data _backend _info)
   1966   (replace-regexp-in-string
   1967    "\\(\\\\end{[A-Za-z0-9*]+}\\|^\\)[ \t]*\\\\\\\\[ \t]*$" "\\1"
   1968    data))
   1969 
   1970 
   1971 ;;; Template
   1972 
   1973 ;;;###autoload
   1974 (defun org-latex-make-preamble (info &optional template snippet?)
   1975   "Return a formatted LaTeX preamble.
   1976 INFO is a plist used as a communication channel.  Optional
   1977 argument TEMPLATE, when non-nil, is the header template string,
   1978 as expected by `org-splice-latex-header'.  When SNIPPET? is
   1979 non-nil, only includes packages relevant to image generation, as
   1980 specified in `org-latex-default-packages-alist' or
   1981 `org-latex-packages-alist'."
   1982   (let* ((class (plist-get info :latex-class))
   1983 	 (class-template
   1984 	  (or template
   1985 	      (let* ((class-options (plist-get info :latex-class-options))
   1986 		     (header (nth 1 (assoc class (plist-get info :latex-classes)))))
   1987 		(and (stringp header)
   1988 		     (if (not class-options) header
   1989 		       (replace-regexp-in-string
   1990 			"^[ \t]*\\\\documentclass\\(\\(\\[[^]]*\\]\\)?\\)"
   1991 			class-options header t nil 1))))
   1992 	      (user-error "Unknown LaTeX class `%s'" class))))
   1993     (org-latex-guess-polyglossia-language
   1994      (org-latex-guess-babel-language
   1995       (org-latex-guess-inputenc
   1996        (org-element-normalize-string
   1997 	(org-splice-latex-header
   1998 	 class-template
   1999 	 (org-latex--remove-packages org-latex-default-packages-alist info)
   2000 	 (org-latex--remove-packages org-latex-packages-alist info)
   2001 	 snippet?
   2002 	 (mapconcat #'org-element-normalize-string
   2003 		    (list (plist-get info :latex-header)
   2004 			  (and (not snippet?)
   2005 			       (plist-get info :latex-header-extra)))
   2006 		    ""))))
   2007       info)
   2008      info)))
   2009 
   2010 (defun org-latex-template (contents info)
   2011   "Return complete document string after LaTeX conversion.
   2012 CONTENTS is the transcoded contents string.  INFO is a plist
   2013 holding export options."
   2014   (let ((title (org-export-data (plist-get info :title) info))
   2015 	(spec (org-latex--format-spec info)))
   2016     (concat
   2017      ;; Timestamp.
   2018      (and (plist-get info :time-stamp-file)
   2019 	  (format-time-string "%% Created %Y-%m-%d %a %H:%M\n"))
   2020      ;; LaTeX compiler.
   2021      (org-latex--insert-compiler info)
   2022      ;; Document class and packages.
   2023      (org-latex-make-preamble info)
   2024      ;; Possibly limit depth for headline numbering.
   2025      (let ((sec-num (plist-get info :section-numbers)))
   2026        (when (integerp sec-num)
   2027 	 (format "\\setcounter{secnumdepth}{%d}\n" sec-num)))
   2028      ;; Author.
   2029      (let ((author (and (plist-get info :with-author)
   2030 			(let ((auth (plist-get info :author)))
   2031 			  (and auth (org-export-data auth info)))))
   2032 	   (email (and (plist-get info :with-email)
   2033 		       (org-export-data (plist-get info :email) info))))
   2034        (cond ((and author email (not (string= "" email)))
   2035 	      (format "\\author{%s\\thanks{%s}}\n" author email))
   2036 	     ((or author email) (format "\\author{%s}\n" (or author email)))))
   2037      ;; Date.
   2038      ;; LaTeX displays today's date by default. One can override this by
   2039      ;; inserting \date{} for no date, or \date{string} with any other
   2040      ;; string to be displayed as the date.
   2041      (let ((date (and (plist-get info :with-date) (org-export-get-date info))))
   2042        (format "\\date{%s}\n" (org-export-data date info)))
   2043      ;; Title and subtitle.
   2044      (let* ((subtitle (plist-get info :subtitle))
   2045 	    (formatted-subtitle
   2046 	     (when subtitle
   2047 	       (format (plist-get info :latex-subtitle-format)
   2048 		       (org-export-data subtitle info))))
   2049 	    (separate (plist-get info :latex-subtitle-separate)))
   2050        (concat
   2051 	(format "\\title{%s%s}\n" title
   2052 		(if separate "" (or formatted-subtitle "")))
   2053 	(when (and separate subtitle)
   2054 	  (concat formatted-subtitle "\n"))))
   2055      ;; Hyperref options.
   2056      (let ((template (plist-get info :latex-hyperref-template)))
   2057        (and (stringp template)
   2058             (format-spec template spec)))
   2059      ;; engrave-faces-latex preamble
   2060      (when (and (eq (plist-get info :latex-src-block-backend) 'engraved)
   2061                 (org-element-map (plist-get info :parse-tree)
   2062                     '(src-block inline-src-block) #'identity
   2063                     info t))
   2064        (org-latex-generate-engraved-preamble info))
   2065      ;; Document start.
   2066      "\\begin{document}\n\n"
   2067      ;; Title command.
   2068      (let* ((title-command (plist-get info :latex-title-command))
   2069             (command (and (stringp title-command)
   2070                           (format-spec title-command spec))))
   2071        (org-element-normalize-string
   2072 	(cond ((not (plist-get info :with-title)) nil)
   2073 	      ((string= "" title) nil)
   2074 	      ((not (stringp command)) nil)
   2075 	      ((string-match "\\(?:[^%]\\|^\\)%s" command)
   2076 	       (format command title))
   2077 	      (t command))))
   2078      ;; Table of contents.
   2079      (let ((depth (plist-get info :with-toc)))
   2080        (when depth
   2081 	 (concat (when (integerp depth)
   2082 		   (format "\\setcounter{tocdepth}{%d}\n" depth))
   2083 		 (plist-get info :latex-toc-command))))
   2084      ;; Document's body.
   2085      contents
   2086      ;; Creator.
   2087      (and (plist-get info :with-creator)
   2088 	  (concat (plist-get info :creator) "\n"))
   2089      ;; Document end.
   2090      "\\end{document}")))
   2091 
   2092 
   2093 
   2094 ;;; Transcode Functions
   2095 
   2096 ;;;; Bold
   2097 
   2098 (defun org-latex-bold (_bold contents info)
   2099   "Transcode BOLD from Org to LaTeX.
   2100 CONTENTS is the text with bold markup.  INFO is a plist holding
   2101 contextual information."
   2102   (org-latex--text-markup contents 'bold info))
   2103 
   2104 
   2105 ;;;; Center Block
   2106 
   2107 (defun org-latex-center-block (center-block contents info)
   2108   "Transcode a CENTER-BLOCK element from Org to LaTeX.
   2109 CONTENTS holds the contents of the center block.  INFO is a plist
   2110 holding contextual information."
   2111   (org-latex--wrap-label
   2112    center-block (format "\\begin{center}\n%s\\end{center}" contents) info))
   2113 
   2114 
   2115 ;;;; Clock
   2116 
   2117 (defun org-latex-clock (clock _contents info)
   2118   "Transcode a CLOCK element from Org to LaTeX.
   2119 CONTENTS is nil.  INFO is a plist holding contextual
   2120 information."
   2121   (concat
   2122    "\\noindent"
   2123    (format "\\textbf{%s} " org-clock-string)
   2124    (format (plist-get info :latex-inactive-timestamp-format)
   2125 	   (concat (org-timestamp-translate (org-element-property :value clock))
   2126 		   (let ((time (org-element-property :duration clock)))
   2127 		     (and time (format " (%s)" time)))))
   2128    "\\\\"))
   2129 
   2130 
   2131 ;;;; Code
   2132 
   2133 (defun org-latex-code (code _contents info)
   2134   "Transcode a CODE object from Org to LaTeX.
   2135 CONTENTS is nil.  INFO is a plist used as a communication
   2136 channel."
   2137   (org-latex--text-markup (org-element-property :value code) 'code info))
   2138 
   2139 
   2140 ;;;; Drawer
   2141 
   2142 (defun org-latex-drawer (drawer contents info)
   2143   "Transcode a DRAWER element from Org to LaTeX.
   2144 CONTENTS holds the contents of the block.  INFO is a plist
   2145 holding contextual information."
   2146   (let* ((name (org-element-property :drawer-name drawer))
   2147 	 (output (funcall (plist-get info :latex-format-drawer-function)
   2148 			  name contents)))
   2149     (org-latex--wrap-label drawer output info)))
   2150 
   2151 
   2152 ;;;; Dynamic Block
   2153 
   2154 (defun org-latex-dynamic-block (dynamic-block contents info)
   2155   "Transcode a DYNAMIC-BLOCK element from Org to LaTeX.
   2156 CONTENTS holds the contents of the block.  INFO is a plist
   2157 holding contextual information.  See `org-export-data'."
   2158   (org-latex--wrap-label dynamic-block contents info))
   2159 
   2160 
   2161 ;;;; Entity
   2162 
   2163 (defun org-latex-entity (entity _contents _info)
   2164   "Transcode an ENTITY object from Org to LaTeX.
   2165 CONTENTS are the definition itself.  INFO is a plist holding
   2166 contextual information."
   2167   (org-element-property :latex entity))
   2168 
   2169 
   2170 ;;;; Example Block
   2171 
   2172 (defun org-latex-example-block (example-block _contents info)
   2173   "Transcode an EXAMPLE-BLOCK element from Org to LaTeX.
   2174 CONTENTS is nil.  INFO is a plist holding contextual
   2175 information."
   2176   (when (org-string-nw-p (org-element-property :value example-block))
   2177     (let ((environment (or (org-export-read-attribute
   2178 			    :attr_latex example-block :environment)
   2179 			   "verbatim")))
   2180       (org-latex--wrap-label
   2181        example-block
   2182        (format "\\begin{%s}\n%s\\end{%s}"
   2183 	       environment
   2184 	       (org-export-format-code-default example-block info)
   2185 	       environment)
   2186        info))))
   2187 
   2188 
   2189 ;;;; Export Block
   2190 
   2191 (defun org-latex-export-block (export-block _contents _info)
   2192   "Transcode a EXPORT-BLOCK element from Org to LaTeX.
   2193 CONTENTS is nil.  INFO is a plist holding contextual information."
   2194   (when (member (org-element-property :type export-block) '("LATEX" "TEX"))
   2195     (org-remove-indentation (org-element-property :value export-block))))
   2196 
   2197 
   2198 ;;;; Export Snippet
   2199 
   2200 (defun org-latex-export-snippet (export-snippet _contents _info)
   2201   "Transcode a EXPORT-SNIPPET object from Org to LaTeX.
   2202 CONTENTS is nil.  INFO is a plist holding contextual information."
   2203   (when (eq (org-export-snippet-backend export-snippet) 'latex)
   2204     (org-element-property :value export-snippet)))
   2205 
   2206 
   2207 ;;;; Fixed Width
   2208 
   2209 (defun org-latex-fixed-width (fixed-width _contents info)
   2210   "Transcode a FIXED-WIDTH element from Org to LaTeX.
   2211 CONTENTS is nil.  INFO is a plist holding contextual information."
   2212   (org-latex--wrap-label
   2213    fixed-width
   2214    (format "\\begin{verbatim}\n%s\n\\end{verbatim}"
   2215 	   (org-remove-indentation
   2216 	    (org-element-property :value fixed-width)))
   2217    info))
   2218 
   2219 
   2220 ;;;; Footnote Reference
   2221 
   2222 (defun org-latex-footnote-reference (footnote-reference _contents info)
   2223   "Transcode a FOOTNOTE-REFERENCE element from Org to LaTeX.
   2224 CONTENTS is nil.  INFO is a plist holding contextual information."
   2225   (let ((label (org-element-property :label footnote-reference)))
   2226     (concat
   2227      ;; Insert separator between two footnotes in a row.
   2228      (let ((prev (org-export-get-previous-element footnote-reference info)))
   2229        (when (org-element-type-p prev 'footnote-reference)
   2230 	 (plist-get info :latex-footnote-separator)))
   2231      (cond
   2232       ;; Use `:latex-footnote-defined-format' if the footnote has
   2233       ;; already been defined.
   2234       ((not (org-export-footnote-first-reference-p footnote-reference info))
   2235        (format (plist-get info :latex-footnote-defined-format)
   2236 	       (org-latex--label
   2237 		(org-export-get-footnote-definition footnote-reference info)
   2238 		info t)))
   2239       ;; Use \footnotemark if reference is within another footnote
   2240       ;; reference, footnote definition, table cell, verse block, or
   2241       ;; item's tag.
   2242       ((or (org-element-lineage footnote-reference
   2243 				'(footnote-reference footnote-definition
   2244 						     table-cell verse-block))
   2245 	   (org-element-type-p
   2246 	    (org-element-parent-element footnote-reference) 'item))
   2247        "\\footnotemark")
   2248       ;; Otherwise, define it with \footnote command.
   2249       (t
   2250        (let ((def (org-export-get-footnote-definition footnote-reference info)))
   2251 	 (concat
   2252 	  (format (plist-get info :latex-default-footnote-command) (org-trim (org-export-data def info))
   2253 		  ;; Only insert a \label if there exist another
   2254 		  ;; reference to def.
   2255 		  (cond ((not label) "")
   2256 			((org-element-map (plist-get info :parse-tree)
   2257 			     'footnote-reference
   2258 			   (lambda (f)
   2259 			     (and (not (eq f footnote-reference))
   2260 				  (equal (org-element-property :label f) label)
   2261 				  (org-trim (org-latex--label def info t t))))
   2262 			   info t))
   2263 			(t "")))
   2264 	  ;; Retrieve all footnote references within the footnote and
   2265 	  ;; add their definition after it, since LaTeX doesn't support
   2266 	  ;; them inside.
   2267 	  (org-latex--delayed-footnotes-definitions def info))))))))
   2268 
   2269 
   2270 ;;;; Headline
   2271 
   2272 (defun org-latex-headline (headline contents info)
   2273   "Transcode a HEADLINE element from Org to LaTeX.
   2274 CONTENTS holds the contents of the headline.  INFO is a plist
   2275 holding contextual information."
   2276   (unless (org-element-property :footnote-section-p headline)
   2277     (let* ((class (plist-get info :latex-class))
   2278 	   (level (org-export-get-relative-level headline info))
   2279 	   (numberedp (org-export-numbered-headline-p headline info))
   2280 	   (class-sectioning (assoc class (plist-get info :latex-classes)))
   2281 	   ;; Section formatting will set two placeholders: one for
   2282 	   ;; the title and the other for the contents.
   2283 	   (section-fmt
   2284 	    (let ((sec (if (functionp (nth 2 class-sectioning))
   2285 			   (funcall (nth 2 class-sectioning) level numberedp)
   2286 			 (nth (1+ level) class-sectioning))))
   2287 	      (cond
   2288 	       ;; No section available for that LEVEL.
   2289 	       ((not sec) nil)
   2290 	       ;; Section format directly returned by a function.  Add
   2291 	       ;; placeholder for contents.
   2292 	       ((stringp sec) (concat sec "\n%s"))
   2293 	       ;; (numbered-section . unnumbered-section)
   2294 	       ((not (consp (cdr sec)))
   2295 		(concat (funcall (if numberedp #'car #'cdr) sec) "\n%s"))
   2296 	       ;; (numbered-open numbered-close)
   2297 	       ((= (length sec) 2)
   2298 		(when numberedp (concat (car sec) "\n%s" (nth 1 sec))))
   2299 	       ;; (num-in num-out no-num-in no-num-out)
   2300 	       ((= (length sec) 4)
   2301 		(if numberedp (concat (car sec) "\n%s" (nth 1 sec))
   2302 		  (concat (nth 2 sec) "\n%s" (nth 3 sec)))))))
   2303 	   ;; Create a temporary export backend that hard-codes
   2304 	   ;; "\underline" within "\section" and alike.
   2305 	   (section-backend
   2306             (org-export-create-backend
   2307              :parent 'latex
   2308              :transcoders
   2309              '((underline . (lambda (o c i) (format "\\underline{%s}" c)))
   2310                ;; LaTeX isn't happy when you try to use \verb inside the argument of other
   2311                ;; commands (like \section, etc.), and this causes compilation to fail.
   2312                ;; So, within headings it's a good idea to replace any instances of \verb
   2313                ;; with \texttt.
   2314                (code . (lambda (o _ _) (org-latex--protect-texttt (org-element-property :value o))))
   2315                (verbatim . (lambda (o _ _) (org-latex--protect-texttt (org-element-property :value o)))))))
   2316            ;; Create a temporary export backend that strips footnotes from title.
   2317            ;; Footnotes are not allowed in \section and similar
   2318            ;; commands that contribute to TOC and footers.
   2319            ;; See https://orgmode.org/list/691643eb-49d0-45c3-ab7f-a1edbd093bef@gmail.com
   2320            ;; https://texfaq.org/FAQ-ftnsect
   2321            (section-no-footnote-backend
   2322             (org-export-create-backend
   2323              :parent section-backend
   2324              :transcoders
   2325              `((footnote-reference . ignore))))
   2326 	   (text
   2327 	    (org-export-data-with-backend
   2328 	     (org-element-property :title headline) section-backend info))
   2329            (text-no-footnote
   2330             (org-export-data-with-backend
   2331 	     (org-element-property :title headline) section-no-footnote-backend info))
   2332 	   (todo
   2333 	    (and (plist-get info :with-todo-keywords)
   2334 		 (let ((todo (org-element-property :todo-keyword headline)))
   2335 		   (and todo (org-export-data todo info)))))
   2336 	   (todo-type (and todo (org-element-property :todo-type headline)))
   2337 	   (tags (and (plist-get info :with-tags)
   2338 		      (org-export-get-tags headline info)))
   2339 	   (priority (and (plist-get info :with-priority)
   2340 			  (org-element-property :priority headline)))
   2341 	   ;; Create the headline text along with a no-tag version.
   2342 	   ;; The latter is required to remove tags from toc.
   2343 	   (full-text (funcall (plist-get info :latex-format-headline-function)
   2344 			       todo todo-type priority text tags info))
   2345            (full-text-no-footnote
   2346             (funcall (plist-get info :latex-format-headline-function)
   2347 		     todo todo-type priority text-no-footnote tags info))
   2348 	   ;; Associate \label to the headline for internal links.
   2349 	   (headline-label (org-latex--label headline info t t))
   2350 	   (pre-blanks
   2351 	    (make-string (org-element-property :pre-blank headline) ?\n)))
   2352       (if (or (not section-fmt) (org-export-low-level-p headline info))
   2353 	  ;; This is a deep sub-tree: export it as a list item.  Also
   2354 	  ;; export as items headlines for which no section format has
   2355 	  ;; been found.
   2356 	  (let ((low-level-body
   2357 		 (concat
   2358 		  ;; If headline is the first sibling, start a list.
   2359 		  (when (org-export-first-sibling-p headline info)
   2360 		    (format "\\begin{%s}\n" (if numberedp 'enumerate 'itemize)))
   2361 		  ;; Itemize headline
   2362 		  "\\item"
   2363 		  (and full-text
   2364 		       (string-match-p "\\`[ \t]*\\[" full-text)
   2365 		       "\\relax")
   2366 		  " " full-text "\n"
   2367 		  headline-label
   2368 		  pre-blanks
   2369 		  contents)))
   2370 	    ;; If headline is not the last sibling simply return
   2371 	    ;; LOW-LEVEL-BODY.  Otherwise, also close the list, before
   2372 	    ;; any blank line.
   2373 	    (if (not (org-export-last-sibling-p headline info)) low-level-body
   2374 	      (replace-regexp-in-string
   2375 	       "[ \t\n]*\\'"
   2376 	       (format "\n\\\\end{%s}" (if numberedp 'enumerate 'itemize))
   2377 	       low-level-body)))
   2378 	;; This is a standard headline.  Export it as a section.  Add
   2379 	;; an alternative heading when possible, and when this is not
   2380 	;; identical to the usual heading.
   2381 	(let ((opt-title
   2382 	       (funcall (plist-get info :latex-format-headline-function)
   2383 			todo todo-type priority
   2384 			(org-export-data-with-backend
   2385 			 (org-export-get-alt-title headline info)
   2386 			 section-backend info)
   2387 			(and (eq (plist-get info :with-tags) t) tags)
   2388 			info))
   2389 	      ;; Maybe end local TOC (see `org-latex-keyword').
   2390 	      (contents
   2391 	       (concat
   2392 		contents
   2393 		(let ((case-fold-search t)
   2394 		      (section
   2395 		       (let ((first (car (org-element-contents headline))))
   2396 			 (and (org-element-type-p first 'section) first))))
   2397 		  (org-element-map section 'keyword
   2398 		    (lambda (k)
   2399 		      (and (equal (org-element-property :key k) "TOC")
   2400 			   (let ((v (org-element-property :value k)))
   2401 			     (and (string-match-p "\\<headlines\\>" v)
   2402 				  (string-match-p "\\<local\\>" v)
   2403 				  (format "\\stopcontents[level-%d]" level)))))
   2404 		    info t)))))
   2405 	  (if (and (or (and opt-title (not (equal opt-title full-text)))
   2406                        ;; Heading contains footnotes.  Add optional title
   2407                        ;; version without footnotes to avoid footnotes in
   2408                        ;; TOC/footers.
   2409                        (and (not (equal full-text-no-footnote full-text))
   2410                             (setq opt-title full-text-no-footnote)))
   2411 		   (string-match "\\`\\\\\\(.+?\\){" section-fmt))
   2412               (format (replace-match "\\1[%s]" nil nil section-fmt 1)
   2413 		      ;; Replace square brackets with parenthesis
   2414 		      ;; since square brackets are not supported in
   2415 		      ;; optional arguments.
   2416 		      (replace-regexp-in-string
   2417 		       "\\[" "(" (replace-regexp-in-string "\\]" ")" opt-title))
   2418 		      full-text
   2419 		      (concat headline-label pre-blanks contents))
   2420 	    ;; Impossible to add an alternative heading.  Fallback to
   2421 	    ;; regular sectioning format string.
   2422 	    (format section-fmt full-text
   2423 		    (concat headline-label pre-blanks contents))))))))
   2424 
   2425 (defun org-latex-format-headline-default-function
   2426     (todo _todo-type priority text tags _info)
   2427   "Default format function for a headline.
   2428 See `org-latex-format-headline-function' for details."
   2429   (concat
   2430    (and todo (format "{\\bfseries\\sffamily %s} " todo))
   2431    (and priority (format "\\framebox{\\#%c} " priority))
   2432    text
   2433    (and tags
   2434 	(format "\\hfill{}\\textsc{%s}"
   2435 		(mapconcat #'org-latex--protect-text tags ":")))))
   2436 
   2437 
   2438 ;;;; Horizontal Rule
   2439 
   2440 (defun org-latex-horizontal-rule (horizontal-rule _contents info)
   2441   "Transcode an HORIZONTAL-RULE object from Org to LaTeX.
   2442 CONTENTS is nil.  INFO is a plist holding contextual information."
   2443   (let ((attr (org-export-read-attribute :attr_latex horizontal-rule))
   2444 	(prev (org-export-get-previous-element horizontal-rule info)))
   2445     (concat
   2446      ;; Make sure the rule doesn't start at the end of the current
   2447      ;; line by separating it with a blank line from previous element.
   2448      (when (and prev
   2449 		(let ((prev-blank (org-element-property :post-blank prev)))
   2450 		  (or (not prev-blank) (zerop prev-blank))))
   2451        "\n")
   2452      (org-latex--wrap-label
   2453       horizontal-rule
   2454       (format "\\noindent\\rule{%s}{%s}"
   2455 	      (or (plist-get attr :width) "\\textwidth")
   2456 	      (or (plist-get attr :thickness) "0.5pt"))
   2457       info))))
   2458 
   2459 
   2460 ;;;; Inline Src Block
   2461 
   2462 (defun org-latex-inline-src-block (inline-src-block _contents info)
   2463   "Transcode an INLINE-SRC-BLOCK element from Org to LaTeX.
   2464 CONTENTS holds the contents of the item.  INFO is a plist holding
   2465 contextual information."
   2466   (let ((code (org-element-property :value inline-src-block))
   2467         (lang (org-element-property :language inline-src-block)))
   2468     (pcase (plist-get info :latex-src-block-backend)
   2469       ((or `verbatim (guard (not lang))) (org-latex--text-markup code 'code info))
   2470       (`minted (org-latex-inline-src-block--minted info code lang))
   2471       (`engraved (org-latex-inline-src-block--engraved info code lang))
   2472       (`listings (org-latex-inline-src-block--listings info code lang))
   2473       (oldval
   2474        (warn "Please update `org-latex-src-block-backend' to %s"
   2475              (if oldval "listings" "verbatim"))
   2476        (if oldval
   2477            (org-latex-inline-src-block--listings info code lang)
   2478          (org-latex--text-markup code 'code info))))))
   2479 
   2480 (defun org-latex-inline-src-block--minted (info code lang)
   2481   "Transcode an inline src block's content from Org to LaTeX, using minted.
   2482 INFO, CODE, and LANG are provided by `org-latex-inline-src-block'."
   2483   (let ((mint-lang (or (cadr (assq (intern lang)
   2484                                    (plist-get info :latex-minted-langs)))
   2485                        (downcase lang)))
   2486         (options (org-latex--make-option-string
   2487                   (plist-get info :latex-minted-options))))
   2488     (format "\\mintinline%s{%s}{%s}"
   2489             (if (string= options "") "" (format "[%s]" options))
   2490             mint-lang
   2491             code)))
   2492 
   2493 (defun org-latex-inline-src-block--engraved (info code lang)
   2494   "Transcode an inline src block's content from Org to LaTeX, using engrave-faces.
   2495 INFO, CODE, and LANG are provided by `org-latex-inline-src-block'."
   2496   (org-latex-src--engrave-code
   2497    code lang nil (plist-get info :latex-engraved-options) t))
   2498 
   2499 (defun org-latex-inline-src-block--listings (info code lang)
   2500   "Transcode an inline src block's content from Org to LaTeX, using lstlistings.
   2501 INFO, CODE, and LANG are provided by `org-latex-inline-src-block'."
   2502   (let* ((lst-lang (or (cadr (assq (intern lang)
   2503                                    (plist-get info :latex-listings-langs)))
   2504                        lang))
   2505          (separator (org-latex--find-verb-separator code))
   2506          (options (org-latex--make-option-string
   2507                    (append (plist-get info :latex-listings-options)
   2508                            `(("language" ,lst-lang))))))
   2509     (concat (format "\\lstinline[%s]" options)
   2510             separator code separator)))
   2511 
   2512 ;;;; Inlinetask
   2513 
   2514 (defun org-latex-inlinetask (inlinetask contents info)
   2515   "Transcode an INLINETASK element from Org to LaTeX.
   2516 CONTENTS holds the contents of the block.  INFO is a plist
   2517 holding contextual information."
   2518   (let ((title (org-export-data (org-element-property :title inlinetask) info))
   2519 	(todo (and (plist-get info :with-todo-keywords)
   2520 		   (let ((todo (org-element-property :todo-keyword inlinetask)))
   2521 		     (and todo (org-export-data todo info)))))
   2522 	(todo-type (org-element-property :todo-type inlinetask))
   2523 	(tags (and (plist-get info :with-tags)
   2524 		   (org-export-get-tags inlinetask info)))
   2525 	(priority (and (plist-get info :with-priority)
   2526 		       (org-element-property :priority inlinetask)))
   2527 	(contents (concat (org-latex--label inlinetask info) contents)))
   2528     (funcall (plist-get info :latex-format-inlinetask-function)
   2529 	     todo todo-type priority title tags contents info)))
   2530 
   2531 (defun org-latex-format-inlinetask-default-function
   2532     (todo _todo-type priority title tags contents _info)
   2533   "Default format function for inlinetasks.
   2534 See `org-latex-format-inlinetask-function' for details."
   2535   (let ((full-title
   2536 	 (concat (when todo (format "\\textbf{\\textsf{\\textsc{%s}}} " todo))
   2537 		 (when priority (format "\\framebox{\\#%c} " priority))
   2538 		 title
   2539 		 (when tags
   2540 		   (format "\\hfill{}\\textsc{%s}"
   2541 			   (org-make-tag-string
   2542 			    (mapcar #'org-latex--protect-text tags)))))))
   2543     (concat "\\begin{center}\n"
   2544 	    "\\fbox{\n"
   2545 	    "\\begin{minipage}[c]{.6\\linewidth}\n"
   2546 	    full-title "\n\n"
   2547 	    (and (org-string-nw-p contents)
   2548 		 (concat "\\rule[.8em]{\\linewidth}{2pt}\n\n" contents))
   2549 	    "\\end{minipage}\n"
   2550 	    "}\n"
   2551 	    "\\end{center}")))
   2552 
   2553 
   2554 ;;;; Italic
   2555 
   2556 (defun org-latex-italic (_italic contents info)
   2557   "Transcode ITALIC from Org to LaTeX.
   2558 CONTENTS is the text with italic markup.  INFO is a plist holding
   2559 contextual information."
   2560   (org-latex--text-markup contents 'italic info))
   2561 
   2562 
   2563 ;;;; Item
   2564 
   2565 (defun org-latex-item (item contents info)
   2566   "Transcode an ITEM element from Org to LaTeX.
   2567 CONTENTS holds the contents of the item.  INFO is a plist holding
   2568 contextual information."
   2569   (let* ((orderedp (eq (org-element-property
   2570 			:type (org-element-parent item))
   2571 		       'ordered))
   2572 	 (level
   2573 	  ;; Determine level of current item to determine the
   2574 	  ;; correct LaTeX counter to use (enumi, enumii...).
   2575 	  (let ((parent item) (level 0))
   2576 	    (while (org-element-type-p
   2577 		    (setq parent (org-element-parent parent))
   2578 		    '(plain-list item))
   2579 	      (when (and (org-element-type-p parent 'plain-list)
   2580 			 (eq (org-element-property :type parent)
   2581 			     'ordered))
   2582 		(cl-incf level)))
   2583 	    level))
   2584 	 (count (org-element-property :counter item))
   2585 	 (counter (and count
   2586 		       (< level 5)
   2587 		       (format "\\setcounter{enum%s}{%s}\n"
   2588 			       (nth (1- level) '("i" "ii" "iii" "iv"))
   2589 			       (1- count))))
   2590 	 (checkbox (cl-case (org-element-property :checkbox item)
   2591 		     (on "$\\boxtimes$")
   2592 		     (off "$\\square$")
   2593 		     (trans "$\\boxminus$")))
   2594 	 (tag (let ((tag (org-element-property :tag item)))
   2595 		(and tag (org-export-data tag info))))
   2596 	 ;; If there are footnotes references in tag, be sure to add
   2597 	 ;; their definition at the end of the item.  This workaround
   2598 	 ;; is necessary since "\footnote{}" command is not supported
   2599 	 ;; in tags.
   2600 	 (tag-footnotes
   2601 	  (or (and tag (org-latex--delayed-footnotes-definitions
   2602 			(org-element-property :tag item) info))
   2603 	      "")))
   2604     (concat counter
   2605 	    "\\item"
   2606 	    (cond
   2607 	     ((and checkbox tag)
   2608 	      (format (if orderedp "{%s %s} %s" "[{%s %s}] %s")
   2609 		      checkbox tag tag-footnotes))
   2610 	     ((or checkbox tag)
   2611 	      (format (if orderedp "{%s} %s" "[{%s}] %s")
   2612 		      (or checkbox tag) tag-footnotes))
   2613 	     ;; Without a tag or a check-box, if CONTENTS starts with
   2614 	     ;; an opening square bracket, add "\relax" to "\item",
   2615 	     ;; unless the brackets comes from an initial export
   2616 	     ;; snippet (i.e. it is inserted willingly by the user).
   2617 	     ((and contents
   2618 		   (string-match-p "\\`[ \t]*\\[" contents)
   2619 		   (not (let ((e (car (org-element-contents item))))
   2620 			(and (org-element-type-p e 'paragraph)
   2621 			     (let ((o (car (org-element-contents e))))
   2622 			       (and (org-element-type-p o 'export-snippet)
   2623 				    (eq (org-export-snippet-backend o)
   2624 					'latex)))))))
   2625 	      "\\relax ")
   2626 	     (t " "))
   2627 	    (and contents (org-trim contents)))))
   2628 
   2629 
   2630 ;;;; Keyword
   2631 
   2632 (defun org-latex-keyword (keyword _contents info)
   2633   "Transcode a KEYWORD element from Org to LaTeX.
   2634 CONTENTS is nil.  INFO is a plist holding contextual information."
   2635   (let ((key (org-element-property :key keyword))
   2636 	(value (org-element-property :value keyword)))
   2637     (cond
   2638      ((string= key "LATEX") value)
   2639      ((string= key "INDEX") (format "\\index{%s}" value))
   2640      ((string= key "TOC")
   2641       (let ((case-fold-search t))
   2642 	(cond
   2643 	 ((string-match-p "\\<headlines\\>" value)
   2644 	  (let* ((localp (string-match-p "\\<local\\>" value))
   2645 		 (parent (org-element-lineage keyword 'headline))
   2646 		 (level (if (not (and localp parent)) 0
   2647 			  (org-export-get-relative-level parent info)))
   2648 		 (depth
   2649 		  (and (string-match "\\<[0-9]+\\>" value)
   2650 		       (format
   2651 			"\\setcounter{tocdepth}{%d}"
   2652 			(+ (string-to-number (match-string 0 value)) level)))))
   2653 	    (if (and localp parent)
   2654 		;; Start local TOC, assuming package "titletoc" is
   2655 		;; required.
   2656 		(format "\\startcontents[level-%d]
   2657 \\printcontents[level-%d]{}{0}{%s}"
   2658 			level level (or depth ""))
   2659 	      (concat depth (and depth "\n") "\\tableofcontents"))))
   2660 	 ((string-match-p "\\<tables\\>" value) "\\listoftables")
   2661 	 ((string-match-p "\\<listings\\>" value)
   2662 	  (cl-case (plist-get info :latex-src-block-backend)
   2663 	    ((nil) "\\listoffigures")
   2664 	    (minted "\\listoflistings")
   2665 	    (engraved "\\listoflistings")
   2666 	    (otherwise "\\lstlistoflistings")))))))))
   2667 
   2668 
   2669 ;;;; LaTeX Environment
   2670 
   2671 (defun org-latex--environment-type (latex-environment)
   2672   "Return the TYPE of LATEX-ENVIRONMENT.
   2673 
   2674 The TYPE is determined from the actual latex environment, and
   2675 could be a member of `org-latex-caption-above' or `math'."
   2676   (let* ((latex-begin-re "\\\\begin{\\([A-Za-z0-9*]+\\)}")
   2677 	 (value (org-remove-indentation
   2678 		 (org-element-property :value latex-environment)))
   2679 	 (env (or (and (string-match latex-begin-re value)
   2680 		       (match-string 1 value))
   2681 		  "")))
   2682     (cond
   2683      ((string-match-p org-latex-math-environments-re value) 'math)
   2684      ((string-match-p
   2685        (eval-when-compile
   2686 	 (regexp-opt '("table" "longtable" "tabular" "tabu" "longtabu")))
   2687        env)
   2688       'table)
   2689      ((string-match-p "figure" env) 'image)
   2690      ((string-match-p
   2691        (eval-when-compile
   2692 	 (regexp-opt '("lstlisting" "listing" "verbatim" "minted")))
   2693        env)
   2694       'src-block)
   2695      (t 'special-block))))
   2696 
   2697 (defun org-latex-latex-environment (latex-environment _contents info)
   2698   "Transcode a LATEX-ENVIRONMENT element from Org to LaTeX.
   2699 CONTENTS is nil.  INFO is a plist holding contextual information."
   2700   (when (plist-get info :with-latex)
   2701     (let* ((value (org-remove-indentation
   2702 		   (org-element-property :value latex-environment)))
   2703 	   (type (org-latex--environment-type latex-environment))
   2704 	   (caption (if (eq type 'math)
   2705 			(org-latex--label latex-environment info nil t)
   2706 		      (org-latex--caption/label-string latex-environment info)))
   2707 	   (caption-above-p
   2708             (or (eq type 'math)
   2709                 (org-latex--caption-above-p latex-environment info))))
   2710       (if (not (or (org-element-property :name latex-environment)
   2711 		 (org-element-property :caption latex-environment)))
   2712 	  value
   2713 	;; Environment is labeled: label must be within the environment
   2714 	;; (otherwise, a reference pointing to that element will count
   2715 	;; the section instead).  Also insert caption if `latex-environment'
   2716 	;; is not a math environment.
   2717 	(with-temp-buffer
   2718 	  (insert value)
   2719 	  (if caption-above-p
   2720 	      (progn
   2721 		(goto-char (point-min))
   2722 		(forward-line))
   2723 	    (goto-char (point-max))
   2724 	    (forward-line -1))
   2725 	  (insert caption)
   2726 	  (buffer-string))))))
   2727 
   2728 ;;;; LaTeX Fragment
   2729 
   2730 (defun org-latex-latex-fragment (latex-fragment _contents _info)
   2731   "Transcode a LATEX-FRAGMENT object from Org to LaTeX.
   2732 CONTENTS is nil.  INFO is a plist holding contextual information."
   2733   (let ((value (org-element-property :value latex-fragment)))
   2734     ;; Trim math markers since the fragment is enclosed within
   2735     ;; a latex-math-block object anyway.
   2736     (cond ((string-match-p "\\`\\$[^$]" value) (substring value 1 -1))
   2737 	  ((string-prefix-p "\\(" value) (substring value 2 -2))
   2738 	  (t value))))
   2739 
   2740 
   2741 ;;;; Line Break
   2742 
   2743 (defun org-latex-line-break (_line-break _contents _info)
   2744   "Transcode a LINE-BREAK object from Org to LaTeX.
   2745 CONTENTS is nil.  INFO is a plist holding contextual information."
   2746   "\\\\\n")
   2747 
   2748 
   2749 ;;;; Link
   2750 
   2751 (defun org-latex-image-link-filter (data _backend info)
   2752   (org-export-insert-image-links data info org-latex-inline-image-rules))
   2753 
   2754 (defun org-latex--inline-image (link info)
   2755   "Return LaTeX code for an inline image.
   2756 LINK is the link pointing to the inline image.  INFO is a plist
   2757 used as a communication channel."
   2758   (let* ((parent (org-element-parent-element link))
   2759 	 (path (let ((raw-path (org-element-property :path link)))
   2760 		 (if (not (file-name-absolute-p raw-path)) raw-path
   2761 		   (expand-file-name raw-path))))
   2762 	 (filetype (file-name-extension path))
   2763 	 (caption (org-latex--caption/label-string parent info))
   2764 	 (caption-above-p (org-latex--caption-above-p link info))
   2765 	 ;; Retrieve latex attributes from the element around.
   2766 	 (attr (org-export-read-attribute :attr_latex parent))
   2767 	 (float (let ((float (plist-get attr :float)))
   2768 		  (cond
   2769                    ((org-element-map (org-element-contents parent) t
   2770                       (lambda (node)
   2771                         (cond
   2772                          ((and (org-element-type-p node 'plain-text)
   2773                                (not (org-string-nw-p node)))
   2774                           nil)
   2775                          ((eq link node)
   2776                           ;; Objects inside link description are
   2777                           ;; allowed.
   2778                           (throw :org-element-skip nil))
   2779                          (t 'not-a-float)))
   2780                       info 'first-match)
   2781                     ;; Not a single link inside paragraph (spaces
   2782                     ;; ignored).  Cannot use float environment.  It
   2783                     ;; would be inside paragraph.
   2784                     nil)
   2785                    ((string= float "wrap") 'wrap)
   2786 		   ((string= float "sideways") 'sideways)
   2787 		   ((string= float "multicolumn") 'multicolumn)
   2788                    ((string= float "t") 'figure)
   2789 		   ((and (plist-member attr :float) (not float)) 'nonfloat)
   2790                    (float float)
   2791 		   ((or (org-element-property :caption parent)
   2792 			(org-string-nw-p (plist-get attr :caption)))
   2793 		    'figure)
   2794 		   (t 'nonfloat))))
   2795 	 (placement
   2796 	  (let ((place (plist-get attr :placement)))
   2797 	    (cond
   2798 	     (place (format "%s" place))
   2799 	     ((eq float 'wrap) "{l}{0.5\\textwidth}")
   2800 	     ((eq float 'figure)
   2801 	      (format "[%s]" (plist-get info :latex-default-figure-position)))
   2802 	     (t ""))))
   2803 	 (center
   2804 	  (cond
   2805 	   ;; If link is an image link, do not center.
   2806 	   ((org-element-type-p (org-element-parent link) 'link) nil)
   2807 	   ((plist-member attr :center) (plist-get attr :center))
   2808 	   (t (plist-get info :latex-images-centered))))
   2809 	 (comment-include (if (plist-get attr :comment-include) "%" ""))
   2810 	 ;; It is possible to specify scale or width and height in
   2811 	 ;; the ATTR_LATEX line, and also via default variables.
   2812 	 (scale (cond ((eq float 'wrap) "")
   2813 		      ((plist-get attr :scale))
   2814 		      (t (plist-get info :latex-image-default-scale))))
   2815 	 (width (cond ((org-string-nw-p scale) "")
   2816 		      ((plist-get attr :width))
   2817 		      ((plist-get attr :height) "")
   2818 		      ((eq float 'wrap) "0.48\\textwidth")
   2819 		      (t (plist-get info :latex-image-default-width))))
   2820 	 (height (cond ((org-string-nw-p scale) "")
   2821 		       ((plist-get attr :height))
   2822 		       ((or (plist-get attr :width)
   2823 			    (memq float '(figure wrap))) "")
   2824 		       (t (plist-get info :latex-image-default-height))))
   2825 	 (options (let ((opt (or (plist-get attr :options)
   2826 				 (plist-get info :latex-image-default-option))))
   2827 		    (if (not (string-match "\\`\\[\\(.*\\)\\]\\'" opt)) opt
   2828 		      (match-string 1 opt))))
   2829 	 image-code)
   2830     (if (member filetype '("tikz" "pgf"))
   2831 	;; For tikz images:
   2832 	;; - use \input to read in image file.
   2833 	;; - if options are present, wrap in a tikzpicture environment.
   2834 	;; - if width or height are present, use \resizebox to change
   2835 	;;   the image size.
   2836 	(progn
   2837 	  (setq image-code (format "\\input{%s}" path))
   2838 	  (when (org-string-nw-p options)
   2839 	    (setq image-code
   2840 		  (format "\\begin{tikzpicture}[%s]\n%s\n\\end{tikzpicture}"
   2841 			  options
   2842 			  image-code)))
   2843 	  (setq image-code
   2844 		(cond ((org-string-nw-p scale)
   2845 		       (format "\\scalebox{%s}{%s}" scale image-code))
   2846 		      ((or (org-string-nw-p width) (org-string-nw-p height))
   2847 		       (format "\\resizebox{%s}{%s}{%s}"
   2848 			       (if (org-string-nw-p width) width "!")
   2849 			       (if (org-string-nw-p height) height "!")
   2850 			       image-code))
   2851 		      (t image-code))))
   2852       ;; For other images:
   2853       ;; - add scale, or width and height to options.
   2854       ;; - include the image with \includegraphics.
   2855       (if (org-string-nw-p scale)
   2856 	  (setq options (concat options ",scale=" scale))
   2857 	(when (org-string-nw-p width) (setq options (concat options ",width=" width)))
   2858 	(when (org-string-nw-p height) (setq options (concat options ",height=" height))))
   2859       (let ((search-option (org-element-property :search-option link)))
   2860         (when (and search-option
   2861                    (equal filetype "pdf")
   2862                    (string-match-p "\\`[0-9]+\\'" search-option)
   2863                    (not (string-match-p "page=" options)))
   2864           (setq options (concat options ",page=" search-option))))
   2865       (setq image-code
   2866 	    (format "\\includegraphics%s{%s}"
   2867 		    (cond ((not (org-string-nw-p options)) "")
   2868 			  ((string-prefix-p "," options)
   2869 			   (format "[%s]" (substring options 1)))
   2870 			  (t (format "[%s]" options)))
   2871                     ;; While \includegraphics is fine with unicode in the path,
   2872                     ;; \includesvg is prone to producing errors.
   2873                     (if (and (string-match-p "[^[:ascii:]]" path)
   2874                              (equal filetype "svg"))
   2875                         (concat "\\detokenize{" path "}")
   2876                       path)))
   2877       (when (equal filetype "svg")
   2878 	(setq image-code (replace-regexp-in-string "^\\\\includegraphics"
   2879 						   "\\includesvg"
   2880 						   image-code
   2881 						   nil t))
   2882 	(setq image-code (replace-regexp-in-string "\\.svg}"
   2883 						   "}"
   2884 						   image-code
   2885 						   nil t))))
   2886     ;; Return proper string, depending on FLOAT.
   2887     (pcase float
   2888       ((and (pred stringp) env-string)
   2889        (format "\\begin{%s}%s
   2890 %s%s
   2891 %s%s
   2892 %s\\end{%s}"
   2893                env-string
   2894                placement
   2895                (if caption-above-p caption "")
   2896                (if center "\\centering" "")
   2897                comment-include image-code
   2898                (if caption-above-p "" caption)
   2899                env-string))
   2900       (`wrap (format "\\begin{wrapfigure}%s
   2901 %s%s
   2902 %s%s
   2903 %s\\end{wrapfigure}"
   2904 		     placement
   2905 		     (if caption-above-p caption "")
   2906 		     (if center "\\centering" "")
   2907 		     comment-include image-code
   2908 		     (if caption-above-p "" caption)))
   2909       (`sideways (format "\\begin{sidewaysfigure}
   2910 %s%s
   2911 %s%s
   2912 %s\\end{sidewaysfigure}"
   2913 			 (if caption-above-p caption "")
   2914 			 (if center "\\centering" "")
   2915 			 comment-include image-code
   2916 			 (if caption-above-p "" caption)))
   2917       (`multicolumn (format "\\begin{figure*}%s
   2918 %s%s
   2919 %s%s
   2920 %s\\end{figure*}"
   2921 			    placement
   2922 			    (if caption-above-p caption "")
   2923 			    (if center "\\centering" "")
   2924 			    comment-include image-code
   2925 			    (if caption-above-p "" caption)))
   2926       (`figure (format "\\begin{figure}%s
   2927 %s%s
   2928 %s%s
   2929 %s\\end{figure}"
   2930 		       placement
   2931 		       (if caption-above-p caption "")
   2932 		       (if center "\\centering" "")
   2933 		       comment-include image-code
   2934 		       (if caption-above-p "" caption)))
   2935       ((guard center)
   2936        (format "\\begin{center}
   2937 %s%s
   2938 %s\\end{center}"
   2939 	       (if caption-above-p caption "")
   2940 	       image-code
   2941 	       (if caption-above-p "" caption)))
   2942       (_
   2943        (concat (if caption-above-p caption "")
   2944 	       image-code
   2945 	       (if caption-above-p caption ""))))))
   2946 
   2947 (defun org-latex-link (link desc info)
   2948   "Transcode a LINK object from Org to LaTeX.
   2949 
   2950 DESC is the description part of the link, or the empty string.
   2951 INFO is a plist holding contextual information.  See
   2952 `org-export-data'."
   2953   (let* ((type (org-element-property :type link))
   2954 	 (raw-path (org-element-property :path link))
   2955 	 ;; Ensure DESC really exists, or set it to nil.
   2956 	 (desc (and (not (string= desc "")) desc))
   2957 	 (imagep (org-export-inline-image-p
   2958 		  link (plist-get info :latex-inline-image-rules)))
   2959 	 (path (org-latex--protect-text
   2960 		(pcase type
   2961 		  ("file"
   2962 		   (org-export-file-uri raw-path))
   2963 		  (_
   2964 		   (concat type ":" raw-path))))))
   2965     (cond
   2966      ;; Link type is handled by a special function.
   2967      ((org-export-custom-protocol-maybe link desc 'latex info))
   2968      ;; Image file.
   2969      (imagep (org-latex--inline-image (org-export-link-localise link) info))
   2970      ;; Radio link: Transcode target's contents and use them as link's
   2971      ;; description.
   2972      ((string= type "radio")
   2973       (let ((destination (org-export-resolve-radio-link link info)))
   2974 	(if (not destination) desc
   2975 	  (format "\\hyperref[%s]{%s}"
   2976 		  (org-export-get-reference destination info)
   2977 		  desc))))
   2978      ;; Links pointing to a headline: Find destination and build
   2979      ;; appropriate referencing command.
   2980      ((member type '("custom-id" "fuzzy" "id"))
   2981       (let ((destination
   2982 	     (if (string= type "fuzzy")
   2983 		 (org-export-resolve-fuzzy-link link info 'latex-matrices)
   2984 	       (org-export-resolve-id-link link info))))
   2985 	(cl-case (org-element-type destination)
   2986 	  ;; Id link points to an external file.
   2987 	  (plain-text
   2988 	   (if desc (format "\\href{%s}{%s}" destination desc)
   2989 	     (format "\\url{%s}" destination)))
   2990 	  ;; Fuzzy link points nowhere.
   2991 	  ((nil)
   2992 	   (format (plist-get info :latex-link-with-unknown-path-format)
   2993 		   (or desc
   2994 		       (org-export-data
   2995 			(org-element-property :raw-link link) info))))
   2996 	  ;; LINK points to a headline.  If headlines are numbered
   2997 	  ;; and the link has no description, display headline's
   2998 	  ;; number.  Otherwise, display description or headline's
   2999 	  ;; title.
   3000 	  (headline
   3001 	   (let ((label (org-latex--label destination info t)))
   3002 	     (if (and (not desc)
   3003 		      (org-export-numbered-headline-p destination info))
   3004 		 (format org-latex-reference-command label)
   3005 	       (format "\\hyperref[%s]{%s}" label
   3006 		       (or desc
   3007 			   (org-export-data
   3008 			    (org-element-property :title destination) info))))))
   3009           ;; Fuzzy link points to a target.  Do as above.
   3010 	  (otherwise
   3011 	   (let ((ref (org-latex--label destination info t)))
   3012 	     (if (not desc) (format org-latex-reference-command ref)
   3013 	       (format "\\hyperref[%s]{%s}" ref desc)))))))
   3014      ;; Coderef: replace link with the reference name or the
   3015      ;; equivalent line number.
   3016      ((string= type "coderef")
   3017       (format (org-export-get-coderef-format path desc)
   3018 	      ;; Resolve with RAW-PATH since PATH could be tainted
   3019 	      ;; with `org-latex--protect-text' call above.
   3020 	      (org-export-resolve-coderef raw-path info)))
   3021      ;; External link with a description part.
   3022      ((and path desc) (format "\\href{%s}{%s}" path desc))
   3023      ;; External link without a description part.
   3024      (path (format "\\url{%s}" path))
   3025      ;; No path, only description.  Try to do something useful.
   3026      (t (format (plist-get info :latex-link-with-unknown-path-format) desc)))))
   3027 
   3028 
   3029 ;;;; Node Property
   3030 
   3031 (defun org-latex-node-property (node-property _contents _info)
   3032   "Transcode a NODE-PROPERTY element from Org to LaTeX.
   3033 CONTENTS is nil.  INFO is a plist holding contextual
   3034 information."
   3035   (format "%s:%s"
   3036           (org-element-property :key node-property)
   3037           (let ((value (org-element-property :value node-property)))
   3038             (if value (concat " " value) ""))))
   3039 
   3040 
   3041 ;;;; Paragraph
   3042 
   3043 (defun org-latex-paragraph (_paragraph contents _info)
   3044   "Transcode a PARAGRAPH element from Org to LaTeX.
   3045 CONTENTS is the contents of the paragraph, as a string.  INFO is
   3046 the plist used as a communication channel."
   3047   ;; Ensure that we do not create multiple paragraphs, when a single
   3048   ;; paragraph is expected.
   3049   ;; Multiple newlines may appear in CONTENTS, for example, when
   3050   ;; certain objects are stripped from export, leaving single newlines
   3051   ;; before and after.
   3052   (org-remove-blank-lines contents))
   3053 
   3054 
   3055 ;;;; Plain List
   3056 
   3057 (defun org-latex-plain-list (plain-list contents info)
   3058   "Transcode a PLAIN-LIST element from Org to LaTeX.
   3059 CONTENTS is the contents of the list.  INFO is a plist holding
   3060 contextual information."
   3061   (let* ((type (org-element-property :type plain-list))
   3062 	 (attr (org-export-read-attribute :attr_latex plain-list))
   3063 	 (latex-type (let ((env (plist-get attr :environment)))
   3064 		       (cond (env (format "%s" env))
   3065 			     ((eq type 'ordered) "enumerate")
   3066 			     ((eq type 'descriptive) "description")
   3067 			     (t "itemize")))))
   3068     (org-latex--wrap-label
   3069      plain-list
   3070      (format "\\begin{%s}%s\n%s\\end{%s}"
   3071 	     latex-type
   3072 	     (or (plist-get attr :options) "")
   3073 	     contents
   3074 	     latex-type)
   3075      info)))
   3076 
   3077 
   3078 ;;;; Plain Text
   3079 
   3080 (defun org-latex-plain-text (text info)
   3081   "Transcode a TEXT string from Org to LaTeX.
   3082 TEXT is the string to transcode.  INFO is a plist holding
   3083 contextual information."
   3084   (let* ((specialp (plist-get info :with-special-strings))
   3085 	 (output
   3086 	  ;; Turn LaTeX into \LaTeX{} and TeX into \TeX{}.
   3087 	  (let ((case-fold-search nil))
   3088 	    (replace-regexp-in-string
   3089 	     "\\<\\(?:La\\)?TeX\\>" "\\\\\\&{}"
   3090 	     ;; Protect ^, ~, %, #, &, $, _, { and }.  Also protect \.
   3091 	     ;; However, if special strings are used, be careful not
   3092 	     ;; to protect "\" in "\-" constructs.
   3093 	     (replace-regexp-in-string
   3094 	      (concat "[%$#&{}_~^]\\|\\\\" (and specialp "\\([^-]\\|$\\)"))
   3095 	      (lambda (m)
   3096 		(cl-case (string-to-char m)
   3097 		  (?\\ "$\\\\backslash$\\1")
   3098 		  (?~ "\\\\textasciitilde{}")
   3099 		  (?^ "\\\\^{}")
   3100 		  (t "\\\\\\&")))
   3101 	      text)))))
   3102     ;; Activate smart quotes.  Be sure to provide original TEXT string
   3103     ;; since OUTPUT may have been modified.
   3104     (when (plist-get info :with-smart-quotes)
   3105       (setq output (org-export-activate-smart-quotes output :latex info text)))
   3106     ;; Convert special strings.
   3107     (when specialp
   3108       (setq output (replace-regexp-in-string "\\.\\.\\." "\\\\ldots{}" output)))
   3109     ;; Handle break preservation if required.
   3110     (when (plist-get info :preserve-breaks)
   3111       (setq output (replace-regexp-in-string
   3112 		    "\\(?:[ \t]*\\\\\\\\\\)?[ \t]*\n" "\\\\\n" output nil t)))
   3113     ;; Protect [foo] at the beginning of lines / beginning of the
   3114     ;; plain-text object.  This prevents LaTeX from unexpectedly
   3115     ;; interpreting @@latex:\pagebreak@@ [foo] as a command with
   3116     ;; optional argument.
   3117     (setq output (replace-regexp-in-string
   3118                   (rx bol (0+ space) (group "["))
   3119                   "{[}"
   3120                   output
   3121                   nil nil 1))
   3122     ;; Return value.
   3123     output))
   3124 
   3125 
   3126 ;;;; Planning
   3127 
   3128 (defun org-latex-planning (planning _contents info)
   3129   "Transcode a PLANNING element from Org to LaTeX.
   3130 CONTENTS is nil.  INFO is a plist holding contextual
   3131 information."
   3132   (concat
   3133    "\\noindent"
   3134    (mapconcat
   3135     'identity
   3136     (delq nil
   3137 	  (list
   3138 	   (let ((closed (org-element-property :closed planning)))
   3139 	     (when closed
   3140 	       (concat
   3141 		(format "\\textbf{%s} " org-closed-string)
   3142 		(format (plist-get info :latex-inactive-timestamp-format)
   3143 			(org-timestamp-translate closed)))))
   3144 	   (let ((deadline (org-element-property :deadline planning)))
   3145 	     (when deadline
   3146 	       (concat
   3147 		(format "\\textbf{%s} " org-deadline-string)
   3148 		(format (plist-get info :latex-active-timestamp-format)
   3149 			(org-timestamp-translate deadline)))))
   3150 	   (let ((scheduled (org-element-property :scheduled planning)))
   3151 	     (when scheduled
   3152 	       (concat
   3153 		(format "\\textbf{%s} " org-scheduled-string)
   3154 		(format (plist-get info :latex-active-timestamp-format)
   3155 			(org-timestamp-translate scheduled)))))))
   3156     " ")
   3157    "\\\\"))
   3158 
   3159 
   3160 ;;;; Property Drawer
   3161 
   3162 (defun org-latex-property-drawer (_property-drawer contents _info)
   3163   "Transcode a PROPERTY-DRAWER element from Org to LaTeX.
   3164 CONTENTS holds the contents of the drawer.  INFO is a plist
   3165 holding contextual information."
   3166   (and (org-string-nw-p contents)
   3167        (format "\\begin{verbatim}\n%s\\end{verbatim}" contents)))
   3168 
   3169 
   3170 ;;;; Pseudo Element: LaTeX Matrices
   3171 
   3172 ;; `latex-matrices' elements have the following properties:
   3173 ;; `:caption', `:post-blank' and `:markup' (`inline', `equation' or
   3174 ;; `math').
   3175 
   3176 (defun org-latex--wrap-latex-matrices (data info)
   3177   "Merge contiguous tables with the same mode within a pseudo-element.
   3178 DATA is a parse tree or a secondary string.  INFO is a plist
   3179 containing export options.  Modify DATA by side-effect and return
   3180 it."
   3181   (org-element-map data 'table
   3182     (lambda (table)
   3183       (when (eq (org-element-property :type table) 'org)
   3184 	(let ((mode (or (org-export-read-attribute :attr_latex table :mode)
   3185 			(plist-get info :latex-default-table-mode))))
   3186 	  (when (and (member mode '("inline-math" "math"))
   3187 		     ;; Do not wrap twice the same table.
   3188 		     (not (org-element-type-p
   3189 			 (org-element-parent table) 'latex-matrices)))
   3190 	    (let* ((caption (and (not (string= mode "inline-math"))
   3191 				 (org-element-property :caption table)))
   3192 		   (name (and (not (string= mode "inline-math"))
   3193 			      (org-element-property :name table)))
   3194 		   (matrices
   3195 		    (list 'latex-matrices
   3196 			  ;; Inherit name from the first table.
   3197 			  (list :name name
   3198 				;; FIXME: what syntax for captions?
   3199 				;;
   3200 				;; :caption caption
   3201 				:markup
   3202 				(cond ((string= mode "inline-math") 'inline)
   3203 				      ((or caption name) 'equation)
   3204 				      (t 'math)))))
   3205 		   (previous table)
   3206 		   (next (org-export-get-next-element table info)))
   3207 	      (org-element-insert-before matrices table)
   3208 	      ;; Swallow all contiguous tables sharing the same mode.
   3209 	      (while (and
   3210 		      (zerop (or (org-element-property :post-blank previous) 0))
   3211 		      (setq next (org-export-get-next-element previous info))
   3212 		      (org-element-type-p next 'table)
   3213 		      (eq (org-element-property :type next) 'org)
   3214 		      (string= (or (org-export-read-attribute
   3215 				    :attr_latex next :mode)
   3216 				   (plist-get info :latex-default-table-mode))
   3217 			       mode))
   3218 		(org-element-put-property table :name nil)
   3219 		(org-element-put-property table :caption nil)
   3220 		(org-element-extract previous)
   3221 		(org-element-adopt matrices previous)
   3222 		(setq previous next))
   3223 	      ;; Inherit `:post-blank' from the value of the last
   3224 	      ;; swallowed table.  Set the latter's `:post-blank'
   3225 	      ;; value to 0 so as to not duplicate empty lines.
   3226 	      (org-element-put-property
   3227 	       matrices :post-blank (org-element-property :post-blank previous))
   3228 	      (org-element-put-property previous :post-blank 0)
   3229 	      (org-element-put-property table :name nil)
   3230 	      (org-element-put-property table :caption nil)
   3231 	      (org-element-extract previous)
   3232 	      (org-element-adopt matrices previous))))))
   3233     info)
   3234   data)
   3235 
   3236 (defun org-latex-matrices (matrices contents info)
   3237   "Transcode a MATRICES element from Org to LaTeX.
   3238 CONTENTS is a string.  INFO is a plist used as a communication
   3239 channel."
   3240   (pcase (org-element-property :markup matrices)
   3241     (`inline (format "\\(%s\\)" contents))
   3242     (`equation
   3243      (let ((caption (org-latex--caption/label-string matrices info))
   3244 	   (caption-above? (org-latex--caption-above-p matrices info)))
   3245        (concat "\\begin{equation}\n"
   3246 	       (and caption-above? caption)
   3247 	       contents
   3248 	       (and (not caption-above?) caption)
   3249 	       "\\end{equation}")))
   3250     (_
   3251      (format "\\[\n%s\\]" contents))))
   3252 
   3253 
   3254 ;;;; Pseudo Object: LaTeX Math Block
   3255 
   3256 ;; `latex-math-block' objects have the following property:
   3257 ;; `:post-blank'.
   3258 
   3259 (defun org-latex--wrap-latex-math-block (data info)
   3260   "Merge contiguous math objects in a pseudo-object container.
   3261 DATA is a parse tree or a secondary string.  INFO is a plist
   3262 containing export options.  Modify DATA by side-effect and return it."
   3263   (let ((valid-object-p
   3264 	 ;; Non-nil when OBJECT can be added to a latex math block.
   3265 	 (lambda (object)
   3266 	   (pcase (org-element-type object)
   3267 	     (`entity (org-element-property :latex-math-p object))
   3268 	     (`latex-fragment
   3269 	      (let ((value (org-element-property :value object)))
   3270 		(or (string-prefix-p "\\(" value)
   3271 		    (string-match-p "\\`\\$[^$]" value))))))))
   3272     (org-element-map data '(entity latex-fragment)
   3273       (lambda (object)
   3274 	;; Skip objects already wrapped.
   3275 	(when (and (not (org-element-type-p
   3276 		       (org-element-parent object) 'latex-math-block))
   3277 		   (funcall valid-object-p object))
   3278 	  (let ((math-block (list 'latex-math-block nil))
   3279 		(next-elements (org-export-get-next-element object info t))
   3280 		(last object))
   3281 	    ;; Wrap MATH-BLOCK around OBJECT in DATA.
   3282 	    (org-element-insert-before math-block object)
   3283 	    (org-element-extract object)
   3284 	    (org-element-adopt math-block object)
   3285 	    (when (zerop (or (org-element-property :post-blank object) 0))
   3286 	      ;; MATH-BLOCK swallows consecutive math objects.
   3287 	      (catch 'exit
   3288 		(dolist (next next-elements)
   3289 		  (unless (funcall valid-object-p next) (throw 'exit nil))
   3290 		  (org-element-extract next)
   3291 		  (org-element-adopt math-block next)
   3292 		  ;; Eschew the case: \beta$x$ -> \(\betax\).
   3293 		  (org-element-put-property last :post-blank 1)
   3294 		  (setq last next)
   3295 		  (when (> (or (org-element-property :post-blank next) 0) 0)
   3296 		    (throw 'exit nil)))))
   3297 	    (org-element-put-property
   3298 	     math-block :post-blank (org-element-property :post-blank last)))))
   3299       info nil '(latex-math-block) t)
   3300     ;; Return updated DATA.
   3301     data))
   3302 
   3303 (defun org-latex-math-block (_math-block contents _info)
   3304   "Transcode a MATH-BLOCK object from Org to LaTeX.
   3305 CONTENTS is a string.  INFO is a plist used as a communication
   3306 channel."
   3307   (when (org-string-nw-p contents)
   3308     (format "\\(%s\\)" (org-trim contents))))
   3309 
   3310 ;;;; Quote Block
   3311 
   3312 (defun org-latex-quote-block (quote-block contents info)
   3313   "Transcode a QUOTE-BLOCK element from Org to LaTeX.
   3314 CONTENTS holds the contents of the block.  INFO is a plist
   3315 holding contextual information."
   3316   (let ((environment
   3317 	 (or (org-export-read-attribute :attr_latex quote-block :environment)
   3318 	     (plist-get info :latex-default-quote-environment)))
   3319 	(options
   3320 	 (or (org-export-read-attribute :attr_latex quote-block :options)
   3321 	     "")))
   3322     (org-latex--wrap-label
   3323      quote-block (format "\\begin{%s}%s\n%s\\end{%s}"
   3324 			 environment
   3325 			 options
   3326 			 contents
   3327 			 environment)
   3328      info)))
   3329 
   3330 ;;;; Radio Target
   3331 
   3332 (defun org-latex-radio-target (radio-target text info)
   3333   "Transcode a RADIO-TARGET object from Org to LaTeX.
   3334 TEXT is the text of the target.  INFO is a plist holding
   3335 contextual information."
   3336   (format "\\label{%s}%s" (org-export-get-reference radio-target info) text))
   3337 
   3338 
   3339 ;;;; Section
   3340 
   3341 (defun org-latex-section (_section contents _info)
   3342   "Transcode a SECTION element from Org to LaTeX.
   3343 CONTENTS holds the contents of the section.  INFO is a plist
   3344 holding contextual information."
   3345   contents)
   3346 
   3347 
   3348 ;;;; Special Block
   3349 
   3350 (defun org-latex-special-block (special-block contents info)
   3351   "Transcode a SPECIAL-BLOCK element from Org to LaTeX.
   3352 CONTENTS holds the contents of the block.  INFO is a plist
   3353 holding contextual information."
   3354   (let ((type (org-element-property :type special-block))
   3355 	(opt (org-export-read-attribute :attr_latex special-block :options))
   3356 	(caption (org-latex--caption/label-string special-block info))
   3357 	(caption-above-p (org-latex--caption-above-p special-block info)))
   3358     (concat (format "\\begin{%s}%s\n" type (or opt ""))
   3359 	    (and caption-above-p caption)
   3360 	    contents
   3361 	    (and (not caption-above-p) caption)
   3362 	    (format "\\end{%s}" type))))
   3363 
   3364 
   3365 ;;;; Src Block
   3366 
   3367 (defun org-latex-src-block (src-block _contents info)
   3368   "Transcode a SRC-BLOCK element from Org to LaTeX.
   3369 CONTENTS holds the contents of the item.  INFO is a plist holding
   3370 contextual information."
   3371   (when (org-string-nw-p (org-element-property :value src-block))
   3372     (let* ((lang (org-element-property :language src-block))
   3373            (caption (org-element-property :caption src-block))
   3374            (caption-above-p (org-latex--caption-above-p src-block info))
   3375            (label (org-element-property :name src-block))
   3376            (custom-env (and lang
   3377                             (cadr (assq (intern lang)
   3378                                         org-latex-custom-lang-environments))))
   3379            (num-start (org-export-get-loc src-block info))
   3380            (retain-labels (org-element-property :retain-labels src-block))
   3381            (attributes (org-export-read-attribute :attr_latex src-block))
   3382            (float (plist-get attributes :float)))
   3383       (funcall
   3384        (pcase (plist-get info :latex-src-block-backend)
   3385          ((or `verbatim (guard (not lang))) #'org-latex-src-block--verbatim)
   3386          (`minted #'org-latex-src-block--minted)
   3387          (`engraved #'org-latex-src-block--engraved)
   3388          (`listings #'org-latex-src-block--listings)
   3389          ((guard custom-env) #'org-latex-src-block--custom)
   3390          (oldval
   3391           (warn "Please update `org-latex-src-block-backend' to %s"
   3392                 (if oldval "listings" "verbatim"))
   3393           (if oldval
   3394               #'org-latex-src-block--listings
   3395             #'org-latex-src-block--verbatim)))
   3396        :src-block src-block
   3397        :info info
   3398        :lang lang
   3399        :caption caption
   3400        :caption-above-p caption-above-p
   3401        :label label
   3402        :num-start num-start
   3403        :retain-labels retain-labels
   3404        :attributes attributes
   3405        :float float
   3406        :custom-env custom-env))))
   3407 
   3408 (cl-defun org-latex-src-block--verbatim
   3409     (&key src-block info caption caption-above-p float &allow-other-keys)
   3410   "Transcode a SRC-BLOCK element from Org to LaTeX, using verbatim.
   3411 LANG, CAPTION, CAPTION-ABOVE-P, LABEL, NUM-START, RETAIN-LABELS, ATTRIBUTES
   3412 and FLOAT are extracted from SRC-BLOCK and INFO in `org-latex-src-block'."
   3413   (let ((caption-str (org-latex--caption/label-string src-block info))
   3414         (verbatim (format "\\begin{verbatim}\n%s\\end{verbatim}"
   3415                           (org-export-format-code-default src-block info))))
   3416     (cond ((string= "multicolumn" float)
   3417            (format "\\begin{figure*}[%s]\n%s%s\n%s\\end{figure*}"
   3418                    (plist-get info :latex-default-figure-position)
   3419                    (if caption-above-p caption-str "")
   3420                    verbatim
   3421                    (if caption-above-p "" caption-str)))
   3422           (caption (concat
   3423                     (if caption-above-p caption-str "")
   3424                     verbatim
   3425                     (if caption-above-p "" (concat "\n" caption-str))))
   3426           (t verbatim))))
   3427 
   3428 (cl-defun org-latex-src-block--custom
   3429     (&key src-block info caption caption-above-p attributes float custom-env &allow-other-keys)
   3430   "Transcode a SRC-BLOCK element from Org to LaTeX, using a custom environment.
   3431 LANG, CAPTION, CAPTION-ABOVE-P, LABEL, NUM-START, RETAIN-LABELS, ATTRIBUTES
   3432 and FLOAT are extracted from SRC-BLOCK and INFO in `org-latex-src-block'."
   3433   (let ((caption-str (org-latex--caption/label-string src-block info))
   3434         (formatted-src (org-export-format-code-default src-block info)))
   3435     (if (string-match-p "\\`[a-zA-Z0-9]+\\'" custom-env)
   3436         (format "\\begin{%s}\n%s\\end{%s}\n"
   3437                 custom-env
   3438                 (concat (and caption-above-p caption-str)
   3439                         formatted-src
   3440                         (and (not caption-above-p) caption-str))
   3441                 custom-env)
   3442       (format-spec custom-env
   3443                    `((?s . ,formatted-src)
   3444                      (?c . ,caption)
   3445                      (?f . ,float)
   3446                      (?l . ,(org-latex--label src-block info))
   3447                      (?o . ,(or (plist-get attributes :options) "")))))))
   3448 
   3449 (cl-defun org-latex-src-block--minted
   3450     (&key src-block info lang caption caption-above-p num-start retain-labels attributes float &allow-other-keys)
   3451   "Transcode a SRC-BLOCK element from Org to LaTeX, using minted.
   3452 LANG, CAPTION, CAPTION-ABOVE-P, LABEL, NUM-START, RETAIN-LABELS, ATTRIBUTES
   3453 and FLOAT are extracted from SRC-BLOCK and INFO in `org-latex-src-block'."
   3454   (let* ((caption-str (org-latex--caption/label-string src-block info))
   3455          (placement (or (org-unbracket-string "[" "]" (plist-get attributes :placement))
   3456                         (plist-get info :latex-default-figure-position)))
   3457          (multicolumn-p (string= "multicolumn" float))
   3458          (float-env
   3459           (cond
   3460            ((or caption multicolumn-p)
   3461             (cons
   3462              (concat "\\begin{listing" (when multicolumn-p "*")
   3463                      "}[" placement "]\n"
   3464                      (if caption-above-p caption-str ""))
   3465              (concat "\n" (if caption-above-p "" caption-str)
   3466                      "\\end{listing" (when multicolumn-p "*") "}")))
   3467            ((string= "t" float)
   3468             (cons
   3469              (concat "\\begin{listing}[" placement "]\n")
   3470              "\n\\end{listing}"))))
   3471          (options (plist-get info :latex-minted-options))
   3472          (body
   3473           (format
   3474            "\\begin{minted}[%s]{%s}\n%s\\end{minted}"
   3475            ;; Options.
   3476            (concat
   3477             (org-latex--make-option-string
   3478              (if (or (not num-start) (assoc "linenos" options))
   3479                  options
   3480                (append
   3481                 `(("linenos")
   3482                   ("firstnumber" ,(number-to-string (1+ num-start))))
   3483                 options)))
   3484             (let ((local-options (plist-get attributes :options)))
   3485               (and local-options (concat "," local-options))))
   3486            ;; Language.
   3487            (or (cadr (assq (intern lang)
   3488                            (plist-get info :latex-minted-langs)))
   3489                (downcase lang))
   3490            ;; Source code.
   3491            (let* ((code-info (org-export-unravel-code src-block))
   3492                   (max-width
   3493                    (apply 'max
   3494                           (mapcar 'string-width
   3495                                   (org-split-string (car code-info)
   3496                                                     "\n")))))
   3497              (org-export-format-code
   3498               (car code-info)
   3499               (lambda (loc _num ref)
   3500                 (concat
   3501                  loc
   3502                  (when ref
   3503                    ;; Ensure references are flushed to the right,
   3504                    ;; separated with 6 spaces from the widest line
   3505                    ;; of code.
   3506                    (concat (make-string (+ (- max-width (length loc)) 6)
   3507                                         ?\s)
   3508                            (format "(%s)" ref)))))
   3509               nil (and retain-labels (cdr code-info)))))))
   3510     (concat (car float-env) body (cdr float-env))))
   3511 
   3512 (defun org-latex-src--engrave-mathescape-p (info options)
   3513   "From the export INFO plist, and the per-block OPTIONS, determine mathescape."
   3514   (let ((default-options (plist-get info :latex-engraved-options))
   3515         (mathescape-status
   3516          (lambda (opts)
   3517            (cl-some
   3518             (lambda (opt)
   3519               (or (and
   3520                    (null (cdr opt))
   3521                    (cond
   3522                     ((string-match-p
   3523                       "\\(?:^\\|,\\)mathescape=false\\(?:,\\|$\\)"
   3524                       (car opt))
   3525                      'no)
   3526                     ((or (string-match-p
   3527                           "\\(?:^\\|,\\)mathescape\\(?:=true\\)?\\(?:,\\|$\\)"
   3528                           (car opt))
   3529                          (string= "mathescape" (car opt)))
   3530                      'yes)))
   3531                   (and
   3532                    (string= (car opt) "mathescape")
   3533                    (cond
   3534                     ((or (and (stringp (cdr opt)) (string= (cdr opt) "true"))
   3535                          (equal '("true") (cdr opt)))
   3536                      'yes)
   3537                     ((or (and (stringp (cdr opt)) (string= "false" (cdr opt)))
   3538                          (equal '("false") (cdr opt)))
   3539                      'no)))))
   3540             opts))))
   3541     (let ((mathescape (or (funcall mathescape-status default-options)
   3542                           (funcall mathescape-status options))))
   3543       (when (eq mathescape 'yes)
   3544         (or engrave-faces-latex-mathescape t)))))
   3545 
   3546 (defun org-latex-src--engrave-code (content lang &optional theme options inline)
   3547   "Engrave CONTENT to LaTeX in a LANG-mode buffer, and give the result.
   3548 When the THEME symbol is non-nil, that theme will be used.
   3549 
   3550 When INLINE is nil, a Verbatim environment wrapped in a Code
   3551 environment will be used.  When t, a Verb command will be used.
   3552 
   3553 When OPTIONS is provided, as either a string or list of key-value
   3554 pairs accepted by `org-latex--make-option-string', it is passed
   3555 to the Verbatim environment or Verb command."
   3556   (if (require 'engrave-faces-latex nil t)
   3557       (let* ((lang-mode (and lang (org-src-get-lang-mode lang)))
   3558              (engrave-faces-current-preset-style
   3559               (if theme
   3560                   (engrave-faces-get-theme theme)
   3561                 engrave-faces-current-preset-style))
   3562              (engraved-buffer
   3563               (with-temp-buffer
   3564                 (insert (replace-regexp-in-string "\n\\'" "" content))
   3565                 (when lang-mode
   3566                   (if (functionp lang-mode)
   3567                       (funcall lang-mode)
   3568                     (warn "Cannot engrave code as %s. %s is undefined."
   3569                           lang lang-mode)))
   3570                 (engrave-faces-latex-buffer)))
   3571              (engraved-code
   3572               (with-current-buffer engraved-buffer
   3573                 (buffer-string)))
   3574              (engraved-options
   3575               (when options
   3576                 (concat "["
   3577                         (if (listp options)
   3578                             (org-latex--make-option-string options)
   3579                           options)
   3580                         "]")))
   3581              (engraved-wrapped
   3582               (if inline
   3583                   (concat "\\Verb" engraved-options "{" engraved-code "}")
   3584                 (concat "\\begin{Code}\n\\begin{Verbatim}" engraved-options "\n"
   3585                         engraved-code "\n\\end{Verbatim}\n\\end{Code}"))))
   3586         (kill-buffer engraved-buffer)
   3587         (if theme
   3588             (concat "{\\engravedtheme"
   3589                     (replace-regexp-in-string "[^A-Za-z]" ""
   3590                                               (symbol-name theme))
   3591                     engraved-wrapped
   3592                     "}")
   3593           engraved-wrapped))
   3594     (user-error "Cannot engrave code as `engrave-faces-latex' is unavailable")))
   3595 
   3596 (cl-defun org-latex-src-block--engraved
   3597     (&key src-block info lang caption caption-above-p num-start retain-labels attributes float &allow-other-keys)
   3598   "Transcode a SRC-BLOCK element from Org to LaTeX, using engrave-faces-latex.
   3599 LANG, CAPTION, CAPTION-ABOVE-P, LABEL, NUM-START, RETAIN-LABELS, ATTRIBUTES
   3600 and FLOAT are extracted from SRC-BLOCK and INFO in `org-latex-src-block'."
   3601   (let* ((caption-str (org-latex--caption/label-string src-block info))
   3602          (placement (or (org-unbracket-string "[" "]" (plist-get attributes :placement))
   3603                         (plist-get info :latex-default-figure-position)))
   3604          (multicolumn-p (string= "multicolumn" float))
   3605          (float-env
   3606           (cond
   3607            ((or caption multicolumn-p)
   3608             (cons
   3609              (concat "\\begin{listing" (when multicolumn-p "*")
   3610                      "}[" placement "]\n"
   3611                      (if caption-above-p caption-str ""))
   3612              (concat "\n" (if caption-above-p "" caption-str)
   3613                      "\\end{listing" (when multicolumn-p "*") "}")))
   3614            ((string= "t" float)
   3615             (cons
   3616              (concat "\\begin{listing}[" placement "]\n")
   3617              "\n\\end{listing}"))))
   3618          (options
   3619           (let ((engraved-options (plist-get info :latex-engraved-options))
   3620                 (local-options (plist-get attributes :options)))
   3621             (append
   3622              (when (and num-start (not (assoc "linenos" engraved-options)))
   3623                `(("linenos")
   3624                  ("firstnumber" ,(number-to-string (1+ num-start)))))
   3625              (and local-options `((,local-options))))))
   3626          (engraved-theme (plist-get attributes :engraved-theme))
   3627          (content
   3628           (let* ((code-info (org-export-unravel-code src-block))
   3629                  (max-width
   3630                   (apply 'max
   3631                          (mapcar 'string-width
   3632                                  (org-split-string (car code-info)
   3633                                                    "\n")))))
   3634             (org-export-format-code
   3635              (car code-info)
   3636              (lambda (loc _num ref)
   3637                (concat
   3638                 loc
   3639                 (when ref
   3640                   ;; Ensure references are flushed to the right,
   3641                   ;; separated with 6 spaces from the widest line
   3642                   ;; of code.
   3643                   (concat (make-string (+ (- max-width (length loc)) 6)
   3644                                        ?\s)
   3645                           (format "(%s)" ref)))))
   3646              nil (and retain-labels (cdr code-info)))))
   3647          (body
   3648           (let ((engrave-faces-latex-mathescape
   3649                  (org-latex-src--engrave-mathescape-p info options)))
   3650             (org-latex-src--engrave-code
   3651              content lang
   3652              (when engraved-theme (intern engraved-theme))
   3653              options))))
   3654     (concat (car float-env) body (cdr float-env))))
   3655 
   3656 (cl-defun org-latex-src-block--listings
   3657     (&key src-block info lang caption caption-above-p label num-start retain-labels attributes float &allow-other-keys)
   3658   "Transcode a SRC-BLOCK element from Org to LaTeX, using listings.
   3659 LANG, CAPTION, CAPTION-ABOVE-P, LABEL, NUM-START, RETAIN-LABELS, ATTRIBUTES
   3660 and FLOAT are extracted from SRC-BLOCK and INFO in `org-latex-src-block'."
   3661   (let ((lst-lang
   3662          (or (cadr (assq (intern lang)
   3663                          (plist-get info :latex-listings-langs)))
   3664              lang))
   3665         (caption-str
   3666          (when caption
   3667            (let ((main (org-export-get-caption src-block))
   3668                  (secondary (org-export-get-caption src-block t)))
   3669              (if (not secondary)
   3670                  (format "{%s}" (org-export-data main info))
   3671                (format "{[%s]%s}"
   3672                        (org-export-data secondary info)
   3673                        (org-export-data main info))))))
   3674         (lst-opt (plist-get info :latex-listings-options)))
   3675     (concat
   3676      (format
   3677       "\\begin{lstlisting}[%s]\n%s\\end{lstlisting}"
   3678       ;; Options.
   3679       (concat
   3680        (org-latex--make-option-string
   3681         (append
   3682          lst-opt
   3683          (cond
   3684           ((and (not float) (plist-member attributes :float)) nil)
   3685           ((string= "multicolumn" float) '(("float" "*")))
   3686           ((and float (not (assoc "float" lst-opt)))
   3687            `(("float" ,(plist-get info :latex-default-figure-position)))))
   3688          (unless (plist-get info :latex-listings-src-omit-language)
   3689            `(("language" ,lst-lang)))
   3690          (when label
   3691            `(("label" ,(org-latex--label src-block info))))
   3692          (when caption-str
   3693            `(("caption" ,caption-str)))
   3694          (when caption-str
   3695            ;; caption-above-p means captionpos is t(op)
   3696            ;; else b(ottom)
   3697            `(("captionpos" ,(if caption-above-p "t" "b"))))
   3698          (cond ((assoc "numbers" lst-opt) nil)
   3699                ((not num-start) '(("numbers" "none")))
   3700                (t `(("firstnumber" ,(number-to-string (1+ num-start)))
   3701                     ("numbers" "left"))))))
   3702        (let ((local-options (plist-get attributes :options)))
   3703          (and local-options (concat "," local-options))))
   3704       ;; Source code.
   3705       (let* ((code-info (org-export-unravel-code src-block))
   3706              (max-width
   3707               (apply 'max
   3708                      (mapcar 'string-width
   3709                              (org-split-string (car code-info) "\n")))))
   3710         (org-export-format-code
   3711          (car code-info)
   3712          (lambda (loc _num ref)
   3713            (concat
   3714             loc
   3715             (when ref
   3716               ;; Ensure references are flushed to the right,
   3717               ;; separated with 6 spaces from the widest line of
   3718               ;; code
   3719               (concat (make-string (+ (- max-width (length loc)) 6) ?\s)
   3720                       (format "(%s)" ref)))))
   3721          nil (and retain-labels (cdr code-info))))))))
   3722 
   3723 ;;;; Statistics Cookie
   3724 
   3725 (defun org-latex-statistics-cookie (statistics-cookie _contents _info)
   3726   "Transcode a STATISTICS-COOKIE object from Org to LaTeX.
   3727 CONTENTS is nil.  INFO is a plist holding contextual information."
   3728   (replace-regexp-in-string
   3729    "%" "\\%" (org-element-property :value statistics-cookie) nil t))
   3730 
   3731 
   3732 ;;;; Strike-Through
   3733 
   3734 (defun org-latex-strike-through (_strike-through contents info)
   3735   "Transcode STRIKE-THROUGH from Org to LaTeX.
   3736 CONTENTS is the text with strike-through markup.  INFO is a plist
   3737 holding contextual information."
   3738   (org-latex--text-markup contents 'strike-through info))
   3739 
   3740 
   3741 ;;;; Subscript
   3742 
   3743 (defun org-latex-subscript (_subscript contents _info)
   3744   "Transcode a SUBSCRIPT object from Org to LaTeX.
   3745 CONTENTS is the contents of the object."
   3746   (format "\\textsubscript{%s}" contents))
   3747 
   3748 
   3749 ;;;; Superscript
   3750 
   3751 (defun org-latex-superscript (_superscript contents _info)
   3752   "Transcode a SUPERSCRIPT object from Org to LaTeX.
   3753 CONTENTS is the contents of the object."
   3754   (format "\\textsuperscript{%s}" contents))
   3755 
   3756 
   3757 ;;;; Table
   3758 ;;
   3759 ;; `org-latex-table' is the entry point for table transcoding.  It
   3760 ;; takes care of tables with a "verbatim" mode.  Otherwise, it
   3761 ;; delegates the job to either `org-latex--table.el-table',
   3762 ;; `org-latex--org-table', `org-latex--math-table' or
   3763 ;; `org-table--org-tabbing' functions,
   3764 ;; depending of the type of the table and the mode requested.
   3765 ;;
   3766 ;; `org-latex--align-string' is a subroutine used to build alignment
   3767 ;; string for Org tables.
   3768 
   3769 (defun org-latex-table (table contents info)
   3770   "Transcode a TABLE element from Org to LaTeX.
   3771 CONTENTS is the contents of the table.  INFO is a plist holding
   3772 contextual information."
   3773   (if (eq (org-element-property :type table) 'table.el)
   3774       ;; "table.el" table.  Convert it using appropriate tools.
   3775       (org-latex--table.el-table table info)
   3776     (let ((type (or (org-export-read-attribute :attr_latex table :mode)
   3777 		    (plist-get info :latex-default-table-mode))))
   3778       (cond
   3779        ;; Case 1: Verbatim table.
   3780        ((string= type "verbatim")
   3781 	(format "\\begin{verbatim}\n%s\n\\end{verbatim}"
   3782 		;; Re-create table, without affiliated keywords.
   3783 		(org-trim (org-element-interpret-data
   3784 			   `(table nil ,@(org-element-contents table))))))
   3785        ;; Case 2: Matrix.
   3786        ((or (string= type "math") (string= type "inline-math"))
   3787         (org-latex--math-table table info))
   3788        ;; Case 3: Tabbing
   3789        ((string= type "tabbing")
   3790         (org-table--org-tabbing table contents info))
   3791        ;; Case 4: Standard table.
   3792        (t (concat (org-latex--org-table table contents info)
   3793 		  ;; When there are footnote references within the
   3794 		  ;; table, insert their definition just after it.
   3795 		  (org-latex--delayed-footnotes-definitions table info)))))))
   3796 
   3797 (defun org-latex--align-string (table info &optional math?)
   3798   "Return an appropriate LaTeX alignment string.
   3799 TABLE is the considered table.  INFO is a plist used as
   3800 a communication channel.  When optional argument MATH? is
   3801 non-nil, TABLE is meant to be a matrix, where all cells are
   3802 centered."
   3803   (or (org-export-read-attribute :attr_latex table :align)
   3804       (let (align)
   3805 	;; Extract column groups and alignment from first (non-rule)
   3806 	;; row.
   3807 	(org-element-map
   3808 	    (org-element-map table 'table-row
   3809 	      (lambda (row)
   3810 		(and (eq (org-element-property :type row) 'standard) row))
   3811 	      info 'first-match)
   3812 	    'table-cell
   3813 	  (lambda (cell)
   3814 	    (let ((borders (org-export-table-cell-borders cell info)))
   3815 	      ;; Check left border for the first cell only.
   3816 	      (when (and (memq 'left borders) (not align))
   3817 		(push "|" align))
   3818 	      (push (if math? "c"	;center cells in matrices
   3819 		      (cl-case (org-export-table-cell-alignment cell info)
   3820 			(left "l")
   3821 			(right "r")
   3822 			(center "c")))
   3823 		    align)
   3824 	      (when (memq 'right borders) (push "|" align))))
   3825 	  info)
   3826 	(apply 'concat (nreverse align)))))
   3827 
   3828 (defun org-latex--align-string-tabbing (table info)
   3829   "Return LaTeX alignment string using tabbing environment.
   3830 TABLE is the considered table.  INFO is a plist used as
   3831 a communication channel."
   3832   (or (org-export-read-attribute :attr_latex table :align)
   3833       (let* ((count
   3834               ;; Count the number of cells in the first row.
   3835               (length
   3836                (org-element-map
   3837                    (org-element-map table 'table-row
   3838                      (lambda (row)
   3839                        (and (eq (org-element-property :type row)
   3840                                 'standard)
   3841                             row))
   3842                      info 'first-match)
   3843                    'table-cell #'identity)))
   3844              ;; Calculate the column width, using a proportion of
   3845              ;; the document's textwidth.
   3846              (separator
   3847               (format "\\hspace{%s\\textwidth} \\= "
   3848                       (- (/  1.0 count) 0.01))))
   3849         (concat (apply 'concat (make-list count separator))
   3850                 "\\kill"))))
   3851 
   3852 (defun org-latex--decorate-table (table attributes caption above? info)
   3853   "Decorate TABLE string with caption and float environment.
   3854 
   3855 ATTRIBUTES is the plist containing LaTeX attributes.  CAPTION is
   3856 its caption, as a string or nil.  It is located above the table
   3857 if ABOVE? is non-nil.  INFO is the plist containing current
   3858 export parameters.
   3859 
   3860 Return new environment, as a string."
   3861   (let* ((float-environment
   3862 	  (let ((float (plist-get attributes :float)))
   3863 	    (cond ((and (not float) (plist-member attributes :float)) nil)
   3864 		  ((member float '("sidewaystable" "sideways")) "sidewaystable")
   3865 		  ((equal float "multicolumn") "table*")
   3866                   ((string= float "t") "table")
   3867                   (float float)
   3868 		  ((org-string-nw-p caption) "table")
   3869 		  (t nil))))
   3870 	 (placement
   3871 	  (or (plist-get attributes :placement)
   3872 	      (format "[%s]" (plist-get info :latex-default-figure-position))))
   3873 	 (center? (if (plist-member attributes :center)
   3874 		      (plist-get attributes :center)
   3875 		    (plist-get info :latex-tables-centered)))
   3876 	 (fontsize (let ((font (plist-get attributes :font)))
   3877 		     (and font (concat font "\n")))))
   3878     (concat (cond
   3879 	     (float-environment
   3880 	      (concat (format "\\begin{%s}%s\n" float-environment placement)
   3881 		      (if above? caption "")
   3882 		      (when center? "\\centering\n")
   3883 		      fontsize))
   3884 	     (caption
   3885 	      (concat (and center? "\\begin{center}\n" )
   3886 		      (if above? caption "")
   3887 		      (cond ((and fontsize center?) fontsize)
   3888 			    (fontsize (concat "{" fontsize))
   3889 			    (t nil))))
   3890 	     (center? (concat "\\begin{center}\n" fontsize))
   3891 	     (fontsize (concat "{" fontsize)))
   3892 	    table
   3893 	    (cond
   3894 	     (float-environment
   3895 	      (concat (if above? "" (concat "\n" caption))
   3896 		      (format "\n\\end{%s}" float-environment)))
   3897 	     (caption
   3898 	      (concat (if above? "" (concat "\n" caption))
   3899 		      (and center? "\n\\end{center}")
   3900 		      (and fontsize (not center?) "}")))
   3901 	     (center? "\n\\end{center}")
   3902 	     (fontsize "}")))))
   3903 
   3904 (defun org-latex--org-table (table contents info)
   3905   "Return appropriate LaTeX code for an Org table.
   3906 
   3907 TABLE is the table type element to transcode.  CONTENTS is its
   3908 contents, as a string.  INFO is a plist used as a communication
   3909 channel.
   3910 
   3911 This function assumes TABLE has `org' as its `:type' property and
   3912 `table' as its `:mode' attribute."
   3913   (let* ((attr (org-export-read-attribute :attr_latex table))
   3914 	 (alignment (org-latex--align-string table info))
   3915          (opt (org-export-read-attribute :attr_latex table :options))
   3916 	 (table-env (or (plist-get attr :environment)
   3917 			(plist-get info :latex-default-table-environment)))
   3918 	 (width
   3919 	  (let ((w (plist-get attr :width)))
   3920 	    (cond ((not w) "")
   3921 		  ((member table-env '("tabular" "longtable")) "")
   3922 		  ((member table-env '("tabu" "longtabu"))
   3923 		   (format (if (plist-get attr :spread) " spread %s "
   3924 			     " to %s ")
   3925 			   w))
   3926 		  (t (format "{%s}" w)))))
   3927 	 (caption (org-latex--caption/label-string table info))
   3928 	 (above? (org-latex--caption-above-p table info)))
   3929     (cond
   3930      ((member table-env '("longtable" "longtabu"))
   3931       (let ((fontsize (let ((font (plist-get attr :font)))
   3932 			(and font (concat font "\n")))))
   3933 	(concat (and fontsize (concat "{" fontsize))
   3934 		(format "\\begin{%s}%s{%s}\n" table-env width alignment)
   3935 		(and above?
   3936 		     (org-string-nw-p caption)
   3937 		     (concat caption "\\\\\n"))
   3938 		contents
   3939 		(and (not above?)
   3940 		     (org-string-nw-p caption)
   3941 		     (concat caption "\\\\\n"))
   3942 		(format "\\end{%s}" table-env)
   3943 		(and fontsize "}"))))
   3944      (t
   3945       (let ((output (format "\\begin{%s}%s%s{%s}\n%s\\end{%s}"
   3946 			    table-env
   3947                             (if opt (format "[%s]" opt) "")
   3948 			    width
   3949 			    alignment
   3950 			    contents
   3951 			    table-env)))
   3952 	(org-latex--decorate-table output attr caption above? info))))))
   3953 
   3954 
   3955 (defun org-table--org-tabbing (table contents info)
   3956   "Return tabbing environment LaTeX code for Org table.
   3957 TABLE is the table type element to transcode.  CONTENTS is its
   3958 contents, as a string.  INFO is a plist used as a communication
   3959 channel.
   3960 
   3961 This function assumes TABLE has `org' as its `:type' property and
   3962 `tabbing' as its `:mode' attribute."
   3963   (format "\\begin{%s}\n%s\n%s\\end{%s}"
   3964           "tabbing"
   3965           (org-latex--align-string-tabbing table info)
   3966           contents
   3967           "tabbing"))
   3968 
   3969 (defun org-latex--table.el-table (table info)
   3970   "Return appropriate LaTeX code for a table.el table.
   3971 
   3972 TABLE is the table type element to transcode.  INFO is a plist
   3973 used as a communication channel.
   3974 
   3975 This function assumes TABLE has `table.el' as its `:type'
   3976 property."
   3977   (require 'table)
   3978   ;; Ensure "*org-export-table*" buffer is empty.
   3979   (with-current-buffer (get-buffer-create "*org-export-table*")
   3980     (erase-buffer))
   3981   (let ((output
   3982 	 (replace-regexp-in-string
   3983 	  "^%.*\n" ""			;remove comments
   3984 	  (with-temp-buffer
   3985 	    (save-excursion (insert (org-element-property :value table)))
   3986 	    (re-search-forward "^[ \t]*|[^|]" nil t)
   3987 	    (table-generate-source 'latex "*org-export-table*")
   3988 	    (with-current-buffer "*org-export-table*"
   3989 	      (org-trim (buffer-string))))
   3990 	  t t)))
   3991     (kill-buffer (get-buffer "*org-export-table*"))
   3992     (let ((attr (org-export-read-attribute :attr_latex table))
   3993 	  (caption (org-latex--caption/label-string table info))
   3994 	  (above? (org-latex--caption-above-p table info)))
   3995       (when (plist-get attr :rmlines)
   3996 	;; When the "rmlines" attribute is provided, remove all hlines
   3997 	;; but the one separating heading from the table body.
   3998 	(let ((n 0) (pos 0))
   3999 	  (while (and (< (length output) pos)
   4000 		      (setq pos (string-match "^\\\\hline\n?" output pos)))
   4001 	    (cl-incf n)
   4002 	    (unless (= n 2) (setq output (replace-match "" nil nil output))))))
   4003       (org-latex--decorate-table output attr caption above? info))))
   4004 
   4005 (defun org-latex--math-table (table info)
   4006   "Return appropriate LaTeX code for a matrix.
   4007 
   4008 TABLE is the table type element to transcode.  INFO is a plist
   4009 used as a communication channel.
   4010 
   4011 This function assumes TABLE has `org' as its `:type' property and
   4012 `inline-math' or `math' as its `:mode' attribute."
   4013   (let* ((attr (org-export-read-attribute :attr_latex table))
   4014 	 (env (or (plist-get attr :environment)
   4015 		  (plist-get info :latex-default-table-environment)))
   4016 	 (contents
   4017 	  (mapconcat
   4018 	   (lambda (row)
   4019 	     (if (eq (org-element-property :type row) 'rule) "\\hline"
   4020 	       ;; Return each cell unmodified.
   4021 	       (concat
   4022 		(mapconcat
   4023 		 (lambda (cell)
   4024 		   (substring (org-element-interpret-data cell) 0 -1))
   4025 		 (org-element-map row 'table-cell #'identity info) "&")
   4026 		(or (cdr (assoc env org-latex-table-matrix-macros)) "\\\\")
   4027 		"\n")))
   4028 	   (org-element-map table 'table-row #'identity info) "")))
   4029     (concat
   4030      ;; Prefix.
   4031      (plist-get attr :math-prefix)
   4032      ;; Environment.  Also treat special cases.
   4033      (cond ((member env '("array" "tabular"))
   4034 	    (format "\\begin{%s}{%s}\n%s\\end{%s}"
   4035 		    env (org-latex--align-string table info t) contents env))
   4036 	   ((assoc env org-latex-table-matrix-macros)
   4037 	    (format "\\%s%s{\n%s}"
   4038 		    env
   4039 		    (or (plist-get attr :math-arguments) "")
   4040 		    contents))
   4041 	   (t (format "\\begin{%s}\n%s\\end{%s}" env contents env)))
   4042      ;; Suffix.
   4043      (plist-get attr :math-suffix))))
   4044 
   4045 
   4046 ;;;; Table Cell
   4047 
   4048 (defun org-latex-table-cell (table-cell contents info)
   4049   "Transcode a TABLE-CELL element from Org to LaTeX.
   4050 CONTENTS is the cell contents.  INFO is a plist used as
   4051 a communication channel."
   4052   (let ((type (org-export-read-attribute
   4053                :attr_latex (org-element-lineage table-cell 'table) :mode))
   4054         (scientific-format (plist-get info :latex-table-scientific-notation)))
   4055     (concat
   4056      (if (and contents
   4057 	      scientific-format
   4058 	      (string-match orgtbl-exp-regexp contents))
   4059 	 ;; Use appropriate format string for scientific
   4060 	 ;; notation.
   4061 	 (format scientific-format
   4062 		 (match-string 1 contents)
   4063 		 (match-string 2 contents))
   4064        contents)
   4065      (when (org-export-get-next-element table-cell info)
   4066        (if (string= type "tabbing") " \\> " " & ")))))
   4067 
   4068 
   4069 ;;;; Table Row
   4070 
   4071 (defun org-latex-table-row (table-row contents info)
   4072   "Transcode a TABLE-ROW element from Org to LaTeX.
   4073 CONTENTS is the contents of the row.  INFO is a plist used as
   4074 a communication channel."
   4075   (let* ((attr (org-export-read-attribute :attr_latex
   4076 					  (org-element-parent table-row)))
   4077 	 (booktabsp (if (plist-member attr :booktabs) (plist-get attr :booktabs)
   4078 		      (plist-get info :latex-tables-booktabs)))
   4079 	 (longtablep
   4080 	  (member (or (plist-get attr :environment)
   4081 		      (plist-get info :latex-default-table-environment))
   4082 		  '("longtable" "longtabu"))))
   4083     (if (eq (org-element-property :type table-row) 'rule)
   4084 	(cond
   4085 	 ((not booktabsp) "\\hline")
   4086 	 ((not (org-export-get-previous-element table-row info)) "\\toprule")
   4087 	 ((not (org-export-get-next-element table-row info)) "\\bottomrule")
   4088 	 ((and longtablep
   4089 	       (org-export-table-row-ends-header-p
   4090 		(org-export-get-previous-element table-row info) info))
   4091 	  "")
   4092 	 (t "\\midrule"))
   4093       ;; Memorize table header in case it is multiline. We need this
   4094       ;; information to define contents before "\\endhead" in longtable environments.
   4095       (when (org-export-table-row-in-header-p table-row info)
   4096         (let ((table-head-cache (plist-get info :org-latex-table-head-cache)))
   4097           (unless (hash-table-p table-head-cache)
   4098             (setq table-head-cache (make-hash-table :test #'eq))
   4099             (plist-put info :org-latex-table-head-cache table-head-cache))
   4100           (if-let* ((head-contents (gethash (org-element-parent table-row) table-head-cache)))
   4101               (puthash (org-element-parent table-row) (concat head-contents "\\\\\n" contents)
   4102                        table-head-cache)
   4103             (puthash (org-element-parent table-row) contents table-head-cache))))
   4104       ;; Return LaTeX string as the transcoder.
   4105       (concat
   4106        ;; When BOOKTABS are activated enforce top-rule even when no
   4107        ;; hline was specifically marked.
   4108        (and booktabsp (not (org-export-get-previous-element table-row info))
   4109 	    "\\toprule\n")
   4110        contents "\\\\\n"
   4111        (cond
   4112 	;; Special case for long tables.  Define header and footers.
   4113 	((and longtablep (org-export-table-row-ends-header-p table-row info))
   4114 	 (let ((columns (cdr (org-export-table-dimensions
   4115 			      (org-element-lineage table-row 'table) info))))
   4116 	   (format "%s
   4117 \\endfirsthead
   4118 \\multicolumn{%d}{l}{%s} \\\\
   4119 %s
   4120 %s \\\\\n
   4121 %s
   4122 \\endhead
   4123 %s\\multicolumn{%d}{r}{%s} \\\\
   4124 \\endfoot
   4125 \\endlastfoot"
   4126 		   (if booktabsp "\\midrule" "\\hline")
   4127 		   columns
   4128 		   (org-latex--translate "Continued from previous page" info)
   4129 		   (cond
   4130 		    ((not (org-export-table-row-starts-header-p table-row info))
   4131 		     "")
   4132 		    (booktabsp "\\toprule\n")
   4133 		    (t "\\hline\n"))
   4134 		   (gethash (org-element-parent table-row) (plist-get info :org-latex-table-head-cache))
   4135 		   (if booktabsp "\\midrule" "\\hline")
   4136 		   (if booktabsp "\\midrule" "\\hline")
   4137 		   columns
   4138 		   (org-latex--translate "Continued on next page" info))))
   4139 	;; When BOOKTABS are activated enforce bottom rule even when
   4140 	;; no hline was specifically marked.
   4141 	((and booktabsp (not (org-export-get-next-element table-row info)))
   4142 	 "\\bottomrule"))))))
   4143 
   4144 
   4145 ;;;; Target
   4146 
   4147 (defun org-latex-target (target _contents info)
   4148   "Transcode a TARGET object from Org to LaTeX.
   4149 CONTENTS is nil.  INFO is a plist holding contextual
   4150 information."
   4151   (format "\\label{%s}" (org-latex--label target info)))
   4152 
   4153 
   4154 ;;;; Timestamp
   4155 
   4156 (defun org-latex-timestamp (timestamp _contents info)
   4157   "Transcode a TIMESTAMP object from Org to LaTeX.
   4158 CONTENTS is nil.  INFO is a plist holding contextual
   4159 information."
   4160   (let ((value (org-latex-plain-text (org-timestamp-translate timestamp) info)))
   4161     (format
   4162      (plist-get info
   4163 		(cl-case (org-element-property :type timestamp)
   4164 		  ((active active-range) :latex-active-timestamp-format)
   4165 		  ((inactive inactive-range) :latex-inactive-timestamp-format)
   4166 		  (otherwise :latex-diary-timestamp-format)))
   4167      value)))
   4168 
   4169 
   4170 ;;;; Underline
   4171 
   4172 (defun org-latex-underline (_underline contents info)
   4173   "Transcode UNDERLINE from Org to LaTeX.
   4174 CONTENTS is the text with underline markup.  INFO is a plist
   4175 holding contextual information."
   4176   (org-latex--text-markup contents 'underline info))
   4177 
   4178 
   4179 ;;;; Verbatim
   4180 
   4181 (defun org-latex-verbatim (verbatim _contents info)
   4182   "Transcode a VERBATIM object from Org to LaTeX.
   4183 CONTENTS is nil.  INFO is a plist used as a communication
   4184 channel."
   4185   (org-latex--text-markup
   4186    (org-element-property :value verbatim) 'verbatim info))
   4187 
   4188 
   4189 ;;;; Verse Block
   4190 
   4191 (defun org-latex-verse-block (verse-block contents info)
   4192   "Transcode a VERSE-BLOCK element from Org to LaTeX.
   4193 CONTENTS is verse block contents.  INFO is a plist holding
   4194 contextual information."
   4195   (let* ((lin (org-export-read-attribute :attr_latex verse-block :lines))
   4196          (latcode (org-export-read-attribute :attr_latex verse-block :latexcode))
   4197          (cent (org-export-read-attribute :attr_latex verse-block :center))
   4198          (lit (org-export-read-attribute :attr_latex verse-block :literal))
   4199          (attr (concat
   4200 		(if cent "[\\versewidth]" "")
   4201 		(if lin (format "\n\\poemlines{%s}" lin) "")
   4202 		(if latcode (format "\n%s" latcode) "")))
   4203          (versewidth (org-export-read-attribute :attr_latex verse-block :versewidth))
   4204          (vwidth (if versewidth (format "\\settowidth{\\versewidth}{%s}\n" versewidth) ""))
   4205          (linreset (if lin "\n\\poemlines{0}" "")))
   4206     (concat
   4207      (org-latex--wrap-label
   4208       verse-block
   4209       ;; In a verse environment, add a line break to each newline
   4210       ;; character and change each white space at beginning of a line
   4211       ;; into a normal space, calculated with `\fontdimen2\font'.  One
   4212       ;; or more blank lines between lines are exported as a single
   4213       ;; blank line.  If the `:lines' attribute is used, the last
   4214       ;; verse of each stanza ends with the string `\\!', according to
   4215       ;; the syntax of the `verse' package. The separation between
   4216       ;; stanzas can be controlled with the length `\stanzaskip', of
   4217       ;; the aforementioned package.  If the `:literal' attribute is
   4218       ;; used, all blank lines are preserved and exported as
   4219       ;; `\vspace*{\baselineskip}', including the blank lines before
   4220       ;; or after CONTENTS.
   4221       (format "%s\\begin{verse}%s\n%s\\end{verse}%s"
   4222 	      vwidth
   4223 	      attr
   4224 	      (replace-regexp-in-string
   4225 	       "^[ \t]+" (lambda (m) (format "\\hspace*{%d\\fontdimen2\\font}" (length m)))
   4226 	       (replace-regexp-in-string
   4227                 (if (not lit)
   4228 		    (rx-to-string
   4229                      `(seq (group "\\\\\n")
   4230 		           (1+ (group line-start (0+ space) "\\\\\n"))))
   4231 		  "^[ \t]*\\\\$")
   4232 	        (if (not lit)
   4233 		    (if lin "\\\\!\n\n" "\n\n")
   4234 		  "\\vspace*{\\baselineskip}")
   4235 	        (replace-regexp-in-string
   4236 	         "\\([ \t]*\\\\\\\\\\)?[ \t]*\n"
   4237                  "\\\\\n"
   4238 	         (if (not lit)
   4239 		     (concat (org-trim contents t) "\n")
   4240 		   contents)
   4241                  nil t)
   4242                 nil t)
   4243                nil t)
   4244               linreset)
   4245       info)
   4246      ;; Insert footnote definitions, if any, after the environment, so
   4247      ;; the special formatting above is not applied to them.
   4248      (org-latex--delayed-footnotes-definitions verse-block info))))
   4249 
   4250 
   4251 ;;; End-user functions
   4252 
   4253 ;;;###autoload
   4254 (defun org-latex-export-as-latex
   4255     (&optional async subtreep visible-only body-only ext-plist)
   4256   "Export current buffer as a LaTeX buffer.
   4257 
   4258 If narrowing is active in the current buffer, only export its
   4259 narrowed part.
   4260 
   4261 If a region is active, export that region.
   4262 
   4263 A non-nil optional argument ASYNC means the process should happen
   4264 asynchronously.  The resulting buffer should be accessible
   4265 through the `org-export-stack' interface.
   4266 
   4267 When optional argument SUBTREEP is non-nil, export the sub-tree
   4268 at point, extracting information from the headline properties
   4269 first.
   4270 
   4271 When optional argument VISIBLE-ONLY is non-nil, don't export
   4272 contents of hidden elements.
   4273 
   4274 When optional argument BODY-ONLY is non-nil, only write code
   4275 between \"\\begin{document}\" and \"\\end{document}\".
   4276 
   4277 EXT-PLIST, when provided, is a property list with external
   4278 parameters overriding Org default settings, but still inferior to
   4279 file-local settings.
   4280 
   4281 Export is done in a buffer named \"*Org LATEX Export*\", which
   4282 will be displayed when `org-export-show-temporary-export-buffer'
   4283 is non-nil."
   4284   (interactive)
   4285   (org-export-to-buffer 'latex "*Org LATEX Export*"
   4286     async subtreep visible-only body-only ext-plist
   4287     (if (fboundp 'major-mode-remap)
   4288         (major-mode-remap 'latex-mode)
   4289       #'LaTeX-mode)))
   4290 
   4291 ;;;###autoload
   4292 (defun org-latex-convert-region-to-latex ()
   4293   "Assume the current region has Org syntax, and convert it to LaTeX.
   4294 This can be used in any buffer.  For example, you can write an
   4295 itemized list in Org syntax in an LaTeX buffer and use this
   4296 command to convert it."
   4297   (interactive)
   4298   (org-export-replace-region-by 'latex))
   4299 
   4300 (defalias 'org-export-region-to-latex #'org-latex-convert-region-to-latex)
   4301 
   4302 ;;;###autoload
   4303 (defun org-latex-export-to-latex
   4304     (&optional async subtreep visible-only body-only ext-plist)
   4305   "Export current buffer to a LaTeX file.
   4306 
   4307 If narrowing is active in the current buffer, only export its
   4308 narrowed part.
   4309 
   4310 If a region is active, export that region.
   4311 
   4312 A non-nil optional argument ASYNC means the process should happen
   4313 asynchronously.  The resulting file should be accessible through
   4314 the `org-export-stack' interface.
   4315 
   4316 When optional argument SUBTREEP is non-nil, export the sub-tree
   4317 at point, extracting information from the headline properties
   4318 first.
   4319 
   4320 When optional argument VISIBLE-ONLY is non-nil, don't export
   4321 contents of hidden elements.
   4322 
   4323 When optional argument BODY-ONLY is non-nil, only write code
   4324 between \"\\begin{document}\" and \"\\end{document}\".
   4325 
   4326 EXT-PLIST, when provided, is a property list with external
   4327 parameters overriding Org default settings, but still inferior to
   4328 file-local settings."
   4329   (interactive)
   4330   (let ((outfile (org-export-output-file-name ".tex" subtreep)))
   4331     (org-export-to-file 'latex outfile
   4332       async subtreep visible-only body-only ext-plist)))
   4333 
   4334 ;;;###autoload
   4335 (defun org-latex-export-to-pdf
   4336     (&optional async subtreep visible-only body-only ext-plist)
   4337   "Export current buffer to LaTeX then process through to PDF.
   4338 
   4339 If narrowing is active in the current buffer, only export its
   4340 narrowed part.
   4341 
   4342 If a region is active, export that region.
   4343 
   4344 A non-nil optional argument ASYNC means the process should happen
   4345 asynchronously.  The resulting file should be accessible through
   4346 the `org-export-stack' interface.
   4347 
   4348 When optional argument SUBTREEP is non-nil, export the sub-tree
   4349 at point, extracting information from the headline properties
   4350 first.
   4351 
   4352 When optional argument VISIBLE-ONLY is non-nil, don't export
   4353 contents of hidden elements.
   4354 
   4355 When optional argument BODY-ONLY is non-nil, only write code
   4356 between \"\\begin{document}\" and \"\\end{document}\".
   4357 
   4358 EXT-PLIST, when provided, is a property list with external
   4359 parameters overriding Org default settings, but still inferior to
   4360 file-local settings.
   4361 
   4362 Return PDF file's name."
   4363   (interactive)
   4364   (let ((outfile (org-export-output-file-name ".tex" subtreep)))
   4365     (org-export-to-file 'latex outfile
   4366       async subtreep visible-only body-only ext-plist
   4367       #'org-latex-compile)))
   4368 
   4369 (defun org-latex-compile (texfile &optional snippet)
   4370   "Compile a TeX file.
   4371 
   4372 TEXFILE is the name of the file being compiled.  Processing is
   4373 done through the command specified in `org-latex-pdf-process',
   4374 which see.  Output is redirected to \"*Org PDF LaTeX Output*\"
   4375 buffer.
   4376 
   4377 When optional argument SNIPPET is non-nil, TEXFILE is a temporary
   4378 file used to preview a LaTeX snippet.  In this case, do not
   4379 create a log buffer and do not remove log files.
   4380 
   4381 Return PDF file name or raise an error if it couldn't be
   4382 produced."
   4383   (unless snippet (message "Processing LaTeX file %s..." texfile))
   4384   (let* ((compiler
   4385 	  (or (with-temp-buffer
   4386 		(save-excursion (insert-file-contents texfile))
   4387 		(and (search-forward-regexp (regexp-opt org-latex-compilers)
   4388 					    (line-end-position 2)
   4389 					    t)
   4390 		     (progn (forward-line 0) (eq (char-after) ?%))
   4391 		     (match-string 0)))
   4392               ;; Cannot find the compiler inserted by
   4393               ;; `org-latex-template' -> `org-latex--insert-compiler'.
   4394               ;; Use a fallback.
   4395               org-latex-compiler))
   4396 	 (process (if (functionp org-latex-pdf-process) org-latex-pdf-process
   4397 		    ;; Replace "%latex" with "%L" and "%bib" and
   4398 		    ;; "%bibtex" with "%B" to adhere to `format-spec'
   4399 		    ;; specifications.
   4400 		    (mapcar (lambda (command)
   4401 			      (replace-regexp-in-string
   4402                                "%\\(?:\\(?:bib\\|la\\)tex\\|bib\\)\\>"
   4403 			       (lambda (m) (upcase (substring m 0 2)))
   4404 			       command))
   4405 			    org-latex-pdf-process)))
   4406          (spec `((?B . ,(shell-quote-argument org-latex-bib-compiler))
   4407                  (?L . ,(shell-quote-argument compiler))))
   4408 	 (log-buf-name "*Org PDF LaTeX Output*")
   4409          (log-buf (and (not snippet) (get-buffer-create log-buf-name)))
   4410          outfile)
   4411     ;; Erase compile buffer at the start.
   4412     (with-current-buffer log-buf
   4413       (erase-buffer))
   4414     (setq outfile
   4415           (org-compile-file
   4416            texfile process "pdf"
   4417 	   (format "See %S for details" log-buf-name)
   4418 	   log-buf spec))
   4419     (org-latex-compile--postprocess outfile log-buf snippet)
   4420     ;; Return output file name.
   4421     outfile))
   4422 
   4423 (defun org-latex-compile--postprocess (outfile log-buf &optional snippet)
   4424   "Process the results of creating OUTFILE via LaTeX compilation.
   4425 Warnings and errors are collected from LOG-BUF.
   4426 When SNIPPET is nil and `org-latex-remove-logfiles' non-nil,
   4427 log files (as specified by `org-latex-logfiles-extensions') are deleted."
   4428   (unless snippet
   4429     (when org-latex-remove-logfiles
   4430       (mapc #'delete-file
   4431             (directory-files
   4432              (or (file-name-directory outfile) default-directory)
   4433              t
   4434              (concat (regexp-quote (file-name-base outfile))
   4435                      "\\(?:\\.[0-9]+\\)?\\."
   4436                      (regexp-opt org-latex-logfiles-extensions))
   4437              t)))
   4438     (let ((warnings (org-latex--collect-warnings log-buf)))
   4439       (funcall
   4440        (if warnings
   4441            (apply-partially
   4442             #'display-warning
   4443             '(ox-latex))
   4444          #'message)
   4445        (concat "PDF file produced"
   4446                (cond
   4447                 ((eq warnings 'error) " with errors.")
   4448                 (warnings (concat " with warnings: " warnings))
   4449                 (t ".")))))))
   4450 
   4451 (defun org-latex--collect-warnings (buffer)
   4452   "Collect some warnings from \"pdflatex\" command output.
   4453 BUFFER is the buffer containing output.  Return collected
   4454 warnings types as a string, `error' if a LaTeX error was
   4455 encountered or nil if there was none."
   4456   (with-current-buffer buffer
   4457     (save-excursion
   4458       (goto-char (point-max))
   4459       (when (re-search-backward "^[ \t]*This is .*?TeX.*?Version" nil t)
   4460 	(if (and
   4461 	     (re-search-forward "^!\\(.+\\)" nil t)
   4462              ;; This error is passed as missing character warning
   4463              (not (string-match-p "Unicode character" (match-string 1))))
   4464             'error
   4465 	  (let ((case-fold-search t)
   4466 		(warnings ""))
   4467 	    (dolist (warning org-latex-known-warnings)
   4468 	      (when (save-excursion (re-search-forward (car warning) nil t))
   4469 		(setq warnings (concat warnings " " (cdr warning)))))
   4470 	    (org-string-nw-p (org-trim warnings))))))))
   4471 
   4472 ;;;###autoload
   4473 (defun org-latex-publish-to-latex (plist filename pub-dir)
   4474   "Publish an Org file to LaTeX.
   4475 
   4476 FILENAME is the filename of the Org file to be published.  PLIST
   4477 is the property list for the given project.  PUB-DIR is the
   4478 publishing directory.
   4479 
   4480 Return output file name."
   4481   (org-publish-org-to 'latex filename ".tex" plist pub-dir))
   4482 
   4483 ;;;###autoload
   4484 (defun org-latex-publish-to-pdf (plist filename pub-dir)
   4485   "Publish an Org file to PDF (via LaTeX).
   4486 
   4487 FILENAME is the filename of the Org file to be published.  PLIST
   4488 is the property list for the given project.  PUB-DIR is the
   4489 publishing directory.
   4490 
   4491 Return output file name."
   4492   ;; Unlike to `org-latex-publish-to-latex', PDF file is generated
   4493   ;; in working directory and then moved to publishing directory.
   4494   (org-publish-attachment
   4495    plist
   4496    ;; Default directory could be anywhere when this function is
   4497    ;; called.  We ensure it is set to source file directory during
   4498    ;; compilation so as to not break links to external documents.
   4499    (let ((default-directory (file-name-directory filename)))
   4500      (org-latex-compile
   4501       (org-publish-org-to
   4502        'latex filename ".tex" plist (file-name-directory filename))))
   4503    pub-dir))
   4504 
   4505 
   4506 (provide 'ox-latex)
   4507 
   4508 ;; Local variables:
   4509 ;; generated-autoload-file: "org-loaddefs.el"
   4510 ;; End:
   4511 
   4512 ;;; ox-latex.el ends here