* ob-vbnet.el: Org-babel functions for VB.Net evaluation
[org-mode/org-tableheadings.git] / lisp / ox-latex.el
blob0901726938fc59cbf1e257c098acf40a49a96adb
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 (require 'cl-lib)
30 (require 'ox)
31 (require 'ox-publish)
33 (defvar org-latex-default-packages-alist)
34 (defvar org-latex-packages-alist)
35 (defvar orgtbl-exp-regexp)
39 ;;; Define Back-End
41 (org-export-define-backend 'latex
42 '((bold . org-latex-bold)
43 (center-block . org-latex-center-block)
44 (clock . org-latex-clock)
45 (code . org-latex-code)
46 (drawer . org-latex-drawer)
47 (dynamic-block . org-latex-dynamic-block)
48 (entity . org-latex-entity)
49 (example-block . org-latex-example-block)
50 (export-block . org-latex-export-block)
51 (export-snippet . org-latex-export-snippet)
52 (fixed-width . org-latex-fixed-width)
53 (footnote-definition . org-latex-footnote-definition)
54 (footnote-reference . org-latex-footnote-reference)
55 (headline . org-latex-headline)
56 (horizontal-rule . org-latex-horizontal-rule)
57 (inline-src-block . org-latex-inline-src-block)
58 (inlinetask . org-latex-inlinetask)
59 (italic . org-latex-italic)
60 (item . org-latex-item)
61 (keyword . org-latex-keyword)
62 (latex-environment . org-latex-latex-environment)
63 (latex-fragment . org-latex-latex-fragment)
64 (line-break . org-latex-line-break)
65 (link . org-latex-link)
66 (node-property . org-latex-node-property)
67 (paragraph . org-latex-paragraph)
68 (plain-list . org-latex-plain-list)
69 (plain-text . org-latex-plain-text)
70 (planning . org-latex-planning)
71 (property-drawer . org-latex-property-drawer)
72 (quote-block . org-latex-quote-block)
73 (radio-target . org-latex-radio-target)
74 (section . org-latex-section)
75 (special-block . org-latex-special-block)
76 (src-block . org-latex-src-block)
77 (statistics-cookie . org-latex-statistics-cookie)
78 (strike-through . org-latex-strike-through)
79 (subscript . org-latex-subscript)
80 (superscript . org-latex-superscript)
81 (table . org-latex-table)
82 (table-cell . org-latex-table-cell)
83 (table-row . org-latex-table-row)
84 (target . org-latex-target)
85 (template . org-latex-template)
86 (timestamp . org-latex-timestamp)
87 (underline . org-latex-underline)
88 (verbatim . org-latex-verbatim)
89 (verse-block . org-latex-verse-block)
90 ;; Pseudo objects and elements.
91 (latex-math-block . org-latex-math-block)
92 (latex-matrices . org-latex-matrices))
93 :menu-entry
94 '(?l "Export to LaTeX"
95 ((?L "As LaTeX buffer" org-latex-export-as-latex)
96 (?l "As LaTeX file" org-latex-export-to-latex)
97 (?p "As PDF file" org-latex-export-to-pdf)
98 (?o "As PDF file and open"
99 (lambda (a s v b)
100 (if a (org-latex-export-to-pdf t s v b)
101 (org-open-file (org-latex-export-to-pdf nil s v b)))))))
102 :filters-alist '((:filter-options . org-latex-math-block-options-filter)
103 (:filter-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")))
625 ;;;; Headline
627 (defcustom org-latex-format-headline-function
628 'org-latex-format-headline-default-function
629 "Function for formatting the headline's text.
631 This function will be called with six arguments:
632 TODO the todo keyword (string or nil)
633 TODO-TYPE the type of todo (symbol: `todo', `done', nil)
634 PRIORITY the priority of the headline (integer or nil)
635 TEXT the main headline text (string)
636 TAGS the tags (list of strings or nil)
637 INFO the export options (plist)
639 The function result will be used in the section format string."
640 :group 'org-export-latex
641 :version "24.4"
642 :package-version '(Org . "8.0")
643 :type 'function)
646 ;;;; Footnotes
648 (defcustom org-latex-footnote-separator "\\textsuperscript{,}\\,"
649 "Text used to separate footnotes."
650 :group 'org-export-latex
651 :type 'string)
653 (defcustom org-latex-footnote-defined-format "\\textsuperscript{\\ref{%s}}"
654 "Format string used to format reference to footnote already defined.
655 %s will be replaced by the label of the referred footnote."
656 :group 'org-export-latex
657 :type '(choice
658 (const :tag "Use plain superscript (default)" "\\textsuperscript{\\ref{%s}}")
659 (const :tag "Use Memoir/KOMA-Script footref" "\\footref{%s}")
660 (string :tag "Other format string"))
661 :version "25.2"
662 :package-version '(Org . "9.0"))
664 ;;;; Timestamps
666 (defcustom org-latex-active-timestamp-format "\\textit{%s}"
667 "A printf format string to be applied to active timestamps."
668 :group 'org-export-latex
669 :type 'string)
671 (defcustom org-latex-inactive-timestamp-format "\\textit{%s}"
672 "A printf format string to be applied to inactive timestamps."
673 :group 'org-export-latex
674 :type 'string)
676 (defcustom org-latex-diary-timestamp-format "\\textit{%s}"
677 "A printf format string to be applied to diary timestamps."
678 :group 'org-export-latex
679 :type 'string)
682 ;;;; Links
684 (defcustom org-latex-image-default-option ""
685 "Default option for images."
686 :group 'org-export-latex
687 :version "24.4"
688 :package-version '(Org . "8.0")
689 :type 'string)
691 (defcustom org-latex-image-default-width ".9\\linewidth"
692 "Default width for images.
693 This value will not be used if a height is provided."
694 :group 'org-export-latex
695 :version "24.4"
696 :package-version '(Org . "8.0")
697 :type 'string)
699 (defcustom org-latex-image-default-height ""
700 "Default height for images.
701 This value will not be used if a width is provided, or if the
702 image is wrapped within a \"figure\" or \"wrapfigure\"
703 environment."
704 :group 'org-export-latex
705 :version "24.4"
706 :package-version '(Org . "8.0")
707 :type 'string)
709 (defcustom org-latex-default-figure-position "htb"
710 "Default position for latex figures."
711 :group 'org-export-latex
712 :type 'string)
714 (defcustom org-latex-inline-image-rules
715 '(("file" . "\\.\\(pdf\\|jpeg\\|jpg\\|png\\|ps\\|eps\\|tikz\\|pgf\\|svg\\)\\'"))
716 "Rules characterizing image files that can be inlined into LaTeX.
718 A rule consists in an association whose key is the type of link
719 to consider, and value is a regexp that will be matched against
720 link's path.
722 Note that, by default, the image extension *actually* allowed
723 depend on the way the LaTeX file is processed. When used with
724 pdflatex, pdf, jpg and png images are OK. When processing
725 through dvi to Postscript, only ps and eps are allowed. The
726 default we use here encompasses both."
727 :group 'org-export-latex
728 :version "24.4"
729 :package-version '(Org . "8.0")
730 :type '(alist :key-type (string :tag "Type")
731 :value-type (regexp :tag "Path")))
733 (defcustom org-latex-link-with-unknown-path-format "\\texttt{%s}"
734 "Format string for links with unknown path type."
735 :group 'org-export-latex
736 :type 'string)
739 ;;;; Tables
741 (defcustom org-latex-default-table-environment "tabular"
742 "Default environment used to build tables."
743 :group 'org-export-latex
744 :version "24.4"
745 :package-version '(Org . "8.0")
746 :type 'string)
748 (defcustom org-latex-default-table-mode 'table
749 "Default mode for tables.
751 Value can be a symbol among:
753 `table' Regular LaTeX table.
755 `math' In this mode, every cell is considered as being in math
756 mode and the complete table will be wrapped within a math
757 environment. It is particularly useful to write matrices.
759 `inline-math' This mode is almost the same as `math', but the
760 math environment will be inlined.
762 `verbatim' The table is exported as it appears in the Org
763 buffer, within a verbatim environment.
765 This value can be overridden locally with, i.e. \":mode math\" in
766 LaTeX attributes.
768 When modifying this variable, it may be useful to change
769 `org-latex-default-table-environment' accordingly."
770 :group 'org-export-latex
771 :version "24.4"
772 :package-version '(Org . "8.0")
773 :type '(choice (const :tag "Table" table)
774 (const :tag "Matrix" math)
775 (const :tag "Inline matrix" inline-math)
776 (const :tag "Verbatim" verbatim))
777 :safe (lambda (s) (memq s '(table math inline-math verbatim))))
779 (defcustom org-latex-tables-centered t
780 "When non-nil, tables are exported in a center environment."
781 :group 'org-export-latex
782 :type 'boolean
783 :safe #'booleanp)
785 (defcustom org-latex-tables-booktabs nil
786 "When non-nil, display tables in a formal \"booktabs\" style.
787 This option assumes that the \"booktabs\" package is properly
788 loaded in the header of the document. This value can be ignored
789 locally with \":booktabs t\" and \":booktabs nil\" LaTeX
790 attributes."
791 :group 'org-export-latex
792 :version "24.4"
793 :package-version '(Org . "8.0")
794 :type 'boolean
795 :safe #'booleanp)
797 (defcustom org-latex-table-scientific-notation "%s\\,(%s)"
798 "Format string to display numbers in scientific notation.
799 The format should have \"%s\" twice, for mantissa and exponent
800 \(i.e., \"%s\\\\times10^{%s}\").
802 When nil, no transformation is made."
803 :group 'org-export-latex
804 :version "24.4"
805 :package-version '(Org . "8.0")
806 :type '(choice
807 (string :tag "Format string")
808 (const :tag "No formatting" nil)))
810 ;;;; Text markup
812 (defcustom org-latex-text-markup-alist '((bold . "\\textbf{%s}")
813 (code . protectedtexttt)
814 (italic . "\\emph{%s}")
815 (strike-through . "\\sout{%s}")
816 (underline . "\\uline{%s}")
817 (verbatim . protectedtexttt))
818 "Alist of LaTeX expressions to convert text markup.
820 The key must be a symbol among `bold', `code', `italic',
821 `strike-through', `underline' and `verbatim'. The value is
822 a formatting string to wrap fontified text with.
824 Value can also be set to the following symbols: `verb' and
825 `protectedtexttt'. For the former, Org will use \"\\verb\" to
826 create a format string and select a delimiter character that
827 isn't in the string. For the latter, Org will use \"\\texttt\"
828 to typeset and try to protect special characters.
830 If no association can be found for a given markup, text will be
831 returned as-is."
832 :group 'org-export-latex
833 :version "25.1"
834 :package-version '(Org . "8.3")
835 :type 'alist
836 :options '(bold code italic strike-through underline verbatim))
839 ;;;; Drawers
841 (defcustom org-latex-format-drawer-function (lambda (_ contents) contents)
842 "Function called to format a drawer in LaTeX code.
844 The function must accept two parameters:
845 NAME the drawer name, like \"LOGBOOK\"
846 CONTENTS the contents of the drawer.
848 The function should return the string to be exported.
850 The default function simply returns the value of CONTENTS."
851 :group 'org-export-latex
852 :version "24.4"
853 :package-version '(Org . "8.3")
854 :type 'function)
857 ;;;; Inlinetasks
859 (defcustom org-latex-format-inlinetask-function
860 'org-latex-format-inlinetask-default-function
861 "Function called to format an inlinetask in LaTeX code.
863 The function must accept seven parameters:
864 TODO the todo keyword (string or nil)
865 TODO-TYPE the todo type (symbol: `todo', `done', nil)
866 PRIORITY the inlinetask priority (integer or nil)
867 NAME the inlinetask name (string)
868 TAGS the inlinetask tags (list of strings or nil)
869 CONTENTS the contents of the inlinetask (string or nil)
870 INFO the export options (plist)
872 The function should return the string to be exported."
873 :group 'org-export-latex
874 :type 'function
875 :version "25.1"
876 :package-version '(Org . "8.3"))
879 ;; Src blocks
881 (defcustom org-latex-listings nil
882 "Non-nil means export source code using the listings package.
884 This package will fontify source code, possibly even with color.
885 If you want to use this, you also need to make LaTeX use the
886 listings package, and if you want to have color, the color
887 package. Just add these to `org-latex-packages-alist', for
888 example using customize, or with something like:
890 (require \\='ox-latex)
891 (add-to-list \\='org-latex-packages-alist \\='(\"\" \"listings\"))
892 (add-to-list \\='org-latex-packages-alist \\='(\"\" \"color\"))
894 Alternatively,
896 (setq org-latex-listings \\='minted)
898 causes source code to be exported using the minted package as
899 opposed to listings. If you want to use minted, you need to add
900 the minted package to `org-latex-packages-alist', for example
901 using customize, or with
903 (require \\='ox-latex)
904 (add-to-list \\='org-latex-packages-alist \\='(\"newfloat\" \"minted\"))
906 In addition, it is necessary to install pygments
907 \(http://pygments.org), and to configure the variable
908 `org-latex-pdf-process' so that the -shell-escape option is
909 passed to pdflatex.
911 The minted choice has possible repercussions on the preview of
912 latex fragments (see `org-preview-latex-fragment'). If you run
913 into previewing problems, please consult
915 http://orgmode.org/worg/org-tutorials/org-latex-preview.html"
916 :group 'org-export-latex
917 :type '(choice
918 (const :tag "Use listings" t)
919 (const :tag "Use minted" minted)
920 (const :tag "Export verbatim" nil))
921 :safe (lambda (s) (memq s '(t nil minted))))
923 (defcustom org-latex-listings-langs
924 '((emacs-lisp "Lisp") (lisp "Lisp") (clojure "Lisp")
925 (c "C") (cc "C++")
926 (fortran "fortran")
927 (perl "Perl") (cperl "Perl") (python "Python") (ruby "Ruby")
928 (html "HTML") (xml "XML")
929 (tex "TeX") (latex "[LaTeX]TeX")
930 (shell-script "bash")
931 (gnuplot "Gnuplot")
932 (ocaml "Caml") (caml "Caml")
933 (sql "SQL") (sqlite "sql")
934 (makefile "make")
935 (R "r"))
936 "Alist mapping languages to their listing language counterpart.
937 The key is a symbol, the major mode symbol without the \"-mode\".
938 The value is the string that should be inserted as the language
939 parameter for the listings package. If the mode name and the
940 listings name are the same, the language does not need an entry
941 in this list - but it does not hurt if it is present."
942 :group 'org-export-latex
943 :version "24.4"
944 :package-version '(Org . "8.3")
945 :type '(repeat
946 (list
947 (symbol :tag "Major mode ")
948 (string :tag "Listings language"))))
950 (defcustom org-latex-listings-options nil
951 "Association list of options for the latex listings package.
953 These options are supplied as a comma-separated list to the
954 \\lstset command. Each element of the association list should be
955 a list containing two strings: the name of the option, and the
956 value. For example,
958 (setq org-latex-listings-options
959 \\='((\"basicstyle\" \"\\\\small\")
960 (\"keywordstyle\" \"\\\\color{black}\\\\bfseries\\\\underbar\")))
962 will typeset the code in a small size font with underlined, bold
963 black keywords.
965 Note that the same options will be applied to blocks of all
966 languages. If you need block-specific options, you may use the
967 following syntax:
969 #+ATTR_LATEX: :options key1=value1,key2=value2
970 #+BEGIN_SRC <LANG>
972 #+END_SRC"
973 :group 'org-export-latex
974 :type '(repeat
975 (list
976 (string :tag "Listings option name ")
977 (string :tag "Listings option value"))))
979 (defcustom org-latex-minted-langs
980 '((emacs-lisp "common-lisp")
981 (cc "c++")
982 (cperl "perl")
983 (shell-script "bash")
984 (caml "ocaml"))
985 "Alist mapping languages to their minted language counterpart.
986 The key is a symbol, the major mode symbol without the \"-mode\".
987 The value is the string that should be inserted as the language
988 parameter for the minted package. If the mode name and the
989 listings name are the same, the language does not need an entry
990 in this list - but it does not hurt if it is present.
992 Note that minted uses all lower case for language identifiers,
993 and that the full list of language identifiers can be obtained
994 with:
996 pygmentize -L lexers"
997 :group 'org-export-latex
998 :type '(repeat
999 (list
1000 (symbol :tag "Major mode ")
1001 (string :tag "Minted language"))))
1003 (defcustom org-latex-minted-options nil
1004 "Association list of options for the latex minted package.
1006 These options are supplied within square brackets in
1007 \\begin{minted} environments. Each element of the alist should
1008 be a list containing two strings: the name of the option, and the
1009 value. For example,
1011 (setq org-latex-minted-options
1012 '((\"bgcolor\" \"bg\") (\"frame\" \"lines\")))
1014 will result in src blocks being exported with
1016 \\begin{minted}[bgcolor=bg,frame=lines]{<LANG>}
1018 as the start of the minted environment. Note that the same
1019 options will be applied to blocks of all languages. If you need
1020 block-specific options, you may use the following syntax:
1022 #+ATTR_LATEX: :options key1=value1,key2=value2
1023 #+BEGIN_SRC <LANG>
1025 #+END_SRC"
1026 :group 'org-export-latex
1027 :type '(repeat
1028 (list
1029 (string :tag "Minted option name ")
1030 (string :tag "Minted option value"))))
1032 (defcustom org-latex-custom-lang-environments nil
1033 "Alist mapping languages to language-specific LaTeX environments.
1035 It is used during export of src blocks by the listings and minted
1036 latex packages. The environment may be a simple string, composed of
1037 only letters and numbers. In this case, the string is directly the
1038 name of the latex environment to use. The environment may also be
1039 a format string. In this case the format string will be directly
1040 exported. This format string may contain these elements:
1042 %s for the formatted source
1043 %c for the caption
1044 %f for the float attribute
1045 %l for an appropriate label
1046 %o for the LaTeX attributes
1048 For example,
1050 (setq org-latex-custom-lang-environments
1051 '((python \"pythoncode\")
1052 (ocaml \"\\\\begin{listing}
1053 \\\\begin{minted}[%o]{ocaml}
1054 %s\\\\end{minted}
1055 \\\\caption{%c}
1056 \\\\label{%l}\")))
1058 would have the effect that if Org encounters a Python source block
1059 during LaTeX export it will produce
1061 \\begin{pythoncode}
1062 <src block body>
1063 \\end{pythoncode}
1065 and if Org encounters an Ocaml source block during LaTeX export it
1066 will produce
1068 \\begin{listing}
1069 \\begin{minted}[<attr_latex options>]{ocaml}
1070 <src block body>
1071 \\end{minted}
1072 \\caption{<caption>}
1073 \\label{<label>}
1074 \\end{listing}"
1075 :group 'org-export-latex
1076 :type '(repeat
1077 (list
1078 (symbol :tag "Language name ")
1079 (string :tag "Environment name or format string")))
1080 :version "25.1"
1081 :package-version '(Org . "9.0"))
1084 ;;;; Compilation
1086 (defcustom org-latex-compiler-file-string "%% Intended LaTeX compiler: %s\n"
1087 "LaTeX compiler format-string.
1088 See also `org-latex-compiler'."
1089 :group 'org-export-latex
1090 :type '(choice
1091 (const :tag "Comment" "%% Intended LaTeX compiler: %s\n")
1092 (const :tag "latex-mode file variable" "%% -*- latex-run-command: %s -*-\n")
1093 (const :tag "AUCTeX file variable" "%% -*- LaTeX-command: %s -*-\n")
1094 (string :tag "custom format" "%% %s"))
1095 :version "25.1"
1096 :package-version '(Org . "9.0"))
1098 (defcustom org-latex-compiler "pdflatex"
1099 "LaTeX compiler to use.
1101 Must be an element in `org-latex-compilers' or the empty quote.
1102 Can also be set in buffers via #+LATEX_COMPILER. See also
1103 `org-latex-compiler-file-string'."
1104 :group 'org-export-latex
1105 :type '(choice
1106 (const :tag "pdfLaTeX" "pdflatex")
1107 (const :tag "XeLaTeX" "xelatex")
1108 (const :tag "LuaLaTeX" "lualatex")
1109 (const :tag "Unset" ""))
1110 :version "25.1"
1111 :package-version '(Org . "9.0"))
1113 (defconst org-latex-compilers '("pdflatex" "xelatex" "lualatex")
1114 "Known LaTeX compilers.
1115 See also `org-latex-compiler'.")
1117 (defcustom org-latex-bib-compiler "bibtex"
1118 "Command to process a LaTeX file's bibliography.
1120 The shorthand %bib in `org-latex-pdf-process' is replaced with
1121 this value.
1123 A better approach is to use a compiler suit such as `latexmk'."
1124 :group 'org-export-latex
1125 :type '(choice (const :tag "BibTeX" "bibtex")
1126 (const :tag "Biber" "biber")
1127 (string :tag "Other process"))
1128 :version "25.1"
1129 :package-version '(Org . "9.0"))
1131 (defcustom org-latex-pdf-process
1132 '("%latex -interaction nonstopmode -output-directory %o %f"
1133 "%latex -interaction nonstopmode -output-directory %o %f"
1134 "%latex -interaction nonstopmode -output-directory %o %f")
1135 "Commands to process a LaTeX file to a PDF file.
1136 This is a list of strings, each of them will be given to the
1137 shell as a command. %f in the command will be replaced by the
1138 full file name, %b by the file base name (i.e. without directory
1139 and extension parts), %o by the base directory of the file,
1140 %latex is the LaTeX compiler (see `org-latex-compiler'), and %bib
1141 is the BibTeX-like compiler (see `org-latex-bib-compiler').
1143 The reason why this is a list is that it usually takes several
1144 runs of `pdflatex', maybe mixed with a call to `bibtex'. Org
1145 does not have a clever mechanism to detect which of these
1146 commands have to be run to get to a stable result, and it also
1147 does not do any error checking.
1149 Consider a smart LaTeX compiler such as `texi2dvi' or `latexmk',
1150 which calls the \"correct\" combinations of auxiliary programs.
1152 Alternatively, this may be a Lisp function that does the
1153 processing, so you could use this to apply the machinery of
1154 AUCTeX or the Emacs LaTeX mode. This function should accept the
1155 file name as its single argument."
1156 :group 'org-export-pdf
1157 :type '(choice
1158 (repeat :tag "Shell command sequence"
1159 (string :tag "Shell command"))
1160 (const :tag "2 runs of latex"
1161 ("%latex -interaction nonstopmode -output-directory %o %f"
1162 "%latex -interaction nonstopmode -output-directory %o %f"))
1163 (const :tag "3 runs of latex"
1164 ("%latex -interaction nonstopmode -output-directory %o %f"
1165 "%latex -interaction nonstopmode -output-directory %o %f"
1166 "%latex -interaction nonstopmode -output-directory %o %f"))
1167 (const :tag "latex,bibtex,latex,latex"
1168 ("%latex -interaction nonstopmode -output-directory %o %f"
1169 "%bib %b"
1170 "%latex -interaction nonstopmode -output-directory %o %f"
1171 "%latex -interaction nonstopmode -output-directory %o %f"))
1172 (const :tag "texi2dvi"
1173 ("LATEX=\"%latex\" texi2dvi -p -b -V %f"))
1174 (const :tag "latexmk"
1175 ("latexmk -g -pdflatex=\"%latex\" %f"))
1176 (function)))
1178 (defcustom org-latex-logfiles-extensions
1179 '("aux" "bcf" "blg" "fdb_latexmk" "fls" "figlist" "idx" "log" "nav" "out"
1180 "ptc" "run.xml" "snm" "toc" "vrb" "xdv")
1181 "The list of file extensions to consider as LaTeX logfiles.
1182 The logfiles will be removed if `org-latex-remove-logfiles' is
1183 non-nil."
1184 :group 'org-export-latex
1185 :version "25.1"
1186 :package-version '(Org . "8.3")
1187 :type '(repeat (string :tag "Extension")))
1189 (defcustom org-latex-remove-logfiles t
1190 "Non-nil means remove the logfiles produced by PDF production.
1191 By default, logfiles are files with these extensions: .aux, .idx,
1192 .log, .out, .toc, .nav, .snm and .vrb. To define the set of
1193 logfiles to remove, set `org-latex-logfiles-extensions'."
1194 :group 'org-export-latex
1195 :type 'boolean)
1197 (defcustom org-latex-known-warnings
1198 '(("Reference.*?undefined" . "[undefined reference]")
1199 ("Runaway argument" . "[runaway argument]")
1200 ("Underfull \\hbox" . "[underfull hbox]")
1201 ("Overfull \\hbox" . "[overfull hbox]")
1202 ("Citation.*?undefined" . "[undefined citation]")
1203 ("Undefined control sequence" . "[undefined control sequence]"))
1204 "Alist of regular expressions and associated messages for the user.
1205 The regular expressions are used to find possible warnings in the
1206 log of a latex-run. These warnings will be reported after
1207 calling `org-latex-compile'."
1208 :group 'org-export-latex
1209 :version "25.1"
1210 :package-version '(Org . "8.3")
1211 :type '(repeat
1212 (cons
1213 (string :tag "Regexp")
1214 (string :tag "Message"))))
1218 ;;; Internal Functions
1220 (defun org-latex--caption-above-p (element info)
1221 "Non nil when caption is expected to be located above ELEMENT.
1222 INFO is a plist holding contextual information."
1223 (let ((above (plist-get info :latex-caption-above)))
1224 (if (symbolp above) above
1225 (let ((type (org-element-type element)))
1226 (memq (if (eq type 'link) 'image type) above)))))
1228 (defun org-latex--label (datum info &optional force full)
1229 "Return an appropriate label for DATUM.
1230 DATUM is an element or a `target' type object. INFO is the
1231 current export state, as a plist.
1233 Return nil if element DATUM has no NAME or VALUE affiliated
1234 keyword or no CUSTOM_ID property, unless FORCE is non-nil. In
1235 this case always return a unique label.
1237 Eventually, if FULL is non-nil, wrap label within \"\\label{}\"."
1238 (let* ((type (org-element-type datum))
1239 (user-label
1240 (org-element-property
1241 (cl-case type
1242 ((headline inlinetask) :CUSTOM_ID)
1243 (target :value)
1244 (otherwise :name))
1245 datum))
1246 (label
1247 (and (or user-label force)
1248 (if (and user-label (plist-get info :latex-prefer-user-labels))
1249 user-label
1250 (concat (cl-case type
1251 (headline "sec:")
1252 (table "tab:")
1253 (latex-environment
1254 (and (org-string-match-p
1255 org-latex-math-environments-re
1256 (org-element-property :value datum))
1257 "eq:"))
1258 (paragraph
1259 (and (org-element-property :caption datum)
1260 "fig:")))
1261 (org-export-get-reference datum info))))))
1262 (cond ((not full) label)
1263 (label (format "\\label{%s}%s"
1264 label
1265 (if (eq type 'target) "" "\n")))
1266 (t ""))))
1268 (defun org-latex--caption/label-string (element info)
1269 "Return caption and label LaTeX string for ELEMENT.
1271 INFO is a plist holding contextual information. If there's no
1272 caption nor label, return the empty string.
1274 For non-floats, see `org-latex--wrap-label'."
1275 (let* ((label (org-latex--label element info nil t))
1276 (main (org-export-get-caption element))
1277 (attr (org-export-read-attribute :attr_latex element))
1278 (type (org-element-type element))
1279 (nonfloat (or (and (plist-member attr :float)
1280 (not (plist-get attr :float))
1281 main)
1282 (and (eq type 'src-block)
1283 (not (plist-get attr :float))
1284 (memq (plist-get info :latex-listings)
1285 '(nil minted)))))
1286 (short (org-export-get-caption element t))
1287 (caption-from-attr-latex (plist-get attr :caption)))
1288 (cond
1289 ((org-string-nw-p caption-from-attr-latex)
1290 (concat caption-from-attr-latex "\n"))
1291 ((and (not main) (equal label "")) "")
1292 ((not main) label)
1293 ;; Option caption format with short name.
1295 (format (if nonfloat "\\captionof{%s}%s{%s%s}\n"
1296 "\\caption%s%s{%s%s}\n")
1297 (if nonfloat
1298 (cl-case type
1299 (paragraph "figure")
1300 (src-block (if (plist-get info :latex-listings)
1301 "listing"
1302 "figure"))
1303 (t (symbol-name type)))
1305 (if short (format "[%s]" (org-export-data short info)) "")
1306 label
1307 (org-export-data main info))))))
1309 (defun org-latex-guess-inputenc (header)
1310 "Set the coding system in inputenc to what the buffer is.
1312 HEADER is the LaTeX header string. This function only applies
1313 when specified inputenc option is \"AUTO\".
1315 Return the new header, as a string."
1316 (let* ((cs (or (ignore-errors
1317 (latexenc-coding-system-to-inputenc
1318 (or org-export-coding-system buffer-file-coding-system)))
1319 "utf8")))
1320 (if (not cs) header
1321 ;; First translate if that is requested.
1322 (setq cs (or (cdr (assoc cs org-latex-inputenc-alist)) cs))
1323 ;; Then find the \usepackage statement and replace the option.
1324 (replace-regexp-in-string "\\\\usepackage\\[\\(AUTO\\)\\]{inputenc}"
1325 cs header t nil 1))))
1327 (defun org-latex-guess-babel-language (header info)
1328 "Set Babel's language according to LANGUAGE keyword.
1330 HEADER is the LaTeX header string. INFO is the plist used as
1331 a communication channel.
1333 Insertion of guessed language only happens when Babel package has
1334 explicitly been loaded. Then it is added to the rest of
1335 package's options.
1337 The argument to Babel may be \"AUTO\" which is then replaced with
1338 the language of the document or `org-export-default-language'
1339 unless language in question is already loaded.
1341 Return the new header."
1342 (let ((language-code (plist-get info :language)))
1343 ;; If no language is set or Babel package is not loaded, return
1344 ;; HEADER as-is.
1345 (if (or (not (stringp language-code))
1346 (not (string-match "\\\\usepackage\\[\\(.*\\)\\]{babel}" header)))
1347 header
1348 (let ((options (save-match-data
1349 (org-split-string (match-string 1 header) ",[ \t]*")))
1350 (language (cdr (assoc-string language-code
1351 org-latex-babel-language-alist t))))
1352 ;; If LANGUAGE is already loaded, return header without AUTO.
1353 ;; Otherwise, replace AUTO with language or append language if
1354 ;; AUTO is not present.
1355 (replace-match
1356 (mapconcat (lambda (option) (if (equal "AUTO" option) language option))
1357 (cond ((member language options) (delete "AUTO" options))
1358 ((member "AUTO" options) options)
1359 (t (append options (list language))))
1360 ", ")
1361 t nil header 1)))))
1363 (defun org-latex-guess-polyglossia-language (header info)
1364 "Set the Polyglossia language according to the LANGUAGE keyword.
1366 HEADER is the LaTeX header string. INFO is the plist used as
1367 a communication channel.
1369 Insertion of guessed language only happens when the Polyglossia
1370 package has been explicitly loaded.
1372 The argument to Polyglossia may be \"AUTO\" which is then
1373 replaced with the language of the document or
1374 `org-export-default-language'. Note, the language is really set
1375 using \setdefaultlanguage and not as an option to the package.
1377 Return the new header."
1378 (let ((language (plist-get info :language)))
1379 ;; If no language is set or Polyglossia is not loaded, return
1380 ;; HEADER as-is.
1381 (if (or (not (stringp language))
1382 (not (string-match
1383 "\\\\usepackage\\(?:\\[\\([^]]+?\\)\\]\\){polyglossia}\n"
1384 header)))
1385 header
1386 (let* ((options (org-string-nw-p (match-string 1 header)))
1387 (languages (and options
1388 ;; Reverse as the last loaded language is
1389 ;; the main language.
1390 (nreverse
1391 (delete-dups
1392 (save-match-data
1393 (org-split-string
1394 (replace-regexp-in-string
1395 "AUTO" language options t)
1396 ",[ \t]*"))))))
1397 (main-language-set
1398 (string-match-p "\\\\setmainlanguage{.*?}" header)))
1399 (replace-match
1400 (concat "\\usepackage{polyglossia}\n"
1401 (mapconcat
1402 (lambda (l)
1403 (let ((l (or (assoc l org-latex-polyglossia-language-alist)
1404 l)))
1405 (format (if main-language-set "\\setotherlanguage%s{%s}\n"
1406 (setq main-language-set t)
1407 "\\setmainlanguage%s{%s}\n")
1408 (if (and (consp l) (= (length l) 3))
1409 (format "[variant=%s]" (nth 2 l))
1411 (nth 1 l))))
1412 languages
1413 ""))
1414 t t header 0)))))
1416 (defun org-latex--remove-packages (pkg-alist info)
1417 "Remove packages based on the current LaTeX compiler.
1419 If the fourth argument of an element is set in pkg-alist, and it
1420 is not a member of the LaTeX compiler of the document, the packages
1421 is removed. See also `org-latex-compiler'.
1423 Return modified pkg-alist."
1424 (let ((compiler (or (plist-get info :latex-compiler) "")))
1425 (if (member-ignore-case compiler org-latex-compilers)
1426 (delq nil
1427 (mapcar
1428 (lambda (pkg)
1429 (unless (and
1430 (listp pkg)
1431 (let ((third (nth 3 pkg)))
1432 (and third
1433 (not (member-ignore-case
1434 compiler
1435 (if (listp third) third (list third)))))))
1436 pkg))
1437 pkg-alist))
1438 pkg-alist)))
1440 (defun org-latex--find-verb-separator (s)
1441 "Return a character not used in string S.
1442 This is used to choose a separator for constructs like \\verb."
1443 (let ((ll "~,./?;':\"|!@#%^&-_=+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ<>()[]{}"))
1444 (cl-loop for c across ll
1445 when (not (string-match (regexp-quote (char-to-string c)) s))
1446 return (char-to-string c))))
1448 (defun org-latex--make-option-string (options)
1449 "Return a comma separated string of keywords and values.
1450 OPTIONS is an alist where the key is the options keyword as
1451 a string, and the value a list containing the keyword value, or
1452 nil."
1453 (mapconcat (lambda (pair)
1454 (concat (first pair)
1455 (when (> (length (second pair)) 0)
1456 (concat "=" (second pair)))))
1457 options
1458 ","))
1460 (defun org-latex--wrap-label (element output info)
1461 "Wrap label associated to ELEMENT around OUTPUT, if appropriate.
1462 INFO is the current export state, as a plist. This function
1463 should not be used for floats. See
1464 `org-latex--caption/label-string'."
1465 (if (not (and (org-string-nw-p output) (org-element-property :name element)))
1466 output
1467 (concat (format "\\phantomsection\n\\label{%s}\n"
1468 (org-latex--label element info))
1469 output)))
1471 (defun org-latex--protect-text (text)
1472 "Protect special characters in string TEXT and return it."
1473 (replace-regexp-in-string
1474 "--\\|[\\{}$%&_#~^]"
1475 (lambda (m)
1476 (cond ((equal m "--") "-{}-")
1477 ((equal m "\\") "\\textbackslash{}")
1478 ((equal m "~") "\\textasciitilde{}")
1479 ((equal m "^") "\\textasciicircum{}")
1480 (t (concat "\\" m))))
1481 text nil t))
1483 (defun org-latex--text-markup (text markup info)
1484 "Format TEXT depending on MARKUP text markup.
1485 INFO is a plist used as a communication channel. See
1486 `org-latex-text-markup-alist' for details."
1487 (let ((fmt (cdr (assq markup (plist-get info :latex-text-markup-alist)))))
1488 (cl-case fmt
1489 ;; No format string: Return raw text.
1490 ((nil) text)
1491 ;; Handle the `verb' special case: Find an appropriate separator
1492 ;; and use "\\verb" command.
1493 (verb
1494 (let ((separator (org-latex--find-verb-separator text)))
1495 (concat "\\verb" separator
1496 (replace-regexp-in-string "\n" " " text)
1497 separator)))
1498 ;; Handle the `protectedtexttt' special case: Protect some
1499 ;; special chars and use "\texttt{%s}" format string.
1500 (protectedtexttt
1501 (format "\\texttt{%s}" (org-latex--protect-text text)))
1502 ;; Else use format string.
1503 (t (format fmt text)))))
1505 (defun org-latex--delayed-footnotes-definitions (element info)
1506 "Return footnotes definitions in ELEMENT as a string.
1508 INFO is a plist used as a communication channel.
1510 Footnotes definitions are returned within \"\\footnotetext{}\"
1511 commands.
1513 This function is used within constructs that don't support
1514 \"\\footnote{}\" command (i.e. an item's tag). In that case,
1515 \"\\footnotemark\" is used within the construct and the function
1516 just outside of it."
1517 (mapconcat
1518 (lambda (ref)
1519 (format
1520 "\\footnotetext[%s]{%s}"
1521 (org-export-get-footnote-number ref info)
1522 (org-trim
1523 (org-export-data
1524 (org-export-get-footnote-definition ref info) info))))
1525 ;; Find every footnote reference in ELEMENT.
1526 (letrec ((all-refs nil)
1527 (search-refs
1528 (lambda (data)
1529 ;; Return a list of all footnote references never seen
1530 ;; before in DATA.
1531 (org-element-map data 'footnote-reference
1532 (lambda (ref)
1533 (when (org-export-footnote-first-reference-p ref info)
1534 (push ref all-refs)
1535 (when (eq (org-element-property :type ref) 'standard)
1536 (funcall search-refs
1537 (org-export-get-footnote-definition ref info)))))
1538 info)
1539 (reverse all-refs))))
1540 (funcall search-refs element))
1541 ""))
1543 (defun org-latex--translate (s info)
1544 "Translate string S according to specified language.
1545 INFO is a plist used as a communication channel."
1546 (org-export-translate s :latex info))
1548 (defun org-latex--format-spec (info)
1549 "Create a format-spec for document meta-data.
1550 INFO is a plist used as a communication channel."
1551 (let ((language (let ((lang (plist-get info :language)))
1552 (or (cdr (assoc-string lang org-latex-babel-language-alist t))
1553 (nth 1 (assoc-string lang org-latex-polyglossia-language-alist t))
1554 lang))))
1555 `((?a . ,(org-export-data (plist-get info :author) info))
1556 (?t . ,(org-export-data (plist-get info :title) info))
1557 (?k . ,(org-export-data (org-latex--wrap-latex-math-block
1558 (plist-get info :keywords) info)
1559 info))
1560 (?d . ,(org-export-data (org-latex--wrap-latex-math-block
1561 (plist-get info :description) info)
1562 info))
1563 (?c . ,(plist-get info :creator))
1564 (?l . ,language)
1565 (?L . ,(capitalize language))
1566 (?D . ,(org-export-get-date info)))))
1568 (defun org-latex--make-preamble (info)
1569 "Return a formatted LaTeX preamble.
1570 INFO is a plist used as a communication channel."
1571 (let* ((class (plist-get info :latex-class))
1572 (class-options (plist-get info :latex-class-options))
1573 (header (nth 1 (assoc class (plist-get info :latex-classes))))
1574 (document-class-string
1575 (and (stringp header)
1576 (if (not class-options) header
1577 (replace-regexp-in-string
1578 "^[ \t]*\\\\documentclass\\(\\(\\[[^]]*\\]\\)?\\)"
1579 class-options header t nil 1)))))
1580 (if (not document-class-string)
1581 (user-error "Unknown LaTeX class `%s'" class)
1582 (org-latex-guess-polyglossia-language
1583 (org-latex-guess-babel-language
1584 (org-latex-guess-inputenc
1585 (org-element-normalize-string
1586 (org-splice-latex-header
1587 document-class-string
1588 (org-latex--remove-packages
1589 org-latex-default-packages-alist info)
1590 (org-latex--remove-packages
1591 org-latex-packages-alist info)
1593 (mapconcat 'org-element-normalize-string
1594 (list (plist-get info :latex-header)
1595 (plist-get info :latex-header-extra)) ""))))
1596 info)
1597 info))))
1599 (defun org-latex--insert-compiler (info)
1600 "Insert LaTeX_compiler info into the document.
1601 INFO is a plist used as a communication channel."
1602 (let ((compiler (plist-get info :latex-compiler)))
1603 (and (org-string-nw-p org-latex-compiler-file-string)
1604 (string-match-p (regexp-opt org-latex-compilers) (or compiler ""))
1605 (format org-latex-compiler-file-string compiler))))
1608 ;;; Template
1610 (defun org-latex-template (contents info)
1611 "Return complete document string after LaTeX conversion.
1612 CONTENTS is the transcoded contents string. INFO is a plist
1613 holding export options."
1614 (let ((title (org-export-data (plist-get info :title) info))
1615 (spec (org-latex--format-spec info)))
1616 (concat
1617 ;; Time-stamp.
1618 (and (plist-get info :time-stamp-file)
1619 (format-time-string "%% Created %Y-%m-%d %a %H:%M\n"))
1620 ;; LaTeX compiler.
1621 (org-latex--insert-compiler info)
1622 ;; Document class and packages.
1623 (org-latex--make-preamble info)
1624 ;; Possibly limit depth for headline numbering.
1625 (let ((sec-num (plist-get info :section-numbers)))
1626 (when (integerp sec-num)
1627 (format "\\setcounter{secnumdepth}{%d}\n" sec-num)))
1628 ;; Author.
1629 (let ((author (and (plist-get info :with-author)
1630 (let ((auth (plist-get info :author)))
1631 (and auth (org-export-data auth info)))))
1632 (email (and (plist-get info :with-email)
1633 (org-export-data (plist-get info :email) info))))
1634 (cond ((and author email (not (string= "" email)))
1635 (format "\\author{%s\\thanks{%s}}\n" author email))
1636 ((or author email) (format "\\author{%s}\n" (or author email)))))
1637 ;; Date.
1638 (let ((date (and (plist-get info :with-date) (org-export-get-date info))))
1639 (format "\\date{%s}\n" (org-export-data date info)))
1640 ;; Title and subtitle.
1641 (let* ((subtitle (plist-get info :subtitle))
1642 (formatted-subtitle
1643 (when subtitle
1644 (format (plist-get info :latex-subtitle-format)
1645 (org-export-data subtitle info))))
1646 (separate (plist-get info :latex-subtitle-separate)))
1647 (concat
1648 (format "\\title{%s%s}\n" title
1649 (if separate "" (or formatted-subtitle "")))
1650 (when (and separate subtitle)
1651 (concat formatted-subtitle "\n"))))
1652 ;; Hyperref options.
1653 (let ((template (plist-get info :latex-hyperref-template)))
1654 (and (stringp template)
1655 (format-spec template spec)))
1656 ;; Document start.
1657 "\\begin{document}\n\n"
1658 ;; Title command.
1659 (let* ((title-command (plist-get info :latex-title-command))
1660 (command (and (stringp title-command)
1661 (format-spec title-command spec))))
1662 (org-element-normalize-string
1663 (cond ((not (plist-get info :with-title)) nil)
1664 ((string= "" title) nil)
1665 ((not (stringp command)) nil)
1666 ((string-match "\\(?:[^%]\\|^\\)%s" command)
1667 (format command title))
1668 (t command))))
1669 ;; Table of contents.
1670 (let ((depth (plist-get info :with-toc)))
1671 (when depth
1672 (concat (when (wholenump depth)
1673 (format "\\setcounter{tocdepth}{%d}\n" depth))
1674 (plist-get info :latex-toc-command))))
1675 ;; Document's body.
1676 contents
1677 ;; Creator.
1678 (and (plist-get info :with-creator)
1679 (concat (plist-get info :creator) "\n"))
1680 ;; Document end.
1681 "\\end{document}")))
1685 ;;; Transcode Functions
1687 ;;;; Bold
1689 (defun org-latex-bold (_bold contents info)
1690 "Transcode BOLD from Org to LaTeX.
1691 CONTENTS is the text with bold markup. INFO is a plist holding
1692 contextual information."
1693 (org-latex--text-markup contents 'bold info))
1696 ;;;; Center Block
1698 (defun org-latex-center-block (center-block contents info)
1699 "Transcode a CENTER-BLOCK element from Org to LaTeX.
1700 CONTENTS holds the contents of the center block. INFO is a plist
1701 holding contextual information."
1702 (org-latex--wrap-label
1703 center-block (format "\\begin{center}\n%s\\end{center}" contents) info))
1706 ;;;; Clock
1708 (defun org-latex-clock (clock _contents info)
1709 "Transcode a CLOCK element from Org to LaTeX.
1710 CONTENTS is nil. INFO is a plist holding contextual
1711 information."
1712 (concat
1713 "\\noindent"
1714 (format "\\textbf{%s} " org-clock-string)
1715 (format (plist-get info :latex-inactive-timestamp-format)
1716 (concat (org-timestamp-translate (org-element-property :value clock))
1717 (let ((time (org-element-property :duration clock)))
1718 (and time (format " (%s)" time)))))
1719 "\\\\"))
1722 ;;;; Code
1724 (defun org-latex-code (code _contents info)
1725 "Transcode a CODE object from Org to LaTeX.
1726 CONTENTS is nil. INFO is a plist used as a communication
1727 channel."
1728 (org-latex--text-markup (org-element-property :value code) 'code info))
1731 ;;;; Drawer
1733 (defun org-latex-drawer (drawer contents info)
1734 "Transcode a DRAWER element from Org to LaTeX.
1735 CONTENTS holds the contents of the block. INFO is a plist
1736 holding contextual information."
1737 (let* ((name (org-element-property :drawer-name drawer))
1738 (output (funcall (plist-get info :latex-format-drawer-function)
1739 name contents)))
1740 (org-latex--wrap-label drawer output info)))
1743 ;;;; Dynamic Block
1745 (defun org-latex-dynamic-block (dynamic-block contents info)
1746 "Transcode a DYNAMIC-BLOCK element from Org to LaTeX.
1747 CONTENTS holds the contents of the block. INFO is a plist
1748 holding contextual information. See `org-export-data'."
1749 (org-latex--wrap-label dynamic-block contents info))
1752 ;;;; Entity
1754 (defun org-latex-entity (entity _contents _info)
1755 "Transcode an ENTITY object from Org to LaTeX.
1756 CONTENTS are the definition itself. INFO is a plist holding
1757 contextual information."
1758 (org-element-property :latex entity))
1761 ;;;; Example Block
1763 (defun org-latex-example-block (example-block _contents info)
1764 "Transcode an EXAMPLE-BLOCK element from Org to LaTeX.
1765 CONTENTS is nil. INFO is a plist holding contextual
1766 information."
1767 (when (org-string-nw-p (org-element-property :value example-block))
1768 (let ((environment (or (org-export-read-attribute
1769 :attr_latex example-block :environment)
1770 "verbatim")))
1771 (org-latex--wrap-label
1772 example-block
1773 (format "\\begin{%s}\n%s\\end{%s}"
1774 environment
1775 (org-export-format-code-default example-block info)
1776 environment)
1777 info))))
1780 ;;;; Export Block
1782 (defun org-latex-export-block (export-block _contents _info)
1783 "Transcode a EXPORT-BLOCK element from Org to LaTeX.
1784 CONTENTS is nil. INFO is a plist holding contextual information."
1785 (when (member (org-element-property :type export-block) '("LATEX" "TEX"))
1786 (org-remove-indentation (org-element-property :value export-block))))
1789 ;;;; Export Snippet
1791 (defun org-latex-export-snippet (export-snippet _contents _info)
1792 "Transcode a EXPORT-SNIPPET object from Org to LaTeX.
1793 CONTENTS is nil. INFO is a plist holding contextual information."
1794 (when (eq (org-export-snippet-backend export-snippet) 'latex)
1795 (org-element-property :value export-snippet)))
1798 ;;;; Fixed Width
1800 (defun org-latex-fixed-width (fixed-width _contents info)
1801 "Transcode a FIXED-WIDTH element from Org to LaTeX.
1802 CONTENTS is nil. INFO is a plist holding contextual information."
1803 (org-latex--wrap-label
1804 fixed-width
1805 (format "\\begin{verbatim}\n%s\\end{verbatim}"
1806 (org-remove-indentation
1807 (org-element-property :value fixed-width)))
1808 info))
1811 ;;;; Footnote Reference
1813 (defun org-latex-footnote-reference (footnote-reference _contents info)
1814 "Transcode a FOOTNOTE-REFERENCE element from Org to LaTeX.
1815 CONTENTS is nil. INFO is a plist holding contextual information."
1816 (let ((label (org-element-property :label footnote-reference)))
1817 (concat
1818 ;; Insert separator between two footnotes in a row.
1819 (let ((prev (org-export-get-previous-element footnote-reference info)))
1820 (when (eq (org-element-type prev) 'footnote-reference)
1821 (plist-get info :latex-footnote-separator)))
1822 (cond
1823 ;; Use `:latex-footnote-defined-format' if the footnote has
1824 ;; already been defined.
1825 ((not (org-export-footnote-first-reference-p footnote-reference info))
1826 (format (plist-get info :latex-footnote-defined-format)
1827 (org-latex--label
1828 (org-export-get-footnote-definition footnote-reference info)
1829 info t)))
1830 ;; Use \footnotemark if reference is within another footnote
1831 ;; reference, footnote definition or table cell.
1832 ((org-element-lineage footnote-reference
1833 '(footnote-reference footnote-definition table-cell))
1834 "\\footnotemark")
1835 ;; Otherwise, define it with \footnote command.
1837 (let ((def (org-export-get-footnote-definition footnote-reference info)))
1838 (concat
1839 (format "\\footnote{%s%s}" (org-trim (org-export-data def info))
1840 ;; Only insert a \label if there exist another
1841 ;; reference to def.
1842 (cond ((not label) "")
1843 ((org-element-map (plist-get info :parse-tree) 'footnote-reference
1844 (lambda (f)
1845 (and (not (eq f footnote-reference))
1846 (equal (org-element-property :label f) label)
1847 (org-trim (org-latex--label def info t t))))
1848 info t))
1849 (t "")))
1850 ;; Retrieve all footnote references within the footnote and
1851 ;; add their definition after it, since LaTeX doesn't support
1852 ;; them inside.
1853 (org-latex--delayed-footnotes-definitions def info))))))))
1856 ;;;; Headline
1858 (defun org-latex-headline (headline contents info)
1859 "Transcode a HEADLINE element from Org to LaTeX.
1860 CONTENTS holds the contents of the headline. INFO is a plist
1861 holding contextual information."
1862 (unless (org-element-property :footnote-section-p headline)
1863 (let* ((class (plist-get info :latex-class))
1864 (level (org-export-get-relative-level headline info))
1865 (numberedp (org-export-numbered-headline-p headline info))
1866 (class-sectioning (assoc class (plist-get info :latex-classes)))
1867 ;; Section formatting will set two placeholders: one for
1868 ;; the title and the other for the contents.
1869 (section-fmt
1870 (let ((sec (if (functionp (nth 2 class-sectioning))
1871 (funcall (nth 2 class-sectioning) level numberedp)
1872 (nth (1+ level) class-sectioning))))
1873 (cond
1874 ;; No section available for that LEVEL.
1875 ((not sec) nil)
1876 ;; Section format directly returned by a function. Add
1877 ;; placeholder for contents.
1878 ((stringp sec) (concat sec "\n%s"))
1879 ;; (numbered-section . unnumbered-section)
1880 ((not (consp (cdr sec)))
1881 (concat (funcall (if numberedp #'car #'cdr) sec) "\n%s"))
1882 ;; (numbered-open numbered-close)
1883 ((= (length sec) 2)
1884 (when numberedp (concat (car sec) "\n%s" (nth 1 sec))))
1885 ;; (num-in num-out no-num-in no-num-out)
1886 ((= (length sec) 4)
1887 (if numberedp (concat (car sec) "\n%s" (nth 1 sec))
1888 (concat (nth 2 sec) "\n%s" (nth 3 sec)))))))
1889 ;; Create a temporary export back-end that hard-codes
1890 ;; "\underline" within "\section" and alike.
1891 (section-back-end
1892 (org-export-create-backend
1893 :parent 'latex
1894 :transcoders
1895 '((underline . (lambda (o c i) (format "\\underline{%s}" c))))))
1896 (text
1897 (org-export-data-with-backend
1898 (org-element-property :title headline) section-back-end info))
1899 (todo
1900 (and (plist-get info :with-todo-keywords)
1901 (let ((todo (org-element-property :todo-keyword headline)))
1902 (and todo (org-export-data todo info)))))
1903 (todo-type (and todo (org-element-property :todo-type headline)))
1904 (tags (and (plist-get info :with-tags)
1905 (org-export-get-tags headline info)))
1906 (priority (and (plist-get info :with-priority)
1907 (org-element-property :priority headline)))
1908 ;; Create the headline text along with a no-tag version.
1909 ;; The latter is required to remove tags from toc.
1910 (full-text (funcall (plist-get info :latex-format-headline-function)
1911 todo todo-type priority text tags info))
1912 ;; Associate \label to the headline for internal links.
1913 (headline-label (org-latex--label headline info t t))
1914 (pre-blanks
1915 (make-string (org-element-property :pre-blank headline) ?\n)))
1916 (if (or (not section-fmt) (org-export-low-level-p headline info))
1917 ;; This is a deep sub-tree: export it as a list item. Also
1918 ;; export as items headlines for which no section format has
1919 ;; been found.
1920 (let ((low-level-body
1921 (concat
1922 ;; If headline is the first sibling, start a list.
1923 (when (org-export-first-sibling-p headline info)
1924 (format "\\begin{%s}\n" (if numberedp 'enumerate 'itemize)))
1925 ;; Itemize headline
1926 "\\item"
1927 (and full-text (org-string-match-p "\\`[ \t]*\\[" full-text)
1928 "\\relax")
1929 " " full-text "\n"
1930 headline-label
1931 pre-blanks
1932 contents)))
1933 ;; If headline is not the last sibling simply return
1934 ;; LOW-LEVEL-BODY. Otherwise, also close the list, before
1935 ;; any blank line.
1936 (if (not (org-export-last-sibling-p headline info)) low-level-body
1937 (replace-regexp-in-string
1938 "[ \t\n]*\\'"
1939 (format "\n\\\\end{%s}" (if numberedp 'enumerate 'itemize))
1940 low-level-body)))
1941 ;; This is a standard headline. Export it as a section. Add
1942 ;; an alternative heading when possible, and when this is not
1943 ;; identical to the usual heading.
1944 (let ((opt-title
1945 (funcall (plist-get info :latex-format-headline-function)
1946 todo todo-type priority
1947 (org-export-data-with-backend
1948 (org-export-get-alt-title headline info)
1949 section-back-end info)
1950 (and (eq (plist-get info :with-tags) t) tags)
1951 info))
1952 ;; Maybe end local TOC (see `org-latex-keyword').
1953 (contents
1954 (concat
1955 contents
1956 (let ((case-fold-search t)
1957 (section
1958 (let ((first (car (org-element-contents headline))))
1959 (and (eq (org-element-type first) 'section) first))))
1960 (org-element-map section 'keyword
1961 (lambda (k)
1962 (and (equal (org-element-property :key k) "TOC")
1963 (let ((v (org-element-property :value k)))
1964 (and (org-string-match-p "\\<headlines\\>" v)
1965 (org-string-match-p "\\<local\\>" v)
1966 (format "\\stopcontents[level-%d]" level)))))
1967 info t)))))
1968 (if (and opt-title
1969 (not (equal opt-title full-text))
1970 (string-match "\\`\\\\\\(.+?\\){" section-fmt))
1971 (format (replace-match "\\1[%s]" nil nil section-fmt 1)
1972 ;; Replace square brackets with parenthesis
1973 ;; since square brackets are not supported in
1974 ;; optional arguments.
1975 (replace-regexp-in-string
1976 "\\[" "(" (replace-regexp-in-string "\\]" ")" opt-title))
1977 full-text
1978 (concat headline-label pre-blanks contents))
1979 ;; Impossible to add an alternative heading. Fallback to
1980 ;; regular sectioning format string.
1981 (format section-fmt full-text
1982 (concat headline-label pre-blanks contents))))))))
1984 (defun org-latex-format-headline-default-function
1985 (todo _todo-type priority text tags info)
1986 "Default format function for a headline.
1987 See `org-latex-format-headline-function' for details."
1988 (concat
1989 (and todo (format "{\\bfseries\\sffamily %s} " todo))
1990 (and priority (format "\\framebox{\\#%c} " priority))
1991 text
1992 (and tags
1993 (format "\\hfill{}\\textsc{%s}"
1994 (mapconcat (lambda (tag) (org-latex-plain-text tag info))
1995 tags ":")))))
1998 ;;;; Horizontal Rule
2000 (defun org-latex-horizontal-rule (horizontal-rule _contents info)
2001 "Transcode an HORIZONTAL-RULE object from Org to LaTeX.
2002 CONTENTS is nil. INFO is a plist holding contextual information."
2003 (let ((attr (org-export-read-attribute :attr_latex horizontal-rule))
2004 (prev (org-export-get-previous-element horizontal-rule info)))
2005 (concat
2006 ;; Make sure the rule doesn't start at the end of the current
2007 ;; line by separating it with a blank line from previous element.
2008 (when (and prev
2009 (let ((prev-blank (org-element-property :post-blank prev)))
2010 (or (not prev-blank) (zerop prev-blank))))
2011 "\n")
2012 (org-latex--wrap-label
2013 horizontal-rule
2014 (format "\\rule{%s}{%s}"
2015 (or (plist-get attr :width) "\\linewidth")
2016 (or (plist-get attr :thickness) "0.5pt"))
2017 info))))
2020 ;;;; Inline Src Block
2022 (defun org-latex-inline-src-block (inline-src-block _contents info)
2023 "Transcode an INLINE-SRC-BLOCK element from Org to LaTeX.
2024 CONTENTS holds the contents of the item. INFO is a plist holding
2025 contextual information."
2026 (let* ((code (org-element-property :value inline-src-block))
2027 (separator (org-latex--find-verb-separator code)))
2028 (cl-case (plist-get info :latex-listings)
2029 ;; Do not use a special package: transcode it verbatim.
2030 ((nil) (format "\\texttt{%s}" (org-latex--protect-text code)))
2031 ;; Use minted package.
2032 (minted
2033 (let* ((org-lang (org-element-property :language inline-src-block))
2034 (mint-lang (or (cadr (assq (intern org-lang)
2035 (plist-get info :latex-minted-langs)))
2036 (downcase org-lang)))
2037 (options (org-latex--make-option-string
2038 (plist-get info :latex-minted-options))))
2039 (format "\\mintinline%s{%s}{%s}"
2040 (if (string= options "") "" (format "[%s]" options))
2041 mint-lang
2042 code)))
2043 ;; Use listings package.
2044 (otherwise
2045 ;; Maybe translate language's name.
2046 (let* ((org-lang (org-element-property :language inline-src-block))
2047 (lst-lang (or (cadr (assq (intern org-lang)
2048 (plist-get info :latex-listings-langs)))
2049 org-lang))
2050 (options (org-latex--make-option-string
2051 (append (plist-get info :latex-listings-options)
2052 `(("language" ,lst-lang))))))
2053 (concat (format "\\lstinline[%s]" options)
2054 separator code separator))))))
2057 ;;;; Inlinetask
2059 (defun org-latex-inlinetask (inlinetask contents info)
2060 "Transcode an INLINETASK element from Org to LaTeX.
2061 CONTENTS holds the contents of the block. INFO is a plist
2062 holding contextual information."
2063 (let ((title (org-export-data (org-element-property :title inlinetask) info))
2064 (todo (and (plist-get info :with-todo-keywords)
2065 (let ((todo (org-element-property :todo-keyword inlinetask)))
2066 (and todo (org-export-data todo info)))))
2067 (todo-type (org-element-property :todo-type inlinetask))
2068 (tags (and (plist-get info :with-tags)
2069 (org-export-get-tags inlinetask info)))
2070 (priority (and (plist-get info :with-priority)
2071 (org-element-property :priority inlinetask)))
2072 (contents (concat (org-latex--label inlinetask info) contents)))
2073 (funcall (plist-get info :latex-format-inlinetask-function)
2074 todo todo-type priority title tags contents info)))
2076 (defun org-latex-format-inlinetask-default-function
2077 (todo _todo-type priority title tags contents info)
2078 "Default format function for a inlinetasks.
2079 See `org-latex-format-inlinetask-function' for details."
2080 (let ((full-title
2081 (concat (when todo (format "\\textbf{\\textsf{\\textsc{%s}}} " todo))
2082 (when priority (format "\\framebox{\\#%c} " priority))
2083 title
2084 (when tags
2085 (format "\\hfill{}\\textsc{:%s:}"
2086 (mapconcat
2087 (lambda (tag) (org-latex-plain-text tag info))
2088 tags ":"))))))
2089 (concat "\\begin{center}\n"
2090 "\\fbox{\n"
2091 "\\begin{minipage}[c]{.6\\textwidth}\n"
2092 full-title "\n\n"
2093 (and (org-string-nw-p contents)
2094 (concat "\\rule[.8em]{\\textwidth}{2pt}\n\n" contents))
2095 "\\end{minipage}\n"
2096 "}\n"
2097 "\\end{center}")))
2100 ;;;; Italic
2102 (defun org-latex-italic (_italic contents info)
2103 "Transcode ITALIC from Org to LaTeX.
2104 CONTENTS is the text with italic markup. INFO is a plist holding
2105 contextual information."
2106 (org-latex--text-markup contents 'italic info))
2109 ;;;; Item
2111 (defun org-latex-item (item contents info)
2112 "Transcode an ITEM element from Org to LaTeX.
2113 CONTENTS holds the contents of the item. INFO is a plist holding
2114 contextual information."
2115 (let* ((counter
2116 (let ((count (org-element-property :counter item))
2117 (level
2118 ;; Determine level of current item to determine the
2119 ;; correct LaTeX counter to use (enumi, enumii...).
2120 (let ((parent item) (level 0))
2121 (while (memq (org-element-type
2122 (setq parent (org-export-get-parent parent)))
2123 '(plain-list item))
2124 (when (and (eq (org-element-type parent) 'plain-list)
2125 (eq (org-element-property :type parent)
2126 'ordered))
2127 (cl-incf level)))
2128 level)))
2129 (and count
2130 (< level 5)
2131 (format "\\setcounter{enum%s}{%s}\n"
2132 (nth (1- level) '("i" "ii" "iii" "iv"))
2133 (1- count)))))
2134 (checkbox (cl-case (org-element-property :checkbox item)
2135 (on "$\\boxtimes$ ")
2136 (off "$\\square$ ")
2137 (trans "$\\boxminus$ ")))
2138 (tag (let ((tag (org-element-property :tag item)))
2139 ;; Check-boxes must belong to the tag.
2140 (and tag (format "[{%s}] "
2141 (concat checkbox
2142 (org-export-data tag info)))))))
2143 (concat counter
2144 "\\item"
2145 (cond
2146 (tag)
2147 (checkbox (concat " " checkbox))
2148 ;; Without a tag or a check-box, if CONTENTS starts with
2149 ;; an opening square bracket, add "\relax" to "\item",
2150 ;; unless the brackets comes from an initial export
2151 ;; snippet (i.e. it is inserted willingly by the user).
2152 ((and contents
2153 (org-string-match-p "\\`[ \t]*\\[" contents)
2154 (not (let ((e (car (org-element-contents item))))
2155 (and (eq (org-element-type e) 'paragraph)
2156 (let ((o (car (org-element-contents e))))
2157 (and (eq (org-element-type o) 'export-snippet)
2158 (eq (org-export-snippet-backend o)
2159 'latex)))))))
2160 "\\relax ")
2161 (t " "))
2162 (and contents (org-trim contents))
2163 ;; If there are footnotes references in tag, be sure to
2164 ;; add their definition at the end of the item. This
2165 ;; workaround is necessary since "\footnote{}" command is
2166 ;; not supported in tags.
2167 (and tag
2168 (org-latex--delayed-footnotes-definitions
2169 (org-element-property :tag item) info)))))
2172 ;;;; Keyword
2174 (defun org-latex-keyword (keyword _contents info)
2175 "Transcode a KEYWORD element from Org to LaTeX.
2176 CONTENTS is nil. INFO is a plist holding contextual information."
2177 (let ((key (org-element-property :key keyword))
2178 (value (org-element-property :value keyword)))
2179 (cond
2180 ((string= key "LATEX") value)
2181 ((string= key "INDEX") (format "\\index{%s}" value))
2182 ((string= key "TOC")
2183 (let ((case-fold-search t))
2184 (cond
2185 ((org-string-match-p "\\<headlines\\>" value)
2186 (let* ((localp (org-string-match-p "\\<local\\>" value))
2187 (parent (org-element-lineage keyword '(headline)))
2188 (level (if (not (and localp parent)) 0
2189 (org-export-get-relative-level parent info)))
2190 (depth
2191 (and (string-match "\\<[0-9]+\\>" value)
2192 (format
2193 "\\setcounter{tocdepth}{%d}"
2194 (+ (string-to-number (match-string 0 value)) level)))))
2195 (if (and localp parent)
2196 ;; Start local TOC, assuming package "titletoc" is
2197 ;; required.
2198 (format "\\startcontents[level-%d]
2199 \\printcontents[level-%d]{}{0}{%s}"
2200 level level (or depth ""))
2201 (concat depth (and depth "\n") "\\tableofcontents"))))
2202 ((org-string-match-p "\\<tables\\>" value) "\\listoftables")
2203 ((org-string-match-p "\\<listings\\>" value)
2204 (cl-case (plist-get info :latex-listings)
2205 ((nil) "\\listoffigures")
2206 (minted "\\listoflistings")
2207 (otherwise "\\lstlistoflistings")))))))))
2210 ;;;; Latex Environment
2212 (defun org-latex-latex-environment (latex-environment _contents info)
2213 "Transcode a LATEX-ENVIRONMENT element from Org to LaTeX.
2214 CONTENTS is nil. INFO is a plist holding contextual information."
2215 (when (plist-get info :with-latex)
2216 (let ((value (org-remove-indentation
2217 (org-element-property :value latex-environment))))
2218 (if (not (org-element-property :name latex-environment)) value
2219 ;; Environment is labeled: label must be within the environment
2220 ;; (otherwise, a reference pointing to that element will count
2221 ;; the section instead).
2222 (with-temp-buffer
2223 (insert value)
2224 (goto-char (point-min))
2225 (forward-line)
2226 (insert (org-latex--label latex-environment info nil t))
2227 (buffer-string))))))
2230 ;;;; Latex Fragment
2232 (defun org-latex-latex-fragment (latex-fragment _contents _info)
2233 "Transcode a LATEX-FRAGMENT object from Org to LaTeX.
2234 CONTENTS is nil. INFO is a plist holding contextual information."
2235 (let ((value (org-element-property :value latex-fragment)))
2236 ;; Trim math markers since the fragment is enclosed within
2237 ;; a latex-math-block object anyway.
2238 (cond ((string-match-p "\\`\\$[^$]" value) (substring value 1 -1))
2239 ((string-prefix-p "\\(" value) (substring value 2 -2))
2240 (t value))))
2243 ;;;; Line Break
2245 (defun org-latex-line-break (_line-break _contents _info)
2246 "Transcode a LINE-BREAK object from Org to LaTeX.
2247 CONTENTS is nil. INFO is a plist holding contextual information."
2248 "\\\\\n")
2251 ;;;; Link
2253 (defun org-latex--inline-image (link info)
2254 "Return LaTeX code for an inline image.
2255 LINK is the link pointing to the inline image. INFO is a plist
2256 used as a communication channel."
2257 (let* ((parent (org-export-get-parent-element link))
2258 (path (let ((raw-path (org-element-property :path link)))
2259 (if (not (file-name-absolute-p raw-path)) raw-path
2260 (expand-file-name raw-path))))
2261 (filetype (file-name-extension path))
2262 (caption (org-latex--caption/label-string parent info))
2263 (caption-above-p (org-latex--caption-above-p link info))
2264 ;; Retrieve latex attributes from the element around.
2265 (attr (org-export-read-attribute :attr_latex parent))
2266 (float (let ((float (plist-get attr :float)))
2267 (cond ((string= float "wrap") 'wrap)
2268 ((string= float "sideways") 'sideways)
2269 ((string= float "multicolumn") 'multicolumn)
2270 ((or float
2271 (org-element-property :caption parent)
2272 (org-string-nw-p (plist-get attr :caption)))
2273 (if (and (plist-member attr :float) (not float))
2274 'nonfloat
2275 'figure))
2276 ((and (not float) (plist-member attr :float)) nil))))
2277 (placement
2278 (let ((place (plist-get attr :placement)))
2279 (cond
2280 (place (format "%s" place))
2281 ((eq float 'wrap) "{l}{0.5\\textwidth}")
2282 ((eq float 'figure)
2283 (format "[%s]" (plist-get info :latex-default-figure-position)))
2284 (t ""))))
2285 (comment-include (if (plist-get attr :comment-include) "%" ""))
2286 ;; It is possible to specify width and height in the
2287 ;; ATTR_LATEX line, and also via default variables.
2288 (width (cond ((plist-get attr :width))
2289 ((plist-get attr :height) "")
2290 ((eq float 'wrap) "0.48\\textwidth")
2291 (t (plist-get info :latex-image-default-width))))
2292 (height (cond ((plist-get attr :height))
2293 ((or (plist-get attr :width)
2294 (memq float '(figure wrap))) "")
2295 (t (plist-get info :latex-image-default-height))))
2296 (options (let ((opt (or (plist-get attr :options)
2297 (plist-get info :latex-image-default-option))))
2298 (if (not (string-match "\\`\\[\\(.*\\)\\]\\'" opt)) opt
2299 (match-string 1 opt))))
2300 image-code)
2301 (if (member filetype '("tikz" "pgf"))
2302 ;; For tikz images:
2303 ;; - use \input to read in image file.
2304 ;; - if options are present, wrap in a tikzpicture environment.
2305 ;; - if width or height are present, use \resizebox to change
2306 ;; the image size.
2307 (progn
2308 (setq image-code (format "\\input{%s}" path))
2309 (when (org-string-nw-p options)
2310 (setq image-code
2311 (format "\\begin{tikzpicture}[%s]\n%s\n\\end{tikzpicture}"
2312 options
2313 image-code)))
2314 (when (or (org-string-nw-p width) (org-string-nw-p height))
2315 (setq image-code (format "\\resizebox{%s}{%s}{%s}"
2316 (if (org-string-nw-p width) width "!")
2317 (if (org-string-nw-p height) height "!")
2318 image-code))))
2319 ;; For other images:
2320 ;; - add width and height to options.
2321 ;; - include the image with \includegraphics.
2322 (when (org-string-nw-p width)
2323 (setq options (concat options ",width=" width)))
2324 (when (org-string-nw-p height)
2325 (setq options (concat options ",height=" height)))
2326 (let ((search-option (org-element-property :search-option link)))
2327 (when (and search-option
2328 (equal filetype "pdf")
2329 (org-string-match-p "\\`[0-9]+\\'" search-option)
2330 (not (org-string-match-p "page=" options)))
2331 (setq options (concat options ",page=" search-option))))
2332 (setq image-code
2333 (format "\\includegraphics%s{%s}"
2334 (cond ((not (org-string-nw-p options)) "")
2335 ((= (aref options 0) ?,)
2336 (format "[%s]"(substring options 1)))
2337 (t (format "[%s]" options)))
2338 path))
2339 (when (equal filetype "svg")
2340 (setq image-code (replace-regexp-in-string "^\\\\includegraphics"
2341 "\\includesvg"
2342 image-code
2343 nil t))
2344 (setq image-code (replace-regexp-in-string "\\.svg}"
2346 image-code
2347 nil t))))
2348 ;; Return proper string, depending on FLOAT.
2349 (cl-case float
2350 (wrap (format "\\begin{wrapfigure}%s
2351 %s\\centering
2352 %s%s
2353 %s\\end{wrapfigure}"
2354 placement
2355 (if caption-above-p caption "")
2356 comment-include image-code
2357 (if caption-above-p "" caption)))
2358 (sideways (format "\\begin{sidewaysfigure}
2359 %s\\centering
2360 %s%s
2361 %s\\end{sidewaysfigure}"
2362 (if caption-above-p caption "")
2363 comment-include image-code
2364 (if caption-above-p "" caption)))
2365 (multicolumn (format "\\begin{figure*}%s
2366 %s\\centering
2367 %s%s
2368 %s\\end{figure*}"
2369 placement
2370 (if caption-above-p caption "")
2371 comment-include image-code
2372 (if caption-above-p "" caption)))
2373 (figure (format "\\begin{figure}%s
2374 %s\\centering
2375 %s%s
2376 %s\\end{figure}"
2377 placement
2378 (if caption-above-p caption "")
2379 comment-include image-code
2380 (if caption-above-p "" caption)))
2381 (nonfloat
2382 (format "\\begin{center}
2383 %s%s
2384 %s\\end{center}"
2385 (if caption-above-p caption "")
2386 image-code
2387 (if caption-above-p "" caption)))
2388 (otherwise image-code))))
2390 (defun org-latex-link (link desc info)
2391 "Transcode a LINK object from Org to LaTeX.
2393 DESC is the description part of the link, or the empty string.
2394 INFO is a plist holding contextual information. See
2395 `org-export-data'."
2396 (let* ((type (org-element-property :type link))
2397 (raw-path (replace-regexp-in-string
2398 "%" "\\%" (org-element-property :path link) nil t))
2399 ;; Ensure DESC really exists, or set it to nil.
2400 (desc (and (not (string= desc "")) desc))
2401 (imagep (org-export-inline-image-p
2402 link (plist-get info :latex-inline-image-rules)))
2403 (path (cond
2404 ((member type '("http" "https" "ftp" "mailto" "doi"))
2405 (concat type ":" raw-path))
2406 ((string= type "file") (org-export-file-uri raw-path))
2407 (t raw-path))))
2408 (cond
2409 ;; Link type is handled by a special function.
2410 ((org-export-custom-protocol-maybe link desc 'latex))
2411 ;; Image file.
2412 (imagep (org-latex--inline-image link info))
2413 ;; Radio link: Transcode target's contents and use them as link's
2414 ;; description.
2415 ((string= type "radio")
2416 (let ((destination (org-export-resolve-radio-link link info)))
2417 (if (not destination) desc
2418 (format "\\hyperref[%s]{%s}"
2419 (org-export-get-reference destination info)
2420 desc))))
2421 ;; Links pointing to a headline: Find destination and build
2422 ;; appropriate referencing command.
2423 ((member type '("custom-id" "fuzzy" "id"))
2424 (let ((destination (if (string= type "fuzzy")
2425 (org-export-resolve-fuzzy-link link info)
2426 (org-export-resolve-id-link link info))))
2427 (cl-case (org-element-type destination)
2428 ;; Id link points to an external file.
2429 (plain-text
2430 (if desc (format "\\href{%s}{%s}" destination desc)
2431 (format "\\url{%s}" destination)))
2432 ;; Fuzzy link points nowhere.
2433 ((nil)
2434 (format (plist-get info :latex-link-with-unknown-path-format)
2435 (or desc
2436 (org-export-data
2437 (org-element-property :raw-link link) info))))
2438 ;; LINK points to a headline. If headlines are numbered
2439 ;; and the link has no description, display headline's
2440 ;; number. Otherwise, display description or headline's
2441 ;; title.
2442 (headline
2443 (let ((label (org-latex--label destination info t)))
2444 (if (and (not desc)
2445 (org-export-numbered-headline-p destination info))
2446 (format "\\ref{%s}" label)
2447 (format "\\hyperref[%s]{%s}" label
2448 (or desc
2449 (org-export-data
2450 (org-element-property :title destination) info))))))
2451 ;; Fuzzy link points to a target. Do as above.
2452 (otherwise
2453 (let ((ref (org-latex--label destination info t)))
2454 (if (not desc) (format "\\ref{%s}" ref)
2455 (format "\\hyperref[%s]{%s}" ref desc)))))))
2456 ;; Coderef: replace link with the reference name or the
2457 ;; equivalent line number.
2458 ((string= type "coderef")
2459 (format (org-export-get-coderef-format path desc)
2460 (org-export-resolve-coderef path info)))
2461 ;; External link with a description part.
2462 ((and path desc) (format "\\href{%s}{%s}" path desc))
2463 ;; External link without a description part.
2464 (path (format "\\url{%s}" path))
2465 ;; No path, only description. Try to do something useful.
2466 (t (format (plist-get info :latex-link-with-unknown-path-format) desc)))))
2469 ;;;; Node Property
2471 (defun org-latex-node-property (node-property _contents _info)
2472 "Transcode a NODE-PROPERTY element from Org to LaTeX.
2473 CONTENTS is nil. INFO is a plist holding contextual
2474 information."
2475 (format "%s:%s"
2476 (org-element-property :key node-property)
2477 (let ((value (org-element-property :value node-property)))
2478 (if value (concat " " value) ""))))
2481 ;;;; Paragraph
2483 (defun org-latex-paragraph (_paragraph contents _info)
2484 "Transcode a PARAGRAPH element from Org to LaTeX.
2485 CONTENTS is the contents of the paragraph, as a string. INFO is
2486 the plist used as a communication channel."
2487 contents)
2490 ;;;; Plain List
2492 (defun org-latex-plain-list (plain-list contents info)
2493 "Transcode a PLAIN-LIST element from Org to LaTeX.
2494 CONTENTS is the contents of the list. INFO is a plist holding
2495 contextual information."
2496 (let* ((type (org-element-property :type plain-list))
2497 (attr (org-export-read-attribute :attr_latex plain-list))
2498 (latex-type (let ((env (plist-get attr :environment)))
2499 (cond (env (format "%s" env))
2500 ((eq type 'ordered) "enumerate")
2501 ((eq type 'descriptive) "description")
2502 (t "itemize")))))
2503 (org-latex--wrap-label
2504 plain-list
2505 (format "\\begin{%s}%s\n%s\\end{%s}"
2506 latex-type
2507 (or (plist-get attr :options) "")
2508 contents
2509 latex-type)
2510 info)))
2513 ;;;; Plain Text
2515 (defun org-latex-plain-text (text info)
2516 "Transcode a TEXT string from Org to LaTeX.
2517 TEXT is the string to transcode. INFO is a plist holding
2518 contextual information."
2519 (let* ((specialp (plist-get info :with-special-strings))
2520 (output
2521 ;; Turn LaTeX into \LaTeX{} and TeX into \TeX{}.
2522 (let ((case-fold-search nil))
2523 (replace-regexp-in-string
2524 "\\<\\(?:La\\)?TeX\\>" "\\\\\\&{}"
2525 ;; Protect ^, ~, %, #, &, $, _, { and }. Also protect \.
2526 ;; However, if special strings are used, be careful not
2527 ;; to protect "\" in "\-" constructs.
2528 (replace-regexp-in-string
2529 (concat "[%$#&{}_~^]\\|\\\\" (and specialp "\\([^-]\\|$\\)"))
2530 (lambda (m)
2531 (cl-case (string-to-char m)
2532 (?\\ "$\\\\backslash$\\1")
2533 (?~ "\\\\textasciitilde{}")
2534 (?^ "\\\\^{}")
2535 (t "\\\\\\&")))
2536 text)))))
2537 ;; Activate smart quotes. Be sure to provide original TEXT string
2538 ;; since OUTPUT may have been modified.
2539 (when (plist-get info :with-smart-quotes)
2540 (setq output (org-export-activate-smart-quotes output :latex info text)))
2541 ;; Convert special strings.
2542 (when specialp
2543 (setq output (replace-regexp-in-string "\\.\\.\\." "\\\\ldots{}" output)))
2544 ;; Handle break preservation if required.
2545 (when (plist-get info :preserve-breaks)
2546 (setq output (replace-regexp-in-string
2547 "\\(?:[ \t]*\\\\\\\\\\)?[ \t]*\n" "\\\\\n" output nil t)))
2548 ;; Return value.
2549 output))
2552 ;;;; Planning
2554 (defun org-latex-planning (planning _contents info)
2555 "Transcode a PLANNING element from Org to LaTeX.
2556 CONTENTS is nil. INFO is a plist holding contextual
2557 information."
2558 (concat
2559 "\\noindent"
2560 (mapconcat
2561 'identity
2562 (delq nil
2563 (list
2564 (let ((closed (org-element-property :closed planning)))
2565 (when closed
2566 (concat
2567 (format "\\textbf{%s} " org-closed-string)
2568 (format (plist-get info :latex-inactive-timestamp-format)
2569 (org-timestamp-translate closed)))))
2570 (let ((deadline (org-element-property :deadline planning)))
2571 (when deadline
2572 (concat
2573 (format "\\textbf{%s} " org-deadline-string)
2574 (format (plist-get info :latex-active-timestamp-format)
2575 (org-timestamp-translate deadline)))))
2576 (let ((scheduled (org-element-property :scheduled planning)))
2577 (when scheduled
2578 (concat
2579 (format "\\textbf{%s} " org-scheduled-string)
2580 (format (plist-get info :latex-active-timestamp-format)
2581 (org-timestamp-translate scheduled)))))))
2582 " ")
2583 "\\\\"))
2586 ;;;; Property Drawer
2588 (defun org-latex-property-drawer (_property-drawer contents _info)
2589 "Transcode a PROPERTY-DRAWER element from Org to LaTeX.
2590 CONTENTS holds the contents of the drawer. INFO is a plist
2591 holding contextual information."
2592 (and (org-string-nw-p contents)
2593 (format "\\begin{verbatim}\n%s\\end{verbatim}" contents)))
2596 ;;;; Pseudo Element: LaTeX Matrices
2598 ;; `latex-matrices' elements have the following properties:
2599 ;; `:caption', `:post-blank' and `:markup' (`inline', `equation' or
2600 ;; `math').
2602 (defun org-latex--wrap-latex-matrices (data info)
2603 "Merge contiguous tables with the same mode within a pseudo-element.
2604 DATA is a parse tree or a secondary string. INFO is a plist
2605 containing export options. Modify DATA by side-effect and return
2606 it."
2607 (org-element-map data 'table
2608 (lambda (table)
2609 (when (eq (org-element-property :type table) 'org)
2610 (let ((mode (or (org-export-read-attribute :attr_latex table :mode)
2611 (plist-get info :latex-default-table-mode))))
2612 (when (and (member mode '("inline-math" "math"))
2613 ;; Do not wrap twice the same table.
2614 (not (eq (org-element-type
2615 (org-element-property :parent table))
2616 'latex-matrices)))
2617 (let* ((caption (and (not (string= mode "inline-math"))
2618 (org-element-property :caption table)))
2619 (matrices
2620 (list 'latex-matrices
2621 (list :caption caption
2622 :markup
2623 (cond ((string= mode "inline-math") 'inline)
2624 (caption 'equation)
2625 (t 'math)))))
2626 (previous table)
2627 (next (org-export-get-next-element table info)))
2628 (org-element-insert-before matrices table)
2629 ;; Swallow all contiguous tables sharing the same mode.
2630 (while (and
2631 (zerop (or (org-element-property :post-blank previous) 0))
2632 (setq next (org-export-get-next-element previous info))
2633 (eq (org-element-type next) 'table)
2634 (eq (org-element-property :type next) 'org)
2635 (string= (or (org-export-read-attribute
2636 :attr_latex next :mode)
2637 (plist-get info :latex-default-table-mode))
2638 mode))
2639 (org-element-extract-element previous)
2640 (org-element-adopt-elements matrices previous)
2641 (setq previous next))
2642 (org-element-put-property
2643 matrices :post-blank (org-element-property :post-blank previous))
2644 (org-element-extract-element previous)
2645 (org-element-adopt-elements matrices previous))))))
2646 info)
2647 data)
2649 (defun org-latex-matrices (matrices contents _info)
2650 "Transcode a MATRICES element from Org to LaTeX.
2651 CONTENTS is a string. INFO is a plist used as a communication
2652 channel."
2653 (format (cl-case (org-element-property :markup matrices)
2654 (inline "\\(%s\\)")
2655 (equation "\\begin{equation}\n%s\\end{equation}")
2656 (t "\\[\n%s\\]"))
2657 contents))
2659 (defun org-latex-matrices-tree-filter (tree _backend info)
2660 (org-latex--wrap-latex-matrices tree info))
2662 ;;;; Pseudo Object: LaTeX Math Block
2664 ;; `latex-math-block' objects have the following property:
2665 ;; `:post-blank'.
2667 (defun org-latex--wrap-latex-math-block (data info)
2668 "Merge contiguous math objects in a pseudo-object container.
2669 DATA is a parse tree or a secondary string. INFO is a plist
2670 containing export options. Modify DATA by side-effect and return it."
2671 (let ((valid-object-p
2672 ;; Non-nil when OBJ can be added to the latex math block.
2673 (lambda (obj)
2674 (pcase (org-element-type obj)
2675 (`entity (org-element-property :latex-math-p obj))
2676 (`latex-fragment
2677 (let ((value (org-element-property :value obj)))
2678 (or (string-prefix-p "\\(" value)
2679 (string-match-p "\\`\\$[^$]" value))))
2680 ((or `subscript `superscript) t)))))
2681 (org-element-map data '(entity latex-fragment subscript superscript)
2682 (lambda (object)
2683 ;; Skip objects already wrapped.
2684 (when (and (not (eq (org-element-type
2685 (org-element-property :parent object))
2686 'latex-math-block))
2687 (funcall valid-object-p object))
2688 (let ((math-block (list 'latex-math-block nil))
2689 (next-elements (org-export-get-next-element object info t))
2690 (last object))
2691 ;; Wrap MATH-BLOCK around OBJECT in DATA.
2692 (org-element-insert-before math-block object)
2693 (org-element-extract-element object)
2694 (org-element-adopt-elements math-block object)
2695 (when (zerop (or (org-element-property :post-blank object) 0))
2696 ;; MATH-BLOCK swallows consecutive math objects.
2697 (catch 'exit
2698 (dolist (next next-elements)
2699 (if (not (funcall valid-object-p next)) (throw 'exit nil)
2700 (org-element-extract-element next)
2701 (org-element-adopt-elements math-block next)
2702 ;; Eschew the case: \beta$x$ -> \(\betax\).
2703 (unless (memq (org-element-type next)
2704 '(subscript superscript))
2705 (org-element-put-property last :post-blank 1))
2706 (setq last next)
2707 (when (> (or (org-element-property :post-blank next) 0) 0)
2708 (throw 'exit nil))))))
2709 (org-element-put-property
2710 math-block :post-blank (org-element-property :post-blank last)))))
2711 info nil '(subscript superscript latex-math-block) t)
2712 ;; Return updated DATA.
2713 data))
2715 (defun org-latex-math-block-tree-filter (tree _backend info)
2716 (org-latex--wrap-latex-math-block tree info))
2718 (defun org-latex-math-block-options-filter (info _backend)
2719 (dolist (prop '(:author :date :title) info)
2720 (plist-put info prop
2721 (org-latex--wrap-latex-math-block (plist-get info prop) info))))
2723 (defun org-latex-math-block (_math-block contents _info)
2724 "Transcode a MATH-BLOCK object from Org to LaTeX.
2725 CONTENTS is a string. INFO is a plist used as a communication
2726 channel."
2727 (when (org-string-nw-p contents)
2728 (format "\\(%s\\)" (org-trim contents))))
2730 ;;;; Quote Block
2732 (defun org-latex-quote-block (quote-block contents info)
2733 "Transcode a QUOTE-BLOCK element from Org to LaTeX.
2734 CONTENTS holds the contents of the block. INFO is a plist
2735 holding contextual information."
2736 (org-latex--wrap-label
2737 quote-block (format "\\begin{quote}\n%s\\end{quote}" contents) info))
2740 ;;;; Radio Target
2742 (defun org-latex-radio-target (radio-target text info)
2743 "Transcode a RADIO-TARGET object from Org to LaTeX.
2744 TEXT is the text of the target. INFO is a plist holding
2745 contextual information."
2746 (format "\\label{%s}%s" (org-export-get-reference radio-target info) text))
2749 ;;;; Section
2751 (defun org-latex-section (_section contents _info)
2752 "Transcode a SECTION element from Org to LaTeX.
2753 CONTENTS holds the contents of the section. INFO is a plist
2754 holding contextual information."
2755 contents)
2758 ;;;; Special Block
2760 (defun org-latex-special-block (special-block contents info)
2761 "Transcode a SPECIAL-BLOCK element from Org to LaTeX.
2762 CONTENTS holds the contents of the block. INFO is a plist
2763 holding contextual information."
2764 (let ((type (org-element-property :type special-block))
2765 (opt (org-export-read-attribute :attr_latex special-block :options))
2766 (caption (org-latex--caption/label-string special-block info))
2767 (caption-above-p (org-latex--caption-above-p special-block info)))
2768 (concat (format "\\begin{%s}%s\n" type (or opt ""))
2769 (and caption-above-p caption)
2770 contents
2771 (and (not caption-above-p) caption)
2772 (format "\\end{%s}" type))))
2775 ;;;; Src Block
2777 (defun org-latex-src-block (src-block _contents info)
2778 "Transcode a SRC-BLOCK element from Org to LaTeX.
2779 CONTENTS holds the contents of the item. INFO is a plist holding
2780 contextual information."
2781 (when (org-string-nw-p (org-element-property :value src-block))
2782 (let* ((lang (org-element-property :language src-block))
2783 (caption (org-element-property :caption src-block))
2784 (caption-above-p (org-latex--caption-above-p src-block info))
2785 (label (org-element-property :name src-block))
2786 (custom-env (and lang
2787 (cadr (assq (intern lang)
2788 org-latex-custom-lang-environments))))
2789 (num-start (org-export-get-loc src-block info))
2790 (retain-labels (org-element-property :retain-labels src-block))
2791 (attributes (org-export-read-attribute :attr_latex src-block))
2792 (float (plist-get attributes :float))
2793 (listings (plist-get info :latex-listings)))
2794 (cond
2795 ;; Case 1. No source fontification.
2796 ((not listings)
2797 (let* ((caption-str (org-latex--caption/label-string src-block info))
2798 (float-env
2799 (cond ((string= "multicolumn" float)
2800 (format "\\begin{figure*}[%s]\n%s%%s\n%s\\end{figure*}"
2801 (plist-get info :latex-default-figure-position)
2802 (if caption-above-p caption-str "")
2803 (if caption-above-p "" caption-str)))
2804 (caption (concat
2805 (if caption-above-p caption-str "")
2806 "%s"
2807 (if caption-above-p "" (concat "\n" caption-str))))
2808 (t "%s"))))
2809 (format
2810 float-env
2811 (concat (format "\\begin{verbatim}\n%s\\end{verbatim}"
2812 (org-export-format-code-default src-block info))))))
2813 ;; Case 2. Custom environment.
2814 (custom-env
2815 (let ((caption-str (org-latex--caption/label-string src-block info))
2816 (formatted-src (org-export-format-code-default src-block info)))
2817 (if (org-string-match-p "\\`[a-zA-Z0-9]+\\'" custom-env)
2818 (format "\\begin{%s}\n%s\\end{%s}\n"
2819 custom-env
2820 (concat (and caption-above-p caption-str)
2821 formatted-src
2822 (and (not caption-above-p) caption-str))
2823 custom-env)
2824 (format-spec custom-env
2825 `((?s . ,formatted-src)
2826 (?c . ,caption)
2827 (?f . ,float)
2828 (?l . ,(org-latex--label src-block info))
2829 (?o . ,(or (plist-get attributes :options) "")))))))
2830 ;; Case 3. Use minted package.
2831 ((eq listings 'minted)
2832 (let* ((caption-str (org-latex--caption/label-string src-block info))
2833 (float-env
2834 (cond
2835 ((string= "multicolumn" float)
2836 (format "\\begin{listing*}\n%s%%s\n%s\\end{listing*}"
2837 (if caption-above-p caption-str "")
2838 (if caption-above-p "" caption-str)))
2839 (caption
2840 (concat (if caption-above-p caption-str "")
2841 "%s"
2842 (if caption-above-p "" (concat "\n" caption-str))))
2843 (t "%s")))
2844 (options (plist-get info :latex-minted-options))
2845 (body
2846 (format
2847 "\\begin{minted}[%s]{%s}\n%s\\end{minted}"
2848 ;; Options.
2849 (concat
2850 (org-latex--make-option-string
2851 (if (or (not num-start) (assoc "linenos" options))
2852 options
2853 (append
2854 `(("linenos")
2855 ("firstnumber" ,(number-to-string (1+ num-start))))
2856 options)))
2857 (let ((local-options (plist-get attributes :options)))
2858 (and local-options (concat "," local-options))))
2859 ;; Language.
2860 (or (cadr (assq (intern lang)
2861 (plist-get info :latex-minted-langs)))
2862 (downcase lang))
2863 ;; Source code.
2864 (let* ((code-info (org-export-unravel-code src-block))
2865 (max-width
2866 (apply 'max
2867 (mapcar 'length
2868 (org-split-string (car code-info)
2869 "\n")))))
2870 (org-export-format-code
2871 (car code-info)
2872 (lambda (loc _num ref)
2873 (concat
2875 (when ref
2876 ;; Ensure references are flushed to the right,
2877 ;; separated with 6 spaces from the widest line
2878 ;; of code.
2879 (concat (make-string (+ (- max-width (length loc)) 6)
2880 ?\s)
2881 (format "(%s)" ref)))))
2882 nil (and retain-labels (cdr code-info)))))))
2883 ;; Return value.
2884 (format float-env body)))
2885 ;; Case 4. Use listings package.
2887 (let ((lst-lang
2888 (or (cadr (assq (intern lang)
2889 (plist-get info :latex-listings-langs)))
2890 lang))
2891 (caption-str
2892 (when caption
2893 (let ((main (org-export-get-caption src-block))
2894 (secondary (org-export-get-caption src-block t)))
2895 (if (not secondary)
2896 (format "{%s}" (org-export-data main info))
2897 (format "{[%s]%s}"
2898 (org-export-data secondary info)
2899 (org-export-data main info))))))
2900 (lst-opt (plist-get info :latex-listings-options)))
2901 (concat
2902 ;; Options.
2903 (format
2904 "\\lstset{%s}\n"
2905 (concat
2906 (org-latex--make-option-string
2907 (append
2908 lst-opt
2909 (cond
2910 ((and (not float) (plist-member attributes :float)) nil)
2911 ((string= "multicolumn" float) '(("float" "*")))
2912 ((and float (not (assoc "float" lst-opt)))
2913 `(("float" ,(plist-get info :latex-default-figure-position)))))
2914 `(("language" ,lst-lang))
2915 (if label `(("label" ,label)) '(("label" " ")))
2916 (if caption-str `(("caption" ,caption-str)) '(("caption" " ")))
2917 `(("captionpos" ,(if caption-above-p "t" "b")))
2918 (cond ((assoc "numbers" lst-opt) nil)
2919 ((not num-start) '(("numbers" "none")))
2920 (t `(("firstnumber" ,(number-to-string (1+ num-start)))
2921 ("numbers" "left"))))))
2922 (let ((local-options (plist-get attributes :options)))
2923 (and local-options (concat "," local-options)))))
2924 ;; Source code.
2925 (format
2926 "\\begin{lstlisting}\n%s\\end{lstlisting}"
2927 (let* ((code-info (org-export-unravel-code src-block))
2928 (max-width
2929 (apply 'max
2930 (mapcar 'length
2931 (org-split-string (car code-info) "\n")))))
2932 (org-export-format-code
2933 (car code-info)
2934 (lambda (loc _num ref)
2935 (concat
2937 (when ref
2938 ;; Ensure references are flushed to the right,
2939 ;; separated with 6 spaces from the widest line of
2940 ;; code
2941 (concat (make-string (+ (- max-width (length loc)) 6) ?\s)
2942 (format "(%s)" ref)))))
2943 nil (and retain-labels (cdr code-info))))))))))))
2946 ;;;; Statistics Cookie
2948 (defun org-latex-statistics-cookie (statistics-cookie _contents _info)
2949 "Transcode a STATISTICS-COOKIE object from Org to LaTeX.
2950 CONTENTS is nil. INFO is a plist holding contextual information."
2951 (replace-regexp-in-string
2952 "%" "\\%" (org-element-property :value statistics-cookie) nil t))
2955 ;;;; Strike-Through
2957 (defun org-latex-strike-through (_strike-through contents info)
2958 "Transcode STRIKE-THROUGH from Org to LaTeX.
2959 CONTENTS is the text with strike-through markup. INFO is a plist
2960 holding contextual information."
2961 (org-latex--text-markup contents 'strike-through info))
2964 ;;;; Subscript
2966 (defun org-latex--script-size (object info)
2967 "Transcode a subscript or superscript object.
2968 OBJECT is an Org object. INFO is a plist used as a communication
2969 channel."
2970 (let ((output ""))
2971 (org-element-map (org-element-contents object)
2972 (cons 'plain-text org-element-all-objects)
2973 (lambda (obj)
2974 (cl-case (org-element-type obj)
2975 ((entity latex-fragment)
2976 (let ((data (org-trim (org-export-data obj info))))
2977 (string-match
2978 "\\`\\(?:\\\\[([]\\|\\$+\\)?\\(.*?\\)\\(?:\\\\[])]\\|\\$+\\)?\\'"
2979 data)
2980 (setq output
2981 (concat output
2982 (match-string 1 data)
2983 (let ((blank (org-element-property :post-blank obj)))
2984 (and blank (> blank 0) "\\ "))))))
2985 (plain-text
2986 (setq output
2987 (format "%s\\text{%s}" output (org-export-data obj info))))
2988 (otherwise
2989 (setq output
2990 (concat output
2991 (org-export-data obj info)
2992 (let ((blank (org-element-property :post-blank obj)))
2993 (and blank (> blank 0) "\\ ")))))))
2994 info nil org-element-recursive-objects)
2995 ;; Result. Do not wrap into curly brackets if OUTPUT is a single
2996 ;; character.
2997 (concat (if (eq (org-element-type object) 'subscript) "_" "^")
2998 (and (> (length output) 1) "{")
2999 output
3000 (and (> (length output) 1) "}"))))
3002 (defun org-latex-subscript (subscript _contents info)
3003 "Transcode a SUBSCRIPT object from Org to LaTeX.
3004 CONTENTS is the contents of the object. INFO is a plist holding
3005 contextual information."
3006 (org-latex--script-size subscript info))
3009 ;;;; Superscript
3011 (defun org-latex-superscript (superscript _contents info)
3012 "Transcode a SUPERSCRIPT object from Org to LaTeX.
3013 CONTENTS is the contents of the object. INFO is a plist holding
3014 contextual information."
3015 (org-latex--script-size superscript info))
3018 ;;;; Table
3020 ;; `org-latex-table' is the entry point for table transcoding. It
3021 ;; takes care of tables with a "verbatim" mode. Otherwise, it
3022 ;; delegates the job to either `org-latex--table.el-table',
3023 ;; `org-latex--org-table' or `org-latex--math-table' functions,
3024 ;; depending of the type of the table and the mode requested.
3026 ;; `org-latex--align-string' is a subroutine used to build alignment
3027 ;; string for Org tables.
3029 (defun org-latex-table (table contents info)
3030 "Transcode a TABLE element from Org to LaTeX.
3031 CONTENTS is the contents of the table. INFO is a plist holding
3032 contextual information."
3033 (if (eq (org-element-property :type table) 'table.el)
3034 ;; "table.el" table. Convert it using appropriate tools.
3035 (org-latex--table.el-table table info)
3036 (let ((type (or (org-export-read-attribute :attr_latex table :mode)
3037 (plist-get info :latex-default-table-mode))))
3038 (cond
3039 ;; Case 1: Verbatim table.
3040 ((string= type "verbatim")
3041 (format "\\begin{verbatim}\n%s\n\\end{verbatim}"
3042 ;; Re-create table, without affiliated keywords.
3043 (org-trim (org-element-interpret-data
3044 `(table nil ,@(org-element-contents table))))))
3045 ;; Case 2: Matrix.
3046 ((or (string= type "math") (string= type "inline-math"))
3047 (org-latex--math-table table info))
3048 ;; Case 3: Standard table.
3049 (t (concat (org-latex--org-table table contents info)
3050 ;; When there are footnote references within the
3051 ;; table, insert their definition just after it.
3052 (org-latex--delayed-footnotes-definitions table info)))))))
3054 (defun org-latex--align-string (table info)
3055 "Return an appropriate LaTeX alignment string.
3056 TABLE is the considered table. INFO is a plist used as
3057 a communication channel."
3058 (or (org-export-read-attribute :attr_latex table :align)
3059 (let (align)
3060 ;; Extract column groups and alignment from first (non-rule)
3061 ;; row.
3062 (org-element-map
3063 (org-element-map table 'table-row
3064 (lambda (row)
3065 (and (eq (org-element-property :type row) 'standard) row))
3066 info 'first-match)
3067 'table-cell
3068 (lambda (cell)
3069 (let ((borders (org-export-table-cell-borders cell info)))
3070 ;; Check left border for the first cell only.
3071 (when (and (memq 'left borders) (not align))
3072 (push "|" align))
3073 (push (cl-case (org-export-table-cell-alignment cell info)
3074 (left "l")
3075 (right "r")
3076 (center "c"))
3077 align)
3078 (when (memq 'right borders) (push "|" align))))
3079 info)
3080 (apply 'concat (nreverse align)))))
3082 (defun org-latex--org-table (table contents info)
3083 "Return appropriate LaTeX code for an Org table.
3085 TABLE is the table type element to transcode. CONTENTS is its
3086 contents, as a string. INFO is a plist used as a communication
3087 channel.
3089 This function assumes TABLE has `org' as its `:type' property and
3090 `table' as its `:mode' attribute."
3091 (let* ((caption (org-latex--caption/label-string table info))
3092 (attr (org-export-read-attribute :attr_latex table))
3093 ;; Determine alignment string.
3094 (alignment (org-latex--align-string table info))
3095 ;; Determine environment for the table: longtable, tabular...
3096 (table-env (or (plist-get attr :environment)
3097 (plist-get info :latex-default-table-environment)))
3098 ;; If table is a float, determine environment: table, table*
3099 ;; or sidewaystable.
3100 (float-env (unless (member table-env '("longtable" "longtabu"))
3101 (let ((float (plist-get attr :float)))
3102 (cond
3103 ((and (not float) (plist-member attr :float)) nil)
3104 ((or (string= float "sidewaystable")
3105 (string= float "sideways")) "sidewaystable")
3106 ((string= float "multicolumn") "table*")
3107 ((or float
3108 (org-element-property :caption table)
3109 (org-string-nw-p (plist-get attr :caption)))
3110 "table")))))
3111 ;; Extract others display options.
3112 (fontsize (let ((font (plist-get attr :font)))
3113 (and font (concat font "\n"))))
3114 ;; "tabular" environment doesn't allow to define a width.
3115 (width (and (not (equal table-env "tabular")) (plist-get attr :width)))
3116 (spreadp (plist-get attr :spread))
3117 (placement
3118 (or (plist-get attr :placement)
3119 (format "[%s]" (plist-get info :latex-default-figure-position))))
3120 (centerp (if (plist-member attr :center) (plist-get attr :center)
3121 (plist-get info :latex-tables-centered)))
3122 (caption-above-p (org-latex--caption-above-p table info)))
3123 ;; Prepare the final format string for the table.
3124 (cond
3125 ;; Longtable.
3126 ((equal "longtable" table-env)
3127 (concat (and fontsize (concat "{" fontsize))
3128 (format "\\begin{longtable}{%s}\n" alignment)
3129 (and caption-above-p
3130 (org-string-nw-p caption)
3131 (concat caption "\\\\\n"))
3132 contents
3133 (and (not caption-above-p)
3134 (org-string-nw-p caption)
3135 (concat caption "\\\\\n"))
3136 "\\end{longtable}\n"
3137 (and fontsize "}")))
3138 ;; Longtabu
3139 ((equal "longtabu" table-env)
3140 (concat (and fontsize (concat "{" fontsize))
3141 (format "\\begin{longtabu}%s{%s}\n"
3142 (if width
3143 (format " %s %s "
3144 (if spreadp "spread" "to") width) "")
3145 alignment)
3146 (and caption-above-p
3147 (org-string-nw-p caption)
3148 (concat caption "\\\\\n"))
3149 contents
3150 (and (not caption-above-p)
3151 (org-string-nw-p caption)
3152 (concat caption "\\\\\n"))
3153 "\\end{longtabu}\n"
3154 (and fontsize "}")))
3155 ;; Others.
3156 (t (concat (cond
3157 (float-env
3158 (concat (format "\\begin{%s}%s\n" float-env placement)
3159 (if caption-above-p caption "")
3160 (when centerp "\\centering\n")
3161 fontsize))
3162 ((and (not float-env) caption)
3163 (concat
3164 (and centerp "\\begin{center}\n" )
3165 (if caption-above-p caption "")
3166 (cond ((and fontsize centerp) fontsize)
3167 (fontsize (concat "{" fontsize)))))
3168 (centerp (concat "\\begin{center}\n" fontsize))
3169 (fontsize (concat "{" fontsize)))
3170 (cond ((equal "tabu" table-env)
3171 (format "\\begin{tabu}%s{%s}\n%s\\end{tabu}"
3172 (if width (format
3173 (if spreadp " spread %s " " to %s ")
3174 width) "")
3175 alignment
3176 contents))
3177 (t (format "\\begin{%s}%s{%s}\n%s\\end{%s}"
3178 table-env
3179 (if width (format "{%s}" width) "")
3180 alignment
3181 contents
3182 table-env)))
3183 (cond
3184 (float-env
3185 (concat (if caption-above-p "" (concat "\n" caption))
3186 (format "\n\\end{%s}" float-env)))
3187 ((and (not float-env) caption)
3188 (concat
3189 (if caption-above-p "" (concat "\n" caption))
3190 (and centerp "\n\\end{center}")
3191 (and fontsize (not centerp) "}")))
3192 (centerp "\n\\end{center}")
3193 (fontsize "}")))))))
3195 (defun org-latex--table.el-table (table info)
3196 "Return appropriate LaTeX code for a table.el table.
3198 TABLE is the table type element to transcode. INFO is a plist
3199 used as a communication channel.
3201 This function assumes TABLE has `table.el' as its `:type'
3202 property."
3203 (require 'table)
3204 ;; Ensure "*org-export-table*" buffer is empty.
3205 (with-current-buffer (get-buffer-create "*org-export-table*")
3206 (erase-buffer))
3207 (let ((output (with-temp-buffer
3208 (insert (org-element-property :value table))
3209 (goto-char 1)
3210 (re-search-forward "^[ \t]*|[^|]" nil t)
3211 (table-generate-source 'latex "*org-export-table*")
3212 (with-current-buffer "*org-export-table*"
3213 (org-trim (buffer-string))))))
3214 (kill-buffer (get-buffer "*org-export-table*"))
3215 ;; Remove left out comments.
3216 (while (string-match "^%.*\n" output)
3217 (setq output (replace-match "" t t output)))
3218 (let ((attr (org-export-read-attribute :attr_latex table)))
3219 (when (plist-get attr :rmlines)
3220 ;; When the "rmlines" attribute is provided, remove all hlines
3221 ;; but the the one separating heading from the table body.
3222 (let ((n 0) (pos 0))
3223 (while (and (< (length output) pos)
3224 (setq pos (string-match "^\\\\hline\n?" output pos)))
3225 (cl-incf n)
3226 (unless (= n 2) (setq output (replace-match "" nil nil output))))))
3227 (let ((centerp (if (plist-member attr :center) (plist-get attr :center)
3228 (plist-get info :latex-tables-centered))))
3229 (if (not centerp) output
3230 (format "\\begin{center}\n%s\n\\end{center}" output))))))
3232 (defun org-latex--math-table (table info)
3233 "Return appropriate LaTeX code for a matrix.
3235 TABLE is the table type element to transcode. INFO is a plist
3236 used as a communication channel.
3238 This function assumes TABLE has `org' as its `:type' property and
3239 `inline-math' or `math' as its `:mode' attribute."
3240 (let* ((attr (org-export-read-attribute :attr_latex table))
3241 (env (or (plist-get attr :environment)
3242 (plist-get info :latex-default-table-environment)))
3243 (contents
3244 (mapconcat
3245 (lambda (row)
3246 ;; Ignore horizontal rules.
3247 (when (eq (org-element-property :type row) 'standard)
3248 ;; Return each cell unmodified.
3249 (concat
3250 (mapconcat
3251 (lambda (cell)
3252 (substring (org-element-interpret-data cell) 0 -1))
3253 (org-element-map row 'table-cell #'identity info) "&")
3254 (or (cdr (assoc env org-latex-table-matrix-macros)) "\\\\")
3255 "\n")))
3256 (org-element-map table 'table-row #'identity info) "")))
3257 (concat
3258 ;; Prefix.
3259 (plist-get attr :math-prefix)
3260 ;; Environment. Also treat special cases.
3261 (cond ((member env '("array" "tabular"))
3262 (let ((align (make-string
3263 (cdr (org-export-table-dimensions table info)) ?c)))
3264 (format "\\begin{%s}{%s}\n%s\\end{%s}" env align contents env)))
3265 ((assoc env org-latex-table-matrix-macros)
3266 (format "\\%s%s{\n%s}"
3268 (or (plist-get attr :math-arguments) "")
3269 contents))
3270 (t (format "\\begin{%s}\n%s\\end{%s}" env contents env)))
3271 ;; Suffix.
3272 (plist-get attr :math-suffix))))
3275 ;;;; Table Cell
3277 (defun org-latex-table-cell (table-cell contents info)
3278 "Transcode a TABLE-CELL element from Org to LaTeX.
3279 CONTENTS is the cell contents. INFO is a plist used as
3280 a communication channel."
3281 (concat
3282 (let ((scientific-format (plist-get info :latex-table-scientific-notation)))
3283 (if (and contents
3284 scientific-format
3285 (string-match orgtbl-exp-regexp contents))
3286 ;; Use appropriate format string for scientific
3287 ;; notation.
3288 (format scientific-format
3289 (match-string 1 contents)
3290 (match-string 2 contents))
3291 contents))
3292 (when (org-export-get-next-element table-cell info) " & ")))
3295 ;;;; Table Row
3297 (defun org-latex-table-row (table-row contents info)
3298 "Transcode a TABLE-ROW element from Org to LaTeX.
3299 CONTENTS is the contents of the row. INFO is a plist used as
3300 a communication channel."
3301 (let* ((attr (org-export-read-attribute :attr_latex
3302 (org-export-get-parent table-row)))
3303 (booktabsp (if (plist-member attr :booktabs) (plist-get attr :booktabs)
3304 (plist-get info :latex-tables-booktabs)))
3305 (longtablep
3306 (member (or (plist-get attr :environment)
3307 (plist-get info :latex-default-table-environment))
3308 '("longtable" "longtabu"))))
3309 (if (eq (org-element-property :type table-row) 'rule)
3310 (cond
3311 ((not booktabsp) "\\hline")
3312 ((not (org-export-get-previous-element table-row info)) "\\toprule")
3313 ((not (org-export-get-next-element table-row info)) "\\bottomrule")
3314 ((and longtablep
3315 (org-export-table-row-ends-header-p
3316 (org-export-get-previous-element table-row info) info))
3318 (t "\\midrule"))
3319 (concat
3320 ;; When BOOKTABS are activated enforce top-rule even when no
3321 ;; hline was specifically marked.
3322 (and booktabsp (not (org-export-get-previous-element table-row info))
3323 "\\toprule\n")
3324 contents "\\\\\n"
3325 (cond
3326 ;; Special case for long tables. Define header and footers.
3327 ((and longtablep (org-export-table-row-ends-header-p table-row info))
3328 (let ((columns (cdr (org-export-table-dimensions
3329 (org-export-get-parent-table table-row) info))))
3330 (format "%s
3331 \\endfirsthead
3332 \\multicolumn{%d}{l}{%s} \\\\
3334 %s \\\\\n
3336 \\endhead
3337 %s\\multicolumn{%d}{r}{%s} \\\\
3338 \\endfoot
3339 \\endlastfoot"
3340 (if booktabsp "\\midrule" "\\hline")
3341 columns
3342 (org-latex--translate "Continued from previous page" info)
3343 (cond
3344 ((not (org-export-table-row-starts-header-p table-row info))
3346 (booktabsp "\\toprule\n")
3347 (t "\\hline\n"))
3348 contents
3349 (if booktabsp "\\midrule" "\\hline")
3350 (if booktabsp "\\midrule" "\\hline")
3351 columns
3352 (org-latex--translate "Continued on next page" info))))
3353 ;; When BOOKTABS are activated enforce bottom rule even when
3354 ;; no hline was specifically marked.
3355 ((and booktabsp (not (org-export-get-next-element table-row info)))
3356 "\\bottomrule"))))))
3359 ;;;; Target
3361 (defun org-latex-target (target _contents info)
3362 "Transcode a TARGET object from Org to LaTeX.
3363 CONTENTS is nil. INFO is a plist holding contextual
3364 information."
3365 (format "\\label{%s}" (org-latex--label target info)))
3368 ;;;; Timestamp
3370 (defun org-latex-timestamp (timestamp _contents info)
3371 "Transcode a TIMESTAMP object from Org to LaTeX.
3372 CONTENTS is nil. INFO is a plist holding contextual
3373 information."
3374 (let ((value (org-latex-plain-text (org-timestamp-translate timestamp) info)))
3375 (format
3376 (plist-get info
3377 (cl-case (org-element-property :type timestamp)
3378 ((active active-range) :latex-active-timestamp-format)
3379 ((inactive inactive-range) :latex-inactive-timestamp-format)
3380 (otherwise :latex-diary-timestamp-format)))
3381 value)))
3384 ;;;; Underline
3386 (defun org-latex-underline (_underline contents info)
3387 "Transcode UNDERLINE from Org to LaTeX.
3388 CONTENTS is the text with underline markup. INFO is a plist
3389 holding contextual information."
3390 (org-latex--text-markup contents 'underline info))
3393 ;;;; Verbatim
3395 (defun org-latex-verbatim (verbatim _contents info)
3396 "Transcode a VERBATIM object from Org to LaTeX.
3397 CONTENTS is nil. INFO is a plist used as a communication
3398 channel."
3399 (org-latex--text-markup
3400 (org-element-property :value verbatim) 'verbatim info))
3403 ;;;; Verse Block
3405 (defun org-latex-verse-block (verse-block contents info)
3406 "Transcode a VERSE-BLOCK element from Org to LaTeX.
3407 CONTENTS is verse block contents. INFO is a plist holding
3408 contextual information."
3409 (org-latex--wrap-label
3410 verse-block
3411 ;; In a verse environment, add a line break to each newline
3412 ;; character and change each white space at beginning of a line
3413 ;; into a space of 1 em. Also change each blank line with
3414 ;; a vertical space of 1 em.
3415 (format "\\begin{verse}\n%s\\end{verse}"
3416 (replace-regexp-in-string
3417 "^[ \t]+" (lambda (m) (format "\\hspace*{%dem}" (length m)))
3418 (replace-regexp-in-string
3419 "^[ \t]*\\\\\\\\$" "\\vspace*{1em}"
3420 (replace-regexp-in-string
3421 "\\([ \t]*\\\\\\\\\\)?[ \t]*\n" "\\\\\n"
3422 contents nil t) nil t) nil t))
3423 info))
3427 ;;; End-user functions
3429 ;;;###autoload
3430 (defun org-latex-export-as-latex
3431 (&optional async subtreep visible-only body-only ext-plist)
3432 "Export current buffer as a LaTeX buffer.
3434 If narrowing is active in the current buffer, only export its
3435 narrowed part.
3437 If a region is active, export that region.
3439 A non-nil optional argument ASYNC means the process should happen
3440 asynchronously. The resulting buffer should be accessible
3441 through the `org-export-stack' interface.
3443 When optional argument SUBTREEP is non-nil, export the sub-tree
3444 at point, extracting information from the headline properties
3445 first.
3447 When optional argument VISIBLE-ONLY is non-nil, don't export
3448 contents of hidden elements.
3450 When optional argument BODY-ONLY is non-nil, only write code
3451 between \"\\begin{document}\" and \"\\end{document}\".
3453 EXT-PLIST, when provided, is a property list with external
3454 parameters overriding Org default settings, but still inferior to
3455 file-local settings.
3457 Export is done in a buffer named \"*Org LATEX Export*\", which
3458 will be displayed when `org-export-show-temporary-export-buffer'
3459 is non-nil."
3460 (interactive)
3461 (org-export-to-buffer 'latex "*Org LATEX Export*"
3462 async subtreep visible-only body-only ext-plist (lambda () (LaTeX-mode))))
3464 ;;;###autoload
3465 (defun org-latex-convert-region-to-latex ()
3466 "Assume the current region has org-mode syntax, and convert it to LaTeX.
3467 This can be used in any buffer. For example, you can write an
3468 itemized list in org-mode syntax in an LaTeX buffer and use this
3469 command to convert it."
3470 (interactive)
3471 (org-export-replace-region-by 'latex))
3473 ;;;###autoload
3474 (defun org-latex-export-to-latex
3475 (&optional async subtreep visible-only body-only ext-plist)
3476 "Export current buffer to a LaTeX file.
3478 If narrowing is active in the current buffer, only export its
3479 narrowed part.
3481 If a region is active, export that region.
3483 A non-nil optional argument ASYNC means the process should happen
3484 asynchronously. The resulting file should be accessible through
3485 the `org-export-stack' interface.
3487 When optional argument SUBTREEP is non-nil, export the sub-tree
3488 at point, extracting information from the headline properties
3489 first.
3491 When optional argument VISIBLE-ONLY is non-nil, don't export
3492 contents of hidden elements.
3494 When optional argument BODY-ONLY is non-nil, only write code
3495 between \"\\begin{document}\" and \"\\end{document}\".
3497 EXT-PLIST, when provided, is a property list with external
3498 parameters overriding Org default settings, but still inferior to
3499 file-local settings."
3500 (interactive)
3501 (let ((outfile (org-export-output-file-name ".tex" subtreep)))
3502 (org-export-to-file 'latex outfile
3503 async subtreep visible-only body-only ext-plist)))
3505 ;;;###autoload
3506 (defun org-latex-export-to-pdf
3507 (&optional async subtreep visible-only body-only ext-plist)
3508 "Export current buffer to LaTeX then process through to PDF.
3510 If narrowing is active in the current buffer, only export its
3511 narrowed part.
3513 If a region is active, export that region.
3515 A non-nil optional argument ASYNC means the process should happen
3516 asynchronously. The resulting file should be accessible through
3517 the `org-export-stack' interface.
3519 When optional argument SUBTREEP is non-nil, export the sub-tree
3520 at point, extracting information from the headline properties
3521 first.
3523 When optional argument VISIBLE-ONLY is non-nil, don't export
3524 contents of hidden elements.
3526 When optional argument BODY-ONLY is non-nil, only write code
3527 between \"\\begin{document}\" and \"\\end{document}\".
3529 EXT-PLIST, when provided, is a property list with external
3530 parameters overriding Org default settings, but still inferior to
3531 file-local settings.
3533 Return PDF file's name."
3534 (interactive)
3535 (let ((outfile (org-export-output-file-name ".tex" subtreep)))
3536 (org-export-to-file 'latex outfile
3537 async subtreep visible-only body-only ext-plist
3538 (lambda (file) (org-latex-compile file)))))
3540 (defun org-latex-compile (texfile &optional snippet)
3541 "Compile a TeX file.
3543 TEXFILE is the name of the file being compiled. Processing is
3544 done through the command specified in `org-latex-pdf-process',
3545 which see. Output is redirected to \"*Org PDF LaTeX Output*\"
3546 buffer.
3548 When optional argument SNIPPET is non-nil, TEXFILE is a temporary
3549 file used to preview a LaTeX snippet. In this case, do not
3550 create a log buffer and do not remove log files.
3552 Return PDF file name or raise an error if it couldn't be
3553 produced."
3554 (unless snippet (message "Processing LaTeX file %s..." texfile))
3555 (let* ((compiler
3556 (or (with-temp-buffer
3557 (save-excursion (insert-file-contents texfile))
3558 (and (search-forward-regexp (regexp-opt org-latex-compilers)
3559 (line-end-position 2)
3561 (progn (beginning-of-line) (looking-at-p "%"))
3562 (match-string 0)))
3563 "pdflatex"))
3564 (process (if (functionp org-latex-pdf-process) org-latex-pdf-process
3565 ;; Replace "%latex" and "%bibtex" with,
3566 ;; respectively, "%L" and "%B" so as to adhere to
3567 ;; `format-spec' specifications.
3568 (mapcar (lambda (command)
3569 (replace-regexp-in-string
3570 "%\\(?:bib\\|la\\)tex\\>"
3571 (lambda (m) (upcase (substring m 0 2)))
3572 command))
3573 org-latex-pdf-process)))
3574 (spec `((?B . ,(shell-quote-argument org-latex-bib-compiler))
3575 (?L . ,(shell-quote-argument compiler))))
3576 (log-buf-name "*Org PDF LaTeX Output*")
3577 (log-buf (and (not snippet) (get-buffer-create log-buf-name)))
3578 (outfile (org-compile-file texfile process "pdf"
3579 (format "See %S for details" log-buf-name)
3580 log-buf spec)))
3581 (unless snippet
3582 (when org-latex-remove-logfiles
3583 (mapc #'delete-file
3584 (directory-files
3585 (file-name-directory texfile) t
3586 (concat (regexp-quote (file-name-base outfile))
3587 "\\(?:\\.[0-9]+\\)?\\."
3588 (regexp-opt org-latex-logfiles-extensions)))))
3589 (let ((warnings (org-latex--collect-warnings log-buf)))
3590 (message (concat "PDF file produced"
3591 (cond
3592 ((eq warnings 'error) " with errors.")
3593 (warnings (concat " with warnings: " warnings))
3594 (t "."))))))
3595 ;; Return output file name.
3596 outfile))
3598 (defun org-latex--collect-warnings (buffer)
3599 "Collect some warnings from \"pdflatex\" command output.
3600 BUFFER is the buffer containing output. Return collected
3601 warnings types as a string, `error' if a LaTeX error was
3602 encountered or nil if there was none."
3603 (with-current-buffer buffer
3604 (save-excursion
3605 (goto-char (point-max))
3606 (when (re-search-backward "^[ \t]*This is .*?TeX.*?Version" nil t)
3607 (if (re-search-forward "^!" nil t) 'error
3608 (let ((case-fold-search t)
3609 (warnings ""))
3610 (dolist (warning org-latex-known-warnings)
3611 (when (save-excursion (re-search-forward (car warning) nil t))
3612 (setq warnings (concat warnings " " (cdr warning)))))
3613 (org-string-nw-p (org-trim warnings))))))))
3615 ;;;###autoload
3616 (defun org-latex-publish-to-latex (plist filename pub-dir)
3617 "Publish an Org file to LaTeX.
3619 FILENAME is the filename of the Org file to be published. PLIST
3620 is the property list for the given project. PUB-DIR is the
3621 publishing directory.
3623 Return output file name."
3624 (org-publish-org-to 'latex filename ".tex" plist pub-dir))
3626 ;;;###autoload
3627 (defun org-latex-publish-to-pdf (plist filename pub-dir)
3628 "Publish an Org file to PDF (via LaTeX).
3630 FILENAME is the filename of the Org file to be published. PLIST
3631 is the property list for the given project. PUB-DIR is the
3632 publishing directory.
3634 Return output file name."
3635 ;; Unlike to `org-latex-publish-to-latex', PDF file is generated
3636 ;; in working directory and then moved to publishing directory.
3637 (org-publish-attachment
3638 plist
3639 (org-latex-compile
3640 (org-publish-org-to
3641 'latex filename ".tex" plist (file-name-directory filename)))
3642 pub-dir))
3645 (provide 'ox-latex)
3647 ;; Local variables:
3648 ;; generated-autoload-file: "org-loaddefs.el"
3649 ;; End:
3651 ;;; ox-latex.el ends here