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