dotemacs

My Emacs configuration
git clone git://git.entf.net/dotemacs
Log | Files | Refs | LICENSE

ox-latex.el (168064B)


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