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