Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / ox-latex.el
blob1b663f31721dffd9bb598b01380d8888c815a39a
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 org-latex-image-link-filter)
107 (:filter-verse-block . org-latex-clean-invalid-line-breaks))
108 :options-alist
109 '((:latex-class "LATEX_CLASS" nil org-latex-default-class t)
110 (:latex-class-options "LATEX_CLASS_OPTIONS" nil nil t)
111 (:latex-header "LATEX_HEADER" nil nil newline)
112 (:latex-header-extra "LATEX_HEADER_EXTRA" nil nil newline)
113 (:description "DESCRIPTION" nil nil parse)
114 (:keywords "KEYWORDS" nil nil parse)
115 (:subtitle "SUBTITLE" nil nil parse)
116 ;; Other variables.
117 (:latex-active-timestamp-format nil nil org-latex-active-timestamp-format)
118 (:latex-caption-above nil nil org-latex-caption-above)
119 (:latex-classes nil nil org-latex-classes)
120 (:latex-default-figure-position nil nil org-latex-default-figure-position)
121 (:latex-default-table-environment nil nil org-latex-default-table-environment)
122 (:latex-default-table-mode nil nil org-latex-default-table-mode)
123 (:latex-diary-timestamp-format nil nil org-latex-diary-timestamp-format)
124 (:latex-footnote-defined-format nil nil org-latex-footnote-defined-format)
125 (:latex-footnote-separator nil nil org-latex-footnote-separator)
126 (:latex-format-drawer-function nil nil org-latex-format-drawer-function)
127 (:latex-format-headline-function nil nil org-latex-format-headline-function)
128 (:latex-format-inlinetask-function nil nil org-latex-format-inlinetask-function)
129 (:latex-hyperref-template nil nil org-latex-hyperref-template t)
130 (:latex-image-default-height nil nil org-latex-image-default-height)
131 (:latex-image-default-option nil nil org-latex-image-default-option)
132 (:latex-image-default-width nil nil org-latex-image-default-width)
133 (:latex-images-centered nil nil org-latex-images-centered)
134 (:latex-inactive-timestamp-format nil nil org-latex-inactive-timestamp-format)
135 (:latex-inline-image-rules nil nil org-latex-inline-image-rules)
136 (:latex-link-with-unknown-path-format nil nil org-latex-link-with-unknown-path-format)
137 (:latex-listings nil nil org-latex-listings)
138 (:latex-listings-langs nil nil org-latex-listings-langs)
139 (:latex-listings-options nil nil org-latex-listings-options)
140 (:latex-minted-langs nil nil org-latex-minted-langs)
141 (:latex-minted-options nil nil org-latex-minted-options)
142 (:latex-prefer-user-labels nil nil org-latex-prefer-user-labels)
143 (:latex-subtitle-format nil nil org-latex-subtitle-format)
144 (:latex-subtitle-separate nil nil org-latex-subtitle-separate)
145 (:latex-table-scientific-notation nil nil org-latex-table-scientific-notation)
146 (:latex-tables-booktabs nil nil org-latex-tables-booktabs)
147 (:latex-tables-centered nil nil org-latex-tables-centered)
148 (:latex-text-markup-alist nil nil org-latex-text-markup-alist)
149 (:latex-title-command nil nil org-latex-title-command)
150 (:latex-toc-command nil nil org-latex-toc-command)
151 (:latex-compiler "LATEX_COMPILER" nil org-latex-compiler)
152 ;; Redefine regular options.
153 (:date "DATE" nil "\\today" parse)))
157 ;;; Internal Variables
159 (defconst org-latex-babel-language-alist
160 '(("af" . "afrikaans")
161 ("bg" . "bulgarian")
162 ("bt-br" . "brazilian")
163 ("ca" . "catalan")
164 ("cs" . "czech")
165 ("cy" . "welsh")
166 ("da" . "danish")
167 ("de" . "germanb")
168 ("de-at" . "naustrian")
169 ("de-de" . "ngerman")
170 ("el" . "greek")
171 ("en" . "english")
172 ("en-au" . "australian")
173 ("en-ca" . "canadian")
174 ("en-gb" . "british")
175 ("en-ie" . "irish")
176 ("en-nz" . "newzealand")
177 ("en-us" . "american")
178 ("es" . "spanish")
179 ("et" . "estonian")
180 ("eu" . "basque")
181 ("fi" . "finnish")
182 ("fr" . "frenchb")
183 ("fr-ca" . "canadien")
184 ("gl" . "galician")
185 ("hr" . "croatian")
186 ("hu" . "hungarian")
187 ("id" . "indonesian")
188 ("is" . "icelandic")
189 ("it" . "italian")
190 ("la" . "latin")
191 ("ms" . "malay")
192 ("nl" . "dutch")
193 ("nb" . "norsk")
194 ("nn" . "nynorsk")
195 ("no" . "norsk")
196 ("pl" . "polish")
197 ("pt" . "portuguese")
198 ("ro" . "romanian")
199 ("ru" . "russian")
200 ("sa" . "sanskrit")
201 ("sb" . "uppersorbian")
202 ("sk" . "slovak")
203 ("sl" . "slovene")
204 ("sq" . "albanian")
205 ("sr" . "serbian")
206 ("sv" . "swedish")
207 ("ta" . "tamil")
208 ("tr" . "turkish")
209 ("uk" . "ukrainian"))
210 "Alist between language code and corresponding Babel option.")
212 (defconst org-latex-polyglossia-language-alist
213 '(("am" "amharic")
214 ("ast" "asturian")
215 ("ar" "arabic")
216 ("bo" "tibetan")
217 ("bn" "bengali")
218 ("bg" "bulgarian")
219 ("br" "breton")
220 ("bt-br" "brazilian")
221 ("ca" "catalan")
222 ("cop" "coptic")
223 ("cs" "czech")
224 ("cy" "welsh")
225 ("da" "danish")
226 ("de" "german" "german")
227 ("de-at" "german" "austrian")
228 ("de-de" "german" "german")
229 ("dv" "divehi")
230 ("el" "greek")
231 ("en" "english" "usmax")
232 ("en-au" "english" "australian")
233 ("en-gb" "english" "uk")
234 ("en-nz" "english" "newzealand")
235 ("en-us" "english" "usmax")
236 ("eo" "esperanto")
237 ("es" "spanish")
238 ("et" "estonian")
239 ("eu" "basque")
240 ("fa" "farsi")
241 ("fi" "finnish")
242 ("fr" "french")
243 ("fu" "friulan")
244 ("ga" "irish")
245 ("gd" "scottish")
246 ("gl" "galician")
247 ("he" "hebrew")
248 ("hi" "hindi")
249 ("hr" "croatian")
250 ("hu" "magyar")
251 ("hy" "armenian")
252 ("id" "bahasai")
253 ("ia" "interlingua")
254 ("is" "icelandic")
255 ("it" "italian")
256 ("kn" "kannada")
257 ("la" "latin" "modern")
258 ("la-modern" "latin" "modern")
259 ("la-classic" "latin" "classic")
260 ("la-medieval" "latin" "medieval")
261 ("lo" "lao")
262 ("lt" "lithuanian")
263 ("lv" "latvian")
264 ("mr" "maranthi")
265 ("ml" "malayalam")
266 ("nl" "dutch")
267 ("nb" "norsk")
268 ("nn" "nynorsk")
269 ("nko" "nko")
270 ("no" "norsk")
271 ("oc" "occitan")
272 ("pl" "polish")
273 ("pms" "piedmontese")
274 ("pt" "portuges")
275 ("rm" "romansh")
276 ("ro" "romanian")
277 ("ru" "russian")
278 ("sa" "sanskrit")
279 ("hsb" "usorbian")
280 ("dsb" "lsorbian")
281 ("sk" "slovak")
282 ("sl" "slovenian")
283 ("se" "samin")
284 ("sq" "albanian")
285 ("sr" "serbian")
286 ("sv" "swedish")
287 ("syr" "syriac")
288 ("ta" "tamil")
289 ("te" "telugu")
290 ("th" "thai")
291 ("tk" "turkmen")
292 ("tr" "turkish")
293 ("uk" "ukrainian")
294 ("ur" "urdu")
295 ("vi" "vietnamese"))
296 "Alist between language code and corresponding Polyglossia option")
300 (defconst org-latex-table-matrix-macros '(("bordermatrix" . "\\cr")
301 ("qbordermatrix" . "\\cr")
302 ("kbordermatrix" . "\\\\"))
303 "Alist between matrix macros and their row ending.")
305 (defconst org-latex-math-environments-re
306 (format
307 "\\`[ \t]*\\\\begin{%s\\*?}"
308 (regexp-opt
309 '("equation" "eqnarray" "math" "displaymath"
310 "align" "gather" "multline" "flalign" "alignat"
311 "xalignat" "xxalignat"
312 "subequations"
313 ;; breqn
314 "dmath" "dseries" "dgroup" "darray"
315 ;; empheq
316 "empheq")))
317 "Regexp of LaTeX math environments.")
320 ;;; User Configurable Variables
322 (defgroup org-export-latex nil
323 "Options for exporting Org mode files to LaTeX."
324 :tag "Org Export LaTeX"
325 :group 'org-export)
327 ;;;; Generic
329 (defcustom org-latex-caption-above '(table)
330 "When non-nil, place caption string at the beginning of elements.
331 Otherwise, place it near the end. When value is a list of
332 symbols, put caption above selected elements only. Allowed
333 symbols are: `image', `table', `src-block' and `special-block'."
334 :group 'org-export-latex
335 :version "25.2"
336 :package-version '(Org . "8.3")
337 :type '(choice
338 (const :tag "For all elements" t)
339 (const :tag "For no element" nil)
340 (set :tag "For the following elements only" :greedy t
341 (const :tag "Images" image)
342 (const :tag "Tables" table)
343 (const :tag "Source code" src-block)
344 (const :tag "Special blocks" special-block))))
346 (defcustom org-latex-prefer-user-labels nil
347 "Use user-provided labels instead of internal ones when non-nil.
349 When this variable is non-nil, Org will use the value of
350 CUSTOM_ID property, NAME keyword or Org target as the key for the
351 \\label commands generated.
353 By default, Org generates its own internal labels during LaTeX
354 export. This process ensures that the \\label keys are unique
355 and valid, but it means the keys are not available in advance of
356 the export process.
358 Setting this variable gives you control over how Org generates
359 labels during LaTeX export, so that you may know their keys in
360 advance. One reason to do this is that it allows you to refer to
361 various elements using a single label both in Org's link syntax
362 and in embedded LaTeX code.
364 For example, when this variable is non-nil, a headline like this:
366 ** Some section
367 :PROPERTIES:
368 :CUSTOM_ID: sec:foo
369 :END:
370 This is section [[#sec:foo]].
371 #+BEGIN_EXPORT latex
372 And this is still section \\ref{sec:foo}.
373 #+END_EXPORT
375 will be exported to LaTeX as:
377 \\subsection{Some section}
378 \\label{sec:foo}
379 This is section \\ref{sec:foo}.
380 And this is still section \\ref{sec:foo}.
382 Note, however, that setting this variable introduces a limitation
383 on the possible values for CUSTOM_ID and NAME. When this
384 variable is non-nil, Org passes their value to \\label unchanged.
385 You are responsible for ensuring that the value is a valid LaTeX
386 \\label key, and that no other \\label commands with the same key
387 appear elsewhere in your document. (Keys may contain letters,
388 numbers, and the following punctuation: '_' '.' '-' ':'.) There
389 are no such limitations on CUSTOM_ID and NAME when this variable
390 is nil.
392 For headlines that do not define the CUSTOM_ID property or
393 elements without a NAME, Org will continue to use its default
394 labeling scheme to generate labels and resolve links into proper
395 references."
396 :group 'org-export-latex
397 :type 'boolean
398 :version "25.2"
399 :package-version '(Org . "8.3"))
401 ;;;; Preamble
403 (defcustom org-latex-default-class "article"
404 "The default LaTeX class."
405 :group 'org-export-latex
406 :type '(string :tag "LaTeX class"))
408 (defcustom org-latex-classes
409 '(("article"
410 "\\documentclass[11pt]{article}"
411 ("\\section{%s}" . "\\section*{%s}")
412 ("\\subsection{%s}" . "\\subsection*{%s}")
413 ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
414 ("\\paragraph{%s}" . "\\paragraph*{%s}")
415 ("\\subparagraph{%s}" . "\\subparagraph*{%s}"))
416 ("report"
417 "\\documentclass[11pt]{report}"
418 ("\\part{%s}" . "\\part*{%s}")
419 ("\\chapter{%s}" . "\\chapter*{%s}")
420 ("\\section{%s}" . "\\section*{%s}")
421 ("\\subsection{%s}" . "\\subsection*{%s}")
422 ("\\subsubsection{%s}" . "\\subsubsection*{%s}"))
423 ("book"
424 "\\documentclass[11pt]{book}"
425 ("\\part{%s}" . "\\part*{%s}")
426 ("\\chapter{%s}" . "\\chapter*{%s}")
427 ("\\section{%s}" . "\\section*{%s}")
428 ("\\subsection{%s}" . "\\subsection*{%s}")
429 ("\\subsubsection{%s}" . "\\subsubsection*{%s}")))
430 "Alist of LaTeX classes and associated header and structure.
431 If #+LATEX_CLASS is set in the buffer, use its value and the
432 associated information. Here is the structure of each cell:
434 (class-name
435 header-string
436 (numbered-section . unnumbered-section)
437 ...)
439 The header string
440 -----------------
442 The HEADER-STRING is the header that will be inserted into the
443 LaTeX file. It should contain the \\documentclass macro, and
444 anything else that is needed for this setup. To this header, the
445 following commands will be added:
447 - Calls to \\usepackage for all packages mentioned in the
448 variables `org-latex-default-packages-alist' and
449 `org-latex-packages-alist'. Thus, your header definitions
450 should avoid to also request these packages.
452 - Lines specified via \"#+LATEX_HEADER:\" and
453 \"#+LATEX_HEADER_EXTRA:\" keywords.
455 If you need more control about the sequence in which the header
456 is built up, or if you want to exclude one of these building
457 blocks for a particular class, you can use the following
458 macro-like placeholders.
460 [DEFAULT-PACKAGES] \\usepackage statements for default packages
461 [NO-DEFAULT-PACKAGES] do not include any of the default packages
462 [PACKAGES] \\usepackage statements for packages
463 [NO-PACKAGES] do not include the packages
464 [EXTRA] the stuff from #+LATEX_HEADER(_EXTRA)
465 [NO-EXTRA] do not include #+LATEX_HEADER(_EXTRA) stuff
467 So a header like
469 \\documentclass{article}
470 [NO-DEFAULT-PACKAGES]
471 [EXTRA]
472 \\providecommand{\\alert}[1]{\\textbf{#1}}
473 [PACKAGES]
475 will omit the default packages, and will include the
476 #+LATEX_HEADER and #+LATEX_HEADER_EXTRA lines, then have a call
477 to \\providecommand, and then place \\usepackage commands based
478 on the content of `org-latex-packages-alist'.
480 If your header, `org-latex-default-packages-alist' or
481 `org-latex-packages-alist' inserts \"\\usepackage[AUTO]{inputenc}\",
482 AUTO will automatically be replaced with a coding system derived
483 from `buffer-file-coding-system'. See also the variable
484 `org-latex-inputenc-alist' for a way to influence this mechanism.
486 Likewise, if your header contains \"\\usepackage[AUTO]{babel}\"
487 or \"\\usepackage[AUTO]{polyglossia}\", AUTO will be replaced
488 with the language related to the language code specified by
489 `org-export-default-language'. Note that constructions such as
490 \"\\usepackage[french,AUTO,english]{babel}\" are permitted. For
491 Polyglossia the language will be set via the macros
492 \"\\setmainlanguage\" and \"\\setotherlanguage\". See also
493 `org-latex-guess-babel-language' and
494 `org-latex-guess-polyglossia-language'.
496 The sectioning structure
497 ------------------------
499 The sectioning structure of the class is given by the elements
500 following the header string. For each sectioning level, a number
501 of strings is specified. A %s formatter is mandatory in each
502 section string and will be replaced by the title of the section.
504 Instead of a cons cell (numbered . unnumbered), you can also
505 provide a list of 2 or 4 elements,
507 (numbered-open numbered-close)
511 (numbered-open numbered-close unnumbered-open unnumbered-close)
513 providing opening and closing strings for a LaTeX environment
514 that should represent the document section. The opening clause
515 should have a %s to represent the section title.
517 Instead of a list of sectioning commands, you can also specify
518 a function name. That function will be called with two
519 parameters, the (reduced) level of the headline, and a predicate
520 non-nil when the headline should be numbered. It must return
521 a format string in which the section title will be added."
522 :group 'org-export-latex
523 :type '(repeat
524 (list (string :tag "LaTeX class")
525 (string :tag "LaTeX header")
526 (repeat :tag "Levels" :inline t
527 (choice
528 (cons :tag "Heading"
529 (string :tag " numbered")
530 (string :tag "unnumbered"))
531 (list :tag "Environment"
532 (string :tag "Opening (numbered)")
533 (string :tag "Closing (numbered)")
534 (string :tag "Opening (unnumbered)")
535 (string :tag "Closing (unnumbered)"))
536 (function :tag "Hook computing sectioning"))))))
538 (defcustom org-latex-inputenc-alist nil
539 "Alist of inputenc coding system names, and what should really be used.
540 For example, adding an entry
542 (\"utf8\" . \"utf8x\")
544 will cause \\usepackage[utf8x]{inputenc} to be used for buffers that
545 are written as utf8 files."
546 :group 'org-export-latex
547 :type '(repeat
548 (cons
549 (string :tag "Derived from buffer")
550 (string :tag "Use this instead"))))
552 (defcustom org-latex-title-command "\\maketitle"
553 "The command used to insert the title just after \\begin{document}.
555 This format string may contain these elements:
557 %a for AUTHOR keyword
558 %t for TITLE keyword
559 %s for SUBTITLE keyword
560 %k for KEYWORDS line
561 %d for DESCRIPTION line
562 %c for CREATOR line
563 %l for Language keyword
564 %L for capitalized language keyword
565 %D for DATE keyword
567 If you need to use a \"%\" character, you need to escape it
568 like that: \"%%\".
570 Setting :latex-title-command in publishing projects will take
571 precedence over this variable."
572 :group 'org-export-latex
573 :type '(string :tag "Format string"))
575 (defcustom org-latex-subtitle-format "\\\\\\medskip\n\\large %s"
576 "Format string used for transcoded subtitle.
577 The format string should have at most one \"%s\"-expression,
578 which is replaced with the subtitle."
579 :group 'org-export-latex
580 :version "25.2"
581 :package-version '(Org . "8.3")
582 :type '(string :tag "Format string"))
584 (defcustom org-latex-subtitle-separate nil
585 "Non-nil means the subtitle is not typeset as part of title."
586 :group 'org-export-latex
587 :version "25.2"
588 :package-version '(Org . "8.3")
589 :type 'boolean)
591 (defcustom org-latex-toc-command "\\tableofcontents\n\n"
592 "LaTeX command to set the table of contents, list of figures, etc.
593 This command only applies to the table of contents generated with
594 the toc:nil option, not to those generated with #+TOC keyword."
595 :group 'org-export-latex
596 :type 'string)
598 (defcustom org-latex-hyperref-template
599 "\\hypersetup{\n pdfauthor={%a},\n pdftitle={%t},\n pdfkeywords={%k},
600 pdfsubject={%d},\n pdfcreator={%c}, \n pdflang={%L}}\n"
601 "Template for hyperref package options.
603 This format string may contain these elements:
605 %a for AUTHOR keyword
606 %t for TITLE keyword
607 %s for SUBTITLE keyword
608 %k for KEYWORDS line
609 %d for DESCRIPTION line
610 %c for CREATOR line
611 %l for Language keyword
612 %L for capitalized language keyword
613 %D for DATE keyword
615 If you need to use a \"%\" character, you need to escape it
616 like that: \"%%\".
618 As a special case, a nil value prevents template from being
619 inserted.
621 Setting :latex-hyperref-template in publishing projects will take
622 precedence over this variable."
623 :group 'org-export-latex
624 :version "25.2"
625 :package-version '(Org . "8.3")
626 :type '(choice (const :tag "No template" nil)
627 (string :tag "Format string")))
629 ;;;; Headline
631 (defcustom org-latex-format-headline-function
632 'org-latex-format-headline-default-function
633 "Function for formatting the headline's text.
635 This function will be called with six arguments:
636 TODO the todo keyword (string or nil)
637 TODO-TYPE the type of todo (symbol: `todo', `done', nil)
638 PRIORITY the priority of the headline (integer or nil)
639 TEXT the main headline text (string)
640 TAGS the tags (list of strings or nil)
641 INFO the export options (plist)
643 The function result will be used in the section format string."
644 :group 'org-export-latex
645 :version "24.4"
646 :package-version '(Org . "8.0")
647 :type 'function)
650 ;;;; Footnotes
652 (defcustom org-latex-footnote-separator "\\textsuperscript{,}\\,"
653 "Text used to separate footnotes."
654 :group 'org-export-latex
655 :type 'string)
657 (defcustom org-latex-footnote-defined-format "\\textsuperscript{\\ref{%s}}"
658 "Format string used to format reference to footnote already defined.
659 %s will be replaced by the label of the referred footnote."
660 :group 'org-export-latex
661 :type '(choice
662 (const :tag "Use plain superscript (default)" "\\textsuperscript{\\ref{%s}}")
663 (const :tag "Use Memoir/KOMA-Script footref" "\\footref{%s}")
664 (string :tag "Other format string"))
665 :version "25.2"
666 :package-version '(Org . "9.0"))
668 ;;;; Timestamps
670 (defcustom org-latex-active-timestamp-format "\\textit{%s}"
671 "A printf format string to be applied to active timestamps."
672 :group 'org-export-latex
673 :type 'string)
675 (defcustom org-latex-inactive-timestamp-format "\\textit{%s}"
676 "A printf format string to be applied to inactive timestamps."
677 :group 'org-export-latex
678 :type 'string)
680 (defcustom org-latex-diary-timestamp-format "\\textit{%s}"
681 "A printf format string to be applied to diary timestamps."
682 :group 'org-export-latex
683 :type 'string)
686 ;;;; Links
688 (defcustom org-latex-images-centered t
689 "When non-nil, images are centered."
690 :group 'org-export-latex
691 :version "25.2"
692 :package-version '(Org . "9.0")
693 :type 'boolean
694 :safe #'booleanp)
696 (defcustom org-latex-image-default-option ""
697 "Default option for images."
698 :group 'org-export-latex
699 :version "24.4"
700 :package-version '(Org . "8.0")
701 :type 'string)
703 (defcustom org-latex-image-default-width ".9\\linewidth"
704 "Default width for images.
705 This value will not be used if a height is provided."
706 :group 'org-export-latex
707 :version "24.4"
708 :package-version '(Org . "8.0")
709 :type 'string)
711 (defcustom org-latex-image-default-height ""
712 "Default height for images.
713 This value will not be used if a width is provided, or if the
714 image is wrapped within a \"figure\" or \"wrapfigure\"
715 environment."
716 :group 'org-export-latex
717 :version "24.4"
718 :package-version '(Org . "8.0")
719 :type 'string)
721 (defcustom org-latex-default-figure-position "htbp"
722 "Default position for LaTeX figures."
723 :group 'org-export-latex
724 :type 'string
725 :version "25.2"
726 :package-version '(Org . "9.0")
727 :safe #'stringp)
729 (defcustom org-latex-inline-image-rules
730 `(("file" . ,(regexp-opt
731 '("pdf" "jpeg" "jpg" "png" "ps" "eps" "tikz" "pgf" "svg"))))
732 "Rules characterizing image files that can be inlined into LaTeX.
734 A rule consists in an association whose key is the type of link
735 to consider, and value is a regexp that will be matched against
736 link's path.
738 Note that, by default, the image extension *actually* allowed
739 depend on the way the LaTeX file is processed. When used with
740 pdflatex, pdf, jpg and png images are OK. When processing
741 through dvi to Postscript, only ps and eps are allowed. The
742 default we use here encompasses both."
743 :group 'org-export-latex
744 :version "24.4"
745 :package-version '(Org . "8.0")
746 :type '(alist :key-type (string :tag "Type")
747 :value-type (regexp :tag "Path")))
749 (defcustom org-latex-link-with-unknown-path-format "\\texttt{%s}"
750 "Format string for links with unknown path type."
751 :group 'org-export-latex
752 :type 'string)
755 ;;;; Tables
757 (defcustom org-latex-default-table-environment "tabular"
758 "Default environment used to build tables."
759 :group 'org-export-latex
760 :version "24.4"
761 :package-version '(Org . "8.0")
762 :type 'string)
764 (defcustom org-latex-default-table-mode 'table
765 "Default mode for tables.
767 Value can be a symbol among:
769 `table' Regular LaTeX table.
771 `math' In this mode, every cell is considered as being in math
772 mode and the complete table will be wrapped within a math
773 environment. It is particularly useful to write matrices.
775 `inline-math' This mode is almost the same as `math', but the
776 math environment will be inlined.
778 `verbatim' The table is exported as it appears in the Org
779 buffer, within a verbatim environment.
781 This value can be overridden locally with, i.e. \":mode math\" in
782 LaTeX attributes.
784 When modifying this variable, it may be useful to change
785 `org-latex-default-table-environment' accordingly."
786 :group 'org-export-latex
787 :version "24.4"
788 :package-version '(Org . "8.0")
789 :type '(choice (const :tag "Table" table)
790 (const :tag "Matrix" math)
791 (const :tag "Inline matrix" inline-math)
792 (const :tag "Verbatim" verbatim))
793 :safe (lambda (s) (memq s '(table math inline-math verbatim))))
795 (defcustom org-latex-tables-centered t
796 "When non-nil, tables are exported in a center environment."
797 :group 'org-export-latex
798 :type 'boolean
799 :safe #'booleanp)
801 (defcustom org-latex-tables-booktabs nil
802 "When non-nil, display tables in a formal \"booktabs\" style.
803 This option assumes that the \"booktabs\" package is properly
804 loaded in the header of the document. This value can be ignored
805 locally with \":booktabs t\" and \":booktabs nil\" LaTeX
806 attributes."
807 :group 'org-export-latex
808 :version "24.4"
809 :package-version '(Org . "8.0")
810 :type 'boolean
811 :safe #'booleanp)
813 (defcustom org-latex-table-scientific-notation "%s\\,(%s)"
814 "Format string to display numbers in scientific notation.
815 The format should have \"%s\" twice, for mantissa and exponent
816 \(i.e., \"%s\\\\times10^{%s}\").
818 When nil, no transformation is made."
819 :group 'org-export-latex
820 :version "24.4"
821 :package-version '(Org . "8.0")
822 :type '(choice
823 (string :tag "Format string")
824 (const :tag "No formatting" nil)))
826 ;;;; Text markup
828 (defcustom org-latex-text-markup-alist '((bold . "\\textbf{%s}")
829 (code . protectedtexttt)
830 (italic . "\\emph{%s}")
831 (strike-through . "\\sout{%s}")
832 (underline . "\\uline{%s}")
833 (verbatim . protectedtexttt))
834 "Alist of LaTeX expressions to convert text markup.
836 The key must be a symbol among `bold', `code', `italic',
837 `strike-through', `underline' and `verbatim'. The value is
838 a formatting string to wrap fontified text with.
840 Value can also be set to the following symbols: `verb' and
841 `protectedtexttt'. For the former, Org will use \"\\verb\" to
842 create a format string and select a delimiter character that
843 isn't in the string. For the latter, Org will use \"\\texttt\"
844 to typeset and try to protect special characters.
846 If no association can be found for a given markup, text will be
847 returned as-is."
848 :group 'org-export-latex
849 :version "25.2"
850 :package-version '(Org . "8.3")
851 :type 'alist
852 :options '(bold code italic strike-through underline verbatim))
855 ;;;; Drawers
857 (defcustom org-latex-format-drawer-function (lambda (_ contents) contents)
858 "Function called to format a drawer in LaTeX code.
860 The function must accept two parameters:
861 NAME the drawer name, like \"LOGBOOK\"
862 CONTENTS the contents of the drawer.
864 The function should return the string to be exported.
866 The default function simply returns the value of CONTENTS."
867 :group 'org-export-latex
868 :version "24.4"
869 :package-version '(Org . "8.3")
870 :type 'function)
873 ;;;; Inlinetasks
875 (defcustom org-latex-format-inlinetask-function
876 'org-latex-format-inlinetask-default-function
877 "Function called to format an inlinetask in LaTeX code.
879 The function must accept seven parameters:
880 TODO the todo keyword (string or nil)
881 TODO-TYPE the todo type (symbol: `todo', `done', nil)
882 PRIORITY the inlinetask priority (integer or nil)
883 NAME the inlinetask name (string)
884 TAGS the inlinetask tags (list of strings or nil)
885 CONTENTS the contents of the inlinetask (string or nil)
886 INFO the export options (plist)
888 The function should return the string to be exported."
889 :group 'org-export-latex
890 :type 'function
891 :version "25.2"
892 :package-version '(Org . "8.3"))
895 ;; Src blocks
897 (defcustom org-latex-listings nil
898 "Non-nil means export source code using the listings package.
900 This package will fontify source code, possibly even with color.
901 If you want to use this, you also need to make LaTeX use the
902 listings package, and if you want to have color, the color
903 package. Just add these to `org-latex-packages-alist', for
904 example using customize, or with something like:
906 (require \\='ox-latex)
907 (add-to-list \\='org-latex-packages-alist \\='(\"\" \"listings\"))
908 (add-to-list \\='org-latex-packages-alist \\='(\"\" \"color\"))
910 Alternatively,
912 (setq org-latex-listings \\='minted)
914 causes source code to be exported using the minted package as
915 opposed to listings. If you want to use minted, you need to add
916 the minted package to `org-latex-packages-alist', for example
917 using customize, or with
919 (require \\='ox-latex)
920 (add-to-list \\='org-latex-packages-alist \\='(\"newfloat\" \"minted\"))
922 In addition, it is necessary to install pygments
923 \(http://pygments.org), and to configure the variable
924 `org-latex-pdf-process' so that the -shell-escape option is
925 passed to pdflatex.
927 The minted choice has possible repercussions on the preview of
928 latex fragments (see `org-preview-latex-fragment'). If you run
929 into previewing problems, please consult
931 http://orgmode.org/worg/org-tutorials/org-latex-preview.html"
932 :group 'org-export-latex
933 :type '(choice
934 (const :tag "Use listings" t)
935 (const :tag "Use minted" minted)
936 (const :tag "Export verbatim" nil))
937 :safe (lambda (s) (memq s '(t nil minted))))
939 (defcustom org-latex-listings-langs
940 '((emacs-lisp "Lisp") (lisp "Lisp") (clojure "Lisp")
941 (c "C") (cc "C++")
942 (fortran "fortran")
943 (perl "Perl") (cperl "Perl") (python "Python") (ruby "Ruby")
944 (html "HTML") (xml "XML")
945 (tex "TeX") (latex "[LaTeX]TeX")
946 (shell-script "bash")
947 (gnuplot "Gnuplot")
948 (ocaml "Caml") (caml "Caml")
949 (sql "SQL") (sqlite "sql")
950 (makefile "make")
951 (R "r"))
952 "Alist mapping languages to their listing language counterpart.
953 The key is a symbol, the major mode symbol without the \"-mode\".
954 The value is the string that should be inserted as the language
955 parameter for the listings package. If the mode name and the
956 listings name are the same, the language does not need an entry
957 in this list - but it does not hurt if it is present."
958 :group 'org-export-latex
959 :version "24.4"
960 :package-version '(Org . "8.3")
961 :type '(repeat
962 (list
963 (symbol :tag "Major mode ")
964 (string :tag "Listings language"))))
966 (defcustom org-latex-listings-options nil
967 "Association list of options for the latex listings package.
969 These options are supplied as a comma-separated list to the
970 \\lstset command. Each element of the association list should be
971 a list containing two strings: the name of the option, and the
972 value. For example,
974 (setq org-latex-listings-options
975 \\='((\"basicstyle\" \"\\\\small\")
976 (\"keywordstyle\" \"\\\\color{black}\\\\bfseries\\\\underbar\")))
978 will typeset the code in a small size font with underlined, bold
979 black keywords.
981 Note that the same options will be applied to blocks of all
982 languages. If you need block-specific options, you may use the
983 following syntax:
985 #+ATTR_LATEX: :options key1=value1,key2=value2
986 #+BEGIN_SRC <LANG>
988 #+END_SRC"
989 :group 'org-export-latex
990 :type '(repeat
991 (list
992 (string :tag "Listings option name ")
993 (string :tag "Listings option value"))))
995 (defcustom org-latex-minted-langs
996 '((emacs-lisp "common-lisp")
997 (cc "c++")
998 (cperl "perl")
999 (shell-script "bash")
1000 (caml "ocaml"))
1001 "Alist mapping languages to their minted language counterpart.
1002 The key is a symbol, the major mode symbol without the \"-mode\".
1003 The value is the string that should be inserted as the language
1004 parameter for the minted package. If the mode name and the
1005 listings name are the same, the language does not need an entry
1006 in this list - but it does not hurt if it is present.
1008 Note that minted uses all lower case for language identifiers,
1009 and that the full list of language identifiers can be obtained
1010 with:
1012 pygmentize -L lexers"
1013 :group 'org-export-latex
1014 :type '(repeat
1015 (list
1016 (symbol :tag "Major mode ")
1017 (string :tag "Minted language"))))
1019 (defcustom org-latex-minted-options nil
1020 "Association list of options for the latex minted package.
1022 These options are supplied within square brackets in
1023 \\begin{minted} environments. Each element of the alist should
1024 be a list containing two strings: the name of the option, and the
1025 value. For example,
1027 (setq org-latex-minted-options
1028 \\='((\"bgcolor\" \"bg\") (\"frame\" \"lines\")))
1030 will result in src blocks being exported with
1032 \\begin{minted}[bgcolor=bg,frame=lines]{<LANG>}
1034 as the start of the minted environment. Note that the same
1035 options will be applied to blocks of all languages. If you need
1036 block-specific options, you may use the following syntax:
1038 #+ATTR_LATEX: :options key1=value1,key2=value2
1039 #+BEGIN_SRC <LANG>
1041 #+END_SRC"
1042 :group 'org-export-latex
1043 :type '(repeat
1044 (list
1045 (string :tag "Minted option name ")
1046 (string :tag "Minted option value"))))
1048 (defcustom org-latex-custom-lang-environments nil
1049 "Alist mapping languages to language-specific LaTeX environments.
1051 It is used during export of src blocks by the listings and minted
1052 latex packages. The environment may be a simple string, composed of
1053 only letters and numbers. In this case, the string is directly the
1054 name of the latex environment to use. The environment may also be
1055 a format string. In this case the format string will be directly
1056 exported. This format string may contain these elements:
1058 %s for the formatted source
1059 %c for the caption
1060 %f for the float attribute
1061 %l for an appropriate label
1062 %o for the LaTeX attributes
1064 For example,
1066 (setq org-latex-custom-lang-environments
1067 \\='((python \"pythoncode\")
1068 (ocaml \"\\\\begin{listing}
1069 \\\\begin{minted}[%o]{ocaml}
1070 %s\\\\end{minted}
1071 \\\\caption{%c}
1072 \\\\label{%l}\")))
1074 would have the effect that if Org encounters a Python source block
1075 during LaTeX export it will produce
1077 \\begin{pythoncode}
1078 <src block body>
1079 \\end{pythoncode}
1081 and if Org encounters an Ocaml source block during LaTeX export it
1082 will produce
1084 \\begin{listing}
1085 \\begin{minted}[<attr_latex options>]{ocaml}
1086 <src block body>
1087 \\end{minted}
1088 \\caption{<caption>}
1089 \\label{<label>}
1090 \\end{listing}"
1091 :group 'org-export-latex
1092 :type '(repeat
1093 (list
1094 (symbol :tag "Language name ")
1095 (string :tag "Environment name or format string")))
1096 :version "25.2"
1097 :package-version '(Org . "9.0"))
1100 ;;;; Compilation
1102 (defcustom org-latex-compiler-file-string "%% Intended LaTeX compiler: %s\n"
1103 "LaTeX compiler format-string.
1104 See also `org-latex-compiler'."
1105 :group 'org-export-latex
1106 :type '(choice
1107 (const :tag "Comment" "%% Intended LaTeX compiler: %s\n")
1108 (const :tag "latex-mode file variable" "%% -*- latex-run-command: %s -*-\n")
1109 (const :tag "AUCTeX file variable" "%% -*- LaTeX-command: %s -*-\n")
1110 (string :tag "custom format" "%% %s"))
1111 :version "25.2"
1112 :package-version '(Org . "9.0"))
1114 (defcustom org-latex-compiler "pdflatex"
1115 "LaTeX compiler to use.
1117 Must be an element in `org-latex-compilers' or the empty quote.
1118 Can also be set in buffers via #+LATEX_COMPILER. See also
1119 `org-latex-compiler-file-string'."
1120 :group 'org-export-latex
1121 :type '(choice
1122 (const :tag "pdfLaTeX" "pdflatex")
1123 (const :tag "XeLaTeX" "xelatex")
1124 (const :tag "LuaLaTeX" "lualatex")
1125 (const :tag "Unset" ""))
1126 :version "25.2"
1127 :package-version '(Org . "9.0"))
1129 (defconst org-latex-compilers '("pdflatex" "xelatex" "lualatex")
1130 "Known LaTeX compilers.
1131 See also `org-latex-compiler'.")
1133 (defcustom org-latex-bib-compiler "bibtex"
1134 "Command to process a LaTeX file's bibliography.
1136 The shorthand %bib in `org-latex-pdf-process' is replaced with
1137 this value.
1139 A better approach is to use a compiler suit such as `latexmk'."
1140 :group 'org-export-latex
1141 :type '(choice (const :tag "BibTeX" "bibtex")
1142 (const :tag "Biber" "biber")
1143 (string :tag "Other process"))
1144 :version "25.2"
1145 :package-version '(Org . "9.0"))
1147 (defcustom org-latex-pdf-process
1148 '("%latex -interaction nonstopmode -output-directory %o %f"
1149 "%latex -interaction nonstopmode -output-directory %o %f"
1150 "%latex -interaction nonstopmode -output-directory %o %f")
1151 "Commands to process a LaTeX file to a PDF file.
1153 This is a list of strings, each of them will be given to the
1154 shell as a command. %f in the command will be replaced by the
1155 relative file name, %F by the absolute file name, %b by the file
1156 base name (i.e. without directory and extension parts), %o by the
1157 base directory of the file, %O by the absolute file name of the
1158 output file, %latex is the LaTeX compiler (see
1159 `org-latex-compiler'), and %bib is the BibTeX-like compiler (see
1160 `org-latex-bib-compiler').
1162 The reason why this is a list is that it usually takes several
1163 runs of `pdflatex', maybe mixed with a call to `bibtex'. Org
1164 does not have a clever mechanism to detect which of these
1165 commands have to be run to get to a stable result, and it also
1166 does not do any error checking.
1168 Consider a smart LaTeX compiler such as `texi2dvi' or `latexmk',
1169 which calls the \"correct\" combinations of auxiliary programs.
1171 Alternatively, this may be a Lisp function that does the
1172 processing, so you could use this to apply the machinery of
1173 AUCTeX or the Emacs LaTeX mode. This function should accept the
1174 file name as its single argument."
1175 :group 'org-export-pdf
1176 :type '(choice
1177 (repeat :tag "Shell command sequence"
1178 (string :tag "Shell command"))
1179 (const :tag "2 runs of latex"
1180 ("%latex -interaction nonstopmode -output-directory %o %f"
1181 "%latex -interaction nonstopmode -output-directory %o %f"))
1182 (const :tag "3 runs of latex"
1183 ("%latex -interaction nonstopmode -output-directory %o %f"
1184 "%latex -interaction nonstopmode -output-directory %o %f"
1185 "%latex -interaction nonstopmode -output-directory %o %f"))
1186 (const :tag "latex,bibtex,latex,latex"
1187 ("%latex -interaction nonstopmode -output-directory %o %f"
1188 "%bib %b"
1189 "%latex -interaction nonstopmode -output-directory %o %f"
1190 "%latex -interaction nonstopmode -output-directory %o %f"))
1191 (const :tag "texi2dvi"
1192 ("cd %o; LATEX=\"%latex\" texi2dvi -p -b -V %b.tex"))
1193 (const :tag "latexmk"
1194 ("latexmk -g -pdf -pdflatex=\"%latex\" -outdir=%o %f"))
1195 (function)))
1197 (defcustom org-latex-logfiles-extensions
1198 '("aux" "bcf" "blg" "fdb_latexmk" "fls" "figlist" "idx" "log" "nav" "out"
1199 "ptc" "run.xml" "snm" "toc" "vrb" "xdv")
1200 "The list of file extensions to consider as LaTeX logfiles.
1201 The logfiles will be removed if `org-latex-remove-logfiles' is
1202 non-nil."
1203 :group 'org-export-latex
1204 :version "25.2"
1205 :package-version '(Org . "8.3")
1206 :type '(repeat (string :tag "Extension")))
1208 (defcustom org-latex-remove-logfiles t
1209 "Non-nil means remove the logfiles produced by PDF production.
1210 By default, logfiles are files with these extensions: .aux, .idx,
1211 .log, .out, .toc, .nav, .snm and .vrb. To define the set of
1212 logfiles to remove, set `org-latex-logfiles-extensions'."
1213 :group 'org-export-latex
1214 :type 'boolean)
1216 (defcustom org-latex-known-warnings
1217 '(("Reference.*?undefined" . "[undefined reference]")
1218 ("Runaway argument" . "[runaway argument]")
1219 ("Underfull \\hbox" . "[underfull hbox]")
1220 ("Overfull \\hbox" . "[overfull hbox]")
1221 ("Citation.*?undefined" . "[undefined citation]")
1222 ("Undefined control sequence" . "[undefined control sequence]"))
1223 "Alist of regular expressions and associated messages for the user.
1224 The regular expressions are used to find possible warnings in the
1225 log of a latex-run. These warnings will be reported after
1226 calling `org-latex-compile'."
1227 :group 'org-export-latex
1228 :version "25.2"
1229 :package-version '(Org . "8.3")
1230 :type '(repeat
1231 (cons
1232 (string :tag "Regexp")
1233 (string :tag "Message"))))
1237 ;;; Internal Functions
1239 (defun org-latex--caption-above-p (element info)
1240 "Non nil when caption is expected to be located above ELEMENT.
1241 INFO is a plist holding contextual information."
1242 (let ((above (plist-get info :latex-caption-above)))
1243 (if (symbolp above) above
1244 (let ((type (org-element-type element)))
1245 (memq (if (eq type 'link) 'image type) above)))))
1247 (defun org-latex--label (datum info &optional force full)
1248 "Return an appropriate label for DATUM.
1249 DATUM is an element or a `target' type object. INFO is the
1250 current export state, as a plist.
1252 Return nil if element DATUM has no NAME or VALUE affiliated
1253 keyword or no CUSTOM_ID property, unless FORCE is non-nil. In
1254 this case always return a unique label.
1256 Eventually, if FULL is non-nil, wrap label within \"\\label{}\"."
1257 (let* ((type (org-element-type datum))
1258 (user-label
1259 (org-element-property
1260 (cl-case type
1261 ((headline inlinetask) :CUSTOM_ID)
1262 (target :value)
1263 (otherwise :name))
1264 datum))
1265 (label
1266 (and (or user-label force)
1267 (if (and user-label (plist-get info :latex-prefer-user-labels))
1268 user-label
1269 (concat (cl-case type
1270 (headline "sec:")
1271 (table "tab:")
1272 (latex-environment
1273 (and (string-match-p
1274 org-latex-math-environments-re
1275 (org-element-property :value datum))
1276 "eq:"))
1277 (paragraph
1278 (and (org-element-property :caption datum)
1279 "fig:")))
1280 (org-export-get-reference datum info))))))
1281 (cond ((not full) label)
1282 (label (format "\\label{%s}%s"
1283 label
1284 (if (eq type 'target) "" "\n")))
1285 (t ""))))
1287 (defun org-latex--caption/label-string (element info)
1288 "Return caption and label LaTeX string for ELEMENT.
1290 INFO is a plist holding contextual information. If there's no
1291 caption nor label, return the empty string.
1293 For non-floats, see `org-latex--wrap-label'."
1294 (let* ((label (org-latex--label element info nil t))
1295 (main (org-export-get-caption element))
1296 (attr (org-export-read-attribute :attr_latex element))
1297 (type (org-element-type element))
1298 (nonfloat (or (and (plist-member attr :float)
1299 (not (plist-get attr :float))
1300 main)
1301 (and (eq type 'src-block)
1302 (not (plist-get attr :float))
1303 (memq (plist-get info :latex-listings)
1304 '(nil minted)))))
1305 (short (org-export-get-caption element t))
1306 (caption-from-attr-latex (plist-get attr :caption)))
1307 (cond
1308 ((org-string-nw-p caption-from-attr-latex)
1309 (concat caption-from-attr-latex "\n"))
1310 ((and (not main) (equal label "")) "")
1311 ((not main) label)
1312 ;; Option caption format with short name.
1314 (format (if nonfloat "\\captionof{%s}%s{%s%s}\n"
1315 "\\caption%s%s{%s%s}\n")
1316 (if nonfloat
1317 (cl-case type
1318 (paragraph "figure")
1319 (src-block (if (plist-get info :latex-listings)
1320 "listing"
1321 "figure"))
1322 (t (symbol-name type)))
1324 (if short (format "[%s]" (org-export-data short info)) "")
1325 label
1326 (org-export-data main info))))))
1328 (defun org-latex-guess-inputenc (header)
1329 "Set the coding system in inputenc to what the buffer is.
1331 HEADER is the LaTeX header string. This function only applies
1332 when specified inputenc option is \"AUTO\".
1334 Return the new header, as a string."
1335 (let* ((cs (or (ignore-errors
1336 (latexenc-coding-system-to-inputenc
1337 (or org-export-coding-system buffer-file-coding-system)))
1338 "utf8")))
1339 (if (not cs) header
1340 ;; First translate if that is requested.
1341 (setq cs (or (cdr (assoc cs org-latex-inputenc-alist)) cs))
1342 ;; Then find the \usepackage statement and replace the option.
1343 (replace-regexp-in-string "\\\\usepackage\\[\\(AUTO\\)\\]{inputenc}"
1344 cs header t nil 1))))
1346 (defun org-latex-guess-babel-language (header info)
1347 "Set Babel's language according to LANGUAGE keyword.
1349 HEADER is the LaTeX header string. INFO is the plist used as
1350 a communication channel.
1352 Insertion of guessed language only happens when Babel package has
1353 explicitly been loaded. Then it is added to the rest of
1354 package's options.
1356 The argument to Babel may be \"AUTO\" which is then replaced with
1357 the language of the document or `org-export-default-language'
1358 unless language in question is already loaded.
1360 Return the new header."
1361 (let ((language-code (plist-get info :language)))
1362 ;; If no language is set or Babel package is not loaded, return
1363 ;; HEADER as-is.
1364 (if (or (not (stringp language-code))
1365 (not (string-match "\\\\usepackage\\[\\(.*\\)\\]{babel}" header)))
1366 header
1367 (let ((options (save-match-data
1368 (org-split-string (match-string 1 header) ",[ \t]*")))
1369 (language (cdr (assoc-string language-code
1370 org-latex-babel-language-alist t))))
1371 ;; If LANGUAGE is already loaded, return header without AUTO.
1372 ;; Otherwise, replace AUTO with language or append language if
1373 ;; AUTO is not present.
1374 (replace-match
1375 (mapconcat (lambda (option) (if (equal "AUTO" option) language option))
1376 (cond ((member language options) (delete "AUTO" options))
1377 ((member "AUTO" options) options)
1378 (t (append options (list language))))
1379 ", ")
1380 t nil header 1)))))
1382 (defun org-latex-guess-polyglossia-language (header info)
1383 "Set the Polyglossia language according to the LANGUAGE keyword.
1385 HEADER is the LaTeX header string. INFO is the plist used as
1386 a communication channel.
1388 Insertion of guessed language only happens when the Polyglossia
1389 package has been explicitly loaded.
1391 The argument to Polyglossia may be \"AUTO\" which is then
1392 replaced with the language of the document or
1393 `org-export-default-language'. Note, the language is really set
1394 using \setdefaultlanguage and not as an option to the package.
1396 Return the new header."
1397 (let ((language (plist-get info :language)))
1398 ;; If no language is set or Polyglossia is not loaded, return
1399 ;; HEADER as-is.
1400 (if (or (not (stringp language))
1401 (not (string-match
1402 "\\\\usepackage\\(?:\\[\\([^]]+?\\)\\]\\){polyglossia}\n"
1403 header)))
1404 header
1405 (let* ((options (org-string-nw-p (match-string 1 header)))
1406 (languages (and options
1407 ;; Reverse as the last loaded language is
1408 ;; the main language.
1409 (nreverse
1410 (delete-dups
1411 (save-match-data
1412 (org-split-string
1413 (replace-regexp-in-string
1414 "AUTO" language options t)
1415 ",[ \t]*"))))))
1416 (main-language-set
1417 (string-match-p "\\\\setmainlanguage{.*?}" header)))
1418 (replace-match
1419 (concat "\\usepackage{polyglossia}\n"
1420 (mapconcat
1421 (lambda (l)
1422 (let ((l (or (assoc l org-latex-polyglossia-language-alist)
1423 l)))
1424 (format (if main-language-set "\\setotherlanguage%s{%s}\n"
1425 (setq main-language-set t)
1426 "\\setmainlanguage%s{%s}\n")
1427 (if (and (consp l) (= (length l) 3))
1428 (format "[variant=%s]" (nth 2 l))
1430 (nth 1 l))))
1431 languages
1432 ""))
1433 t t header 0)))))
1435 (defun org-latex--remove-packages (pkg-alist info)
1436 "Remove packages based on the current LaTeX compiler.
1438 If the fourth argument of an element is set in pkg-alist, and it
1439 is not a member of the LaTeX compiler of the document, the packages
1440 is removed. See also `org-latex-compiler'.
1442 Return modified pkg-alist."
1443 (let ((compiler (or (plist-get info :latex-compiler) "")))
1444 (if (member-ignore-case compiler org-latex-compilers)
1445 (delq nil
1446 (mapcar
1447 (lambda (pkg)
1448 (unless (and
1449 (listp pkg)
1450 (let ((third (nth 3 pkg)))
1451 (and third
1452 (not (member-ignore-case
1453 compiler
1454 (if (listp third) third (list third)))))))
1455 pkg))
1456 pkg-alist))
1457 pkg-alist)))
1459 (defun org-latex--find-verb-separator (s)
1460 "Return a character not used in string S.
1461 This is used to choose a separator for constructs like \\verb."
1462 (let ((ll "~,./?;':\"|!@#%^&-_=+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ<>()[]{}"))
1463 (cl-loop for c across ll
1464 when (not (string-match (regexp-quote (char-to-string c)) s))
1465 return (char-to-string c))))
1467 (defun org-latex--make-option-string (options)
1468 "Return a comma separated string of keywords and values.
1469 OPTIONS is an alist where the key is the options keyword as
1470 a string, and the value a list containing the keyword value, or
1471 nil."
1472 (mapconcat (lambda (pair)
1473 (pcase-let ((`(,keyword ,value) pair))
1474 (concat keyword
1475 (and (> (length value) 0)
1476 (concat "=" value)))))
1477 options
1478 ","))
1480 (defun org-latex--wrap-label (element output info)
1481 "Wrap label associated to ELEMENT around OUTPUT, if appropriate.
1482 INFO is the current export state, as a plist. This function
1483 should not be used for floats. See
1484 `org-latex--caption/label-string'."
1485 (if (not (and (org-string-nw-p output) (org-element-property :name element)))
1486 output
1487 (concat (format "\\phantomsection\n\\label{%s}\n"
1488 (org-latex--label element info))
1489 output)))
1491 (defun org-latex--protect-text (text)
1492 "Protect special characters in string TEXT and return it."
1493 (replace-regexp-in-string "[\\{}$%&_#~^]" "\\\\\\&" text))
1495 (defun org-latex--text-markup (text markup info)
1496 "Format TEXT depending on MARKUP text markup.
1497 INFO is a plist used as a communication channel. See
1498 `org-latex-text-markup-alist' for details."
1499 (let ((fmt (cdr (assq markup (plist-get info :latex-text-markup-alist)))))
1500 (cl-case fmt
1501 ;; No format string: Return raw text.
1502 ((nil) text)
1503 ;; Handle the `verb' special case: Find an appropriate separator
1504 ;; and use "\\verb" command.
1505 (verb
1506 (let ((separator (org-latex--find-verb-separator text)))
1507 (concat "\\verb"
1508 separator
1509 (replace-regexp-in-string "\n" " " text)
1510 separator)))
1511 ;; Handle the `protectedtexttt' special case: Protect some
1512 ;; special chars and use "\texttt{%s}" format string.
1513 (protectedtexttt
1514 (format "\\texttt{%s}"
1515 (replace-regexp-in-string
1516 "--\\|[\\{}$%&_#~^]"
1517 (lambda (m)
1518 (cond ((equal m "--") "-{}-")
1519 ((equal m "\\") "\\textbackslash{}")
1520 ((equal m "~") "\\textasciitilde{}")
1521 ((equal m "^") "\\textasciicircum{}")
1522 (t (org-latex--protect-text m))))
1523 text nil t)))
1524 ;; Else use format string.
1525 (t (format fmt text)))))
1527 (defun org-latex--delayed-footnotes-definitions (element info)
1528 "Return footnotes definitions in ELEMENT as a string.
1530 INFO is a plist used as a communication channel.
1532 Footnotes definitions are returned within \"\\footnotetext{}\"
1533 commands.
1535 This function is used within constructs that don't support
1536 \"\\footnote{}\" command (e.g., an item tag). In that case,
1537 \"\\footnotemark\" is used within the construct and the function
1538 just outside of it."
1539 (mapconcat
1540 (lambda (ref)
1541 (let ((def (org-export-get-footnote-definition ref info)))
1542 (format "\\footnotetext[%d]{%s%s}"
1543 (org-export-get-footnote-number ref info)
1544 (org-trim (org-latex--label def info t t))
1545 (org-trim (org-export-data def info)))))
1546 ;; Find every footnote reference in ELEMENT.
1547 (letrec ((all-refs nil)
1548 (search-refs
1549 (lambda (data)
1550 ;; Return a list of all footnote references never seen
1551 ;; before in DATA.
1552 (org-element-map data 'footnote-reference
1553 (lambda (ref)
1554 (when (org-export-footnote-first-reference-p ref info)
1555 (push ref all-refs)
1556 (when (eq (org-element-property :type ref) 'standard)
1557 (funcall search-refs
1558 (org-export-get-footnote-definition ref info)))))
1559 info)
1560 (reverse all-refs))))
1561 (funcall search-refs element))
1562 ""))
1564 (defun org-latex--translate (s info)
1565 "Translate string S according to specified language.
1566 INFO is a plist used as a communication channel."
1567 (org-export-translate s :latex info))
1569 (defun org-latex--format-spec (info)
1570 "Create a format-spec for document meta-data.
1571 INFO is a plist used as a communication channel."
1572 (let ((language (let ((lang (plist-get info :language)))
1573 (or (cdr (assoc-string lang org-latex-babel-language-alist t))
1574 (nth 1 (assoc-string lang org-latex-polyglossia-language-alist t))
1575 lang))))
1576 `((?a . ,(org-export-data (plist-get info :author) info))
1577 (?t . ,(org-export-data (plist-get info :title) info))
1578 (?k . ,(org-export-data (org-latex--wrap-latex-math-block
1579 (plist-get info :keywords) info)
1580 info))
1581 (?d . ,(org-export-data (org-latex--wrap-latex-math-block
1582 (plist-get info :description) info)
1583 info))
1584 (?c . ,(plist-get info :creator))
1585 (?l . ,language)
1586 (?L . ,(capitalize language))
1587 (?D . ,(org-export-get-date info)))))
1589 (defun org-latex--insert-compiler (info)
1590 "Insert LaTeX_compiler info into the document.
1591 INFO is a plist used as a communication channel."
1592 (let ((compiler (plist-get info :latex-compiler)))
1593 (and (org-string-nw-p org-latex-compiler-file-string)
1594 (member (or compiler "") org-latex-compilers)
1595 (format org-latex-compiler-file-string compiler))))
1598 ;;; Filters
1600 (defun org-latex-matrices-tree-filter (tree _backend info)
1601 (org-latex--wrap-latex-matrices tree info))
1603 (defun org-latex-math-block-tree-filter (tree _backend info)
1604 (org-latex--wrap-latex-math-block tree info))
1606 (defun org-latex-math-block-options-filter (info _backend)
1607 (dolist (prop '(:author :date :title) info)
1608 (plist-put info prop
1609 (org-latex--wrap-latex-math-block (plist-get info prop) info))))
1611 (defun org-latex-clean-invalid-line-breaks (data _backend _info)
1612 (replace-regexp-in-string
1613 "\\(\\end{[A-Za-z0-9*]+}\\|^\\)[ \t]*\\\\\\\\[ \t]*$" "\\1"
1614 data))
1617 ;;; Template
1619 ;;;###autoload
1620 (defun org-latex-make-preamble (info &optional template)
1621 "Return a formatted LaTeX preamble.
1622 INFO is a plist used as a communication channel. Optional
1623 argument TEMPLATE, when non-nil, is the header template string,
1624 as expected by `org-splice-latex-header'."
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)
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 "\\rule{%s}{%s}"
2056 (or (plist-get attr :width) "\\linewidth")
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-image-link-filter (data _backend info)
2293 (org-export-insert-image-links data info org-latex-inline-image-rules))
2295 (defun org-latex--inline-image (link info)
2296 "Return LaTeX code for an inline image.
2297 LINK is the link pointing to the inline image. INFO is a plist
2298 used as a communication channel."
2299 (let* ((parent (org-export-get-parent-element link))
2300 (path (let ((raw-path (org-element-property :path link)))
2301 (if (not (file-name-absolute-p raw-path)) raw-path
2302 (expand-file-name raw-path))))
2303 (filetype (file-name-extension path))
2304 (caption (org-latex--caption/label-string parent info))
2305 (caption-above-p (org-latex--caption-above-p link info))
2306 ;; Retrieve latex attributes from the element around.
2307 (attr (org-export-read-attribute :attr_latex parent))
2308 (float (let ((float (plist-get attr :float)))
2309 (cond ((string= float "wrap") 'wrap)
2310 ((string= float "sideways") 'sideways)
2311 ((string= float "multicolumn") 'multicolumn)
2312 ((and (plist-member attr :float) (not float)) 'nonfloat)
2313 ((or float
2314 (org-element-property :caption parent)
2315 (org-string-nw-p (plist-get attr :caption)))
2316 'figure)
2317 (t 'nonfloat))))
2318 (placement
2319 (let ((place (plist-get attr :placement)))
2320 (cond
2321 (place (format "%s" place))
2322 ((eq float 'wrap) "{l}{0.5\\textwidth}")
2323 ((eq float 'figure)
2324 (format "[%s]" (plist-get info :latex-default-figure-position)))
2325 (t ""))))
2326 (center
2327 (if (plist-member attr :center) (plist-get attr :center)
2328 (plist-get info :latex-images-centered)))
2329 (comment-include (if (plist-get attr :comment-include) "%" ""))
2330 ;; It is possible to specify width and height in the
2331 ;; ATTR_LATEX line, and also via default variables.
2332 (width (cond ((plist-get attr :width))
2333 ((plist-get attr :height) "")
2334 ((eq float 'wrap) "0.48\\textwidth")
2335 (t (plist-get info :latex-image-default-width))))
2336 (height (cond ((plist-get attr :height))
2337 ((or (plist-get attr :width)
2338 (memq float '(figure wrap))) "")
2339 (t (plist-get info :latex-image-default-height))))
2340 (options (let ((opt (or (plist-get attr :options)
2341 (plist-get info :latex-image-default-option))))
2342 (if (not (string-match "\\`\\[\\(.*\\)\\]\\'" opt)) opt
2343 (match-string 1 opt))))
2344 image-code)
2345 (if (member filetype '("tikz" "pgf"))
2346 ;; For tikz images:
2347 ;; - use \input to read in image file.
2348 ;; - if options are present, wrap in a tikzpicture environment.
2349 ;; - if width or height are present, use \resizebox to change
2350 ;; the image size.
2351 (progn
2352 (setq image-code (format "\\input{%s}" path))
2353 (when (org-string-nw-p options)
2354 (setq image-code
2355 (format "\\begin{tikzpicture}[%s]\n%s\n\\end{tikzpicture}"
2356 options
2357 image-code)))
2358 (when (or (org-string-nw-p width) (org-string-nw-p height))
2359 (setq image-code (format "\\resizebox{%s}{%s}{%s}"
2360 (if (org-string-nw-p width) width "!")
2361 (if (org-string-nw-p height) height "!")
2362 image-code))))
2363 ;; For other images:
2364 ;; - add width and height to options.
2365 ;; - include the image with \includegraphics.
2366 (when (org-string-nw-p width)
2367 (setq options (concat options ",width=" width)))
2368 (when (org-string-nw-p height)
2369 (setq options (concat options ",height=" height)))
2370 (let ((search-option (org-element-property :search-option link)))
2371 (when (and search-option
2372 (equal filetype "pdf")
2373 (string-match-p "\\`[0-9]+\\'" search-option)
2374 (not (string-match-p "page=" options)))
2375 (setq options (concat options ",page=" search-option))))
2376 (setq image-code
2377 (format "\\includegraphics%s{%s}"
2378 (cond ((not (org-string-nw-p options)) "")
2379 ((string-prefix-p "," options)
2380 (format "[%s]" (substring options 1)))
2381 (t (format "[%s]" options)))
2382 path))
2383 (when (equal filetype "svg")
2384 (setq image-code (replace-regexp-in-string "^\\\\includegraphics"
2385 "\\includesvg"
2386 image-code
2387 nil t))
2388 (setq image-code (replace-regexp-in-string "\\.svg}"
2390 image-code
2391 nil t))))
2392 ;; Return proper string, depending on FLOAT.
2393 (pcase float
2394 (`wrap (format "\\begin{wrapfigure}%s
2395 %s%s
2396 %s%s
2397 %s\\end{wrapfigure}"
2398 placement
2399 (if caption-above-p caption "")
2400 (if center "\\centering" "")
2401 comment-include image-code
2402 (if caption-above-p "" caption)))
2403 (`sideways (format "\\begin{sidewaysfigure}
2404 %s%s
2405 %s%s
2406 %s\\end{sidewaysfigure}"
2407 (if caption-above-p caption "")
2408 (if center "\\centering" "")
2409 comment-include image-code
2410 (if caption-above-p "" caption)))
2411 (`multicolumn (format "\\begin{figure*}%s
2412 %s%s
2413 %s%s
2414 %s\\end{figure*}"
2415 placement
2416 (if caption-above-p caption "")
2417 (if center "\\centering" "")
2418 comment-include image-code
2419 (if caption-above-p "" caption)))
2420 (`figure (format "\\begin{figure}%s
2421 %s%s
2422 %s%s
2423 %s\\end{figure}"
2424 placement
2425 (if caption-above-p caption "")
2426 (if center "\\centering" "")
2427 comment-include image-code
2428 (if caption-above-p "" caption)))
2429 ((guard center)
2430 (format "\\begin{center}
2431 %s%s
2432 %s\\end{center}"
2433 (if caption-above-p caption "")
2434 image-code
2435 (if caption-above-p "" caption)))
2437 (concat (if caption-above-p caption "")
2438 image-code
2439 (if caption-above-p caption ""))))))
2441 (defun org-latex-link (link desc info)
2442 "Transcode a LINK object from Org to LaTeX.
2444 DESC is the description part of the link, or the empty string.
2445 INFO is a plist holding contextual information. See
2446 `org-export-data'."
2447 (let* ((type (org-element-property :type link))
2448 (raw-path (org-element-property :path link))
2449 ;; Ensure DESC really exists, or set it to nil.
2450 (desc (and (not (string= desc "")) desc))
2451 (imagep (org-export-inline-image-p
2452 link (plist-get info :latex-inline-image-rules)))
2453 (path (org-latex--protect-text
2454 (cond ((member type '("http" "https" "ftp" "mailto" "doi"))
2455 (concat type ":" raw-path))
2456 ((string= type "file") (org-export-file-uri raw-path))
2457 (t raw-path)))))
2458 (cond
2459 ;; Link type is handled by a special function.
2460 ((org-export-custom-protocol-maybe link desc 'latex))
2461 ;; Image file.
2462 (imagep (org-latex--inline-image link info))
2463 ;; Radio link: Transcode target's contents and use them as link's
2464 ;; description.
2465 ((string= type "radio")
2466 (let ((destination (org-export-resolve-radio-link link info)))
2467 (if (not destination) desc
2468 (format "\\hyperref[%s]{%s}"
2469 (org-export-get-reference destination info)
2470 desc))))
2471 ;; Links pointing to a headline: Find destination and build
2472 ;; appropriate referencing command.
2473 ((member type '("custom-id" "fuzzy" "id"))
2474 (let ((destination (if (string= type "fuzzy")
2475 (org-export-resolve-fuzzy-link link info)
2476 (org-export-resolve-id-link link info))))
2477 (cl-case (org-element-type destination)
2478 ;; Id link points to an external file.
2479 (plain-text
2480 (if desc (format "\\href{%s}{%s}" destination desc)
2481 (format "\\url{%s}" destination)))
2482 ;; Fuzzy link points nowhere.
2483 ((nil)
2484 (format (plist-get info :latex-link-with-unknown-path-format)
2485 (or desc
2486 (org-export-data
2487 (org-element-property :raw-link link) info))))
2488 ;; LINK points to a headline. If headlines are numbered
2489 ;; and the link has no description, display headline's
2490 ;; number. Otherwise, display description or headline's
2491 ;; title.
2492 (headline
2493 (let ((label (org-latex--label destination info t)))
2494 (if (and (not desc)
2495 (org-export-numbered-headline-p destination info))
2496 (format "\\ref{%s}" label)
2497 (format "\\hyperref[%s]{%s}" label
2498 (or desc
2499 (org-export-data
2500 (org-element-property :title destination) info))))))
2501 ;; Fuzzy link points to a target. Do as above.
2502 (otherwise
2503 (let ((ref (org-latex--label destination info t)))
2504 (if (not desc) (format "\\ref{%s}" ref)
2505 (format "\\hyperref[%s]{%s}" ref desc)))))))
2506 ;; Coderef: replace link with the reference name or the
2507 ;; equivalent line number.
2508 ((string= type "coderef")
2509 (format (org-export-get-coderef-format path desc)
2510 (org-export-resolve-coderef path info)))
2511 ;; External link with a description part.
2512 ((and path desc) (format "\\href{%s}{%s}" path desc))
2513 ;; External link without a description part.
2514 (path (format "\\url{%s}" path))
2515 ;; No path, only description. Try to do something useful.
2516 (t (format (plist-get info :latex-link-with-unknown-path-format) desc)))))
2519 ;;;; Node Property
2521 (defun org-latex-node-property (node-property _contents _info)
2522 "Transcode a NODE-PROPERTY element from Org to LaTeX.
2523 CONTENTS is nil. INFO is a plist holding contextual
2524 information."
2525 (format "%s:%s"
2526 (org-element-property :key node-property)
2527 (let ((value (org-element-property :value node-property)))
2528 (if value (concat " " value) ""))))
2531 ;;;; Paragraph
2533 (defun org-latex-paragraph (_paragraph contents _info)
2534 "Transcode a PARAGRAPH element from Org to LaTeX.
2535 CONTENTS is the contents of the paragraph, as a string. INFO is
2536 the plist used as a communication channel."
2537 contents)
2540 ;;;; Plain List
2542 (defun org-latex-plain-list (plain-list contents info)
2543 "Transcode a PLAIN-LIST element from Org to LaTeX.
2544 CONTENTS is the contents of the list. INFO is a plist holding
2545 contextual information."
2546 (let* ((type (org-element-property :type plain-list))
2547 (attr (org-export-read-attribute :attr_latex plain-list))
2548 (latex-type (let ((env (plist-get attr :environment)))
2549 (cond (env (format "%s" env))
2550 ((eq type 'ordered) "enumerate")
2551 ((eq type 'descriptive) "description")
2552 (t "itemize")))))
2553 (org-latex--wrap-label
2554 plain-list
2555 (format "\\begin{%s}%s\n%s\\end{%s}"
2556 latex-type
2557 (or (plist-get attr :options) "")
2558 contents
2559 latex-type)
2560 info)))
2563 ;;;; Plain Text
2565 (defun org-latex-plain-text (text info)
2566 "Transcode a TEXT string from Org to LaTeX.
2567 TEXT is the string to transcode. INFO is a plist holding
2568 contextual information."
2569 (let* ((specialp (plist-get info :with-special-strings))
2570 (output
2571 ;; Turn LaTeX into \LaTeX{} and TeX into \TeX{}.
2572 (let ((case-fold-search nil))
2573 (replace-regexp-in-string
2574 "\\<\\(?:La\\)?TeX\\>" "\\\\\\&{}"
2575 ;; Protect ^, ~, %, #, &, $, _, { and }. Also protect \.
2576 ;; However, if special strings are used, be careful not
2577 ;; to protect "\" in "\-" constructs.
2578 (replace-regexp-in-string
2579 (concat "[%$#&{}_~^]\\|\\\\" (and specialp "\\([^-]\\|$\\)"))
2580 (lambda (m)
2581 (cl-case (string-to-char m)
2582 (?\\ "$\\\\backslash$\\1")
2583 (?~ "\\\\textasciitilde{}")
2584 (?^ "\\\\^{}")
2585 (t "\\\\\\&")))
2586 text)))))
2587 ;; Activate smart quotes. Be sure to provide original TEXT string
2588 ;; since OUTPUT may have been modified.
2589 (when (plist-get info :with-smart-quotes)
2590 (setq output (org-export-activate-smart-quotes output :latex info text)))
2591 ;; Convert special strings.
2592 (when specialp
2593 (setq output (replace-regexp-in-string "\\.\\.\\." "\\\\ldots{}" output)))
2594 ;; Handle break preservation if required.
2595 (when (plist-get info :preserve-breaks)
2596 (setq output (replace-regexp-in-string
2597 "\\(?:[ \t]*\\\\\\\\\\)?[ \t]*\n" "\\\\\n" output nil t)))
2598 ;; Return value.
2599 output))
2602 ;;;; Planning
2604 (defun org-latex-planning (planning _contents info)
2605 "Transcode a PLANNING element from Org to LaTeX.
2606 CONTENTS is nil. INFO is a plist holding contextual
2607 information."
2608 (concat
2609 "\\noindent"
2610 (mapconcat
2611 'identity
2612 (delq nil
2613 (list
2614 (let ((closed (org-element-property :closed planning)))
2615 (when closed
2616 (concat
2617 (format "\\textbf{%s} " org-closed-string)
2618 (format (plist-get info :latex-inactive-timestamp-format)
2619 (org-timestamp-translate closed)))))
2620 (let ((deadline (org-element-property :deadline planning)))
2621 (when deadline
2622 (concat
2623 (format "\\textbf{%s} " org-deadline-string)
2624 (format (plist-get info :latex-active-timestamp-format)
2625 (org-timestamp-translate deadline)))))
2626 (let ((scheduled (org-element-property :scheduled planning)))
2627 (when scheduled
2628 (concat
2629 (format "\\textbf{%s} " org-scheduled-string)
2630 (format (plist-get info :latex-active-timestamp-format)
2631 (org-timestamp-translate scheduled)))))))
2632 " ")
2633 "\\\\"))
2636 ;;;; Property Drawer
2638 (defun org-latex-property-drawer (_property-drawer contents _info)
2639 "Transcode a PROPERTY-DRAWER element from Org to LaTeX.
2640 CONTENTS holds the contents of the drawer. INFO is a plist
2641 holding contextual information."
2642 (and (org-string-nw-p contents)
2643 (format "\\begin{verbatim}\n%s\\end{verbatim}" contents)))
2646 ;;;; Pseudo Element: LaTeX Matrices
2648 ;; `latex-matrices' elements have the following properties:
2649 ;; `:caption', `:post-blank' and `:markup' (`inline', `equation' or
2650 ;; `math').
2652 (defun org-latex--wrap-latex-matrices (data info)
2653 "Merge contiguous tables with the same mode within a pseudo-element.
2654 DATA is a parse tree or a secondary string. INFO is a plist
2655 containing export options. Modify DATA by side-effect and return
2656 it."
2657 (org-element-map data 'table
2658 (lambda (table)
2659 (when (eq (org-element-property :type table) 'org)
2660 (let ((mode (or (org-export-read-attribute :attr_latex table :mode)
2661 (plist-get info :latex-default-table-mode))))
2662 (when (and (member mode '("inline-math" "math"))
2663 ;; Do not wrap twice the same table.
2664 (not (eq (org-element-type
2665 (org-element-property :parent table))
2666 'latex-matrices)))
2667 (let* ((caption (and (not (string= mode "inline-math"))
2668 (org-element-property :caption table)))
2669 (matrices
2670 (list 'latex-matrices
2671 (list :caption caption
2672 :markup
2673 (cond ((string= mode "inline-math") 'inline)
2674 (caption 'equation)
2675 (t 'math)))))
2676 (previous table)
2677 (next (org-export-get-next-element table info)))
2678 (org-element-insert-before matrices table)
2679 ;; Swallow all contiguous tables sharing the same mode.
2680 (while (and
2681 (zerop (or (org-element-property :post-blank previous) 0))
2682 (setq next (org-export-get-next-element previous info))
2683 (eq (org-element-type next) 'table)
2684 (eq (org-element-property :type next) 'org)
2685 (string= (or (org-export-read-attribute
2686 :attr_latex next :mode)
2687 (plist-get info :latex-default-table-mode))
2688 mode))
2689 (org-element-extract-element previous)
2690 (org-element-adopt-elements matrices previous)
2691 (setq previous next))
2692 ;; Inherit `:post-blank' from the value of the last
2693 ;; swallowed table. Set the latter's `:post-blank'
2694 ;; value to 0 so as to not duplicate empty lines.
2695 (org-element-put-property
2696 matrices :post-blank (org-element-property :post-blank previous))
2697 (org-element-put-property previous :post-blank 0)
2698 (org-element-extract-element previous)
2699 (org-element-adopt-elements matrices previous))))))
2700 info)
2701 data)
2703 (defun org-latex-matrices (matrices contents _info)
2704 "Transcode a MATRICES element from Org to LaTeX.
2705 CONTENTS is a string. INFO is a plist used as a communication
2706 channel."
2707 (format (cl-case (org-element-property :markup matrices)
2708 (inline "\\(%s\\)")
2709 (equation "\\begin{equation}\n%s\\end{equation}")
2710 (t "\\[\n%s\\]"))
2711 contents))
2714 ;;;; Pseudo Object: LaTeX Math Block
2716 ;; `latex-math-block' objects have the following property:
2717 ;; `:post-blank'.
2719 (defun org-latex--wrap-latex-math-block (data info)
2720 "Merge contiguous math objects in a pseudo-object container.
2721 DATA is a parse tree or a secondary string. INFO is a plist
2722 containing export options. Modify DATA by side-effect and return it."
2723 (let ((valid-object-p
2724 ;; Non-nil when OBJ can be added to the latex math block B.
2725 (lambda (obj b)
2726 (pcase (org-element-type obj)
2727 (`entity (org-element-property :latex-math-p obj))
2728 (`latex-fragment
2729 (let ((value (org-element-property :value obj)))
2730 (or (string-prefix-p "\\(" value)
2731 (string-match-p "\\`\\$[^$]" value))))
2732 ((and type (or `subscript `superscript))
2733 (not (memq type (mapcar #'org-element-type
2734 (org-element-contents b)))))))))
2735 (org-element-map data '(entity latex-fragment subscript superscript)
2736 (lambda (object)
2737 ;; Skip objects already wrapped.
2738 (when (and (not (eq (org-element-type
2739 (org-element-property :parent object))
2740 'latex-math-block))
2741 (funcall valid-object-p object nil))
2742 (let ((math-block (list 'latex-math-block nil))
2743 (next-elements (org-export-get-next-element object info t))
2744 (last object))
2745 ;; Wrap MATH-BLOCK around OBJECT in DATA.
2746 (org-element-insert-before math-block object)
2747 (org-element-extract-element object)
2748 (org-element-adopt-elements math-block object)
2749 (when (zerop (or (org-element-property :post-blank object) 0))
2750 ;; MATH-BLOCK swallows consecutive math objects.
2751 (catch 'exit
2752 (dolist (next next-elements)
2753 (unless (funcall valid-object-p next math-block)
2754 (throw 'exit nil))
2755 (org-element-extract-element next)
2756 (org-element-adopt-elements math-block next)
2757 ;; Eschew the case: \beta$x$ -> \(\betax\).
2758 (unless (memq (org-element-type next)
2759 '(subscript superscript))
2760 (org-element-put-property last :post-blank 1))
2761 (setq last next)
2762 (when (> (or (org-element-property :post-blank next) 0) 0)
2763 (throw 'exit nil)))))
2764 (org-element-put-property
2765 math-block :post-blank (org-element-property :post-blank last)))))
2766 info nil '(subscript superscript latex-math-block) t)
2767 ;; Return updated DATA.
2768 data))
2770 (defun org-latex-math-block (_math-block contents _info)
2771 "Transcode a MATH-BLOCK object from Org to LaTeX.
2772 CONTENTS is a string. INFO is a plist used as a communication
2773 channel."
2774 (when (org-string-nw-p contents)
2775 (format "\\(%s\\)" (org-trim contents))))
2777 ;;;; Quote Block
2779 (defun org-latex-quote-block (quote-block contents info)
2780 "Transcode a QUOTE-BLOCK element from Org to LaTeX.
2781 CONTENTS holds the contents of the block. INFO is a plist
2782 holding contextual information."
2783 (org-latex--wrap-label
2784 quote-block (format "\\begin{quote}\n%s\\end{quote}" contents) info))
2787 ;;;; Radio Target
2789 (defun org-latex-radio-target (radio-target text info)
2790 "Transcode a RADIO-TARGET object from Org to LaTeX.
2791 TEXT is the text of the target. INFO is a plist holding
2792 contextual information."
2793 (format "\\label{%s}%s" (org-export-get-reference radio-target info) text))
2796 ;;;; Section
2798 (defun org-latex-section (_section contents _info)
2799 "Transcode a SECTION element from Org to LaTeX.
2800 CONTENTS holds the contents of the section. INFO is a plist
2801 holding contextual information."
2802 contents)
2805 ;;;; Special Block
2807 (defun org-latex-special-block (special-block contents info)
2808 "Transcode a SPECIAL-BLOCK element from Org to LaTeX.
2809 CONTENTS holds the contents of the block. INFO is a plist
2810 holding contextual information."
2811 (let ((type (org-element-property :type special-block))
2812 (opt (org-export-read-attribute :attr_latex special-block :options))
2813 (caption (org-latex--caption/label-string special-block info))
2814 (caption-above-p (org-latex--caption-above-p special-block info)))
2815 (concat (format "\\begin{%s}%s\n" type (or opt ""))
2816 (and caption-above-p caption)
2817 contents
2818 (and (not caption-above-p) caption)
2819 (format "\\end{%s}" type))))
2822 ;;;; Src Block
2824 (defun org-latex-src-block (src-block _contents info)
2825 "Transcode a SRC-BLOCK element from Org to LaTeX.
2826 CONTENTS holds the contents of the item. INFO is a plist holding
2827 contextual information."
2828 (when (org-string-nw-p (org-element-property :value src-block))
2829 (let* ((lang (org-element-property :language src-block))
2830 (caption (org-element-property :caption src-block))
2831 (caption-above-p (org-latex--caption-above-p src-block info))
2832 (label (org-element-property :name src-block))
2833 (custom-env (and lang
2834 (cadr (assq (intern lang)
2835 org-latex-custom-lang-environments))))
2836 (num-start (org-export-get-loc src-block info))
2837 (retain-labels (org-element-property :retain-labels src-block))
2838 (attributes (org-export-read-attribute :attr_latex src-block))
2839 (float (plist-get attributes :float))
2840 (listings (plist-get info :latex-listings)))
2841 (cond
2842 ;; Case 1. No source fontification.
2843 ((not listings)
2844 (let* ((caption-str (org-latex--caption/label-string src-block info))
2845 (float-env
2846 (cond ((string= "multicolumn" float)
2847 (format "\\begin{figure*}[%s]\n%s%%s\n%s\\end{figure*}"
2848 (plist-get info :latex-default-figure-position)
2849 (if caption-above-p caption-str "")
2850 (if caption-above-p "" caption-str)))
2851 (caption (concat
2852 (if caption-above-p caption-str "")
2853 "%s"
2854 (if caption-above-p "" (concat "\n" caption-str))))
2855 (t "%s"))))
2856 (format
2857 float-env
2858 (concat (format "\\begin{verbatim}\n%s\\end{verbatim}"
2859 (org-export-format-code-default src-block info))))))
2860 ;; Case 2. Custom environment.
2861 (custom-env
2862 (let ((caption-str (org-latex--caption/label-string src-block info))
2863 (formatted-src (org-export-format-code-default src-block info)))
2864 (if (string-match-p "\\`[a-zA-Z0-9]+\\'" custom-env)
2865 (format "\\begin{%s}\n%s\\end{%s}\n"
2866 custom-env
2867 (concat (and caption-above-p caption-str)
2868 formatted-src
2869 (and (not caption-above-p) caption-str))
2870 custom-env)
2871 (format-spec custom-env
2872 `((?s . ,formatted-src)
2873 (?c . ,caption)
2874 (?f . ,float)
2875 (?l . ,(org-latex--label src-block info))
2876 (?o . ,(or (plist-get attributes :options) "")))))))
2877 ;; Case 3. Use minted package.
2878 ((eq listings 'minted)
2879 (let* ((caption-str (org-latex--caption/label-string src-block info))
2880 (float-env
2881 (cond
2882 ((string= "multicolumn" float)
2883 (format "\\begin{listing*}\n%s%%s\n%s\\end{listing*}"
2884 (if caption-above-p caption-str "")
2885 (if caption-above-p "" caption-str)))
2886 (caption
2887 (concat (if caption-above-p caption-str "")
2888 "%s"
2889 (if caption-above-p "" (concat "\n" caption-str))))
2890 (t "%s")))
2891 (options (plist-get info :latex-minted-options))
2892 (body
2893 (format
2894 "\\begin{minted}[%s]{%s}\n%s\\end{minted}"
2895 ;; Options.
2896 (concat
2897 (org-latex--make-option-string
2898 (if (or (not num-start) (assoc "linenos" options))
2899 options
2900 (append
2901 `(("linenos")
2902 ("firstnumber" ,(number-to-string (1+ num-start))))
2903 options)))
2904 (let ((local-options (plist-get attributes :options)))
2905 (and local-options (concat "," local-options))))
2906 ;; Language.
2907 (or (cadr (assq (intern lang)
2908 (plist-get info :latex-minted-langs)))
2909 (downcase lang))
2910 ;; Source code.
2911 (let* ((code-info (org-export-unravel-code src-block))
2912 (max-width
2913 (apply 'max
2914 (mapcar 'length
2915 (org-split-string (car code-info)
2916 "\n")))))
2917 (org-export-format-code
2918 (car code-info)
2919 (lambda (loc _num ref)
2920 (concat
2922 (when ref
2923 ;; Ensure references are flushed to the right,
2924 ;; separated with 6 spaces from the widest line
2925 ;; of code.
2926 (concat (make-string (+ (- max-width (length loc)) 6)
2927 ?\s)
2928 (format "(%s)" ref)))))
2929 nil (and retain-labels (cdr code-info)))))))
2930 ;; Return value.
2931 (format float-env body)))
2932 ;; Case 4. Use listings package.
2934 (let ((lst-lang
2935 (or (cadr (assq (intern lang)
2936 (plist-get info :latex-listings-langs)))
2937 lang))
2938 (caption-str
2939 (when caption
2940 (let ((main (org-export-get-caption src-block))
2941 (secondary (org-export-get-caption src-block t)))
2942 (if (not secondary)
2943 (format "{%s}" (org-export-data main info))
2944 (format "{[%s]%s}"
2945 (org-export-data secondary info)
2946 (org-export-data main info))))))
2947 (lst-opt (plist-get info :latex-listings-options)))
2948 (concat
2949 ;; Options.
2950 (format
2951 "\\lstset{%s}\n"
2952 (concat
2953 (org-latex--make-option-string
2954 (append
2955 lst-opt
2956 (cond
2957 ((and (not float) (plist-member attributes :float)) nil)
2958 ((string= "multicolumn" float) '(("float" "*")))
2959 ((and float (not (assoc "float" lst-opt)))
2960 `(("float" ,(plist-get info :latex-default-figure-position)))))
2961 `(("language" ,lst-lang))
2962 (if label
2963 `(("label" ,(org-latex--label src-block info)))
2964 '(("label" " ")))
2965 (if caption-str `(("caption" ,caption-str)) '(("caption" " ")))
2966 `(("captionpos" ,(if caption-above-p "t" "b")))
2967 (cond ((assoc "numbers" lst-opt) nil)
2968 ((not num-start) '(("numbers" "none")))
2969 (t `(("firstnumber" ,(number-to-string (1+ num-start)))
2970 ("numbers" "left"))))))
2971 (let ((local-options (plist-get attributes :options)))
2972 (and local-options (concat "," local-options)))))
2973 ;; Source code.
2974 (format
2975 "\\begin{lstlisting}\n%s\\end{lstlisting}"
2976 (let* ((code-info (org-export-unravel-code src-block))
2977 (max-width
2978 (apply 'max
2979 (mapcar 'length
2980 (org-split-string (car code-info) "\n")))))
2981 (org-export-format-code
2982 (car code-info)
2983 (lambda (loc _num ref)
2984 (concat
2986 (when ref
2987 ;; Ensure references are flushed to the right,
2988 ;; separated with 6 spaces from the widest line of
2989 ;; code
2990 (concat (make-string (+ (- max-width (length loc)) 6) ?\s)
2991 (format "(%s)" ref)))))
2992 nil (and retain-labels (cdr code-info))))))))))))
2995 ;;;; Statistics Cookie
2997 (defun org-latex-statistics-cookie (statistics-cookie _contents _info)
2998 "Transcode a STATISTICS-COOKIE object from Org to LaTeX.
2999 CONTENTS is nil. INFO is a plist holding contextual information."
3000 (replace-regexp-in-string
3001 "%" "\\%" (org-element-property :value statistics-cookie) nil t))
3004 ;;;; Strike-Through
3006 (defun org-latex-strike-through (_strike-through contents info)
3007 "Transcode STRIKE-THROUGH from Org to LaTeX.
3008 CONTENTS is the text with strike-through markup. INFO is a plist
3009 holding contextual information."
3010 (org-latex--text-markup contents 'strike-through info))
3013 ;;;; Subscript
3015 (defun org-latex--script-size (object info)
3016 "Transcode a subscript or superscript object.
3017 OBJECT is an Org object. INFO is a plist used as a communication
3018 channel."
3019 (let ((output ""))
3020 (org-element-map (org-element-contents object)
3021 (cons 'plain-text org-element-all-objects)
3022 (lambda (obj)
3023 (cl-case (org-element-type obj)
3024 ((entity latex-fragment)
3025 (let ((data (org-trim (org-export-data obj info))))
3026 (string-match
3027 "\\`\\(?:\\\\[([]\\|\\$+\\)?\\(.*?\\)\\(?:\\\\[])]\\|\\$+\\)?\\'"
3028 data)
3029 (setq output
3030 (concat output
3031 (match-string 1 data)
3032 (let ((blank (org-element-property :post-blank obj)))
3033 (and blank (> blank 0) "\\ "))))))
3034 (plain-text
3035 (setq output
3036 (format "%s\\text{%s}" output (org-export-data obj info))))
3037 (otherwise
3038 (setq output
3039 (concat output
3040 (org-export-data obj info)
3041 (let ((blank (org-element-property :post-blank obj)))
3042 (and blank (> blank 0) "\\ ")))))))
3043 info nil org-element-recursive-objects)
3044 ;; Result. Do not wrap into curly brackets if OUTPUT is a single
3045 ;; character.
3046 (concat (if (eq (org-element-type object) 'subscript) "_" "^")
3047 (and (> (length output) 1) "{")
3048 output
3049 (and (> (length output) 1) "}"))))
3051 (defun org-latex-subscript (subscript _contents info)
3052 "Transcode a SUBSCRIPT object from Org to LaTeX.
3053 CONTENTS is the contents of the object. INFO is a plist holding
3054 contextual information."
3055 (org-latex--script-size subscript info))
3058 ;;;; Superscript
3060 (defun org-latex-superscript (superscript _contents info)
3061 "Transcode a SUPERSCRIPT object from Org to LaTeX.
3062 CONTENTS is the contents of the object. INFO is a plist holding
3063 contextual information."
3064 (org-latex--script-size superscript info))
3067 ;;;; Table
3069 ;; `org-latex-table' is the entry point for table transcoding. It
3070 ;; takes care of tables with a "verbatim" mode. Otherwise, it
3071 ;; delegates the job to either `org-latex--table.el-table',
3072 ;; `org-latex--org-table' or `org-latex--math-table' functions,
3073 ;; depending of the type of the table and the mode requested.
3075 ;; `org-latex--align-string' is a subroutine used to build alignment
3076 ;; string for Org tables.
3078 (defun org-latex-table (table contents info)
3079 "Transcode a TABLE element from Org to LaTeX.
3080 CONTENTS is the contents of the table. INFO is a plist holding
3081 contextual information."
3082 (if (eq (org-element-property :type table) 'table.el)
3083 ;; "table.el" table. Convert it using appropriate tools.
3084 (org-latex--table.el-table table info)
3085 (let ((type (or (org-export-read-attribute :attr_latex table :mode)
3086 (plist-get info :latex-default-table-mode))))
3087 (cond
3088 ;; Case 1: Verbatim table.
3089 ((string= type "verbatim")
3090 (format "\\begin{verbatim}\n%s\n\\end{verbatim}"
3091 ;; Re-create table, without affiliated keywords.
3092 (org-trim (org-element-interpret-data
3093 `(table nil ,@(org-element-contents table))))))
3094 ;; Case 2: Matrix.
3095 ((or (string= type "math") (string= type "inline-math"))
3096 (org-latex--math-table table info))
3097 ;; Case 3: Standard table.
3098 (t (concat (org-latex--org-table table contents info)
3099 ;; When there are footnote references within the
3100 ;; table, insert their definition just after it.
3101 (org-latex--delayed-footnotes-definitions table info)))))))
3103 (defun org-latex--align-string (table info)
3104 "Return an appropriate LaTeX alignment string.
3105 TABLE is the considered table. INFO is a plist used as
3106 a communication channel."
3107 (or (org-export-read-attribute :attr_latex table :align)
3108 (let (align)
3109 ;; Extract column groups and alignment from first (non-rule)
3110 ;; row.
3111 (org-element-map
3112 (org-element-map table 'table-row
3113 (lambda (row)
3114 (and (eq (org-element-property :type row) 'standard) row))
3115 info 'first-match)
3116 'table-cell
3117 (lambda (cell)
3118 (let ((borders (org-export-table-cell-borders cell info)))
3119 ;; Check left border for the first cell only.
3120 (when (and (memq 'left borders) (not align))
3121 (push "|" align))
3122 (push (cl-case (org-export-table-cell-alignment cell info)
3123 (left "l")
3124 (right "r")
3125 (center "c"))
3126 align)
3127 (when (memq 'right borders) (push "|" align))))
3128 info)
3129 (apply 'concat (nreverse align)))))
3131 (defun org-latex--org-table (table contents info)
3132 "Return appropriate LaTeX code for an Org table.
3134 TABLE is the table type element to transcode. CONTENTS is its
3135 contents, as a string. INFO is a plist used as a communication
3136 channel.
3138 This function assumes TABLE has `org' as its `:type' property and
3139 `table' as its `:mode' attribute."
3140 (let* ((caption (org-latex--caption/label-string table info))
3141 (attr (org-export-read-attribute :attr_latex table))
3142 ;; Determine alignment string.
3143 (alignment (org-latex--align-string table info))
3144 ;; Determine environment for the table: longtable, tabular...
3145 (table-env (or (plist-get attr :environment)
3146 (plist-get info :latex-default-table-environment)))
3147 ;; If table is a float, determine environment: table, table*
3148 ;; or sidewaystable.
3149 (float-env (unless (member table-env '("longtable" "longtabu"))
3150 (let ((float (plist-get attr :float)))
3151 (cond
3152 ((and (not float) (plist-member attr :float)) nil)
3153 ((or (string= float "sidewaystable")
3154 (string= float "sideways")) "sidewaystable")
3155 ((string= float "multicolumn") "table*")
3156 ((or float
3157 (org-element-property :caption table)
3158 (org-string-nw-p (plist-get attr :caption)))
3159 "table")))))
3160 ;; Extract others display options.
3161 (fontsize (let ((font (plist-get attr :font)))
3162 (and font (concat font "\n"))))
3163 ;; "tabular" environment doesn't allow to define a width.
3164 (width (and (not (equal table-env "tabular")) (plist-get attr :width)))
3165 (spreadp (plist-get attr :spread))
3166 (placement
3167 (or (plist-get attr :placement)
3168 (format "[%s]" (plist-get info :latex-default-figure-position))))
3169 (centerp (if (plist-member attr :center) (plist-get attr :center)
3170 (plist-get info :latex-tables-centered)))
3171 (caption-above-p (org-latex--caption-above-p table info)))
3172 ;; Prepare the final format string for the table.
3173 (cond
3174 ;; Longtable.
3175 ((equal "longtable" table-env)
3176 (concat (and fontsize (concat "{" fontsize))
3177 (format "\\begin{longtable}{%s}\n" alignment)
3178 (and caption-above-p
3179 (org-string-nw-p caption)
3180 (concat caption "\\\\\n"))
3181 contents
3182 (and (not caption-above-p)
3183 (org-string-nw-p caption)
3184 (concat caption "\\\\\n"))
3185 "\\end{longtable}\n"
3186 (and fontsize "}")))
3187 ;; Longtabu
3188 ((equal "longtabu" table-env)
3189 (concat (and fontsize (concat "{" fontsize))
3190 (format "\\begin{longtabu}%s{%s}\n"
3191 (if width
3192 (format " %s %s "
3193 (if spreadp "spread" "to") width) "")
3194 alignment)
3195 (and caption-above-p
3196 (org-string-nw-p caption)
3197 (concat caption "\\\\\n"))
3198 contents
3199 (and (not caption-above-p)
3200 (org-string-nw-p caption)
3201 (concat caption "\\\\\n"))
3202 "\\end{longtabu}\n"
3203 (and fontsize "}")))
3204 ;; Others.
3205 (t (concat (cond
3206 (float-env
3207 (concat (format "\\begin{%s}%s\n" float-env placement)
3208 (if caption-above-p caption "")
3209 (when centerp "\\centering\n")
3210 fontsize))
3211 ((and (not float-env) caption)
3212 (concat
3213 (and centerp "\\begin{center}\n" )
3214 (if caption-above-p caption "")
3215 (cond ((and fontsize centerp) fontsize)
3216 (fontsize (concat "{" fontsize)))))
3217 (centerp (concat "\\begin{center}\n" fontsize))
3218 (fontsize (concat "{" fontsize)))
3219 (cond ((equal "tabu" table-env)
3220 (format "\\begin{tabu}%s{%s}\n%s\\end{tabu}"
3221 (if width (format
3222 (if spreadp " spread %s " " to %s ")
3223 width) "")
3224 alignment
3225 contents))
3226 (t (format "\\begin{%s}%s{%s}\n%s\\end{%s}"
3227 table-env
3228 (if width (format "{%s}" width) "")
3229 alignment
3230 contents
3231 table-env)))
3232 (cond
3233 (float-env
3234 (concat (if caption-above-p "" (concat "\n" caption))
3235 (format "\n\\end{%s}" float-env)))
3236 ((and (not float-env) caption)
3237 (concat
3238 (if caption-above-p "" (concat "\n" caption))
3239 (and centerp "\n\\end{center}")
3240 (and fontsize (not centerp) "}")))
3241 (centerp "\n\\end{center}")
3242 (fontsize "}")))))))
3244 (defun org-latex--table.el-table (table info)
3245 "Return appropriate LaTeX code for a table.el table.
3247 TABLE is the table type element to transcode. INFO is a plist
3248 used as a communication channel.
3250 This function assumes TABLE has `table.el' as its `:type'
3251 property."
3252 (require 'table)
3253 ;; Ensure "*org-export-table*" buffer is empty.
3254 (with-current-buffer (get-buffer-create "*org-export-table*")
3255 (erase-buffer))
3256 (let ((output (with-temp-buffer
3257 (insert (org-element-property :value table))
3258 (goto-char 1)
3259 (re-search-forward "^[ \t]*|[^|]" nil t)
3260 (table-generate-source 'latex "*org-export-table*")
3261 (with-current-buffer "*org-export-table*"
3262 (org-trim (buffer-string))))))
3263 (kill-buffer (get-buffer "*org-export-table*"))
3264 ;; Remove left out comments.
3265 (while (string-match "^%.*\n" output)
3266 (setq output (replace-match "" t t output)))
3267 (let ((attr (org-export-read-attribute :attr_latex table)))
3268 (when (plist-get attr :rmlines)
3269 ;; When the "rmlines" attribute is provided, remove all hlines
3270 ;; but the the one separating heading from the table body.
3271 (let ((n 0) (pos 0))
3272 (while (and (< (length output) pos)
3273 (setq pos (string-match "^\\\\hline\n?" output pos)))
3274 (cl-incf n)
3275 (unless (= n 2) (setq output (replace-match "" nil nil output))))))
3276 (let ((centerp (if (plist-member attr :center) (plist-get attr :center)
3277 (plist-get info :latex-tables-centered))))
3278 (if (not centerp) output
3279 (format "\\begin{center}\n%s\n\\end{center}" output))))))
3281 (defun org-latex--math-table (table info)
3282 "Return appropriate LaTeX code for a matrix.
3284 TABLE is the table type element to transcode. INFO is a plist
3285 used as a communication channel.
3287 This function assumes TABLE has `org' as its `:type' property and
3288 `inline-math' or `math' as its `:mode' attribute."
3289 (let* ((attr (org-export-read-attribute :attr_latex table))
3290 (env (or (plist-get attr :environment)
3291 (plist-get info :latex-default-table-environment)))
3292 (contents
3293 (mapconcat
3294 (lambda (row)
3295 (if (eq (org-element-property :type row) 'rule) "\\hline"
3296 ;; Return each cell unmodified.
3297 (concat
3298 (mapconcat
3299 (lambda (cell)
3300 (substring (org-element-interpret-data cell) 0 -1))
3301 (org-element-map row 'table-cell #'identity info) "&")
3302 (or (cdr (assoc env org-latex-table-matrix-macros)) "\\\\")
3303 "\n")))
3304 (org-element-map table 'table-row #'identity info) "")))
3305 (concat
3306 ;; Prefix.
3307 (plist-get attr :math-prefix)
3308 ;; Environment. Also treat special cases.
3309 (cond ((member env '("array" "tabular"))
3310 ;; Make sure cells are always centered while preserving
3311 ;; vertical separators.
3312 (let ((align (replace-regexp-in-string
3313 "[lr]" "c" (org-latex--align-string table info))))
3314 (format "\\begin{%s}{%s}\n%s\\end{%s}" env align contents env)))
3315 ((assoc env org-latex-table-matrix-macros)
3316 (format "\\%s%s{\n%s}"
3318 (or (plist-get attr :math-arguments) "")
3319 contents))
3320 (t (format "\\begin{%s}\n%s\\end{%s}" env contents env)))
3321 ;; Suffix.
3322 (plist-get attr :math-suffix))))
3325 ;;;; Table Cell
3327 (defun org-latex-table-cell (table-cell contents info)
3328 "Transcode a TABLE-CELL element from Org to LaTeX.
3329 CONTENTS is the cell contents. INFO is a plist used as
3330 a communication channel."
3331 (concat
3332 (let ((scientific-format (plist-get info :latex-table-scientific-notation)))
3333 (if (and contents
3334 scientific-format
3335 (string-match orgtbl-exp-regexp contents))
3336 ;; Use appropriate format string for scientific
3337 ;; notation.
3338 (format scientific-format
3339 (match-string 1 contents)
3340 (match-string 2 contents))
3341 contents))
3342 (when (org-export-get-next-element table-cell info) " & ")))
3345 ;;;; Table Row
3347 (defun org-latex-table-row (table-row contents info)
3348 "Transcode a TABLE-ROW element from Org to LaTeX.
3349 CONTENTS is the contents of the row. INFO is a plist used as
3350 a communication channel."
3351 (let* ((attr (org-export-read-attribute :attr_latex
3352 (org-export-get-parent table-row)))
3353 (booktabsp (if (plist-member attr :booktabs) (plist-get attr :booktabs)
3354 (plist-get info :latex-tables-booktabs)))
3355 (longtablep
3356 (member (or (plist-get attr :environment)
3357 (plist-get info :latex-default-table-environment))
3358 '("longtable" "longtabu"))))
3359 (if (eq (org-element-property :type table-row) 'rule)
3360 (cond
3361 ((not booktabsp) "\\hline")
3362 ((not (org-export-get-previous-element table-row info)) "\\toprule")
3363 ((not (org-export-get-next-element table-row info)) "\\bottomrule")
3364 ((and longtablep
3365 (org-export-table-row-ends-header-p
3366 (org-export-get-previous-element table-row info) info))
3368 (t "\\midrule"))
3369 (concat
3370 ;; When BOOKTABS are activated enforce top-rule even when no
3371 ;; hline was specifically marked.
3372 (and booktabsp (not (org-export-get-previous-element table-row info))
3373 "\\toprule\n")
3374 contents "\\\\\n"
3375 (cond
3376 ;; Special case for long tables. Define header and footers.
3377 ((and longtablep (org-export-table-row-ends-header-p table-row info))
3378 (let ((columns (cdr (org-export-table-dimensions
3379 (org-export-get-parent-table table-row) info))))
3380 (format "%s
3381 \\endfirsthead
3382 \\multicolumn{%d}{l}{%s} \\\\
3384 %s \\\\\n
3386 \\endhead
3387 %s\\multicolumn{%d}{r}{%s} \\\\
3388 \\endfoot
3389 \\endlastfoot"
3390 (if booktabsp "\\midrule" "\\hline")
3391 columns
3392 (org-latex--translate "Continued from previous page" info)
3393 (cond
3394 ((not (org-export-table-row-starts-header-p table-row info))
3396 (booktabsp "\\toprule\n")
3397 (t "\\hline\n"))
3398 contents
3399 (if booktabsp "\\midrule" "\\hline")
3400 (if booktabsp "\\midrule" "\\hline")
3401 columns
3402 (org-latex--translate "Continued on next page" info))))
3403 ;; When BOOKTABS are activated enforce bottom rule even when
3404 ;; no hline was specifically marked.
3405 ((and booktabsp (not (org-export-get-next-element table-row info)))
3406 "\\bottomrule"))))))
3409 ;;;; Target
3411 (defun org-latex-target (target _contents info)
3412 "Transcode a TARGET object from Org to LaTeX.
3413 CONTENTS is nil. INFO is a plist holding contextual
3414 information."
3415 (format "\\label{%s}" (org-latex--label target info)))
3418 ;;;; Timestamp
3420 (defun org-latex-timestamp (timestamp _contents info)
3421 "Transcode a TIMESTAMP object from Org to LaTeX.
3422 CONTENTS is nil. INFO is a plist holding contextual
3423 information."
3424 (let ((value (org-latex-plain-text (org-timestamp-translate timestamp) info)))
3425 (format
3426 (plist-get info
3427 (cl-case (org-element-property :type timestamp)
3428 ((active active-range) :latex-active-timestamp-format)
3429 ((inactive inactive-range) :latex-inactive-timestamp-format)
3430 (otherwise :latex-diary-timestamp-format)))
3431 value)))
3434 ;;;; Underline
3436 (defun org-latex-underline (_underline contents info)
3437 "Transcode UNDERLINE from Org to LaTeX.
3438 CONTENTS is the text with underline markup. INFO is a plist
3439 holding contextual information."
3440 (org-latex--text-markup contents 'underline info))
3443 ;;;; Verbatim
3445 (defun org-latex-verbatim (verbatim _contents info)
3446 "Transcode a VERBATIM object from Org to LaTeX.
3447 CONTENTS is nil. INFO is a plist used as a communication
3448 channel."
3449 (org-latex--text-markup
3450 (org-element-property :value verbatim) 'verbatim info))
3453 ;;;; Verse Block
3455 (defun org-latex-verse-block (verse-block contents info)
3456 "Transcode a VERSE-BLOCK element from Org to LaTeX.
3457 CONTENTS is verse block contents. INFO is a plist holding
3458 contextual information."
3459 (org-latex--wrap-label
3460 verse-block
3461 ;; In a verse environment, add a line break to each newline
3462 ;; character and change each white space at beginning of a line
3463 ;; into a space of 1 em. Also change each blank line with
3464 ;; a vertical space of 1 em.
3465 (format "\\begin{verse}\n%s\\end{verse}"
3466 (replace-regexp-in-string
3467 "^[ \t]+" (lambda (m) (format "\\hspace*{%dem}" (length m)))
3468 (replace-regexp-in-string
3469 "^[ \t]*\\\\\\\\$" "\\vspace*{1em}"
3470 (replace-regexp-in-string
3471 "\\([ \t]*\\\\\\\\\\)?[ \t]*\n" "\\\\\n"
3472 contents nil t) nil t) nil t))
3473 info))
3477 ;;; End-user functions
3479 ;;;###autoload
3480 (defun org-latex-export-as-latex
3481 (&optional async subtreep visible-only body-only ext-plist)
3482 "Export current buffer as a LaTeX buffer.
3484 If narrowing is active in the current buffer, only export its
3485 narrowed part.
3487 If a region is active, export that region.
3489 A non-nil optional argument ASYNC means the process should happen
3490 asynchronously. The resulting buffer should be accessible
3491 through the `org-export-stack' interface.
3493 When optional argument SUBTREEP is non-nil, export the sub-tree
3494 at point, extracting information from the headline properties
3495 first.
3497 When optional argument VISIBLE-ONLY is non-nil, don't export
3498 contents of hidden elements.
3500 When optional argument BODY-ONLY is non-nil, only write code
3501 between \"\\begin{document}\" and \"\\end{document}\".
3503 EXT-PLIST, when provided, is a property list with external
3504 parameters overriding Org default settings, but still inferior to
3505 file-local settings.
3507 Export is done in a buffer named \"*Org LATEX Export*\", which
3508 will be displayed when `org-export-show-temporary-export-buffer'
3509 is non-nil."
3510 (interactive)
3511 (org-export-to-buffer 'latex "*Org LATEX Export*"
3512 async subtreep visible-only body-only ext-plist (lambda () (LaTeX-mode))))
3514 ;;;###autoload
3515 (defun org-latex-convert-region-to-latex ()
3516 "Assume the current region has Org syntax, and convert it to LaTeX.
3517 This can be used in any buffer. For example, you can write an
3518 itemized list in Org syntax in an LaTeX buffer and use this
3519 command to convert it."
3520 (interactive)
3521 (org-export-replace-region-by 'latex))
3523 ;;;###autoload
3524 (defun org-latex-export-to-latex
3525 (&optional async subtreep visible-only body-only ext-plist)
3526 "Export current buffer to a LaTeX file.
3528 If narrowing is active in the current buffer, only export its
3529 narrowed part.
3531 If a region is active, export that region.
3533 A non-nil optional argument ASYNC means the process should happen
3534 asynchronously. The resulting file should be accessible through
3535 the `org-export-stack' interface.
3537 When optional argument SUBTREEP is non-nil, export the sub-tree
3538 at point, extracting information from the headline properties
3539 first.
3541 When optional argument VISIBLE-ONLY is non-nil, don't export
3542 contents of hidden elements.
3544 When optional argument BODY-ONLY is non-nil, only write code
3545 between \"\\begin{document}\" and \"\\end{document}\".
3547 EXT-PLIST, when provided, is a property list with external
3548 parameters overriding Org default settings, but still inferior to
3549 file-local settings."
3550 (interactive)
3551 (let ((outfile (org-export-output-file-name ".tex" subtreep)))
3552 (org-export-to-file 'latex outfile
3553 async subtreep visible-only body-only ext-plist)))
3555 ;;;###autoload
3556 (defun org-latex-export-to-pdf
3557 (&optional async subtreep visible-only body-only ext-plist)
3558 "Export current buffer to LaTeX then process through to PDF.
3560 If narrowing is active in the current buffer, only export its
3561 narrowed part.
3563 If a region is active, export that region.
3565 A non-nil optional argument ASYNC means the process should happen
3566 asynchronously. The resulting file should be accessible through
3567 the `org-export-stack' interface.
3569 When optional argument SUBTREEP is non-nil, export the sub-tree
3570 at point, extracting information from the headline properties
3571 first.
3573 When optional argument VISIBLE-ONLY is non-nil, don't export
3574 contents of hidden elements.
3576 When optional argument BODY-ONLY is non-nil, only write code
3577 between \"\\begin{document}\" and \"\\end{document}\".
3579 EXT-PLIST, when provided, is a property list with external
3580 parameters overriding Org default settings, but still inferior to
3581 file-local settings.
3583 Return PDF file's name."
3584 (interactive)
3585 (let ((outfile (org-export-output-file-name ".tex" subtreep)))
3586 (org-export-to-file 'latex outfile
3587 async subtreep visible-only body-only ext-plist
3588 (lambda (file) (org-latex-compile file)))))
3590 (defun org-latex-compile (texfile &optional snippet)
3591 "Compile a TeX file.
3593 TEXFILE is the name of the file being compiled. Processing is
3594 done through the command specified in `org-latex-pdf-process',
3595 which see. Output is redirected to \"*Org PDF LaTeX Output*\"
3596 buffer.
3598 When optional argument SNIPPET is non-nil, TEXFILE is a temporary
3599 file used to preview a LaTeX snippet. In this case, do not
3600 create a log buffer and do not remove log files.
3602 Return PDF file name or raise an error if it couldn't be
3603 produced."
3604 (unless snippet (message "Processing LaTeX file %s..." texfile))
3605 (let* ((compiler
3606 (or (with-temp-buffer
3607 (save-excursion (insert-file-contents texfile))
3608 (and (search-forward-regexp (regexp-opt org-latex-compilers)
3609 (line-end-position 2)
3611 (progn (beginning-of-line) (looking-at-p "%"))
3612 (match-string 0)))
3613 "pdflatex"))
3614 (process (if (functionp org-latex-pdf-process) org-latex-pdf-process
3615 ;; Replace "%latex" and "%bibtex" with,
3616 ;; respectively, "%L" and "%B" so as to adhere to
3617 ;; `format-spec' specifications.
3618 (mapcar (lambda (command)
3619 (replace-regexp-in-string
3620 "%\\(?:bib\\|la\\)tex\\>"
3621 (lambda (m) (upcase (substring m 0 2)))
3622 command))
3623 org-latex-pdf-process)))
3624 (spec `((?B . ,(shell-quote-argument org-latex-bib-compiler))
3625 (?L . ,(shell-quote-argument compiler))))
3626 (log-buf-name "*Org PDF LaTeX Output*")
3627 (log-buf (and (not snippet) (get-buffer-create log-buf-name)))
3628 (outfile (org-compile-file texfile process "pdf"
3629 (format "See %S for details" log-buf-name)
3630 log-buf spec)))
3631 (unless snippet
3632 (when org-latex-remove-logfiles
3633 (mapc #'delete-file
3634 (directory-files
3635 (file-name-directory outfile)
3637 (concat (regexp-quote (file-name-base outfile))
3638 "\\(?:\\.[0-9]+\\)?\\."
3639 (regexp-opt org-latex-logfiles-extensions))
3640 t)))
3641 (let ((warnings (org-latex--collect-warnings log-buf)))
3642 (message (concat "PDF file produced"
3643 (cond
3644 ((eq warnings 'error) " with errors.")
3645 (warnings (concat " with warnings: " warnings))
3646 (t "."))))))
3647 ;; Return output file name.
3648 outfile))
3650 (defun org-latex--collect-warnings (buffer)
3651 "Collect some warnings from \"pdflatex\" command output.
3652 BUFFER is the buffer containing output. Return collected
3653 warnings types as a string, `error' if a LaTeX error was
3654 encountered or nil if there was none."
3655 (with-current-buffer buffer
3656 (save-excursion
3657 (goto-char (point-max))
3658 (when (re-search-backward "^[ \t]*This is .*?TeX.*?Version" nil t)
3659 (if (re-search-forward "^!" nil t) 'error
3660 (let ((case-fold-search t)
3661 (warnings ""))
3662 (dolist (warning org-latex-known-warnings)
3663 (when (save-excursion (re-search-forward (car warning) nil t))
3664 (setq warnings (concat warnings " " (cdr warning)))))
3665 (org-string-nw-p (org-trim warnings))))))))
3667 ;;;###autoload
3668 (defun org-latex-publish-to-latex (plist filename pub-dir)
3669 "Publish an Org file to LaTeX.
3671 FILENAME is the filename of the Org file to be published. PLIST
3672 is the property list for the given project. PUB-DIR is the
3673 publishing directory.
3675 Return output file name."
3676 (org-publish-org-to 'latex filename ".tex" plist pub-dir))
3678 ;;;###autoload
3679 (defun org-latex-publish-to-pdf (plist filename pub-dir)
3680 "Publish an Org file to PDF (via LaTeX).
3682 FILENAME is the filename of the Org file to be published. PLIST
3683 is the property list for the given project. PUB-DIR is the
3684 publishing directory.
3686 Return output file name."
3687 ;; Unlike to `org-latex-publish-to-latex', PDF file is generated
3688 ;; in working directory and then moved to publishing directory.
3689 (org-publish-attachment
3690 plist
3691 (org-latex-compile
3692 (org-publish-org-to
3693 'latex filename ".tex" plist (file-name-directory filename)))
3694 pub-dir))
3697 (provide 'ox-latex)
3699 ;; Local variables:
3700 ;; generated-autoload-file: "org-loaddefs.el"
3701 ;; End:
3703 ;;; ox-latex.el ends here