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