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