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