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