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