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