Let =`latexmk'= be an option to =`org-latex-pdf-process'=.
[org-mode/org-kjn.git] / lisp / ox-latex.el
blobf2c6261008b07d60e0c76f5c298ae2ac78d0ff20
1 ;;; ox-latex.el --- LaTeX Back-End for Org Export Engine
3 ;; Copyright (C) 2011-2013 Free Software Foundation, Inc.
5 ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
6 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; GNU Emacs is free software: you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation, either version 3 of the License, or
11 ;; (at your option) any later version.
13 ;; GNU Emacs is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 ;; GNU General Public License for more details.
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
21 ;;; Commentary:
23 ;; See Org manual for details.
25 ;;; Code:
27 (eval-when-compile (require 'cl))
28 (require 'ox)
29 (require 'ox-publish)
31 (defvar org-latex-default-packages-alist)
32 (defvar org-latex-packages-alist)
33 (defvar orgtbl-exp-regexp)
37 ;;; Define Back-End
39 (org-export-define-backend 'latex
40 '((bold . org-latex-bold)
41 (center-block . org-latex-center-block)
42 (clock . org-latex-clock)
43 (code . org-latex-code)
44 (comment . (lambda (&rest args) ""))
45 (comment-block . (lambda (&rest args) ""))
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 (paragraph . org-latex-paragraph)
67 (plain-list . org-latex-plain-list)
68 (plain-text . org-latex-plain-text)
69 (planning . org-latex-planning)
70 (property-drawer . (lambda (&rest args) ""))
71 (quote-block . org-latex-quote-block)
72 (quote-section . org-latex-quote-section)
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 :export-block '("LATEX" "TEX")
91 :menu-entry
92 '(?l "Export to LaTeX"
93 ((?L "As LaTeX buffer" org-latex-export-as-latex)
94 (?l "As LaTeX file" org-latex-export-to-latex)
95 (?p "As PDF file" org-latex-export-to-pdf)
96 (?o "As PDF file and open"
97 (lambda (a s v b)
98 (if a (org-latex-export-to-pdf t s v b)
99 (org-open-file (org-latex-export-to-pdf nil s v b)))))))
100 :options-alist '((:latex-class "LATEX_CLASS" nil org-latex-default-class t)
101 (:latex-class-options "LATEX_CLASS_OPTIONS" nil nil t)
102 (:latex-header "LATEX_HEADER" nil nil newline)
103 (:latex-header-extra "LATEX_HEADER_EXTRA" nil nil newline)
104 (:latex-hyperref-p nil "texht" org-latex-with-hyperref t)
105 ;; Redefine regular options.
106 (:date "DATE" nil "\\today" t)))
110 ;;; Internal Variables
112 (defconst org-latex-babel-language-alist
113 '(("af" . "afrikaans")
114 ("bg" . "bulgarian")
115 ("bt-br" . "brazilian")
116 ("ca" . "catalan")
117 ("cs" . "czech")
118 ("cy" . "welsh")
119 ("da" . "danish")
120 ("de" . "germanb")
121 ("de-at" . "naustrian")
122 ("de-de" . "ngerman")
123 ("el" . "greek")
124 ("en" . "english")
125 ("en-au" . "australian")
126 ("en-ca" . "canadian")
127 ("en-gb" . "british")
128 ("en-ie" . "irish")
129 ("en-nz" . "newzealand")
130 ("en-us" . "american")
131 ("es" . "spanish")
132 ("et" . "estonian")
133 ("eu" . "basque")
134 ("fi" . "finnish")
135 ("fr" . "frenchb")
136 ("fr-ca" . "canadien")
137 ("gl" . "galician")
138 ("hr" . "croatian")
139 ("hu" . "hungarian")
140 ("id" . "indonesian")
141 ("is" . "icelandic")
142 ("it" . "italian")
143 ("la" . "latin")
144 ("ms" . "malay")
145 ("nl" . "dutch")
146 ("no-no" . "nynorsk")
147 ("pl" . "polish")
148 ("pt" . "portuguese")
149 ("ro" . "romanian")
150 ("ru" . "russian")
151 ("sa" . "sanskrit")
152 ("sb" . "uppersorbian")
153 ("sk" . "slovak")
154 ("sl" . "slovene")
155 ("sq" . "albanian")
156 ("sr" . "serbian")
157 ("sv" . "swedish")
158 ("ta" . "tamil")
159 ("tr" . "turkish")
160 ("uk" . "ukrainian"))
161 "Alist between language code and corresponding Babel option.")
163 (defconst org-latex-table-matrix-macros '(("bordermatrix" . "\\cr")
164 ("qbordermatrix" . "\\cr")
165 ("kbordermatrix" . "\\\\"))
166 "Alist between matrix macros and their row ending.")
170 ;;; User Configurable Variables
172 (defgroup org-export-latex nil
173 "Options for exporting Org mode files to LaTeX."
174 :tag "Org Export LaTeX"
175 :group 'org-export)
178 ;;;; Preamble
180 (defcustom org-latex-default-class "article"
181 "The default LaTeX class."
182 :group 'org-export-latex
183 :type '(string :tag "LaTeX class"))
185 (defcustom org-latex-classes
186 '(("article"
187 "\\documentclass[11pt]{article}"
188 ("\\section{%s}" . "\\section*{%s}")
189 ("\\subsection{%s}" . "\\subsection*{%s}")
190 ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
191 ("\\paragraph{%s}" . "\\paragraph*{%s}")
192 ("\\subparagraph{%s}" . "\\subparagraph*{%s}"))
193 ("report"
194 "\\documentclass[11pt]{report}"
195 ("\\part{%s}" . "\\part*{%s}")
196 ("\\chapter{%s}" . "\\chapter*{%s}")
197 ("\\section{%s}" . "\\section*{%s}")
198 ("\\subsection{%s}" . "\\subsection*{%s}")
199 ("\\subsubsection{%s}" . "\\subsubsection*{%s}"))
200 ("book"
201 "\\documentclass[11pt]{book}"
202 ("\\part{%s}" . "\\part*{%s}")
203 ("\\chapter{%s}" . "\\chapter*{%s}")
204 ("\\section{%s}" . "\\section*{%s}")
205 ("\\subsection{%s}" . "\\subsection*{%s}")
206 ("\\subsubsection{%s}" . "\\subsubsection*{%s}")))
207 "Alist of LaTeX classes and associated header and structure.
208 If #+LATEX_CLASS is set in the buffer, use its value and the
209 associated information. Here is the structure of each cell:
211 \(class-name
212 header-string
213 \(numbered-section . unnumbered-section)
214 ...)
216 The header string
217 -----------------
219 The HEADER-STRING is the header that will be inserted into the
220 LaTeX file. It should contain the \\documentclass macro, and
221 anything else that is needed for this setup. To this header, the
222 following commands will be added:
224 - Calls to \\usepackage for all packages mentioned in the
225 variables `org-latex-default-packages-alist' and
226 `org-latex-packages-alist'. Thus, your header definitions
227 should avoid to also request these packages.
229 - Lines specified via \"#+LATEX_HEADER:\" and
230 \"#+LATEX_HEADER_EXTRA:\" keywords.
232 If you need more control about the sequence in which the header
233 is built up, or if you want to exclude one of these building
234 blocks for a particular class, you can use the following
235 macro-like placeholders.
237 [DEFAULT-PACKAGES] \\usepackage statements for default packages
238 [NO-DEFAULT-PACKAGES] do not include any of the default packages
239 [PACKAGES] \\usepackage statements for packages
240 [NO-PACKAGES] do not include the packages
241 [EXTRA] the stuff from #+LATEX_HEADER(_EXTRA)
242 [NO-EXTRA] do not include #+LATEX_HEADER(_EXTRA) stuff
244 So a header like
246 \\documentclass{article}
247 [NO-DEFAULT-PACKAGES]
248 [EXTRA]
249 \\providecommand{\\alert}[1]{\\textbf{#1}}
250 [PACKAGES]
252 will omit the default packages, and will include the
253 #+LATEX_HEADER and #+LATEX_HEADER_EXTRA lines, then have a call
254 to \\providecommand, and then place \\usepackage commands based
255 on the content of `org-latex-packages-alist'.
257 If your header, `org-latex-default-packages-alist' or
258 `org-latex-packages-alist' inserts \"\\usepackage[AUTO]{inputenc}\",
259 AUTO will automatically be replaced with a coding system derived
260 from `buffer-file-coding-system'. See also the variable
261 `org-latex-inputenc-alist' for a way to influence this mechanism.
263 Likewise, if your header contains \"\\usepackage[AUTO]{babel}\",
264 AUTO will be replaced with the language related to the language
265 code specified by `org-export-default-language', which see. Note
266 that constructions such as \"\\usepackage[french,AUTO,english]{babel}\"
267 are permitted.
269 The sectioning structure
270 ------------------------
272 The sectioning structure of the class is given by the elements
273 following the header string. For each sectioning level, a number
274 of strings is specified. A %s formatter is mandatory in each
275 section string and will be replaced by the title of the section.
277 Instead of a cons cell (numbered . unnumbered), you can also
278 provide a list of 2 or 4 elements,
280 \(numbered-open numbered-close)
284 \(numbered-open numbered-close unnumbered-open unnumbered-close)
286 providing opening and closing strings for a LaTeX environment
287 that should represent the document section. The opening clause
288 should have a %s to represent the section title.
290 Instead of a list of sectioning commands, you can also specify
291 a function name. That function will be called with two
292 parameters, the (reduced) level of the headline, and a predicate
293 non-nil when the headline should be numbered. It must return
294 a format string in which the section title will be added."
295 :group 'org-export-latex
296 :type '(repeat
297 (list (string :tag "LaTeX class")
298 (string :tag "LaTeX header")
299 (repeat :tag "Levels" :inline t
300 (choice
301 (cons :tag "Heading"
302 (string :tag " numbered")
303 (string :tag "unnumbered"))
304 (list :tag "Environment"
305 (string :tag "Opening (numbered)")
306 (string :tag "Closing (numbered)")
307 (string :tag "Opening (unnumbered)")
308 (string :tag "Closing (unnumbered)"))
309 (function :tag "Hook computing sectioning"))))))
311 (defcustom org-latex-inputenc-alist nil
312 "Alist of inputenc coding system names, and what should really be used.
313 For example, adding an entry
315 (\"utf8\" . \"utf8x\")
317 will cause \\usepackage[utf8x]{inputenc} to be used for buffers that
318 are written as utf8 files."
319 :group 'org-export-latex
320 :type '(repeat
321 (cons
322 (string :tag "Derived from buffer")
323 (string :tag "Use this instead"))))
325 (defcustom org-latex-title-command "\\maketitle"
326 "The command used to insert the title just after \\begin{document}.
327 If this string contains the formatting specification \"%s\" then
328 it will be used as a formatting string, passing the title as an
329 argument."
330 :group 'org-export-latex
331 :type 'string)
333 (defcustom org-latex-toc-command "\\tableofcontents\n\n"
334 "LaTeX command to set the table of contents, list of figures, etc.
335 This command only applies to the table of contents generated with
336 the toc:nil option, not to those generated with #+TOC keyword."
337 :group 'org-export-latex
338 :type 'string)
340 (defcustom org-latex-with-hyperref t
341 "Toggle insertion of \\hypersetup{...} in the preamble."
342 :group 'org-export-latex
343 :type 'boolean)
346 ;;;; Headline
348 (defcustom org-latex-format-headline-function
349 'org-latex-format-headline-default-function
350 "Function for formatting the headline's text.
352 This function will be called with 5 arguments:
353 TODO the todo keyword (string or nil).
354 TODO-TYPE the type of todo (symbol: `todo', `done', nil)
355 PRIORITY the priority of the headline (integer or nil)
356 TEXT the main headline text (string).
357 TAGS the tags as a list of strings (list of strings or nil).
359 The function result will be used in the section format string.
361 Use `org-latex-format-headline-default-function' by default,
362 which format headlines like for Org version prior to 8.0."
363 :group 'org-export-latex
364 :version "24.4"
365 :package-version '(Org . "8.0")
366 :type 'function)
369 ;;;; Footnotes
371 (defcustom org-latex-footnote-separator "\\textsuperscript{,}\\,"
372 "Text used to separate footnotes."
373 :group 'org-export-latex
374 :type 'string)
377 ;;;; Timestamps
379 (defcustom org-latex-active-timestamp-format "\\textit{%s}"
380 "A printf format string to be applied to active timestamps."
381 :group 'org-export-latex
382 :type 'string)
384 (defcustom org-latex-inactive-timestamp-format "\\textit{%s}"
385 "A printf format string to be applied to inactive timestamps."
386 :group 'org-export-latex
387 :type 'string)
389 (defcustom org-latex-diary-timestamp-format "\\textit{%s}"
390 "A printf format string to be applied to diary timestamps."
391 :group 'org-export-latex
392 :type 'string)
395 ;;;; Links
397 (defcustom org-latex-image-default-option ""
398 "Default option for images."
399 :group 'org-export-latex
400 :version "24.4"
401 :package-version '(Org . "8.0")
402 :type 'string)
404 (defcustom org-latex-image-default-width ".9\\linewidth"
405 "Default width for images.
406 This value will not be used if a height is provided."
407 :group 'org-export-latex
408 :version "24.4"
409 :package-version '(Org . "8.0")
410 :type 'string)
412 (defcustom org-latex-image-default-height ""
413 "Default height for images.
414 This value will not be used if a width is provided, or if the
415 image is wrapped within a \"figure\" or \"wrapfigure\"
416 environment."
417 :group 'org-export-latex
418 :version "24.4"
419 :package-version '(Org . "8.0")
420 :type 'string)
422 (defcustom org-latex-default-figure-position "htb"
423 "Default position for latex figures."
424 :group 'org-export-latex
425 :type 'string)
427 (defcustom org-latex-inline-image-rules
428 '(("file" . "\\.\\(pdf\\|jpeg\\|jpg\\|png\\|ps\\|eps\\|tikz\\|pgf\\)\\'"))
429 "Rules characterizing image files that can be inlined into LaTeX.
431 A rule consists in an association whose key is the type of link
432 to consider, and value is a regexp that will be matched against
433 link's path.
435 Note that, by default, the image extension *actually* allowed
436 depend on the way the LaTeX file is processed. When used with
437 pdflatex, pdf, jpg and png images are OK. When processing
438 through dvi to Postscript, only ps and eps are allowed. The
439 default we use here encompasses both."
440 :group 'org-export-latex
441 :version "24.4"
442 :package-version '(Org . "8.0")
443 :type '(alist :key-type (string :tag "Type")
444 :value-type (regexp :tag "Path")))
446 (defcustom org-latex-link-with-unknown-path-format "\\texttt{%s}"
447 "Format string for links with unknown path type."
448 :group 'org-export-latex
449 :type 'string)
452 ;;;; Tables
454 (defcustom org-latex-default-table-environment "tabular"
455 "Default environment used to build tables."
456 :group 'org-export-latex
457 :version "24.4"
458 :package-version '(Org . "8.0")
459 :type 'string)
461 (defcustom org-latex-default-table-mode 'table
462 "Default mode for tables.
464 Value can be a symbol among:
466 `table' Regular LaTeX table.
468 `math' In this mode, every cell is considered as being in math
469 mode and the complete table will be wrapped within a math
470 environment. It is particularly useful to write matrices.
472 `inline-math' This mode is almost the same as `math', but the
473 math environment will be inlined.
475 `verbatim' The table is exported as it appears in the Org
476 buffer, within a verbatim environment.
478 This value can be overridden locally with, i.e. \":mode math\" in
479 LaTeX attributes.
481 When modifying this variable, it may be useful to change
482 `org-latex-default-table-environment' accordingly."
483 :group 'org-export-latex
484 :version "24.4"
485 :package-version '(Org . "8.0")
486 :type '(choice (const :tag "Table" table)
487 (const :tag "Matrix" math)
488 (const :tag "Inline matrix" inline-math)
489 (const :tag "Verbatim" verbatim)))
491 (defcustom org-latex-tables-centered t
492 "When non-nil, tables are exported in a center environment."
493 :group 'org-export-latex
494 :type 'boolean)
496 (defcustom org-latex-tables-booktabs nil
497 "When non-nil, display tables in a formal \"booktabs\" style.
498 This option assumes that the \"booktabs\" package is properly
499 loaded in the header of the document. This value can be ignored
500 locally with \":booktabs t\" and \":booktabs nil\" LaTeX
501 attributes."
502 :group 'org-export-latex
503 :version "24.4"
504 :package-version '(Org . "8.0")
505 :type 'boolean)
507 (defcustom org-latex-table-caption-above t
508 "When non-nil, place caption string at the beginning of the table.
509 Otherwise, place it near the end."
510 :group 'org-export-latex
511 :type 'boolean)
513 (defcustom org-latex-table-scientific-notation "%s\\,(%s)"
514 "Format string to display numbers in scientific notation.
515 The format should have \"%s\" twice, for mantissa and exponent
516 \(i.e., \"%s\\\\times10^{%s}\").
518 When nil, no transformation is made."
519 :group 'org-export-latex
520 :version "24.4"
521 :package-version '(Org . "8.0")
522 :type '(choice
523 (string :tag "Format string")
524 (const :tag "No formatting")))
527 ;;;; Text markup
529 (defcustom org-latex-text-markup-alist '((bold . "\\textbf{%s}")
530 (code . verb)
531 (italic . "\\emph{%s}")
532 (strike-through . "\\sout{%s}")
533 (underline . "\\uline{%s}")
534 (verbatim . protectedtexttt))
535 "Alist of LaTeX expressions to convert text markup.
537 The key must be a symbol among `bold', `code', `italic',
538 `strike-through', `underline' and `verbatim'. The value is
539 a formatting string to wrap fontified text with.
541 Value can also be set to the following symbols: `verb' and
542 `protectedtexttt'. For the former, Org will use \"\\verb\" to
543 create a format string and select a delimiter character that
544 isn't in the string. For the latter, Org will use \"\\texttt\"
545 to typeset and try to protect special characters.
547 If no association can be found for a given markup, text will be
548 returned as-is."
549 :group 'org-export-latex
550 :type 'alist
551 :options '(bold code italic strike-through underline verbatim))
554 ;;;; Drawers
556 (defcustom org-latex-format-drawer-function nil
557 "Function called to format a drawer in LaTeX code.
559 The function must accept two parameters:
560 NAME the drawer name, like \"LOGBOOK\"
561 CONTENTS the contents of the drawer.
563 The function should return the string to be exported.
565 For example, the variable could be set to the following function
566 in order to mimic default behaviour:
568 \(defun org-latex-format-drawer-default \(name contents\)
569 \"Format a drawer element for LaTeX export.\"
570 contents\)"
571 :group 'org-export-latex
572 :type 'function)
575 ;;;; Inlinetasks
577 (defcustom org-latex-format-inlinetask-function nil
578 "Function called to format an inlinetask in LaTeX code.
580 The function must accept six parameters:
581 TODO the todo keyword, as a string
582 TODO-TYPE the todo type, a symbol among `todo', `done' and nil.
583 PRIORITY the inlinetask priority, as a string
584 NAME the inlinetask name, as a string.
585 TAGS the inlinetask tags, as a list of strings.
586 CONTENTS the contents of the inlinetask, as a string.
588 The function should return the string to be exported.
590 For example, the variable could be set to the following function
591 in order to mimic default behaviour:
593 \(defun org-latex-format-inlinetask \(todo type priority name tags contents\)
594 \"Format an inline task element for LaTeX export.\"
595 \(let ((full-title
596 \(concat
597 \(when todo
598 \(format \"\\\\textbf{\\\\textsf{\\\\textsc{%s}}} \" todo))
599 \(when priority (format \"\\\\framebox{\\\\#%c} \" priority))
600 title
601 \(when tags
602 \(format \"\\\\hfill{}\\\\textsc{:%s:}\"
603 \(mapconcat 'identity tags \":\")))))
604 \(format (concat \"\\\\begin{center}\\n\"
605 \"\\\\fbox{\\n\"
606 \"\\\\begin{minipage}[c]{.6\\\\textwidth}\\n\"
607 \"%s\\n\\n\"
608 \"\\\\rule[.8em]{\\\\textwidth}{2pt}\\n\\n\"
609 \"%s\"
610 \"\\\\end{minipage}}\"
611 \"\\\\end{center}\")
612 full-title contents))"
613 :group 'org-export-latex
614 :type 'function)
617 ;; Src blocks
619 (defcustom org-latex-listings nil
620 "Non-nil means export source code using the listings package.
621 This package will fontify source code, possibly even with color.
622 If you want to use this, you also need to make LaTeX use the
623 listings package, and if you want to have color, the color
624 package. Just add these to `org-latex-packages-alist', for
625 example using customize, or with something like:
627 \(require 'ox-latex)
628 \(add-to-list 'org-latex-packages-alist '\(\"\" \"listings\"))
629 \(add-to-list 'org-latex-packages-alist '\(\"\" \"color\"))
631 Alternatively,
633 \(setq org-latex-listings 'minted)
635 causes source code to be exported using the minted package as
636 opposed to listings. If you want to use minted, you need to add
637 the minted package to `org-latex-packages-alist', for example
638 using customize, or with
640 \(require 'ox-latex)
641 \(add-to-list 'org-latex-packages-alist '\(\"\" \"minted\"))
643 In addition, it is necessary to install pygments
644 \(http://pygments.org), and to configure the variable
645 `org-latex-pdf-process' so that the -shell-escape option is
646 passed to pdflatex."
647 :group 'org-export-latex
648 :type '(choice
649 (const :tag "Use listings" t)
650 (const :tag "Use minted" 'minted)
651 (const :tag "Export verbatim" nil)))
653 (defcustom org-latex-listings-langs
654 '((emacs-lisp "Lisp") (lisp "Lisp") (clojure "Lisp")
655 (c "C") (cc "C++")
656 (fortran "fortran")
657 (perl "Perl") (cperl "Perl") (python "Python") (ruby "Ruby")
658 (html "HTML") (xml "XML")
659 (tex "TeX") (latex "[LaTeX]TeX")
660 (shell-script "bash")
661 (gnuplot "Gnuplot")
662 (ocaml "Caml") (caml "Caml")
663 (sql "SQL") (sqlite "sql"))
664 "Alist mapping languages to their listing language counterpart.
665 The key is a symbol, the major mode symbol without the \"-mode\".
666 The value is the string that should be inserted as the language
667 parameter for the listings package. If the mode name and the
668 listings name are the same, the language does not need an entry
669 in this list - but it does not hurt if it is present."
670 :group 'org-export-latex
671 :type '(repeat
672 (list
673 (symbol :tag "Major mode ")
674 (string :tag "Listings language"))))
676 (defcustom org-latex-listings-options nil
677 "Association list of options for the latex listings package.
679 These options are supplied as a comma-separated list to the
680 \\lstset command. Each element of the association list should be
681 a list containing two strings: the name of the option, and the
682 value. For example,
684 (setq org-latex-listings-options
685 '((\"basicstyle\" \"\\small\")
686 (\"keywordstyle\" \"\\color{black}\\bfseries\\underbar\")))
688 will typeset the code in a small size font with underlined, bold
689 black keywords.
691 Note that the same options will be applied to blocks of all
692 languages."
693 :group 'org-export-latex
694 :type '(repeat
695 (list
696 (string :tag "Listings option name ")
697 (string :tag "Listings option value"))))
699 (defcustom org-latex-minted-langs
700 '((emacs-lisp "common-lisp")
701 (cc "c++")
702 (cperl "perl")
703 (shell-script "bash")
704 (caml "ocaml"))
705 "Alist mapping languages to their minted language counterpart.
706 The key is a symbol, the major mode symbol without the \"-mode\".
707 The value is the string that should be inserted as the language
708 parameter for the minted package. If the mode name and the
709 listings name are the same, the language does not need an entry
710 in this list - but it does not hurt if it is present.
712 Note that minted uses all lower case for language identifiers,
713 and that the full list of language identifiers can be obtained
714 with:
716 pygmentize -L lexers"
717 :group 'org-export-latex
718 :type '(repeat
719 (list
720 (symbol :tag "Major mode ")
721 (string :tag "Minted language"))))
723 (defcustom org-latex-minted-options nil
724 "Association list of options for the latex minted package.
726 These options are supplied within square brackets in
727 \\begin{minted} environments. Each element of the alist should
728 be a list containing two strings: the name of the option, and the
729 value. For example,
731 \(setq org-latex-minted-options
732 '\((\"bgcolor\" \"bg\") \(\"frame\" \"lines\")))
734 will result in src blocks being exported with
736 \\begin{minted}[bgcolor=bg,frame=lines]{<LANG>}
738 as the start of the minted environment. Note that the same
739 options will be applied to blocks of all languages."
740 :group 'org-export-latex
741 :type '(repeat
742 (list
743 (string :tag "Minted option name ")
744 (string :tag "Minted option value"))))
746 (defvar org-latex-custom-lang-environments nil
747 "Alist mapping languages to language-specific LaTeX environments.
749 It is used during export of src blocks by the listings and minted
750 latex packages. For example,
752 \(setq org-latex-custom-lang-environments
753 '\(\(python \"pythoncode\"\)\)\)
755 would have the effect that if org encounters begin_src python
756 during latex export it will output
758 \\begin{pythoncode}
759 <src block body>
760 \\end{pythoncode}")
763 ;;;; Compilation
765 (defcustom org-latex-pdf-process
766 '("pdflatex -interaction nonstopmode -output-directory %o %f"
767 "pdflatex -interaction nonstopmode -output-directory %o %f"
768 "pdflatex -interaction nonstopmode -output-directory %o %f")
769 "Commands to process a LaTeX file to a PDF file.
770 This is a list of strings, each of them will be given to the
771 shell as a command. %f in the command will be replaced by the
772 full file name, %b by the file base name (i.e. without directory
773 and extension parts) and %o by the base directory of the file.
775 The reason why this is a list is that it usually takes several
776 runs of `pdflatex', maybe mixed with a call to `bibtex'. Org
777 does not have a clever mechanism to detect which of these
778 commands have to be run to get to a stable result, and it also
779 does not do any error checking.
781 By default, Org uses 3 runs of `pdflatex' to do the processing.
782 If you have texi2dvi on your system and if that does not cause
783 the infamous egrep/locale bug:
785 http://lists.gnu.org/archive/html/bug-texinfo/2010-03/msg00031.html
787 then `texi2dvi' is the superior choice as it automates the LaTeX
788 build process by calling the \"correct\" combinations of
789 auxiliary programs. Org does offer `texi2dvi' as one of the
790 customize options. Alternatively, `rubber' and `latexmk' also
791 provide similar functionality. The latter supports `biber' out
792 of the box.
794 Alternatively, this may be a Lisp function that does the
795 processing, so you could use this to apply the machinery of
796 AUCTeX or the Emacs LaTeX mode. This function should accept the
797 file name as its single argument."
798 :group 'org-export-pdf
799 :type '(choice
800 (repeat :tag "Shell command sequence"
801 (string :tag "Shell command"))
802 (const :tag "2 runs of pdflatex"
803 ("pdflatex -interaction nonstopmode -output-directory %o %f"
804 "pdflatex -interaction nonstopmode -output-directory %o %f"))
805 (const :tag "3 runs of pdflatex"
806 ("pdflatex -interaction nonstopmode -output-directory %o %f"
807 "pdflatex -interaction nonstopmode -output-directory %o %f"
808 "pdflatex -interaction nonstopmode -output-directory %o %f"))
809 (const :tag "pdflatex,bibtex,pdflatex,pdflatex"
810 ("pdflatex -interaction nonstopmode -output-directory %o %f"
811 "bibtex %b"
812 "pdflatex -interaction nonstopmode -output-directory %o %f"
813 "pdflatex -interaction nonstopmode -output-directory %o %f"))
814 (const :tag "2 runs of xelatex"
815 ("xelatex -interaction nonstopmode -output-directory %o %f"
816 "xelatex -interaction nonstopmode -output-directory %o %f"))
817 (const :tag "3 runs of xelatex"
818 ("xelatex -interaction nonstopmode -output-directory %o %f"
819 "xelatex -interaction nonstopmode -output-directory %o %f"
820 "xelatex -interaction nonstopmode -output-directory %o %f"))
821 (const :tag "xelatex,bibtex,xelatex,xelatex"
822 ("xelatex -interaction nonstopmode -output-directory %o %f"
823 "bibtex %b"
824 "xelatex -interaction nonstopmode -output-directory %o %f"
825 "xelatex -interaction nonstopmode -output-directory %o %f"))
826 (const :tag "texi2dvi"
827 ("texi2dvi -p -b -V %f"))
828 (const :tag "rubber"
829 ("rubber -d --into %o %f"))
830 (const :tag "latexmk"
831 ("latexmk -g -pdf %f"))
832 (function)))
834 (defcustom org-latex-logfiles-extensions
835 '("aux" "idx" "log" "out" "toc" "nav" "snm" "vrb")
836 "The list of file extensions to consider as LaTeX logfiles.
837 The logfiles will be remove if `org-latex-remove-logfiles' is
838 non-nil."
839 :group 'org-export-latex
840 :type '(repeat (string :tag "Extension")))
842 (defcustom org-latex-remove-logfiles t
843 "Non-nil means remove the logfiles produced by PDF production.
844 By default, logfiles are files with these extensions: .aux, .idx,
845 .log, .out, .toc, .nav, .snm and .vrb. To define the set of
846 logfiles to remove, set `org-latex-logfiles-extensions'."
847 :group 'org-export-latex
848 :type 'boolean)
850 (defcustom org-latex-known-errors
851 '(("Reference.*?undefined" . "[undefined reference]")
852 ("Citation.*?undefined" . "[undefined citation]")
853 ("Undefined control sequence" . "[undefined control sequence]")
854 ("^! LaTeX.*?Error" . "[LaTeX error]")
855 ("^! Package.*?Error" . "[package error]")
856 ("Runaway argument" . "Runaway argument"))
857 "Alist of regular expressions and associated messages for the user.
858 The regular expressions are used to find possible errors in the
859 log of a latex-run."
860 :group 'org-export-latex
861 :version "24.4"
862 :package-version '(Org . "8.0")
863 :type '(repeat
864 (cons
865 (string :tag "Regexp")
866 (string :tag "Message"))))
870 ;;; Internal Functions
872 (defun org-latex--caption/label-string (element info)
873 "Return caption and label LaTeX string for ELEMENT.
875 INFO is a plist holding contextual information. If there's no
876 caption nor label, return the empty string.
878 For non-floats, see `org-latex--wrap-label'."
879 (let* ((label (org-element-property :name element))
880 (label-str (if (not (org-string-nw-p label)) ""
881 (format "\\label{%s}"
882 (org-export-solidify-link-text label))))
883 (main (org-export-get-caption element))
884 (short (org-export-get-caption element t)))
885 (cond
886 ((and (not main) (equal label-str "")) "")
887 ((not main) (concat label-str "\n"))
888 ;; Option caption format with short name.
889 (short (format "\\caption[%s]{%s%s}\n"
890 (org-export-data short info)
891 label-str
892 (org-export-data main info)))
893 ;; Standard caption format.
894 (t (format "\\caption{%s%s}\n" label-str (org-export-data main info))))))
896 (defun org-latex-guess-inputenc (header)
897 "Set the coding system in inputenc to what the buffer is.
899 HEADER is the LaTeX header string. This function only applies
900 when specified inputenc option is \"AUTO\".
902 Return the new header, as a string."
903 (let* ((cs (or (ignore-errors
904 (latexenc-coding-system-to-inputenc
905 (or org-export-coding-system buffer-file-coding-system)))
906 "utf8")))
907 (if (not cs) header
908 ;; First translate if that is requested.
909 (setq cs (or (cdr (assoc cs org-latex-inputenc-alist)) cs))
910 ;; Then find the \usepackage statement and replace the option.
911 (replace-regexp-in-string "\\\\usepackage\\[\\(AUTO\\)\\]{inputenc}"
912 cs header t nil 1))))
914 (defun org-latex-guess-babel-language (header info)
915 "Set Babel's language according to LANGUAGE keyword.
917 HEADER is the LaTeX header string. INFO is the plist used as
918 a communication channel.
920 Insertion of guessed language only happens when Babel package has
921 explicitly been loaded. Then it is added to the rest of
922 package's options.
924 The argument to Babel may be \"AUTO\" which is then replaced with
925 the language of the document or `org-export-default-language'
926 unless language in question is already loaded.
928 Return the new header."
929 (let ((language-code (plist-get info :language)))
930 ;; If no language is set or Babel package is not loaded, return
931 ;; HEADER as-is.
932 (if (or (not (stringp language-code))
933 (not (string-match "\\\\usepackage\\[\\(.*\\)\\]{babel}" header)))
934 header
935 (let ((options (save-match-data
936 (org-split-string (match-string 1 header) ",[ \t]*")))
937 (language (cdr (assoc language-code
938 org-latex-babel-language-alist))))
939 ;; If LANGUAGE is already loaded, return header without AUTO.
940 ;; Otherwise, replace AUTO with language or append language if
941 ;; AUTO is not present.
942 (replace-match
943 (mapconcat (lambda (option) (if (equal "AUTO" option) language option))
944 (cond ((member language options) (delete "AUTO" options))
945 ((member "AUTO" options) options)
946 (t (append options (list language))))
947 ", ")
948 t nil header 1)))))
950 (defun org-latex--find-verb-separator (s)
951 "Return a character not used in string S.
952 This is used to choose a separator for constructs like \\verb."
953 (let ((ll "~,./?;':\"|!@#%^&-_=+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ<>()[]{}"))
954 (loop for c across ll
955 when (not (string-match (regexp-quote (char-to-string c)) s))
956 return (char-to-string c))))
958 (defun org-latex--make-option-string (options)
959 "Return a comma separated string of keywords and values.
960 OPTIONS is an alist where the key is the options keyword as
961 a string, and the value a list containing the keyword value, or
962 nil."
963 (mapconcat (lambda (pair)
964 (concat (first pair)
965 (when (> (length (second pair)) 0)
966 (concat "=" (second pair)))))
967 options
968 ","))
970 (defun org-latex--wrap-label (element output)
971 "Wrap label associated to ELEMENT around OUTPUT, if appropriate.
972 This function shouldn't be used for floats. See
973 `org-latex--caption/label-string'."
974 (let ((label (org-element-property :name element)))
975 (if (not (and (org-string-nw-p output) (org-string-nw-p label))) output
976 (concat (format "\\label{%s}\n" (org-export-solidify-link-text label))
977 output))))
979 (defun org-latex--text-markup (text markup)
980 "Format TEXT depending on MARKUP text markup.
981 See `org-latex-text-markup-alist' for details."
982 (let ((fmt (cdr (assq markup org-latex-text-markup-alist))))
983 (cond
984 ;; No format string: Return raw text.
985 ((not fmt) text)
986 ;; Handle the `verb' special case: Find and appropriate separator
987 ;; and use "\\verb" command.
988 ((eq 'verb fmt)
989 (let ((separator (org-latex--find-verb-separator text)))
990 (concat "\\verb" separator text separator)))
991 ;; Handle the `protectedtexttt' special case: Protect some
992 ;; special chars and use "\texttt{%s}" format string.
993 ((eq 'protectedtexttt fmt)
994 (let ((start 0)
995 (trans '(("\\" . "\\textbackslash{}")
996 ("~" . "\\textasciitilde{}")
997 ("^" . "\\textasciicircum{}")))
998 (rtn "")
999 char)
1000 (while (string-match "[\\{}$%&_#~^]" text)
1001 (setq char (match-string 0 text))
1002 (if (> (match-beginning 0) 0)
1003 (setq rtn (concat rtn (substring text 0 (match-beginning 0)))))
1004 (setq text (substring text (1+ (match-beginning 0))))
1005 (setq char (or (cdr (assoc char trans)) (concat "\\" char))
1006 rtn (concat rtn char)))
1007 (setq text (concat rtn text)
1008 fmt "\\texttt{%s}")
1009 (while (string-match "--" text)
1010 (setq text (replace-match "-{}-" t t text)))
1011 (format fmt text)))
1012 ;; Else use format string.
1013 (t (format fmt text)))))
1015 (defun org-latex--delayed-footnotes-definitions (element info)
1016 "Return footnotes definitions in ELEMENT as a string.
1018 INFO is a plist used as a communication channel.
1020 Footnotes definitions are returned within \"\\footnotetxt{}\"
1021 commands.
1023 This function is used within constructs that don't support
1024 \"\\footnote{}\" command (i.e. an item's tag). In that case,
1025 \"\\footnotemark\" is used within the construct and the function
1026 just outside of it."
1027 (mapconcat
1028 (lambda (ref)
1029 (format
1030 "\\footnotetext[%s]{%s}"
1031 (org-export-get-footnote-number ref info)
1032 (org-trim
1033 (org-export-data
1034 (org-export-get-footnote-definition ref info) info))))
1035 ;; Find every footnote reference in ELEMENT.
1036 (let* (all-refs
1037 search-refs ; For byte-compiler.
1038 (search-refs
1039 (function
1040 (lambda (data)
1041 ;; Return a list of all footnote references never seen
1042 ;; before in DATA.
1043 (org-element-map data 'footnote-reference
1044 (lambda (ref)
1045 (when (org-export-footnote-first-reference-p ref info)
1046 (push ref all-refs)
1047 (when (eq (org-element-property :type ref) 'standard)
1048 (funcall search-refs
1049 (org-export-get-footnote-definition ref info)))))
1050 info)
1051 (reverse all-refs)))))
1052 (funcall search-refs element))
1053 ""))
1057 ;;; Template
1059 (defun org-latex-template (contents info)
1060 "Return complete document string after LaTeX conversion.
1061 CONTENTS is the transcoded contents string. INFO is a plist
1062 holding export options."
1063 (let ((title (org-export-data (plist-get info :title) info)))
1064 (concat
1065 ;; Time-stamp.
1066 (and (plist-get info :time-stamp-file)
1067 (format-time-string "%% Created %Y-%m-%d %a %H:%M\n"))
1068 ;; Document class and packages.
1069 (let ((class (plist-get info :latex-class))
1070 (class-options (plist-get info :latex-class-options)))
1071 (org-element-normalize-string
1072 (let* ((header (nth 1 (assoc class org-latex-classes)))
1073 (document-class-string
1074 (and (stringp header)
1075 (if (not class-options) header
1076 (replace-regexp-in-string
1077 "^[ \t]*\\\\documentclass\\(\\(\\[[^]]*\\]\\)?\\)"
1078 class-options header t nil 1)))))
1079 (if (not document-class-string)
1080 (user-error "Unknown LaTeX class `%s'" class)
1081 (org-latex-guess-babel-language
1082 (org-latex-guess-inputenc
1083 (org-splice-latex-header
1084 document-class-string
1085 org-latex-default-packages-alist
1086 org-latex-packages-alist nil
1087 (concat (plist-get info :latex-header)
1088 (plist-get info :latex-header-extra))))
1089 info)))))
1090 ;; Possibly limit depth for headline numbering.
1091 (let ((sec-num (plist-get info :section-numbers)))
1092 (when (integerp sec-num)
1093 (format "\\setcounter{secnumdepth}{%d}\n" sec-num)))
1094 ;; Author.
1095 (let ((author (and (plist-get info :with-author)
1096 (let ((auth (plist-get info :author)))
1097 (and auth (org-export-data auth info)))))
1098 (email (and (plist-get info :with-email)
1099 (org-export-data (plist-get info :email) info))))
1100 (cond ((and author email (not (string= "" email)))
1101 (format "\\author{%s\\thanks{%s}}\n" author email))
1102 ((or author email) (format "\\author{%s}\n" (or author email)))))
1103 ;; Date.
1104 (let ((date (and (plist-get info :with-date) (org-export-get-date info))))
1105 (format "\\date{%s}\n" (org-export-data date info)))
1106 ;; Title
1107 (format "\\title{%s}\n" title)
1108 ;; Hyperref options.
1109 (when (plist-get info :latex-hyperref-p)
1110 (format "\\hypersetup{\n pdfkeywords={%s},\n pdfsubject={%s},\n pdfcreator={%s}}\n"
1111 (or (plist-get info :keywords) "")
1112 (or (plist-get info :description) "")
1113 (if (not (plist-get info :with-creator)) ""
1114 (plist-get info :creator))))
1115 ;; Document start.
1116 "\\begin{document}\n\n"
1117 ;; Title command.
1118 (org-element-normalize-string
1119 (cond ((string= "" title) nil)
1120 ((not (stringp org-latex-title-command)) nil)
1121 ((string-match "\\(?:[^%]\\|^\\)%s"
1122 org-latex-title-command)
1123 (format org-latex-title-command title))
1124 (t org-latex-title-command)))
1125 ;; Table of contents.
1126 (let ((depth (plist-get info :with-toc)))
1127 (when depth
1128 (concat (when (wholenump depth)
1129 (format "\\setcounter{tocdepth}{%d}\n" depth))
1130 org-latex-toc-command)))
1131 ;; Document's body.
1132 contents
1133 ;; Creator.
1134 (let ((creator-info (plist-get info :with-creator)))
1135 (cond
1136 ((not creator-info) "")
1137 ((eq creator-info 'comment)
1138 (format "%% %s\n" (plist-get info :creator)))
1139 (t (concat (plist-get info :creator) "\n"))))
1140 ;; Document end.
1141 "\\end{document}")))
1145 ;;; Transcode Functions
1147 ;;;; Bold
1149 (defun org-latex-bold (bold contents info)
1150 "Transcode BOLD from Org to LaTeX.
1151 CONTENTS is the text with bold markup. INFO is a plist holding
1152 contextual information."
1153 (org-latex--text-markup contents 'bold))
1156 ;;;; Center Block
1158 (defun org-latex-center-block (center-block contents info)
1159 "Transcode a CENTER-BLOCK element from Org to LaTeX.
1160 CONTENTS holds the contents of the center block. INFO is a plist
1161 holding contextual information."
1162 (org-latex--wrap-label
1163 center-block
1164 (format "\\begin{center}\n%s\\end{center}" contents)))
1167 ;;;; Clock
1169 (defun org-latex-clock (clock contents info)
1170 "Transcode a CLOCK element from Org to LaTeX.
1171 CONTENTS is nil. INFO is a plist holding contextual
1172 information."
1173 (concat
1174 "\\noindent"
1175 (format "\\textbf{%s} " org-clock-string)
1176 (format org-latex-inactive-timestamp-format
1177 (concat (org-translate-time
1178 (org-element-property :raw-value
1179 (org-element-property :value clock)))
1180 (let ((time (org-element-property :duration clock)))
1181 (and time (format " (%s)" time)))))
1182 "\\\\"))
1185 ;;;; Code
1187 (defun org-latex-code (code contents info)
1188 "Transcode a CODE object from Org to LaTeX.
1189 CONTENTS is nil. INFO is a plist used as a communication
1190 channel."
1191 (org-latex--text-markup (org-element-property :value code) 'code))
1194 ;;;; Drawer
1196 (defun org-latex-drawer (drawer contents info)
1197 "Transcode a DRAWER element from Org to LaTeX.
1198 CONTENTS holds the contents of the block. INFO is a plist
1199 holding contextual information."
1200 (let* ((name (org-element-property :drawer-name drawer))
1201 (output (if (functionp org-latex-format-drawer-function)
1202 (funcall org-latex-format-drawer-function
1203 name contents)
1204 ;; If there's no user defined function: simply
1205 ;; display contents of the drawer.
1206 contents)))
1207 (org-latex--wrap-label drawer output)))
1210 ;;;; Dynamic Block
1212 (defun org-latex-dynamic-block (dynamic-block contents info)
1213 "Transcode a DYNAMIC-BLOCK element from Org to LaTeX.
1214 CONTENTS holds the contents of the block. INFO is a plist
1215 holding contextual information. See `org-export-data'."
1216 (org-latex--wrap-label dynamic-block contents))
1219 ;;;; Entity
1221 (defun org-latex-entity (entity contents info)
1222 "Transcode an ENTITY object from Org to LaTeX.
1223 CONTENTS are the definition itself. INFO is a plist holding
1224 contextual information."
1225 (let ((ent (org-element-property :latex entity)))
1226 (if (org-element-property :latex-math-p entity) (format "$%s$" ent) ent)))
1229 ;;;; Example Block
1231 (defun org-latex-example-block (example-block contents info)
1232 "Transcode an EXAMPLE-BLOCK element from Org to LaTeX.
1233 CONTENTS is nil. INFO is a plist holding contextual
1234 information."
1235 (when (org-string-nw-p (org-element-property :value example-block))
1236 (org-latex--wrap-label
1237 example-block
1238 (format "\\begin{verbatim}\n%s\\end{verbatim}"
1239 (org-export-format-code-default example-block info)))))
1242 ;;;; Export Block
1244 (defun org-latex-export-block (export-block contents info)
1245 "Transcode a EXPORT-BLOCK element from Org to LaTeX.
1246 CONTENTS is nil. INFO is a plist holding contextual information."
1247 (when (member (org-element-property :type export-block) '("LATEX" "TEX"))
1248 (org-remove-indentation (org-element-property :value export-block))))
1251 ;;;; Export Snippet
1253 (defun org-latex-export-snippet (export-snippet contents info)
1254 "Transcode a EXPORT-SNIPPET object from Org to LaTeX.
1255 CONTENTS is nil. INFO is a plist holding contextual information."
1256 (when (eq (org-export-snippet-backend export-snippet) 'latex)
1257 (org-element-property :value export-snippet)))
1260 ;;;; Fixed Width
1262 (defun org-latex-fixed-width (fixed-width contents info)
1263 "Transcode a FIXED-WIDTH element from Org to LaTeX.
1264 CONTENTS is nil. INFO is a plist holding contextual information."
1265 (org-latex--wrap-label
1266 fixed-width
1267 (format "\\begin{verbatim}\n%s\\end{verbatim}"
1268 (org-remove-indentation
1269 (org-element-property :value fixed-width)))))
1272 ;;;; Footnote Reference
1274 ;; Footnote reference export is handled by
1275 ;; `org-latex-footnote-reference'.
1277 ;; Internally, `org-latex--get-footnote-counter' is used to restore
1278 ;; the value of the LaTeX "footnote" counter after a jump due to
1279 ;; a reference to an already defined footnote. It is only needed in
1280 ;; item tags since the optional argument to \footnotemark is not
1281 ;; allowed there.
1283 (defun org-latex--get-footnote-counter (footnote-reference info)
1284 "Return \"footnote\" counter before FOOTNOTE-REFERENCE is encountered.
1285 INFO is a plist used as a communication channel."
1286 ;; Find original counter value by counting number of footnote
1287 ;; references appearing for the first time before the current
1288 ;; footnote reference.
1289 (let* ((label (org-element-property :label footnote-reference))
1290 seen-refs
1291 search-ref ; For byte-compiler.
1292 (search-ref
1293 (function
1294 (lambda (data)
1295 ;; Search footnote references through DATA, filling
1296 ;; SEEN-REFS along the way.
1297 (org-element-map data 'footnote-reference
1298 (lambda (fn)
1299 (let ((fn-lbl (org-element-property :label fn)))
1300 (cond
1301 ;; Anonymous footnote match: return number.
1302 ((eq fn footnote-reference) (length seen-refs))
1303 ;; Anonymous footnote: it's always a new one.
1304 ;; Also, be sure to return nil from the `cond' so
1305 ;; `first-match' doesn't get us out of the loop.
1306 ((not fn-lbl) (push 'inline seen-refs) nil)
1307 ;; Label not seen so far: add it so SEEN-REFS.
1309 ;; Also search for subsequent references in
1310 ;; footnote definition so numbering follows
1311 ;; reading logic. Note that we don't care about
1312 ;; inline definitions, since `org-element-map'
1313 ;; already traverses them at the right time.
1314 ((not (member fn-lbl seen-refs))
1315 (push fn-lbl seen-refs)
1316 (funcall search-ref
1317 (org-export-get-footnote-definition fn info))))))
1318 ;; Don't enter footnote definitions since it will
1319 ;; happen when their first reference is found.
1320 info 'first-match 'footnote-definition)))))
1321 (funcall search-ref (plist-get info :parse-tree))))
1323 (defun org-latex-footnote-reference (footnote-reference contents info)
1324 "Transcode a FOOTNOTE-REFERENCE element from Org to LaTeX.
1325 CONTENTS is nil. INFO is a plist holding contextual information."
1326 (concat
1327 ;; Insert separator between two footnotes in a row.
1328 (let ((prev (org-export-get-previous-element footnote-reference info)))
1329 (when (eq (org-element-type prev) 'footnote-reference)
1330 org-latex-footnote-separator))
1331 (cond
1332 ;; Use \footnotemark if the footnote has already been defined.
1333 ((not (org-export-footnote-first-reference-p footnote-reference info))
1334 (format "\\footnotemark[%s]{}"
1335 (org-export-get-footnote-number footnote-reference info)))
1336 ;; Use \footnotemark if reference is within another footnote
1337 ;; reference, footnote definition or table cell.
1338 ((loop for parent in (org-export-get-genealogy footnote-reference)
1339 thereis (memq (org-element-type parent)
1340 '(footnote-reference footnote-definition table-cell)))
1341 "\\footnotemark")
1342 ;; Otherwise, define it with \footnote command.
1344 (let ((def (org-export-get-footnote-definition footnote-reference info)))
1345 (concat
1346 (format "\\footnote{%s}" (org-trim (org-export-data def info)))
1347 ;; Retrieve all footnote references within the footnote and
1348 ;; add their definition after it, since LaTeX doesn't support
1349 ;; them inside.
1350 (org-latex--delayed-footnotes-definitions def info)))))))
1353 ;;;; Headline
1355 (defun org-latex-headline (headline contents info)
1356 "Transcode a HEADLINE element from Org to LaTeX.
1357 CONTENTS holds the contents of the headline. INFO is a plist
1358 holding contextual information."
1359 (unless (org-element-property :footnote-section-p headline)
1360 (let* ((class (plist-get info :latex-class))
1361 (level (org-export-get-relative-level headline info))
1362 (numberedp (org-export-numbered-headline-p headline info))
1363 (class-sectionning (assoc class org-latex-classes))
1364 ;; Section formatting will set two placeholders: one for
1365 ;; the title and the other for the contents.
1366 (section-fmt
1367 (let ((sec (if (functionp (nth 2 class-sectionning))
1368 (funcall (nth 2 class-sectionning) level numberedp)
1369 (nth (1+ level) class-sectionning))))
1370 (cond
1371 ;; No section available for that LEVEL.
1372 ((not sec) nil)
1373 ;; Section format directly returned by a function. Add
1374 ;; placeholder for contents.
1375 ((stringp sec) (concat sec "\n%s"))
1376 ;; (numbered-section . unnumbered-section)
1377 ((not (consp (cdr sec)))
1378 (concat (funcall (if numberedp #'car #'cdr) sec) "\n%s"))
1379 ;; (numbered-open numbered-close)
1380 ((= (length sec) 2)
1381 (when numberedp (concat (car sec) "\n%s" (nth 1 sec))))
1382 ;; (num-in num-out no-num-in no-num-out)
1383 ((= (length sec) 4)
1384 (if numberedp (concat (car sec) "\n%s" (nth 1 sec))
1385 (concat (nth 2 sec) "\n%s" (nth 3 sec)))))))
1386 (text (org-export-data (org-element-property :title headline) info))
1387 (todo
1388 (and (plist-get info :with-todo-keywords)
1389 (let ((todo (org-element-property :todo-keyword headline)))
1390 (and todo (org-export-data todo info)))))
1391 (todo-type (and todo (org-element-property :todo-type headline)))
1392 (tags (and (plist-get info :with-tags)
1393 (org-export-get-tags headline info)))
1394 (priority (and (plist-get info :with-priority)
1395 (org-element-property :priority headline)))
1396 ;; Create the headline text along with a no-tag version.
1397 ;; The latter is required to remove tags from toc.
1398 (full-text (funcall org-latex-format-headline-function
1399 todo todo-type priority text tags))
1400 ;; Associate \label to the headline for internal links.
1401 (headline-label
1402 (format "\\label{sec-%s}\n"
1403 (mapconcat 'number-to-string
1404 (org-export-get-headline-number headline info)
1405 "-")))
1406 (pre-blanks
1407 (make-string (org-element-property :pre-blank headline) 10)))
1408 (if (or (not section-fmt) (org-export-low-level-p headline info))
1409 ;; This is a deep sub-tree: export it as a list item. Also
1410 ;; export as items headlines for which no section format has
1411 ;; been found.
1412 (let ((low-level-body
1413 (concat
1414 ;; If headline is the first sibling, start a list.
1415 (when (org-export-first-sibling-p headline info)
1416 (format "\\begin{%s}\n" (if numberedp 'enumerate 'itemize)))
1417 ;; Itemize headline
1418 "\\item " full-text "\n" headline-label pre-blanks contents)))
1419 ;; If headline is not the last sibling simply return
1420 ;; LOW-LEVEL-BODY. Otherwise, also close the list, before
1421 ;; any blank line.
1422 (if (not (org-export-last-sibling-p headline info)) low-level-body
1423 (replace-regexp-in-string
1424 "[ \t\n]*\\'"
1425 (format "\n\\\\end{%s}" (if numberedp 'enumerate 'itemize))
1426 low-level-body)))
1427 ;; This is a standard headline. Export it as a section. Add
1428 ;; an alternative heading when possible, and when this is not
1429 ;; identical to the usual heading.
1430 (let ((opt-title
1431 (funcall org-latex-format-headline-function
1432 todo todo-type priority
1433 (org-export-data
1434 (org-export-get-alt-title headline info) info)
1435 (and (eq (plist-get info :with-tags) t) tags))))
1436 (if (and numberedp opt-title
1437 (not (equal opt-title full-text))
1438 (string-match "\\`\\\\\\(.*?[^*]\\){" section-fmt))
1439 (format (replace-match "\\1[%s]" nil nil section-fmt 1)
1440 ;; Replace square brackets with parenthesis
1441 ;; since square brackets are not supported in
1442 ;; optional arguments.
1443 (replace-regexp-in-string
1444 "\\[" "(" (replace-regexp-in-string "\\]" ")" opt-title))
1445 full-text
1446 (concat headline-label pre-blanks contents))
1447 ;; Impossible to add an alternative heading. Fallback to
1448 ;; regular sectioning format string.
1449 (format section-fmt full-text
1450 (concat headline-label pre-blanks contents))))))))
1452 (defun org-latex-format-headline-default-function
1453 (todo todo-type priority text tags)
1454 "Default format function for a headline.
1455 See `org-latex-format-headline-function' for details."
1456 (concat
1457 (and todo (format "{\\bfseries\\sffamily %s} " todo))
1458 (and priority (format "\\framebox{\\#%c} " priority))
1459 text
1460 (and tags
1461 (format "\\hfill{}\\textsc{%s}" (mapconcat 'identity tags ":")))))
1464 ;;;; Horizontal Rule
1466 (defun org-latex-horizontal-rule (horizontal-rule contents info)
1467 "Transcode an HORIZONTAL-RULE object from Org to LaTeX.
1468 CONTENTS is nil. INFO is a plist holding contextual information."
1469 (let ((attr (org-export-read-attribute :attr_latex horizontal-rule))
1470 (prev (org-export-get-previous-element horizontal-rule info)))
1471 (concat
1472 ;; Make sure the rule doesn't start at the end of the current
1473 ;; line by separating it with a blank line from previous element.
1474 (when (and prev
1475 (let ((prev-blank (org-element-property :post-blank prev)))
1476 (or (not prev-blank) (zerop prev-blank))))
1477 "\n")
1478 (org-latex--wrap-label
1479 horizontal-rule
1480 (format "\\rule{%s}{%s}"
1481 (or (plist-get attr :width) "\\linewidth")
1482 (or (plist-get attr :thickness) "0.5pt"))))))
1485 ;;;; Inline Src Block
1487 (defun org-latex-inline-src-block (inline-src-block contents info)
1488 "Transcode an INLINE-SRC-BLOCK element from Org to LaTeX.
1489 CONTENTS holds the contents of the item. INFO is a plist holding
1490 contextual information."
1491 (let* ((code (org-element-property :value inline-src-block))
1492 (separator (org-latex--find-verb-separator code)))
1493 (cond
1494 ;; Do not use a special package: transcode it verbatim.
1495 ((not org-latex-listings)
1496 (concat "\\verb" separator code separator))
1497 ;; Use minted package.
1498 ((eq org-latex-listings 'minted)
1499 (let* ((org-lang (org-element-property :language inline-src-block))
1500 (mint-lang (or (cadr (assq (intern org-lang)
1501 org-latex-minted-langs))
1502 org-lang))
1503 (options (org-latex--make-option-string
1504 org-latex-minted-options)))
1505 (concat (format "\\mint%s{%s}"
1506 (if (string= options "") "" (format "[%s]" options))
1507 mint-lang)
1508 separator code separator)))
1509 ;; Use listings package.
1511 ;; Maybe translate language's name.
1512 (let* ((org-lang (org-element-property :language inline-src-block))
1513 (lst-lang (or (cadr (assq (intern org-lang)
1514 org-latex-listings-langs))
1515 org-lang))
1516 (options (org-latex--make-option-string
1517 (append org-latex-listings-options
1518 `(("language" ,lst-lang))))))
1519 (concat (format "\\lstinline[%s]" options)
1520 separator code separator))))))
1523 ;;;; Inlinetask
1525 (defun org-latex-inlinetask (inlinetask contents info)
1526 "Transcode an INLINETASK element from Org to LaTeX.
1527 CONTENTS holds the contents of the block. INFO is a plist
1528 holding contextual information."
1529 (let ((title (org-export-data (org-element-property :title inlinetask) info))
1530 (todo (and (plist-get info :with-todo-keywords)
1531 (let ((todo (org-element-property :todo-keyword inlinetask)))
1532 (and todo (org-export-data todo info)))))
1533 (todo-type (org-element-property :todo-type inlinetask))
1534 (tags (and (plist-get info :with-tags)
1535 (org-export-get-tags inlinetask info)))
1536 (priority (and (plist-get info :with-priority)
1537 (org-element-property :priority inlinetask))))
1538 ;; If `org-latex-format-inlinetask-function' is provided, call it
1539 ;; with appropriate arguments.
1540 (if (functionp org-latex-format-inlinetask-function)
1541 (funcall org-latex-format-inlinetask-function
1542 todo todo-type priority title tags contents)
1543 ;; Otherwise, use a default template.
1544 (org-latex--wrap-label
1545 inlinetask
1546 (let ((full-title
1547 (concat
1548 (when todo (format "\\textbf{\\textsf{\\textsc{%s}}} " todo))
1549 (when priority (format "\\framebox{\\#%c} " priority))
1550 title
1551 (when tags (format "\\hfill{}\\textsc{:%s:}"
1552 (mapconcat 'identity tags ":"))))))
1553 (format (concat "\\begin{center}\n"
1554 "\\fbox{\n"
1555 "\\begin{minipage}[c]{.6\\textwidth}\n"
1556 "%s\n\n"
1557 "\\rule[.8em]{\\textwidth}{2pt}\n\n"
1558 "%s"
1559 "\\end{minipage}\n"
1560 "}\n"
1561 "\\end{center}")
1562 full-title contents))))))
1565 ;;;; Italic
1567 (defun org-latex-italic (italic contents info)
1568 "Transcode ITALIC from Org to LaTeX.
1569 CONTENTS is the text with italic markup. INFO is a plist holding
1570 contextual information."
1571 (org-latex--text-markup contents 'italic))
1574 ;;;; Item
1576 (defun org-latex-item (item contents info)
1577 "Transcode an ITEM element from Org to LaTeX.
1578 CONTENTS holds the contents of the item. INFO is a plist holding
1579 contextual information."
1580 (let* ((counter
1581 (let ((count (org-element-property :counter item))
1582 (level
1583 ;; Determine level of current item to determine the
1584 ;; correct LaTeX counter to use (enumi, enumii...).
1585 (let ((parent item) (level 0))
1586 (while (memq (org-element-type
1587 (setq parent (org-export-get-parent parent)))
1588 '(plain-list item))
1589 (when (and (eq (org-element-type parent) 'plain-list)
1590 (eq (org-element-property :type parent)
1591 'ordered))
1592 (incf level)))
1593 level)))
1594 (and count
1595 (< level 5)
1596 (format "\\setcounter{enum%s}{%s}\n"
1597 (nth (1- level) '("i" "ii" "iii" "iv"))
1598 (1- count)))))
1599 (checkbox (case (org-element-property :checkbox item)
1600 (on "$\\boxtimes$ ")
1601 (off "$\\Box$ ")
1602 (trans "$\\boxminus$ ")))
1603 (tag (let ((tag (org-element-property :tag item)))
1604 ;; Check-boxes must belong to the tag.
1605 (and tag (format "[{%s}] "
1606 (concat checkbox
1607 (org-export-data tag info)))))))
1608 (concat counter "\\item" (or tag (concat " " checkbox))
1609 (and contents (org-trim contents))
1610 ;; If there are footnotes references in tag, be sure to
1611 ;; add their definition at the end of the item. This
1612 ;; workaround is necessary since "\footnote{}" command is
1613 ;; not supported in tags.
1614 (and tag
1615 (org-latex--delayed-footnotes-definitions
1616 (org-element-property :tag item) info)))))
1619 ;;;; Keyword
1621 (defun org-latex-keyword (keyword contents info)
1622 "Transcode a KEYWORD element from Org to LaTeX.
1623 CONTENTS is nil. INFO is a plist holding contextual information."
1624 (let ((key (org-element-property :key keyword))
1625 (value (org-element-property :value keyword)))
1626 (cond
1627 ((string= key "LATEX") value)
1628 ((string= key "INDEX") (format "\\index{%s}" value))
1629 ((string= key "TOC")
1630 (let ((value (downcase value)))
1631 (cond
1632 ((string-match "\\<headlines\\>" value)
1633 (let ((depth (or (and (string-match "[0-9]+" value)
1634 (string-to-number (match-string 0 value)))
1635 (plist-get info :with-toc))))
1636 (concat
1637 (when (wholenump depth)
1638 (format "\\setcounter{tocdepth}{%s}\n" depth))
1639 "\\tableofcontents")))
1640 ((string= "tables" value) "\\listoftables")
1641 ((string= "listings" value)
1642 (cond
1643 ((eq org-latex-listings 'minted) "\\listoflistings")
1644 (org-latex-listings "\\lstlistoflistings")
1645 ;; At the moment, src blocks with a caption are wrapped
1646 ;; into a figure environment.
1647 (t "\\listoffigures")))))))))
1650 ;;;; Latex Environment
1652 (defun org-latex-latex-environment (latex-environment contents info)
1653 "Transcode a LATEX-ENVIRONMENT element from Org to LaTeX.
1654 CONTENTS is nil. INFO is a plist holding contextual information."
1655 (when (plist-get info :with-latex)
1656 (let ((label (org-element-property :name latex-environment))
1657 (value (org-remove-indentation
1658 (org-element-property :value latex-environment))))
1659 (if (not (org-string-nw-p label)) value
1660 ;; Environment is labelled: label must be within the environment
1661 ;; (otherwise, a reference pointing to that element will count
1662 ;; the section instead).
1663 (with-temp-buffer
1664 (insert value)
1665 (goto-char (point-min))
1666 (forward-line)
1667 (insert
1668 (format "\\label{%s}\n" (org-export-solidify-link-text label)))
1669 (buffer-string))))))
1672 ;;;; Latex Fragment
1674 (defun org-latex-latex-fragment (latex-fragment contents info)
1675 "Transcode a LATEX-FRAGMENT object from Org to LaTeX.
1676 CONTENTS is nil. INFO is a plist holding contextual information."
1677 (when (plist-get info :with-latex)
1678 (org-element-property :value latex-fragment)))
1681 ;;;; Line Break
1683 (defun org-latex-line-break (line-break contents info)
1684 "Transcode a LINE-BREAK object from Org to LaTeX.
1685 CONTENTS is nil. INFO is a plist holding contextual information."
1686 "\\\\\n")
1689 ;;;; Link
1691 (defun org-latex--inline-image (link info)
1692 "Return LaTeX code for an inline image.
1693 LINK is the link pointing to the inline image. INFO is a plist
1694 used as a communication channel."
1695 (let* ((parent (org-export-get-parent-element link))
1696 (path (let ((raw-path (org-element-property :path link)))
1697 (if (not (file-name-absolute-p raw-path)) raw-path
1698 (expand-file-name raw-path))))
1699 (filetype (file-name-extension path))
1700 (caption (org-latex--caption/label-string parent info))
1701 ;; Retrieve latex attributes from the element around.
1702 (attr (org-export-read-attribute :attr_latex parent))
1703 (float (let ((float (plist-get attr :float)))
1704 (cond ((and (not float) (plist-member attr :float)) nil)
1705 ((string= float "wrap") 'wrap)
1706 ((string= float "multicolumn") 'multicolumn)
1707 ((or float (org-element-property :caption parent))
1708 'figure))))
1709 (placement
1710 (let ((place (plist-get attr :placement)))
1711 (cond (place (format "%s" place))
1712 ((eq float 'wrap) "{l}{0.5\\textwidth}")
1713 ((eq float 'figure)
1714 (format "[%s]" org-latex-default-figure-position))
1715 (t ""))))
1716 (comment-include (if (plist-get attr :comment-include) "%" ""))
1717 ;; It is possible to specify width and height in the
1718 ;; ATTR_LATEX line, and also via default variables.
1719 (width (cond ((plist-get attr :width))
1720 ((plist-get attr :height) "")
1721 ((eq float 'wrap) "0.48\\textwidth")
1722 (t org-latex-image-default-width)))
1723 (height (cond ((plist-get attr :height))
1724 ((or (plist-get attr :width)
1725 (memq float '(figure wrap))) "")
1726 (t org-latex-image-default-height)))
1727 (options (let ((opt (or (plist-get attr :options)
1728 org-latex-image-default-option)))
1729 (if (not (string-match "\\`\\[\\(.*\\)\\]\\'" opt)) opt
1730 (match-string 1 opt))))
1731 image-code)
1732 (if (member filetype '("tikz" "pgf"))
1733 ;; For tikz images:
1734 ;; - use \input to read in image file.
1735 ;; - if options are present, wrap in a tikzpicture environment.
1736 ;; - if width or height are present, use \resizebox to change
1737 ;; the image size.
1738 (progn
1739 (setq image-code (format "\\input{%s}" path))
1740 (when (org-string-nw-p options)
1741 (setq image-code
1742 (format "\\begin{tikzpicture}[%s]\n%s\n\\end{tikzpicture}"
1743 options
1744 image-code)))
1745 (when (or (org-string-nw-p width) (org-string-nw-p height))
1746 (setq image-code (format "\\resizebox{%s}{%s}{%s}"
1747 (if (org-string-nw-p width) width "!")
1748 (if (org-string-nw-p height) height "!")
1749 image-code))))
1750 ;; For other images:
1751 ;; - add width and height to options.
1752 ;; - include the image with \includegraphics.
1753 (when (org-string-nw-p width)
1754 (setq options (concat options ",width=" width)))
1755 (when (org-string-nw-p height)
1756 (setq options (concat options ",height=" height)))
1757 (setq image-code
1758 (format "\\includegraphics%s{%s}"
1759 (cond ((not (org-string-nw-p options)) "")
1760 ((= (aref options 0) ?,)
1761 (format "[%s]"(substring options 1)))
1762 (t (format "[%s]" options)))
1763 path)))
1764 ;; Return proper string, depending on FLOAT.
1765 (case float
1766 (wrap (format "\\begin{wrapfigure}%s
1767 \\centering
1768 %s%s
1769 %s\\end{wrapfigure}" placement comment-include image-code caption))
1770 (multicolumn (format "\\begin{figure*}%s
1771 \\centering
1772 %s%s
1773 %s\\end{figure*}" placement comment-include image-code caption))
1774 (figure (format "\\begin{figure}%s
1775 \\centering
1776 %s%s
1777 %s\\end{figure}" placement comment-include image-code caption))
1778 (otherwise image-code))))
1780 (defun org-latex-link (link desc info)
1781 "Transcode a LINK object from Org to LaTeX.
1783 DESC is the description part of the link, or the empty string.
1784 INFO is a plist holding contextual information. See
1785 `org-export-data'."
1786 (let* ((type (org-element-property :type link))
1787 (raw-path (org-element-property :path link))
1788 ;; Ensure DESC really exists, or set it to nil.
1789 (desc (and (not (string= desc "")) desc))
1790 (imagep (org-export-inline-image-p
1791 link org-latex-inline-image-rules))
1792 (path (cond
1793 ((member type '("http" "https" "ftp" "mailto"))
1794 (concat type ":" raw-path))
1795 ((string= type "file")
1796 (if (not (file-name-absolute-p raw-path)) raw-path
1797 (concat "file://" (expand-file-name raw-path))))
1798 (t raw-path)))
1799 protocol)
1800 (cond
1801 ;; Image file.
1802 (imagep (org-latex--inline-image link info))
1803 ;; Radio link: Transcode target's contents and use them as link's
1804 ;; description.
1805 ((string= type "radio")
1806 (let ((destination (org-export-resolve-radio-link link info)))
1807 (when destination
1808 (format "\\hyperref[%s]{%s}"
1809 (org-export-solidify-link-text path)
1810 (org-export-data (org-element-contents destination) info)))))
1811 ;; Links pointing to a headline: Find destination and build
1812 ;; appropriate referencing command.
1813 ((member type '("custom-id" "fuzzy" "id"))
1814 (let ((destination (if (string= type "fuzzy")
1815 (org-export-resolve-fuzzy-link link info)
1816 (org-export-resolve-id-link link info))))
1817 (case (org-element-type destination)
1818 ;; Id link points to an external file.
1819 (plain-text
1820 (if desc (format "\\href{%s}{%s}" destination desc)
1821 (format "\\url{%s}" destination)))
1822 ;; Fuzzy link points nowhere.
1823 ('nil
1824 (format org-latex-link-with-unknown-path-format
1825 (or desc
1826 (org-export-data
1827 (org-element-property :raw-link link) info))))
1828 ;; LINK points to a headline. If headlines are numbered
1829 ;; and the link has no description, display headline's
1830 ;; number. Otherwise, display description or headline's
1831 ;; title.
1832 (headline
1833 (let ((label
1834 (format "sec-%s"
1835 (mapconcat
1836 'number-to-string
1837 (org-export-get-headline-number destination info)
1838 "-"))))
1839 (if (and (plist-get info :section-numbers) (not desc))
1840 (format "\\ref{%s}" label)
1841 (format "\\hyperref[%s]{%s}" label
1842 (or desc
1843 (org-export-data
1844 (org-element-property :title destination) info))))))
1845 ;; Fuzzy link points to a target. Do as above.
1846 (otherwise
1847 (let ((path (org-export-solidify-link-text path)))
1848 (if (not desc) (format "\\ref{%s}" path)
1849 (format "\\hyperref[%s]{%s}" path desc)))))))
1850 ;; Coderef: replace link with the reference name or the
1851 ;; equivalent line number.
1852 ((string= type "coderef")
1853 (format (org-export-get-coderef-format path desc)
1854 (org-export-resolve-coderef path info)))
1855 ;; Link type is handled by a special function.
1856 ((functionp (setq protocol (nth 2 (assoc type org-link-protocols))))
1857 (funcall protocol (org-link-unescape path) desc 'latex))
1858 ;; External link with a description part.
1859 ((and path desc) (format "\\href{%s}{%s}" path desc))
1860 ;; External link without a description part.
1861 (path (format "\\url{%s}" path))
1862 ;; No path, only description. Try to do something useful.
1863 (t (format org-latex-link-with-unknown-path-format desc)))))
1866 ;;;; Paragraph
1868 (defun org-latex-paragraph (paragraph contents info)
1869 "Transcode a PARAGRAPH element from Org to LaTeX.
1870 CONTENTS is the contents of the paragraph, as a string. INFO is
1871 the plist used as a communication channel."
1872 contents)
1875 ;;;; Plain List
1877 (defun org-latex-plain-list (plain-list contents info)
1878 "Transcode a PLAIN-LIST element from Org to LaTeX.
1879 CONTENTS is the contents of the list. INFO is a plist holding
1880 contextual information."
1881 (let* ((type (org-element-property :type plain-list))
1882 (attr (org-export-read-attribute :attr_latex plain-list))
1883 (latex-type (let ((env (plist-get attr :environment)))
1884 (cond (env (format "%s" env))
1885 ((eq type 'ordered) "enumerate")
1886 ((eq type 'unordered) "itemize")
1887 ((eq type 'descriptive) "description")))))
1888 (org-latex--wrap-label
1889 plain-list
1890 (format "\\begin{%s}%s\n%s\\end{%s}"
1891 latex-type
1892 ;; Put optional arguments, if any inside square brackets
1893 ;; when necessary.
1894 (let ((options (format "%s" (or (plist-get attr :options) ""))))
1895 (cond ((equal options "") "")
1896 ((string-match "\\`\\[.*\\]\\'" options) options)
1897 (t (format "[%s]" options))))
1898 contents
1899 latex-type))))
1902 ;;;; Plain Text
1904 (defun org-latex-plain-text (text info)
1905 "Transcode a TEXT string from Org to LaTeX.
1906 TEXT is the string to transcode. INFO is a plist holding
1907 contextual information."
1908 (let ((specialp (plist-get info :with-special-strings))
1909 (output text))
1910 ;; Protect %, #, &, $, _, { and }.
1911 (while (string-match "\\([^\\]\\|^\\)\\([%$#&{}_]\\)" output)
1912 (setq output
1913 (replace-match
1914 (format "\\%s" (match-string 2 output)) nil t output 2)))
1915 ;; Protect ^.
1916 (setq output
1917 (replace-regexp-in-string
1918 "\\([^\\]\\|^\\)\\(\\^\\)" "\\\\^{}" output nil nil 2))
1919 ;; Protect \. If special strings are used, be careful not to
1920 ;; protect "\" in "\-" constructs.
1921 (let ((symbols (if specialp "-%$#&{}^_\\" "%$#&{}^_\\")))
1922 (setq output
1923 (replace-regexp-in-string
1924 (format "\\(?:[^\\]\\|^\\)\\(\\\\\\)\\(?:[^%s]\\|$\\)" symbols)
1925 "$\\backslash$" output nil t 1)))
1926 ;; Protect ~.
1927 (setq output
1928 (replace-regexp-in-string
1929 "\\([^\\]\\|^\\)\\(~\\)" "\\textasciitilde{}" output nil t 2))
1930 ;; Activate smart quotes. Be sure to provide original TEXT string
1931 ;; since OUTPUT may have been modified.
1932 (when (plist-get info :with-smart-quotes)
1933 (setq output (org-export-activate-smart-quotes output :latex info text)))
1934 ;; LaTeX into \LaTeX{} and TeX into \TeX{}.
1935 (let ((case-fold-search nil)
1936 (start 0))
1937 (while (string-match "\\<\\(\\(?:La\\)?TeX\\)\\>" output start)
1938 (setq output (replace-match
1939 (format "\\%s{}" (match-string 1 output)) nil t output)
1940 start (match-end 0))))
1941 ;; Convert special strings.
1942 (when specialp
1943 (setq output
1944 (replace-regexp-in-string "\\.\\.\\." "\\ldots{}" output nil t)))
1945 ;; Handle break preservation if required.
1946 (when (plist-get info :preserve-breaks)
1947 (setq output (replace-regexp-in-string
1948 "\\(\\\\\\\\\\)?[ \t]*\n" " \\\\\\\\\n" output)))
1949 ;; Return value.
1950 output))
1953 ;;;; Planning
1955 (defun org-latex-planning (planning contents info)
1956 "Transcode a PLANNING element from Org to LaTeX.
1957 CONTENTS is nil. INFO is a plist holding contextual
1958 information."
1959 (concat
1960 "\\noindent"
1961 (mapconcat
1962 'identity
1963 (delq nil
1964 (list
1965 (let ((closed (org-element-property :closed planning)))
1966 (when closed
1967 (concat
1968 (format "\\textbf{%s} " org-closed-string)
1969 (format org-latex-inactive-timestamp-format
1970 (org-translate-time
1971 (org-element-property :raw-value closed))))))
1972 (let ((deadline (org-element-property :deadline planning)))
1973 (when deadline
1974 (concat
1975 (format "\\textbf{%s} " org-deadline-string)
1976 (format org-latex-active-timestamp-format
1977 (org-translate-time
1978 (org-element-property :raw-value deadline))))))
1979 (let ((scheduled (org-element-property :scheduled planning)))
1980 (when scheduled
1981 (concat
1982 (format "\\textbf{%s} " org-scheduled-string)
1983 (format org-latex-active-timestamp-format
1984 (org-translate-time
1985 (org-element-property :raw-value scheduled))))))))
1986 " ")
1987 "\\\\"))
1990 ;;;; Quote Block
1992 (defun org-latex-quote-block (quote-block contents info)
1993 "Transcode a QUOTE-BLOCK element from Org to LaTeX.
1994 CONTENTS holds the contents of the block. INFO is a plist
1995 holding contextual information."
1996 (org-latex--wrap-label
1997 quote-block
1998 (format "\\begin{quote}\n%s\\end{quote}" contents)))
2001 ;;;; Quote Section
2003 (defun org-latex-quote-section (quote-section contents info)
2004 "Transcode a QUOTE-SECTION element from Org to LaTeX.
2005 CONTENTS is nil. INFO is a plist holding contextual information."
2006 (let ((value (org-remove-indentation
2007 (org-element-property :value quote-section))))
2008 (when value (format "\\begin{verbatim}\n%s\\end{verbatim}" value))))
2011 ;;;; Radio Target
2013 (defun org-latex-radio-target (radio-target text info)
2014 "Transcode a RADIO-TARGET object from Org to LaTeX.
2015 TEXT is the text of the target. INFO is a plist holding
2016 contextual information."
2017 (format "\\label{%s}%s"
2018 (org-export-solidify-link-text
2019 (org-element-property :value radio-target))
2020 text))
2023 ;;;; Section
2025 (defun org-latex-section (section contents info)
2026 "Transcode a SECTION element from Org to LaTeX.
2027 CONTENTS holds the contents of the section. INFO is a plist
2028 holding contextual information."
2029 contents)
2032 ;;;; Special Block
2034 (defun org-latex-special-block (special-block contents info)
2035 "Transcode a SPECIAL-BLOCK element from Org to LaTeX.
2036 CONTENTS holds the contents of the block. INFO is a plist
2037 holding contextual information."
2038 (let ((type (downcase (org-element-property :type special-block)))
2039 (opt (org-export-read-attribute :attr_latex special-block :options)))
2040 (concat (format "\\begin{%s}%s\n" type (or opt ""))
2041 ;; Insert any label or caption within the block
2042 ;; (otherwise, a reference pointing to that element will
2043 ;; count the section instead).
2044 (org-latex--caption/label-string special-block info)
2045 contents
2046 (format "\\end{%s}" type))))
2049 ;;;; Src Block
2051 (defun org-latex-src-block (src-block contents info)
2052 "Transcode a SRC-BLOCK element from Org to LaTeX.
2053 CONTENTS holds the contents of the item. INFO is a plist holding
2054 contextual information."
2055 (when (org-string-nw-p (org-element-property :value src-block))
2056 (let* ((lang (org-element-property :language src-block))
2057 (caption (org-element-property :caption src-block))
2058 (label (org-element-property :name src-block))
2059 (custom-env (and lang
2060 (cadr (assq (intern lang)
2061 org-latex-custom-lang-environments))))
2062 (num-start (case (org-element-property :number-lines src-block)
2063 (continued (org-export-get-loc src-block info))
2064 (new 0)))
2065 (retain-labels (org-element-property :retain-labels src-block))
2066 (attributes (org-export-read-attribute :attr_latex src-block))
2067 (float (plist-get attributes :float)))
2068 (cond
2069 ;; Case 1. No source fontification.
2070 ((not org-latex-listings)
2071 (let* ((caption-str (org-latex--caption/label-string src-block info))
2072 (float-env
2073 (cond ((and (not float) (plist-member attributes :float)) "%s")
2074 ((string= "multicolumn" float)
2075 (format "\\begin{figure*}[%s]\n%s%%s\n\\end{figure*}"
2076 org-latex-default-figure-position
2077 caption-str))
2078 ((or caption float)
2079 (format "\\begin{figure}[H]\n%s%%s\n\\end{figure}"
2080 caption-str))
2081 (t "%s"))))
2082 (format
2083 float-env
2084 (concat (format "\\begin{verbatim}\n%s\\end{verbatim}"
2085 (org-export-format-code-default src-block info))))))
2086 ;; Case 2. Custom environment.
2087 (custom-env (format "\\begin{%s}\n%s\\end{%s}\n"
2088 custom-env
2089 (org-export-format-code-default src-block info)
2090 custom-env))
2091 ;; Case 3. Use minted package.
2092 ((eq org-latex-listings 'minted)
2093 (let* ((caption-str (org-latex--caption/label-string src-block info))
2094 (float-env
2095 (cond ((and (not float) (plist-member attributes :float)) "%s")
2096 ((string= "multicolumn" float)
2097 (format "\\begin{listing*}\n%%s\n%s\\end{listing*}"
2098 caption-str))
2099 ((or caption float)
2100 (format "\\begin{listing}[H]\n%%s\n%s\\end{listing}"
2101 caption-str))
2102 (t "%s")))
2103 (body
2104 (format
2105 "\\begin{minted}[%s]{%s}\n%s\\end{minted}"
2106 ;; Options.
2107 (org-latex--make-option-string
2108 (if (or (not num-start)
2109 (assoc "linenos" org-latex-minted-options))
2110 org-latex-minted-options
2111 (append
2112 `(("linenos")
2113 ("firstnumber" ,(number-to-string (1+ num-start))))
2114 org-latex-minted-options)))
2115 ;; Language.
2116 (or (cadr (assq (intern lang) org-latex-minted-langs)) lang)
2117 ;; Source code.
2118 (let* ((code-info (org-export-unravel-code src-block))
2119 (max-width
2120 (apply 'max
2121 (mapcar 'length
2122 (org-split-string (car code-info)
2123 "\n")))))
2124 (org-export-format-code
2125 (car code-info)
2126 (lambda (loc num ref)
2127 (concat
2129 (when ref
2130 ;; Ensure references are flushed to the right,
2131 ;; separated with 6 spaces from the widest line
2132 ;; of code.
2133 (concat (make-string (+ (- max-width (length loc)) 6)
2134 ?\s)
2135 (format "(%s)" ref)))))
2136 nil (and retain-labels (cdr code-info)))))))
2137 ;; Return value.
2138 (format float-env body)))
2139 ;; Case 4. Use listings package.
2141 (let ((lst-lang
2142 (or (cadr (assq (intern lang) org-latex-listings-langs)) lang))
2143 (caption-str
2144 (when caption
2145 (let ((main (org-export-get-caption src-block))
2146 (secondary (org-export-get-caption src-block t)))
2147 (if (not secondary)
2148 (format "{%s}" (org-export-data main info))
2149 (format "{[%s]%s}"
2150 (org-export-data secondary info)
2151 (org-export-data main info)))))))
2152 (concat
2153 ;; Options.
2154 (format
2155 "\\lstset{%s}\n"
2156 (org-latex--make-option-string
2157 (append
2158 org-latex-listings-options
2159 (cond
2160 ((and (not float) (plist-member attributes :float)) nil)
2161 ((string= "multicolumn" float) '(("float" "*")))
2162 ((and float (not (assoc "float" org-latex-listings-options)))
2163 `(("float" ,org-latex-default-figure-position))))
2164 `(("language" ,lst-lang))
2165 (when label `(("label" ,label)))
2166 (when caption-str `(("caption" ,caption-str)))
2167 (cond ((assoc "numbers" org-latex-listings-options) nil)
2168 ((not num-start) '(("numbers" "none")))
2169 ((zerop num-start) '(("numbers" "left")))
2170 (t `(("numbers" "left")
2171 ("firstnumber"
2172 ,(number-to-string (1+ num-start)))))))))
2173 ;; Source code.
2174 (format
2175 "\\begin{lstlisting}\n%s\\end{lstlisting}"
2176 (let* ((code-info (org-export-unravel-code src-block))
2177 (max-width
2178 (apply 'max
2179 (mapcar 'length
2180 (org-split-string (car code-info) "\n")))))
2181 (org-export-format-code
2182 (car code-info)
2183 (lambda (loc num ref)
2184 (concat
2186 (when ref
2187 ;; Ensure references are flushed to the right,
2188 ;; separated with 6 spaces from the widest line of
2189 ;; code
2190 (concat (make-string (+ (- max-width (length loc)) 6) ? )
2191 (format "(%s)" ref)))))
2192 nil (and retain-labels (cdr code-info))))))))))))
2195 ;;;; Statistics Cookie
2197 (defun org-latex-statistics-cookie (statistics-cookie contents info)
2198 "Transcode a STATISTICS-COOKIE object from Org to LaTeX.
2199 CONTENTS is nil. INFO is a plist holding contextual information."
2200 (replace-regexp-in-string
2201 "%" "\\%" (org-element-property :value statistics-cookie) nil t))
2204 ;;;; Strike-Through
2206 (defun org-latex-strike-through (strike-through contents info)
2207 "Transcode STRIKE-THROUGH from Org to LaTeX.
2208 CONTENTS is the text with strike-through markup. INFO is a plist
2209 holding contextual information."
2210 (org-latex--text-markup contents 'strike-through))
2213 ;;;; Subscript
2215 (defun org-latex--script-size (object info)
2216 "Transcode a subscript or superscript object.
2217 OBJECT is an Org object. INFO is a plist used as a communication
2218 channel."
2219 (let ((in-script-p
2220 ;; Non-nil if object is already in a sub/superscript.
2221 (let ((parent object))
2222 (catch 'exit
2223 (while (setq parent (org-export-get-parent parent))
2224 (let ((type (org-element-type parent)))
2225 (cond ((memq type '(subscript superscript))
2226 (throw 'exit t))
2227 ((memq type org-element-all-elements)
2228 (throw 'exit nil))))))))
2229 (type (org-element-type object))
2230 (output ""))
2231 (org-element-map (org-element-contents object)
2232 (cons 'plain-text org-element-all-objects)
2233 (lambda (obj)
2234 (case (org-element-type obj)
2235 ((entity latex-fragment)
2236 (let ((data (org-trim (org-export-data obj info))))
2237 (string-match
2238 "\\`\\(?:\\\\[([]\\|\\$+\\)?\\(.*?\\)\\(?:\\\\[])]\\|\\$+\\)?\\'"
2239 data)
2240 (setq output
2241 (concat output
2242 (match-string 1 data)
2243 (let ((blank (org-element-property :post-blank obj)))
2244 (and blank (> blank 0) "\\ "))))))
2245 (plain-text
2246 (setq output
2247 (format "%s\\text{%s}" output (org-export-data obj info))))
2248 (otherwise
2249 (setq output
2250 (concat output
2251 (org-export-data obj info)
2252 (let ((blank (org-element-property :post-blank obj)))
2253 (and blank (> blank 0) "\\ ")))))))
2254 info nil org-element-recursive-objects)
2255 ;; Result. Do not wrap into math mode if already in a subscript
2256 ;; or superscript. Do not wrap into curly brackets if OUTPUT is
2257 ;; a single character. Also merge consecutive subscript and
2258 ;; superscript into the same math snippet.
2259 (concat (and (not in-script-p)
2260 (let ((prev (org-export-get-previous-element object info)))
2261 (or (not prev)
2262 (not (eq (org-element-type prev)
2263 (if (eq type 'subscript) 'superscript
2264 'subscript)))
2265 (let ((blank (org-element-property :post-blank prev)))
2266 (and blank (> blank 0)))))
2267 "$")
2268 (if (eq (org-element-type object) 'subscript) "_" "^")
2269 (and (> (length output) 1) "{")
2270 output
2271 (and (> (length output) 1) "}")
2272 (and (not in-script-p)
2273 (or (let ((blank (org-element-property :post-blank object)))
2274 (and blank (> blank 0)))
2275 (not (eq (org-element-type
2276 (org-export-get-next-element object info))
2277 (if (eq type 'subscript) 'superscript
2278 'subscript))))
2279 "$"))))
2281 (defun org-latex-subscript (subscript contents info)
2282 "Transcode a SUBSCRIPT object from Org to LaTeX.
2283 CONTENTS is the contents of the object. INFO is a plist holding
2284 contextual information."
2285 (org-latex--script-size subscript info))
2288 ;;;; Superscript
2290 (defun org-latex-superscript (superscript contents info)
2291 "Transcode a SUPERSCRIPT object from Org to LaTeX.
2292 CONTENTS is the contents of the object. INFO is a plist holding
2293 contextual information."
2294 (org-latex--script-size superscript info))
2297 ;;;; Table
2299 ;; `org-latex-table' is the entry point for table transcoding. It
2300 ;; takes care of tables with a "verbatim" mode. Otherwise, it
2301 ;; delegates the job to either `org-latex--table.el-table',
2302 ;; `org-latex--org-table' or `org-latex--math-table' functions,
2303 ;; depending of the type of the table and the mode requested.
2305 ;; `org-latex--align-string' is a subroutine used to build alignment
2306 ;; string for Org tables.
2308 (defun org-latex-table (table contents info)
2309 "Transcode a TABLE element from Org to LaTeX.
2310 CONTENTS is the contents of the table. INFO is a plist holding
2311 contextual information."
2312 (if (eq (org-element-property :type table) 'table.el)
2313 ;; "table.el" table. Convert it using appropriate tools.
2314 (org-latex--table.el-table table info)
2315 (let ((type (or (org-export-read-attribute :attr_latex table :mode)
2316 org-latex-default-table-mode)))
2317 (cond
2318 ;; Case 1: Verbatim table.
2319 ((string= type "verbatim")
2320 (format "\\begin{verbatim}\n%s\n\\end{verbatim}"
2321 ;; Re-create table, without affiliated keywords.
2322 (org-trim (org-element-interpret-data
2323 `(table nil ,@(org-element-contents table))))))
2324 ;; Case 2: Matrix.
2325 ((or (string= type "math") (string= type "inline-math"))
2326 (org-latex--math-table table info))
2327 ;; Case 3: Standard table.
2328 (t (concat (org-latex--org-table table contents info)
2329 ;; When there are footnote references within the
2330 ;; table, insert their definition just after it.
2331 (org-latex--delayed-footnotes-definitions table info)))))))
2333 (defun org-latex--align-string (table info)
2334 "Return an appropriate LaTeX alignment string.
2335 TABLE is the considered table. INFO is a plist used as
2336 a communication channel."
2337 (or (org-export-read-attribute :attr_latex table :align)
2338 (let (align)
2339 ;; Extract column groups and alignment from first (non-rule)
2340 ;; row.
2341 (org-element-map
2342 (org-element-map table 'table-row
2343 (lambda (row)
2344 (and (eq (org-element-property :type row) 'standard) row))
2345 info 'first-match)
2346 'table-cell
2347 (lambda (cell)
2348 (let ((borders (org-export-table-cell-borders cell info)))
2349 ;; Check left border for the first cell only.
2350 (when (and (memq 'left borders) (not align))
2351 (push "|" align))
2352 (push (case (org-export-table-cell-alignment cell info)
2353 (left "l")
2354 (right "r")
2355 (center "c"))
2356 align)
2357 (when (memq 'right borders) (push "|" align))))
2358 info)
2359 (apply 'concat (nreverse align)))))
2361 (defun org-latex--org-table (table contents info)
2362 "Return appropriate LaTeX code for an Org table.
2364 TABLE is the table type element to transcode. CONTENTS is its
2365 contents, as a string. INFO is a plist used as a communication
2366 channel.
2368 This function assumes TABLE has `org' as its `:type' property and
2369 `table' as its `:mode' attribute."
2370 (let* ((caption (org-latex--caption/label-string table info))
2371 (attr (org-export-read-attribute :attr_latex table))
2372 ;; Determine alignment string.
2373 (alignment (org-latex--align-string table info))
2374 ;; Determine environment for the table: longtable, tabular...
2375 (table-env (or (plist-get attr :environment)
2376 org-latex-default-table-environment))
2377 ;; If table is a float, determine environment: table, table*
2378 ;; or sidewaystable.
2379 (float-env (unless (member table-env '("longtable" "longtabu"))
2380 (let ((float (plist-get attr :float)))
2381 (cond
2382 ((and (not float) (plist-member attr :float)) nil)
2383 ((string= float "sidewaystable") "sidewaystable")
2384 ((string= float "multicolumn") "table*")
2385 ((or float (org-element-property :caption table))
2386 "table")))))
2387 ;; Extract others display options.
2388 (fontsize (let ((font (plist-get attr :font)))
2389 (and font (concat font "\n"))))
2390 (width (plist-get attr :width))
2391 (spreadp (plist-get attr :spread))
2392 (placement (or (plist-get attr :placement)
2393 (format "[%s]" org-latex-default-figure-position)))
2394 (centerp (if (plist-member attr :center) (plist-get attr :center)
2395 org-latex-tables-centered)))
2396 ;; Prepare the final format string for the table.
2397 (cond
2398 ;; Longtable.
2399 ((equal "longtable" table-env)
2400 (concat (and fontsize (concat "{" fontsize))
2401 (format "\\begin{longtable}{%s}\n" alignment)
2402 (and org-latex-table-caption-above
2403 (org-string-nw-p caption)
2404 (concat caption "\\\\\n"))
2405 contents
2406 (and (not org-latex-table-caption-above)
2407 (org-string-nw-p caption)
2408 (concat caption "\\\\\n"))
2409 "\\end{longtable}\n"
2410 (and fontsize "}")))
2411 ;; Longtabu
2412 ((equal "longtabu" table-env)
2413 (concat (and fontsize (concat "{" fontsize))
2414 (format "\\begin{longtabu}%s{%s}\n"
2415 (if width
2416 (format " %s %s "
2417 (if spreadp "spread" "to") width) "")
2418 alignment)
2419 (and org-latex-table-caption-above
2420 (org-string-nw-p caption)
2421 (concat caption "\\\\\n"))
2422 contents
2423 (and (not org-latex-table-caption-above)
2424 (org-string-nw-p caption)
2425 (concat caption "\\\\\n"))
2426 "\\end{longtabu}\n"
2427 (and fontsize "}")))
2428 ;; Others.
2429 (t (concat (cond
2430 (float-env
2431 (concat (format "\\begin{%s}%s\n" float-env placement)
2432 (if org-latex-table-caption-above caption "")
2433 (when centerp "\\centering\n")
2434 fontsize))
2435 (centerp (concat "\\begin{center}\n" fontsize))
2436 (fontsize (concat "{" fontsize)))
2437 (cond ((equal "tabu" table-env)
2438 (format "\\begin{tabu}%s{%s}\n%s\\end{tabu}"
2439 (if width (format
2440 (if spreadp " spread %s " " to %s ")
2441 width) "")
2442 alignment
2443 contents))
2444 (t (format "\\begin{%s}%s{%s}\n%s\\end{%s}"
2445 table-env
2446 (if width (format "{%s}" width) "")
2447 alignment
2448 contents
2449 table-env)))
2450 (cond
2451 (float-env
2452 (concat (if org-latex-table-caption-above "" caption)
2453 (format "\n\\end{%s}" float-env)))
2454 (centerp "\n\\end{center}")
2455 (fontsize "}")))))))
2457 (defun org-latex--table.el-table (table info)
2458 "Return appropriate LaTeX code for a table.el table.
2460 TABLE is the table type element to transcode. INFO is a plist
2461 used as a communication channel.
2463 This function assumes TABLE has `table.el' as its `:type'
2464 property."
2465 (require 'table)
2466 ;; Ensure "*org-export-table*" buffer is empty.
2467 (with-current-buffer (get-buffer-create "*org-export-table*")
2468 (erase-buffer))
2469 (let ((output (with-temp-buffer
2470 (insert (org-element-property :value table))
2471 (goto-char 1)
2472 (re-search-forward "^[ \t]*|[^|]" nil t)
2473 (table-generate-source 'latex "*org-export-table*")
2474 (with-current-buffer "*org-export-table*"
2475 (org-trim (buffer-string))))))
2476 (kill-buffer (get-buffer "*org-export-table*"))
2477 ;; Remove left out comments.
2478 (while (string-match "^%.*\n" output)
2479 (setq output (replace-match "" t t output)))
2480 (let ((attr (org-export-read-attribute :attr_latex table)))
2481 (when (plist-get attr :rmlines)
2482 ;; When the "rmlines" attribute is provided, remove all hlines
2483 ;; but the the one separating heading from the table body.
2484 (let ((n 0) (pos 0))
2485 (while (and (< (length output) pos)
2486 (setq pos (string-match "^\\\\hline\n?" output pos)))
2487 (incf n)
2488 (unless (= n 2) (setq output (replace-match "" nil nil output))))))
2489 (let ((centerp (if (plist-member attr :center) (plist-get attr :center)
2490 org-latex-tables-centered)))
2491 (if (not centerp) output
2492 (format "\\begin{center}\n%s\n\\end{center}" output))))))
2494 (defun org-latex--math-table (table info)
2495 "Return appropriate LaTeX code for a matrix.
2497 TABLE is the table type element to transcode. INFO is a plist
2498 used as a communication channel.
2500 This function assumes TABLE has `org' as its `:type' property and
2501 `inline-math' or `math' as its `:mode' attribute.."
2502 (let* ((caption (org-latex--caption/label-string table info))
2503 (attr (org-export-read-attribute :attr_latex table))
2504 (inlinep (equal (plist-get attr :mode) "inline-math"))
2505 (env (or (plist-get attr :environment)
2506 org-latex-default-table-environment))
2507 (contents
2508 (mapconcat
2509 (lambda (row)
2510 ;; Ignore horizontal rules.
2511 (when (eq (org-element-property :type row) 'standard)
2512 ;; Return each cell unmodified.
2513 (concat
2514 (mapconcat
2515 (lambda (cell)
2516 (substring (org-element-interpret-data cell) 0 -1))
2517 (org-element-map row 'table-cell 'identity info) "&")
2518 (or (cdr (assoc env org-latex-table-matrix-macros)) "\\\\")
2519 "\n")))
2520 (org-element-map table 'table-row 'identity info) ""))
2521 ;; Variables related to math clusters (contiguous math tables
2522 ;; of the same type).
2523 (mode (org-export-read-attribute :attr_latex table :mode))
2524 (prev (org-export-get-previous-element table info))
2525 (next (org-export-get-next-element table info))
2526 (same-mode-p
2527 (lambda (table)
2528 ;; Non-nil when TABLE has the same mode as current table.
2529 (string= (or (org-export-read-attribute :attr_latex table :mode)
2530 org-latex-default-table-mode)
2531 mode))))
2532 (concat
2533 ;; Opening string. If TABLE is in the middle of a table cluster,
2534 ;; do not insert any.
2535 (cond ((and prev
2536 (eq (org-element-type prev) 'table)
2537 (memq (org-element-property :post-blank prev) '(0 nil))
2538 (funcall same-mode-p prev))
2539 nil)
2540 (inlinep "\\(")
2541 ((org-string-nw-p caption) (concat "\\begin{equation}\n" caption))
2542 (t "\\["))
2543 ;; Prefix.
2544 (or (plist-get attr :math-prefix) "")
2545 ;; Environment. Also treat special cases.
2546 (cond ((equal env "array")
2547 (let ((align (org-latex--align-string table info)))
2548 (format "\\begin{array}{%s}\n%s\\end{array}" align contents)))
2549 ((assoc env org-latex-table-matrix-macros)
2550 (format "\\%s%s{\n%s}"
2552 (or (plist-get attr :math-arguments) "")
2553 contents))
2554 (t (format "\\begin{%s}\n%s\\end{%s}" env contents env)))
2555 ;; Suffix.
2556 (or (plist-get attr :math-suffix) "")
2557 ;; Closing string. If TABLE is in the middle of a table cluster,
2558 ;; do not insert any. If it closes such a cluster, be sure to
2559 ;; close the cluster with a string matching the opening string.
2560 (cond ((and next
2561 (eq (org-element-type next) 'table)
2562 (memq (org-element-property :post-blank table) '(0 nil))
2563 (funcall same-mode-p next))
2564 nil)
2565 (inlinep "\\)")
2566 ;; Find cluster beginning to know which environment to use.
2567 ((let ((cluster-beg table) prev)
2568 (while (and (setq prev (org-export-get-previous-element
2569 cluster-beg info))
2570 (memq (org-element-property :post-blank prev)
2571 '(0 nil))
2572 (funcall same-mode-p prev))
2573 (setq cluster-beg prev))
2574 (and (or (org-element-property :caption cluster-beg)
2575 (org-element-property :name cluster-beg))
2576 "\n\\end{equation}")))
2577 (t "\\]")))))
2580 ;;;; Table Cell
2582 (defun org-latex-table-cell (table-cell contents info)
2583 "Transcode a TABLE-CELL element from Org to LaTeX.
2584 CONTENTS is the cell contents. INFO is a plist used as
2585 a communication channel."
2586 (concat (if (and contents
2587 org-latex-table-scientific-notation
2588 (string-match orgtbl-exp-regexp contents))
2589 ;; Use appropriate format string for scientific
2590 ;; notation.
2591 (format org-latex-table-scientific-notation
2592 (match-string 1 contents)
2593 (match-string 2 contents))
2594 contents)
2595 (when (org-export-get-next-element table-cell info) " & ")))
2598 ;;;; Table Row
2600 (defun org-latex-table-row (table-row contents info)
2601 "Transcode a TABLE-ROW element from Org to LaTeX.
2602 CONTENTS is the contents of the row. INFO is a plist used as
2603 a communication channel."
2604 ;; Rules are ignored since table separators are deduced from
2605 ;; borders of the current row.
2606 (when (eq (org-element-property :type table-row) 'standard)
2607 (let* ((attr (org-export-read-attribute :attr_latex
2608 (org-export-get-parent table-row)))
2609 (longtablep (member (or (plist-get attr :environment)
2610 org-latex-default-table-environment)
2611 '("longtable" "longtabu")))
2612 (booktabsp (if (plist-member attr :booktabs)
2613 (plist-get attr :booktabs)
2614 org-latex-tables-booktabs))
2615 ;; TABLE-ROW's borders are extracted from its first cell.
2616 (borders (org-export-table-cell-borders
2617 (car (org-element-contents table-row)) info)))
2618 (concat
2619 ;; When BOOKTABS are activated enforce top-rule even when no
2620 ;; hline was specifically marked.
2621 (cond ((and booktabsp (memq 'top borders)) "\\toprule\n")
2622 ((and (memq 'top borders) (memq 'above borders)) "\\hline\n"))
2623 contents "\\\\\n"
2624 (cond
2625 ;; Special case for long tables. Define header and footers.
2626 ((and longtablep (org-export-table-row-ends-header-p table-row info))
2627 (format "%s
2628 \\endhead
2629 %s\\multicolumn{%d}{r}{Continued on next page} \\\\
2630 \\endfoot
2631 \\endlastfoot"
2632 (if booktabsp "\\midrule" "\\hline")
2633 (if booktabsp "\\midrule" "\\hline")
2634 ;; Number of columns.
2635 (cdr (org-export-table-dimensions
2636 (org-export-get-parent-table table-row) info))))
2637 ;; When BOOKTABS are activated enforce bottom rule even when
2638 ;; no hline was specifically marked.
2639 ((and booktabsp (memq 'bottom borders)) "\\bottomrule")
2640 ((and (memq 'bottom borders) (memq 'below borders)) "\\hline")
2641 ((memq 'below borders) (if booktabsp "\\midrule" "\\hline")))))))
2644 ;;;; Target
2646 (defun org-latex-target (target contents info)
2647 "Transcode a TARGET object from Org to LaTeX.
2648 CONTENTS is nil. INFO is a plist holding contextual
2649 information."
2650 (format "\\label{%s}"
2651 (org-export-solidify-link-text (org-element-property :value target))))
2654 ;;;; Timestamp
2656 (defun org-latex-timestamp (timestamp contents info)
2657 "Transcode a TIMESTAMP object from Org to LaTeX.
2658 CONTENTS is nil. INFO is a plist holding contextual
2659 information."
2660 (let ((value (org-latex-plain-text
2661 (org-timestamp-translate timestamp) info)))
2662 (case (org-element-property :type timestamp)
2663 ((active active-range) (format org-latex-active-timestamp-format value))
2664 ((inactive inactive-range)
2665 (format org-latex-inactive-timestamp-format value))
2666 (otherwise (format org-latex-diary-timestamp-format value)))))
2669 ;;;; Underline
2671 (defun org-latex-underline (underline contents info)
2672 "Transcode UNDERLINE from Org to LaTeX.
2673 CONTENTS is the text with underline markup. INFO is a plist
2674 holding contextual information."
2675 (org-latex--text-markup contents 'underline))
2678 ;;;; Verbatim
2680 (defun org-latex-verbatim (verbatim contents info)
2681 "Transcode a VERBATIM object from Org to LaTeX.
2682 CONTENTS is nil. INFO is a plist used as a communication
2683 channel."
2684 (org-latex--text-markup (org-element-property :value verbatim) 'verbatim))
2687 ;;;; Verse Block
2689 (defun org-latex-verse-block (verse-block contents info)
2690 "Transcode a VERSE-BLOCK element from Org to LaTeX.
2691 CONTENTS is verse block contents. INFO is a plist holding
2692 contextual information."
2693 (org-latex--wrap-label
2694 verse-block
2695 ;; In a verse environment, add a line break to each newline
2696 ;; character and change each white space at beginning of a line
2697 ;; into a space of 1 em. Also change each blank line with
2698 ;; a vertical space of 1 em.
2699 (progn
2700 (setq contents (replace-regexp-in-string
2701 "^ *\\\\\\\\$" "\\\\vspace*{1em}"
2702 (replace-regexp-in-string
2703 "\\(\\\\\\\\\\)?[ \t]*\n" " \\\\\\\\\n" contents)))
2704 (while (string-match "^[ \t]+" contents)
2705 (let ((new-str (format "\\hspace*{%dem}"
2706 (length (match-string 0 contents)))))
2707 (setq contents (replace-match new-str nil t contents))))
2708 (format "\\begin{verse}\n%s\\end{verse}" contents))))
2712 ;;; End-user functions
2714 ;;;###autoload
2715 (defun org-latex-export-as-latex
2716 (&optional async subtreep visible-only body-only ext-plist)
2717 "Export current buffer as a LaTeX buffer.
2719 If narrowing is active in the current buffer, only export its
2720 narrowed part.
2722 If a region is active, export that region.
2724 A non-nil optional argument ASYNC means the process should happen
2725 asynchronously. The resulting buffer should be accessible
2726 through the `org-export-stack' interface.
2728 When optional argument SUBTREEP is non-nil, export the sub-tree
2729 at point, extracting information from the headline properties
2730 first.
2732 When optional argument VISIBLE-ONLY is non-nil, don't export
2733 contents of hidden elements.
2735 When optional argument BODY-ONLY is non-nil, only write code
2736 between \"\\begin{document}\" and \"\\end{document}\".
2738 EXT-PLIST, when provided, is a property list with external
2739 parameters overriding Org default settings, but still inferior to
2740 file-local settings.
2742 Export is done in a buffer named \"*Org LATEX Export*\", which
2743 will be displayed when `org-export-show-temporary-export-buffer'
2744 is non-nil."
2745 (interactive)
2746 (if async
2747 (org-export-async-start
2748 (lambda (output)
2749 (with-current-buffer (get-buffer-create "*Org LATEX Export*")
2750 (erase-buffer)
2751 (insert output)
2752 (goto-char (point-min))
2753 (LaTeX-mode)
2754 (org-export-add-to-stack (current-buffer) 'latex)))
2755 `(org-export-as 'latex ,subtreep ,visible-only ,body-only
2756 ',ext-plist))
2757 (let ((outbuf
2758 (org-export-to-buffer 'latex "*Org LATEX Export*"
2759 subtreep visible-only body-only ext-plist)))
2760 (with-current-buffer outbuf (LaTeX-mode))
2761 (when org-export-show-temporary-export-buffer
2762 (switch-to-buffer-other-window outbuf)))))
2764 ;;;###autoload
2765 (defun org-latex-convert-region-to-latex ()
2766 "Assume the current region has org-mode syntax, and convert it to LaTeX.
2767 This can be used in any buffer. For example, you can write an
2768 itemized list in org-mode syntax in an LaTeX buffer and use this
2769 command to convert it."
2770 (interactive)
2771 (org-export-replace-region-by 'latex))
2773 ;;;###autoload
2774 (defun org-latex-export-to-latex
2775 (&optional async subtreep visible-only body-only ext-plist)
2776 "Export current buffer to a LaTeX file.
2778 If narrowing is active in the current buffer, only export its
2779 narrowed part.
2781 If a region is active, export that region.
2783 A non-nil optional argument ASYNC means the process should happen
2784 asynchronously. The resulting file should be accessible through
2785 the `org-export-stack' interface.
2787 When optional argument SUBTREEP is non-nil, export the sub-tree
2788 at point, extracting information from the headline properties
2789 first.
2791 When optional argument VISIBLE-ONLY is non-nil, don't export
2792 contents of hidden elements.
2794 When optional argument BODY-ONLY is non-nil, only write code
2795 between \"\\begin{document}\" and \"\\end{document}\".
2797 EXT-PLIST, when provided, is a property list with external
2798 parameters overriding Org default settings, but still inferior to
2799 file-local settings.
2801 Return output file's name."
2802 (interactive)
2803 (let ((outfile (org-export-output-file-name ".tex" subtreep)))
2804 (if async
2805 (org-export-async-start
2806 (lambda (f) (org-export-add-to-stack f 'latex))
2807 `(expand-file-name
2808 (org-export-to-file
2809 'latex ,outfile ,subtreep ,visible-only ,body-only ',ext-plist)))
2810 (org-export-to-file
2811 'latex outfile subtreep visible-only body-only ext-plist))))
2813 ;;;###autoload
2814 (defun org-latex-export-to-pdf
2815 (&optional async subtreep visible-only body-only ext-plist)
2816 "Export current buffer to LaTeX then process through to PDF.
2818 If narrowing is active in the current buffer, only export its
2819 narrowed part.
2821 If a region is active, export that region.
2823 A non-nil optional argument ASYNC means the process should happen
2824 asynchronously. The resulting file should be accessible through
2825 the `org-export-stack' interface.
2827 When optional argument SUBTREEP is non-nil, export the sub-tree
2828 at point, extracting information from the headline properties
2829 first.
2831 When optional argument VISIBLE-ONLY is non-nil, don't export
2832 contents of hidden elements.
2834 When optional argument BODY-ONLY is non-nil, only write code
2835 between \"\\begin{document}\" and \"\\end{document}\".
2837 EXT-PLIST, when provided, is a property list with external
2838 parameters overriding Org default settings, but still inferior to
2839 file-local settings.
2841 Return PDF file's name."
2842 (interactive)
2843 (if async
2844 (let ((outfile (org-export-output-file-name ".tex" subtreep)))
2845 (org-export-async-start
2846 (lambda (f) (org-export-add-to-stack f 'latex))
2847 `(expand-file-name
2848 (org-latex-compile
2849 (org-export-to-file
2850 'latex ,outfile ,subtreep ,visible-only ,body-only
2851 ',ext-plist)))))
2852 (org-latex-compile
2853 (org-latex-export-to-latex
2854 nil subtreep visible-only body-only ext-plist))))
2856 (defun org-latex-compile (texfile &optional snippet)
2857 "Compile a TeX file.
2859 TEXFILE is the name of the file being compiled. Processing is
2860 done through the command specified in `org-latex-pdf-process'.
2862 When optional argument SNIPPET is non-nil, TEXFILE is a temporary
2863 file used to preview a LaTeX snippet. In this case, do not
2864 create a log buffer and do not bother removing log files.
2866 Return PDF file name or an error if it couldn't be produced."
2867 (let* ((base-name (file-name-sans-extension (file-name-nondirectory texfile)))
2868 (full-name (file-truename texfile))
2869 (out-dir (file-name-directory texfile))
2870 ;; Properly set working directory for compilation.
2871 (default-directory (if (file-name-absolute-p texfile)
2872 (file-name-directory full-name)
2873 default-directory))
2874 errors)
2875 (unless snippet (message (format "Processing LaTeX file %s..." texfile)))
2876 (save-window-excursion
2877 (cond
2878 ;; A function is provided: Apply it.
2879 ((functionp org-latex-pdf-process)
2880 (funcall org-latex-pdf-process (shell-quote-argument texfile)))
2881 ;; A list is provided: Replace %b, %f and %o with appropriate
2882 ;; values in each command before applying it. Output is
2883 ;; redirected to "*Org PDF LaTeX Output*" buffer.
2884 ((consp org-latex-pdf-process)
2885 (let ((outbuf (and (not snippet)
2886 (get-buffer-create "*Org PDF LaTeX Output*"))))
2887 (mapc
2888 (lambda (command)
2889 (shell-command
2890 (replace-regexp-in-string
2891 "%b" (shell-quote-argument base-name)
2892 (replace-regexp-in-string
2893 "%f" (shell-quote-argument full-name)
2894 (replace-regexp-in-string
2895 "%o" (shell-quote-argument out-dir) command t t) t t) t t)
2896 outbuf))
2897 org-latex-pdf-process)
2898 ;; Collect standard errors from output buffer.
2899 (setq errors (and (not snippet) (org-latex--collect-errors outbuf)))))
2900 (t (error "No valid command to process to PDF")))
2901 (let ((pdffile (concat out-dir base-name ".pdf")))
2902 ;; Check for process failure. Provide collected errors if
2903 ;; possible.
2904 (if (not (file-exists-p pdffile))
2905 (error (concat (format "PDF file %s wasn't produced" pdffile)
2906 (when errors (concat ": " errors))))
2907 ;; Else remove log files, when specified, and signal end of
2908 ;; process to user, along with any error encountered.
2909 (when (and (not snippet) org-latex-remove-logfiles)
2910 (dolist (ext org-latex-logfiles-extensions)
2911 (let ((file (concat out-dir base-name "." ext)))
2912 (when (file-exists-p file) (delete-file file)))))
2913 (message (concat "Process completed"
2914 (if (not errors) "."
2915 (concat " with errors: " errors)))))
2916 ;; Return output file name.
2917 pdffile))))
2919 (defun org-latex--collect-errors (buffer)
2920 "Collect some kind of errors from \"pdflatex\" command output.
2922 BUFFER is the buffer containing output.
2924 Return collected error types as a string, or nil if there was
2925 none."
2926 (with-current-buffer buffer
2927 (save-excursion
2928 (goto-char (point-max))
2929 (when (re-search-backward "^[ \t]*This is .*?TeX.*?Version" nil t)
2930 (let ((case-fold-search t)
2931 (errors ""))
2932 (dolist (latex-error org-latex-known-errors)
2933 (when (save-excursion (re-search-forward (car latex-error) nil t))
2934 (setq errors (concat errors " " (cdr latex-error)))))
2935 (and (org-string-nw-p errors) (org-trim errors)))))))
2937 ;;;###autoload
2938 (defun org-latex-publish-to-latex (plist filename pub-dir)
2939 "Publish an Org file to LaTeX.
2941 FILENAME is the filename of the Org file to be published. PLIST
2942 is the property list for the given project. PUB-DIR is the
2943 publishing directory.
2945 Return output file name."
2946 (org-publish-org-to 'latex filename ".tex" plist pub-dir))
2948 ;;;###autoload
2949 (defun org-latex-publish-to-pdf (plist filename pub-dir)
2950 "Publish an Org file to PDF (via LaTeX).
2952 FILENAME is the filename of the Org file to be published. PLIST
2953 is the property list for the given project. PUB-DIR is the
2954 publishing directory.
2956 Return output file name."
2957 ;; Unlike to `org-latex-publish-to-latex', PDF file is generated
2958 ;; in working directory and then moved to publishing directory.
2959 (org-publish-attachment
2960 plist
2961 (org-latex-compile (org-publish-org-to 'latex filename ".tex" plist))
2962 pub-dir))
2965 (provide 'ox-latex)
2967 ;; Local variables:
2968 ;; generated-autoload-file: "org-loaddefs.el"
2969 ;; End:
2971 ;;; ox-latex.el ends here