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