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