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