introduce $(SUDO) to make install with administrative privileges customizable
[org-mode.git] / lisp / org-latex.el
blob8e056161172449b63f738d064da65c35ca790f6d
1 ;;; org-latex.el --- LaTeX exporter for org-mode
2 ;;
3 ;; Copyright (C) 2007-2012 Free Software Foundation, Inc.
4 ;;
5 ;; Emacs Lisp Archive Entry
6 ;; Filename: org-latex.el
7 ;; Author: Bastien Guerry <bzg AT gnu DOT org>
8 ;; Maintainer: Carsten Dominik <carsten.dominik AT gmail DOT com>
9 ;; Keywords: org, wp, tex
10 ;; Description: Converts an org-mode buffer into LaTeX
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
27 ;;; Commentary:
29 ;; This library implements a LaTeX exporter for org-mode.
31 ;; It is part of Org and will be autoloaded
33 ;; The interactive functions are similar to those of the HTML exporter:
35 ;; M-x `org-export-as-latex'
36 ;; M-x `org-export-as-pdf'
37 ;; M-x `org-export-as-pdf-and-open'
38 ;; M-x `org-export-as-latex-batch'
39 ;; M-x `org-export-as-latex-to-buffer'
40 ;; M-x `org-export-region-as-latex'
41 ;; M-x `org-replace-region-by-latex'
43 ;;; Code:
45 (eval-when-compile
46 (require 'cl))
48 (require 'footnote)
49 (require 'org)
50 (require 'org-exp)
51 (require 'org-macs)
52 (require 'org-beamer)
54 ;;; Variables:
55 (defvar org-export-latex-class nil)
56 (defvar org-export-latex-class-options nil)
57 (defvar org-export-latex-header nil)
58 (defvar org-export-latex-append-header nil)
59 (defvar org-export-latex-options-plist nil)
60 (defvar org-export-latex-todo-keywords-1 nil)
61 (defvar org-export-latex-complex-heading-re nil)
62 (defvar org-export-latex-not-done-keywords nil)
63 (defvar org-export-latex-done-keywords nil)
64 (defvar org-export-latex-display-custom-times nil)
65 (defvar org-export-latex-all-targets-re nil)
66 (defvar org-export-latex-add-level 0)
67 (defvar org-export-latex-footmark-seen nil
68 "List of footnotes markers seen so far by exporter.")
69 (defvar org-export-latex-sectioning "")
70 (defvar org-export-latex-sectioning-depth 0)
71 (defvar org-export-latex-special-keyword-regexp
72 (concat "\\<\\(" org-scheduled-string "\\|"
73 org-deadline-string "\\|"
74 org-closed-string"\\)")
75 "Regexp matching special time planning keywords plus the time after it.")
76 (defvar org-re-quote) ; dynamically scoped from org.el
77 (defvar org-commentsp) ; dynamically scoped from org.el
79 ;;; User variables:
81 (defgroup org-export-latex nil
82 "Options for exporting Org-mode files to LaTeX."
83 :tag "Org Export LaTeX"
84 :group 'org-export)
86 (defcustom org-export-latex-default-class "article"
87 "The default LaTeX class."
88 :group 'org-export-latex
89 :type '(string :tag "LaTeX class"))
91 (defcustom org-export-latex-classes
92 '(("article"
93 "\\documentclass[11pt]{article}"
94 ("\\section{%s}" . "\\section*{%s}")
95 ("\\subsection{%s}" . "\\subsection*{%s}")
96 ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
97 ("\\paragraph{%s}" . "\\paragraph*{%s}")
98 ("\\subparagraph{%s}" . "\\subparagraph*{%s}"))
99 ("report"
100 "\\documentclass[11pt]{report}"
101 ("\\part{%s}" . "\\part*{%s}")
102 ("\\chapter{%s}" . "\\chapter*{%s}")
103 ("\\section{%s}" . "\\section*{%s}")
104 ("\\subsection{%s}" . "\\subsection*{%s}")
105 ("\\subsubsection{%s}" . "\\subsubsection*{%s}"))
106 ("book"
107 "\\documentclass[11pt]{book}"
108 ("\\part{%s}" . "\\part*{%s}")
109 ("\\chapter{%s}" . "\\chapter*{%s}")
110 ("\\section{%s}" . "\\section*{%s}")
111 ("\\subsection{%s}" . "\\subsection*{%s}")
112 ("\\subsubsection{%s}" . "\\subsubsection*{%s}"))
113 ("beamer"
114 "\\documentclass{beamer}"
115 org-beamer-sectioning
117 "Alist of LaTeX classes and associated header and structure.
118 If #+LaTeX_CLASS is set in the buffer, use its value and the
119 associated information. Here is the structure of each cell:
121 \(class-name
122 header-string
123 (numbered-section . unnumbered-section\)
124 ...\)
126 The header string
127 -----------------
129 The HEADER-STRING is the header that will be inserted into the LaTeX file.
130 It should contain the \\documentclass macro, and anything else that is needed
131 for this setup. To this header, the following commands will be added:
133 - Calls to \\usepackage for all packages mentioned in the variables
134 `org-export-latex-default-packages-alist' and
135 `org-export-latex-packages-alist'. Thus, your header definitions should
136 avoid to also request these packages.
138 - Lines specified via \"#+LaTeX_HEADER:\"
140 If you need more control about the sequence in which the header is built
141 up, or if you want to exclude one of these building blocks for a particular
142 class, you can use the following macro-like placeholders.
144 [DEFAULT-PACKAGES] \\usepackage statements for default packages
145 [NO-DEFAULT-PACKAGES] do not include any of the default packages
146 [PACKAGES] \\usepackage statements for packages
147 [NO-PACKAGES] do not include the packages
148 [EXTRA] the stuff from #+LaTeX_HEADER
149 [NO-EXTRA] do not include #+LaTeX_HEADER stuff
150 [BEAMER-HEADER-EXTRA] the beamer extra headers
152 So a header like
154 \\documentclass{article}
155 [NO-DEFAULT-PACKAGES]
156 [EXTRA]
157 \\providecommand{\\alert}[1]{\\textbf{#1}}
158 [PACKAGES]
160 will omit the default packages, and will include the #+LaTeX_HEADER lines,
161 then have a call to \\providecommand, and then place \\usepackage commands
162 based on the content of `org-export-latex-packages-alist'.
164 If your header or `org-export-latex-default-packages-alist' inserts
165 \"\\usepackage[AUTO]{inputenc}\", AUTO will automatically be replaced with
166 a coding system derived from `buffer-file-coding-system'. See also the
167 variable `org-export-latex-inputenc-alist' for a way to influence this
168 mechanism.
170 The sectioning structure
171 ------------------------
173 The sectioning structure of the class is given by the elements following
174 the header string. For each sectioning level, a number of strings is
175 specified. A %s formatter is mandatory in each section string and will
176 be replaced by the title of the section.
178 Instead of a cons cell (numbered . unnumbered), you can also provide a list
179 of 2 or 4 elements,
181 (numbered-open numbered-close)
185 (numbered-open numbered-close unnumbered-open unnumbered-close)
187 providing opening and closing strings for a LaTeX environment that should
188 represent the document section. The opening clause should have a %s
189 to represent the section title.
191 Instead of a list of sectioning commands, you can also specify a
192 function name. That function will be called with two parameters,
193 the (reduced) level of the headline, and the headline text. The function
194 must return a cons cell with the (possibly modified) headline text, and the
195 sectioning list in the cdr."
196 :group 'org-export-latex
197 :type '(repeat
198 (list (string :tag "LaTeX class")
199 (string :tag "LaTeX header")
200 (repeat :tag "Levels" :inline t
201 (choice
202 (cons :tag "Heading"
203 (string :tag " numbered")
204 (string :tag "unnumbered"))
205 (list :tag "Environment"
206 (string :tag "Opening (numbered)")
207 (string :tag "Closing (numbered)")
208 (string :tag "Opening (unnumbered)")
209 (string :tag "Closing (unnumbered)"))
210 (function :tag "Hook computing sectioning"))))))
212 (defcustom org-export-latex-inputenc-alist nil
213 "Alist of inputenc coding system names, and what should really be used.
214 For example, adding an entry
216 (\"utf8\" . \"utf8x\")
218 will cause \\usepackage[utf8x]{inputenc} to be used for buffers that
219 are written as utf8 files."
220 :group 'org-export-latex
221 :version "24.1"
222 :type '(repeat
223 (cons
224 (string :tag "Derived from buffer")
225 (string :tag "Use this instead"))))
228 (defcustom org-export-latex-emphasis-alist
229 '(("*" "\\textbf{%s}" nil)
230 ("/" "\\emph{%s}" nil)
231 ("_" "\\underline{%s}" nil)
232 ("+" "\\st{%s}" nil)
233 ("=" "\\protectedtexttt" t)
234 ("~" "\\verb" t))
235 "Alist of LaTeX expressions to convert emphasis fontifiers.
236 Each element of the list is a list of three elements.
237 The first element is the character used as a marker for fontification.
238 The second element is a formatting string to wrap fontified text with.
239 If it is \"\\verb\", Org will automatically select a delimiter
240 character that is not in the string. \"\\protectedtexttt\" will use \\texttt
241 to typeset and try to protect special characters.
242 The third element decides whether to protect converted text from other
243 conversions."
244 :group 'org-export-latex
245 :type 'alist)
247 (defcustom org-export-latex-title-command "\\maketitle"
248 "The command used to insert the title just after \\begin{document}.
249 If this string contains the formatting specification \"%s\" then
250 it will be used as a formatting string, passing the title as an
251 argument."
252 :group 'org-export-latex
253 :type 'string)
255 (defcustom org-export-latex-import-inbuffer-stuff nil
256 "Non-nil means define TeX macros for Org's inbuffer definitions.
257 For example \orgTITLE for #+TITLE."
258 :group 'org-export-latex
259 :type 'boolean)
261 (defcustom org-export-latex-date-format
262 "\\today"
263 "Format string for \\date{...}."
264 :group 'org-export-latex
265 :type 'string)
267 (defcustom org-export-latex-todo-keyword-markup "\\textbf{%s}"
268 "Markup for TODO keywords, as a printf format.
269 This can be a single format for all keywords, a cons cell with separate
270 formats for not-done and done states, or an association list with setup
271 for individual keywords. If a keyword shows up for which there is no
272 markup defined, the first one in the association list will be used."
273 :group 'org-export-latex
274 :type '(choice
275 (string :tag "Default")
276 (cons :tag "Distinguish undone and done"
277 (string :tag "Not-DONE states")
278 (string :tag "DONE states"))
279 (repeat :tag "Per keyword markup"
280 (cons
281 (string :tag "Keyword")
282 (string :tag "Markup")))))
284 (defcustom org-export-latex-tag-markup "\\textbf{%s}"
285 "Markup for tags, as a printf format."
286 :group 'org-export-latex
287 :version "24.1"
288 :type 'string)
290 (defcustom org-export-latex-timestamp-markup "\\textit{%s}"
291 "A printf format string to be applied to time stamps."
292 :group 'org-export-latex
293 :type 'string)
295 (defcustom org-export-latex-timestamp-inactive-markup "\\textit{%s}"
296 "A printf format string to be applied to inactive time stamps."
297 :group 'org-export-latex
298 :version "24.1"
299 :type 'string)
301 (defcustom org-export-latex-timestamp-keyword-markup "\\texttt{%s}"
302 "A printf format string to be applied to time stamps."
303 :group 'org-export-latex
304 :type 'string)
306 (defcustom org-export-latex-href-format "\\href{%s}{%s}"
307 "A printf format string to be applied to href links.
308 The format must contain either two %s instances or just one.
309 If it contains two %s instances, the first will be filled with
310 the link, the second with the link description. If it contains
311 only one, the %s will be filled with the link."
312 :group 'org-export-latex
313 :version "24.1"
314 :type 'string)
316 (defcustom org-export-latex-hyperref-format "\\hyperref[%s]{%s}"
317 "A printf format string to be applied to hyperref links.
318 The format must contain one or two %s instances. The first one
319 will be filled with the link, the second with its description."
320 :group 'org-export-latex
321 :version "24.1"
322 :type 'string)
324 (defcustom org-export-latex-footnote-separator "\\textsuperscript{,}\\,"
325 "Text used to separate footnotes."
326 :group 'org-export-latex
327 :version "24.1"
328 :type 'string)
330 (defcustom org-export-latex-quotes
331 '(("fr" ("\\(\\s-\\|[[(]\\)\"" . "«~") ("\\(\\S-\\)\"" . "~»") ("\\(\\s-\\|(\\)'" . "'"))
332 ("en" ("\\(\\s-\\|[[(]\\)\"" . "``") ("\\(\\S-\\)\"" . "''") ("\\(\\s-\\|(\\)'" . "`")))
333 "Alist for quotes to use when converting english double-quotes.
335 The CAR of each item in this alist is the language code.
336 The CDR of each item in this alist is a list of three CONS:
337 - the first CONS defines the opening quote;
338 - the second CONS defines the closing quote;
339 - the last CONS defines single quotes.
341 For each item in a CONS, the first string is a regexp
342 for allowed characters before/after the quote, the second
343 string defines the replacement string for this quote."
344 :group 'org-export-latex
345 :version "24.1"
346 :type '(list
347 (cons :tag "Opening quote"
348 (string :tag "Regexp for char before")
349 (string :tag "Replacement quote "))
350 (cons :tag "Closing quote"
351 (string :tag "Regexp for char after ")
352 (string :tag "Replacement quote "))
353 (cons :tag "Single quote"
354 (string :tag "Regexp for char before")
355 (string :tag "Replacement quote "))))
357 (defcustom org-export-latex-tables-verbatim nil
358 "When non-nil, tables are exported verbatim."
359 :group 'org-export-latex
360 :type 'boolean)
362 (defcustom org-export-latex-tables-centered t
363 "When non-nil, tables are exported in a center environment."
364 :group 'org-export-latex
365 :type 'boolean)
367 (defcustom org-export-latex-table-caption-above t
368 "When non-nil, the caption is set above the table. When nil,
369 the caption is set below the table."
370 :group 'org-export-latex
371 :version "24.1"
372 :type 'boolean)
374 (defcustom org-export-latex-tables-column-borders nil
375 "When non-nil, grouping columns can cause outer vertical lines in tables.
376 When nil, grouping causes only separation lines between groups."
377 :group 'org-export-latex
378 :type 'boolean)
380 (defcustom org-export-latex-low-levels 'itemize
381 "How to convert sections below the current level of sectioning.
382 This is specified by the `org-export-headline-levels' option or the
383 value of \"H:\" in Org's #+OPTION line.
385 This can be either nil (skip the sections), `description', `itemize',
386 or `enumerate' (convert the sections as the corresponding list type), or
387 a string to be used instead of \\section{%s}. In this latter case,
388 the %s stands here for the inserted headline and is mandatory.
390 It may also be a list of three string to define a user-defined environment
391 that should be used. The first string should be the like
392 \"\\begin{itemize}\", the second should be like \"\\item %s %s\" with up
393 to two occurrences of %s for the title and a label, respectively. The third
394 string should be like \"\\end{itemize\"."
395 :group 'org-export-latex
396 :type '(choice (const :tag "Ignore" nil)
397 (const :tag "Convert as descriptive list" description)
398 (const :tag "Convert as itemized list" itemize)
399 (const :tag "Convert as enumerated list" enumerate)
400 (list :tag "User-defined environment"
401 :value ("\\begin{itemize}" "\\end{itemize}" "\\item %s")
402 (string :tag "Start")
403 (string :tag "End")
404 (string :tag "item"))
405 (string :tag "Use a section string" :value "\\subparagraph{%s}")))
407 (defcustom org-export-latex-list-parameters
408 '(:cbon "$\\boxtimes$" :cboff "$\\Box$" :cbtrans "$\\boxminus$")
409 "Parameters for the LaTeX list exporter.
410 These parameters will be passed on to `org-list-to-latex', which in turn
411 will pass them (combined with the LaTeX default list parameters) to
412 `org-list-to-generic'."
413 :group 'org-export-latex
414 :type 'plist)
416 (defcustom org-export-latex-verbatim-wrap
417 '("\\begin{verbatim}\n" . "\\end{verbatim}")
418 "Environment to be wrapped around a fixed-width section in LaTeX export.
419 This is a cons with two strings, to be added before and after the
420 fixed-with text.
422 Defaults to \\begin{verbatim} and \\end{verbatim}."
423 :group 'org-export-translation
424 :group 'org-export-latex
425 :type '(cons (string :tag "Open")
426 (string :tag "Close")))
428 (defcustom org-export-latex-listings nil
429 "Non-nil means export source code using the listings package.
430 This package will fontify source code, possibly even with color.
431 If you want to use this, you also need to make LaTeX use the
432 listings package, and if you want to have color, the color
433 package. Just add these to `org-export-latex-packages-alist',
434 for example using customize, or with something like
436 (require 'org-latex)
437 (add-to-list 'org-export-latex-packages-alist '(\"\" \"listings\"))
438 (add-to-list 'org-export-latex-packages-alist '(\"\" \"color\"))
440 Alternatively,
442 (setq org-export-latex-listings 'minted)
444 causes source code to be exported using the minted package as
445 opposed to listings. If you want to use minted, you need to add
446 the minted package to `org-export-latex-packages-alist', for
447 example using customize, or with
449 (require 'org-latex)
450 (add-to-list 'org-export-latex-packages-alist '(\"\" \"minted\"))
452 In addition, it is necessary to install
453 pygments (http://pygments.org), and to configure the variable
454 `org-latex-to-pdf-process' so that the -shell-escape option is
455 passed to pdflatex.
457 :group 'org-export-latex
458 :type 'boolean)
460 (defcustom org-export-latex-listings-langs
461 '((emacs-lisp "Lisp") (lisp "Lisp") (clojure "Lisp")
462 (c "C") (cc "C++")
463 (fortran "fortran")
464 (perl "Perl") (cperl "Perl") (python "Python") (ruby "Ruby")
465 (html "HTML") (xml "XML")
466 (tex "TeX") (latex "TeX")
467 (shell-script "bash")
468 (gnuplot "Gnuplot")
469 (ocaml "Caml") (caml "Caml")
470 (sql "SQL") (sqlite "sql"))
471 "Alist mapping languages to their listing language counterpart.
472 The key is a symbol, the major mode symbol without the \"-mode\".
473 The value is the string that should be inserted as the language parameter
474 for the listings package. If the mode name and the listings name are
475 the same, the language does not need an entry in this list - but it does not
476 hurt if it is present."
477 :group 'org-export-latex
478 :type '(repeat
479 (list
480 (symbol :tag "Major mode ")
481 (string :tag "Listings language"))))
483 (defcustom org-export-latex-listings-w-names t
484 "Non-nil means export names of named code blocks.
485 Code blocks exported with the listings package (controlled by the
486 `org-export-latex-listings' variable) can be named in the style
487 of noweb."
488 :group 'org-export-latex
489 :version "24.1"
490 :type 'boolean)
492 (defcustom org-export-latex-minted-langs
493 '((emacs-lisp "common-lisp")
494 (cc "c++")
495 (cperl "perl")
496 (shell-script "bash")
497 (caml "ocaml"))
498 "Alist mapping languages to their minted language counterpart.
499 The key is a symbol, the major mode symbol without the \"-mode\".
500 The value is the string that should be inserted as the language parameter
501 for the minted package. If the mode name and the listings name are
502 the same, the language does not need an entry in this list - but it does not
503 hurt if it is present.
505 Note that minted uses all lower case for language identifiers,
506 and that the full list of language identifiers can be obtained
507 with:
508 pygmentize -L lexers
510 :group 'org-export-latex
511 :version "24.1"
512 :type '(repeat
513 (list
514 (symbol :tag "Major mode ")
515 (string :tag "Listings language"))))
517 (defcustom org-export-latex-listings-options nil
518 "Association list of options for the latex listings package.
520 These options are supplied as a comma-separated list to the
521 \\lstset command. Each element of the association list should be
522 a list containing two strings: the name of the option, and the
523 value. For example,
525 (setq org-export-latex-listings-options
526 '((\"basicstyle\" \"\\small\")
527 (\"keywordstyle\" \"\\color{black}\\bfseries\\underbar\")))
529 will typeset the code in a small size font with underlined, bold
530 black keywords.
532 Note that the same options will be applied to blocks of all
533 languages."
534 :group 'org-export-latex
535 :version "24.1"
536 :type '(repeat
537 (list
538 (string :tag "Listings option name ")
539 (string :tag "Listings option value"))))
541 (defcustom org-export-latex-minted-options nil
542 "Association list of options for the latex minted package.
544 These options are supplied within square brackets in
545 \\begin{minted} environments. Each element of the alist should be
546 a list containing two strings: the name of the option, and the
547 value. For example,
549 (setq org-export-latex-minted-options
550 '((\"bgcolor\" \"bg\") (\"frame\" \"lines\")))
552 will result in src blocks being exported with
554 \\begin{minted}[bgcolor=bg,frame=lines]{<LANG>}
556 as the start of the minted environment. Note that the same
557 options will be applied to blocks of all languages."
558 :group 'org-export-latex
559 :version "24.1"
560 :type '(repeat
561 (list
562 (string :tag "Minted option name ")
563 (string :tag "Minted option value"))))
565 (defvar org-export-latex-custom-lang-environments nil
566 "Association list mapping languages to language-specific latex
567 environments used during export of src blocks by the listings
568 and minted latex packages. For example,
570 (setq org-export-latex-custom-lang-environments
571 '((python \"pythoncode\")))
573 would have the effect that if org encounters begin_src python
574 during latex export it will output
576 \\begin{pythoncode}
577 <src block body>
578 \\end{pythoncode}")
580 (defcustom org-export-latex-remove-from-headlines
581 '(:todo nil :priority nil :tags nil)
582 "A plist of keywords to remove from headlines. OBSOLETE.
583 Non-nil means remove this keyword type from the headline.
585 Don't remove the keys, just change their values.
587 Obsolete, this variable is no longer used. Use the separate
588 variables `org-export-with-todo-keywords', `org-export-with-priority',
589 and `org-export-with-tags' instead."
590 :type 'plist
591 :group 'org-export-latex)
593 (defcustom org-export-latex-image-default-option "width=.9\\linewidth"
594 "Default option for images."
595 :group 'org-export-latex
596 :type 'string)
598 (defcustom org-latex-default-figure-position "htb"
599 "Default position for latex figures."
600 :group 'org-export-latex
601 :version "24.1"
602 :type 'string)
604 (defcustom org-export-latex-tabular-environment "tabular"
605 "Default environment used to build tables."
606 :group 'org-export-latex
607 :version "24.1"
608 :type 'string)
610 (defcustom org-export-latex-inline-image-extensions
611 '("pdf" "jpeg" "jpg" "png" "ps" "eps")
612 "Extensions of image files that can be inlined into LaTeX.
613 Note that the image extension *actually* allowed depend on the way the
614 LaTeX file is processed. When used with pdflatex, pdf, jpg and png images
615 are OK. When processing through dvi to Postscript, only ps and eps are
616 allowed. The default we use here encompasses both."
617 :group 'org-export-latex
618 :type '(repeat (string :tag "Extension")))
620 (defcustom org-export-latex-coding-system nil
621 "Coding system for the exported LaTeX file."
622 :group 'org-export-latex
623 :type 'coding-system)
625 (defgroup org-export-pdf nil
626 "Options for exporting Org-mode files to PDF, via LaTeX."
627 :tag "Org Export PDF"
628 :group 'org-export-latex
629 :group 'org-export)
631 (defcustom org-latex-to-pdf-process
632 '("pdflatex -interaction nonstopmode -output-directory %o %f"
633 "pdflatex -interaction nonstopmode -output-directory %o %f"
634 "pdflatex -interaction nonstopmode -output-directory %o %f")
635 "Commands to process a LaTeX file to a PDF file.
636 This is a list of strings, each of them will be given to the shell
637 as a command. %f in the command will be replaced by the full file name, %b
638 by the file base name (i.e. without extension) and %o by the base directory
639 of the file.
641 The reason why this is a list is that it usually takes several runs of
642 `pdflatex', maybe mixed with a call to `bibtex'. Org does not have a clever
643 mechanism to detect which of these commands have to be run to get to a stable
644 result, and it also does not do any error checking.
646 By default, Org uses 3 runs of `pdflatex' to do the processing. If you
647 have texi2dvi on your system and if that does not cause the infamous
648 egrep/locale bug:
650 http://lists.gnu.org/archive/html/bug-texinfo/2010-03/msg00031.html
652 then `texi2dvi' is the superior choice. Org does offer it as one
653 of the customize options.
655 Alternatively, this may be a Lisp function that does the processing, so you
656 could use this to apply the machinery of AUCTeX or the Emacs LaTeX mode.
657 This function should accept the file name as its single argument."
658 :group 'org-export-pdf
659 :type '(choice
660 (repeat :tag "Shell command sequence"
661 (string :tag "Shell command"))
662 (const :tag "2 runs of pdflatex"
663 ("pdflatex -interaction nonstopmode -output-directory %o %f"
664 "pdflatex -interaction nonstopmode -output-directory %o %f"))
665 (const :tag "3 runs of pdflatex"
666 ("pdflatex -interaction nonstopmode -output-directory %o %f"
667 "pdflatex -interaction nonstopmode -output-directory %o %f"
668 "pdflatex -interaction nonstopmode -output-directory %o %f"))
669 (const :tag "pdflatex,bibtex,pdflatex,pdflatex"
670 ("pdflatex -interaction nonstopmode -output-directory %o %f"
671 "bibtex %b"
672 "pdflatex -interaction nonstopmode -output-directory %o %f"
673 "pdflatex -interaction nonstopmode -output-directory %o %f"))
674 (const :tag "2 runs of xelatex"
675 ("xelatex -interaction nonstopmode -output-directory %o %f"
676 "xelatex -interaction nonstopmode -output-directory %o %f"))
677 (const :tag "3 runs of xelatex"
678 ("xelatex -interaction nonstopmode -output-directory %o %f"
679 "xelatex -interaction nonstopmode -output-directory %o %f"
680 "xelatex -interaction nonstopmode -output-directory %o %f"))
681 (const :tag "xelatex,bibtex,xelatex,xelatex"
682 ("xelatex -interaction nonstopmode -output-directory %o %f"
683 "bibtex %b"
684 "xelatex -interaction nonstopmode -output-directory %o %f"
685 "xelatex -interaction nonstopmode -output-directory %o %f"))
686 (const :tag "texi2dvi"
687 ("texi2dvi -p -b -c -V %f"))
688 (const :tag "rubber"
689 ("rubber -d --into %o %f"))
690 (function)))
692 (defcustom org-export-pdf-logfiles
693 '("aux" "idx" "log" "out" "toc" "nav" "snm" "vrb")
694 "The list of file extensions to consider as LaTeX logfiles."
695 :group 'org-export-pdf
696 :version "24.1"
697 :type '(repeat (string :tag "Extension")))
699 (defcustom org-export-pdf-remove-logfiles t
700 "Non-nil means remove the logfiles produced by PDF production.
701 These are the .aux, .log, .out, and .toc files."
702 :group 'org-export-pdf
703 :type 'boolean)
705 ;;; Hooks
707 (defvar org-export-latex-after-initial-vars-hook nil
708 "Hook run before LaTeX export.
709 The exact moment is after the initial variables like org-export-latex-class
710 have been determined from the environment.")
712 (defvar org-export-latex-after-blockquotes-hook nil
713 "Hook run during LaTeX export, after blockquote, verse, center are done.")
715 (defvar org-export-latex-final-hook nil
716 "Hook run in the finalized LaTeX buffer.")
718 (defvar org-export-latex-after-save-hook nil
719 "Hook run in the finalized LaTeX buffer, after it has been saved.")
721 ;;; Autoload functions:
723 ;;;###autoload
724 (defun org-export-as-latex-batch ()
725 "Call `org-export-as-latex', may be used in batch processing.
726 For example:
728 emacs --batch
729 --load=$HOME/lib/emacs/org.el
730 --eval \"(setq org-export-headline-levels 2)\"
731 --visit=MyFile --funcall org-export-as-latex-batch"
732 (org-export-as-latex org-export-headline-levels 'hidden))
734 ;;;###autoload
735 (defun org-export-as-latex-to-buffer (arg)
736 "Call `org-export-as-latex` with output to a temporary buffer.
737 No file is created. The prefix ARG is passed through to `org-export-as-latex'."
738 (interactive "P")
739 (org-export-as-latex arg nil nil "*Org LaTeX Export*")
740 (when org-export-show-temporary-export-buffer
741 (switch-to-buffer-other-window "*Org LaTeX Export*")))
743 ;;;###autoload
744 (defun org-replace-region-by-latex (beg end)
745 "Replace the region from BEG to END with its LaTeX export.
746 It assumes the region has `org-mode' syntax, and then convert it to
747 LaTeX. This can be used in any buffer. For example, you could
748 write an itemized list in `org-mode' syntax in an LaTeX buffer and
749 then use this command to convert it."
750 (interactive "r")
751 (let (reg latex buf)
752 (save-window-excursion
753 (if (eq major-mode 'org-mode)
754 (setq latex (org-export-region-as-latex
755 beg end t 'string))
756 (setq reg (buffer-substring beg end)
757 buf (get-buffer-create "*Org tmp*"))
758 (with-current-buffer buf
759 (erase-buffer)
760 (insert reg)
761 (org-mode)
762 (setq latex (org-export-region-as-latex
763 (point-min) (point-max) t 'string)))
764 (kill-buffer buf)))
765 (delete-region beg end)
766 (insert latex)))
768 ;;;###autoload
769 (defun org-export-region-as-latex (beg end &optional body-only buffer)
770 "Convert region from BEG to END in `org-mode' buffer to LaTeX.
771 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
772 contents, and only produce the region of converted text, useful for
773 cut-and-paste operations.
774 If BUFFER is a buffer or a string, use/create that buffer as a target
775 of the converted LaTeX. If BUFFER is the symbol `string', return the
776 produced LaTeX as a string and leave no buffer behind. For example,
777 a Lisp program could call this function in the following way:
779 (setq latex (org-export-region-as-latex beg end t 'string))
781 When called interactively, the output buffer is selected, and shown
782 in a window. A non-interactive call will only return the buffer."
783 (interactive "r\nP")
784 (when (org-called-interactively-p 'any)
785 (setq buffer "*Org LaTeX Export*"))
786 (let ((transient-mark-mode t) (zmacs-regions t)
787 ext-plist rtn)
788 (setq ext-plist (plist-put ext-plist :ignore-subtree-p t))
789 (goto-char end)
790 (set-mark (point)) ;; to activate the region
791 (goto-char beg)
792 (setq rtn (org-export-as-latex
793 nil nil ext-plist
794 buffer body-only))
795 (if (fboundp 'deactivate-mark) (deactivate-mark))
796 (if (and (org-called-interactively-p 'any) (bufferp rtn))
797 (switch-to-buffer-other-window rtn)
798 rtn)))
800 ;;;###autoload
801 (defun org-export-as-latex (arg &optional hidden ext-plist
802 to-buffer body-only pub-dir)
803 "Export current buffer to a LaTeX file.
804 If there is an active region, export only the region. The prefix
805 ARG specifies how many levels of the outline should become
806 headlines. The default is 3. Lower levels will be exported
807 depending on `org-export-latex-low-levels'. The default is to
808 convert them as description lists.
809 HIDDEN is obsolete and does nothing.
810 EXT-PLIST is a property list with
811 external parameters overriding org-mode's default settings, but
812 still inferior to file-local settings. When TO-BUFFER is
813 non-nil, create a buffer with that name and export to that
814 buffer. If TO-BUFFER is the symbol `string', don't leave any
815 buffer behind but just return the resulting LaTeX as a string.
816 When BODY-ONLY is set, don't produce the file header and footer,
817 simply return the content of \\begin{document}...\\end{document},
818 without even the \\begin{document} and \\end{document} commands.
819 when PUB-DIR is set, use this as the publishing directory."
820 (interactive "P")
821 (when (and (not body-only) arg (listp arg)) (setq body-only t))
822 (run-hooks 'org-export-first-hook)
824 ;; Make sure we have a file name when we need it.
825 (when (and (not (or to-buffer body-only))
826 (not buffer-file-name))
827 (if (buffer-base-buffer)
828 (org-set-local 'buffer-file-name
829 (with-current-buffer (buffer-base-buffer)
830 buffer-file-name))
831 (error "Need a file name to be able to export")))
833 (message "Exporting to LaTeX...")
834 (org-unmodified
835 (let ((inhibit-read-only t))
836 (remove-text-properties (point-min) (point-max)
837 '(:org-license-to-kill nil))))
838 (org-update-radio-target-regexp)
839 (org-export-latex-set-initial-vars ext-plist arg)
840 (setq org-export-opt-plist org-export-latex-options-plist
841 org-export-footnotes-data (org-footnote-all-labels 'with-defs)
842 org-export-footnotes-seen nil
843 org-export-latex-footmark-seen nil)
844 (org-install-letbind)
845 (run-hooks 'org-export-latex-after-initial-vars-hook)
846 (let* ((wcf (current-window-configuration))
847 (opt-plist
848 (org-export-process-option-filters org-export-latex-options-plist))
849 (region-p (org-region-active-p))
850 (rbeg (and region-p (region-beginning)))
851 (rend (and region-p (region-end)))
852 (subtree-p
853 (if (plist-get opt-plist :ignore-subtree-p)
855 (when region-p
856 (save-excursion
857 (goto-char rbeg)
858 (and (org-at-heading-p)
859 (>= (org-end-of-subtree t t) rend))))))
860 (opt-plist (setq org-export-opt-plist
861 (if subtree-p
862 (org-export-add-subtree-options opt-plist rbeg)
863 opt-plist)))
864 ;; Make sure the variable contains the updated values.
865 (org-export-latex-options-plist (setq org-export-opt-plist opt-plist))
866 ;; The following two are dynamically scoped into other
867 ;; routines below.
868 (org-current-export-dir
869 (or pub-dir (org-export-directory :html opt-plist)))
870 (org-current-export-file buffer-file-name)
871 (title (or (and subtree-p (org-export-get-title-from-subtree))
872 (plist-get opt-plist :title)
873 (and (not
874 (plist-get opt-plist :skip-before-1st-heading))
875 (org-export-grab-title-from-buffer))
876 (and buffer-file-name
877 (file-name-sans-extension
878 (file-name-nondirectory buffer-file-name)))
879 "No Title"))
880 (filename
881 (and (not to-buffer)
882 (concat
883 (file-name-as-directory
884 (or pub-dir
885 (org-export-directory :LaTeX org-export-latex-options-plist)))
886 (file-name-sans-extension
887 (or (and subtree-p
888 (org-entry-get rbeg "EXPORT_FILE_NAME" t))
889 (file-name-nondirectory ;sans-extension
890 (or buffer-file-name
891 (error "Don't know which export file to use")))))
892 ".tex")))
893 (filename
894 (and filename
895 (if (equal (file-truename filename)
896 (file-truename (or buffer-file-name "dummy.org")))
897 (concat filename ".tex")
898 filename)))
899 (auto-insert nil); Avoid any auto-insert stuff for the new file
900 (TeX-master (boundp 'TeX-master))
901 (buffer (if to-buffer
902 (cond
903 ((eq to-buffer 'string) (get-buffer-create
904 "*Org LaTeX Export*"))
905 (t (get-buffer-create to-buffer)))
906 (find-file-noselect filename)))
907 (odd org-odd-levels-only)
908 (header (org-export-latex-make-header title opt-plist))
909 (skip (cond (subtree-p nil)
910 (region-p nil)
911 (t (plist-get opt-plist :skip-before-1st-heading))))
912 (text (plist-get opt-plist :text))
913 (org-export-preprocess-hook
914 (cons
915 `(lambda () (org-set-local 'org-complex-heading-regexp
916 ,org-export-latex-complex-heading-re))
917 org-export-preprocess-hook))
918 (first-lines (if skip "" (org-export-latex-first-lines
919 opt-plist
920 (if subtree-p
921 (save-excursion
922 (goto-char rbeg)
923 (point-at-bol 2))
924 rbeg)
925 (if region-p rend))))
926 (coding-system (and (boundp 'buffer-file-coding-system)
927 buffer-file-coding-system))
928 (coding-system-for-write (or org-export-latex-coding-system
929 coding-system))
930 (save-buffer-coding-system (or org-export-latex-coding-system
931 coding-system))
932 (region (buffer-substring
933 (if region-p (region-beginning) (point-min))
934 (if region-p (region-end) (point-max))))
935 (text
936 (and text (string-match "\\S-" text)
937 (org-export-preprocess-string
938 text
939 :emph-multiline t
940 :for-backend 'latex
941 :comments nil
942 :tags (plist-get opt-plist :tags)
943 :priority (plist-get opt-plist :priority)
944 :footnotes (plist-get opt-plist :footnotes)
945 :drawers (plist-get opt-plist :drawers)
946 :timestamps (plist-get opt-plist :timestamps)
947 :todo-keywords (plist-get opt-plist :todo-keywords)
948 :tasks (plist-get opt-plist :tasks)
949 :add-text nil
950 :skip-before-1st-heading skip
951 :select-tags nil
952 :exclude-tags nil
953 :LaTeX-fragments nil)))
954 (string-for-export
955 (org-export-preprocess-string
956 region
957 :emph-multiline t
958 :for-backend 'latex
959 :comments nil
960 :tags (plist-get opt-plist :tags)
961 :priority (plist-get opt-plist :priority)
962 :footnotes (plist-get opt-plist :footnotes)
963 :drawers (plist-get opt-plist :drawers)
964 :timestamps (plist-get opt-plist :timestamps)
965 :todo-keywords (plist-get opt-plist :todo-keywords)
966 :tasks (plist-get opt-plist :tasks)
967 :add-text (if (eq to-buffer 'string) nil text)
968 :skip-before-1st-heading skip
969 :select-tags (plist-get opt-plist :select-tags)
970 :exclude-tags (plist-get opt-plist :exclude-tags)
971 :LaTeX-fragments nil)))
973 (set-buffer buffer)
974 (erase-buffer)
975 (org-install-letbind)
977 (and (fboundp 'set-buffer-file-coding-system)
978 (set-buffer-file-coding-system coding-system-for-write))
980 ;; insert the header and initial document commands
981 (unless (or (eq to-buffer 'string) body-only)
982 (insert header))
984 ;; insert text found in #+TEXT
985 (when (and text (not (eq to-buffer 'string)))
986 (insert (org-export-latex-content
987 text '(lists tables fixed-width keywords))
988 "\n\n"))
990 ;; insert lines before the first headline
991 (unless (or skip (string-match "^\\*" first-lines))
992 (insert first-lines))
994 ;; export the content of headlines
995 (org-export-latex-global
996 (with-temp-buffer
997 (insert string-for-export)
998 (goto-char (point-min))
999 (when (re-search-forward "^\\(\\*+\\) " nil t)
1000 (let* ((asters (length (match-string 1)))
1001 (level (if odd (- asters 2) (- asters 1))))
1002 (setq org-export-latex-add-level
1003 (if odd (1- (/ (1+ asters) 2)) (1- asters)))
1004 (org-export-latex-parse-global level odd)))))
1006 ;; finalization
1007 (unless body-only (insert "\n\\end{document}"))
1009 ;; Attach description terms to the \item macro
1010 (goto-char (point-min))
1011 (while (re-search-forward "^[ \t]*\\\\item\\([ \t]+\\)\\[" nil t)
1012 (delete-region (match-beginning 1) (match-end 1)))
1014 ;; Relocate the table of contents
1015 (goto-char (point-min))
1016 (when (re-search-forward "\\[TABLE-OF-CONTENTS\\]" nil t)
1017 (goto-char (point-min))
1018 (while (re-search-forward "\\\\tableofcontents\\>[ \t]*\n?" nil t)
1019 (replace-match ""))
1020 (goto-char (point-min))
1021 (and (re-search-forward "\\[TABLE-OF-CONTENTS\\]" nil t)
1022 (replace-match "\\tableofcontents" t t)))
1024 ;; Cleanup forced line ends in items where they are not needed
1025 (goto-char (point-min))
1026 (while (re-search-forward
1027 "^[ \t]*\\\\item\\>.*\\(\\\\\\\\\\)[ \t]*\\(\n\\\\label.*\\)*\n\\\\begin"
1028 nil t)
1029 (delete-region (match-beginning 1) (match-end 1)))
1030 (goto-char (point-min))
1031 (while (re-search-forward
1032 "^[ \t]*\\\\item\\>.*\\(\\\\\\\\\\)[ \t]*\\(\n\\\\label.*\\)*"
1033 nil t)
1034 (if (looking-at "[\n \t]+")
1035 (replace-match "\n")))
1037 ;; Ensure we have a final newline
1038 (goto-char (point-max))
1039 (or (eq (char-before) ?\n)
1040 (insert ?\n))
1042 (run-hooks 'org-export-latex-final-hook)
1043 (if to-buffer
1044 (unless (eq major-mode 'latex-mode) (latex-mode))
1045 (save-buffer))
1046 (org-export-latex-fix-inputenc)
1047 (run-hooks 'org-export-latex-after-save-hook)
1048 (goto-char (point-min))
1049 (or (org-export-push-to-kill-ring "LaTeX")
1050 (message "Exporting to LaTeX...done"))
1051 (prog1
1052 (if (eq to-buffer 'string)
1053 (prog1 (buffer-substring (point-min) (point-max))
1054 (kill-buffer (current-buffer)))
1055 (current-buffer))
1056 (set-window-configuration wcf))))
1058 ;;;###autoload
1059 (defun org-export-as-pdf (arg &optional hidden ext-plist
1060 to-buffer body-only pub-dir)
1061 "Export as LaTeX, then process through to PDF."
1062 (interactive "P")
1063 (message "Exporting to PDF...")
1064 (let* ((wconfig (current-window-configuration))
1065 (lbuf (org-export-as-latex arg hidden ext-plist
1066 to-buffer body-only pub-dir))
1067 (file (buffer-file-name lbuf))
1068 (base (file-name-sans-extension (buffer-file-name lbuf)))
1069 (pdffile (concat base ".pdf"))
1070 (cmds (if (eq org-export-latex-listings 'minted)
1071 ;; automatically add -shell-escape when needed
1072 (mapcar (lambda (cmd)
1073 (replace-regexp-in-string
1074 "pdflatex " "pdflatex -shell-escape " cmd))
1075 org-latex-to-pdf-process)
1076 org-latex-to-pdf-process))
1077 (outbuf (get-buffer-create "*Org PDF LaTeX Output*"))
1078 (bibtex-p (with-current-buffer lbuf
1079 (save-excursion
1080 (goto-char (point-min))
1081 (re-search-forward "\\\\bibliography{" nil t))))
1082 cmd output-dir errors)
1083 (with-current-buffer outbuf (erase-buffer))
1084 (message (concat "Processing LaTeX file " file "..."))
1085 (setq output-dir (file-name-directory file))
1086 (with-current-buffer lbuf
1087 (save-excursion
1088 (if (and cmds (symbolp cmds))
1089 (funcall cmds (shell-quote-argument file))
1090 (while cmds
1091 (setq cmd (pop cmds))
1092 (while (string-match "%b" cmd)
1093 (setq cmd (replace-match
1094 (save-match-data
1095 (shell-quote-argument base))
1096 t t cmd)))
1097 (while (string-match "%f" cmd)
1098 (setq cmd (replace-match
1099 (save-match-data
1100 (shell-quote-argument file))
1101 t t cmd)))
1102 (while (string-match "%o" cmd)
1103 (setq cmd (replace-match
1104 (save-match-data
1105 (shell-quote-argument output-dir))
1106 t t cmd)))
1107 (shell-command cmd outbuf)))))
1108 (message (concat "Processing LaTeX file " file "...done"))
1109 (setq errors (org-export-latex-get-error outbuf))
1110 (if (not (file-exists-p pdffile))
1111 (error (concat "PDF file " pdffile " was not produced"
1112 (if errors (concat ":" errors "") "")))
1113 (set-window-configuration wconfig)
1114 (when org-export-pdf-remove-logfiles
1115 (dolist (ext org-export-pdf-logfiles)
1116 (setq file (concat base "." ext))
1117 (and (file-exists-p file) (delete-file file))))
1118 (message (concat
1119 "Exporting to PDF...done"
1120 (if errors
1121 (concat ", with some errors:" errors)
1122 "")))
1123 pdffile)))
1125 (defun org-export-latex-get-error (buf)
1126 "Collect the kinds of errors that remain in pdflatex processing."
1127 (with-current-buffer buf
1128 (save-excursion
1129 (goto-char (point-max))
1130 (when (re-search-backward "^[ \t]*This is pdf.*?TeX.*?Version" nil t)
1131 ;; OK, we are at the location of the final run
1132 (let ((pos (point)) (errors "") (case-fold-search t))
1133 (if (re-search-forward "Reference.*?undefined" nil t)
1134 (setq errors (concat errors " [undefined reference]")))
1135 (goto-char pos)
1136 (if (re-search-forward "Citation.*?undefined" nil t)
1137 (setq errors (concat errors " [undefined citation]")))
1138 (goto-char pos)
1139 (if (re-search-forward "Undefined control sequence" nil t)
1140 (setq errors (concat errors " [undefined control sequence]")))
1141 (and (org-string-nw-p errors) errors))))))
1143 ;;;###autoload
1144 (defun org-export-as-pdf-and-open (arg)
1145 "Export as LaTeX, then process through to PDF, and open."
1146 (interactive "P")
1147 (let ((pdffile (org-export-as-pdf arg)))
1148 (if pdffile
1149 (progn
1150 (org-open-file pdffile)
1151 (when org-export-kill-product-buffer-when-displayed
1152 (kill-buffer (find-buffer-visiting
1153 (concat (file-name-sans-extension (buffer-file-name))
1154 ".tex")))))
1155 (error "PDF file was not produced"))))
1157 ;;; Parsing functions:
1159 (defun org-export-latex-parse-global (level odd)
1160 "Parse the current buffer recursively, starting at LEVEL.
1161 If ODD is non-nil, assume the buffer only contains odd sections.
1162 Return a list reflecting the document structure."
1163 (save-excursion
1164 (goto-char (point-min))
1165 (let* ((cnt 0) output
1166 (depth org-export-latex-sectioning-depth))
1167 (while (org-re-search-forward-unprotected
1168 (concat "^\\(\\(?:\\*\\)\\{"
1169 (number-to-string (+ (if odd 2 1) level))
1170 "\\}\\) \\(.*\\)$")
1171 ;; make sure that there is no upper heading
1172 (when (> level 0)
1173 (save-excursion
1174 (save-match-data
1175 (org-re-search-forward-unprotected
1176 (concat "^\\(\\(?:\\*\\)\\{"
1177 (number-to-string level)
1178 "\\}\\) \\(.*\\)$") nil t)))) t)
1179 (setq cnt (1+ cnt))
1180 (let* ((pos (match-beginning 0))
1181 (heading (match-string 2))
1182 (nlevel (if odd (/ (+ 3 level) 2) (1+ level))))
1183 (save-excursion
1184 (narrow-to-region
1185 (point)
1186 (save-match-data
1187 (if (org-re-search-forward-unprotected
1188 (concat "^\\(\\(?:\\*\\)\\{"
1189 (number-to-string (+ (if odd 2 1) level))
1190 "\\}\\) \\(.*\\)$") nil t)
1191 (match-beginning 0)
1192 (point-max))))
1193 (goto-char (point-min))
1194 (setq output
1195 (append output
1196 (list
1197 (list
1198 `(pos . ,pos)
1199 `(level . ,nlevel)
1200 `(occur . ,cnt)
1201 `(heading . ,heading)
1202 `(content . ,(org-export-latex-parse-content))
1203 `(subcontent . ,(org-export-latex-parse-subcontent
1204 level odd)))))))
1205 (widen)))
1206 (list output))))
1208 (defun org-export-latex-parse-content ()
1209 "Extract the content of a section."
1210 (let ((beg (point))
1211 (end (if (org-re-search-forward-unprotected "^\\(\\*\\)+ .*$" nil t)
1212 (progn (beginning-of-line) (point))
1213 (point-max))))
1214 (buffer-substring beg end)))
1216 (defun org-export-latex-parse-subcontent (level odd)
1217 "Extract the subcontent of a section at LEVEL.
1218 If ODD Is non-nil, assume subcontent only contains odd sections."
1219 (if (not (org-re-search-forward-unprotected
1220 (concat "^\\(\\(?:\\*\\)\\{"
1221 (number-to-string (+ (if odd 4 2) level))
1222 "\\}\\) \\(.*\\)$")
1223 nil t))
1224 nil ; subcontent is nil
1225 (org-export-latex-parse-global (+ (if odd 2 1) level) odd)))
1227 ;;; Rendering functions:
1228 (defun org-export-latex-global (content)
1229 "Export CONTENT to LaTeX.
1230 CONTENT is an element of the list produced by
1231 `org-export-latex-parse-global'."
1232 (if (eq (car content) 'subcontent)
1233 (mapc 'org-export-latex-sub (cdr content))
1234 (org-export-latex-sub (car content))))
1236 (defun org-export-latex-sub (subcontent)
1237 "Export the list SUBCONTENT to LaTeX.
1238 SUBCONTENT is an alist containing information about the headline
1239 and its content."
1240 (let ((num (plist-get org-export-latex-options-plist :section-numbers)))
1241 (mapc (lambda(x) (org-export-latex-subcontent x num)) subcontent)))
1243 (defun org-export-latex-subcontent (subcontent num)
1244 "Export each cell of SUBCONTENT to LaTeX.
1245 If NUM is non-nil export numbered sections, otherwise use unnumbered
1246 sections. If NUM is an integer, export the highest NUM levels as
1247 numbered sections and lower levels as unnumbered sections."
1248 (let* ((heading (cdr (assoc 'heading subcontent)))
1249 (level (- (cdr (assoc 'level subcontent))
1250 org-export-latex-add-level))
1251 (occur (number-to-string (cdr (assoc 'occur subcontent))))
1252 (content (cdr (assoc 'content subcontent)))
1253 (subcontent (cadr (assoc 'subcontent subcontent)))
1254 (label (org-get-text-property-any 0 'target heading))
1255 (label-list (cons label (cdr (assoc label
1256 org-export-target-aliases))))
1257 (sectioning org-export-latex-sectioning)
1258 (depth org-export-latex-sectioning-depth)
1259 main-heading sub-heading ctnt)
1260 (when (symbolp (car sectioning))
1261 (setq sectioning (funcall (car sectioning) level heading))
1262 (when sectioning
1263 (setq heading (car sectioning)
1264 sectioning (cdr sectioning)
1265 ;; target property migh have changed...
1266 label (org-get-text-property-any 0 'target heading)
1267 label-list (cons label (cdr (assoc label
1268 org-export-target-aliases)))))
1269 (if sectioning (setq sectioning (make-list 10 sectioning)))
1270 (setq depth (if sectioning 10000 0)))
1271 (if (string-match "[ \t]*\\\\\\\\[ \t]*" heading)
1272 (setq main-heading (substring heading 0 (match-beginning 0))
1273 sub-heading (substring heading (match-end 0))))
1274 (setq heading (org-export-latex-fontify-headline heading)
1275 sub-heading (and sub-heading
1276 (org-export-latex-fontify-headline sub-heading))
1277 main-heading (and main-heading
1278 (org-export-latex-fontify-headline main-heading)))
1279 (cond
1280 ;; Normal conversion
1281 ((<= level depth)
1282 (let* ((sec (nth (1- level) sectioning))
1283 (num (if (integerp num)
1284 (>= num level)
1285 num))
1286 start end)
1287 (if (consp (cdr sec))
1288 (setq start (nth (if num 0 2) sec)
1289 end (nth (if num 1 3) sec))
1290 (setq start (if num (car sec) (cdr sec))))
1291 (insert (format start (if main-heading main-heading heading)
1292 (or sub-heading "")))
1293 (insert "\n")
1294 (when label
1295 (insert (mapconcat (lambda (l) (format "\\label{%s}" l))
1296 label-list "\n") "\n"))
1297 (insert (org-export-latex-content content))
1298 (cond ((stringp subcontent) (insert subcontent))
1299 ((listp subcontent)
1300 (while (org-looking-back "\n\n") (backward-delete-char 1))
1301 (org-export-latex-sub subcontent)))
1302 (when (and end (string-match "[^ \t]" end))
1303 (let ((hook (org-get-text-property-any 0 'org-insert-hook end)))
1304 (and (functionp hook) (funcall hook)))
1305 (insert end "\n"))))
1306 ;; At a level under the hl option: we can drop this subsection
1307 ((> level depth)
1308 (cond ((eq org-export-latex-low-levels 'description)
1309 (if (string-match "% ends low level$"
1310 (buffer-substring (point-at-bol 0) (point)))
1311 (delete-region (point-at-bol 0) (point))
1312 (insert "\\begin{description}\n"))
1313 (insert (format "\n\\item[%s]%s~\n"
1314 heading
1315 (if label (format "\\label{%s}" label) "")))
1316 (insert (org-export-latex-content content))
1317 (cond ((stringp subcontent) (insert subcontent))
1318 ((listp subcontent) (org-export-latex-sub subcontent)))
1319 (insert "\\end{description} % ends low level\n"))
1320 ((memq org-export-latex-low-levels '(itemize enumerate))
1321 (if (string-match "% ends low level$"
1322 (buffer-substring (point-at-bol 0) (point)))
1323 (delete-region (point-at-bol 0) (point))
1324 (insert (format "\\begin{%s}\n"
1325 (symbol-name org-export-latex-low-levels))))
1326 (let ((ctnt (org-export-latex-content content)))
1327 (insert (format (if (not (equal (replace-regexp-in-string "\n" "" ctnt) ""))
1328 "\n\\item %s\\\\\n%s%%"
1329 "\n\\item %s\n%s%%")
1330 heading
1331 (if label (format "\\label{%s}" label) "")))
1332 (insert ctnt))
1333 (cond ((stringp subcontent) (insert subcontent))
1334 ((listp subcontent) (org-export-latex-sub subcontent)))
1335 (insert (format "\\end{%s} %% ends low level\n"
1336 (symbol-name org-export-latex-low-levels))))
1338 ((and (listp org-export-latex-low-levels)
1339 org-export-latex-low-levels)
1340 (if (string-match "% ends low level$"
1341 (buffer-substring (point-at-bol 0) (point)))
1342 (delete-region (point-at-bol 0) (point))
1343 (insert (car org-export-latex-low-levels) "\n"))
1344 (insert (format (nth 2 org-export-latex-low-levels)
1345 heading
1346 (if label (format "\\label{%s}" label) "")))
1347 (insert (org-export-latex-content content))
1348 (cond ((stringp subcontent) (insert subcontent))
1349 ((listp subcontent) (org-export-latex-sub subcontent)))
1350 (insert (nth 1 org-export-latex-low-levels)
1351 " %% ends low level\n"))
1353 ((stringp org-export-latex-low-levels)
1354 (insert (format org-export-latex-low-levels heading) "\n")
1355 (when label (insert (format "\\label{%s}\n" label)))
1356 (insert (org-export-latex-content content))
1357 (cond ((stringp subcontent) (insert subcontent))
1358 ((listp subcontent) (org-export-latex-sub subcontent)))))))))
1360 ;;; Exporting internals:
1361 (defun org-export-latex-set-initial-vars (ext-plist level)
1362 "Store org local variables required for LaTeX export.
1363 EXT-PLIST is an optional additional plist.
1364 LEVEL indicates the default depth for export."
1365 (setq org-export-latex-todo-keywords-1 org-todo-keywords-1
1366 org-export-latex-done-keywords org-done-keywords
1367 org-export-latex-not-done-keywords org-not-done-keywords
1368 org-export-latex-complex-heading-re org-complex-heading-regexp
1369 org-export-latex-display-custom-times org-display-custom-times
1370 org-export-latex-all-targets-re
1371 (org-make-target-link-regexp (org-all-targets))
1372 org-export-latex-options-plist
1373 (org-combine-plists (org-default-export-plist) ext-plist
1374 (org-infile-export-plist))
1375 org-export-latex-class
1376 (or (and (org-region-active-p)
1377 (save-excursion
1378 (goto-char (region-beginning))
1379 (and (looking-at org-complex-heading-regexp)
1380 (org-entry-get nil "LaTeX_CLASS" 'selective))))
1381 (save-excursion
1382 (save-restriction
1383 (widen)
1384 (goto-char (point-min))
1385 (and (re-search-forward "^#\\+LaTeX_CLASS:[ \t]*\\([-/a-zA-Z]+\\)" nil t)
1386 (match-string 1))))
1387 (plist-get org-export-latex-options-plist :latex-class)
1388 org-export-latex-default-class)
1389 org-export-latex-class-options
1390 (or (and (org-region-active-p)
1391 (save-excursion
1392 (goto-char (region-beginning))
1393 (and (looking-at org-complex-heading-regexp)
1394 (org-entry-get nil "LaTeX_CLASS_OPTIONS" 'selective))))
1395 (save-excursion
1396 (save-restriction
1397 (widen)
1398 (goto-char (point-min))
1399 (and (re-search-forward "^#\\+LaTeX_CLASS_OPTIONS:[ \t]*\\(.*?\\)[ \t]*$" nil t)
1400 (match-string 1))))
1401 (plist-get org-export-latex-options-plist :latex-class-options))
1402 org-export-latex-class
1403 (or (car (assoc org-export-latex-class org-export-latex-classes))
1404 (error "No definition for class `%s' in `org-export-latex-classes'"
1405 org-export-latex-class))
1406 org-export-latex-header
1407 (cadr (assoc org-export-latex-class org-export-latex-classes))
1408 org-export-latex-sectioning
1409 (cddr (assoc org-export-latex-class org-export-latex-classes))
1410 org-export-latex-sectioning-depth
1411 (or level
1412 (let ((hl-levels
1413 (plist-get org-export-latex-options-plist :headline-levels))
1414 (sec-depth (length org-export-latex-sectioning)))
1415 (if (> hl-levels sec-depth) sec-depth hl-levels))))
1416 (when (and org-export-latex-class-options
1417 (string-match "\\S-" org-export-latex-class-options)
1418 (string-match "^[ \t]*\\(\\\\documentclass\\)\\(\\[.*?\\]\\)?"
1419 org-export-latex-header))
1420 (setq org-export-latex-header
1421 (concat (substring org-export-latex-header 0 (match-end 1))
1422 org-export-latex-class-options
1423 (substring org-export-latex-header (match-end 0))))))
1425 (defvar org-export-latex-format-toc-function
1426 'org-export-latex-format-toc-default
1427 "The function formatting returning the string to create the table of contents.
1428 The function mus take one parameter, the depth of the table of contents.")
1430 (defun org-export-latex-make-header (title opt-plist)
1431 "Make the LaTeX header and return it as a string.
1432 TITLE is the current title from the buffer or region.
1433 OPT-PLIST is the options plist for current buffer."
1434 (let ((toc (plist-get opt-plist :table-of-contents))
1435 (author (org-export-apply-macros-in-string
1436 (plist-get opt-plist :author)))
1437 (email (replace-regexp-in-string
1438 "_" "\\\\_"
1439 (org-export-apply-macros-in-string
1440 (plist-get opt-plist :email))))
1441 (description (org-export-apply-macros-in-string
1442 (plist-get opt-plist :description)))
1443 (keywords (org-export-apply-macros-in-string
1444 (plist-get opt-plist :keywords))))
1445 (concat
1446 (if (plist-get opt-plist :time-stamp-file)
1447 (format-time-string "%% Created %Y-%m-%d %a %H:%M\n"))
1448 ;; insert LaTeX custom header and packages from the list
1449 (org-splice-latex-header
1450 (org-export-apply-macros-in-string org-export-latex-header)
1451 org-export-latex-default-packages-alist
1452 org-export-latex-packages-alist nil
1453 (org-export-apply-macros-in-string
1454 (plist-get opt-plist :latex-header-extra)))
1455 ;; append another special variable
1456 (org-export-apply-macros-in-string org-export-latex-append-header)
1457 ;; define alert if not yet defined
1458 "\n\\providecommand{\\alert}[1]{\\textbf{#1}}"
1459 ;; insert the title
1460 (format
1461 "\n\n\\title{%s}\n"
1462 (org-export-latex-fontify-headline title))
1463 ;; insert author info
1464 (if (plist-get opt-plist :author-info)
1465 (format "\\author{%s%s}\n"
1466 (org-export-latex-fontify-headline (or author user-full-name))
1467 (if (and (plist-get opt-plist :email-info) email
1468 (string-match "\\S-" email))
1469 (format "\\thanks{%s}" email)
1470 ""))
1471 (format "%%\\author{%s}\n"
1472 (org-export-latex-fontify-headline (or author user-full-name))))
1473 ;; insert the date
1474 (format "\\date{%s}\n"
1475 (format-time-string
1476 (or (plist-get opt-plist :date)
1477 org-export-latex-date-format)))
1478 ;; add some hyperref options
1479 ;; FIXME: let's have a defcustom for this?
1480 (format "\\hypersetup{\n pdfkeywords={%s},\n pdfsubject={%s},\n pdfcreator={%s}}\n"
1481 (org-export-latex-fontify-headline keywords)
1482 (org-export-latex-fontify-headline description)
1483 (concat "Emacs Org-mode version " org-version))
1484 ;; beginning of the document
1485 "\n\\begin{document}\n\n"
1486 ;; insert the title command
1487 (when (string-match "\\S-" title)
1488 (if (string-match "%s" org-export-latex-title-command)
1489 (format org-export-latex-title-command title)
1490 org-export-latex-title-command))
1491 "\n\n"
1492 ;; table of contents
1493 (when (and org-export-with-toc
1494 (plist-get opt-plist :section-numbers))
1495 (funcall org-export-latex-format-toc-function
1496 (cond ((numberp toc)
1497 (min toc (plist-get opt-plist :headline-levels)))
1498 (toc (plist-get opt-plist :headline-levels))))))))
1500 (defun org-export-latex-format-toc-default (depth)
1501 (when depth
1502 (format "\\setcounter{tocdepth}{%s}\n\\tableofcontents\n\\vspace*{1cm}\n"
1503 depth)))
1505 (defun org-export-latex-first-lines (opt-plist &optional beg end)
1506 "Export the first lines before first headline.
1507 If BEG is non-nil, it is the beginning of the region.
1508 If END is non-nil, it is the end of the region."
1509 (save-excursion
1510 (goto-char (or beg (point-min)))
1511 (let* ((pt (point))
1512 (end (if (re-search-forward
1513 (concat "^" (org-get-limited-outline-regexp)) end t)
1514 (goto-char (match-beginning 0))
1515 (goto-char (or end (point-max))))))
1516 (prog1
1517 (org-export-latex-content
1518 (org-export-preprocess-string
1519 (buffer-substring pt end)
1520 :for-backend 'latex
1521 :emph-multiline t
1522 :add-text nil
1523 :comments nil
1524 :skip-before-1st-heading nil
1525 :LaTeX-fragments nil
1526 :timestamps (plist-get opt-plist :timestamps)
1527 :footnotes (plist-get opt-plist :footnotes)))
1528 (org-unmodified
1529 (let ((inhibit-read-only t)
1530 (limit (max pt (1- end))))
1531 (add-text-properties pt limit
1532 '(:org-license-to-kill t))
1533 (save-excursion
1534 (goto-char pt)
1535 (while (re-search-forward "^[ \t]*#\\+.*\n?" limit t)
1536 (let ((case-fold-search t))
1537 (unless (org-string-match-p
1538 "^[ \t]*#\\+\\(attr_\\|caption\\>\\|label\\>\\)"
1539 (match-string 0))
1540 (remove-text-properties (match-beginning 0) (match-end 0)
1541 '(:org-license-to-kill t))))))))))))
1544 (defvar org-export-latex-header-defs nil
1545 "The header definitions that might be used in the LaTeX body.")
1547 (defun org-export-latex-content (content &optional exclude-list)
1548 "Convert CONTENT string to LaTeX.
1549 Don't perform conversions that are in EXCLUDE-LIST. Recognized
1550 conversion types are: quotation-marks, emphasis, sub-superscript,
1551 links, keywords, lists, tables, fixed-width"
1552 (with-temp-buffer
1553 (org-install-letbind)
1554 (insert content)
1555 (unless (memq 'timestamps exclude-list)
1556 (org-export-latex-time-stamps))
1557 (unless (memq 'quotation-marks exclude-list)
1558 (org-export-latex-quotation-marks))
1559 (unless (memq 'emphasis exclude-list)
1560 (when (plist-get org-export-latex-options-plist :emphasize)
1561 (org-export-latex-fontify)))
1562 (unless (memq 'sub-superscript exclude-list)
1563 (org-export-latex-special-chars
1564 (plist-get org-export-latex-options-plist :sub-superscript)))
1565 (unless (memq 'links exclude-list)
1566 (org-export-latex-links))
1567 (unless (memq 'keywords exclude-list)
1568 (org-export-latex-keywords))
1569 (unless (memq 'lists exclude-list)
1570 (org-export-latex-lists))
1571 (unless (memq 'tables exclude-list)
1572 (org-export-latex-tables
1573 (plist-get org-export-latex-options-plist :tables)))
1574 (unless (memq 'fixed-width exclude-list)
1575 (org-export-latex-fixed-width
1576 (plist-get org-export-latex-options-plist :fixed-width)))
1577 ;; return string
1578 (buffer-substring (point-min) (point-max))))
1580 (defun org-export-latex-protect-string (s)
1581 "Add the org-protected property to string S."
1582 (add-text-properties 0 (length s) '(org-protected t) s) s)
1584 (defun org-export-latex-protect-char-in-string (char-list string)
1585 "Add org-protected text-property to char from CHAR-LIST in STRING."
1586 (with-temp-buffer
1587 (save-match-data
1588 (insert string)
1589 (goto-char (point-min))
1590 (while (re-search-forward (regexp-opt char-list) nil t)
1591 (add-text-properties (match-beginning 0)
1592 (match-end 0) '(org-protected t)))
1593 (buffer-string))))
1595 (defun org-export-latex-keywords-maybe (&optional remove-list)
1596 "Maybe remove keywords depending on rules in REMOVE-LIST."
1597 (goto-char (point-min))
1598 (let ((re-todo (mapconcat 'identity org-export-latex-todo-keywords-1 "\\|"))
1599 (case-fold-search nil)
1600 (todo-markup org-export-latex-todo-keyword-markup)
1601 fmt)
1602 ;; convert TODO keywords
1603 (when (re-search-forward (concat "^\\(" re-todo "\\)") nil t)
1604 (if (plist-get remove-list :todo)
1605 (replace-match "")
1606 (setq fmt (cond
1607 ((stringp todo-markup) todo-markup)
1608 ((and (consp todo-markup) (stringp (car todo-markup)))
1609 (if (member (match-string 1) org-export-latex-done-keywords)
1610 (cdr todo-markup) (car todo-markup)))
1611 (t (cdr (or (assoc (match-string 1) todo-markup)
1612 (car todo-markup))))))
1613 (replace-match (org-export-latex-protect-string
1614 (format fmt (match-string 1))) t t)))
1615 ;; convert priority string
1616 (when (re-search-forward "\\[\\\\#.\\]" nil t)
1617 (if (plist-get remove-list :priority)
1618 (replace-match "")
1619 (replace-match (format "\\textbf{%s}" (match-string 0)) t t)))
1620 ;; convert tags
1621 (when (re-search-forward "\\(:[a-zA-Z0-9_@#%]+\\)+:" nil t)
1622 (if (or (not org-export-with-tags)
1623 (plist-get remove-list :tags))
1624 (replace-match "")
1625 (replace-match
1626 (org-export-latex-protect-string
1627 (format org-export-latex-tag-markup
1628 (save-match-data
1629 (replace-regexp-in-string
1630 "\\([_#]\\)" "\\\\\\1" (match-string 0)))))
1631 t t)))))
1633 (defun org-export-latex-fontify-headline (string)
1634 "Fontify special words in STRING."
1635 (with-temp-buffer
1636 ;; FIXME: org-inside-LaTeX-fragment-p doesn't work when the $...$ is at
1637 ;; the beginning of the buffer - inserting "\n" is safe here though.
1638 (insert "\n" string)
1640 ;; Preserve math snippets
1642 (let* ((matchers (plist-get org-format-latex-options :matchers))
1643 (re-list org-latex-regexps)
1644 beg end re e m n block off)
1645 ;; Check the different regular expressions
1646 (while (setq e (pop re-list))
1647 (setq m (car e) re (nth 1 e) n (nth 2 e)
1648 block (if (nth 3 e) "\n\n" ""))
1649 (setq off (if (member m '("$" "$1")) 1 0))
1650 (when (and (member m matchers) (not (equal m "begin")))
1651 (goto-char (point-min))
1652 (while (re-search-forward re nil t)
1653 (setq beg (+ (match-beginning 0) off) end (- (match-end 0) 0))
1654 (add-text-properties beg end
1655 '(org-protected t org-latex-math t))))))
1657 ;; Convert LaTeX to \LaTeX{} and TeX to \TeX{}
1658 (goto-char (point-min))
1659 (let ((case-fold-search nil))
1660 (while (re-search-forward "\\<\\(\\(La\\)?TeX\\)\\>" nil t)
1661 (unless (eq (char-before (match-beginning 1)) ?\\)
1662 (org-if-unprotected-1
1663 (replace-match (org-export-latex-protect-string
1664 (concat "\\" (match-string 1)
1665 "{}")) t t)))))
1666 (goto-char (point-min))
1667 (let ((re (concat "\\\\\\([a-zA-Z]+\\)"
1668 "\\(?:<[^<>\n]*>\\)*"
1669 "\\(?:\\[[^][\n]*?\\]\\)*"
1670 "\\(?:<[^<>\n]*>\\)*"
1671 "\\("
1672 (org-create-multibrace-regexp "{" "}" 3)
1673 "\\)\\{1,3\\}")))
1674 (while (re-search-forward re nil t)
1675 (unless (or
1676 ;; check for comment line
1677 (save-excursion (goto-char (match-beginning 0))
1678 (org-in-indented-comment-line))
1679 ;; Check if this is a defined entity, so that is may need conversion
1680 (org-entity-get (match-string 1)))
1681 (add-text-properties (match-beginning 0) (match-end 0)
1682 '(org-protected t)))))
1683 (when (plist-get org-export-latex-options-plist :emphasize)
1684 (org-export-latex-fontify))
1685 (org-export-latex-time-stamps)
1686 (org-export-latex-quotation-marks)
1687 (org-export-latex-keywords-maybe)
1688 (org-export-latex-special-chars
1689 (plist-get org-export-latex-options-plist :sub-superscript))
1690 (org-export-latex-links)
1691 (org-trim (buffer-string))))
1693 (defun org-export-latex-time-stamps ()
1694 "Format time stamps."
1695 (goto-char (point-min))
1696 (let ((org-display-custom-times org-export-latex-display-custom-times))
1697 (while (re-search-forward org-ts-regexp-both nil t)
1698 (org-if-unprotected-at (1- (point))
1699 (replace-match
1700 (org-export-latex-protect-string
1701 (format (if (string= "<" (substring (match-string 0) 0 1))
1702 org-export-latex-timestamp-markup
1703 org-export-latex-timestamp-inactive-markup)
1704 (substring (org-translate-time (match-string 0)) 1 -1)))
1705 t t)))))
1707 (defun org-export-latex-quotation-marks ()
1708 "Export quotation marks depending on language conventions."
1709 (mapc (lambda(l)
1710 (goto-char (point-min))
1711 (while (re-search-forward (car l) nil t)
1712 (let ((rpl (concat (match-string 1)
1713 (org-export-latex-protect-string
1714 (copy-sequence (cdr l))))))
1715 (org-if-unprotected-1
1716 (replace-match rpl t t)))))
1717 (cdr (or (assoc (plist-get org-export-latex-options-plist :language)
1718 org-export-latex-quotes)
1719 ;; falls back on english
1720 (assoc "en" org-export-latex-quotes)))))
1722 (defun org-export-latex-special-chars (sub-superscript)
1723 "Export special characters to LaTeX.
1724 If SUB-SUPERSCRIPT is non-nil, convert \\ and ^.
1725 See the `org-export-latex.el' code for a complete conversion table."
1726 (goto-char (point-min))
1727 (mapc (lambda(c)
1728 (goto-char (point-min))
1729 (while (re-search-forward c nil t)
1730 ;; Put the point where to check for org-protected
1731 (unless (or (get-text-property (match-beginning 2) 'org-protected)
1732 (save-match-data (org-at-table.el-p)))
1733 (cond ((member (match-string 2) '("\\$" "$"))
1734 (if (equal (match-string 2) "\\$")
1736 (replace-match "\\$" t t)))
1737 ((member (match-string 2) '("&" "%" "#"))
1738 (if (equal (match-string 1) "\\")
1739 (replace-match (match-string 2) t t)
1740 (replace-match (concat (match-string 1) "\\"
1741 (match-string 2)) t t)
1742 (backward-char 1)))
1743 ((equal (match-string 2) "...")
1744 (replace-match
1745 (concat (match-string 1)
1746 (org-export-latex-protect-string "\\ldots{}")) t t))
1747 ((equal (match-string 2) "~")
1748 (cond ((equal (match-string 1) "\\") nil)
1749 ((eq 'org-link (get-text-property 0 'face (match-string 2)))
1750 (replace-match (concat (match-string 1) "\\~") t t))
1751 (t (replace-match
1752 (org-export-latex-protect-string
1753 (concat (match-string 1) "\\~{}")) t t))))
1754 ((member (match-string 2) '("{" "}"))
1755 (unless (save-match-data (org-inside-latex-math-p))
1756 (if (equal (match-string 1) "\\")
1757 (replace-match (match-string 2) t t)
1758 (replace-match (concat (match-string 1) "\\"
1759 (match-string 2)) t t)))))
1760 (unless (save-match-data (org-inside-latex-math-p))
1761 (cond ((equal (match-string 2) "\\")
1762 (replace-match (or (save-match-data
1763 (org-export-latex-treat-backslash-char
1764 (match-string 1)
1765 (or (match-string 3) "")))
1766 "") t t)
1767 (when (and (get-text-property (1- (point)) 'org-entity)
1768 (looking-at "{}"))
1769 ;; OK, this was an entity replacement, and the user
1770 ;; had terminated the entity with {}. Make sure
1771 ;; {} is protected as well, and remove the extra {}
1772 ;; inserted by the conversion.
1773 (put-text-property (point) (+ 2 (point)) 'org-protected t)
1774 (if (save-excursion (goto-char (max (- (point) 2) (point-min)))
1775 (looking-at "{}"))
1776 (replace-match ""))
1777 (forward-char 2))
1778 (backward-char 1))
1779 ((member (match-string 2) '("_" "^"))
1780 (replace-match (or (save-match-data
1781 (org-export-latex-treat-sub-super-char
1782 sub-superscript
1783 (match-string 2)
1784 (match-string 1)
1785 (match-string 3))) "") t t)
1786 (backward-char 1)))))))
1787 '(;"^\\([^\n$]*?\\|^\\)\\(\\\\?\\$\\)\\([^\n$]*\\)$"
1788 "\\(\\(\\\\?\\$\\)\\)"
1789 "\\([a-zA-Z0-9()]+\\|[ \t\n]\\|\\b\\|\\\\\\)\\(_\\|\\^\\)\\({[^{}]+}\\|[a-zA-Z0-9]+\\|[ \t\n]\\|[:punct:]\\|)\\|{[a-zA-Z0-9]+}\\|([a-zA-Z0-9]+)\\)"
1790 "\\(.\\|^\\)\\(\\\\\\)\\([ \t\n]\\|\\([&#%{}\"]\\|[a-zA-Z][a-zA-Z0-9]*\\)\\)"
1791 "\\(^\\|.\\)\\([&#%{}~]\\|\\.\\.\\.\\)"
1792 ;; (?\< . "\\textless{}")
1793 ;; (?\> . "\\textgreater{}")
1796 (defun org-inside-latex-math-p ()
1797 (get-text-property (point) 'org-latex-math))
1799 (defun org-export-latex-treat-sub-super-char
1800 (subsup char string-before string-after)
1801 "Convert the \"_\" and \"^\" characters to LaTeX.
1802 SUBSUP corresponds to the ^: option in the #+OPTIONS line.
1803 Convert CHAR depending on STRING-BEFORE and STRING-AFTER."
1804 (cond ((equal string-before "\\")
1805 (concat string-before char string-after))
1806 ((and (string-match "\\S-+" string-after))
1807 ;; this is part of a math formula
1808 (cond ((eq 'org-link (get-text-property 0 'face char))
1809 (concat string-before "\\" char string-after))
1810 ((save-match-data (org-inside-latex-math-p))
1811 (if subsup
1812 (cond ((eq 1 (length string-after))
1813 (concat string-before char string-after))
1814 ((string-match "[({]?\\([^)}]+\\)[)}]?" string-after)
1815 (format "%s%s{%s}" string-before char
1816 (match-string 1 string-after))))))
1817 ((and (> (length string-after) 1)
1818 (or (eq subsup t)
1819 (and (equal subsup '{}) (eq (string-to-char string-after) ?\{)))
1820 (or (string-match "[{]?\\([^}]+\\)[}]?" string-after)
1821 (string-match "[(]?\\([^)]+\\)[)]?" string-after)))
1823 (org-export-latex-protect-string
1824 (format "%s$%s{%s}$" string-before char
1825 (if (and (> (match-end 1) (1+ (match-beginning 1)))
1826 (not (equal (substring string-after 0 2) "{\\")))
1827 (concat "\\mathrm{" (match-string 1 string-after) "}")
1828 (match-string 1 string-after)))))
1829 ((eq subsup t) (concat string-before "$" char string-after "$"))
1830 (t (org-export-latex-protect-string
1831 (concat string-before "\\" char "{}" string-after)))))
1832 (t (org-export-latex-protect-string
1833 (concat string-before "\\" char "{}" string-after)))))
1835 (defun org-export-latex-treat-backslash-char (string-before string-after)
1836 "Convert the \"$\" special character to LaTeX.
1837 The conversion is made depending of STRING-BEFORE and STRING-AFTER."
1838 (let ((ass (org-entity-get string-after)))
1839 (cond
1840 (ass (org-add-props
1841 (if (nth 2 ass)
1842 (concat string-before
1843 (org-export-latex-protect-string
1844 (concat "$" (nth 1 ass) "$")))
1845 (concat string-before (org-export-latex-protect-string
1846 (nth 1 ass))))
1847 nil 'org-entity t))
1848 ((and (not (string-match "^[ \n\t]" string-after))
1849 (not (string-match "[ \t]\\'\\|^" string-before)))
1850 ;; backslash is inside a word
1851 (concat string-before
1852 (org-export-latex-protect-string
1853 (concat "\\textbackslash{}" string-after))))
1854 ((not (or (equal string-after "")
1855 (string-match "^[ \t\n]" string-after)))
1856 ;; backslash might escape a character (like \#) or a user TeX
1857 ;; macro (like \setcounter)
1858 (concat string-before
1859 (org-export-latex-protect-string (concat "\\" string-after))))
1860 ((and (string-match "^[ \t\n]" string-after)
1861 (string-match "[ \t\n]\\'" string-before))
1862 ;; backslash is alone, convert it to $\backslash$
1863 (org-export-latex-protect-string
1864 (concat string-before "\\textbackslash{}" string-after)))
1865 (t (org-export-latex-protect-string
1866 (concat string-before "\\textbackslash{}" string-after))))))
1868 (defun org-export-latex-keywords ()
1869 "Convert special keywords to LaTeX."
1870 (goto-char (point-min))
1871 (while (re-search-forward org-export-latex-special-keyword-regexp nil t)
1872 (replace-match (format org-export-latex-timestamp-keyword-markup
1873 (match-string 0)) t t)
1874 (save-excursion
1875 (beginning-of-line 1)
1876 (unless (looking-at ".*\n[ \t]*\n")
1877 (end-of-line 1)
1878 (insert "\n")))))
1880 (defun org-export-latex-fixed-width (opt)
1881 "When OPT is non-nil convert fixed-width sections to LaTeX."
1882 (goto-char (point-min))
1883 (while (re-search-forward "^[ \t]*:\\([ \t]\\|$\\)" nil t)
1884 (unless (get-text-property (point) 'org-example)
1885 (if opt
1886 (progn (goto-char (match-beginning 0))
1887 (insert "\\begin{verbatim}\n")
1888 (while (looking-at "^\\([ \t]*\\):\\(\\([ \t]\\|$\\).*\\)$")
1889 (replace-match (concat (match-string 1)
1890 (match-string 2)) t t)
1891 (forward-line))
1892 (insert "\\end{verbatim}\n"))
1893 (progn (goto-char (match-beginning 0))
1894 (while (looking-at "^\\([ \t]*\\):\\(\\([ \t]\\|$\\).*\\)$")
1895 (replace-match (concat "%" (match-string 1)
1896 (match-string 2)) t t)
1897 (forward-line)))))))
1899 (defvar org-table-last-alignment) ; defined in org-table.el
1900 (defvar org-table-last-column-widths) ; defined in org-table.el
1901 (declare-function orgtbl-to-latex "org-table" (table params) t)
1902 (defun org-export-latex-tables (insert)
1903 "Convert tables to LaTeX and INSERT it."
1904 ;; First, get the table.el tables
1905 (goto-char (point-min))
1906 (while (re-search-forward "^[ \t]*\\(\\+-[-+]*\\+\\)[ \t]*\n[ \t]*|" nil t)
1907 (org-if-unprotected
1908 (require 'table)
1909 (org-export-latex-convert-table.el-table)))
1911 ;; And now the Org-mode tables
1912 (goto-char (point-min))
1913 (while (re-search-forward "^\\([ \t]*\\)|" nil t)
1914 (org-if-unprotected-at (1- (point))
1915 (org-table-align)
1916 (let* ((beg (org-table-begin))
1917 (end (org-table-end))
1918 (raw-table (buffer-substring beg end))
1919 (org-table-last-alignment (copy-sequence org-table-last-alignment))
1920 (org-table-last-column-widths (copy-sequence
1921 org-table-last-column-widths))
1922 fnum fields line lines olines gr colgropen line-fmt align
1923 caption width shortn label attr floatp placement
1924 longtblp tblenv tabular-env)
1925 (if org-export-latex-tables-verbatim
1926 (let* ((tbl (concat "\\begin{verbatim}\n" raw-table
1927 "\\end{verbatim}\n")))
1928 (apply 'delete-region (list beg end))
1929 (insert (org-export-latex-protect-string tbl)))
1930 (progn
1931 (setq caption (org-find-text-property-in-string
1932 'org-caption raw-table)
1933 shortn (org-find-text-property-in-string
1934 'org-caption-shortn raw-table)
1935 attr (org-find-text-property-in-string
1936 'org-attributes raw-table)
1937 label (org-find-text-property-in-string
1938 'org-label raw-table)
1939 longtblp (and attr (stringp attr)
1940 (string-match "\\<longtable\\>" attr))
1941 tblenv (if (and attr (stringp attr))
1942 (cond ((string-match "\\<sidewaystable\\>" attr)
1943 "sidewaystable")
1944 ((or (string-match (regexp-quote "table*") attr)
1945 (string-match "\\<multicolumn\\>" attr))
1946 "table*")
1947 (t "table"))
1948 "table")
1949 tabular-env
1950 (if (and attr (stringp attr)
1951 (string-match "\\(tabular.\\)" attr))
1952 (match-string 1 attr)
1953 org-export-latex-tabular-environment)
1954 width (and attr (stringp attr)
1955 (string-match "\\<width=\\([^ \t\n\r]+\\)" attr)
1956 (match-string 1 attr))
1957 align (and attr (stringp attr)
1958 (string-match "\\<align=\\([^ \t\n\r]+\\)" attr)
1959 (match-string 1 attr))
1960 floatp (or caption label (string= "table*" tblenv))
1961 placement (if (and attr
1962 (stringp attr)
1963 (string-match "[ \t]*\\<placement=\\(\\S-+\\)" attr))
1964 (match-string 1 attr)
1965 (concat
1966 "[" org-latex-default-figure-position "]")))
1967 (setq caption (and caption (org-export-latex-fontify-headline caption)))
1968 (setq lines (org-split-string raw-table "\n"))
1969 (apply 'delete-region (list beg end))
1970 (when org-export-table-remove-special-lines
1971 (setq lines (org-table-clean-before-export lines 'maybe-quoted)))
1972 (when org-table-clean-did-remove-column
1973 (pop org-table-last-alignment)
1974 (pop org-table-last-column-widths))
1975 ;; make a formatting string to reflect alignment
1976 (setq olines lines)
1977 (while (and (not line-fmt) (setq line (pop olines)))
1978 (unless (string-match "^[ \t]*|-" line)
1979 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
1980 (setq fnum (make-vector (length fields) 0))
1981 (setq line-fmt
1982 (mapconcat
1983 (lambda (x)
1984 (setq gr (pop org-table-colgroup-info))
1985 (format "%s%%s%s"
1986 (cond ((eq gr :start)
1987 (prog1 (if colgropen "|" "|")
1988 (setq colgropen t)))
1989 ((eq gr :startend)
1990 (prog1 (if colgropen "|" "|")
1991 (setq colgropen nil)))
1992 (t ""))
1993 (if (memq gr '(:end :startend))
1994 (progn (setq colgropen nil) "|")
1995 "")))
1996 fnum ""))))
1997 ;; fix double || in line-fmt
1998 (setq line-fmt (replace-regexp-in-string "||" "|" line-fmt))
1999 ;; maybe remove the first and last "|"
2000 (when (and (not org-export-latex-tables-column-borders)
2001 (string-match "^\\(|\\)?\\(.+\\)|$" line-fmt))
2002 (setq line-fmt (match-string 2 line-fmt)))
2003 ;; format alignment
2004 (unless align
2005 (setq align (apply 'format
2006 (cons line-fmt
2007 (mapcar (lambda (x) (if x "r" "l"))
2008 org-table-last-alignment)))))
2009 ;; prepare the table to send to orgtbl-to-latex
2010 (setq lines
2011 (mapcar
2012 (lambda(elem)
2013 (or (and (string-match "[ \t]*|-+" elem) 'hline)
2014 (org-split-string
2015 (progn (set-text-properties 0 (length elem) nil elem)
2016 (org-trim elem)) "|")))
2017 lines))
2018 (when insert
2019 (insert (org-export-latex-protect-string
2020 (concat
2021 (if longtblp
2022 (concat "\\begin{longtable}{" align "}\n")
2023 (if floatp
2024 (format "\\begin{%s}%s\n" tblenv placement)))
2025 (if (and floatp org-export-latex-table-caption-above)
2026 (format
2027 "\\caption%s{%s} %s"
2028 (if shortn (concat "[" shortn "]") "")
2029 (or caption "")
2030 (if label (format "\\label{%s}" label) "")))
2031 (if (and longtblp caption org-export-latex-table-caption-above)
2032 "\\\\\n" "\n")
2033 (if (and org-export-latex-tables-centered (not longtblp))
2034 "\\begin{center}\n")
2035 (if (not longtblp)
2036 (format "\\begin{%s}%s{%s}\n"
2037 tabular-env
2038 (if width (format "{%s}" width) "")
2039 align))
2040 (orgtbl-to-latex
2041 lines
2042 `(:tstart nil :tend nil
2043 :hlend ,(if longtblp
2044 (format "\\\\
2045 \\hline
2046 \\endhead
2047 \\hline\\multicolumn{%d}{r}{Continued on next page}\\
2048 \\endfoot
2049 \\endlastfoot" (length org-table-last-alignment))
2050 nil)))
2051 (if (not longtblp) (format "\n\\end{%s}" tabular-env))
2052 (if longtblp "\n" (if org-export-latex-tables-centered
2053 "\n\\end{center}\n" "\n"))
2054 (if (and floatp (not org-export-latex-table-caption-above))
2055 (format
2056 "\\caption%s{%s} %s"
2057 (if shortn (concat "[" shortn "]") "")
2058 (or caption "")
2059 (if label (format "\\label{%s}" label) "")))
2060 (if longtblp
2061 "\\end{longtable}"
2062 (if floatp (format "\\end{%s}" tblenv)))))
2063 "\n\n"))))))))
2065 (defun org-export-latex-convert-table.el-table ()
2066 "Replace table.el table at point with LaTeX code."
2067 (let (tbl caption shortn label line floatp attr align rmlines)
2068 (setq line (buffer-substring (point-at-bol) (point-at-eol))
2069 label (org-get-text-property-any 0 'org-label line)
2070 caption (org-get-text-property-any 0 'org-caption line)
2071 shortn (org-get-text-property-any 0 'org-caption-shortn line)
2072 attr (org-get-text-property-any 0 'org-attributes line)
2073 align (and attr (stringp attr)
2074 (string-match "\\<align=\\([^ \t\n\r,]+\\)" attr)
2075 (match-string 1 attr))
2076 rmlines (and attr (stringp attr)
2077 (string-match "\\<rmlines\\>" attr))
2078 floatp (or label caption))
2079 (and (get-buffer "*org-export-table*")
2080 (kill-buffer (get-buffer "*org-export-table*")))
2081 (table-generate-source 'latex "*org-export-table*" "caption")
2082 (setq tbl (with-current-buffer "*org-export-table*"
2083 (buffer-string)))
2084 (while (string-match "^%.*\n" tbl)
2085 (setq tbl (replace-match "" t t tbl)))
2086 ;; fix the hlines
2087 (when rmlines
2088 (let ((n 0) lines)
2089 (setq lines (mapcar (lambda (x)
2090 (if (string-match "^\\\\hline$" x)
2091 (progn
2092 (setq n (1+ n))
2093 (if (= n 2) x nil))
2095 (org-split-string tbl "\n")))
2096 (setq tbl (mapconcat 'identity (delq nil lines) "\n"))))
2097 (when (and align (string-match "\\\\begin{tabular}{.*}" tbl))
2098 (setq tbl (replace-match (concat "\\begin{tabular}{" align "}")
2099 t t tbl)))
2100 (and (get-buffer "*org-export-table*")
2101 (kill-buffer (get-buffer "*org-export-table*")))
2102 (beginning-of-line 0)
2103 (while (looking-at "[ \t]*\\(|\\|\\+-\\)")
2104 (delete-region (point) (1+ (point-at-eol))))
2105 (when org-export-latex-tables-centered
2106 (setq tbl (concat "\\begin{center}\n" tbl "\\end{center}")))
2107 (when floatp
2108 (setq tbl (concat "\\begin{table}\n"
2109 (if (not org-export-latex-table-caption-above) tbl)
2110 (format "\\caption%s{%s%s}\n"
2111 (if shortn (format "[%s]" shortn) "")
2112 (if label (format "\\label{%s}" label) "")
2113 (or caption ""))
2114 (if org-export-latex-table-caption-above tbl)
2115 "\n\\end{table}\n")))
2116 (insert (org-export-latex-protect-string tbl))))
2118 (defun org-export-latex-fontify ()
2119 "Convert fontification to LaTeX."
2120 (goto-char (point-min))
2121 (while (re-search-forward org-emph-re nil t)
2122 ;; The match goes one char after the *string*, except at the end of a line
2123 (let ((emph (assoc (match-string 3)
2124 org-export-latex-emphasis-alist))
2125 (beg (match-beginning 0))
2126 (end (match-end 0))
2127 rpl s)
2128 (unless emph
2129 (message "`org-export-latex-emphasis-alist' has no entry for formatting triggered by \"%s\""
2130 (match-string 3)))
2131 (unless (or (and (get-text-property (- (point) 2) 'org-protected)
2132 (not (get-text-property
2133 (- (point) 2) 'org-verbatim-emph)))
2134 (equal (char-after (match-beginning 3))
2135 (char-after (1+ (match-beginning 3))))
2136 (save-excursion
2137 (goto-char (match-beginning 1))
2138 (save-match-data
2139 (and (org-at-table-p)
2140 (string-match
2141 "[|\n]" (buffer-substring beg end)))))
2142 (and (equal (match-string 3) "+")
2143 (save-match-data
2144 (string-match "\\`-+\\'" (match-string 4)))))
2145 (setq s (match-string 4))
2146 (setq rpl (concat (match-string 1)
2147 (org-export-latex-emph-format (cadr emph)
2148 (match-string 4))
2149 (match-string 5)))
2150 (if (caddr emph)
2151 (setq rpl (org-export-latex-protect-string rpl))
2152 (save-match-data
2153 (if (string-match "\\`.?\\(\\\\[a-z]+{\\)\\(.*\\)\\(}\\).?\\'" rpl)
2154 (progn
2155 (add-text-properties (match-beginning 1) (match-end 1)
2156 '(org-protected t) rpl)
2157 (add-text-properties (match-beginning 3) (match-end 3)
2158 '(org-protected t) rpl)))))
2159 (replace-match rpl t t)))
2160 (backward-char)))
2162 (defun org-export-latex-emph-format (format string)
2163 "Format an emphasis string and handle the \\verb special case."
2164 (when (member format '("\\verb" "\\protectedtexttt"))
2165 (save-match-data
2166 (if (equal format "\\verb")
2167 (let ((ll "~,./?;':\"|!@#%^&-_=+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ<>()[]{}"))
2168 (catch 'exit
2169 (loop for i from 0 to (1- (length ll)) do
2170 (if (not (string-match (regexp-quote (substring ll i (1+ i)))
2171 string))
2172 (progn
2173 (setq format (concat "\\verb" (substring ll i (1+ i))
2174 "%s" (substring ll i (1+ i))))
2175 (throw 'exit nil))))))
2176 (let ((start 0)
2177 (trans '(("\\" . "\\textbackslash{}")
2178 ("~" . "\\textasciitilde{}")
2179 ("^" . "\\textasciicircum{}")))
2180 (rtn "") char)
2181 (while (string-match "[\\{}$%&_#~^]" string)
2182 (setq char (match-string 0 string))
2183 (if (> (match-beginning 0) 0)
2184 (setq rtn (concat rtn (substring string
2185 0 (match-beginning 0)))))
2186 (setq string (substring string (1+ (match-beginning 0))))
2187 (setq char (or (cdr (assoc char trans)) (concat "\\" char))
2188 rtn (concat rtn char)))
2189 (setq string (concat rtn string) format "\\texttt{%s}")
2190 (while (string-match "--" string)
2191 (setq string (replace-match "-{}-" t t string)))))))
2192 (format format string))
2194 (defun org-export-latex-links ()
2195 ;; Make sure to use the LaTeX hyperref and graphicx package
2196 ;; or send some warnings.
2197 "Convert links to LaTeX."
2198 (goto-char (point-min))
2199 (while (re-search-forward org-bracket-link-analytic-regexp++ nil t)
2200 (org-if-unprotected-1
2201 (goto-char (match-beginning 0))
2202 (let* ((re-radio org-export-latex-all-targets-re)
2203 (remove (list (match-beginning 0) (match-end 0)))
2204 (raw-path (org-extract-attributes (match-string 3)))
2205 (full-raw-path (concat (match-string 1) raw-path))
2206 (desc (match-string 5))
2207 (type (or (match-string 2)
2208 (if (or (file-name-absolute-p raw-path)
2209 (string-match "^\\.\\.?/" raw-path))
2210 "file")))
2211 (coderefp (equal type "coderef"))
2212 (caption (org-find-text-property-in-string 'org-caption raw-path))
2213 (shortn (org-find-text-property-in-string 'org-caption-shortn raw-path))
2214 (attr (or (org-find-text-property-in-string 'org-attributes raw-path)
2215 (plist-get org-export-latex-options-plist :latex-image-options)))
2216 (label (org-find-text-property-in-string 'org-label raw-path))
2217 imgp radiop fnc
2218 ;; define the path of the link
2219 (path (cond
2220 ((member type '("coderef"))
2221 raw-path)
2222 ((member type '("http" "https" "ftp"))
2223 (concat type ":" raw-path))
2224 ((and re-radio (string-match re-radio raw-path))
2225 (setq radiop t))
2226 ((equal type "mailto")
2227 (concat type ":" raw-path))
2228 ((equal type "file")
2229 (if (and (org-file-image-p
2230 (expand-file-name
2231 raw-path)
2232 org-export-latex-inline-image-extensions)
2233 (or (get-text-property 0 'org-no-description
2234 raw-path)
2235 (equal desc full-raw-path)))
2236 (setq imgp t)
2237 (progn (when (string-match "\\(.+\\)::.+" raw-path)
2238 (setq raw-path (match-string 1 raw-path)))
2239 (if (file-exists-p raw-path)
2240 (concat type "://" (expand-file-name raw-path))
2241 (concat type "://" (org-export-directory
2242 :LaTeX org-export-latex-options-plist)
2243 raw-path))))))))
2244 ;; process with link inserting
2245 (apply 'delete-region remove)
2246 (setq caption (and caption (org-export-latex-fontify-headline caption)))
2247 (cond ((and imgp
2248 (plist-get org-export-latex-options-plist :inline-images))
2249 ;; OK, we need to inline an image
2250 (insert
2251 (org-export-latex-format-image raw-path caption label attr shortn)))
2252 (coderefp
2253 (insert (format
2254 (org-export-get-coderef-format path desc)
2255 (cdr (assoc path org-export-code-refs)))))
2256 (radiop (insert (format org-export-latex-hyperref-format
2257 (org-solidify-link-text raw-path) desc)))
2258 ((not type)
2259 (insert (format org-export-latex-hyperref-format
2260 (org-remove-initial-hash
2261 (org-solidify-link-text raw-path))
2262 desc)))
2263 (path
2264 (when (org-at-table-p)
2265 ;; There is a strange problem when we have a link in a table,
2266 ;; ampersands then cause a problem. I think this must be
2267 ;; a LaTeX issue, but we here implement a work-around anyway.
2268 (setq path (org-export-latex-protect-amp path)
2269 desc (org-export-latex-protect-amp desc)))
2270 (insert
2271 (if (string-match "%s.*%s" org-export-latex-href-format)
2272 (format org-export-latex-href-format path desc)
2273 (format org-export-latex-href-format path))))
2275 ((functionp (setq fnc (nth 2 (assoc type org-link-protocols))))
2276 ;; The link protocol has a function for formatting the link
2277 (insert
2278 (save-match-data
2279 (funcall fnc (org-link-unescape raw-path) desc 'latex))))
2281 (t (insert "\\texttt{" desc "}")))))))
2284 (defun org-export-latex-format-image (path caption label attr &optional shortn)
2285 "Format the image element, depending on user settings."
2286 (let (ind floatp wrapp multicolumnp placement figenv)
2287 (setq floatp (or caption label))
2288 (setq ind (org-get-text-property-any 0 'original-indentation path))
2289 (when (and attr (stringp attr))
2290 (if (string-match "[ \t]*\\<wrap\\>" attr)
2291 (setq wrapp t floatp nil attr (replace-match "" t t attr)))
2292 (if (string-match "[ \t]*\\<float\\>" attr)
2293 (setq wrapp nil floatp t attr (replace-match "" t t attr)))
2294 (if (string-match "[ \t]*\\<multicolumn\\>" attr)
2295 (setq multicolumnp t attr (replace-match "" t t attr))))
2297 (setq placement
2298 (cond
2299 (wrapp "{l}{0.5\\textwidth}")
2300 (floatp (concat "[" org-latex-default-figure-position "]"))
2301 (t "")))
2303 (when (and attr (stringp attr)
2304 (string-match "[ \t]*\\<placement=\\(\\S-+\\)" attr))
2305 (setq placement (match-string 1 attr)
2306 attr (replace-match "" t t attr)))
2307 (setq attr (and attr (org-trim attr)))
2308 (when (or (not attr) (= (length attr) 0))
2309 (setq attr (cond (floatp "width=0.7\\textwidth")
2310 (wrapp "width=0.48\\textwidth")
2311 (t attr))))
2312 (setq figenv
2313 (cond
2314 (wrapp "\\begin{wrapfigure}%placement
2315 \\centering
2316 \\includegraphics[%attr]{%path}
2317 \\caption%shortn{%labelcmd%caption}
2318 \\end{wrapfigure}")
2319 (multicolumnp "\\begin{figure*}%placement
2320 \\centering
2321 \\includegraphics[%attr]{%path}
2322 \\caption%shortn{%labelcmd%caption}
2323 \\end{figure*}")
2324 (floatp "\\begin{figure}%placement
2325 \\centering
2326 \\includegraphics[%attr]{%path}
2327 \\caption%shortn{%labelcmd%caption}
2328 \\end{figure}")
2329 (t "\\includegraphics[%attr]{%path}")))
2332 (setq figenv (mapconcat 'identity (split-string figenv "\n")
2333 (save-excursion (beginning-of-line 1)
2334 (looking-at "[ \t]*")
2335 (concat "\n" (match-string 0)))))
2337 (if (and (not label) (not caption)
2338 (string-match "^\\\\caption{.*\n" figenv))
2339 (setq figenv (replace-match "" t t figenv)))
2340 (org-add-props
2341 (org-fill-template
2342 figenv
2343 (list (cons "path"
2344 (if (file-name-absolute-p path)
2345 (expand-file-name path)
2346 path))
2347 (cons "attr" attr)
2348 (cons "shortn" (if shortn (format "[%s]" shortn) ""))
2349 (cons "labelcmd" (if label (format "\\label{%s}"
2350 label)""))
2351 (cons "caption" (or caption ""))
2352 (cons "placement" (or placement ""))))
2353 nil 'original-indentation ind)))
2355 (defun org-export-latex-protect-amp (s)
2356 (while (string-match "\\([^\\\\]\\)\\(&\\)" s)
2357 (setq s (replace-match (concat (match-string 1 s) "\\" (match-string 2 s))
2358 t t s)))
2361 (defun org-remove-initial-hash (s)
2362 (if (string-match "\\`#" s)
2363 (substring s 1)
2365 (defvar org-latex-entities) ; defined below
2366 (defvar org-latex-entities-regexp) ; defined below
2368 (defun org-export-latex-preprocess (parameters)
2369 "Clean stuff in the LaTeX export."
2370 ;; Replace footnotes.
2371 (when (plist-get parameters :footnotes)
2372 (goto-char (point-min))
2373 (let (ref)
2374 (while (setq ref (org-footnote-get-next-reference))
2375 (let* ((beg (nth 1 ref))
2376 (lbl (car ref))
2377 (def (nth 1 (assoc (string-to-number lbl)
2378 (mapcar (lambda (e) (cdr e))
2379 org-export-footnotes-seen)))))
2380 ;; Fix body for footnotes ending on a link or a list and
2381 ;; remove definition from buffer.
2382 (setq def
2383 (concat def
2384 (if (string-match "ORG-LIST-END-MARKER\\'" def)
2385 "\n" " ")))
2386 (org-footnote-delete-definitions lbl)
2387 ;; Compute string to insert (FNOTE), and protect the outside
2388 ;; macro from further transformation. When footnote at
2389 ;; point is referring to a previously defined footnote, use
2390 ;; \footnotemark. Otherwise, use \footnote.
2391 (let ((fnote (if (member lbl org-export-latex-footmark-seen)
2392 (org-export-latex-protect-string
2393 (format "\\footnotemark[%s]" lbl))
2394 (push lbl org-export-latex-footmark-seen)
2395 (concat (org-export-latex-protect-string "\\footnote{")
2397 (org-export-latex-protect-string "}"))))
2398 ;; Check if another footnote is immediately following.
2399 ;; If so, add a separator in-between.
2400 (sep (org-export-latex-protect-string
2401 (if (save-excursion (goto-char (1- (nth 2 ref)))
2402 (let ((next (org-footnote-get-next-reference)))
2403 (and next (= (nth 1 next) (nth 2 ref)))))
2404 org-export-latex-footnote-separator ""))))
2405 (when (org-at-heading-p)
2406 (setq fnote (concat (org-export-latex-protect-string "\\protect")
2407 fnote)))
2408 ;; Ensure a footnote at column 0 cannot end a list
2409 ;; containing it.
2410 (put-text-property 0 (length fnote) 'original-indentation 1000 fnote)
2411 ;; Replace footnote reference with FNOTE and, maybe, SEP.
2412 ;; `save-excursion' is required if there are two footnotes
2413 ;; in a row. In that case, point would be left at the
2414 ;; beginning of the second one, and
2415 ;; `org-footnote-get-next-reference' would then skip it.
2416 (goto-char beg)
2417 (delete-region beg (nth 2 ref))
2418 (save-excursion (insert fnote sep)))))))
2420 ;; Remove footnote section tag for LaTeX
2421 (goto-char (point-min))
2422 (while (re-search-forward
2423 (concat "^" footnote-section-tag-regexp) nil t)
2424 (org-if-unprotected
2425 (replace-match "")))
2426 ;; Remove any left-over footnote definition.
2427 (mapc (lambda (fn) (org-footnote-delete-definitions (car fn)))
2428 org-export-footnotes-data)
2429 (mapc (lambda (fn) (org-footnote-delete-definitions fn))
2430 org-export-latex-footmark-seen)
2432 ;; Preserve line breaks
2433 (goto-char (point-min))
2434 (while (re-search-forward "\\\\\\\\" nil t)
2435 (add-text-properties (match-beginning 0) (match-end 0)
2436 '(org-protected t)))
2438 ;; Preserve latex environments
2439 (goto-char (point-min))
2440 (while (re-search-forward "^[ \t]*\\\\begin{\\([a-zA-Z]+\\*?\\)}" nil t)
2441 (org-if-unprotected
2442 (let* ((start (progn (beginning-of-line) (point)))
2443 (end (and (re-search-forward
2444 (concat "^[ \t]*\\\\end{"
2445 (regexp-quote (match-string 1))
2446 "}") nil t)
2447 (point-at-eol))))
2448 (if end
2449 (add-text-properties start end '(org-protected t))
2450 (goto-char (point-at-eol))))))
2452 ;; Preserve math snippets
2453 (let* ((matchers (plist-get org-format-latex-options :matchers))
2454 (re-list org-latex-regexps)
2455 beg end re e m n block off)
2456 ;; Check the different regular expressions
2457 (while (setq e (pop re-list))
2458 (setq m (car e) re (nth 1 e) n (nth 2 e)
2459 block (if (nth 3 e) "\n\n" ""))
2460 (setq off (if (member m '("$" "$1")) 1 0))
2461 (when (and (member m matchers) (not (equal m "begin")))
2462 (goto-char (point-min))
2463 (while (re-search-forward re nil t)
2464 (setq beg (+ (match-beginning 0) off) end (- (match-end 0) 0))
2465 (add-text-properties beg end '(org-protected t org-latex-math t))))))
2467 ;; Convert LaTeX to \LaTeX{} and TeX to \TeX{}
2468 (goto-char (point-min))
2469 (let ((case-fold-search nil))
2470 (while (re-search-forward "\\<\\(\\(La\\)?TeX\\)\\>" nil t)
2471 (unless (eq (char-before (match-beginning 1)) ?\\)
2472 (org-if-unprotected-1
2473 (replace-match (org-export-latex-protect-string
2474 (concat "\\" (match-string 1)
2475 "{}")) t t)))))
2477 ;; Convert blockquotes
2478 (goto-char (point-min))
2479 (while (search-forward "ORG-BLOCKQUOTE-START" nil t)
2480 (org-replace-match-keep-properties "\\begin{quote}" t t))
2481 (goto-char (point-min))
2482 (while (search-forward "ORG-BLOCKQUOTE-END" nil t)
2483 (org-replace-match-keep-properties "\\end{quote}" t t))
2485 ;; Convert verse
2486 (goto-char (point-min))
2487 (while (search-forward "ORG-VERSE-START" nil t)
2488 (org-replace-match-keep-properties "\\begin{verse}" t t)
2489 (beginning-of-line 2)
2490 (while (and (not (looking-at "[ \t]*ORG-VERSE-END.*")) (not (eobp)))
2491 (when (looking-at "\\([ \t]+\\)\\([^ \t\n]\\)")
2492 (goto-char (match-end 1))
2493 (org-replace-match-keep-properties
2494 (org-export-latex-protect-string
2495 (concat "\\hspace*{1cm}" (match-string 2))) t t)
2496 (beginning-of-line 1))
2497 (if (looking-at "[ \t]*$")
2498 (insert (org-export-latex-protect-string "\\vspace*{1em}"))
2499 (unless (looking-at ".*?[^ \t\n].*?\\\\\\\\[ \t]*$")
2500 (end-of-line 1)
2501 (insert "\\\\")))
2502 (beginning-of-line 2))
2503 (and (looking-at "[ \t]*ORG-VERSE-END.*")
2504 (org-replace-match-keep-properties "\\end{verse}" t t)))
2506 ;; Convert #+INDEX to LaTeX \\index.
2507 (goto-char (point-min))
2508 (let ((case-fold-search t) entry)
2509 (while (re-search-forward
2510 "^[ \t]*#\\+index:[ \t]*\\([^ \t\r\n].*?\\)[ \t]*$"
2511 nil t)
2512 (setq entry
2513 (save-match-data
2514 (org-export-latex-protect-string
2515 (org-export-latex-fontify-headline (match-string 1)))))
2516 (replace-match (format "\\index{%s}" entry) t t)))
2518 ;; Convert center
2519 (goto-char (point-min))
2520 (while (search-forward "ORG-CENTER-START" nil t)
2521 (org-replace-match-keep-properties "\\begin{center}" t t))
2522 (goto-char (point-min))
2523 (while (search-forward "ORG-CENTER-END" nil t)
2524 (org-replace-match-keep-properties "\\end{center}" t t))
2526 (run-hooks 'org-export-latex-after-blockquotes-hook)
2528 ;; Convert horizontal rules
2529 (goto-char (point-min))
2530 (while (re-search-forward "^[ \t]*-\\{5,\\}[ \t]*$" nil t)
2531 (org-if-unprotected
2532 (replace-match (org-export-latex-protect-string "\\hrule") t t)))
2534 ;; Protect LaTeX commands like \command[...]{...} or \command{...}
2535 (goto-char (point-min))
2536 (let ((re (concat
2537 "\\\\\\([a-zA-Z]+\\*?\\)"
2538 "\\(?:<[^<>\n]*>\\)*"
2539 "\\(?:\\[[^][\n]*?\\]\\)*"
2540 "\\(?:<[^<>\n]*>\\)*"
2541 "\\(" (org-create-multibrace-regexp "{" "}" 3) "\\)\\{1,3\\}")))
2542 (while (re-search-forward re nil t)
2543 (unless (or
2544 ;; Check for comment line.
2545 (save-excursion (goto-char (match-beginning 0))
2546 (org-in-indented-comment-line))
2547 ;; Check if this is a defined entity, so that is may
2548 ;; need conversion.
2549 (org-entity-get (match-string 1))
2550 ;; Do not protect interior of footnotes. Those have
2551 ;; already been taken care of earlier in the function.
2552 ;; Yet, keep looking inside them for more commands.
2553 (and (equal (match-string 1) "footnote")
2554 (goto-char (match-end 1))))
2555 (add-text-properties (match-beginning 0) (match-end 0)
2556 '(org-protected t)))))
2558 ;; Special case for \nbsp
2559 (goto-char (point-min))
2560 (while (re-search-forward "\\\\nbsp\\({}\\|\\>\\)" nil t)
2561 (org-if-unprotected
2562 (replace-match (org-export-latex-protect-string "~"))))
2564 ;; Protect LaTeX entities
2565 (goto-char (point-min))
2566 (while (re-search-forward org-latex-entities-regexp nil t)
2567 (org-if-unprotected
2568 (add-text-properties (match-beginning 0) (match-end 0)
2569 '(org-protected t))))
2571 ;; Replace radio links
2572 (goto-char (point-min))
2573 (while (re-search-forward
2574 (concat "<<<?" org-export-latex-all-targets-re
2575 ">>>?\\((INVISIBLE)\\)?") nil t)
2576 (org-if-unprotected-at (+ (match-beginning 0) 2)
2577 (replace-match
2578 (concat
2579 (org-export-latex-protect-string
2580 (format "\\label{%s}" (save-match-data (org-solidify-link-text
2581 (match-string 1)))))
2582 (if (match-string 2) "" (match-string 1)))
2583 t t)))
2585 ;; Delete @<...> constructs
2586 ;; Thanks to Daniel Clemente for this regexp
2587 (goto-char (point-min))
2588 (while (re-search-forward "@<\\(?:[^\"\n]\\|\".*\"\\)*?>" nil t)
2589 (org-if-unprotected
2590 (replace-match ""))))
2592 (defun org-export-latex-fix-inputenc ()
2593 "Set the coding system in inputenc to what the buffer is."
2594 (let* ((cs buffer-file-coding-system)
2595 (opt (or (ignore-errors (latexenc-coding-system-to-inputenc cs))
2596 "utf8")))
2597 (when opt
2598 ;; Translate if that is requested
2599 (setq opt (or (cdr (assoc opt org-export-latex-inputenc-alist)) opt))
2600 ;; find the \usepackage statement and replace the option
2601 (goto-char (point-min))
2602 (while (re-search-forward "\\\\usepackage\\[\\(AUTO\\)\\]{inputenc}"
2603 nil t)
2604 (goto-char (match-beginning 1))
2605 (delete-region (match-beginning 1) (match-end 1))
2606 (insert opt))
2607 (and buffer-file-name
2608 (save-buffer)))))
2610 ;;; List handling:
2612 (defun org-export-latex-lists ()
2613 "Convert plain text lists in current buffer into LaTeX lists."
2614 ;; `org-list-end-re' output has changed since preprocess from
2615 ;; org-exp.el. Make sure it is taken into account.
2616 (let ((org-list-end-re "^ORG-LIST-END-MARKER\n"))
2617 (mapc
2618 (lambda (e)
2619 ;; For each type of context allowed for list export (E), find
2620 ;; every list, parse it, delete it and insert resulting
2621 ;; conversion to latex (RES), while keeping the same
2622 ;; `original-indentation' property.
2623 (let (res)
2624 (goto-char (point-min))
2625 (while (re-search-forward (org-item-beginning-re) nil t)
2626 (when (and (eq (get-text-property (point) 'list-context) e)
2627 (not (get-text-property (point) 'org-example)))
2628 (beginning-of-line)
2629 (setq res
2630 (org-list-to-latex
2631 ;; Narrowing is needed because we're converting
2632 ;; from inner functions to outer ones.
2633 (save-restriction
2634 (narrow-to-region (point) (point-max))
2635 (org-list-parse-list t))
2636 org-export-latex-list-parameters))
2637 ;; Extend previous value of original-indentation to the
2638 ;; whole string
2639 (insert (org-add-props res nil 'original-indentation
2640 (org-find-text-property-in-string
2641 'original-indentation res)))))))
2642 ;; List of allowed contexts for export, and the default one.
2643 (append org-list-export-context '(nil)))))
2645 (defconst org-latex-entities
2646 '("\\!"
2647 "\\'"
2648 "\\+"
2649 "\\,"
2650 "\\-"
2651 "\\:"
2652 "\\;"
2653 "\\<"
2654 "\\="
2655 "\\>"
2656 "\\Huge"
2657 "\\LARGE"
2658 "\\Large"
2659 "\\Styles"
2660 "\\\\"
2661 "\\`"
2662 "\\\""
2663 "\\addcontentsline"
2664 "\\address"
2665 "\\addtocontents"
2666 "\\addtocounter"
2667 "\\addtolength"
2668 "\\addvspace"
2669 "\\alph"
2670 "\\appendix"
2671 "\\arabic"
2672 "\\author"
2673 "\\begin{array}"
2674 "\\begin{center}"
2675 "\\begin{description}"
2676 "\\begin{enumerate}"
2677 "\\begin{eqnarray}"
2678 "\\begin{equation}"
2679 "\\begin{figure}"
2680 "\\begin{flushleft}"
2681 "\\begin{flushright}"
2682 "\\begin{itemize}"
2683 "\\begin{list}"
2684 "\\begin{minipage}"
2685 "\\begin{picture}"
2686 "\\begin{quotation}"
2687 "\\begin{quote}"
2688 "\\begin{tabbing}"
2689 "\\begin{table}"
2690 "\\begin{tabular}"
2691 "\\begin{thebibliography}"
2692 "\\begin{theorem}"
2693 "\\begin{titlepage}"
2694 "\\begin{verbatim}"
2695 "\\begin{verse}"
2696 "\\bf"
2697 "\\bf"
2698 "\\bibitem"
2699 "\\bigskip"
2700 "\\cdots"
2701 "\\centering"
2702 "\\circle"
2703 "\\cite"
2704 "\\cleardoublepage"
2705 "\\clearpage"
2706 "\\cline"
2707 "\\closing"
2708 "\\dashbox"
2709 "\\date"
2710 "\\ddots"
2711 "\\dotfill"
2712 "\\em"
2713 "\\fbox"
2714 "\\flushbottom"
2715 "\\fnsymbol"
2716 "\\footnote"
2717 "\\footnotemark"
2718 "\\footnotesize"
2719 "\\footnotetext"
2720 "\\frac"
2721 "\\frame"
2722 "\\framebox"
2723 "\\hfill"
2724 "\\hline"
2725 "\\hrulespace"
2726 "\\hspace"
2727 "\\huge"
2728 "\\hyphenation"
2729 "\\include"
2730 "\\includeonly"
2731 "\\indent"
2732 "\\input"
2733 "\\it"
2734 "\\kill"
2735 "\\label"
2736 "\\large"
2737 "\\ldots"
2738 "\\line"
2739 "\\linebreak"
2740 "\\linethickness"
2741 "\\listoffigures"
2742 "\\listoftables"
2743 "\\location"
2744 "\\makebox"
2745 "\\maketitle"
2746 "\\mark"
2747 "\\mbox"
2748 "\\medskip"
2749 "\\multicolumn"
2750 "\\multiput"
2751 "\\newcommand"
2752 "\\newcounter"
2753 "\\newenvironment"
2754 "\\newfont"
2755 "\\newlength"
2756 "\\newline"
2757 "\\newpage"
2758 "\\newsavebox"
2759 "\\newtheorem"
2760 "\\nocite"
2761 "\\nofiles"
2762 "\\noindent"
2763 "\\nolinebreak"
2764 "\\nopagebreak"
2765 "\\normalsize"
2766 "\\onecolumn"
2767 "\\opening"
2768 "\\oval"
2769 "\\overbrace"
2770 "\\overline"
2771 "\\pagebreak"
2772 "\\pagenumbering"
2773 "\\pageref"
2774 "\\pagestyle"
2775 "\\par"
2776 "\\parbox"
2777 "\\put"
2778 "\\raggedbottom"
2779 "\\raggedleft"
2780 "\\raggedright"
2781 "\\raisebox"
2782 "\\ref"
2783 "\\rm"
2784 "\\roman"
2785 "\\rule"
2786 "\\savebox"
2787 "\\sc"
2788 "\\scriptsize"
2789 "\\setcounter"
2790 "\\setlength"
2791 "\\settowidth"
2792 "\\sf"
2793 "\\shortstack"
2794 "\\signature"
2795 "\\sl"
2796 "\\small"
2797 "\\smallskip"
2798 "\\sqrt"
2799 "\\tableofcontents"
2800 "\\telephone"
2801 "\\thanks"
2802 "\\thispagestyle"
2803 "\\tiny"
2804 "\\title"
2805 "\\tt"
2806 "\\twocolumn"
2807 "\\typein"
2808 "\\typeout"
2809 "\\underbrace"
2810 "\\underline"
2811 "\\usebox"
2812 "\\usecounter"
2813 "\\value"
2814 "\\vdots"
2815 "\\vector"
2816 "\\verb"
2817 "\\vfill"
2818 "\\vline"
2819 "\\vspace")
2820 "A list of LaTeX commands to be protected when performing conversion.")
2822 (defconst org-latex-entities-regexp
2823 (let (names rest)
2824 (dolist (x org-latex-entities)
2825 (if (string-match "[a-zA-Z]$" x)
2826 (push x names)
2827 (push x rest)))
2828 (concat "\\(" (regexp-opt (nreverse names)) "\\>\\)"
2829 "\\|\\(" (regexp-opt (nreverse rest)) "\\)")))
2831 (provide 'org-export-latex)
2832 (provide 'org-latex)
2834 ;;; org-latex.el ends here