ob-lisp: Add SLY support
[org-mode/org-tableheadings.git] / lisp / ox-latex.el
blob7fa68c5701ca97a7242c872da9df299d55feb6ad
1 ;;; ox-latex.el --- LaTeX Back-End for Org Export Engine -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2011-2016 Free Software Foundation, Inc.
5 ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
6 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;; See Org manual for details.
27 ;;; Code:
29 (eval-when-compile (require 'cl))
30 (require 'ox)
31 (require 'ox-publish)
33 (defvar org-latex-default-packages-alist)
34 (defvar org-latex-packages-alist)
35 (defvar orgtbl-exp-regexp)
39 ;;; Define Back-End
41 (org-export-define-backend 'latex
42 '((bold . org-latex-bold)
43 (center-block . org-latex-center-block)
44 (clock . org-latex-clock)
45 (code . org-latex-code)
46 (drawer . org-latex-drawer)
47 (dynamic-block . org-latex-dynamic-block)
48 (entity . org-latex-entity)
49 (example-block . org-latex-example-block)
50 (export-block . org-latex-export-block)
51 (export-snippet . org-latex-export-snippet)
52 (fixed-width . org-latex-fixed-width)
53 (footnote-definition . org-latex-footnote-definition)
54 (footnote-reference . org-latex-footnote-reference)
55 (headline . org-latex-headline)
56 (horizontal-rule . org-latex-horizontal-rule)
57 (inline-src-block . org-latex-inline-src-block)
58 (inlinetask . org-latex-inlinetask)
59 (italic . org-latex-italic)
60 (item . org-latex-item)
61 (keyword . org-latex-keyword)
62 (latex-environment . org-latex-latex-environment)
63 (latex-fragment . org-latex-latex-fragment)
64 (line-break . org-latex-line-break)
65 (link . org-latex-link)
66 (node-property . org-latex-node-property)
67 (paragraph . org-latex-paragraph)
68 (plain-list . org-latex-plain-list)
69 (plain-text . org-latex-plain-text)
70 (planning . org-latex-planning)
71 (property-drawer . org-latex-property-drawer)
72 (quote-block . org-latex-quote-block)
73 (radio-target . org-latex-radio-target)
74 (section . org-latex-section)
75 (special-block . org-latex-special-block)
76 (src-block . org-latex-src-block)
77 (statistics-cookie . org-latex-statistics-cookie)
78 (strike-through . org-latex-strike-through)
79 (subscript . org-latex-subscript)
80 (superscript . org-latex-superscript)
81 (table . org-latex-table)
82 (table-cell . org-latex-table-cell)
83 (table-row . org-latex-table-row)
84 (target . org-latex-target)
85 (template . org-latex-template)
86 (timestamp . org-latex-timestamp)
87 (underline . org-latex-underline)
88 (verbatim . org-latex-verbatim)
89 (verse-block . org-latex-verse-block)
90 ;; Pseudo objects and elements.
91 (latex-math-block . org-latex-math-block)
92 (latex-matrices . org-latex-matrices))
93 :menu-entry
94 '(?l "Export to LaTeX"
95 ((?L "As LaTeX buffer" org-latex-export-as-latex)
96 (?l "As LaTeX file" org-latex-export-to-latex)
97 (?p "As PDF file" org-latex-export-to-pdf)
98 (?o "As PDF file and open"
99 (lambda (a s v b)
100 (if a (org-latex-export-to-pdf t s v b)
101 (org-open-file (org-latex-export-to-pdf nil s v b)))))))
102 :filters-alist '((:filter-options . org-latex-math-block-options-filter)
103 (:filter-parse-tree org-latex-math-block-tree-filter
104 org-latex-matrices-tree-filter))
105 :options-alist
106 '((:latex-class "LATEX_CLASS" nil org-latex-default-class t)
107 (:latex-class-options "LATEX_CLASS_OPTIONS" nil nil t)
108 (:latex-header "LATEX_HEADER" nil nil newline)
109 (:latex-header-extra "LATEX_HEADER_EXTRA" nil nil newline)
110 (:description "DESCRIPTION" nil nil parse)
111 (:keywords "KEYWORDS" nil nil parse)
112 (:subtitle "SUBTITLE" nil nil parse)
113 ;; Other variables.
114 (:latex-active-timestamp-format nil nil org-latex-active-timestamp-format)
115 (:latex-caption-above nil nil org-latex-caption-above)
116 (:latex-classes nil nil org-latex-classes)
117 (:latex-default-figure-position nil nil org-latex-default-figure-position)
118 (:latex-default-table-environment nil nil org-latex-default-table-environment)
119 (:latex-default-table-mode nil nil org-latex-default-table-mode)
120 (:latex-diary-timestamp-format nil nil org-latex-diary-timestamp-format)
121 (:latex-footnote-separator nil nil org-latex-footnote-separator)
122 (:latex-format-drawer-function nil nil org-latex-format-drawer-function)
123 (:latex-format-headline-function nil nil org-latex-format-headline-function)
124 (:latex-format-inlinetask-function nil nil org-latex-format-inlinetask-function)
125 (:latex-hyperref-template nil nil org-latex-hyperref-template t)
126 (:latex-image-default-height nil nil org-latex-image-default-height)
127 (:latex-image-default-option nil nil org-latex-image-default-option)
128 (:latex-image-default-width nil nil org-latex-image-default-width)
129 (:latex-inactive-timestamp-format nil nil org-latex-inactive-timestamp-format)
130 (:latex-inline-image-rules nil nil org-latex-inline-image-rules)
131 (:latex-link-with-unknown-path-format nil nil org-latex-link-with-unknown-path-format)
132 (:latex-listings nil nil org-latex-listings)
133 (:latex-listings-langs nil nil org-latex-listings-langs)
134 (:latex-listings-options nil nil org-latex-listings-options)
135 (:latex-minted-langs nil nil org-latex-minted-langs)
136 (:latex-minted-options nil nil org-latex-minted-options)
137 (:latex-prefer-user-labels nil nil org-latex-prefer-user-labels)
138 (:latex-subtitle-format nil nil org-latex-subtitle-format)
139 (:latex-subtitle-separate nil nil org-latex-subtitle-separate)
140 (:latex-table-scientific-notation nil nil org-latex-table-scientific-notation)
141 (:latex-tables-booktabs nil nil org-latex-tables-booktabs)
142 (:latex-tables-centered nil nil org-latex-tables-centered)
143 (:latex-text-markup-alist nil nil org-latex-text-markup-alist)
144 (:latex-title-command nil nil org-latex-title-command)
145 (:latex-toc-command nil nil org-latex-toc-command)
146 (:latex-compiler "LATEX_COMPILER" nil org-latex-compiler)
147 ;; Redefine regular options.
148 (:date "DATE" nil "\\today" parse)))
152 ;;; Internal Variables
154 (defconst org-latex-babel-language-alist
155 '(("af" . "afrikaans")
156 ("bg" . "bulgarian")
157 ("bt-br" . "brazilian")
158 ("ca" . "catalan")
159 ("cs" . "czech")
160 ("cy" . "welsh")
161 ("da" . "danish")
162 ("de" . "germanb")
163 ("de-at" . "naustrian")
164 ("de-de" . "ngerman")
165 ("el" . "greek")
166 ("en" . "english")
167 ("en-au" . "australian")
168 ("en-ca" . "canadian")
169 ("en-gb" . "british")
170 ("en-ie" . "irish")
171 ("en-nz" . "newzealand")
172 ("en-us" . "american")
173 ("es" . "spanish")
174 ("et" . "estonian")
175 ("eu" . "basque")
176 ("fi" . "finnish")
177 ("fr" . "frenchb")
178 ("fr-ca" . "canadien")
179 ("gl" . "galician")
180 ("hr" . "croatian")
181 ("hu" . "hungarian")
182 ("id" . "indonesian")
183 ("is" . "icelandic")
184 ("it" . "italian")
185 ("la" . "latin")
186 ("ms" . "malay")
187 ("nl" . "dutch")
188 ("nb" . "norsk")
189 ("nn" . "nynorsk")
190 ("no" . "norsk")
191 ("pl" . "polish")
192 ("pt" . "portuguese")
193 ("ro" . "romanian")
194 ("ru" . "russian")
195 ("sa" . "sanskrit")
196 ("sb" . "uppersorbian")
197 ("sk" . "slovak")
198 ("sl" . "slovene")
199 ("sq" . "albanian")
200 ("sr" . "serbian")
201 ("sv" . "swedish")
202 ("ta" . "tamil")
203 ("tr" . "turkish")
204 ("uk" . "ukrainian"))
205 "Alist between language code and corresponding Babel option.")
207 (defconst org-latex-polyglossia-language-alist
208 '(("am" "amharic")
209 ("ast" "asturian")
210 ("ar" "arabic")
211 ("bo" "tibetan")
212 ("bn" "bengali")
213 ("bg" "bulgarian")
214 ("br" "breton")
215 ("bt-br" "brazilian")
216 ("ca" "catalan")
217 ("cop" "coptic")
218 ("cs" "czech")
219 ("cy" "welsh")
220 ("da" "danish")
221 ("de" "german" "german")
222 ("de-at" "german" "austrian")
223 ("de-de" "german" "german")
224 ("dv" "divehi")
225 ("el" "greek")
226 ("en" "english" "usmax")
227 ("en-au" "english" "australian")
228 ("en-gb" "english" "uk")
229 ("en-nz" "english" "newzealand")
230 ("en-us" "english" "usmax")
231 ("eo" "esperanto")
232 ("es" "spanish")
233 ("et" "estonian")
234 ("eu" "basque")
235 ("fa" "farsi")
236 ("fi" "finnish")
237 ("fr" "french")
238 ("fu" "friulan")
239 ("ga" "irish")
240 ("gd" "scottish")
241 ("gl" "galician")
242 ("he" "hebrew")
243 ("hi" "hindi")
244 ("hr" "croatian")
245 ("hu" "magyar")
246 ("hy" "armenian")
247 ("id" "bahasai")
248 ("ia" "interlingua")
249 ("is" "icelandic")
250 ("it" "italian")
251 ("kn" "kannada")
252 ("la" "latin" "modern")
253 ("la-modern" "latin" "modern")
254 ("la-classic" "latin" "classic")
255 ("la-medieval" "latin" "medieval")
256 ("lo" "lao")
257 ("lt" "lithuanian")
258 ("lv" "latvian")
259 ("mr" "maranthi")
260 ("ml" "malayalam")
261 ("nl" "dutch")
262 ("nb" "norsk")
263 ("nn" "nynorsk")
264 ("nko" "nko")
265 ("no" "norsk")
266 ("oc" "occitan")
267 ("pl" "polish")
268 ("pms" "piedmontese")
269 ("pt" "portuges")
270 ("rm" "romansh")
271 ("ro" "romanian")
272 ("ru" "russian")
273 ("sa" "sanskrit")
274 ("hsb" "usorbian")
275 ("dsb" "lsorbian")
276 ("sk" "slovak")
277 ("sl" "slovenian")
278 ("se" "samin")
279 ("sq" "albanian")
280 ("sr" "serbian")
281 ("sv" "swedish")
282 ("syr" "syriac")
283 ("ta" "tamil")
284 ("te" "telugu")
285 ("th" "thai")
286 ("tk" "turkmen")
287 ("tr" "turkish")
288 ("uk" "ukrainian")
289 ("ur" "urdu")
290 ("vi" "vietnamese"))
291 "Alist between language code and corresponding Polyglossia option")
295 (defconst org-latex-table-matrix-macros '(("bordermatrix" . "\\cr")
296 ("qbordermatrix" . "\\cr")
297 ("kbordermatrix" . "\\\\"))
298 "Alist between matrix macros and their row ending.")
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.")
315 ;;; User Configurable Variables
317 (defgroup org-export-latex nil
318 "Options for exporting Org mode files to LaTeX."
319 :tag "Org Export LaTeX"
320 :group 'org-export)
322 ;;;; Generic
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 "25.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))))
341 (defcustom org-latex-prefer-user-labels nil
342 "Use user-provided labels instead of internal ones when non-nil.
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.
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.
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.
359 For example, when this variable is non-nil, a headline like this:
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
370 will be exported to LaTeX as:
372 \\subsection{Some section}
373 \\label{sec:foo}
374 This is section \\ref{sec:foo}.
375 And this is still section \\ref{sec:foo}.
377 Note, however, that setting this variable introduces a limitation
378 on the possible values for CUSTOM_ID and NAME. When this
379 variable is non-nil, Org passes their value to \\label unchanged.
380 You are responsible for ensuring that the value is a valid LaTeX
381 \\label key, and that no other \\label commands with the same key
382 appear elsewhere in your document. (Keys may contain letters,
383 numbers, and the following punctuation: '_' '.' '-' ':'.) There
384 are no such limitations on CUSTOM_ID and NAME when this variable
385 is nil.
387 For headlines that do not define the CUSTOM_ID property or
388 elements without a NAME, Org will continue to use its default
389 labeling scheme to generate labels and resolve links into proper
390 references."
391 :group 'org-export-latex
392 :type 'boolean
393 :version "25.1"
394 :package-version '(Org . "8.3"))
396 ;;;; Preamble
398 (defcustom org-latex-default-class "article"
399 "The default LaTeX class."
400 :group 'org-export-latex
401 :type '(string :tag "LaTeX class"))
403 (defcustom org-latex-classes
404 '(("article"
405 "\\documentclass[11pt]{article}"
406 ("\\section{%s}" . "\\section*{%s}")
407 ("\\subsection{%s}" . "\\subsection*{%s}")
408 ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
409 ("\\paragraph{%s}" . "\\paragraph*{%s}")
410 ("\\subparagraph{%s}" . "\\subparagraph*{%s}"))
411 ("report"
412 "\\documentclass[11pt]{report}"
413 ("\\part{%s}" . "\\part*{%s}")
414 ("\\chapter{%s}" . "\\chapter*{%s}")
415 ("\\section{%s}" . "\\section*{%s}")
416 ("\\subsection{%s}" . "\\subsection*{%s}")
417 ("\\subsubsection{%s}" . "\\subsubsection*{%s}"))
418 ("book"
419 "\\documentclass[11pt]{book}"
420 ("\\part{%s}" . "\\part*{%s}")
421 ("\\chapter{%s}" . "\\chapter*{%s}")
422 ("\\section{%s}" . "\\section*{%s}")
423 ("\\subsection{%s}" . "\\subsection*{%s}")
424 ("\\subsubsection{%s}" . "\\subsubsection*{%s}")))
425 "Alist of LaTeX classes and associated header and structure.
426 If #+LATEX_CLASS is set in the buffer, use its value and the
427 associated information. Here is the structure of each cell:
429 (class-name
430 header-string
431 (numbered-section . unnumbered-section)
432 ...)
434 The header string
435 -----------------
437 The HEADER-STRING is the header that will be inserted into the
438 LaTeX file. It should contain the \\documentclass macro, and
439 anything else that is needed for this setup. To this header, the
440 following commands will be added:
442 - Calls to \\usepackage for all packages mentioned in the
443 variables `org-latex-default-packages-alist' and
444 `org-latex-packages-alist'. Thus, your header definitions
445 should avoid to also request these packages.
447 - Lines specified via \"#+LATEX_HEADER:\" and
448 \"#+LATEX_HEADER_EXTRA:\" keywords.
450 If you need more control about the sequence in which the header
451 is built up, or if you want to exclude one of these building
452 blocks for a particular class, you can use the following
453 macro-like placeholders.
455 [DEFAULT-PACKAGES] \\usepackage statements for default packages
456 [NO-DEFAULT-PACKAGES] do not include any of the default packages
457 [PACKAGES] \\usepackage statements for packages
458 [NO-PACKAGES] do not include the packages
459 [EXTRA] the stuff from #+LATEX_HEADER(_EXTRA)
460 [NO-EXTRA] do not include #+LATEX_HEADER(_EXTRA) stuff
462 So a header like
464 \\documentclass{article}
465 [NO-DEFAULT-PACKAGES]
466 [EXTRA]
467 \\providecommand{\\alert}[1]{\\textbf{#1}}
468 [PACKAGES]
470 will omit the default packages, and will include the
471 #+LATEX_HEADER and #+LATEX_HEADER_EXTRA lines, then have a call
472 to \\providecommand, and then place \\usepackage commands based
473 on the content of `org-latex-packages-alist'.
475 If your header, `org-latex-default-packages-alist' or
476 `org-latex-packages-alist' inserts \"\\usepackage[AUTO]{inputenc}\",
477 AUTO will automatically be replaced with a coding system derived
478 from `buffer-file-coding-system'. See also the variable
479 `org-latex-inputenc-alist' for a way to influence this mechanism.
481 Likewise, if your header contains \"\\usepackage[AUTO]{babel}\"
482 or \"\\usepackage[AUTO]{polyglossia}\", AUTO will be replaced
483 with the language related to the language code specified by
484 `org-export-default-language'. Note that constructions such as
485 \"\\usepackage[french,AUTO,english]{babel}\" are permitted. For
486 Polyglossia the language will be set via the macros
487 \"\\setmainlanguage\" and \"\\setotherlanguage\". See also
488 `org-latex-guess-babel-language' and
489 `org-latex-guess-polyglossia-language'.
491 The sectioning structure
492 ------------------------
494 The sectioning structure of the class is given by the elements
495 following the header string. For each sectioning level, a number
496 of strings is specified. A %s formatter is mandatory in each
497 section string and will be replaced by the title of the section.
499 Instead of a cons cell (numbered . unnumbered), you can also
500 provide a list of 2 or 4 elements,
502 (numbered-open numbered-close)
506 (numbered-open numbered-close unnumbered-open unnumbered-close)
508 providing opening and closing strings for a LaTeX environment
509 that should represent the document section. The opening clause
510 should have a %s to represent the section title.
512 Instead of a list of sectioning commands, you can also specify
513 a function name. That function will be called with two
514 parameters, the (reduced) level of the headline, and a predicate
515 non-nil when the headline should be numbered. It must return
516 a format string in which the section title will be added."
517 :group 'org-export-latex
518 :type '(repeat
519 (list (string :tag "LaTeX class")
520 (string :tag "LaTeX header")
521 (repeat :tag "Levels" :inline t
522 (choice
523 (cons :tag "Heading"
524 (string :tag " numbered")
525 (string :tag "unnumbered"))
526 (list :tag "Environment"
527 (string :tag "Opening (numbered)")
528 (string :tag "Closing (numbered)")
529 (string :tag "Opening (unnumbered)")
530 (string :tag "Closing (unnumbered)"))
531 (function :tag "Hook computing sectioning"))))))
533 (defcustom org-latex-inputenc-alist nil
534 "Alist of inputenc coding system names, and what should really be used.
535 For example, adding an entry
537 (\"utf8\" . \"utf8x\")
539 will cause \\usepackage[utf8x]{inputenc} to be used for buffers that
540 are written as utf8 files."
541 :group 'org-export-latex
542 :type '(repeat
543 (cons
544 (string :tag "Derived from buffer")
545 (string :tag "Use this instead"))))
547 (defcustom org-latex-title-command "\\maketitle"
548 "The command used to insert the title just after \\begin{document}.
550 This format string may contain these elements:
552 %a for AUTHOR keyword
553 %t for TITLE keyword
554 %s for SUBTITLE keyword
555 %k for KEYWORDS line
556 %d for DESCRIPTION line
557 %c for CREATOR line
558 %l for Language keyword
559 %L for capitalized language keyword
560 %D for DATE keyword
562 If you need to use a \"%\" character, you need to escape it
563 like that: \"%%\".
565 Setting :latex-title-command in publishing projects will take
566 precedence over this variable."
567 :group 'org-export-latex
568 :type '(string :tag "Format string"))
570 (defcustom org-latex-subtitle-format "\\\\\\medskip\n\\large %s"
571 "Format string used for transcoded subtitle.
572 The format string should have at most one \"%s\"-expression,
573 which is replaced with the subtitle."
574 :group 'org-export-latex
575 :version "25.1"
576 :package-version '(Org . "8.3")
577 :type '(string :tag "Format string"))
579 (defcustom org-latex-subtitle-separate nil
580 "Non-nil means the subtitle is not typeset as part of title."
581 :group 'org-export-latex
582 :version "25.1"
583 :package-version '(Org . "8.3")
584 :type 'boolean)
586 (defcustom org-latex-toc-command "\\tableofcontents\n\n"
587 "LaTeX command to set the table of contents, list of figures, etc.
588 This command only applies to the table of contents generated with
589 the toc:nil option, not to those generated with #+TOC keyword."
590 :group 'org-export-latex
591 :type 'string)
593 (defcustom org-latex-hyperref-template
594 "\\hypersetup{\n pdfauthor={%a},\n pdftitle={%t},\n pdfkeywords={%k},
595 pdfsubject={%d},\n pdfcreator={%c}, \n pdflang={%L}}\n"
596 "Template for hyperref package options.
598 This format string may contain these elements:
600 %a for AUTHOR keyword
601 %t for TITLE keyword
602 %s for SUBTITLE keyword
603 %k for KEYWORDS line
604 %d for DESCRIPTION line
605 %c for CREATOR line
606 %l for Language keyword
607 %L for capitalized language keyword
608 %D for DATE keyword
610 If you need to use a \"%\" character, you need to escape it
611 like that: \"%%\".
613 As a special case, a nil value prevents template from being
614 inserted.
616 Setting :latex-hyperref-template in publishing projects will take
617 precedence over this variable."
618 :group 'org-export-latex
619 :version "25.1"
620 :package-version '(Org . "8.3")
621 :type '(choice (const :tag "No template" nil)
622 (string :tag "Format string")))
623 (define-obsolete-variable-alias
624 'org-latex-with-hyperref 'org-latex-hyperref-template "25.1")
626 ;;;; Headline
628 (defcustom org-latex-format-headline-function
629 'org-latex-format-headline-default-function
630 "Function for formatting the headline's text.
632 This function will be called with six arguments:
633 TODO the todo keyword (string or nil)
634 TODO-TYPE the type of todo (symbol: `todo', `done', nil)
635 PRIORITY the priority of the headline (integer or nil)
636 TEXT the main headline text (string)
637 TAGS the tags (list of strings or nil)
638 INFO the export options (plist)
640 The function result will be used in the section format string."
641 :group 'org-export-latex
642 :version "24.4"
643 :package-version '(Org . "8.0")
644 :type 'function)
647 ;;;; Footnotes
649 (defcustom org-latex-footnote-separator "\\textsuperscript{,}\\,"
650 "Text used to separate footnotes."
651 :group 'org-export-latex
652 :type 'string)
655 ;;;; Timestamps
657 (defcustom org-latex-active-timestamp-format "\\textit{%s}"
658 "A printf format string to be applied to active timestamps."
659 :group 'org-export-latex
660 :type 'string)
662 (defcustom org-latex-inactive-timestamp-format "\\textit{%s}"
663 "A printf format string to be applied to inactive timestamps."
664 :group 'org-export-latex
665 :type 'string)
667 (defcustom org-latex-diary-timestamp-format "\\textit{%s}"
668 "A printf format string to be applied to diary timestamps."
669 :group 'org-export-latex
670 :type 'string)
673 ;;;; Links
675 (defcustom org-latex-image-default-option ""
676 "Default option for images."
677 :group 'org-export-latex
678 :version "24.4"
679 :package-version '(Org . "8.0")
680 :type 'string)
682 (defcustom org-latex-image-default-width ".9\\linewidth"
683 "Default width for images.
684 This value will not be used if a height is provided."
685 :group 'org-export-latex
686 :version "24.4"
687 :package-version '(Org . "8.0")
688 :type 'string)
690 (defcustom org-latex-image-default-height ""
691 "Default height for images.
692 This value will not be used if a width is provided, or if the
693 image is wrapped within a \"figure\" or \"wrapfigure\"
694 environment."
695 :group 'org-export-latex
696 :version "24.4"
697 :package-version '(Org . "8.0")
698 :type 'string)
700 (defcustom org-latex-default-figure-position "htb"
701 "Default position for latex figures."
702 :group 'org-export-latex
703 :type 'string)
705 (defcustom org-latex-inline-image-rules
706 '(("file" . "\\.\\(pdf\\|jpeg\\|jpg\\|png\\|ps\\|eps\\|tikz\\|pgf\\|svg\\)\\'"))
707 "Rules characterizing image files that can be inlined into LaTeX.
709 A rule consists in an association whose key is the type of link
710 to consider, and value is a regexp that will be matched against
711 link's path.
713 Note that, by default, the image extension *actually* allowed
714 depend on the way the LaTeX file is processed. When used with
715 pdflatex, pdf, jpg and png images are OK. When processing
716 through dvi to Postscript, only ps and eps are allowed. The
717 default we use here encompasses both."
718 :group 'org-export-latex
719 :version "24.4"
720 :package-version '(Org . "8.0")
721 :type '(alist :key-type (string :tag "Type")
722 :value-type (regexp :tag "Path")))
724 (defcustom org-latex-link-with-unknown-path-format "\\texttt{%s}"
725 "Format string for links with unknown path type."
726 :group 'org-export-latex
727 :type 'string)
730 ;;;; Tables
732 (defcustom org-latex-default-table-environment "tabular"
733 "Default environment used to build tables."
734 :group 'org-export-latex
735 :version "24.4"
736 :package-version '(Org . "8.0")
737 :type 'string)
739 (defcustom org-latex-default-table-mode 'table
740 "Default mode for tables.
742 Value can be a symbol among:
744 `table' Regular LaTeX table.
746 `math' In this mode, every cell is considered as being in math
747 mode and the complete table will be wrapped within a math
748 environment. It is particularly useful to write matrices.
750 `inline-math' This mode is almost the same as `math', but the
751 math environment will be inlined.
753 `verbatim' The table is exported as it appears in the Org
754 buffer, within a verbatim environment.
756 This value can be overridden locally with, i.e. \":mode math\" in
757 LaTeX attributes.
759 When modifying this variable, it may be useful to change
760 `org-latex-default-table-environment' accordingly."
761 :group 'org-export-latex
762 :version "24.4"
763 :package-version '(Org . "8.0")
764 :type '(choice (const :tag "Table" table)
765 (const :tag "Matrix" math)
766 (const :tag "Inline matrix" inline-math)
767 (const :tag "Verbatim" verbatim))
768 :safe (lambda (s) (memq s '(table math inline-math verbatim))))
770 (defcustom org-latex-tables-centered t
771 "When non-nil, tables are exported in a center environment."
772 :group 'org-export-latex
773 :type 'boolean
774 :safe #'booleanp)
776 (defcustom org-latex-tables-booktabs nil
777 "When non-nil, display tables in a formal \"booktabs\" style.
778 This option assumes that the \"booktabs\" package is properly
779 loaded in the header of the document. This value can be ignored
780 locally with \":booktabs t\" and \":booktabs nil\" LaTeX
781 attributes."
782 :group 'org-export-latex
783 :version "24.4"
784 :package-version '(Org . "8.0")
785 :type 'boolean
786 :safe #'booleanp)
788 (defcustom org-latex-table-scientific-notation "%s\\,(%s)"
789 "Format string to display numbers in scientific notation.
790 The format should have \"%s\" twice, for mantissa and exponent
791 \(i.e., \"%s\\\\times10^{%s}\").
793 When nil, no transformation is made."
794 :group 'org-export-latex
795 :version "24.4"
796 :package-version '(Org . "8.0")
797 :type '(choice
798 (string :tag "Format string")
799 (const :tag "No formatting" nil)))
801 ;;;; Text markup
803 (defcustom org-latex-text-markup-alist '((bold . "\\textbf{%s}")
804 (code . protectedtexttt)
805 (italic . "\\emph{%s}")
806 (strike-through . "\\sout{%s}")
807 (underline . "\\uline{%s}")
808 (verbatim . protectedtexttt))
809 "Alist of LaTeX expressions to convert text markup.
811 The key must be a symbol among `bold', `code', `italic',
812 `strike-through', `underline' and `verbatim'. The value is
813 a formatting string to wrap fontified text with.
815 Value can also be set to the following symbols: `verb' and
816 `protectedtexttt'. For the former, Org will use \"\\verb\" to
817 create a format string and select a delimiter character that
818 isn't in the string. For the latter, Org will use \"\\texttt\"
819 to typeset and try to protect special characters.
821 If no association can be found for a given markup, text will be
822 returned as-is."
823 :group 'org-export-latex
824 :version "25.1"
825 :package-version '(Org . "8.3")
826 :type 'alist
827 :options '(bold code italic strike-through underline verbatim))
830 ;;;; Drawers
832 (defcustom org-latex-format-drawer-function (lambda (_ contents) contents)
833 "Function called to format a drawer in LaTeX code.
835 The function must accept two parameters:
836 NAME the drawer name, like \"LOGBOOK\"
837 CONTENTS the contents of the drawer.
839 The function should return the string to be exported.
841 The default function simply returns the value of CONTENTS."
842 :group 'org-export-latex
843 :version "24.4"
844 :package-version '(Org . "8.3")
845 :type 'function)
848 ;;;; Inlinetasks
850 (defcustom org-latex-format-inlinetask-function
851 'org-latex-format-inlinetask-default-function
852 "Function called to format an inlinetask in LaTeX code.
854 The function must accept seven parameters:
855 TODO the todo keyword (string or nil)
856 TODO-TYPE the todo type (symbol: `todo', `done', nil)
857 PRIORITY the inlinetask priority (integer or nil)
858 NAME the inlinetask name (string)
859 TAGS the inlinetask tags (list of strings or nil)
860 CONTENTS the contents of the inlinetask (string or nil)
861 INFO the export options (plist)
863 The function should return the string to be exported."
864 :group 'org-export-latex
865 :type 'function
866 :version "25.1"
867 :package-version '(Org . "8.3"))
870 ;; Src blocks
872 (defcustom org-latex-listings nil
873 "Non-nil means export source code using the listings package.
875 This package will fontify source code, possibly even with color.
876 If you want to use this, you also need to make LaTeX use the
877 listings package, and if you want to have color, the color
878 package. Just add these to `org-latex-packages-alist', for
879 example using customize, or with something like:
881 (require \\='ox-latex)
882 (add-to-list \\='org-latex-packages-alist \\='(\"\" \"listings\"))
883 (add-to-list \\='org-latex-packages-alist \\='(\"\" \"color\"))
885 Alternatively,
887 (setq org-latex-listings \\='minted)
889 causes source code to be exported using the minted package as
890 opposed to listings. If you want to use minted, you need to add
891 the minted package to `org-latex-packages-alist', for example
892 using customize, or with
894 (require \\='ox-latex)
895 (add-to-list \\='org-latex-packages-alist \\='(\"newfloat\" \"minted\"))
897 In addition, it is necessary to install pygments
898 \(http://pygments.org), and to configure the variable
899 `org-latex-pdf-process' so that the -shell-escape option is
900 passed to pdflatex.
902 The minted choice has possible repercussions on the preview of
903 latex fragments (see `org-preview-latex-fragment'). If you run
904 into previewing problems, please consult
906 http://orgmode.org/worg/org-tutorials/org-latex-preview.html"
907 :group 'org-export-latex
908 :type '(choice
909 (const :tag "Use listings" t)
910 (const :tag "Use minted" minted)
911 (const :tag "Export verbatim" nil))
912 :safe (lambda (s) (memq s '(t nil minted))))
914 (defcustom org-latex-listings-langs
915 '((emacs-lisp "Lisp") (lisp "Lisp") (clojure "Lisp")
916 (c "C") (cc "C++")
917 (fortran "fortran")
918 (perl "Perl") (cperl "Perl") (python "Python") (ruby "Ruby")
919 (html "HTML") (xml "XML")
920 (tex "TeX") (latex "[LaTeX]TeX")
921 (shell-script "bash")
922 (gnuplot "Gnuplot")
923 (ocaml "Caml") (caml "Caml")
924 (sql "SQL") (sqlite "sql")
925 (makefile "make")
926 (R "r"))
927 "Alist mapping languages to their listing language counterpart.
928 The key is a symbol, the major mode symbol without the \"-mode\".
929 The value is the string that should be inserted as the language
930 parameter for the listings package. If the mode name and the
931 listings name are the same, the language does not need an entry
932 in this list - but it does not hurt if it is present."
933 :group 'org-export-latex
934 :version "24.4"
935 :package-version '(Org . "8.3")
936 :type '(repeat
937 (list
938 (symbol :tag "Major mode ")
939 (string :tag "Listings language"))))
941 (defcustom org-latex-listings-options nil
942 "Association list of options for the latex listings package.
944 These options are supplied as a comma-separated list to the
945 \\lstset command. Each element of the association list should be
946 a list containing two strings: the name of the option, and the
947 value. For example,
949 (setq org-latex-listings-options
950 \\='((\"basicstyle\" \"\\\\small\")
951 (\"keywordstyle\" \"\\\\color{black}\\\\bfseries\\\\underbar\")))
953 will typeset the code in a small size font with underlined, bold
954 black keywords.
956 Note that the same options will be applied to blocks of all
957 languages. If you need block-specific options, you may use the
958 following syntax:
960 #+ATTR_LATEX: :options key1=value1,key2=value2
961 #+BEGIN_SRC <LANG>
963 #+END_SRC"
964 :group 'org-export-latex
965 :type '(repeat
966 (list
967 (string :tag "Listings option name ")
968 (string :tag "Listings option value"))))
970 (defcustom org-latex-minted-langs
971 '((emacs-lisp "common-lisp")
972 (cc "c++")
973 (cperl "perl")
974 (shell-script "bash")
975 (caml "ocaml"))
976 "Alist mapping languages to their minted language counterpart.
977 The key is a symbol, the major mode symbol without the \"-mode\".
978 The value is the string that should be inserted as the language
979 parameter for the minted package. If the mode name and the
980 listings name are the same, the language does not need an entry
981 in this list - but it does not hurt if it is present.
983 Note that minted uses all lower case for language identifiers,
984 and that the full list of language identifiers can be obtained
985 with:
987 pygmentize -L lexers"
988 :group 'org-export-latex
989 :type '(repeat
990 (list
991 (symbol :tag "Major mode ")
992 (string :tag "Minted language"))))
994 (defcustom org-latex-minted-options nil
995 "Association list of options for the latex minted package.
997 These options are supplied within square brackets in
998 \\begin{minted} environments. Each element of the alist should
999 be a list containing two strings: the name of the option, and the
1000 value. For example,
1002 (setq org-latex-minted-options
1003 '((\"bgcolor\" \"bg\") (\"frame\" \"lines\")))
1005 will result in src blocks being exported with
1007 \\begin{minted}[bgcolor=bg,frame=lines]{<LANG>}
1009 as the start of the minted environment. Note that the same
1010 options will be applied to blocks of all languages. If you need
1011 block-specific options, you may use the following syntax:
1013 #+ATTR_LATEX: :options key1=value1,key2=value2
1014 #+BEGIN_SRC <LANG>
1016 #+END_SRC"
1017 :group 'org-export-latex
1018 :type '(repeat
1019 (list
1020 (string :tag "Minted option name ")
1021 (string :tag "Minted option value"))))
1023 (defcustom org-latex-custom-lang-environments nil
1024 "Alist mapping languages to language-specific LaTeX environments.
1026 It is used during export of src blocks by the listings and minted
1027 latex packages. The environment may be a simple string, composed of
1028 only letters and numbers. In this case, the string is directly the
1029 name of the latex environment to use. The environment may also be
1030 a format string. In this case the format string will be directly
1031 exported. This format string may contain these elements:
1033 %s for the formatted source
1034 %c for the caption
1035 %f for the float attribute
1036 %l for an appropriate label
1037 %o for the LaTeX attributes
1039 For example,
1041 (setq org-latex-custom-lang-environments
1042 '((python \"pythoncode\")
1043 (ocaml \"\\\\begin{listing}
1044 \\\\begin{minted}[%o]{ocaml}
1045 %s\\\\end{minted}
1046 \\\\caption{%c}
1047 \\\\label{%l}\")))
1049 would have the effect that if Org encounters a Python source block
1050 during LaTeX export it will produce
1052 \\begin{pythoncode}
1053 <src block body>
1054 \\end{pythoncode}
1056 and if Org encounters an Ocaml source block during LaTeX export it
1057 will produce
1059 \\begin{listing}
1060 \\begin{minted}[<attr_latex options>]{ocaml}
1061 <src block body>
1062 \\end{minted}
1063 \\caption{<caption>}
1064 \\label{<label>}
1065 \\end{listing}"
1066 :group 'org-export-latex
1067 :type '(repeat
1068 (list
1069 (symbol :tag "Language name ")
1070 (string :tag "Environment name or format string")))
1071 :version "25.1"
1072 :package-version '(Org . "9.0"))
1075 ;;;; Compilation
1077 (defcustom org-latex-compiler-file-string "%% Intended LaTeX compiler: %s\n"
1078 "LaTeX compiler format-string.
1079 See also `org-latex-compiler'."
1080 :group 'org-export-latex
1081 :type '(choice
1082 (const :tag "Comment" "%% Intended LaTeX compiler: %s\n")
1083 (const :tag "latex-mode file variable" "%% -*- latex-run-command: %s -*-\n")
1084 (const :tag "AUCTeX file variable" "%% -*- LaTeX-command: %s -*-\n")
1085 (string :tag "custom format" "%% %s"))
1086 :version "25.1"
1087 :package-version '(Org . "9.0"))
1089 (defcustom org-latex-compiler "pdflatex"
1090 "LaTeX compiler to use.
1092 Must be an element in `org-latex-compilers' or the empty quote.
1093 Can also be set in buffers via #+LATEX_COMPILER. See also
1094 `org-latex-compiler-file-string'."
1095 :group 'org-export-latex
1096 :type '(choice
1097 (const :tag "pdfLaTeX" "pdflatex")
1098 (const :tag "XeLaTeX" "xelatex")
1099 (const :tag "LuaLaTeX" "lualatex")
1100 (const :tag "Unset" ""))
1101 :version "25.1"
1102 :package-version '(Org . "9.0"))
1104 (defconst org-latex-compilers '("pdflatex" "xelatex" "lualatex")
1105 "Known LaTeX compilers.
1106 See also `org-latex-compiler'.")
1108 (defcustom org-latex-bib-compiler "bibtex"
1109 "Command to process a LaTeX file's bibliography.
1111 The shorthand %bib in `org-latex-pdf-process' is replaced with
1112 this value.
1114 A better approach is to use a compiler suit such as `latexmk'."
1115 :group 'org-export-latex
1116 :type '(choice (const :tag "BibTeX" "bibtex")
1117 (const :tag "Biber" "biber")
1118 (string :tag "Other process"))
1119 :version "25.1"
1120 :package-version '(Org . "9.0"))
1122 (defcustom org-latex-pdf-process
1123 '("%latex -interaction nonstopmode -output-directory %o %f"
1124 "%latex -interaction nonstopmode -output-directory %o %f"
1125 "%latex -interaction nonstopmode -output-directory %o %f")
1126 "Commands to process a LaTeX file to a PDF file.
1127 This is a list of strings, each of them will be given to the
1128 shell as a command. %f in the command will be replaced by the
1129 full file name, %b by the file base name (i.e. without directory
1130 and extension parts), %o by the base directory of the file,
1131 %latex is the LaTeX compiler (see `org-latex-compiler'), and %bib
1132 is the BibTeX-like compiler (see `org-latex-bib-compiler').
1134 The reason why this is a list is that it usually takes several
1135 runs of `pdflatex', maybe mixed with a call to `bibtex'. Org
1136 does not have a clever mechanism to detect which of these
1137 commands have to be run to get to a stable result, and it also
1138 does not do any error checking.
1140 Consider a smart LaTeX compiler such as `texi2dvi' or `latexmk',
1141 which calls the \"correct\" combinations of auxiliary programs.
1143 Alternatively, this may be a Lisp function that does the
1144 processing, so you could use this to apply the machinery of
1145 AUCTeX or the Emacs LaTeX mode. This function should accept the
1146 file name as its single argument."
1147 :group 'org-export-pdf
1148 :type '(choice
1149 (repeat :tag "Shell command sequence"
1150 (string :tag "Shell command"))
1151 (const :tag "2 runs of latex"
1152 ("%latex -interaction nonstopmode -output-directory %o %f"
1153 "%latex -interaction nonstopmode -output-directory %o %f"))
1154 (const :tag "3 runs of latex"
1155 ("%latex -interaction nonstopmode -output-directory %o %f"
1156 "%latex -interaction nonstopmode -output-directory %o %f"
1157 "%latex -interaction nonstopmode -output-directory %o %f"))
1158 (const :tag "latex,bibtex,latex,latex"
1159 ("%latex -interaction nonstopmode -output-directory %o %f"
1160 "%bib %b"
1161 "%latex -interaction nonstopmode -output-directory %o %f"
1162 "%latex -interaction nonstopmode -output-directory %o %f"))
1163 (const :tag "texi2dvi"
1164 ("LATEX=\"%latex\" texi2dvi -p -b -V %f"))
1165 (const :tag "latexmk"
1166 ("latexmk -g -pdflatex=\"%latex\" %f"))
1167 (function)))
1169 (defcustom org-latex-logfiles-extensions
1170 '("aux" "bcf" "blg" "fdb_latexmk" "fls" "figlist" "idx" "log" "nav" "out"
1171 "ptc" "run.xml" "snm" "toc" "vrb" "xdv")
1172 "The list of file extensions to consider as LaTeX logfiles.
1173 The logfiles will be removed if `org-latex-remove-logfiles' is
1174 non-nil."
1175 :group 'org-export-latex
1176 :version "25.1"
1177 :package-version '(Org . "8.3")
1178 :type '(repeat (string :tag "Extension")))
1180 (defcustom org-latex-remove-logfiles t
1181 "Non-nil means remove the logfiles produced by PDF production.
1182 By default, logfiles are files with these extensions: .aux, .idx,
1183 .log, .out, .toc, .nav, .snm and .vrb. To define the set of
1184 logfiles to remove, set `org-latex-logfiles-extensions'."
1185 :group 'org-export-latex
1186 :type 'boolean)
1188 (defcustom org-latex-known-warnings
1189 '(("Reference.*?undefined" . "[undefined reference]")
1190 ("Runaway argument" . "[runaway argument]")
1191 ("Underfull \\hbox" . "[underfull hbox]")
1192 ("Overfull \\hbox" . "[overfull hbox]")
1193 ("Citation.*?undefined" . "[undefined citation]")
1194 ("Undefined control sequence" . "[undefined control sequence]"))
1195 "Alist of regular expressions and associated messages for the user.
1196 The regular expressions are used to find possible warnings in the
1197 log of a latex-run. These warnings will be reported after
1198 calling `org-latex-compile'."
1199 :group 'org-export-latex
1200 :version "25.1"
1201 :package-version '(Org . "8.3")
1202 :type '(repeat
1203 (cons
1204 (string :tag "Regexp")
1205 (string :tag "Message"))))
1209 ;;; Internal Functions
1211 (defun org-latex--caption-above-p (element info)
1212 "Non nil when caption is expected to be located above ELEMENT.
1213 INFO is a plist holding contextual information."
1214 (let ((above (plist-get info :latex-caption-above)))
1215 (if (symbolp above) above
1216 (let ((type (org-element-type element)))
1217 (memq (if (eq type 'link) 'image type) above)))))
1219 (defun org-latex--label (datum info &optional force full)
1220 "Return an appropriate label for DATUM.
1221 DATUM is an element or a `target' type object. INFO is the
1222 current export state, as a plist.
1224 Return nil if element DATUM has no NAME or VALUE affiliated
1225 keyword or no CUSTOM_ID property, unless FORCE is non-nil. In
1226 this case always return a unique label.
1228 Eventually, if FULL is non-nil, wrap label within \"\\label{}\"."
1229 (let* ((type (org-element-type datum))
1230 (user-label
1231 (org-element-property
1232 (case type
1233 ((headline inlinetask) :CUSTOM_ID)
1234 (target :value)
1235 (otherwise :name))
1236 datum))
1237 (label
1238 (and (or user-label force)
1239 (if (and user-label (plist-get info :latex-prefer-user-labels))
1240 user-label
1241 (concat (case type
1242 (headline "sec:")
1243 (table "tab:")
1244 (latex-environment
1245 (and (org-string-match-p
1246 org-latex-math-environments-re
1247 (org-element-property :value datum))
1248 "eq:"))
1249 (paragraph
1250 (and (org-element-property :caption datum)
1251 "fig:")))
1252 (org-export-get-reference datum info))))))
1253 (cond ((not full) label)
1254 (label (format "\\label{%s}%s"
1255 label
1256 (if (eq type 'target) "" "\n")))
1257 (t ""))))
1259 (defun org-latex--caption/label-string (element info)
1260 "Return caption and label LaTeX string for ELEMENT.
1262 INFO is a plist holding contextual information. If there's no
1263 caption nor label, return the empty string.
1265 For non-floats, see `org-latex--wrap-label'."
1266 (let* ((label (org-latex--label element info nil t))
1267 (main (org-export-get-caption element))
1268 (attr (org-export-read-attribute :attr_latex element))
1269 (type (org-element-type element))
1270 (nonfloat (or (and (plist-member attr :float)
1271 (not (plist-get attr :float))
1272 main)
1273 (and (eq type 'src-block)
1274 (not (plist-get attr :float))
1275 (memq (plist-get info :latex-listings)
1276 '(nil minted)))))
1277 (short (org-export-get-caption element t))
1278 (caption-from-attr-latex (plist-get attr :caption)))
1279 (cond
1280 ((org-string-nw-p caption-from-attr-latex)
1281 (concat caption-from-attr-latex "\n"))
1282 ((and (not main) (equal label "")) "")
1283 ((not main) label)
1284 ;; Option caption format with short name.
1286 (format (if nonfloat "\\captionof{%s}%s{%s%s}\n"
1287 "\\caption%s%s{%s%s}\n")
1288 (if nonfloat
1289 (case type
1290 (paragraph "figure")
1291 (src-block (if (plist-get info :latex-listings)
1292 "listing"
1293 "figure"))
1294 (t (symbol-name type)))
1296 (if short (format "[%s]" (org-export-data short info)) "")
1297 label
1298 (org-export-data main info))))))
1300 (defun org-latex-guess-inputenc (header)
1301 "Set the coding system in inputenc to what the buffer is.
1303 HEADER is the LaTeX header string. This function only applies
1304 when specified inputenc option is \"AUTO\".
1306 Return the new header, as a string."
1307 (let* ((cs (or (ignore-errors
1308 (latexenc-coding-system-to-inputenc
1309 (or org-export-coding-system buffer-file-coding-system)))
1310 "utf8")))
1311 (if (not cs) header
1312 ;; First translate if that is requested.
1313 (setq cs (or (cdr (assoc cs org-latex-inputenc-alist)) cs))
1314 ;; Then find the \usepackage statement and replace the option.
1315 (replace-regexp-in-string "\\\\usepackage\\[\\(AUTO\\)\\]{inputenc}"
1316 cs header t nil 1))))
1318 (defun org-latex-guess-babel-language (header info)
1319 "Set Babel's language according to LANGUAGE keyword.
1321 HEADER is the LaTeX header string. INFO is the plist used as
1322 a communication channel.
1324 Insertion of guessed language only happens when Babel package has
1325 explicitly been loaded. Then it is added to the rest of
1326 package's options.
1328 The argument to Babel may be \"AUTO\" which is then replaced with
1329 the language of the document or `org-export-default-language'
1330 unless language in question is already loaded.
1332 Return the new header."
1333 (let ((language-code (plist-get info :language)))
1334 ;; If no language is set or Babel package is not loaded, return
1335 ;; HEADER as-is.
1336 (if (or (not (stringp language-code))
1337 (not (string-match "\\\\usepackage\\[\\(.*\\)\\]{babel}" header)))
1338 header
1339 (let ((options (save-match-data
1340 (org-split-string (match-string 1 header) ",[ \t]*")))
1341 (language (cdr (assoc language-code
1342 org-latex-babel-language-alist))))
1343 ;; If LANGUAGE is already loaded, return header without AUTO.
1344 ;; Otherwise, replace AUTO with language or append language if
1345 ;; AUTO is not present.
1346 (replace-match
1347 (mapconcat (lambda (option) (if (equal "AUTO" option) language option))
1348 (cond ((member language options) (delete "AUTO" options))
1349 ((member "AUTO" options) options)
1350 (t (append options (list language))))
1351 ", ")
1352 t nil header 1)))))
1354 (defun org-latex-guess-polyglossia-language (header info)
1355 "Set the Polyglossia language according to the LANGUAGE keyword.
1357 HEADER is the LaTeX header string. INFO is the plist used as
1358 a communication channel.
1360 Insertion of guessed language only happens when the Polyglossia
1361 package has been explicitly loaded.
1363 The argument to Polyglossia may be \"AUTO\" which is then
1364 replaced with the language of the document or
1365 `org-export-default-language'. Note, the language is really set
1366 using \setdefaultlanguage and not as an option to the package.
1368 Return the new header."
1369 (let ((language (plist-get info :language)))
1370 ;; If no language is set or Polyglossia is not loaded, return
1371 ;; HEADER as-is.
1372 (if (or (not (stringp language))
1373 (not (string-match
1374 "\\\\usepackage\\(?:\\[\\([^]]+?\\)\\]\\){polyglossia}\n"
1375 header)))
1376 header
1377 (let* ((options (org-string-nw-p (match-string 1 header)))
1378 (languages (and options
1379 ;; Reverse as the last loaded language is
1380 ;; the main language.
1381 (nreverse
1382 (delete-dups
1383 (save-match-data
1384 (org-split-string
1385 (replace-regexp-in-string
1386 "AUTO" language options t)
1387 ",[ \t]*"))))))
1388 (main-language-set
1389 (string-match-p "\\\\setmainlanguage{.*?}" header)))
1390 (replace-match
1391 (concat "\\usepackage{polyglossia}\n"
1392 (mapconcat
1393 (lambda (l)
1394 (let ((l (or (assoc l org-latex-polyglossia-language-alist)
1395 l)))
1396 (format (if main-language-set "\\setotherlanguage%s{%s}\n"
1397 (setq main-language-set t)
1398 "\\setmainlanguage%s{%s}\n")
1399 (if (and (consp l) (= (length l) 3))
1400 (format "[variant=%s]" (nth 2 l))
1402 (nth 1 l))))
1403 languages
1404 ""))
1405 t t header 0)))))
1407 (defun org-latex--remove-packages (pkg-alist info)
1408 "Remove packages based on the current LaTeX compiler.
1410 If the fourth argument of an element is set in pkg-alist, and it
1411 is not a member of the LaTeX compiler of the document, the packages
1412 is removed. See also `org-latex-compiler'.
1414 Return modified pkg-alist."
1415 (let ((compiler (or (plist-get info :latex-compiler) "")))
1416 (if (member-ignore-case compiler org-latex-compilers)
1417 (delq nil
1418 (mapcar
1419 (lambda (pkg)
1420 (unless (and
1421 (listp pkg)
1422 (let ((third (nth 3 pkg)))
1423 (and third
1424 (not (member-ignore-case
1425 compiler
1426 (if (listp third) third (list third)))))))
1427 pkg))
1428 pkg-alist))
1429 pkg-alist)))
1431 (defun org-latex--find-verb-separator (s)
1432 "Return a character not used in string S.
1433 This is used to choose a separator for constructs like \\verb."
1434 (let ((ll "~,./?;':\"|!@#%^&-_=+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ<>()[]{}"))
1435 (loop for c across ll
1436 when (not (string-match (regexp-quote (char-to-string c)) s))
1437 return (char-to-string c))))
1439 (defun org-latex--make-option-string (options)
1440 "Return a comma separated string of keywords and values.
1441 OPTIONS is an alist where the key is the options keyword as
1442 a string, and the value a list containing the keyword value, or
1443 nil."
1444 (mapconcat (lambda (pair)
1445 (concat (first pair)
1446 (when (> (length (second pair)) 0)
1447 (concat "=" (second pair)))))
1448 options
1449 ","))
1451 (defun org-latex--wrap-label (element output info)
1452 "Wrap label associated to ELEMENT around OUTPUT, if appropriate.
1453 INFO is the current export state, as a plist. This function
1454 should not be used for floats. See
1455 `org-latex--caption/label-string'."
1456 (if (not (and (org-string-nw-p output) (org-element-property :name element)))
1457 output
1458 (concat (format "\\phantomsection\n\\label{%s}\n"
1459 (org-latex--label element info))
1460 output)))
1462 (defun org-latex--protect-text (text)
1463 "Protect special characters in string TEXT and return it."
1464 (replace-regexp-in-string
1465 "--\\|[\\{}$%&_#~^]"
1466 (lambda (m)
1467 (cond ((equal m "--") "-{}-")
1468 ((equal m "\\") "\\textbackslash{}")
1469 ((equal m "~") "\\textasciitilde{}")
1470 ((equal m "^") "\\textasciicircum{}")
1471 (t (concat "\\" m))))
1472 text nil t))
1474 (defun org-latex--text-markup (text markup info)
1475 "Format TEXT depending on MARKUP text markup.
1476 INFO is a plist used as a communication channel. See
1477 `org-latex-text-markup-alist' for details."
1478 (let ((fmt (cdr (assq markup (plist-get info :latex-text-markup-alist)))))
1479 (case fmt
1480 ;; No format string: Return raw text.
1481 ((nil) text)
1482 ;; Handle the `verb' special case: Find an appropriate separator
1483 ;; and use "\\verb" command.
1484 (verb
1485 (let ((separator (org-latex--find-verb-separator text)))
1486 (concat "\\verb" separator
1487 (replace-regexp-in-string "\n" " " text)
1488 separator)))
1489 ;; Handle the `protectedtexttt' special case: Protect some
1490 ;; special chars and use "\texttt{%s}" format string.
1491 (protectedtexttt
1492 (format "\\texttt{%s}" (org-latex--protect-text text)))
1493 ;; Else use format string.
1494 (t (format fmt text)))))
1496 (defun org-latex--delayed-footnotes-definitions (element info)
1497 "Return footnotes definitions in ELEMENT as a string.
1499 INFO is a plist used as a communication channel.
1501 Footnotes definitions are returned within \"\\footnotetxt{}\"
1502 commands.
1504 This function is used within constructs that don't support
1505 \"\\footnote{}\" command (i.e. an item's tag). In that case,
1506 \"\\footnotemark\" is used within the construct and the function
1507 just outside of it."
1508 (mapconcat
1509 (lambda (ref)
1510 (format
1511 "\\footnotetext[%s]{%s}"
1512 (org-export-get-footnote-number ref info)
1513 (org-trim
1514 (org-export-data
1515 (org-export-get-footnote-definition ref info) info))))
1516 ;; Find every footnote reference in ELEMENT.
1517 (letrec ((all-refs nil)
1518 (search-refs
1519 (lambda (data)
1520 ;; Return a list of all footnote references never seen
1521 ;; before in DATA.
1522 (org-element-map data 'footnote-reference
1523 (lambda (ref)
1524 (when (org-export-footnote-first-reference-p ref info)
1525 (push ref all-refs)
1526 (when (eq (org-element-property :type ref) 'standard)
1527 (funcall search-refs
1528 (org-export-get-footnote-definition ref info)))))
1529 info)
1530 (reverse all-refs))))
1531 (funcall search-refs element))
1532 ""))
1534 (defun org-latex--translate (s info)
1535 "Translate string S according to specified language.
1536 INFO is a plist used as a communication channel."
1537 (org-export-translate s :latex info))
1539 (defun org-latex--format-spec (info)
1540 "Create a format-spec for document meta-data.
1541 INFO is a plist used as a communication channel."
1542 (let ((language (let ((lang (plist-get info :language)))
1543 (or (cdr (assoc lang org-latex-babel-language-alist))
1544 lang))))
1545 `((?a . ,(org-export-data (plist-get info :author) info))
1546 (?t . ,(org-export-data (plist-get info :title) info))
1547 (?k . ,(org-export-data (org-latex--wrap-latex-math-block
1548 (plist-get info :keywords) info)
1549 info))
1550 (?d . ,(org-export-data (org-latex--wrap-latex-math-block
1551 (plist-get info :description) info)
1552 info))
1553 (?c . ,(plist-get info :creator))
1554 (?l . ,language)
1555 (?L . ,(capitalize language))
1556 (?D . ,(org-export-get-date info)))))
1558 (defun org-latex--make-preamble (info)
1559 "Return a formatted LaTeX preamble.
1560 INFO is a plist used as a communication channel."
1561 (let* ((class (plist-get info :latex-class))
1562 (class-options (plist-get info :latex-class-options))
1563 (header (nth 1 (assoc class (plist-get info :latex-classes))))
1564 (document-class-string
1565 (and (stringp header)
1566 (if (not class-options) header
1567 (replace-regexp-in-string
1568 "^[ \t]*\\\\documentclass\\(\\(\\[[^]]*\\]\\)?\\)"
1569 class-options header t nil 1)))))
1570 (if (not document-class-string)
1571 (user-error "Unknown LaTeX class `%s'" class)
1572 (org-latex-guess-polyglossia-language
1573 (org-latex-guess-babel-language
1574 (org-latex-guess-inputenc
1575 (org-element-normalize-string
1576 (org-splice-latex-header
1577 document-class-string
1578 (org-latex--remove-packages
1579 org-latex-default-packages-alist info)
1580 (org-latex--remove-packages
1581 org-latex-packages-alist info)
1583 (mapconcat 'org-element-normalize-string
1584 (list (plist-get info :latex-header)
1585 (plist-get info :latex-header-extra)) ""))))
1586 info)
1587 info))))
1589 (defun org-latex--insert-compiler (info)
1590 "Insert LaTeX_compiler info into the document.
1591 INFO is a plist used as a communication channel."
1592 (let ((compiler (plist-get info :latex-compiler)))
1593 (and (org-string-nw-p org-latex-compiler-file-string)
1594 (string-match-p (regexp-opt org-latex-compilers) (or compiler ""))
1595 (format org-latex-compiler-file-string compiler))))
1598 ;;; Template
1600 (defun org-latex-template (contents info)
1601 "Return complete document string after LaTeX conversion.
1602 CONTENTS is the transcoded contents string. INFO is a plist
1603 holding export options."
1604 (let ((title (org-export-data (plist-get info :title) info))
1605 (spec (org-latex--format-spec info)))
1606 (concat
1607 ;; Time-stamp.
1608 (and (plist-get info :time-stamp-file)
1609 (format-time-string "%% Created %Y-%m-%d %a %H:%M\n"))
1610 ;; LaTeX compiler.
1611 (org-latex--insert-compiler info)
1612 ;; Document class and packages.
1613 (org-latex--make-preamble info)
1614 ;; Possibly limit depth for headline numbering.
1615 (let ((sec-num (plist-get info :section-numbers)))
1616 (when (integerp sec-num)
1617 (format "\\setcounter{secnumdepth}{%d}\n" sec-num)))
1618 ;; Author.
1619 (let ((author (and (plist-get info :with-author)
1620 (let ((auth (plist-get info :author)))
1621 (and auth (org-export-data auth info)))))
1622 (email (and (plist-get info :with-email)
1623 (org-export-data (plist-get info :email) info))))
1624 (cond ((and author email (not (string= "" email)))
1625 (format "\\author{%s\\thanks{%s}}\n" author email))
1626 ((or author email) (format "\\author{%s}\n" (or author email)))))
1627 ;; Date.
1628 (let ((date (and (plist-get info :with-date) (org-export-get-date info))))
1629 (format "\\date{%s}\n" (org-export-data date info)))
1630 ;; Title and subtitle.
1631 (let* ((subtitle (plist-get info :subtitle))
1632 (formatted-subtitle
1633 (when subtitle
1634 (format (plist-get info :latex-subtitle-format)
1635 (org-export-data subtitle info))))
1636 (separate (plist-get info :latex-subtitle-separate)))
1637 (concat
1638 (format "\\title{%s%s}\n" title
1639 (if separate "" (or formatted-subtitle "")))
1640 (when (and separate subtitle)
1641 (concat formatted-subtitle "\n"))))
1642 ;; Hyperref options.
1643 (let ((template (plist-get info :latex-hyperref-template)))
1644 (and (stringp template)
1645 (format-spec template spec)))
1646 ;; Document start.
1647 "\\begin{document}\n\n"
1648 ;; Title command.
1649 (let* ((title-command (plist-get info :latex-title-command))
1650 (command (and (stringp title-command)
1651 (format-spec title-command spec))))
1652 (org-element-normalize-string
1653 (cond ((not (plist-get info :with-title)) nil)
1654 ((string= "" title) nil)
1655 ((not (stringp command)) nil)
1656 ((string-match "\\(?:[^%]\\|^\\)%s" command)
1657 (format command title))
1658 (t command))))
1659 ;; Table of contents.
1660 (let ((depth (plist-get info :with-toc)))
1661 (when depth
1662 (concat (when (wholenump depth)
1663 (format "\\setcounter{tocdepth}{%d}\n" depth))
1664 (plist-get info :latex-toc-command))))
1665 ;; Document's body.
1666 contents
1667 ;; Creator.
1668 (and (plist-get info :with-creator)
1669 (concat (plist-get info :creator) "\n"))
1670 ;; Document end.
1671 "\\end{document}")))
1675 ;;; Transcode Functions
1677 ;;;; Bold
1679 (defun org-latex-bold (_bold contents info)
1680 "Transcode BOLD from Org to LaTeX.
1681 CONTENTS is the text with bold markup. INFO is a plist holding
1682 contextual information."
1683 (org-latex--text-markup contents 'bold info))
1686 ;;;; Center Block
1688 (defun org-latex-center-block (center-block contents info)
1689 "Transcode a CENTER-BLOCK element from Org to LaTeX.
1690 CONTENTS holds the contents of the center block. INFO is a plist
1691 holding contextual information."
1692 (org-latex--wrap-label
1693 center-block (format "\\begin{center}\n%s\\end{center}" contents) info))
1696 ;;;; Clock
1698 (defun org-latex-clock (clock _contents info)
1699 "Transcode a CLOCK element from Org to LaTeX.
1700 CONTENTS is nil. INFO is a plist holding contextual
1701 information."
1702 (concat
1703 "\\noindent"
1704 (format "\\textbf{%s} " org-clock-string)
1705 (format (plist-get info :latex-inactive-timestamp-format)
1706 (concat (org-timestamp-translate (org-element-property :value clock))
1707 (let ((time (org-element-property :duration clock)))
1708 (and time (format " (%s)" time)))))
1709 "\\\\"))
1712 ;;;; Code
1714 (defun org-latex-code (code _contents info)
1715 "Transcode a CODE object from Org to LaTeX.
1716 CONTENTS is nil. INFO is a plist used as a communication
1717 channel."
1718 (org-latex--text-markup (org-element-property :value code) 'code info))
1721 ;;;; Drawer
1723 (defun org-latex-drawer (drawer contents info)
1724 "Transcode a DRAWER element from Org to LaTeX.
1725 CONTENTS holds the contents of the block. INFO is a plist
1726 holding contextual information."
1727 (let* ((name (org-element-property :drawer-name drawer))
1728 (output (funcall (plist-get info :latex-format-drawer-function)
1729 name contents)))
1730 (org-latex--wrap-label drawer output info)))
1733 ;;;; Dynamic Block
1735 (defun org-latex-dynamic-block (dynamic-block contents info)
1736 "Transcode a DYNAMIC-BLOCK element from Org to LaTeX.
1737 CONTENTS holds the contents of the block. INFO is a plist
1738 holding contextual information. See `org-export-data'."
1739 (org-latex--wrap-label dynamic-block contents info))
1742 ;;;; Entity
1744 (defun org-latex-entity (entity _contents _info)
1745 "Transcode an ENTITY object from Org to LaTeX.
1746 CONTENTS are the definition itself. INFO is a plist holding
1747 contextual information."
1748 (org-element-property :latex entity))
1751 ;;;; Example Block
1753 (defun org-latex-example-block (example-block _contents info)
1754 "Transcode an EXAMPLE-BLOCK element from Org to LaTeX.
1755 CONTENTS is nil. INFO is a plist holding contextual
1756 information."
1757 (when (org-string-nw-p (org-element-property :value example-block))
1758 (let ((environment (or (org-export-read-attribute
1759 :attr_latex example-block :environment)
1760 "verbatim")))
1761 (org-latex--wrap-label
1762 example-block
1763 (format "\\begin{%s}\n%s\\end{%s}"
1764 environment
1765 (org-export-format-code-default example-block info)
1766 environment)
1767 info))))
1770 ;;;; Export Block
1772 (defun org-latex-export-block (export-block _contents _info)
1773 "Transcode a EXPORT-BLOCK element from Org to LaTeX.
1774 CONTENTS is nil. INFO is a plist holding contextual information."
1775 (when (member (org-element-property :type export-block) '("LATEX" "TEX"))
1776 (org-remove-indentation (org-element-property :value export-block))))
1779 ;;;; Export Snippet
1781 (defun org-latex-export-snippet (export-snippet _contents _info)
1782 "Transcode a EXPORT-SNIPPET object from Org to LaTeX.
1783 CONTENTS is nil. INFO is a plist holding contextual information."
1784 (when (eq (org-export-snippet-backend export-snippet) 'latex)
1785 (org-element-property :value export-snippet)))
1788 ;;;; Fixed Width
1790 (defun org-latex-fixed-width (fixed-width _contents info)
1791 "Transcode a FIXED-WIDTH element from Org to LaTeX.
1792 CONTENTS is nil. INFO is a plist holding contextual information."
1793 (org-latex--wrap-label
1794 fixed-width
1795 (format "\\begin{verbatim}\n%s\\end{verbatim}"
1796 (org-remove-indentation
1797 (org-element-property :value fixed-width)))
1798 info))
1801 ;;;; Footnote Reference
1803 (defun org-latex-footnote-reference (footnote-reference _contents info)
1804 "Transcode a FOOTNOTE-REFERENCE element from Org to LaTeX.
1805 CONTENTS is nil. INFO is a plist holding contextual information."
1806 (concat
1807 ;; Insert separator between two footnotes in a row.
1808 (let ((prev (org-export-get-previous-element footnote-reference info)))
1809 (when (eq (org-element-type prev) 'footnote-reference)
1810 (plist-get info :latex-footnote-separator)))
1811 (cond
1812 ;; Use \footnotemark if the footnote has already been defined.
1813 ((not (org-export-footnote-first-reference-p footnote-reference info))
1814 (format "\\footnotemark[%s]{}"
1815 (org-export-get-footnote-number footnote-reference info)))
1816 ;; Use \footnotemark if reference is within another footnote
1817 ;; reference, footnote definition or table cell.
1818 ((org-element-lineage footnote-reference
1819 '(footnote-reference footnote-definition table-cell))
1820 "\\footnotemark")
1821 ;; Otherwise, define it with \footnote command.
1823 (let ((def (org-export-get-footnote-definition footnote-reference info)))
1824 (concat
1825 (format "\\footnote{%s}" (org-trim (org-export-data def info)))
1826 ;; Retrieve all footnote references within the footnote and
1827 ;; add their definition after it, since LaTeX doesn't support
1828 ;; them inside.
1829 (org-latex--delayed-footnotes-definitions def info)))))))
1832 ;;;; Headline
1834 (defun org-latex-headline (headline contents info)
1835 "Transcode a HEADLINE element from Org to LaTeX.
1836 CONTENTS holds the contents of the headline. INFO is a plist
1837 holding contextual information."
1838 (unless (org-element-property :footnote-section-p headline)
1839 (let* ((class (plist-get info :latex-class))
1840 (level (org-export-get-relative-level headline info))
1841 (numberedp (org-export-numbered-headline-p headline info))
1842 (class-sectioning (assoc class (plist-get info :latex-classes)))
1843 ;; Section formatting will set two placeholders: one for
1844 ;; the title and the other for the contents.
1845 (section-fmt
1846 (let ((sec (if (functionp (nth 2 class-sectioning))
1847 (funcall (nth 2 class-sectioning) level numberedp)
1848 (nth (1+ level) class-sectioning))))
1849 (cond
1850 ;; No section available for that LEVEL.
1851 ((not sec) nil)
1852 ;; Section format directly returned by a function. Add
1853 ;; placeholder for contents.
1854 ((stringp sec) (concat sec "\n%s"))
1855 ;; (numbered-section . unnumbered-section)
1856 ((not (consp (cdr sec)))
1857 (concat (funcall (if numberedp #'car #'cdr) sec) "\n%s"))
1858 ;; (numbered-open numbered-close)
1859 ((= (length sec) 2)
1860 (when numberedp (concat (car sec) "\n%s" (nth 1 sec))))
1861 ;; (num-in num-out no-num-in no-num-out)
1862 ((= (length sec) 4)
1863 (if numberedp (concat (car sec) "\n%s" (nth 1 sec))
1864 (concat (nth 2 sec) "\n%s" (nth 3 sec)))))))
1865 ;; Create a temporary export back-end that hard-codes
1866 ;; "\underline" within "\section" and alike.
1867 (section-back-end
1868 (org-export-create-backend
1869 :parent 'latex
1870 :transcoders
1871 '((underline . (lambda (o c i) (format "\\underline{%s}" c))))))
1872 (text
1873 (org-export-data-with-backend
1874 (org-element-property :title headline) section-back-end info))
1875 (todo
1876 (and (plist-get info :with-todo-keywords)
1877 (let ((todo (org-element-property :todo-keyword headline)))
1878 (and todo (org-export-data todo info)))))
1879 (todo-type (and todo (org-element-property :todo-type headline)))
1880 (tags (and (plist-get info :with-tags)
1881 (org-export-get-tags headline info)))
1882 (priority (and (plist-get info :with-priority)
1883 (org-element-property :priority headline)))
1884 ;; Create the headline text along with a no-tag version.
1885 ;; The latter is required to remove tags from toc.
1886 (full-text (funcall (plist-get info :latex-format-headline-function)
1887 todo todo-type priority text tags info))
1888 ;; Associate \label to the headline for internal links.
1889 (headline-label (org-latex--label headline info t t))
1890 (pre-blanks
1891 (make-string (org-element-property :pre-blank headline) ?\n)))
1892 (if (or (not section-fmt) (org-export-low-level-p headline info))
1893 ;; This is a deep sub-tree: export it as a list item. Also
1894 ;; export as items headlines for which no section format has
1895 ;; been found.
1896 (let ((low-level-body
1897 (concat
1898 ;; If headline is the first sibling, start a list.
1899 (when (org-export-first-sibling-p headline info)
1900 (format "\\begin{%s}\n" (if numberedp 'enumerate 'itemize)))
1901 ;; Itemize headline
1902 "\\item"
1903 (and full-text (org-string-match-p "\\`[ \t]*\\[" full-text)
1904 "\\relax")
1905 " " full-text "\n"
1906 headline-label
1907 pre-blanks
1908 contents)))
1909 ;; If headline is not the last sibling simply return
1910 ;; LOW-LEVEL-BODY. Otherwise, also close the list, before
1911 ;; any blank line.
1912 (if (not (org-export-last-sibling-p headline info)) low-level-body
1913 (replace-regexp-in-string
1914 "[ \t\n]*\\'"
1915 (format "\n\\\\end{%s}" (if numberedp 'enumerate 'itemize))
1916 low-level-body)))
1917 ;; This is a standard headline. Export it as a section. Add
1918 ;; an alternative heading when possible, and when this is not
1919 ;; identical to the usual heading.
1920 (let ((opt-title
1921 (funcall (plist-get info :latex-format-headline-function)
1922 todo todo-type priority
1923 (org-export-data-with-backend
1924 (org-export-get-alt-title headline info)
1925 section-back-end info)
1926 (and (eq (plist-get info :with-tags) t) tags)
1927 info))
1928 ;; Maybe end local TOC (see `org-latex-keyword').
1929 (contents
1930 (concat
1931 contents
1932 (let ((case-fold-search t)
1933 (section
1934 (let ((first (car (org-element-contents headline))))
1935 (and (eq (org-element-type first) 'section) first))))
1936 (org-element-map section 'keyword
1937 (lambda (k)
1938 (and (equal (org-element-property :key k) "TOC")
1939 (let ((v (org-element-property :value k)))
1940 (and (org-string-match-p "\\<headlines\\>" v)
1941 (org-string-match-p "\\<local\\>" v)
1942 (format "\\stopcontents[level-%d]" level)))))
1943 info t)))))
1944 (if (and opt-title
1945 (not (equal opt-title full-text))
1946 (string-match "\\`\\\\\\(.+?\\){" section-fmt))
1947 (format (replace-match "\\1[%s]" nil nil section-fmt 1)
1948 ;; Replace square brackets with parenthesis
1949 ;; since square brackets are not supported in
1950 ;; optional arguments.
1951 (replace-regexp-in-string
1952 "\\[" "(" (replace-regexp-in-string "\\]" ")" opt-title))
1953 full-text
1954 (concat headline-label pre-blanks contents))
1955 ;; Impossible to add an alternative heading. Fallback to
1956 ;; regular sectioning format string.
1957 (format section-fmt full-text
1958 (concat headline-label pre-blanks contents))))))))
1960 (defun org-latex-format-headline-default-function
1961 (todo _todo-type priority text tags info)
1962 "Default format function for a headline.
1963 See `org-latex-format-headline-function' for details."
1964 (concat
1965 (and todo (format "{\\bfseries\\sffamily %s} " todo))
1966 (and priority (format "\\framebox{\\#%c} " priority))
1967 text
1968 (and tags
1969 (format "\\hfill{}\\textsc{%s}"
1970 (mapconcat (lambda (tag) (org-latex-plain-text tag info))
1971 tags ":")))))
1974 ;;;; Horizontal Rule
1976 (defun org-latex-horizontal-rule (horizontal-rule _contents info)
1977 "Transcode an HORIZONTAL-RULE object from Org to LaTeX.
1978 CONTENTS is nil. INFO is a plist holding contextual information."
1979 (let ((attr (org-export-read-attribute :attr_latex horizontal-rule))
1980 (prev (org-export-get-previous-element horizontal-rule info)))
1981 (concat
1982 ;; Make sure the rule doesn't start at the end of the current
1983 ;; line by separating it with a blank line from previous element.
1984 (when (and prev
1985 (let ((prev-blank (org-element-property :post-blank prev)))
1986 (or (not prev-blank) (zerop prev-blank))))
1987 "\n")
1988 (org-latex--wrap-label
1989 horizontal-rule
1990 (format "\\rule{%s}{%s}"
1991 (or (plist-get attr :width) "\\linewidth")
1992 (or (plist-get attr :thickness) "0.5pt"))
1993 info))))
1996 ;;;; Inline Src Block
1998 (defun org-latex-inline-src-block (inline-src-block _contents info)
1999 "Transcode an INLINE-SRC-BLOCK element from Org to LaTeX.
2000 CONTENTS holds the contents of the item. INFO is a plist holding
2001 contextual information."
2002 (let* ((code (org-element-property :value inline-src-block))
2003 (separator (org-latex--find-verb-separator code)))
2004 (case (plist-get info :latex-listings)
2005 ;; Do not use a special package: transcode it verbatim.
2006 ((nil) (format "\\texttt{%s}" (org-latex--protect-text code)))
2007 ;; Use minted package.
2008 (minted
2009 (let* ((org-lang (org-element-property :language inline-src-block))
2010 (mint-lang (or (cadr (assq (intern org-lang)
2011 (plist-get info :latex-minted-langs)))
2012 (downcase org-lang)))
2013 (options (org-latex--make-option-string
2014 (plist-get info :latex-minted-options))))
2015 (format "\\mintinline%s{%s}{%s}"
2016 (if (string= options "") "" (format "[%s]" options))
2017 mint-lang
2018 code)))
2019 ;; Use listings package.
2020 (otherwise
2021 ;; Maybe translate language's name.
2022 (let* ((org-lang (org-element-property :language inline-src-block))
2023 (lst-lang (or (cadr (assq (intern org-lang)
2024 (plist-get info :latex-listings-langs)))
2025 org-lang))
2026 (options (org-latex--make-option-string
2027 (append (plist-get info :latex-listings-options)
2028 `(("language" ,lst-lang))))))
2029 (concat (format "\\lstinline[%s]" options)
2030 separator code separator))))))
2033 ;;;; Inlinetask
2035 (defun org-latex-inlinetask (inlinetask contents info)
2036 "Transcode an INLINETASK element from Org to LaTeX.
2037 CONTENTS holds the contents of the block. INFO is a plist
2038 holding contextual information."
2039 (let ((title (org-export-data (org-element-property :title inlinetask) info))
2040 (todo (and (plist-get info :with-todo-keywords)
2041 (let ((todo (org-element-property :todo-keyword inlinetask)))
2042 (and todo (org-export-data todo info)))))
2043 (todo-type (org-element-property :todo-type inlinetask))
2044 (tags (and (plist-get info :with-tags)
2045 (org-export-get-tags inlinetask info)))
2046 (priority (and (plist-get info :with-priority)
2047 (org-element-property :priority inlinetask)))
2048 (contents (concat (org-latex--label inlinetask info) contents)))
2049 (funcall (plist-get info :latex-format-inlinetask-function)
2050 todo todo-type priority title tags contents info)))
2052 (defun org-latex-format-inlinetask-default-function
2053 (todo _todo-type priority title tags contents info)
2054 "Default format function for a inlinetasks.
2055 See `org-latex-format-inlinetask-function' for details."
2056 (let ((full-title
2057 (concat (when todo (format "\\textbf{\\textsf{\\textsc{%s}}} " todo))
2058 (when priority (format "\\framebox{\\#%c} " priority))
2059 title
2060 (when tags
2061 (format "\\hfill{}\\textsc{:%s:}"
2062 (mapconcat
2063 (lambda (tag) (org-latex-plain-text tag info))
2064 tags ":"))))))
2065 (concat "\\begin{center}\n"
2066 "\\fbox{\n"
2067 "\\begin{minipage}[c]{.6\\textwidth}\n"
2068 full-title "\n\n"
2069 (and (org-string-nw-p contents)
2070 (concat "\\rule[.8em]{\\textwidth}{2pt}\n\n" contents))
2071 "\\end{minipage}\n"
2072 "}\n"
2073 "\\end{center}")))
2076 ;;;; Italic
2078 (defun org-latex-italic (_italic contents info)
2079 "Transcode ITALIC from Org to LaTeX.
2080 CONTENTS is the text with italic markup. INFO is a plist holding
2081 contextual information."
2082 (org-latex--text-markup contents 'italic info))
2085 ;;;; Item
2087 (defun org-latex-item (item contents info)
2088 "Transcode an ITEM element from Org to LaTeX.
2089 CONTENTS holds the contents of the item. INFO is a plist holding
2090 contextual information."
2091 (let* ((counter
2092 (let ((count (org-element-property :counter item))
2093 (level
2094 ;; Determine level of current item to determine the
2095 ;; correct LaTeX counter to use (enumi, enumii...).
2096 (let ((parent item) (level 0))
2097 (while (memq (org-element-type
2098 (setq parent (org-export-get-parent parent)))
2099 '(plain-list item))
2100 (when (and (eq (org-element-type parent) 'plain-list)
2101 (eq (org-element-property :type parent)
2102 'ordered))
2103 (incf level)))
2104 level)))
2105 (and count
2106 (< level 5)
2107 (format "\\setcounter{enum%s}{%s}\n"
2108 (nth (1- level) '("i" "ii" "iii" "iv"))
2109 (1- count)))))
2110 (checkbox (case (org-element-property :checkbox item)
2111 (on "$\\boxtimes$ ")
2112 (off "$\\square$ ")
2113 (trans "$\\boxminus$ ")))
2114 (tag (let ((tag (org-element-property :tag item)))
2115 ;; Check-boxes must belong to the tag.
2116 (and tag (format "[{%s}] "
2117 (concat checkbox
2118 (org-export-data tag info)))))))
2119 (concat counter
2120 "\\item"
2121 (cond
2122 (tag)
2123 (checkbox (concat " " checkbox))
2124 ;; Without a tag or a check-box, if CONTENTS starts with
2125 ;; an opening square bracket, add "\relax" to "\item",
2126 ;; unless the brackets comes from an initial export
2127 ;; snippet (i.e. it is inserted willingly by the user).
2128 ((and contents
2129 (org-string-match-p "\\`[ \t]*\\[" contents)
2130 (not (let ((e (car (org-element-contents item))))
2131 (and (eq (org-element-type e) 'paragraph)
2132 (let ((o (car (org-element-contents e))))
2133 (and (eq (org-element-type o) 'export-snippet)
2134 (eq (org-export-snippet-backend o)
2135 'latex)))))))
2136 "\\relax ")
2137 (t " "))
2138 (and contents (org-trim contents))
2139 ;; If there are footnotes references in tag, be sure to
2140 ;; add their definition at the end of the item. This
2141 ;; workaround is necessary since "\footnote{}" command is
2142 ;; not supported in tags.
2143 (and tag
2144 (org-latex--delayed-footnotes-definitions
2145 (org-element-property :tag item) info)))))
2148 ;;;; Keyword
2150 (defun org-latex-keyword (keyword _contents info)
2151 "Transcode a KEYWORD element from Org to LaTeX.
2152 CONTENTS is nil. INFO is a plist holding contextual information."
2153 (let ((key (org-element-property :key keyword))
2154 (value (org-element-property :value keyword)))
2155 (cond
2156 ((string= key "LATEX") value)
2157 ((string= key "INDEX") (format "\\index{%s}" value))
2158 ((string= key "TOC")
2159 (let ((case-fold-search t))
2160 (cond
2161 ((org-string-match-p "\\<headlines\\>" value)
2162 (let* ((localp (org-string-match-p "\\<local\\>" value))
2163 (parent (org-element-lineage keyword '(headline)))
2164 (level (if (not (and localp parent)) 0
2165 (org-export-get-relative-level parent info)))
2166 (depth
2167 (and (string-match "\\<[0-9]+\\>" value)
2168 (format
2169 "\\setcounter{tocdepth}{%d}"
2170 (+ (string-to-number (match-string 0 value)) level)))))
2171 (if (and localp parent)
2172 ;; Start local TOC, assuming package "titletoc" is
2173 ;; required.
2174 (format "\\startcontents[level-%d]
2175 \\printcontents[level-%d]{}{0}{%s}"
2176 level level (or depth ""))
2177 (concat depth (and depth "\n") "\\tableofcontents"))))
2178 ((org-string-match-p "\\<tables\\>" value) "\\listoftables")
2179 ((org-string-match-p "\\<listings\\>" value)
2180 (case (plist-get info :latex-listings)
2181 ((nil) "\\listoffigures")
2182 (minted "\\listoflistings")
2183 (otherwise "\\lstlistoflistings")))))))))
2186 ;;;; Latex Environment
2188 (defun org-latex-latex-environment (latex-environment _contents info)
2189 "Transcode a LATEX-ENVIRONMENT element from Org to LaTeX.
2190 CONTENTS is nil. INFO is a plist holding contextual information."
2191 (when (plist-get info :with-latex)
2192 (let ((value (org-remove-indentation
2193 (org-element-property :value latex-environment))))
2194 (if (not (org-element-property :name latex-environment)) value
2195 ;; Environment is labeled: label must be within the environment
2196 ;; (otherwise, a reference pointing to that element will count
2197 ;; the section instead).
2198 (with-temp-buffer
2199 (insert value)
2200 (goto-char (point-min))
2201 (forward-line)
2202 (insert (org-latex--label latex-environment info nil t))
2203 (buffer-string))))))
2206 ;;;; Latex Fragment
2208 (defun org-latex-latex-fragment (latex-fragment _contents _info)
2209 "Transcode a LATEX-FRAGMENT object from Org to LaTeX.
2210 CONTENTS is nil. INFO is a plist holding contextual information."
2211 (let ((value (org-element-property :value latex-fragment)))
2212 ;; Trim math markers since the fragment is enclosed within
2213 ;; a latex-math-block object anyway.
2214 (cond ((string-match-p "\\`\\$[^$]" value) (substring value 1 -1))
2215 ((string-prefix-p "\\(" value) (substring value 2 -2))
2216 (t value))))
2219 ;;;; Line Break
2221 (defun org-latex-line-break (_line-break _contents _info)
2222 "Transcode a LINE-BREAK object from Org to LaTeX.
2223 CONTENTS is nil. INFO is a plist holding contextual information."
2224 "\\\\\n")
2227 ;;;; Link
2229 (defun org-latex--inline-image (link info)
2230 "Return LaTeX code for an inline image.
2231 LINK is the link pointing to the inline image. INFO is a plist
2232 used as a communication channel."
2233 (let* ((parent (org-export-get-parent-element link))
2234 (path (let ((raw-path (org-element-property :path link)))
2235 (if (not (file-name-absolute-p raw-path)) raw-path
2236 (expand-file-name raw-path))))
2237 (filetype (file-name-extension path))
2238 (caption (org-latex--caption/label-string parent info))
2239 (caption-above-p (org-latex--caption-above-p link info))
2240 ;; Retrieve latex attributes from the element around.
2241 (attr (org-export-read-attribute :attr_latex parent))
2242 (float (let ((float (plist-get attr :float)))
2243 (cond ((string= float "wrap") 'wrap)
2244 ((string= float "sideways") 'sideways)
2245 ((string= float "multicolumn") 'multicolumn)
2246 ((or float
2247 (org-element-property :caption parent)
2248 (org-string-nw-p (plist-get attr :caption)))
2249 (if (and (plist-member attr :float) (not float))
2250 'nonfloat
2251 'figure))
2252 ((and (not float) (plist-member attr :float)) nil))))
2253 (placement
2254 (let ((place (plist-get attr :placement)))
2255 (cond
2256 (place (format "%s" place))
2257 ((eq float 'wrap) "{l}{0.5\\textwidth}")
2258 ((eq float 'figure)
2259 (format "[%s]" (plist-get info :latex-default-figure-position)))
2260 (t ""))))
2261 (comment-include (if (plist-get attr :comment-include) "%" ""))
2262 ;; It is possible to specify width and height in the
2263 ;; ATTR_LATEX line, and also via default variables.
2264 (width (cond ((plist-get attr :width))
2265 ((plist-get attr :height) "")
2266 ((eq float 'wrap) "0.48\\textwidth")
2267 (t (plist-get info :latex-image-default-width))))
2268 (height (cond ((plist-get attr :height))
2269 ((or (plist-get attr :width)
2270 (memq float '(figure wrap))) "")
2271 (t (plist-get info :latex-image-default-height))))
2272 (options (let ((opt (or (plist-get attr :options)
2273 (plist-get info :latex-image-default-option))))
2274 (if (not (string-match "\\`\\[\\(.*\\)\\]\\'" opt)) opt
2275 (match-string 1 opt))))
2276 image-code)
2277 (if (member filetype '("tikz" "pgf"))
2278 ;; For tikz images:
2279 ;; - use \input to read in image file.
2280 ;; - if options are present, wrap in a tikzpicture environment.
2281 ;; - if width or height are present, use \resizebox to change
2282 ;; the image size.
2283 (progn
2284 (setq image-code (format "\\input{%s}" path))
2285 (when (org-string-nw-p options)
2286 (setq image-code
2287 (format "\\begin{tikzpicture}[%s]\n%s\n\\end{tikzpicture}"
2288 options
2289 image-code)))
2290 (when (or (org-string-nw-p width) (org-string-nw-p height))
2291 (setq image-code (format "\\resizebox{%s}{%s}{%s}"
2292 (if (org-string-nw-p width) width "!")
2293 (if (org-string-nw-p height) height "!")
2294 image-code))))
2295 ;; For other images:
2296 ;; - add width and height to options.
2297 ;; - include the image with \includegraphics.
2298 (when (org-string-nw-p width)
2299 (setq options (concat options ",width=" width)))
2300 (when (org-string-nw-p height)
2301 (setq options (concat options ",height=" height)))
2302 (let ((search-option (org-element-property :search-option link)))
2303 (when (and search-option
2304 (equal filetype "pdf")
2305 (org-string-match-p "\\`[0-9]+\\'" search-option)
2306 (not (org-string-match-p "page=" options)))
2307 (setq options (concat options ",page=" search-option))))
2308 (setq image-code
2309 (format "\\includegraphics%s{%s}"
2310 (cond ((not (org-string-nw-p options)) "")
2311 ((= (aref options 0) ?,)
2312 (format "[%s]"(substring options 1)))
2313 (t (format "[%s]" options)))
2314 path))
2315 (when (equal filetype "svg")
2316 (setq image-code (replace-regexp-in-string "^\\\\includegraphics"
2317 "\\includesvg"
2318 image-code
2319 nil t))
2320 (setq image-code (replace-regexp-in-string "\\.svg}"
2322 image-code
2323 nil t))))
2324 ;; Return proper string, depending on FLOAT.
2325 (case float
2326 (wrap (format "\\begin{wrapfigure}%s
2327 %s\\centering
2328 %s%s
2329 %s\\end{wrapfigure}"
2330 placement
2331 (if caption-above-p caption "")
2332 comment-include image-code
2333 (if caption-above-p "" caption)))
2334 (sideways (format "\\begin{sidewaysfigure}
2335 %s\\centering
2336 %s%s
2337 %s\\end{sidewaysfigure}"
2338 (if caption-above-p caption "")
2339 comment-include image-code
2340 (if caption-above-p "" caption)))
2341 (multicolumn (format "\\begin{figure*}%s
2342 %s\\centering
2343 %s%s
2344 %s\\end{figure*}"
2345 placement
2346 (if caption-above-p caption "")
2347 comment-include image-code
2348 (if caption-above-p "" caption)))
2349 (figure (format "\\begin{figure}%s
2350 %s\\centering
2351 %s%s
2352 %s\\end{figure}"
2353 placement
2354 (if caption-above-p caption "")
2355 comment-include image-code
2356 (if caption-above-p "" caption)))
2357 (nonfloat
2358 (format "\\begin{center}
2359 %s%s
2360 %s\\end{center}"
2361 (if caption-above-p caption "")
2362 image-code
2363 (if caption-above-p "" caption)))
2364 (otherwise image-code))))
2366 (defun org-latex-link (link desc info)
2367 "Transcode a LINK object from Org to LaTeX.
2369 DESC is the description part of the link, or the empty string.
2370 INFO is a plist holding contextual information. See
2371 `org-export-data'."
2372 (let* ((type (org-element-property :type link))
2373 (raw-path (replace-regexp-in-string
2374 "%" "\\%" (org-element-property :path link) nil t))
2375 ;; Ensure DESC really exists, or set it to nil.
2376 (desc (and (not (string= desc "")) desc))
2377 (imagep (org-export-inline-image-p
2378 link (plist-get info :latex-inline-image-rules)))
2379 (path (cond
2380 ((member type '("http" "https" "ftp" "mailto" "doi"))
2381 (concat type ":" raw-path))
2382 ((string= type "file") (org-export-file-uri raw-path))
2383 (t raw-path))))
2384 (cond
2385 ;; Link type is handled by a special function.
2386 ((org-export-custom-protocol-maybe link desc 'latex))
2387 ;; Image file.
2388 (imagep (org-latex--inline-image link info))
2389 ;; Radio link: Transcode target's contents and use them as link's
2390 ;; description.
2391 ((string= type "radio")
2392 (let ((destination (org-export-resolve-radio-link link info)))
2393 (if (not destination) desc
2394 (format "\\hyperref[%s]{%s}"
2395 (org-export-get-reference destination info)
2396 desc))))
2397 ;; Links pointing to a headline: Find destination and build
2398 ;; appropriate referencing command.
2399 ((member type '("custom-id" "fuzzy" "id"))
2400 (let ((destination (if (string= type "fuzzy")
2401 (org-export-resolve-fuzzy-link link info)
2402 (org-export-resolve-id-link link info))))
2403 (case (org-element-type destination)
2404 ;; Id link points to an external file.
2405 (plain-text
2406 (if desc (format "\\href{%s}{%s}" destination desc)
2407 (format "\\url{%s}" destination)))
2408 ;; Fuzzy link points nowhere.
2409 ((nil)
2410 (format (plist-get info :latex-link-with-unknown-path-format)
2411 (or desc
2412 (org-export-data
2413 (org-element-property :raw-link link) info))))
2414 ;; LINK points to a headline. If headlines are numbered
2415 ;; and the link has no description, display headline's
2416 ;; number. Otherwise, display description or headline's
2417 ;; title.
2418 (headline
2419 (let ((label (org-latex--label destination info t)))
2420 (if (and (not desc)
2421 (org-export-numbered-headline-p destination info))
2422 (format "\\ref{%s}" label)
2423 (format "\\hyperref[%s]{%s}" label
2424 (or desc
2425 (org-export-data
2426 (org-element-property :title destination) info))))))
2427 ;; Fuzzy link points to a target. Do as above.
2428 (otherwise
2429 (let ((ref (org-latex--label destination info t)))
2430 (if (not desc) (format "\\ref{%s}" ref)
2431 (format "\\hyperref[%s]{%s}" ref desc)))))))
2432 ;; Coderef: replace link with the reference name or the
2433 ;; equivalent line number.
2434 ((string= type "coderef")
2435 (format (org-export-get-coderef-format path desc)
2436 (org-export-resolve-coderef path info)))
2437 ;; External link with a description part.
2438 ((and path desc) (format "\\href{%s}{%s}" path desc))
2439 ;; External link without a description part.
2440 (path (format "\\url{%s}" path))
2441 ;; No path, only description. Try to do something useful.
2442 (t (format (plist-get info :latex-link-with-unknown-path-format) desc)))))
2445 ;;;; Node Property
2447 (defun org-latex-node-property (node-property _contents _info)
2448 "Transcode a NODE-PROPERTY element from Org to LaTeX.
2449 CONTENTS is nil. INFO is a plist holding contextual
2450 information."
2451 (format "%s:%s"
2452 (org-element-property :key node-property)
2453 (let ((value (org-element-property :value node-property)))
2454 (if value (concat " " value) ""))))
2457 ;;;; Paragraph
2459 (defun org-latex-paragraph (_paragraph contents _info)
2460 "Transcode a PARAGRAPH element from Org to LaTeX.
2461 CONTENTS is the contents of the paragraph, as a string. INFO is
2462 the plist used as a communication channel."
2463 contents)
2466 ;;;; Plain List
2468 (defun org-latex-plain-list (plain-list contents info)
2469 "Transcode a PLAIN-LIST element from Org to LaTeX.
2470 CONTENTS is the contents of the list. INFO is a plist holding
2471 contextual information."
2472 (let* ((type (org-element-property :type plain-list))
2473 (attr (org-export-read-attribute :attr_latex plain-list))
2474 (latex-type (let ((env (plist-get attr :environment)))
2475 (cond (env (format "%s" env))
2476 ((eq type 'ordered) "enumerate")
2477 ((eq type 'descriptive) "description")
2478 (t "itemize")))))
2479 (org-latex--wrap-label
2480 plain-list
2481 (format "\\begin{%s}%s\n%s\\end{%s}"
2482 latex-type
2483 (or (plist-get attr :options) "")
2484 contents
2485 latex-type)
2486 info)))
2489 ;;;; Plain Text
2491 (defun org-latex-plain-text (text info)
2492 "Transcode a TEXT string from Org to LaTeX.
2493 TEXT is the string to transcode. INFO is a plist holding
2494 contextual information."
2495 (let* ((specialp (plist-get info :with-special-strings))
2496 (output
2497 ;; Turn LaTeX into \LaTeX{} and TeX into \TeX{}.
2498 (let ((case-fold-search nil))
2499 (replace-regexp-in-string
2500 "\\<\\(?:La\\)?TeX\\>" "\\\\\\&{}"
2501 ;; Protect ^, ~, %, #, &, $, _, { and }. Also protect \.
2502 ;; However, if special strings are used, be careful not
2503 ;; to protect "\" in "\-" constructs.
2504 (replace-regexp-in-string
2505 (concat "[%$#&{}_~^]\\|\\\\" (and specialp "\\([^-]\\|$\\)"))
2506 (lambda (m)
2507 (case (string-to-char m)
2508 (?\\ "$\\\\backslash$\\1")
2509 (?~ "\\\\textasciitilde{}")
2510 (?^ "\\\\^{}")
2511 (t "\\\\\\&")))
2512 text)))))
2513 ;; Activate smart quotes. Be sure to provide original TEXT string
2514 ;; since OUTPUT may have been modified.
2515 (when (plist-get info :with-smart-quotes)
2516 (setq output (org-export-activate-smart-quotes output :latex info text)))
2517 ;; Convert special strings.
2518 (when specialp
2519 (setq output (replace-regexp-in-string "\\.\\.\\." "\\\\ldots{}" output)))
2520 ;; Handle break preservation if required.
2521 (when (plist-get info :preserve-breaks)
2522 (setq output (replace-regexp-in-string
2523 "\\(?:[ \t]*\\\\\\\\\\)?[ \t]*\n" "\\\\\n" output nil t)))
2524 ;; Return value.
2525 output))
2528 ;;;; Planning
2530 (defun org-latex-planning (planning _contents info)
2531 "Transcode a PLANNING element from Org to LaTeX.
2532 CONTENTS is nil. INFO is a plist holding contextual
2533 information."
2534 (concat
2535 "\\noindent"
2536 (mapconcat
2537 'identity
2538 (delq nil
2539 (list
2540 (let ((closed (org-element-property :closed planning)))
2541 (when closed
2542 (concat
2543 (format "\\textbf{%s} " org-closed-string)
2544 (format (plist-get info :latex-inactive-timestamp-format)
2545 (org-timestamp-translate closed)))))
2546 (let ((deadline (org-element-property :deadline planning)))
2547 (when deadline
2548 (concat
2549 (format "\\textbf{%s} " org-deadline-string)
2550 (format (plist-get info :latex-active-timestamp-format)
2551 (org-timestamp-translate deadline)))))
2552 (let ((scheduled (org-element-property :scheduled planning)))
2553 (when scheduled
2554 (concat
2555 (format "\\textbf{%s} " org-scheduled-string)
2556 (format (plist-get info :latex-active-timestamp-format)
2557 (org-timestamp-translate scheduled)))))))
2558 " ")
2559 "\\\\"))
2562 ;;;; Property Drawer
2564 (defun org-latex-property-drawer (_property-drawer contents _info)
2565 "Transcode a PROPERTY-DRAWER element from Org to LaTeX.
2566 CONTENTS holds the contents of the drawer. INFO is a plist
2567 holding contextual information."
2568 (and (org-string-nw-p contents)
2569 (format "\\begin{verbatim}\n%s\\end{verbatim}" contents)))
2572 ;;;; Pseudo Element: LaTeX Matrices
2574 ;; `latex-matrices' elements have the following properties:
2575 ;; `:caption', `:post-blank' and `:markup' (`inline', `equation' or
2576 ;; `math').
2578 (defun org-latex--wrap-latex-matrices (data info)
2579 "Merge contiguous tables with the same mode within a pseudo-element.
2580 DATA is a parse tree or a secondary string. INFO is a plist
2581 containing export options. Modify DATA by side-effect and return
2582 it."
2583 (org-element-map data 'table
2584 (lambda (table)
2585 (when (eq (org-element-property :type table) 'org)
2586 (let ((mode (or (org-export-read-attribute :attr_latex table :mode)
2587 (plist-get info :latex-default-table-mode))))
2588 (when (and (member mode '("inline-math" "math"))
2589 ;; Do not wrap twice the same table.
2590 (not (eq (org-element-type
2591 (org-element-property :parent table))
2592 'latex-matrices)))
2593 (let* ((caption (and (not (string= mode "inline-math"))
2594 (org-element-property :caption table)))
2595 (matrices
2596 (list 'latex-matrices
2597 (list :caption caption
2598 :markup
2599 (cond ((string= mode "inline-math") 'inline)
2600 (caption 'equation)
2601 (t 'math)))))
2602 (previous table)
2603 (next (org-export-get-next-element table info)))
2604 (org-element-insert-before matrices table)
2605 ;; Swallow all contiguous tables sharing the same mode.
2606 (while (and
2607 (zerop (or (org-element-property :post-blank previous) 0))
2608 (setq next (org-export-get-next-element previous info))
2609 (eq (org-element-type next) 'table)
2610 (eq (org-element-property :type next) 'org)
2611 (string= (or (org-export-read-attribute
2612 :attr_latex next :mode)
2613 (plist-get info :latex-default-table-mode))
2614 mode))
2615 (org-element-extract-element previous)
2616 (org-element-adopt-elements matrices previous)
2617 (setq previous next))
2618 (org-element-put-property
2619 matrices :post-blank (org-element-property :post-blank previous))
2620 (org-element-extract-element previous)
2621 (org-element-adopt-elements matrices previous))))))
2622 info)
2623 data)
2625 (defun org-latex-matrices (matrices contents _info)
2626 "Transcode a MATRICES element from Org to LaTeX.
2627 CONTENTS is a string. INFO is a plist used as a communication
2628 channel."
2629 (format (case (org-element-property :markup matrices)
2630 (inline "\\(%s\\)")
2631 (equation "\\begin{equation}\n%s\\end{equation}")
2632 (t "\\[\n%s\\]"))
2633 contents))
2635 (defun org-latex-matrices-tree-filter (tree _backend info)
2636 (org-latex--wrap-latex-matrices tree info))
2638 ;;;; Pseudo Object: LaTeX Math Block
2640 ;; `latex-math-block' objects have the following property:
2641 ;; `:post-blank'.
2643 (defun org-latex--wrap-latex-math-block (data info)
2644 "Merge contiguous math objects in a pseudo-object container.
2645 DATA is a parse tree or a secondary string. INFO is a plist
2646 containing export options. Modify DATA by side-effect and return it."
2647 (let ((valid-object-p
2648 ;; Non-nil when OBJ can be added to the latex math block.
2649 (lambda (obj)
2650 (pcase (org-element-type obj)
2651 (`entity (org-element-property :latex-math-p obj))
2652 (`latex-fragment
2653 (let ((value (org-element-property :value obj)))
2654 (or (string-prefix-p "\\(" value)
2655 (string-match-p "\\`\\$[^$]" value))))
2656 ((or `subscript `superscript) t)))))
2657 (org-element-map data '(entity latex-fragment subscript superscript)
2658 (lambda (object)
2659 ;; Skip objects already wrapped.
2660 (when (and (not (eq (org-element-type
2661 (org-element-property :parent object))
2662 'latex-math-block))
2663 (funcall valid-object-p object))
2664 (let ((math-block (list 'latex-math-block nil))
2665 (next-elements (org-export-get-next-element object info t))
2666 (last object))
2667 ;; Wrap MATH-BLOCK around OBJECT in DATA.
2668 (org-element-insert-before math-block object)
2669 (org-element-extract-element object)
2670 (org-element-adopt-elements math-block object)
2671 (when (zerop (or (org-element-property :post-blank object) 0))
2672 ;; MATH-BLOCK swallows consecutive math objects.
2673 (catch 'exit
2674 (dolist (next next-elements)
2675 (if (not (funcall valid-object-p next)) (throw 'exit nil)
2676 (org-element-extract-element next)
2677 (org-element-adopt-elements math-block next)
2678 ;; Eschew the case: \beta$x$ -> \(\betax\).
2679 (unless (memq (org-element-type next)
2680 '(subscript superscript))
2681 (org-element-put-property last :post-blank 1))
2682 (setq last next)
2683 (when (> (or (org-element-property :post-blank next) 0) 0)
2684 (throw 'exit nil))))))
2685 (org-element-put-property
2686 math-block :post-blank (org-element-property :post-blank last)))))
2687 info nil '(subscript superscript latex-math-block) t)
2688 ;; Return updated DATA.
2689 data))
2691 (defun org-latex-math-block-tree-filter (tree _backend info)
2692 (org-latex--wrap-latex-math-block tree info))
2694 (defun org-latex-math-block-options-filter (info _backend)
2695 (dolist (prop '(:author :date :title) info)
2696 (plist-put info prop
2697 (org-latex--wrap-latex-math-block (plist-get info prop) info))))
2699 (defun org-latex-math-block (_math-block contents _info)
2700 "Transcode a MATH-BLOCK object from Org to LaTeX.
2701 CONTENTS is a string. INFO is a plist used as a communication
2702 channel."
2703 (when (org-string-nw-p contents)
2704 (format "\\(%s\\)" (org-trim contents))))
2706 ;;;; Quote Block
2708 (defun org-latex-quote-block (quote-block contents info)
2709 "Transcode a QUOTE-BLOCK element from Org to LaTeX.
2710 CONTENTS holds the contents of the block. INFO is a plist
2711 holding contextual information."
2712 (org-latex--wrap-label
2713 quote-block (format "\\begin{quote}\n%s\\end{quote}" contents) info))
2716 ;;;; Radio Target
2718 (defun org-latex-radio-target (radio-target text info)
2719 "Transcode a RADIO-TARGET object from Org to LaTeX.
2720 TEXT is the text of the target. INFO is a plist holding
2721 contextual information."
2722 (format "\\label{%s}%s" (org-export-get-reference radio-target info) text))
2725 ;;;; Section
2727 (defun org-latex-section (_section contents _info)
2728 "Transcode a SECTION element from Org to LaTeX.
2729 CONTENTS holds the contents of the section. INFO is a plist
2730 holding contextual information."
2731 contents)
2734 ;;;; Special Block
2736 (defun org-latex-special-block (special-block contents info)
2737 "Transcode a SPECIAL-BLOCK element from Org to LaTeX.
2738 CONTENTS holds the contents of the block. INFO is a plist
2739 holding contextual information."
2740 (let ((type (org-element-property :type special-block))
2741 (opt (org-export-read-attribute :attr_latex special-block :options))
2742 (caption (org-latex--caption/label-string special-block info))
2743 (caption-above-p (org-latex--caption-above-p special-block info)))
2744 (concat (format "\\begin{%s}%s\n" type (or opt ""))
2745 (and caption-above-p caption)
2746 contents
2747 (and (not caption-above-p) caption)
2748 (format "\\end{%s}" type))))
2751 ;;;; Src Block
2753 (defun org-latex-src-block (src-block _contents info)
2754 "Transcode a SRC-BLOCK element from Org to LaTeX.
2755 CONTENTS holds the contents of the item. INFO is a plist holding
2756 contextual information."
2757 (when (org-string-nw-p (org-element-property :value src-block))
2758 (let* ((lang (org-element-property :language src-block))
2759 (caption (org-element-property :caption src-block))
2760 (caption-above-p (org-latex--caption-above-p src-block info))
2761 (label (org-element-property :name src-block))
2762 (custom-env (and lang
2763 (cadr (assq (intern lang)
2764 org-latex-custom-lang-environments))))
2765 (num-start (case (org-element-property :number-lines src-block)
2766 (continued (org-export-get-loc src-block info))
2767 (new 0)))
2768 (retain-labels (org-element-property :retain-labels src-block))
2769 (attributes (org-export-read-attribute :attr_latex src-block))
2770 (float (plist-get attributes :float))
2771 (listings (plist-get info :latex-listings)))
2772 (cond
2773 ;; Case 1. No source fontification.
2774 ((not listings)
2775 (let* ((caption-str (org-latex--caption/label-string src-block info))
2776 (float-env
2777 (cond ((string= "multicolumn" float)
2778 (format "\\begin{figure*}[%s]\n%s%%s\n%s\\end{figure*}"
2779 (plist-get info :latex-default-figure-position)
2780 (if caption-above-p caption-str "")
2781 (if caption-above-p "" caption-str)))
2782 (caption (concat
2783 (if caption-above-p caption-str "")
2784 "%s"
2785 (if caption-above-p "" (concat "\n" caption-str))))
2786 (t "%s"))))
2787 (format
2788 float-env
2789 (concat (format "\\begin{verbatim}\n%s\\end{verbatim}"
2790 (org-export-format-code-default src-block info))))))
2791 ;; Case 2. Custom environment.
2792 (custom-env
2793 (let ((caption-str (org-latex--caption/label-string src-block info))
2794 (formatted-src (org-export-format-code-default src-block info)))
2795 (if (org-string-match-p "\\`[a-zA-Z0-9]+\\'" custom-env)
2796 (format "\\begin{%s}\n%s\\end{%s}\n"
2797 custom-env
2798 (concat (and caption-above-p caption-str)
2799 formatted-src
2800 (and (not caption-above-p) caption-str))
2801 custom-env)
2802 (format-spec custom-env
2803 `((?s . ,formatted-src)
2804 (?c . ,caption)
2805 (?f . ,float)
2806 (?l . ,(org-latex--label src-block info))
2807 (?o . ,(or (plist-get attributes :options) "")))))))
2808 ;; Case 3. Use minted package.
2809 ((eq listings 'minted)
2810 (let* ((caption-str (org-latex--caption/label-string src-block info))
2811 (float-env
2812 (cond
2813 ((string= "multicolumn" float)
2814 (format "\\begin{listing*}\n%s%%s\n%s\\end{listing*}"
2815 (if caption-above-p caption-str "")
2816 (if caption-above-p "" caption-str)))
2817 (caption
2818 (concat (if caption-above-p caption-str "")
2819 "%s"
2820 (if caption-above-p "" (concat "\n" caption-str))))
2821 (t "%s")))
2822 (options (plist-get info :latex-minted-options))
2823 (body
2824 (format
2825 "\\begin{minted}[%s]{%s}\n%s\\end{minted}"
2826 ;; Options.
2827 (concat
2828 (org-latex--make-option-string
2829 (if (or (not num-start) (assoc "linenos" options))
2830 options
2831 (append
2832 `(("linenos")
2833 ("firstnumber" ,(number-to-string (1+ num-start))))
2834 options)))
2835 (let ((local-options (plist-get attributes :options)))
2836 (and local-options (concat "," local-options))))
2837 ;; Language.
2838 (or (cadr (assq (intern lang)
2839 (plist-get info :latex-minted-langs)))
2840 (downcase lang))
2841 ;; Source code.
2842 (let* ((code-info (org-export-unravel-code src-block))
2843 (max-width
2844 (apply 'max
2845 (mapcar 'length
2846 (org-split-string (car code-info)
2847 "\n")))))
2848 (org-export-format-code
2849 (car code-info)
2850 (lambda (loc _num ref)
2851 (concat
2853 (when ref
2854 ;; Ensure references are flushed to the right,
2855 ;; separated with 6 spaces from the widest line
2856 ;; of code.
2857 (concat (make-string (+ (- max-width (length loc)) 6)
2858 ?\s)
2859 (format "(%s)" ref)))))
2860 nil (and retain-labels (cdr code-info)))))))
2861 ;; Return value.
2862 (format float-env body)))
2863 ;; Case 4. Use listings package.
2865 (let ((lst-lang
2866 (or (cadr (assq (intern lang)
2867 (plist-get info :latex-listings-langs)))
2868 lang))
2869 (caption-str
2870 (when caption
2871 (let ((main (org-export-get-caption src-block))
2872 (secondary (org-export-get-caption src-block t)))
2873 (if (not secondary)
2874 (format "{%s}" (org-export-data main info))
2875 (format "{[%s]%s}"
2876 (org-export-data secondary info)
2877 (org-export-data main info))))))
2878 (lst-opt (plist-get info :latex-listings-options)))
2879 (concat
2880 ;; Options.
2881 (format
2882 "\\lstset{%s}\n"
2883 (concat
2884 (org-latex--make-option-string
2885 (append
2886 lst-opt
2887 (cond
2888 ((and (not float) (plist-member attributes :float)) nil)
2889 ((string= "multicolumn" float) '(("float" "*")))
2890 ((and float (not (assoc "float" lst-opt)))
2891 `(("float" ,(plist-get info :latex-default-figure-position)))))
2892 `(("language" ,lst-lang))
2893 (if label `(("label" ,label)) '(("label" " ")))
2894 (if caption-str `(("caption" ,caption-str)) '(("caption" " ")))
2895 `(("captionpos" ,(if caption-above-p "t" "b")))
2896 (cond ((assoc "numbers" lst-opt) nil)
2897 ((not num-start) '(("numbers" "none")))
2898 (t `(("firstnumber" ,(number-to-string (1+ num-start)))
2899 ("numbers" "left"))))))
2900 (let ((local-options (plist-get attributes :options)))
2901 (and local-options (concat "," local-options)))))
2902 ;; Source code.
2903 (format
2904 "\\begin{lstlisting}\n%s\\end{lstlisting}"
2905 (let* ((code-info (org-export-unravel-code src-block))
2906 (max-width
2907 (apply 'max
2908 (mapcar 'length
2909 (org-split-string (car code-info) "\n")))))
2910 (org-export-format-code
2911 (car code-info)
2912 (lambda (loc _num ref)
2913 (concat
2915 (when ref
2916 ;; Ensure references are flushed to the right,
2917 ;; separated with 6 spaces from the widest line of
2918 ;; code
2919 (concat (make-string (+ (- max-width (length loc)) 6) ?\s)
2920 (format "(%s)" ref)))))
2921 nil (and retain-labels (cdr code-info))))))))))))
2924 ;;;; Statistics Cookie
2926 (defun org-latex-statistics-cookie (statistics-cookie _contents _info)
2927 "Transcode a STATISTICS-COOKIE object from Org to LaTeX.
2928 CONTENTS is nil. INFO is a plist holding contextual information."
2929 (replace-regexp-in-string
2930 "%" "\\%" (org-element-property :value statistics-cookie) nil t))
2933 ;;;; Strike-Through
2935 (defun org-latex-strike-through (_strike-through contents info)
2936 "Transcode STRIKE-THROUGH from Org to LaTeX.
2937 CONTENTS is the text with strike-through markup. INFO is a plist
2938 holding contextual information."
2939 (org-latex--text-markup contents 'strike-through info))
2942 ;;;; Subscript
2944 (defun org-latex--script-size (object info)
2945 "Transcode a subscript or superscript object.
2946 OBJECT is an Org object. INFO is a plist used as a communication
2947 channel."
2948 (let ((output ""))
2949 (org-element-map (org-element-contents object)
2950 (cons 'plain-text org-element-all-objects)
2951 (lambda (obj)
2952 (case (org-element-type obj)
2953 ((entity latex-fragment)
2954 (let ((data (org-trim (org-export-data obj info))))
2955 (string-match
2956 "\\`\\(?:\\\\[([]\\|\\$+\\)?\\(.*?\\)\\(?:\\\\[])]\\|\\$+\\)?\\'"
2957 data)
2958 (setq output
2959 (concat output
2960 (match-string 1 data)
2961 (let ((blank (org-element-property :post-blank obj)))
2962 (and blank (> blank 0) "\\ "))))))
2963 (plain-text
2964 (setq output
2965 (format "%s\\text{%s}" output (org-export-data obj info))))
2966 (otherwise
2967 (setq output
2968 (concat output
2969 (org-export-data obj info)
2970 (let ((blank (org-element-property :post-blank obj)))
2971 (and blank (> blank 0) "\\ ")))))))
2972 info nil org-element-recursive-objects)
2973 ;; Result. Do not wrap into curly brackets if OUTPUT is a single
2974 ;; character.
2975 (concat (if (eq (org-element-type object) 'subscript) "_" "^")
2976 (and (> (length output) 1) "{")
2977 output
2978 (and (> (length output) 1) "}"))))
2980 (defun org-latex-subscript (subscript _contents info)
2981 "Transcode a SUBSCRIPT object from Org to LaTeX.
2982 CONTENTS is the contents of the object. INFO is a plist holding
2983 contextual information."
2984 (org-latex--script-size subscript info))
2987 ;;;; Superscript
2989 (defun org-latex-superscript (superscript _contents info)
2990 "Transcode a SUPERSCRIPT object from Org to LaTeX.
2991 CONTENTS is the contents of the object. INFO is a plist holding
2992 contextual information."
2993 (org-latex--script-size superscript info))
2996 ;;;; Table
2998 ;; `org-latex-table' is the entry point for table transcoding. It
2999 ;; takes care of tables with a "verbatim" mode. Otherwise, it
3000 ;; delegates the job to either `org-latex--table.el-table',
3001 ;; `org-latex--org-table' or `org-latex--math-table' functions,
3002 ;; depending of the type of the table and the mode requested.
3004 ;; `org-latex--align-string' is a subroutine used to build alignment
3005 ;; string for Org tables.
3007 (defun org-latex-table (table contents info)
3008 "Transcode a TABLE element from Org to LaTeX.
3009 CONTENTS is the contents of the table. INFO is a plist holding
3010 contextual information."
3011 (if (eq (org-element-property :type table) 'table.el)
3012 ;; "table.el" table. Convert it using appropriate tools.
3013 (org-latex--table.el-table table info)
3014 (let ((type (or (org-export-read-attribute :attr_latex table :mode)
3015 (plist-get info :latex-default-table-mode))))
3016 (cond
3017 ;; Case 1: Verbatim table.
3018 ((string= type "verbatim")
3019 (format "\\begin{verbatim}\n%s\n\\end{verbatim}"
3020 ;; Re-create table, without affiliated keywords.
3021 (org-trim (org-element-interpret-data
3022 `(table nil ,@(org-element-contents table))))))
3023 ;; Case 2: Matrix.
3024 ((or (string= type "math") (string= type "inline-math"))
3025 (org-latex--math-table table info))
3026 ;; Case 3: Standard table.
3027 (t (concat (org-latex--org-table table contents info)
3028 ;; When there are footnote references within the
3029 ;; table, insert their definition just after it.
3030 (org-latex--delayed-footnotes-definitions table info)))))))
3032 (defun org-latex--align-string (table info)
3033 "Return an appropriate LaTeX alignment string.
3034 TABLE is the considered table. INFO is a plist used as
3035 a communication channel."
3036 (or (org-export-read-attribute :attr_latex table :align)
3037 (let (align)
3038 ;; Extract column groups and alignment from first (non-rule)
3039 ;; row.
3040 (org-element-map
3041 (org-element-map table 'table-row
3042 (lambda (row)
3043 (and (eq (org-element-property :type row) 'standard) row))
3044 info 'first-match)
3045 'table-cell
3046 (lambda (cell)
3047 (let ((borders (org-export-table-cell-borders cell info)))
3048 ;; Check left border for the first cell only.
3049 (when (and (memq 'left borders) (not align))
3050 (push "|" align))
3051 (push (case (org-export-table-cell-alignment cell info)
3052 (left "l")
3053 (right "r")
3054 (center "c"))
3055 align)
3056 (when (memq 'right borders) (push "|" align))))
3057 info)
3058 (apply 'concat (nreverse align)))))
3060 (defun org-latex--org-table (table contents info)
3061 "Return appropriate LaTeX code for an Org table.
3063 TABLE is the table type element to transcode. CONTENTS is its
3064 contents, as a string. INFO is a plist used as a communication
3065 channel.
3067 This function assumes TABLE has `org' as its `:type' property and
3068 `table' as its `:mode' attribute."
3069 (let* ((caption (org-latex--caption/label-string table info))
3070 (attr (org-export-read-attribute :attr_latex table))
3071 ;; Determine alignment string.
3072 (alignment (org-latex--align-string table info))
3073 ;; Determine environment for the table: longtable, tabular...
3074 (table-env (or (plist-get attr :environment)
3075 (plist-get info :latex-default-table-environment)))
3076 ;; If table is a float, determine environment: table, table*
3077 ;; or sidewaystable.
3078 (float-env (unless (member table-env '("longtable" "longtabu"))
3079 (let ((float (plist-get attr :float)))
3080 (cond
3081 ((and (not float) (plist-member attr :float)) nil)
3082 ((or (string= float "sidewaystable")
3083 (string= float "sideways")) "sidewaystable")
3084 ((string= float "multicolumn") "table*")
3085 ((or float
3086 (org-element-property :caption table)
3087 (org-string-nw-p (plist-get attr :caption)))
3088 "table")))))
3089 ;; Extract others display options.
3090 (fontsize (let ((font (plist-get attr :font)))
3091 (and font (concat font "\n"))))
3092 ;; "tabular" environment doesn't allow to define a width.
3093 (width (and (not (equal table-env "tabular")) (plist-get attr :width)))
3094 (spreadp (plist-get attr :spread))
3095 (placement
3096 (or (plist-get attr :placement)
3097 (format "[%s]" (plist-get info :latex-default-figure-position))))
3098 (centerp (if (plist-member attr :center) (plist-get attr :center)
3099 (plist-get info :latex-tables-centered)))
3100 (caption-above-p (org-latex--caption-above-p table info)))
3101 ;; Prepare the final format string for the table.
3102 (cond
3103 ;; Longtable.
3104 ((equal "longtable" table-env)
3105 (concat (and fontsize (concat "{" fontsize))
3106 (format "\\begin{longtable}{%s}\n" alignment)
3107 (and caption-above-p
3108 (org-string-nw-p caption)
3109 (concat caption "\\\\\n"))
3110 contents
3111 (and (not caption-above-p)
3112 (org-string-nw-p caption)
3113 (concat caption "\\\\\n"))
3114 "\\end{longtable}\n"
3115 (and fontsize "}")))
3116 ;; Longtabu
3117 ((equal "longtabu" table-env)
3118 (concat (and fontsize (concat "{" fontsize))
3119 (format "\\begin{longtabu}%s{%s}\n"
3120 (if width
3121 (format " %s %s "
3122 (if spreadp "spread" "to") width) "")
3123 alignment)
3124 (and caption-above-p
3125 (org-string-nw-p caption)
3126 (concat caption "\\\\\n"))
3127 contents
3128 (and (not caption-above-p)
3129 (org-string-nw-p caption)
3130 (concat caption "\\\\\n"))
3131 "\\end{longtabu}\n"
3132 (and fontsize "}")))
3133 ;; Others.
3134 (t (concat (cond
3135 (float-env
3136 (concat (format "\\begin{%s}%s\n" float-env placement)
3137 (if caption-above-p caption "")
3138 (when centerp "\\centering\n")
3139 fontsize))
3140 ((and (not float-env) caption)
3141 (concat
3142 (and centerp "\\begin{center}\n" )
3143 (if caption-above-p caption "")
3144 (cond ((and fontsize centerp) fontsize)
3145 (fontsize (concat "{" fontsize)))))
3146 (centerp (concat "\\begin{center}\n" fontsize))
3147 (fontsize (concat "{" fontsize)))
3148 (cond ((equal "tabu" table-env)
3149 (format "\\begin{tabu}%s{%s}\n%s\\end{tabu}"
3150 (if width (format
3151 (if spreadp " spread %s " " to %s ")
3152 width) "")
3153 alignment
3154 contents))
3155 (t (format "\\begin{%s}%s{%s}\n%s\\end{%s}"
3156 table-env
3157 (if width (format "{%s}" width) "")
3158 alignment
3159 contents
3160 table-env)))
3161 (cond
3162 (float-env
3163 (concat (if caption-above-p "" (concat "\n" caption))
3164 (format "\n\\end{%s}" float-env)))
3165 ((and (not float-env) caption)
3166 (concat
3167 (if caption-above-p "" (concat "\n" caption))
3168 (and centerp "\n\\end{center}")
3169 (and fontsize (not centerp) "}")))
3170 (centerp "\n\\end{center}")
3171 (fontsize "}")))))))
3173 (defun org-latex--table.el-table (table info)
3174 "Return appropriate LaTeX code for a table.el table.
3176 TABLE is the table type element to transcode. INFO is a plist
3177 used as a communication channel.
3179 This function assumes TABLE has `table.el' as its `:type'
3180 property."
3181 (require 'table)
3182 ;; Ensure "*org-export-table*" buffer is empty.
3183 (with-current-buffer (get-buffer-create "*org-export-table*")
3184 (erase-buffer))
3185 (let ((output (with-temp-buffer
3186 (insert (org-element-property :value table))
3187 (goto-char 1)
3188 (re-search-forward "^[ \t]*|[^|]" nil t)
3189 (table-generate-source 'latex "*org-export-table*")
3190 (with-current-buffer "*org-export-table*"
3191 (org-trim (buffer-string))))))
3192 (kill-buffer (get-buffer "*org-export-table*"))
3193 ;; Remove left out comments.
3194 (while (string-match "^%.*\n" output)
3195 (setq output (replace-match "" t t output)))
3196 (let ((attr (org-export-read-attribute :attr_latex table)))
3197 (when (plist-get attr :rmlines)
3198 ;; When the "rmlines" attribute is provided, remove all hlines
3199 ;; but the the one separating heading from the table body.
3200 (let ((n 0) (pos 0))
3201 (while (and (< (length output) pos)
3202 (setq pos (string-match "^\\\\hline\n?" output pos)))
3203 (incf n)
3204 (unless (= n 2) (setq output (replace-match "" nil nil output))))))
3205 (let ((centerp (if (plist-member attr :center) (plist-get attr :center)
3206 (plist-get info :latex-tables-centered))))
3207 (if (not centerp) output
3208 (format "\\begin{center}\n%s\n\\end{center}" output))))))
3210 (defun org-latex--math-table (table info)
3211 "Return appropriate LaTeX code for a matrix.
3213 TABLE is the table type element to transcode. INFO is a plist
3214 used as a communication channel.
3216 This function assumes TABLE has `org' as its `:type' property and
3217 `inline-math' or `math' as its `:mode' attribute."
3218 (let* ((attr (org-export-read-attribute :attr_latex table))
3219 (env (or (plist-get attr :environment)
3220 (plist-get info :latex-default-table-environment)))
3221 (contents
3222 (mapconcat
3223 (lambda (row)
3224 ;; Ignore horizontal rules.
3225 (when (eq (org-element-property :type row) 'standard)
3226 ;; Return each cell unmodified.
3227 (concat
3228 (mapconcat
3229 (lambda (cell)
3230 (substring (org-element-interpret-data cell) 0 -1))
3231 (org-element-map row 'table-cell #'identity info) "&")
3232 (or (cdr (assoc env org-latex-table-matrix-macros)) "\\\\")
3233 "\n")))
3234 (org-element-map table 'table-row #'identity info) "")))
3235 (concat
3236 ;; Prefix.
3237 (plist-get attr :math-prefix)
3238 ;; Environment. Also treat special cases.
3239 (cond ((member env '("array" "tabular"))
3240 (let ((align (make-string
3241 (cdr (org-export-table-dimensions table info)) ?c)))
3242 (format "\\begin{%s}{%s}\n%s\\end{%s}" env align contents env)))
3243 ((assoc env org-latex-table-matrix-macros)
3244 (format "\\%s%s{\n%s}"
3246 (or (plist-get attr :math-arguments) "")
3247 contents))
3248 (t (format "\\begin{%s}\n%s\\end{%s}" env contents env)))
3249 ;; Suffix.
3250 (plist-get attr :math-suffix))))
3253 ;;;; Table Cell
3255 (defun org-latex-table-cell (table-cell contents info)
3256 "Transcode a TABLE-CELL element from Org to LaTeX.
3257 CONTENTS is the cell contents. INFO is a plist used as
3258 a communication channel."
3259 (concat
3260 (let ((scientific-format (plist-get info :latex-table-scientific-notation)))
3261 (if (and contents
3262 scientific-format
3263 (string-match orgtbl-exp-regexp contents))
3264 ;; Use appropriate format string for scientific
3265 ;; notation.
3266 (format scientific-format
3267 (match-string 1 contents)
3268 (match-string 2 contents))
3269 contents))
3270 (when (org-export-get-next-element table-cell info) " & ")))
3273 ;;;; Table Row
3275 (defun org-latex-table-row (table-row contents info)
3276 "Transcode a TABLE-ROW element from Org to LaTeX.
3277 CONTENTS is the contents of the row. INFO is a plist used as
3278 a communication channel."
3279 (let* ((attr (org-export-read-attribute :attr_latex
3280 (org-export-get-parent table-row)))
3281 (booktabsp (if (plist-member attr :booktabs) (plist-get attr :booktabs)
3282 (plist-get info :latex-tables-booktabs)))
3283 (longtablep
3284 (member (or (plist-get attr :environment)
3285 (plist-get info :latex-default-table-environment))
3286 '("longtable" "longtabu"))))
3287 (if (eq (org-element-property :type table-row) 'rule)
3288 (cond
3289 ((not booktabsp) "\\hline")
3290 ((not (org-export-get-previous-element table-row info)) "\\toprule")
3291 ((not (org-export-get-next-element table-row info)) "\\bottomrule")
3292 ((and longtablep
3293 (org-export-table-row-ends-header-p
3294 (org-export-get-previous-element table-row info) info))
3296 (t "\\midrule"))
3297 (concat
3298 ;; When BOOKTABS are activated enforce top-rule even when no
3299 ;; hline was specifically marked.
3300 (and booktabsp (not (org-export-get-previous-element table-row info))
3301 "\\toprule\n")
3302 contents "\\\\\n"
3303 (cond
3304 ;; Special case for long tables. Define header and footers.
3305 ((and longtablep (org-export-table-row-ends-header-p table-row info))
3306 (let ((columns (cdr (org-export-table-dimensions
3307 (org-export-get-parent-table table-row) info))))
3308 (format "%s
3309 \\endfirsthead
3310 \\multicolumn{%d}{l}{%s} \\\\
3312 %s \\\\\n
3314 \\endhead
3315 %s\\multicolumn{%d}{r}{%s} \\\\
3316 \\endfoot
3317 \\endlastfoot"
3318 (if booktabsp "\\midrule" "\\hline")
3319 columns
3320 (org-latex--translate "Continued from previous page" info)
3321 (cond
3322 ((not (org-export-table-row-starts-header-p table-row info))
3324 (booktabsp "\\toprule\n")
3325 (t "\\hline\n"))
3326 contents
3327 (if booktabsp "\\midrule" "\\hline")
3328 (if booktabsp "\\midrule" "\\hline")
3329 columns
3330 (org-latex--translate "Continued on next page" info))))
3331 ;; When BOOKTABS are activated enforce bottom rule even when
3332 ;; no hline was specifically marked.
3333 ((and booktabsp (not (org-export-get-next-element table-row info)))
3334 "\\bottomrule"))))))
3337 ;;;; Target
3339 (defun org-latex-target (target _contents info)
3340 "Transcode a TARGET object from Org to LaTeX.
3341 CONTENTS is nil. INFO is a plist holding contextual
3342 information."
3343 (format "\\label{%s}" (org-latex--label target info)))
3346 ;;;; Timestamp
3348 (defun org-latex-timestamp (timestamp _contents info)
3349 "Transcode a TIMESTAMP object from Org to LaTeX.
3350 CONTENTS is nil. INFO is a plist holding contextual
3351 information."
3352 (let ((value (org-latex-plain-text (org-timestamp-translate timestamp) info)))
3353 (format
3354 (plist-get info
3355 (case (org-element-property :type timestamp)
3356 ((active active-range) :latex-active-timestamp-format)
3357 ((inactive inactive-range) :latex-inactive-timestamp-format)
3358 (otherwise :latex-diary-timestamp-format)))
3359 value)))
3362 ;;;; Underline
3364 (defun org-latex-underline (_underline contents info)
3365 "Transcode UNDERLINE from Org to LaTeX.
3366 CONTENTS is the text with underline markup. INFO is a plist
3367 holding contextual information."
3368 (org-latex--text-markup contents 'underline info))
3371 ;;;; Verbatim
3373 (defun org-latex-verbatim (verbatim _contents info)
3374 "Transcode a VERBATIM object from Org to LaTeX.
3375 CONTENTS is nil. INFO is a plist used as a communication
3376 channel."
3377 (org-latex--text-markup
3378 (org-element-property :value verbatim) 'verbatim info))
3381 ;;;; Verse Block
3383 (defun org-latex-verse-block (verse-block contents info)
3384 "Transcode a VERSE-BLOCK element from Org to LaTeX.
3385 CONTENTS is verse block contents. INFO is a plist holding
3386 contextual information."
3387 (org-latex--wrap-label
3388 verse-block
3389 ;; In a verse environment, add a line break to each newline
3390 ;; character and change each white space at beginning of a line
3391 ;; into a space of 1 em. Also change each blank line with
3392 ;; a vertical space of 1 em.
3393 (format "\\begin{verse}\n%s\\end{verse}"
3394 (replace-regexp-in-string
3395 "^[ \t]+" (lambda (m) (format "\\hspace*{%dem}" (length m)))
3396 (replace-regexp-in-string
3397 "^[ \t]*\\\\\\\\$" "\\vspace*{1em}"
3398 (replace-regexp-in-string
3399 "\\([ \t]*\\\\\\\\\\)?[ \t]*\n" "\\\\\n"
3400 contents nil t) nil t) nil t))
3401 info))
3405 ;;; End-user functions
3407 ;;;###autoload
3408 (defun org-latex-export-as-latex
3409 (&optional async subtreep visible-only body-only ext-plist)
3410 "Export current buffer as a LaTeX buffer.
3412 If narrowing is active in the current buffer, only export its
3413 narrowed part.
3415 If a region is active, export that region.
3417 A non-nil optional argument ASYNC means the process should happen
3418 asynchronously. The resulting buffer should be accessible
3419 through the `org-export-stack' interface.
3421 When optional argument SUBTREEP is non-nil, export the sub-tree
3422 at point, extracting information from the headline properties
3423 first.
3425 When optional argument VISIBLE-ONLY is non-nil, don't export
3426 contents of hidden elements.
3428 When optional argument BODY-ONLY is non-nil, only write code
3429 between \"\\begin{document}\" and \"\\end{document}\".
3431 EXT-PLIST, when provided, is a property list with external
3432 parameters overriding Org default settings, but still inferior to
3433 file-local settings.
3435 Export is done in a buffer named \"*Org LATEX Export*\", which
3436 will be displayed when `org-export-show-temporary-export-buffer'
3437 is non-nil."
3438 (interactive)
3439 (org-export-to-buffer 'latex "*Org LATEX Export*"
3440 async subtreep visible-only body-only ext-plist (lambda () (LaTeX-mode))))
3442 ;;;###autoload
3443 (defun org-latex-convert-region-to-latex ()
3444 "Assume the current region has org-mode syntax, and convert it to LaTeX.
3445 This can be used in any buffer. For example, you can write an
3446 itemized list in org-mode syntax in an LaTeX buffer and use this
3447 command to convert it."
3448 (interactive)
3449 (org-export-replace-region-by 'latex))
3451 ;;;###autoload
3452 (defun org-latex-export-to-latex
3453 (&optional async subtreep visible-only body-only ext-plist)
3454 "Export current buffer to a LaTeX file.
3456 If narrowing is active in the current buffer, only export its
3457 narrowed part.
3459 If a region is active, export that region.
3461 A non-nil optional argument ASYNC means the process should happen
3462 asynchronously. The resulting file should be accessible through
3463 the `org-export-stack' interface.
3465 When optional argument SUBTREEP is non-nil, export the sub-tree
3466 at point, extracting information from the headline properties
3467 first.
3469 When optional argument VISIBLE-ONLY is non-nil, don't export
3470 contents of hidden elements.
3472 When optional argument BODY-ONLY is non-nil, only write code
3473 between \"\\begin{document}\" and \"\\end{document}\".
3475 EXT-PLIST, when provided, is a property list with external
3476 parameters overriding Org default settings, but still inferior to
3477 file-local settings."
3478 (interactive)
3479 (let ((outfile (org-export-output-file-name ".tex" subtreep)))
3480 (org-export-to-file 'latex outfile
3481 async subtreep visible-only body-only ext-plist)))
3483 ;;;###autoload
3484 (defun org-latex-export-to-pdf
3485 (&optional async subtreep visible-only body-only ext-plist)
3486 "Export current buffer to LaTeX then process through to PDF.
3488 If narrowing is active in the current buffer, only export its
3489 narrowed part.
3491 If a region is active, export that region.
3493 A non-nil optional argument ASYNC means the process should happen
3494 asynchronously. The resulting file should be accessible through
3495 the `org-export-stack' interface.
3497 When optional argument SUBTREEP is non-nil, export the sub-tree
3498 at point, extracting information from the headline properties
3499 first.
3501 When optional argument VISIBLE-ONLY is non-nil, don't export
3502 contents of hidden elements.
3504 When optional argument BODY-ONLY is non-nil, only write code
3505 between \"\\begin{document}\" and \"\\end{document}\".
3507 EXT-PLIST, when provided, is a property list with external
3508 parameters overriding Org default settings, but still inferior to
3509 file-local settings.
3511 Return PDF file's name."
3512 (interactive)
3513 (let ((outfile (org-export-output-file-name ".tex" subtreep)))
3514 (org-export-to-file 'latex outfile
3515 async subtreep visible-only body-only ext-plist
3516 (lambda (file) (org-latex-compile file)))))
3518 (defun org-latex-compile (texfile &optional snippet)
3519 "Compile a TeX file.
3521 TEXFILE is the name of the file being compiled. Processing is
3522 done through the command specified in `org-latex-pdf-process'.
3524 When optional argument SNIPPET is non-nil, TEXFILE is a temporary
3525 file used to preview a LaTeX snippet. In this case, do not
3526 create a log buffer and do not bother removing log files.
3528 Return PDF file name or an error if it couldn't be produced."
3529 (let* ((base-name (file-name-sans-extension (file-name-nondirectory texfile)))
3530 (full-name (file-truename texfile))
3531 (compiler (or (with-temp-buffer
3532 (save-excursion (insert-file-contents full-name))
3533 (when (and (search-forward-regexp
3534 (regexp-opt org-latex-compilers) (line-end-position 2) t)
3535 (progn (beginning-of-line)
3536 (looking-at-p "%")))
3537 (match-string 0)))
3538 "pdflatex"))
3539 (out-dir (file-name-directory texfile))
3540 ;; Properly set working directory for compilation.
3541 (default-directory (if (file-name-absolute-p texfile)
3542 (file-name-directory full-name)
3543 default-directory))
3544 (time (current-time))
3545 warnings)
3546 (unless snippet (message "Processing LaTeX file %s..." texfile))
3547 (save-window-excursion
3548 (cond
3549 ;; A function is provided: Apply it.
3550 ((functionp org-latex-pdf-process)
3551 (funcall org-latex-pdf-process (shell-quote-argument texfile)))
3552 ;; A list is provided: Replace %b, %f and %o with appropriate
3553 ;; values in each command before applying it. Note that while
3554 ;; "%latex" and "%bibtex" is used in `org-latex-pdf-process',
3555 ;; they are replaced with "%L" and "%B" to adhere to
3556 ;; format-spec. Output is redirected to "*Org PDF LaTeX
3557 ;; Output*" buffer.
3558 ((consp org-latex-pdf-process)
3559 (let ((outbuf (and (not snippet)
3560 (get-buffer-create "*Org PDF LaTeX Output*")))
3561 (spec (list (cons ?B (shell-quote-argument org-latex-bib-compiler))
3562 (cons ?L (shell-quote-argument compiler))
3563 (cons ?b (shell-quote-argument base-name))
3564 (cons ?f (shell-quote-argument full-name))
3565 (cons ?o (shell-quote-argument out-dir)))))
3566 (dolist (command org-latex-pdf-process)
3567 (let ((c (replace-regexp-in-string
3568 "%\\(latex\\|bibtex\\)\\>"
3569 (lambda (str) (upcase (substring str 0 2)))
3570 command)))
3571 (shell-command (format-spec c spec) outbuf)))
3572 ;; Collect standard errors from output buffer.
3573 (setq warnings (and (not snippet)
3574 (org-latex--collect-warnings outbuf)))))
3575 (t (error "No valid command to process to PDF")))
3576 (let ((pdffile (concat out-dir base-name ".pdf")))
3577 ;; Check for process failure. Provide collected errors if
3578 ;; possible.
3579 (if (or (not (file-exists-p pdffile))
3580 ;; Only compare times up to whole seconds as some filesystems
3581 ;; (e.g. HFS+) do not retain any finer granularity.
3582 (time-less-p (cl-subseq (nth 5 (file-attributes pdffile)) 0 2)
3583 (cl-subseq time 0 2)))
3584 (error (format "PDF file %s wasn't produced" pdffile))
3585 ;; Else remove log files, when specified, and signal end of
3586 ;; process to user, along with any error encountered.
3587 (unless snippet
3588 (when org-latex-remove-logfiles
3589 (dolist (file (directory-files
3590 out-dir t
3591 (concat (regexp-quote base-name)
3592 "\\(?:\\.[0-9]+\\)?"
3593 "\\."
3594 (regexp-opt org-latex-logfiles-extensions))))
3595 (delete-file file)))
3596 (message (concat "PDF file produced"
3597 (cond
3598 ((eq warnings 'error) " with errors.")
3599 (warnings (concat " with warnings: " warnings))
3600 (t "."))))))
3601 ;; Return output file name.
3602 pdffile))))
3604 (defun org-latex--collect-warnings (buffer)
3605 "Collect some warnings from \"pdflatex\" command output.
3606 BUFFER is the buffer containing output. Return collected
3607 warnings types as a string, `error' if a LaTeX error was
3608 encountered or nil if there was none."
3609 (with-current-buffer buffer
3610 (save-excursion
3611 (goto-char (point-max))
3612 (when (re-search-backward "^[ \t]*This is .*?TeX.*?Version" nil t)
3613 (if (re-search-forward "^!" nil t) 'error
3614 (let ((case-fold-search t)
3615 (warnings ""))
3616 (dolist (warning org-latex-known-warnings)
3617 (when (save-excursion (re-search-forward (car warning) nil t))
3618 (setq warnings (concat warnings " " (cdr warning)))))
3619 (org-string-nw-p (org-trim warnings))))))))
3621 ;;;###autoload
3622 (defun org-latex-publish-to-latex (plist filename pub-dir)
3623 "Publish an Org file to LaTeX.
3625 FILENAME is the filename of the Org file to be published. PLIST
3626 is the property list for the given project. PUB-DIR is the
3627 publishing directory.
3629 Return output file name."
3630 (org-publish-org-to 'latex filename ".tex" plist pub-dir))
3632 ;;;###autoload
3633 (defun org-latex-publish-to-pdf (plist filename pub-dir)
3634 "Publish an Org file to PDF (via LaTeX).
3636 FILENAME is the filename of the Org file to be published. PLIST
3637 is the property list for the given project. PUB-DIR is the
3638 publishing directory.
3640 Return output file name."
3641 ;; Unlike to `org-latex-publish-to-latex', PDF file is generated
3642 ;; in working directory and then moved to publishing directory.
3643 (org-publish-attachment
3644 plist
3645 (org-latex-compile
3646 (org-publish-org-to
3647 'latex filename ".tex" plist (file-name-directory filename)))
3648 pub-dir))
3651 (provide 'ox-latex)
3653 ;; Local variables:
3654 ;; generated-autoload-file: "org-loaddefs.el"
3655 ;; End:
3657 ;;; ox-latex.el ends here