Merge branch 'master' of orgmode.org:org-mode
[org-mode.git] / EXPERIMENTAL / org-e-latex.el
blobc83d000789b9cffbfed963ed2cb349042653c381
1 ;;; org-e-latex.el --- LaTeX Back-End For Org Export Engine
3 ;; Copyright (C) 2011-2012 Free Software Foundation, Inc.
5 ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
6 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; This program 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 ;; This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
21 ;;; Commentary:
23 ;; This library implements a LaTeX back-end for Org generic exporter.
25 ;; To test it, run
27 ;; M-: (org-export-to-buffer 'e-latex "*Test e-LaTeX*") RET
29 ;; in an org-mode buffer then switch to the buffer to see the LaTeX
30 ;; export. See contrib/lisp/org-export.el for more details on how
31 ;; this exporter works.
33 ;; It introduces three new buffer keywords: "LATEX_CLASS",
34 ;; "LATEX_CLASS_OPTIONS" and "LATEX_HEADER".
36 ;;; Code:
38 (eval-when-compile (require 'cl))
40 (defvar org-export-latex-default-packages-alist)
41 (defvar org-export-latex-packages-alist)
43 (declare-function org-element-property "org-element" (property element))
44 (declare-function org-element-normalize-string "org-element" (s))
45 (declare-function org-element-parse-secondary-string
46 "org-element" (string restriction &optional buffer))
47 (defvar org-element-string-restrictions)
48 (defvar org-element-object-restrictions)
50 (declare-function org-export-clean-table "org-export" (table specialp))
51 (declare-function org-export-data "org-export" (data backend info))
52 (declare-function org-export-directory "org-export" (type plist))
53 (declare-function org-export-expand-macro "org-export" (macro info))
54 (declare-function org-export-first-sibling-p "org-export" (headline info))
55 (declare-function org-export-footnote-first-reference-p "org-export"
56 (footnote-reference info))
57 (declare-function org-export-get-coderef-format "org-export" (path desc))
58 (declare-function org-export-get-footnote-definition "org-export"
59 (footnote-reference info))
60 (declare-function org-export-get-footnote-number "org-export" (footnote info))
61 (declare-function org-export-get-previous-element "org-export" (blob info))
62 (declare-function org-export-get-relative-level "org-export" (headline info))
63 (declare-function org-export-handle-code
64 "org-export" (element info &optional num-fmt ref-fmt delayed))
65 (declare-function org-export-included-file "org-export" (keyword backend info))
66 (declare-function org-export-inline-image-p "org-export"
67 (link &optional extensions))
68 (declare-function org-export-last-sibling-p "org-export" (headline info))
69 (declare-function org-export-low-level-p "org-export" (headline info))
70 (declare-function org-export-output-file-name
71 "org-export" (extension &optional subtreep pub-dir))
72 (declare-function org-export-resolve-coderef "org-export" (ref info))
73 (declare-function org-export-resolve-fuzzy-link "org-export" (link info))
74 (declare-function org-export-secondary-string "org-export"
75 (secondary backend info))
76 (declare-function org-export-solidify-link-text "org-export" (s))
77 (declare-function org-export-table-format-info "org-export" (table))
78 (declare-function
79 org-export-to-buffer "org-export"
80 (backend buffer &optional subtreep visible-only body-only ext-plist))
81 (declare-function
82 org-export-to-file "org-export"
83 (backend file &optional subtreep visible-only body-only ext-plist))
87 ;;; Internal Variables
89 (defconst org-e-latex-option-alist
90 '((:date "DATE" nil org-e-latex-date-format t)
91 (:latex-class "LATEX_CLASS" nil org-e-latex-default-class t)
92 (:latex-class-options "LATEX_CLASS_OPTIONS" nil nil t)
93 (:latex-header-extra "LATEX_HEADER" nil nil newline))
94 "Alist between LaTeX export properties and ways to set them.
95 See `org-export-option-alist' for more information on the
96 structure of the value.")
100 ;;; User Configurable Variables
102 (defgroup org-export-e-latex nil
103 "Options for exporting Org mode files to LaTeX."
104 :tag "Org Export LaTeX"
105 :group 'org-export)
108 ;;;; Preamble
110 (defcustom org-e-latex-default-class "article"
111 "The default LaTeX class."
112 :group 'org-export-e-latex
113 :type '(string :tag "LaTeX class"))
115 (defcustom org-e-latex-classes
116 '(("article"
117 "\\documentclass[11pt]{article}"
118 ("\\section{%s}" . "\\section*{%s}")
119 ("\\subsection{%s}" . "\\subsection*{%s}")
120 ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
121 ("\\paragraph{%s}" . "\\paragraph*{%s}")
122 ("\\subparagraph{%s}" . "\\subparagraph*{%s}"))
123 ("report"
124 "\\documentclass[11pt]{report}"
125 ("\\part{%s}" . "\\part*{%s}")
126 ("\\chapter{%s}" . "\\chapter*{%s}")
127 ("\\section{%s}" . "\\section*{%s}")
128 ("\\subsection{%s}" . "\\subsection*{%s}")
129 ("\\subsubsection{%s}" . "\\subsubsection*{%s}"))
130 ("book"
131 "\\documentclass[11pt]{book}"
132 ("\\part{%s}" . "\\part*{%s}")
133 ("\\chapter{%s}" . "\\chapter*{%s}")
134 ("\\section{%s}" . "\\section*{%s}")
135 ("\\subsection{%s}" . "\\subsection*{%s}")
136 ("\\subsubsection{%s}" . "\\subsubsection*{%s}")))
137 "Alist of LaTeX classes and associated header and structure.
138 If #+LaTeX_CLASS is set in the buffer, use its value and the
139 associated information. Here is the structure of each cell:
141 \(class-name
142 header-string
143 \(numbered-section . unnumbered-section\)
144 ...\)
146 The header string
147 -----------------
149 The HEADER-STRING is the header that will be inserted into the
150 LaTeX file. It should contain the \\documentclass macro, and
151 anything else that is needed for this setup. To this header, the
152 following commands will be added:
154 - Calls to \\usepackage for all packages mentioned in the
155 variables `org-export-latex-default-packages-alist' and
156 `org-export-latex-packages-alist'. Thus, your header
157 definitions should avoid to also request these packages.
159 - Lines specified via \"#+LaTeX_HEADER:\"
161 If you need more control about the sequence in which the header
162 is built up, or if you want to exclude one of these building
163 blocks for a particular class, you can use the following
164 macro-like placeholders.
166 [DEFAULT-PACKAGES] \\usepackage statements for default packages
167 [NO-DEFAULT-PACKAGES] do not include any of the default packages
168 [PACKAGES] \\usepackage statements for packages
169 [NO-PACKAGES] do not include the packages
170 [EXTRA] the stuff from #+LaTeX_HEADER
171 [NO-EXTRA] do not include #+LaTeX_HEADER stuff
172 [BEAMER-HEADER-EXTRA] the beamer extra headers
174 So a header like
176 \\documentclass{article}
177 [NO-DEFAULT-PACKAGES]
178 [EXTRA]
179 \\providecommand{\\alert}[1]{\\textbf{#1}}
180 [PACKAGES]
182 will omit the default packages, and will include the
183 #+LaTeX_HEADER lines, then have a call to \\providecommand, and
184 then place \\usepackage commands based on the content of
185 `org-export-latex-packages-alist'.
187 If your header, `org-export-latex-default-packages-alist' or
188 `org-export-latex-packages-alist' inserts
189 \"\\usepackage[AUTO]{inputenc}\", AUTO will automatically be
190 replaced with a coding system derived from
191 `buffer-file-coding-system'. See also the variable
192 `org-e-latex-inputenc-alist' for a way to influence this
193 mechanism.
195 The sectioning structure
196 ------------------------
198 The sectioning structure of the class is given by the elements
199 following the header string. For each sectioning level, a number
200 of strings is specified. A %s formatter is mandatory in each
201 section string and will be replaced by the title of the section.
203 Instead of a cons cell \(numbered . unnumbered\), you can also
204 provide a list of 2 or 4 elements,
206 \(numbered-open numbered-close\)
210 \(numbered-open numbered-close unnumbered-open unnumbered-close\)
212 providing opening and closing strings for a LaTeX environment
213 that should represent the document section. The opening clause
214 should have a %s to represent the section title.
216 Instead of a list of sectioning commands, you can also specify
217 a function name. That function will be called with two
218 parameters, the \(reduced) level of the headline, and a predicate
219 non-nil when the headline should be numbered. It must return
220 a format string in which the section title will be added."
221 :group 'org-export-e-latex
222 :type '(repeat
223 (list (string :tag "LaTeX class")
224 (string :tag "LaTeX header")
225 (repeat :tag "Levels" :inline t
226 (choice
227 (cons :tag "Heading"
228 (string :tag " numbered")
229 (string :tag "unnumbered"))
230 (list :tag "Environment"
231 (string :tag "Opening (numbered)")
232 (string :tag "Closing (numbered)")
233 (string :tag "Opening (unnumbered)")
234 (string :tag "Closing (unnumbered)"))
235 (function :tag "Hook computing sectioning"))))))
237 (defcustom org-e-latex-inputenc-alist nil
238 "Alist of inputenc coding system names, and what should really be used.
239 For example, adding an entry
241 (\"utf8\" . \"utf8x\")
243 will cause \\usepackage[utf8x]{inputenc} to be used for buffers that
244 are written as utf8 files."
245 :group 'org-export-e-latex
246 :type '(repeat
247 (cons
248 (string :tag "Derived from buffer")
249 (string :tag "Use this instead"))))
251 (defcustom org-e-latex-date-format
252 "\\today"
253 "Format string for \\date{...}."
254 :group 'org-export-e-latex
255 :type 'boolean)
257 (defcustom org-e-latex-title-command "\\maketitle"
258 "The command used to insert the title just after \\begin{document}.
259 If this string contains the formatting specification \"%s\" then
260 it will be used as a formatting string, passing the title as an
261 argument."
262 :group 'org-export-e-latex
263 :type 'string)
266 ;;;; Headline
268 (defcustom org-e-latex-format-headline-function nil
269 "Function to format headline text.
271 This function will be called with 5 arguments:
272 TODO the todo keyword \(string or nil\).
273 TODO-TYPE the type of todo \(symbol: `todo', `done', nil\)
274 PRIORITY the priority of the headline \(integer or nil\)
275 TEXT the main headline text \(string\).
276 TAGS the tags string, separated with colons \(string or nil\).
278 The function result will be used in the section format string.
280 As an example, one could set the variable to the following, in
281 order to reproduce the default set-up:
283 \(defun org-e-latex-format-headline \(todo todo-type priority text tags\)
284 \"Default format function for an headline.\"
285 \(concat \(when todo
286 \(format \"\\\\textbf{\\\\textsc{\\\\textsf{%s}}} \" todo\)\)
287 \(when priority
288 \(format \"\\\\framebox{\\\\#%c} \" priority\)\)
289 text
290 \(when tags \(format \"\\\\hfill{}\\\\textsc{%s}\" tags\)\)\)\)"
291 :group 'org-export-e-latex
292 :type 'function)
295 ;;;; Emphasis
297 (defcustom org-e-latex-emphasis-alist
298 '(("*" . "\\textbf{%s}")
299 ("/" . "\\emph{%s}")
300 ("_" . "\\underline{%s}")
301 ("+" . "\\st{%s}")
302 ("=" . protectedtexttt)
303 ("~" . verb))
304 "Alist of LaTeX expressions to convert emphasis fontifiers.
306 The key is the character used as a marker for fontification. The
307 value is a formatting string to wrap fontified text with.
309 Value can also be set to the following symbols: `verb' and
310 `protectedtexttt'. For the former, Org will use \"\\verb\" to
311 create a format string and select a delimiter character that
312 isn't in the string. For the latter, Org will use \"\\texttt\"
313 to typeset and try to protect special characters."
314 :group 'org-export-e-latex
315 :type 'alist)
318 ;;;; Footnotes
320 (defcustom org-e-latex-footnote-separator "\\textsuperscript{,}\\,"
321 "Text used to separate footnotes."
322 :group 'org-export-e-latex
323 :type 'string)
326 ;;;; Time-stamps
328 (defcustom org-e-latex-active-timestamp-format "\\textit{%s}"
329 "A printf format string to be applied to active time-stamps."
330 :group 'org-export-e-latex
331 :type 'string)
333 (defcustom org-e-latex-inactive-timestamp-format "\\textit{%s}"
334 "A printf format string to be applied to inactive time-stamps."
335 :group 'org-export-e-latex
336 :type 'string)
338 (defcustom org-e-latex-diary-timestamp-format "\\textit{%s}"
339 "A printf format string to be applied to diary time-stamps."
340 :group 'org-export-e-latex
341 :type 'string)
344 ;;;; Links
346 (defcustom org-e-latex-image-default-option "width=.9\\linewidth"
347 "Default option for images."
348 :group 'org-export-e-latex
349 :type 'string)
351 (defcustom org-e-latex-default-figure-position "htb"
352 "Default position for latex figures."
353 :group 'org-export-e-latex
354 :type 'string)
356 (defcustom org-e-latex-inline-image-rules
357 '(("file" . "\\.\\(pdf\\|jpeg\\|jpg\\|png\\|ps\\|eps\\)\\'"))
358 "Rules characterizing image files that can be inlined into LaTeX.
360 A rule consists in an association whose key is the type of link
361 to consider, and value is a regexp that will be matched against
362 link's path.
364 Note that, by default, the image extension *actually* allowed
365 depend on the way the LaTeX file is processed. When used with
366 pdflatex, pdf, jpg and png images are OK. When processing
367 through dvi to Postscript, only ps and eps are allowed. The
368 default we use here encompasses both."
369 :group 'org-export-e-latex
370 :type '(alist :key-type (string :tag "Type")
371 :value-type (regexp :tag "Path")))
374 ;;;; Tables
376 (defcustom org-e-latex-default-table-environment "tabular"
377 "Default environment used to build tables."
378 :group 'org-export-e-latex
379 :type 'string)
381 (defcustom org-e-latex-tables-centered t
382 "When non-nil, tables are exported in a center environment."
383 :group 'org-export-e-latex
384 :type 'boolean)
386 (defcustom org-e-latex-tables-verbatim nil
387 "When non-nil, tables are exported verbatim."
388 :group 'org-export-e-latex
389 :type 'boolean)
391 (defcustom org-e-latex-tables-booktabs nil
392 "When non-nil, display tables in a formal \"booktabs\" style.
393 This option assumes that the \"booktabs\" package is properly
394 loaded in the header of the document. This value can be ignored
395 locally with \"booktabs=yes\" and \"booktabs=no\" LaTeX
396 attributes."
397 :group 'org-export-e-latex
398 :type 'boolean)
400 (defcustom org-e-latex-table-caption-above t
401 "When non-nil, place caption string at the beginning of the table.
402 Otherwise, place it near the end."
403 :group 'org-export-e-latex
404 :type 'boolean)
407 ;;;; Drawers
409 (defcustom org-e-latex-format-drawer-function nil
410 "Function called to format a drawer in LaTeX code.
412 The function must accept two parameters:
413 NAME the drawer name, like \"LOGBOOK\"
414 CONTENTS the contents of the drawer.
416 The function should return the string to be exported.
418 For example, the variable could be set to the following function
419 in order to mimic default behaviour:
421 \(defun org-e-latex-format-drawer-default \(name contents\)
422 \"Format a drawer element for LaTeX export.\"
423 contents\)"
424 :group 'org-export-e-latex
425 :type 'function)
428 ;;;; Inlinetasks
430 (defcustom org-e-latex-format-inlinetask-function nil
431 "Function called to format an inlinetask in LaTeX code.
433 The function must accept six parameters:
434 TODO the todo keyword, as a string
435 TODO-TYPE the todo type, a symbol among `todo', `done' and nil.
436 PRIORITY the inlinetask priority, as a string
437 NAME the inlinetask name, as a string.
438 TAGS the inlinetask tags, as a string.
439 CONTENTS the contents of the inlinetask, as a string.
441 The function should return the string to be exported.
443 For example, the variable could be set to the following function
444 in order to mimic default behaviour:
446 \(defun org-e-latex-format-inlinetask \(todo type priority name tags contents\)
447 \"Format an inline task element for LaTeX export.\"
448 \(let \(\(full-title
449 \(concat
450 \(when todo
451 \(format \"\\\\textbf{\\\\textsf{\\\\textsc{%s}}} \" todo\)\)
452 \(when priority \(format \"\\\\framebox{\\\\#%c} \" priority\)\)
453 title
454 \(when tags \(format \"\\\\hfill{}\\\\textsc{%s}\" tags\)\)\)\)\)
455 \(format \(concat \"\\\\begin{center}\\n\"
456 \"\\\\fbox{\\n\"
457 \"\\\\begin{minipage}[c]{.6\\\\textwidth}\\n\"
458 \"%s\\n\\n\"
459 \"\\\\rule[.8em]{\\\\textwidth}{2pt}\\n\\n\"
460 \"%s\"
461 \"\\\\end{minipage}}\"
462 \"\\\\end{center}\"\)
463 full-title contents\)\)"
464 :group 'org-export-e-latex
465 :type 'function)
468 ;; Src blocks
470 (defcustom org-e-latex-listings nil
471 "Non-nil means export source code using the listings package.
472 This package will fontify source code, possibly even with color.
473 If you want to use this, you also need to make LaTeX use the
474 listings package, and if you want to have color, the color
475 package. Just add these to `org-export-latex-packages-alist',
476 for example using customize, or with something like:
478 \(require 'org-e-latex)
479 \(add-to-list 'org-export-latex-packages-alist '\(\"\" \"listings\"))
480 \(add-to-list 'org-export-latex-packages-alist '\(\"\" \"color\"))
482 Alternatively,
484 \(setq org-e-latex-listings 'minted)
486 causes source code to be exported using the minted package as
487 opposed to listings. If you want to use minted, you need to add
488 the minted package to `org-export-latex-packages-alist', for
489 example using customize, or with
491 \(require 'org-e-latex)
492 \(add-to-list 'org-export-latex-packages-alist '\(\"\" \"minted\"))
494 In addition, it is necessary to install pygments
495 \(http://pygments.org), and to configure the variable
496 `org-e-latex-pdf-process' so that the -shell-escape option is
497 passed to pdflatex."
498 :group 'org-export-e-latex
499 :type '(choice
500 (const :tag "Use listings" t)
501 (const :tag "Use minted" 'minted)
502 (const :tag "Export verbatim" nil)))
504 (defcustom org-e-latex-listings-langs
505 '((emacs-lisp "Lisp") (lisp "Lisp") (clojure "Lisp")
506 (c "C") (cc "C++")
507 (fortran "fortran")
508 (perl "Perl") (cperl "Perl") (python "Python") (ruby "Ruby")
509 (html "HTML") (xml "XML")
510 (tex "TeX") (latex "TeX")
511 (shell-script "bash")
512 (gnuplot "Gnuplot")
513 (ocaml "Caml") (caml "Caml")
514 (sql "SQL") (sqlite "sql"))
515 "Alist mapping languages to their listing language counterpart.
516 The key is a symbol, the major mode symbol without the \"-mode\".
517 The value is the string that should be inserted as the language
518 parameter for the listings package. If the mode name and the
519 listings name are the same, the language does not need an entry
520 in this list - but it does not hurt if it is present."
521 :group 'org-export-e-latex
522 :type '(repeat
523 (list
524 (symbol :tag "Major mode ")
525 (string :tag "Listings language"))))
527 (defcustom org-e-latex-listings-options nil
528 "Association list of options for the latex listings package.
530 These options are supplied as a comma-separated list to the
531 \\lstset command. Each element of the association list should be
532 a list containing two strings: the name of the option, and the
533 value. For example,
535 (setq org-e-latex-listings-options
536 '((\"basicstyle\" \"\\small\")
537 (\"keywordstyle\" \"\\color{black}\\bfseries\\underbar\")))
539 will typeset the code in a small size font with underlined, bold
540 black keywords.
542 Note that the same options will be applied to blocks of all
543 languages."
544 :group 'org-export-e-latex
545 :type '(repeat
546 (list
547 (string :tag "Listings option name ")
548 (string :tag "Listings option value"))))
550 (defcustom org-e-latex-minted-langs
551 '((emacs-lisp "common-lisp")
552 (cc "c++")
553 (cperl "perl")
554 (shell-script "bash")
555 (caml "ocaml"))
556 "Alist mapping languages to their minted language counterpart.
557 The key is a symbol, the major mode symbol without the \"-mode\".
558 The value is the string that should be inserted as the language
559 parameter for the minted package. If the mode name and the
560 listings name are the same, the language does not need an entry
561 in this list - but it does not hurt if it is present.
563 Note that minted uses all lower case for language identifiers,
564 and that the full list of language identifiers can be obtained
565 with:
567 pygmentize -L lexers"
568 :group 'org-export-e-latex
569 :type '(repeat
570 (list
571 (symbol :tag "Major mode ")
572 (string :tag "Minted language"))))
574 (defcustom org-e-latex-minted-options nil
575 "Association list of options for the latex minted package.
577 These options are supplied within square brackets in
578 \\begin{minted} environments. Each element of the alist should
579 be a list containing two strings: the name of the option, and the
580 value. For example,
582 \(setq org-e-latex-minted-options
583 '\((\"bgcolor\" \"bg\") \(\"frame\" \"lines\")))
585 will result in src blocks being exported with
587 \\begin{minted}[bgcolor=bg,frame=lines]{<LANG>}
589 as the start of the minted environment. Note that the same
590 options will be applied to blocks of all languages."
591 :group 'org-export-e-latex
592 :type '(repeat
593 (list
594 (string :tag "Minted option name ")
595 (string :tag "Minted option value"))))
597 (defvar org-e-latex-custom-lang-environments nil
598 "Alist mapping languages to language-specific LaTeX environments.
600 It is used during export of src blocks by the listings and minted
601 latex packages. For example,
603 \(setq org-e-latex-custom-lang-environments
604 '\(\(python \"pythoncode\"\)\)\)
606 would have the effect that if org encounters begin_src python
607 during latex export it will output
609 \\begin{pythoncode}
610 <src block body>
611 \\end{pythoncode}")
614 ;;;; Plain text
616 (defcustom org-e-latex-quotes
617 '(("fr" ("\\(\\s-\\|[[(]\\)\"" . "«~") ("\\(\\S-\\)\"" . "~»") ("\\(\\s-\\|(\\)'" . "'"))
618 ("en" ("\\(\\s-\\|[[(]\\)\"" . "``") ("\\(\\S-\\)\"" . "''") ("\\(\\s-\\|(\\)'" . "`")))
619 "Alist for quotes to use when converting english double-quotes.
621 The CAR of each item in this alist is the language code.
622 The CDR of each item in this alist is a list of three CONS:
623 - the first CONS defines the opening quote;
624 - the second CONS defines the closing quote;
625 - the last CONS defines single quotes.
627 For each item in a CONS, the first string is a regexp
628 for allowed characters before/after the quote, the second
629 string defines the replacement string for this quote."
630 :group 'org-export-e-latex
631 :type '(list
632 (cons :tag "Opening quote"
633 (string :tag "Regexp for char before")
634 (string :tag "Replacement quote "))
635 (cons :tag "Closing quote"
636 (string :tag "Regexp for char after ")
637 (string :tag "Replacement quote "))
638 (cons :tag "Single quote"
639 (string :tag "Regexp for char before")
640 (string :tag "Replacement quote "))))
643 ;;;; Compilation
645 (defcustom org-e-latex-pdf-process
646 '("pdflatex -interaction nonstopmode -output-directory %o %f"
647 "pdflatex -interaction nonstopmode -output-directory %o %f"
648 "pdflatex -interaction nonstopmode -output-directory %o %f")
649 "Commands to process a LaTeX file to a PDF file.
650 This is a list of strings, each of them will be given to the
651 shell as a command. %f in the command will be replaced by the
652 full file name, %b by the file base name \(i.e. without
653 extension) and %o by the base directory of the file.
655 The reason why this is a list is that it usually takes several
656 runs of `pdflatex', maybe mixed with a call to `bibtex'. Org
657 does not have a clever mechanism to detect which of these
658 commands have to be run to get to a stable result, and it also
659 does not do any error checking.
661 By default, Org uses 3 runs of `pdflatex' to do the processing.
662 If you have texi2dvi on your system and if that does not cause
663 the infamous egrep/locale bug:
665 http://lists.gnu.org/archive/html/bug-texinfo/2010-03/msg00031.html
667 then `texi2dvi' is the superior choice. Org does offer it as one
668 of the customize options.
670 Alternatively, this may be a Lisp function that does the
671 processing, so you could use this to apply the machinery of
672 AUCTeX or the Emacs LaTeX mode. This function should accept the
673 file name as its single argument."
674 :group 'org-export-pdf
675 :type '(choice
676 (repeat :tag "Shell command sequence"
677 (string :tag "Shell command"))
678 (const :tag "2 runs of pdflatex"
679 ("pdflatex -interaction nonstopmode -output-directory %o %f"
680 "pdflatex -interaction nonstopmode -output-directory %o %f"))
681 (const :tag "3 runs of pdflatex"
682 ("pdflatex -interaction nonstopmode -output-directory %o %f"
683 "pdflatex -interaction nonstopmode -output-directory %o %f"
684 "pdflatex -interaction nonstopmode -output-directory %o %f"))
685 (const :tag "pdflatex,bibtex,pdflatex,pdflatex"
686 ("pdflatex -interaction nonstopmode -output-directory %o %f"
687 "bibtex %b"
688 "pdflatex -interaction nonstopmode -output-directory %o %f"
689 "pdflatex -interaction nonstopmode -output-directory %o %f"))
690 (const :tag "texi2dvi"
691 ("texi2dvi -p -b -c -V %f"))
692 (const :tag "rubber"
693 ("rubber -d --into %o %f"))
694 (function)))
696 (defcustom org-e-latex-logfiles-extensions
697 '("aux" "idx" "log" "out" "toc" "nav" "snm" "vrb")
698 "The list of file extensions to consider as LaTeX logfiles."
699 :group 'org-export-e-latex
700 :type '(repeat (string :tag "Extension")))
702 (defcustom org-e-latex-remove-logfiles t
703 "Non-nil means remove the logfiles produced by PDF production.
704 These are the .aux, .log, .out, and .toc files."
705 :group 'org-export-e-latex
706 :type 'boolean)
710 ;;; Internal Functions
712 (defun org-e-latex--caption/label-string (caption label info)
713 "Return caption and label LaTeX string for floats.
715 CAPTION is a cons cell of secondary strings, the car being the
716 standard caption and the cdr its short form. LABEL is a string
717 representing the label. INFO is a plist holding contextual
718 information.
720 If there's no caption nor label, return the empty string.
722 For non-floats, see `org-e-latex--wrap-label'."
723 (let ((label-str (if label (format "\\label{%s}" label) "")))
724 (cond
725 ((and (not caption) (not label)) "")
726 ((not caption) (format "\\label{%s}\n" label))
727 ;; Option caption format with short name.
728 ((cdr caption)
729 (format "\\caption[%s]{%s%s}\n"
730 (org-export-secondary-string (cdr caption) 'e-latex info)
731 label-str
732 (org-export-secondary-string (car caption) 'e-latex info)))
733 ;; Standard caption format.
734 (t (format "\\caption{%s%s}\n"
735 label-str
736 (org-export-secondary-string (car caption) 'e-latex info))))))
738 (defun org-e-latex--guess-inputenc (header)
739 "Set the coding system in inputenc to what the buffer is.
741 HEADER is the LaTeX header string.
743 Return the new header."
744 (let* ((cs (or (ignore-errors
745 (latexenc-coding-system-to-inputenc
746 buffer-file-coding-system))
747 "utf8")))
748 (if (not cs) header
749 ;; First translate if that is requested.
750 (setq cs (or (cdr (assoc cs org-e-latex-inputenc-alist)) cs))
751 ;; Then find the \usepackage statement and replace the option.
752 (replace-regexp-in-string "\\\\usepackage\\[\\(AUTO\\)\\]{inputenc}"
753 cs header t nil 1))))
755 (defun org-e-latex--find-verb-separator (s)
756 "Return a character not used in string S.
757 This is used to choose a separator for constructs like \\verb."
758 (let ((ll "~,./?;':\"|!@#%^&-_=+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ<>()[]{}"))
759 (loop for c across ll
760 when (not (string-match (regexp-quote (char-to-string c)) s))
761 return (char-to-string c))))
763 (defun org-e-latex--make-option-string (options)
764 "Return a comma separated string of keywords and values.
765 OPTIONS is an alist where the key is the options keyword as
766 a string, and the value a list containing the keyword value, or
767 nil."
768 (mapconcat (lambda (pair)
769 (concat (first pair)
770 (when (> (length (second pair)) 0)
771 (concat "=" (second pair)))))
772 options
773 ","))
775 (defun org-e-latex--quotation-marks (text info)
776 "Export quotation marks depending on language conventions.
777 TEXT is a string containing quotation marks to be replaced. INFO
778 is a plist used as a communication channel."
779 (mapc (lambda(l)
780 (let ((start 0))
781 (while (setq start (string-match (car l) text start))
782 (let ((new-quote (concat (match-string 1 text) (cdr l))))
783 (setq text (replace-match new-quote t t text))))))
784 (cdr (or (assoc (plist-get info :language) org-e-latex-quotes)
785 ;; Falls back on English.
786 (assoc "en" org-e-latex-quotes))))
787 text)
789 (defun org-e-latex--wrap-label (element output)
790 "Wrap label associated to ELEMENT around OUTPUT, if appropriate.
791 This function shouldn't be used for floats. See
792 `org-e-latex--caption/label-string'."
793 (let ((label (org-element-property :name element)))
794 (if (or (not output) (not label) (string= output "") (string= label ""))
795 output
796 (concat (format "\\label{%s}\n" label) output))))
800 ;;; Template
802 (defun org-e-latex-template (contents info)
803 "Return complete document string after LaTeX conversion.
804 CONTENTS is the transcoded contents string. INFO is a plist
805 holding export options."
806 (let ((title (org-export-secondary-string
807 (plist-get info :title) 'e-latex info)))
808 (concat
809 ;; 1. Time-stamp.
810 (and (plist-get info :time-stamp-file)
811 (format-time-string "%% Created %Y-%m-%d %a %H:%M\n"))
812 ;; 2. Document class and packages.
813 (let ((class (plist-get info :latex-class))
814 (class-options (plist-get info :latex-class-options)))
815 (org-element-normalize-string
816 (let* ((header (nth 1 (assoc class org-e-latex-classes)))
817 (document-class-string
818 (and (stringp header)
819 (if class-options
820 (replace-regexp-in-string
821 "^[ \t]*\\\\documentclass\\(\\[.*?\\]\\)"
822 class-options header t nil 1)
823 header))))
824 (org-e-latex--guess-inputenc
825 (org-splice-latex-header
826 document-class-string
827 org-export-latex-default-packages-alist ; defined in org.el
828 org-export-latex-packages-alist nil ; defined in org.el
829 (plist-get info :latex-header-extra))))))
830 ;; 3. Define alert if not yet defined.
831 "\\providecommand{\\alert}[1]{\\textbf{#1}}\n"
832 ;; 4. Possibly limit depth for headline numbering.
833 (let ((sec-num (plist-get info :section-numbers)))
834 (when (integerp sec-num)
835 (format "\\setcounter{secnumdepth}{%d}\n" sec-num)))
836 ;; 5. Author.
837 (let ((author (and (plist-get info :with-author)
838 (let ((auth (plist-get info :author)))
839 (and auth (org-export-secondary-string
840 auth 'e-latex info)))))
841 (email (and (plist-get info :with-email)
842 (org-export-secondary-string
843 (plist-get info :email) 'e-latex info))))
844 (cond ((and author email (not (string= "" email)))
845 (format "\\author{%s\\thanks{%s}}\n" author email))
846 (author (format "\\author{%s}\n" author))
847 (t "\\author{}\n")))
848 ;; 6. Date.
849 (let ((date (plist-get info :date)))
850 (and date (format "\\date{%s}\n" date)))
851 ;; 7. Title
852 (format "\\title{%s}\n" title)
853 ;; 8. Hyperref options.
854 (format "\\hypersetup{\n pdfkeywords={%s},\n pdfsubject={%s},\n pdfcreator={%s}}\n"
855 (or (plist-get info :keywords) "")
856 (or (plist-get info :description) "")
857 (if (not (plist-get info :with-creator)) ""
858 (plist-get info :creator)))
859 ;; 9. Document start.
860 "\\begin{document}\n\n"
861 ;; 10. Title command.
862 (org-element-normalize-string
863 (cond ((string= "" title) nil)
864 ((not (stringp org-e-latex-title-command)) nil)
865 ((string-match "\\(?:[^%]\\|^\\)%s"
866 org-e-latex-title-command)
867 (format org-e-latex-title-command title))
868 (t org-e-latex-title-command)))
869 ;; 11. Table of contents.
870 (let ((depth (plist-get info :with-toc)))
871 (when depth
872 (concat (when (wholenump depth)
873 (format "\\setcounter{tocdepth}{%d}\n" depth))
874 "\\tableofcontents\n\\vspace*{1cm}\n\n")))
875 ;; 12. Document's body.
876 contents
877 ;; 13. Creator.
878 (let ((creator-info (plist-get info :with-creator)))
879 (cond
880 ((not creator-info) "")
881 ((eq creator-info 'comment)
882 (format "%% %s\n" (plist-get info :creator)))
883 (t (concat (plist-get info :creator) "\n"))))
884 ;; 14. Document end.
885 "\\end{document}")))
889 ;;; Transcode Functions
891 ;;;; Block
893 (defun org-e-latex-center-block (center-block contents info)
894 "Transcode a CENTER-BLOCK element from Org to LaTeX.
895 CONTENTS holds the contents of the block. INFO is a plist
896 holding contextual information."
897 (org-e-latex--wrap-label
898 center-block
899 (format "\\begin{center}\n%s\\end{center}" contents)))
902 ;;;; Comment
904 ;; Comments are ignored.
907 ;;;; Comment Block
909 ;; Comment Blocks are ignored.
912 ;;;; Drawer
914 (defun org-e-latex-drawer (drawer contents info)
915 "Transcode a DRAWER element from Org to LaTeX.
916 CONTENTS holds the contents of the block. INFO is a plist
917 holding contextual information."
918 (let* ((name (org-element-property :drawer-name drawer))
919 (output (if (functionp org-e-latex-format-drawer-function)
920 (funcall org-e-latex-format-drawer-function
921 name contents)
922 ;; If there's no user defined function: simply
923 ;; display contents of the drawer.
924 contents)))
925 (org-e-latex--wrap-label drawer output)))
928 ;;;; Dynamic Block
930 (defun org-e-latex-dynamic-block (dynamic-block contents info)
931 "Transcode a DYNAMIC-BLOCK element from Org to LaTeX.
932 CONTENTS holds the contents of the block. INFO is a plist
933 holding contextual information. See
934 `org-export-data'."
935 (org-e-latex--wrap-label dynamic-block contents))
938 ;;;; Emphasis
940 (defun org-e-latex-emphasis (emphasis contents info)
941 "Transcode EMPHASIS from Org to LaTeX.
942 CONTENTS is the contents of the emphasized text. INFO is a plist
943 holding contextual information.."
944 (format (cdr (assoc (org-element-property :marker emphasis)
945 org-e-latex-emphasis-alist))
946 contents))
949 ;;;; Entity
951 (defun org-e-latex-entity (entity contents info)
952 "Transcode an ENTITY object from Org to LaTeX.
953 CONTENTS are the definition itself. INFO is a plist holding
954 contextual information."
955 (let ((ent (org-element-property :latex entity)))
956 (if (org-element-property :latex-math-p entity) (format "$%s$" ent) ent)))
959 ;;;; Example Block
961 (defun org-e-latex-example-block (example-block contents info)
962 "Transcode a EXAMPLE-BLOCK element from Org to LaTeX.
963 CONTENTS is nil. INFO is a plist holding contextual information."
964 (let* ((options (or (org-element-property :options example-block) ""))
965 (value (org-export-handle-code example-block info)))
966 (org-e-latex--wrap-label
967 example-block (format "\\begin{verbatim}\n%s\\end{verbatim}" value))))
970 ;;;; Export Snippet
972 (defun org-e-latex-export-snippet (export-snippet contents info)
973 "Transcode a EXPORT-SNIPPET object from Org to LaTeX.
974 CONTENTS is nil. INFO is a plist holding contextual information."
975 (when (eq (org-export-snippet-backend export-snippet) 'e-latex)
976 (org-element-property :value export-snippet)))
979 ;;;; Export Block
981 (defun org-e-latex-export-block (export-block contents info)
982 "Transcode a EXPORT-BLOCK element from Org to LaTeX.
983 CONTENTS is nil. INFO is a plist holding contextual information."
984 (when (string= (org-element-property :type export-block) "latex")
985 (org-remove-indentation (org-element-property :value export-block))))
988 ;;;; Fixed Width
990 (defun org-e-latex-fixed-width (fixed-width contents info)
991 "Transcode a FIXED-WIDTH element from Org to LaTeX.
992 CONTENTS is nil. INFO is a plist holding contextual information."
993 (let* ((value (org-element-normalize-string
994 (replace-regexp-in-string
995 "^[ \t]*: ?" ""
996 (org-element-property :value fixed-width)))))
997 (org-e-latex--wrap-label
998 fixed-width (format "\\begin{verbatim}\n%s\\end{verbatim}" value))))
1001 ;;;; Footnote Definition
1003 ;; Footnote Definitions are ignored.
1006 ;;;; Footnote Reference
1008 (defun org-e-latex-footnote-reference (footnote-reference contents info)
1009 "Transcode a FOOTNOTE-REFERENCE element from Org to LaTeX.
1010 CONTENTS is nil. INFO is a plist holding contextual information."
1011 (concat
1012 ;; Insert separator between two footnotes in a row.
1013 (let ((prev (org-export-get-previous-element footnote-reference info)))
1014 (when (eq (org-element-type prev) 'footnote-reference)
1015 org-e-latex-footnote-separator))
1016 (cond
1017 ;; Use \footnotemark if the footnote has already been defined.
1018 ((not (org-export-footnote-first-reference-p footnote-reference info))
1019 (format "\\footnotemark[%s]{}"
1020 (org-export-get-footnote-number footnote-reference info)))
1021 ;; Use also \footnotemark if reference is within another footnote
1022 ;; reference or footnote definition.
1023 ((loop for parent in (org-export-get-genealogy footnote-reference info)
1024 thereis (memq (org-element-type parent)
1025 '(footnote-reference footnote-definition)))
1026 (let ((num (org-export-get-footnote-number footnote-reference info)))
1027 (format "\\footnotemark[%s]{}\\setcounter{footnote}{%s}" num num)))
1028 ;; Otherwise, define it with \footnote command.
1030 (let ((def (org-export-get-footnote-definition footnote-reference info)))
1031 (unless (eq (org-element-type def) 'org-data)
1032 (setq def (cons 'org-data (cons nil def))))
1033 (concat
1034 (format "\\footnote{%s}" (org-trim (org-export-data def 'e-latex info)))
1035 ;; Retrieve all footnote references within the footnote and
1036 ;; add their definition after it, since LaTeX doesn't support
1037 ;; them inside.
1038 (let (all-refs
1039 (search-refs
1040 (function
1041 (lambda (data)
1042 ;; Return a list of all footnote references in DATA.
1043 (org-element-map
1044 data 'footnote-reference
1045 (lambda (ref)
1046 (when (org-export-footnote-first-reference-p ref info)
1047 (push ref all-refs)
1048 (when (eq (org-element-property :type ref) 'standard)
1049 (funcall
1050 search-refs
1051 (org-export-get-footnote-definition ref info)))))
1052 info) (reverse all-refs)))))
1053 (mapconcat
1054 (lambda (ref)
1055 (format
1056 "\\footnotetext[%s]{%s}"
1057 (org-export-get-footnote-number ref info)
1058 (org-trim
1059 (funcall
1060 (if (eq (org-element-property :type ref) 'inline)
1061 'org-export-secondary-string
1062 'org-export-data)
1063 (org-export-get-footnote-definition ref info) 'e-latex info))))
1064 (funcall search-refs def) ""))))))))
1067 ;;;; Headline
1069 (defun org-e-latex-headline (headline contents info)
1070 "Transcode an HEADLINE element from Org to LaTeX.
1071 CONTENTS holds the contents of the headline. INFO is a plist
1072 holding contextual information."
1073 (let* ((class (plist-get info :latex-class))
1074 (level (org-export-get-relative-level headline info))
1075 (numberedp (org-export-numbered-headline-p headline info))
1076 (class-sectionning (assoc class org-e-latex-classes))
1077 ;; Section formatting will set two placeholders: one for the
1078 ;; title and the other for the contents.
1079 (section-fmt
1080 (let ((sec (if (and (symbolp (nth 2 class-sectionning))
1081 (fboundp (nth 2 class-sectionning)))
1082 (funcall (nth 2 class-sectionning) level numberedp)
1083 (nth (1+ level) class-sectionning))))
1084 (cond
1085 ;; No section available for that LEVEL.
1086 ((not sec) nil)
1087 ;; Section format directly returned by a function.
1088 ((stringp sec) sec)
1089 ;; (numbered-section . unnumbered-section)
1090 ((not (consp (cdr sec)))
1091 (concat (funcall (if numberedp #'car #'cdr) sec) "\n%s"))
1092 ;; (numbered-open numbered-close)
1093 ((= (length sec) 2)
1094 (when numberedp (concat (car sec) "\n%s" (nth 1 sec))))
1095 ;; (num-in num-out no-num-in no-num-out)
1096 ((= (length sec) 4)
1097 (if numberedp (concat (car sec) "\n%s" (nth 1 sec))
1098 (concat (nth 2 sec) "\n%s" (nth 3 sec)))))))
1099 (text (org-export-secondary-string
1100 (org-element-property :title headline) 'e-latex info))
1101 (todo
1102 (and (plist-get info :with-todo-keywords)
1103 (let ((todo (org-element-property :todo-keyword headline)))
1104 (and todo (org-export-secondary-string todo 'e-latex info)))))
1105 (todo-type (and todo (org-element-property :todo-type headline)))
1106 (tags (and (plist-get info :with-tags)
1107 (org-element-property :tags headline)))
1108 (priority (and (plist-get info :with-priority)
1109 (org-element-property :priority headline)))
1110 ;; Create the headline text.
1111 (full-text (if (functionp org-e-latex-format-headline-function)
1112 ;; User-defined formatting function.
1113 (funcall org-e-latex-format-headline-function
1114 todo todo-type priority text tags)
1115 ;; Default formatting.
1116 (concat
1117 (when todo
1118 (format "\\textbf{\\textsf{\\textsc{%s}}} " todo))
1119 (when priority (format "\\framebox{\\#%c} " priority))
1120 text
1121 (when tags (format "\\hfill{}\\textsc{%s}" tags)))))
1122 ;; Associate some \label to the headline for internal links.
1123 (headline-label
1124 (format "\\label{sec-%s}\n"
1125 (mapconcat 'number-to-string
1126 (org-export-get-headline-number headline info)
1127 "-")))
1128 (pre-blanks
1129 (make-string (org-element-property :pre-blank headline) 10)))
1130 (cond
1131 ;; Case 1: This is a footnote section: ignore it.
1132 ((org-element-property :footnote-section-p headline) nil)
1133 ;; Case 2. This is a deep sub-tree: export it as a list item.
1134 ;; Also export as items headlines for which no section
1135 ;; format has been found.
1136 ((or (not section-fmt) (org-export-low-level-p headline info))
1137 ;; Build the real contents of the sub-tree.
1138 (let ((low-level-body
1139 (concat
1140 ;; If the headline is the first sibling, start a list.
1141 (when (org-export-first-sibling-p headline info)
1142 (format "\\begin{%s}\n" (if numberedp 'enumerate 'itemize)))
1143 ;; Itemize headline
1144 "\\item " full-text "\n" headline-label pre-blanks contents)))
1145 ;; If headline is not the last sibling simply return
1146 ;; LOW-LEVEL-BODY. Otherwise, also close the list, before any
1147 ;; blank line.
1148 (if (not (org-export-last-sibling-p headline info)) low-level-body
1149 (replace-regexp-in-string
1150 "[ \t\n]*\\'"
1151 (format "\n\\\\end{%s}" (if numberedp 'enumerate 'itemize))
1152 low-level-body))))
1153 ;; Case 3. Standard headline. Export it as a section.
1154 (t (format section-fmt full-text
1155 (concat headline-label pre-blanks contents))))))
1158 ;;;; Horizontal Rule
1160 (defun org-e-latex-horizontal-rule (horizontal-rule contents info)
1161 "Transcode an HORIZONTAL-RULE object from Org to LaTeX.
1162 CONTENTS is nil. INFO is a plist holding contextual information."
1163 (let ((attr (mapconcat #'identity
1164 (org-element-property :attr_latex horizontal-rule)
1165 " ")))
1166 (org-e-latex--wrap-label horizontal-rule (concat "\\hrule " attr))))
1169 ;;;; Inline Babel Call
1171 ;; Inline Babel Calls are ignored.
1174 ;;;; Inline Src Block
1176 (defun org-e-latex-inline-src-block (inline-src-block contents info)
1177 "Transcode an INLINE-SRC-BLOCK element from Org to LaTeX.
1178 CONTENTS holds the contents of the item. INFO is a plist holding
1179 contextual information."
1180 (let* ((code (org-element-property :value inline-src-block))
1181 (separator (org-e-latex--find-verb-separator code)))
1182 (cond
1183 ;; Do not use a special package: transcode it verbatim.
1184 ((not org-e-latex-listings)
1185 (concat "\\verb" separator code separator))
1186 ;; Use minted package.
1187 ((eq org-e-latex-listings 'minted)
1188 (let* ((org-lang (org-element-property :language inline-src-block))
1189 (mint-lang (or (cadr (assq (intern org-lang)
1190 org-e-latex-minted-langs))
1191 org-lang))
1192 (options (org-e-latex--make-option-string
1193 org-e-latex-minted-options)))
1194 (concat (format "\\mint%s{%s}"
1195 (if (string= options "") "" (format "[%s]" options))
1196 mint-lang)
1197 separator code separator)))
1198 ;; Use listings package.
1200 ;; Maybe translate language's name.
1201 (let* ((org-lang (org-element-property :language inline-src-block))
1202 (lst-lang (or (cadr (assq (intern org-lang)
1203 org-e-latex-listings-langs))
1204 org-lang))
1205 (options (org-e-latex--make-option-string
1206 (append org-e-latex-listings-options
1207 `(("language" ,lst-lang))))))
1208 (concat (format "\\lstinline[%s]" options)
1209 separator code separator))))))
1212 ;;;; Inlinetask
1214 (defun org-e-latex-inlinetask (inlinetask contents info)
1215 "Transcode an INLINETASK element from Org to LaTeX.
1216 CONTENTS holds the contents of the block. INFO is a plist
1217 holding contextual information."
1218 (let ((title (org-export-secondary-string
1219 (org-element-property :title inlinetask) 'e-latex info))
1220 (todo (and (plist-get info :with-todo-keywords)
1221 (let ((todo (org-element-property
1222 :todo-keyword inlinetask)))
1223 (and todo
1224 (org-export-secondary-string todo 'e-latex info)))))
1225 (todo-type (org-element-property :todo-type inlinetask))
1226 (tags (and (plist-get info :with-tags)
1227 (org-element-property :tags inlinetask)))
1228 (priority (and (plist-get info :with-priority)
1229 (org-element-property :priority inlinetask))))
1230 ;; If `org-e-latex-format-inlinetask-function' is provided, call it
1231 ;; with appropriate arguments.
1232 (if (functionp org-e-latex-format-inlinetask-function)
1233 (funcall org-e-latex-format-inlinetask-function
1234 todo todo-type priority title tags contents)
1235 ;; Otherwise, use a default template.
1236 (org-e-latex--wrap-label
1237 inlinetask
1238 (let ((full-title
1239 (concat
1240 (when todo (format "\\textbf{\\textsf{\\textsc{%s}}} " todo))
1241 (when priority (format "\\framebox{\\#%c} " priority))
1242 title
1243 (when tags (format "\\hfill{}\\textsc{%s}" tags)))))
1244 (format (concat "\\begin{center}\n"
1245 "\\fbox{\n"
1246 "\\begin{minipage}[c]{.6\\textwidth}\n"
1247 "%s\n\n"
1248 "\\rule[.8em]{\\textwidth}{2pt}\n\n"
1249 "%s"
1250 "\\end{minipage}\n"
1251 "}\n"
1252 "\\end{center}")
1253 full-title contents))))))
1256 ;;;; Item
1258 (defun org-e-latex-item (item contents info)
1259 "Transcode an ITEM element from Org to LaTeX.
1260 CONTENTS holds the contents of the item. INFO is a plist holding
1261 contextual information."
1262 ;; Grab `:level' from plain-list properties, which is always the
1263 ;; first element above current item.
1264 (let* ((level (org-element-property :level (org-export-get-parent item info)))
1265 (counter (let ((count (org-element-property :counter item)))
1266 (and count
1267 (< level 4)
1268 (format "\\setcounter{enum%s}{%s}\n"
1269 (nth level '("i" "ii" "iii" "iv"))
1270 (1- count)))))
1271 (checkbox (let ((checkbox (org-element-property :checkbox item)))
1272 (cond ((eq checkbox 'on) "$\\boxtimes$ ")
1273 ((eq checkbox 'off) "$\\Box$ ")
1274 ((eq checkbox 'trans) "$\\boxminus$ "))))
1275 (tag (let ((tag (org-element-property :tag item)))
1276 (and tag
1277 (format "[%s]" (org-export-secondary-string
1278 tag 'e-latex info))))))
1279 (concat counter "\\item" tag " " checkbox contents)))
1282 ;;;; Keyword
1284 (defun org-e-latex-keyword (keyword contents info)
1285 "Transcode a KEYWORD element from Org to LaTeX.
1286 CONTENTS is nil. INFO is a plist holding contextual information."
1287 (let ((key (downcase (org-element-property :key keyword)))
1288 (value (org-element-property :value keyword)))
1289 (cond
1290 ((string= key "latex") value)
1291 ((string= key "index") (format "\\index{%s}" value))
1292 ;; Invisible targets.
1293 ((string= key "target") nil)
1294 ((string= key "toc")
1295 (let ((value (downcase value)))
1296 (cond
1297 ((string-match "\\<headlines\\>" value)
1298 (let ((depth (or (and (string-match "[0-9]+" value)
1299 (string-to-number (match-string 0 value)))
1300 (plist-get info :with-toc))))
1301 (concat
1302 (when (wholenump depth)
1303 (format "\\setcounter{tocdepth}{%s}\n" depth))
1304 "\\tableofcontents")))
1305 ((string= "tables" value) "\\listoftables")
1306 ((string= "figures" value) "\\listoffigures")
1307 ((string= "listings" value)
1308 (cond
1309 ((eq org-e-latex-listings 'minted) "\\listoflistings")
1310 (org-e-latex-listings "\\lstlistoflistings")
1311 ;; At the moment, src blocks with a caption are wrapped
1312 ;; into a figure environment.
1313 (t "\\listoffigures")))))))))
1316 ;;;; Latex Environment
1318 (defun org-e-latex-latex-environment (latex-environment contents info)
1319 "Transcode a LATEX-ENVIRONMENT element from Org to LaTeX.
1320 CONTENTS is nil. INFO is a plist holding contextual information."
1321 (let ((label (org-element-property :name latex-environment))
1322 (value (org-remove-indentation
1323 (org-element-property :value latex-environment))))
1324 (if (not (org-string-nw-p label)) value
1325 ;; Environment is labelled: label must be within the environment
1326 ;; (otherwise, a reference pointing to that element will count
1327 ;; the section instead).
1328 (with-temp-buffer
1329 (insert value)
1330 (goto-char (point-min))
1331 (forward-line)
1332 (insert (format "\\label{%s}\n" label))
1333 (buffer-string)))))
1336 ;;;; Latex Fragment
1338 (defun org-e-latex-latex-fragment (latex-fragment contents info)
1339 "Transcode a LATEX-FRAGMENT object from Org to LaTeX.
1340 CONTENTS is nil. INFO is a plist holding contextual information."
1341 (org-element-property :value latex-fragment))
1344 ;;;; Line Break
1346 (defun org-e-latex-line-break (line-break contents info)
1347 "Transcode a LINE-BREAK object from Org to LaTeX.
1348 CONTENTS is nil. INFO is a plist holding contextual information."
1349 "\\\\")
1352 ;;;; Link
1354 (defun org-e-latex-link--inline-image (link info)
1355 "Return LaTeX code for an inline image.
1356 LINK is the link pointing to the inline image. INFO is a plist
1357 used as a communication channel."
1358 (let* ((parent (org-export-get-parent-paragraph link info))
1359 (path (let ((raw-path (org-element-property :path link)))
1360 (if (not (file-name-absolute-p raw-path)) raw-path
1361 (expand-file-name raw-path))))
1362 (caption (org-e-latex--caption/label-string
1363 (org-element-property :caption parent)
1364 (org-element-property :name parent)
1365 info))
1366 ;; Retrieve latex attributes from the element around.
1367 (attr (let ((raw-attr
1368 (mapconcat #'identity
1369 (org-element-property :attr_latex parent)
1370 " ")))
1371 (unless (string= raw-attr "") raw-attr)))
1372 (disposition
1373 (cond
1374 ((and attr (string-match "\\<wrap\\>" attr)) 'wrap)
1375 ((and attr (string-match "\\<multicolumn\\>" attr)) 'multicolumn)
1376 ((or (and attr (string-match "\\<float\\>" attr))
1377 (not (string= caption "")))
1378 'float)))
1379 (placement
1380 (cond
1381 ((and attr (string-match "\\<placement=\\(\\S-+\\)" attr))
1382 (org-match-string-no-properties 1 attr))
1383 ((eq disposition 'wrap) "{l}{0.5\\textwidth}")
1384 ((eq disposition 'float)
1385 (concat "[" org-e-latex-default-figure-position "]"))
1386 (t ""))))
1387 ;; Now clear ATTR from any special keyword and set a default
1388 ;; value if nothing is left.
1389 (setq attr
1390 (if (not attr) ""
1391 (org-trim
1392 (replace-regexp-in-string
1393 "\\(wrap\\|multicolumn\\|float\\|placement=\\S-+\\)" "" attr))))
1394 (setq attr (cond ((not (string= attr "")) attr)
1395 ((eq disposition 'float) "width=0.7\\textwidth")
1396 ((eq disposition 'wrap) "width=0.48\\textwidth")
1397 (t (or org-e-latex-image-default-option ""))))
1398 ;; Return proper string, depending on DISPOSITION.
1399 (case disposition
1400 (wrap (format "\\begin{wrapfigure}%s
1401 \\centering
1402 \\includegraphics[%s]{%s}
1403 %s\\end{wrapfigure}" placement attr path caption))
1404 (mulicolumn (format "\\begin{figure*}%s
1405 \\centering
1406 \\includegraphics[%s]{%s}
1407 %s\\end{figure*}" placement attr path caption))
1408 (float (format "\\begin{figure}%s
1409 \\centering
1410 \\includegraphics[%s]{%s}
1411 %s\\end{figure}" placement attr path caption))
1412 (t (format "\\includegraphics[%s]{%s}" attr path)))))
1414 (defun org-e-latex-link (link desc info)
1415 "Transcode a LINK object from Org to LaTeX.
1417 DESC is the description part of the link, or the empty string.
1418 INFO is a plist holding contextual information. See
1419 `org-export-data'."
1420 (let* ((type (org-element-property :type link))
1421 (raw-path (org-element-property :path link))
1422 ;; Ensure DESC really exists, or set it to nil.
1423 (desc (and (not (string= desc "")) desc))
1424 (imagep (org-export-inline-image-p
1425 link org-e-latex-inline-image-rules))
1426 (path (cond
1427 ((member type '("http" "https" "ftp" "mailto"))
1428 (concat type ":" raw-path))
1429 ((string= type "file")
1430 (when (string-match "\\(.+\\)::.+" raw-path)
1431 (setq raw-path (match-string 1 raw-path)))
1432 (if (file-name-absolute-p raw-path)
1433 (concat "file://" (expand-file-name raw-path))
1434 ;; TODO: Not implemented yet. Concat also:
1435 ;; (org-export-directory :LaTeX info)
1436 (concat "file://" raw-path)))
1437 (t raw-path)))
1438 protocol)
1439 (cond
1440 ;; Image file.
1441 (imagep (org-e-latex-link--inline-image link info))
1442 ;; Radioed target: Target's name is obtained from original raw
1443 ;; link. Path is parsed and transcoded in order to have a proper
1444 ;; display of the contents.
1445 ((string= type "radio")
1446 (format "\\hyperref[%s]{%s}"
1447 (org-export-solidify-link-text path)
1448 (org-export-secondary-string
1449 (org-element-parse-secondary-string
1450 path (cdr (assq 'radio-target org-element-object-restrictions)))
1451 'e-latex info)))
1452 ;; Links pointing to an headline: Find destination and build
1453 ;; appropriate referencing command.
1454 ((member type '("custom-id" "fuzzy" "id"))
1455 (let ((destination (if (string= type "fuzzy")
1456 (org-export-resolve-fuzzy-link link info)
1457 (org-export-resolve-id-link link info))))
1458 (case (org-element-type destination)
1459 ;; Fuzzy link points nowhere.
1460 ('nil
1461 (format "\\texttt{%s}"
1462 (or desc
1463 (org-export-secondary-string
1464 (org-element-property :raw-link link)
1465 'e-latex info))))
1466 ;; Fuzzy link points to an invisible target.
1467 (keyword nil)
1468 ;; LINK points to an headline. If headlines are numbered
1469 ;; and the link has no description, display headline's
1470 ;; number. Otherwise, display description or headline's
1471 ;; title.
1472 (headline
1473 (let ((label
1474 (format "sec-%s"
1475 (mapconcat
1476 'number-to-string
1477 (org-export-get-headline-number destination info)
1478 "-"))))
1479 (if (and (plist-get info :section-numbers) (not desc))
1480 (format "\\ref{%s}" label)
1481 (format "\\hyperref[%s]{%s}" label
1482 (or desc
1483 (org-export-secondary-string
1484 (org-element-property :title destination)
1485 'e-latex info))))))
1486 ;; Fuzzy link points to a target. Do as above.
1487 (otherwise
1488 (let ((path (org-export-solidify-link-text path)))
1489 (if (not desc) (format "\\ref{%s}" path)
1490 (format "\\hyperref[%s]{%s}" path desc)))))))
1491 ;; Coderef: replace link with the reference name or the
1492 ;; equivalent line number.
1493 ((string= type "coderef")
1494 (format (org-export-get-coderef-format path (or desc ""))
1495 (org-export-resolve-coderef path info)))
1496 ;; Link type is handled by a special function.
1497 ((functionp (setq protocol (nth 2 (assoc type org-link-protocols))))
1498 (funcall protocol (org-link-unescape path) desc 'latex))
1499 ;; External link with a description part.
1500 ((and path desc) (format "\\href{%s}{%s}" path desc))
1501 ;; External link without a description part.
1502 (path (format "\\url{%s}" path))
1503 ;; No path, only description. Try to do something useful.
1504 (t (format "\\texttt{%s}" desc)))))
1507 ;;;; Babel Call
1509 ;; Babel Calls are ignored.
1512 ;;;; Macro
1514 (defun org-e-latex-macro (macro contents info)
1515 "Transcode a MACRO element from Org to LaTeX.
1516 CONTENTS is nil. INFO is a plist holding contextual information."
1517 ;; Use available tools.
1518 (org-export-expand-macro macro info))
1521 ;;;; Paragraph
1523 (defun org-e-latex-paragraph (paragraph contents info)
1524 "Transcode a PARAGRAPH element from Org to LaTeX.
1525 CONTENTS is the contents of the paragraph, as a string. INFO is
1526 the plist used as a communication channel."
1527 contents)
1530 ;;;; Plain List
1532 (defun org-e-latex-plain-list (plain-list contents info)
1533 "Transcode a PLAIN-LIST element from Org to LaTeX.
1534 CONTENTS is the contents of the list. INFO is a plist holding
1535 contextual information."
1536 (let* ((type (org-element-property :type plain-list))
1537 (paralist-types '("inparaenum" "asparaenum" "inparaitem" "asparaitem"
1538 "inparadesc" "asparadesc"))
1539 (paralist-regexp (concat
1540 "\\("
1541 (mapconcat 'identity paralist-types "\\|")
1542 "\\)"))
1543 (attr (mapconcat #'identity
1544 (org-element-property :attr_latex plain-list)
1545 " "))
1546 (latex-type (cond
1547 ((and attr
1548 (string-match
1549 (format "\\<%s\\>" paralist-regexp) attr))
1550 (match-string 1 attr))
1551 ((eq type 'ordered) "enumerate")
1552 ((eq type 'unordered) "itemize")
1553 ((eq type 'descriptive) "description"))))
1554 (org-e-latex--wrap-label
1555 plain-list
1556 (format "\\begin{%s}%s\n%s\\end{%s}"
1557 latex-type
1558 ;; Once special environment, if any, has been removed, the
1559 ;; rest of the attributes will be optional arguments.
1560 ;; They will be put inside square brackets if necessary.
1561 (let ((opt (replace-regexp-in-string
1562 (format " *%s *" paralist-regexp) "" attr)))
1563 (cond ((string= opt "") "")
1564 ((string-match "\\`\\[[^][]+\\]\\'" opt) opt)
1565 (t (format "[%s]" opt))))
1566 contents
1567 latex-type))))
1570 ;;;; Plain Text
1572 (defun org-e-latex-plain-text (text info)
1573 "Transcode a TEXT string from Org to LaTeX.
1574 TEXT is the string to transcode. INFO is a plist holding
1575 contextual information."
1576 ;; Protect %, #, &, $, ~, ^, _, { and }.
1577 (while (string-match "\\([^\\]\\|^\\)\\([%$#&{}~^_]\\)" text)
1578 (setq text
1579 (replace-match (format "\\%s" (match-string 2 text)) nil t text 2)))
1580 ;; Protect \
1581 (setq text (replace-regexp-in-string
1582 "\\(?:[^\\]\\|^\\)\\(\\\\\\)\\(?:[^%$#&{}~^_\\]\\|$\\)"
1583 "$\\backslash$" text nil t 1))
1584 ;; LaTeX into \LaTeX{} and TeX into \TeX{}.
1585 (let ((case-fold-search nil)
1586 (start 0))
1587 (while (string-match "\\<\\(\\(?:La\\)?TeX\\)\\>" text start)
1588 (setq text (replace-match
1589 (format "\\%s{}" (match-string 1 text)) nil t text)
1590 start (match-end 0))))
1591 ;; Handle quotation marks
1592 (setq text (org-e-latex--quotation-marks text info))
1593 ;; Convert special strings.
1594 (when (plist-get info :with-special-strings)
1595 (while (string-match (regexp-quote "...") text)
1596 (setq text (replace-match "\\ldots{}" nil t text))))
1597 ;; Handle break preservation if required.
1598 (when (plist-get info :preserve-breaks)
1599 (setq text (replace-regexp-in-string "\\(\\\\\\\\\\)?[ \t]*\n" " \\\\\\\\\n"
1600 text)))
1601 ;; Return value.
1602 text)
1605 ;;;; Property Drawer
1607 (defun org-e-latex-property-drawer (property-drawer contents info)
1608 "Transcode a PROPERTY-DRAWER element from Org to LaTeX.
1609 CONTENTS is nil. INFO is a plist holding contextual
1610 information."
1611 ;; The property drawer isn't exported but we want separating blank
1612 ;; lines nonetheless.
1616 ;;;; Quote Block
1618 (defun org-e-latex-quote-block (quote-block contents info)
1619 "Transcode a QUOTE-BLOCK element from Org to LaTeX.
1620 CONTENTS holds the contents of the block. INFO is a plist
1621 holding contextual information."
1622 (org-e-latex--wrap-label
1623 quote-block
1624 (format "\\begin{quote}\n%s\\end{quote}" contents)))
1627 ;;;; Quote Section
1629 (defun org-e-latex-quote-section (quote-section contents info)
1630 "Transcode a QUOTE-SECTION element from Org to LaTeX.
1631 CONTENTS is nil. INFO is a plist holding contextual information."
1632 (let ((value (org-remove-indentation
1633 (org-element-property :value quote-section))))
1634 (when value (format "\\begin{verbatim}\n%s\\end{verbatim}" value))))
1637 ;;;; Section
1639 (defun org-e-latex-section (section contents info)
1640 "Transcode a SECTION element from Org to LaTeX.
1641 CONTENTS holds the contents of the section. INFO is a plist
1642 holding contextual information."
1643 contents)
1646 ;;;; Radio Target
1648 (defun org-e-latex-radio-target (radio-target text info)
1649 "Transcode a RADIO-TARGET object from Org to LaTeX.
1650 TEXT is the text of the target. INFO is a plist holding
1651 contextual information."
1652 (format "\\label{%s}%s"
1653 (org-export-solidify-link-text
1654 (org-element-property :raw-value radio-target))
1655 text))
1658 ;;;; Special Block
1660 (defun org-e-latex-special-block (special-block contents info)
1661 "Transcode a SPECIAL-BLOCK element from Org to LaTeX.
1662 CONTENTS holds the contents of the block. INFO is a plist
1663 holding contextual information."
1664 (let ((type (downcase (org-element-property :type special-block))))
1665 (org-e-latex--wrap-label
1666 special-block
1667 (format "\\begin{%s}\n%s\\end{%s}" type contents type))))
1670 ;;;; Src Block
1672 (defun org-e-latex-src-block (src-block contents info)
1673 "Transcode a SRC-BLOCK element from Org to LaTeX.
1674 CONTENTS holds the contents of the item. INFO is a plist holding
1675 contextual information."
1676 (let* ((lang (org-element-property :language src-block))
1677 (code (org-export-handle-code src-block info))
1678 (caption (org-element-property :caption src-block))
1679 (label (org-element-property :name src-block))
1680 (custom-env (and lang
1681 (cadr (assq (intern lang)
1682 org-e-latex-custom-lang-environments)))))
1683 (cond
1684 ;; No source fontification.
1685 ((not org-e-latex-listings)
1686 (let ((caption-str (org-e-latex--caption/label-string
1687 caption label info))
1688 (float-env (when caption "\\begin{figure}[H]\n%s\n\\end{figure}")))
1689 (format (or float-env "%s")
1690 (concat
1691 caption-str
1692 (format "\\begin{verbatim}\n%s\\end{verbatim}" code)))))
1693 ;; Custom environment.
1694 (custom-env
1695 (format "\\begin{%s}\n%s\\end{%s}\n" custom-env code custom-env))
1696 ;; Use minted package.
1697 ((eq org-e-latex-listings 'minted)
1698 (let* ((mint-lang (or (cadr (assq (intern lang) org-e-latex-minted-langs))
1699 lang))
1700 (float-env (when (or label caption)
1701 (format "\\begin{listing}[H]\n%%s\n%s\\end{listing}"
1702 (org-e-latex--caption/label-string
1703 caption label info))))
1704 (body (format "\\begin{minted}[%s]{%s}\n%s\\end{minted}"
1705 (org-e-latex--make-option-string
1706 org-e-latex-minted-options)
1707 mint-lang code)))
1708 (if float-env (format float-env body) body)))
1709 ;; Use listings package.
1711 (let ((lst-lang
1712 (or (cadr (assq (intern lang) org-e-latex-listings-langs)) lang))
1713 (caption-str
1714 (when caption
1715 (let ((main (org-export-secondary-string
1716 (car caption) 'e-latex info)))
1717 (if (not (cdr caption)) (format "{%s}" main)
1718 (format
1719 "{[%s]%s}"
1720 (org-export-secondary-string (cdr caption) 'e-latex info)
1721 main))))))
1722 (concat (format "\\lstset{%s}\n"
1723 (org-e-latex--make-option-string
1724 (append org-e-latex-listings-options
1725 `(("language" ,lst-lang))
1726 (when label `(("label" ,label)))
1727 (when caption-str
1728 `(("caption" ,caption-str))))))
1729 (format "\\begin{lstlisting}\n%s\\end{lstlisting}" code)))))))
1732 ;;;; Statistics Cookie
1734 (defun org-e-latex-statistics-cookie (statistics-cookie contents info)
1735 "Transcode a STATISTICS-COOKIE object from Org to LaTeX.
1736 CONTENTS is nil. INFO is a plist holding contextual information."
1737 (org-element-property :value statistics-cookie))
1740 ;;;; Subscript
1742 (defun org-e-latex-subscript (subscript contents info)
1743 "Transcode a SUBSCRIPT object from Org to LaTeX.
1744 CONTENTS is the contents of the object. INFO is a plist holding
1745 contextual information."
1746 (format (if (= (length contents) 1) "$_%s$" "$_{\\mathrm{%s}}$") contents))
1749 ;;;; Superscript
1751 (defun org-e-latex-superscript (superscript contents info)
1752 "Transcode a SUPERSCRIPT object from Org to LaTeX.
1753 CONTENTS is the contents of the object. INFO is a plist holding
1754 contextual information."
1755 (format (if (= (length contents) 1) "$^%s$" "$^{\\mathrm{%s}}$") contents))
1758 ;;;; Table
1760 (defun org-e-latex-table--format-string (table table-info info)
1761 "Return an appropriate format string for TABLE.
1763 TABLE-INFO is the plist containing format info about the table,
1764 as returned by `org-export-table-format-info'. INFO is a plist
1765 used as a communication channel.
1767 The format string leaves one placeholder for the body of the
1768 table."
1769 (let* ((label (org-element-property :name table))
1770 (caption (org-e-latex--caption/label-string
1771 (org-element-property :caption table) label info))
1772 (attr (mapconcat 'identity
1773 (org-element-property :attr_latex table)
1774 " "))
1775 ;; Determine alignment string.
1776 (alignment (org-e-latex-table--align-string attr table-info))
1777 ;; Determine environment for the table: longtable, tabular...
1778 (table-env (cond
1779 ((not attr) org-e-latex-default-table-environment)
1780 ((string-match "\\<longtable\\>" attr) "longtable")
1781 ((string-match "\\<tabular.?\\>" attr)
1782 (org-match-string-no-properties 0 attr))
1783 (t org-e-latex-default-table-environment)))
1784 ;; If table is a float, determine environment: table or table*.
1785 (float-env (cond
1786 ((string= "longtable" table-env) nil)
1787 ((and attr
1788 (or (string-match (regexp-quote "table*") attr)
1789 (string-match "\\<multicolumn\\>" attr)))
1790 "table*")
1791 ((or (not (string= caption "")) label) "table")))
1792 ;; Extract others display options.
1793 (width (and attr (string-match "\\<width=\\(\\S-+\\)" attr)
1794 (org-match-string-no-properties 1 attr)))
1795 (placement
1796 (if (and attr (string-match "\\<placement=\\(\\S-+\\)" attr))
1797 (org-match-string-no-properties 1 attr)
1798 (format "[%s]" org-e-latex-default-figure-position))))
1799 ;; Prepare the final format string for the table.
1800 (cond
1801 ;; Longtable.
1802 ((string= "longtable" table-env)
1803 (format
1804 "\\begin{longtable}{%s}\n%s\n%%s\n%s\\end{longtable}"
1805 alignment
1806 (if (or (not org-e-latex-table-caption-above) (string= "" caption)) ""
1807 (concat (org-trim caption) "\\\\"))
1808 (if (or org-e-latex-table-caption-above (string= "" caption)) ""
1809 (concat (org-trim caption) "\\\\\n"))))
1810 ;; Others.
1811 (t (concat (when float-env
1812 (concat
1813 (format "\\begin{%s}%s\n" float-env placement)
1814 (if org-e-latex-table-caption-above caption "")))
1815 (when org-e-latex-tables-centered "\\begin{center}\n")
1816 (format "\\begin{%s}%s{%s}\n%%s\n\\end{%s}"
1817 table-env
1818 (if width (format "{%s}" width) "") alignment table-env)
1819 (when org-e-latex-tables-centered "\n\\end{center}")
1820 (when float-env
1821 (concat (if org-e-latex-table-caption-above "" caption)
1822 (format "\n\\end{%s}" float-env))))))))
1824 (defun org-e-latex-table--align-string (attr table-info)
1825 "Return an appropriate LaTeX alignment string.
1826 ATTR is a string containing table's LaTeX specific attributes.
1827 TABLE-INFO is the plist containing format info about the table,
1828 as returned by `org-export-table-format-info'."
1829 (or (and attr
1830 (string-match "\\<align=\\(\\S-+\\)" attr)
1831 (match-string 1 attr))
1832 (let* ((align (copy-sequence (plist-get table-info :alignment)))
1833 (colgroups (copy-sequence (plist-get table-info :column-groups)))
1834 (cols (length align))
1835 (separators (make-vector (1+ cols) "")))
1836 ;; Ignore the first column if it's special.
1837 (when (plist-get table-info :special-column-p)
1838 (aset align 0 "") (aset colgroups 0 nil))
1839 (let ((col 0))
1840 (mapc (lambda (el)
1841 (let ((gr (aref colgroups col)))
1842 (when (memq gr '(start start-end))
1843 (aset separators col "|"))
1844 (when (memq gr '(end start-end))
1845 (aset separators (1+ col) "|")))
1846 (incf col))
1847 align))
1848 ;; Build the LaTeX specific alignment string.
1849 (loop for al across align
1850 for sep across separators
1851 concat (concat sep al) into output
1852 finally return (concat output (aref separators cols))))))
1854 (defun org-e-latex-table (table contents info)
1855 "Transcode a TABLE element from Org to LaTeX.
1856 CONTENTS is nil. INFO is a plist holding contextual information."
1857 (let ((attr (mapconcat #'identity
1858 (org-element-property :attr_latex table)
1859 " "))
1860 (raw-table (org-element-property :raw-table table)))
1861 (cond
1862 ;; Case 1: verbatim table.
1863 ((or org-e-latex-tables-verbatim
1864 (and attr (string-match "\\<verbatim\\>" attr)))
1865 (format "\\begin{verbatim}\n%s\n\\end{verbatim}"
1866 (org-export-clean-table
1867 raw-table
1868 (plist-get (org-export-table-format-info raw-table)
1869 :special-column-p))))
1870 ;; Case 2: table.el table. Convert it using appropriate tools.
1871 ((eq (org-element-property :type table) 'table.el)
1872 (require 'table)
1873 ;; Ensure "*org-export-table*" buffer is empty.
1874 (with-current-buffer (get-buffer-create "*org-export-table*")
1875 (erase-buffer))
1876 (let ((output (with-temp-buffer
1877 (insert raw-table)
1878 (goto-char 1)
1879 (re-search-forward "^[ \t]*|[^|]" nil t)
1880 (table-generate-source 'latex "*org-export-table*")
1881 (with-current-buffer "*org-export-table*"
1882 (org-trim (buffer-string))))))
1883 (kill-buffer (get-buffer "*org-export-table*"))
1884 ;; Remove left out comments.
1885 (while (string-match "^%.*\n" output)
1886 (setq output (replace-match "" t t output)))
1887 ;; When the "rmlines" attribute is provided, remove all hlines
1888 ;; but the the one separating heading from the table body.
1889 (when (and attr (string-match "\\<rmlines\\>" attr))
1890 (let ((n 0) (pos 0))
1891 (while (and (< (length output) pos)
1892 (setq pos (string-match "^\\\\hline\n?" output pos)))
1893 (incf n)
1894 (unless (= n 2)
1895 (setq output (replace-match "" nil nil output))))))
1896 (if (not org-e-latex-tables-centered) output
1897 (format "\\begin{center}\n%s\n\\end{center}" output))))
1898 ;; Case 3: Standard table.
1900 (let* ((table-info (org-export-table-format-info raw-table))
1901 (columns-number (length (plist-get table-info :alignment)))
1902 (longtablep (and attr (string-match "\\<longtable\\>" attr)))
1903 (booktabsp
1904 (or (and attr (string-match "\\<booktabs=\\(yes\\|t\\)\\>" attr))
1905 org-e-latex-tables-booktabs))
1906 ;; CLEAN-TABLE is a table turned into a list, much like
1907 ;; `org-table-to-lisp', with special column and
1908 ;; formatting cookies removed, and cells already
1909 ;; transcoded.
1910 (clean-table
1911 (mapcar
1912 (lambda (row)
1913 (if (string-match org-table-hline-regexp row) 'hline
1914 (mapcar
1915 (lambda (cell)
1916 (org-export-secondary-string
1917 (org-element-parse-secondary-string
1918 cell
1919 (cdr (assq 'table org-element-string-restrictions)))
1920 'e-latex info))
1921 (org-split-string row "[ \t]*|[ \t]*"))))
1922 (org-split-string
1923 (org-export-clean-table
1924 raw-table (plist-get table-info :special-column-p))
1925 "\n"))))
1926 ;; If BOOKTABSP is non-nil, remove any rule at the beginning
1927 ;; and the end of the table, since booktabs' special rules
1928 ;; will be inserted instead.
1929 (when booktabsp
1930 (when (eq (car clean-table) 'hline)
1931 (setq clean-table (cdr clean-table)))
1932 (when (eq (car (last clean-table)) 'hline)
1933 (setq clean-table (butlast clean-table))))
1934 ;; Convert ROWS to send them to `orgtbl-to-latex'. In
1935 ;; particular, send each cell to
1936 ;; `org-element-parse-secondary-string' to expand any Org
1937 ;; object within. Eventually, flesh the format string out
1938 ;; with the table.
1939 (format
1940 (org-e-latex-table--format-string table table-info info)
1941 (orgtbl-to-latex
1942 clean-table
1943 ;; Parameters passed to `orgtbl-to-latex'.
1944 `(:tstart ,(and booktabsp "\\toprule")
1945 :tend ,(and booktabsp "\\bottomrule")
1946 :hline ,(if booktabsp "\\midrule" "\\hline")
1947 ;; Longtable environment requires specific header
1948 ;; lines end string.
1949 :hlend ,(and longtablep
1950 (format "\\\\
1952 \\endhead
1953 %s\\multicolumn{%d}{r}{Continued on next page}\\\\
1954 \\endfoot
1955 \\endlastfoot"
1956 (if booktabsp "\\midrule" "\\hline")
1957 (if booktabsp "\\midrule" "\\hline")
1958 columns-number))))))))))
1961 ;;;; Target
1963 (defun org-e-latex-target (target contents info)
1964 "Transcode a TARGET object from Org to LaTeX.
1965 CONTENTS is nil. INFO is a plist holding contextual
1966 information."
1967 (format "\\label{%s}"
1968 (org-export-solidify-link-text (org-element-property :value target))))
1971 ;;;; Time-stamp
1973 (defun org-e-latex-time-stamp (time-stamp contents info)
1974 "Transcode a TIME-STAMP object from Org to LaTeX.
1975 CONTENTS is nil. INFO is a plist holding contextual
1976 information."
1977 (let ((value (org-element-property :value time-stamp))
1978 (type (org-element-property :type time-stamp))
1979 (appt-type (org-element-property :appt-type time-stamp)))
1980 (concat (cond ((eq appt-type 'scheduled)
1981 (format "\\textbf{\\textsc{%s}} " org-scheduled-string))
1982 ((eq appt-type 'deadline)
1983 (format "\\textbf{\\textsc{%s}} " org-deadline-string))
1984 ((eq appt-type 'closed)
1985 (format "\\textbf{\\textsc{%s}} " org-closed-string)))
1986 (cond ((memq type '(active active-range))
1987 (format org-e-latex-active-timestamp-format value))
1988 ((memq type '(inactive inactive-range))
1989 (format org-e-latex-inactive-timestamp-format value))
1991 (format org-e-latex-diary-timestamp-format value))))))
1994 ;;;; Verbatim
1996 (defun org-e-latex-verbatim (verbatim contents info)
1997 "Transcode a VERBATIM object from Org to LaTeX.
1998 CONTENTS is nil. INFO is a plist used as a communication
1999 channel."
2000 (let ((fmt (cdr (assoc (org-element-property :marker verbatim)
2001 org-e-latex-emphasis-alist)))
2002 (value (org-element-property :value verbatim)))
2003 (cond
2004 ;; Handle the `verb' special case.
2005 ((eq 'verb fmt)
2006 (let ((separator (org-e-latex--find-verb-separator value)))
2007 (concat "\\verb" separator value separator)))
2008 ;; Handle the `protectedtexttt' special case.
2009 ((eq 'protectedtexttt fmt)
2010 (let ((start 0)
2011 (trans '(("\\" . "\\textbackslash{}")
2012 ("~" . "\\textasciitilde{}")
2013 ("^" . "\\textasciicircum{}")))
2014 (rtn "")
2015 char)
2016 (while (string-match "[\\{}$%&_#~^]" value)
2017 (setq char (match-string 0 value))
2018 (if (> (match-beginning 0) 0)
2019 (setq rtn (concat rtn (substring value 0 (match-beginning 0)))))
2020 (setq value (substring value (1+ (match-beginning 0))))
2021 (setq char (or (cdr (assoc char trans)) (concat "\\" char))
2022 rtn (concat rtn char)))
2023 (setq value (concat rtn value)
2024 fmt "\\texttt{%s}")
2025 (while (string-match "--" value)
2026 (setq value (replace-match "-{}-" t t value)))
2027 (format fmt value)))
2028 ;; Else use format string.
2029 (t (format fmt value)))))
2032 ;;;; Verse Block
2034 (defun org-e-latex-verse-block (verse-block contents info)
2035 "Transcode a VERSE-BLOCK element from Org to LaTeX.
2036 CONTENTS is nil. INFO is a plist holding contextual information."
2037 (org-e-latex--wrap-label
2038 verse-block
2039 ;; In a verse environment, add a line break to each newline
2040 ;; character and change each white space at beginning of a line
2041 ;; into a space of 1 em. Also change each blank line with
2042 ;; a vertical space of 1 em.
2043 (progn
2044 (setq contents (replace-regexp-in-string
2045 "^ *\\\\\\\\$" "\\\\vspace*{1em}"
2046 (replace-regexp-in-string
2047 "\\(\\\\\\\\\\)?[ \t]*\n" " \\\\\\\\\n"
2048 (org-remove-indentation
2049 (org-export-secondary-string
2050 (org-element-property :value verse-block)
2051 'e-latex info)))))
2052 (while (string-match "^[ \t]+" contents)
2053 (let ((new-str (format "\\hspace*{%dem}"
2054 (length (match-string 0 contents)))))
2055 (setq contents (replace-match new-str nil t contents))))
2056 (format "\\begin{verse}\n%s\\end{verse}" contents))))
2060 ;;; Interactive functions
2062 (defun org-e-latex-export-to-latex
2063 (&optional subtreep visible-only body-only ext-plist pub-dir)
2064 "Export current buffer to a LaTeX file.
2066 If narrowing is active in the current buffer, only export its
2067 narrowed part.
2069 If a region is active, export that region.
2071 When optional argument SUBTREEP is non-nil, export the sub-tree
2072 at point, extracting information from the headline properties
2073 first.
2075 When optional argument VISIBLE-ONLY is non-nil, don't export
2076 contents of hidden elements.
2078 When optional argument BODY-ONLY is non-nil, only write code
2079 between \"\\begin{document}\" and \"\\end{document}\".
2081 EXT-PLIST, when provided, is a property list with external
2082 parameters overriding Org default settings, but still inferior to
2083 file-local settings.
2085 When optional argument PUB-DIR is set, use it as the publishing
2086 directory.
2088 Return output file's name."
2089 (interactive)
2090 (let ((outfile (org-export-output-file-name ".tex" subtreep pub-dir)))
2091 (org-export-to-file
2092 'e-latex outfile subtreep visible-only body-only ext-plist)))
2094 (defun org-e-latex-export-to-pdf
2095 (&optional subtreep visible-only body-only ext-plist pub-dir)
2096 "Export current buffer to LaTeX then process through to PDF.
2098 If narrowing is active in the current buffer, only export its
2099 narrowed part.
2101 If a region is active, export that region.
2103 When optional argument SUBTREEP is non-nil, export the sub-tree
2104 at point, extracting information from the headline properties
2105 first.
2107 When optional argument VISIBLE-ONLY is non-nil, don't export
2108 contents of hidden elements.
2110 When optional argument BODY-ONLY is non-nil, only write code
2111 between \"\\begin{document}\" and \"\\end{document}\".
2113 EXT-PLIST, when provided, is a property list with external
2114 parameters overriding Org default settings, but still inferior to
2115 file-local settings.
2117 When optional argument PUB-DIR is set, use it as the publishing
2118 directory.
2120 Return PDF file's name."
2121 (interactive)
2122 (org-e-latex-compile
2123 (org-e-latex-export-to-latex
2124 subtreep visible-only body-only ext-plist pub-dir)))
2126 (defun org-e-latex-compile (texfile)
2127 "Compile a TeX file.
2129 TEXFILE is the name of the file being compiled. Processing is
2130 done through the command specified in `org-e-latex-pdf-process'.
2132 Return PDF file name or an error if it couldn't be produced."
2133 (let* ((wconfig (current-window-configuration))
2134 (texfile (file-truename texfile))
2135 (base (file-name-sans-extension texfile))
2136 errors)
2137 (message (format "Processing LaTeX file %s ..." texfile))
2138 (unwind-protect
2139 (progn
2140 (cond
2141 ;; A function is provided: Apply it.
2142 ((functionp org-e-latex-pdf-process)
2143 (funcall org-e-latex-pdf-process (shell-quote-argument texfile)))
2144 ;; A list is provided: Replace %b, %f and %o with appropriate
2145 ;; values in each command before applying it. Output is
2146 ;; redirected to "*Org PDF LaTeX Output*" buffer.
2147 ((consp org-e-latex-pdf-process)
2148 (let* ((out-dir (or (file-name-directory texfile) "./"))
2149 (outbuf (get-buffer-create "*Org PDF LaTeX Output*")))
2150 (mapc
2151 (lambda (command)
2152 (shell-command
2153 (replace-regexp-in-string
2154 "%b" (shell-quote-argument base)
2155 (replace-regexp-in-string
2156 "%f" (shell-quote-argument texfile)
2157 (replace-regexp-in-string
2158 "%o" (shell-quote-argument out-dir) command t t) t t) t t)
2159 outbuf))
2160 org-e-latex-pdf-process)
2161 ;; Collect standard errors from output buffer.
2162 (setq errors (org-e-latex-collect-errors outbuf))))
2163 (t (error "No valid command to process to PDF")))
2164 (let ((pdffile (concat base ".pdf")))
2165 ;; Check for process failure. Provide collected errors if
2166 ;; possible.
2167 (if (not (file-exists-p pdffile))
2168 (error (concat (format "PDF file %s wasn't produced" pdffile)
2169 (when errors (concat ": " errors))))
2170 ;; Else remove log files, when specified, and signal end of
2171 ;; process to user, along with any error encountered.
2172 (when org-e-latex-remove-logfiles
2173 (dolist (ext org-e-latex-logfiles-extensions)
2174 (let ((file (concat base "." ext)))
2175 (when (file-exists-p file) (delete-file file)))))
2176 (message (concat "Process completed"
2177 (if (not errors) "."
2178 (concat " with errors: " errors)))))
2179 ;; Return output file name.
2180 pdffile))
2181 (set-window-configuration wconfig))))
2183 (defun org-e-latex-collect-errors (buffer)
2184 "Collect some kind of errors from \"pdflatex\" command output.
2186 BUFFER is the buffer containing output.
2188 Return collected error types as a string, or nil if there was
2189 none."
2190 (with-current-buffer buffer
2191 (save-excursion
2192 (goto-char (point-max))
2193 ;; Find final "pdflatex" run.
2194 (when (re-search-backward "^[ \t]*This is pdf.*?TeX.*?Version" nil t)
2195 (let ((case-fold-search t)
2196 (errors ""))
2197 (when (save-excursion
2198 (re-search-forward "Reference.*?undefined" nil t))
2199 (setq errors (concat errors " [undefined reference]")))
2200 (when (save-excursion
2201 (re-search-forward "Citation.*?undefined" nil t))
2202 (setq errors (concat errors " [undefined citation]")))
2203 (when (save-excursion
2204 (re-search-forward "Undefined control sequence" nil t))
2205 (setq errors (concat errors " [undefined control sequence]")))
2206 (when (save-excursion
2207 (re-search-forward "^! LaTeX.*?Error" nil t))
2208 (setq errors (concat errors " [LaTeX error]")))
2209 (when (save-excursion
2210 (re-search-forward "^! Package.*?Error" nil t))
2211 (setq errors (concat errors " [package error]")))
2212 (and (org-string-nw-p errors) (org-trim errors)))))))
2215 (provide 'org-e-latex)
2216 ;;; org-e-latex.el ends here