Release 6.17c
[org-mode/org-tableheadings.git] / lisp / org-export-latex.el
blob96e2356823ef429857ff33947a03b44246eef65e
1 ;;; org-export-latex.el --- LaTeX exporter for org-mode
2 ;;
3 ;; Copyright (C) 2007, 2008, 2009 Free Software Foundation, Inc.
4 ;;
5 ;; Emacs Lisp Archive Entry
6 ;; Filename: org-export-latex.el
7 ;; Version: 6.17c
8 ;; Author: Bastien Guerry <bzg AT altern DOT org>
9 ;; Maintainer: Bastien Guerry <bzg AT altern DOT org>
10 ;; Keywords: org, wp, tex
11 ;; Description: Converts an org-mode buffer into LaTeX
12 ;; URL: http://www.cognition.ens.fr/~guerry/u/org-export-latex.el
14 ;; This file is part of GNU Emacs.
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
29 ;;; Commentary:
31 ;; This library implements a LaTeX exporter for org-mode.
33 ;; Put this file into your load-path and the following into your ~/.emacs:
34 ;; (require 'org-export-latex)
36 ;; The interactive functions are similar to those of the HTML exporter:
38 ;; M-x `org-export-as-latex'
39 ;; M-x `org-export-as-pdf'
40 ;; M-x `org-export-as-pdf-and-open'
41 ;; M-x `org-export-as-latex-batch'
42 ;; M-x `org-export-as-latex-to-buffer'
43 ;; M-x `org-export-region-as-latex'
44 ;; M-x `org-replace-region-by-latex'
46 ;;; Code:
48 (eval-when-compile
49 (require 'cl))
51 (require 'footnote)
52 (require 'org)
53 (require 'org-exp)
55 ;;; Variables:
56 (defvar org-export-latex-class nil)
57 (defvar org-export-latex-header nil)
58 (defvar org-export-latex-append-header nil)
59 (defvar org-export-latex-options-plist nil)
60 (defvar org-export-latex-todo-keywords-1 nil)
61 (defvar org-export-latex-all-targets-re nil)
62 (defvar org-export-latex-add-level 0)
63 (defvar org-export-latex-sectioning "")
64 (defvar org-export-latex-sectioning-depth 0)
65 (defvar org-export-latex-special-string-regexps
66 '(org-ts-regexp
67 org-scheduled-string
68 org-deadline-string
69 org-clock-string)
70 "A list of regexps to convert as special keywords.")
72 (defvar latexp) ; dynamically scoped from org.el
73 (defvar re-quote) ; dynamically scoped from org.el
74 (defvar commentsp) ; dynamically scoped from org.el
76 ;;; User variables:
78 (defgroup org-export-latex nil
79 "Options for exporting Org-mode files to LaTeX."
80 :tag "Org Export LaTeX"
81 :group 'org-export)
83 (defcustom org-export-latex-default-class "article"
84 "The default LaTeX class."
85 :group 'org-export-latex
86 :type '(string :tag "LaTeX class"))
88 (defcustom org-export-latex-classes
89 '(("article"
90 "\\documentclass[11pt,a4paper]{article}
91 \\usepackage[utf8]{inputenc}
92 \\usepackage[T1]{fontenc}
93 \\usepackage{graphicx}
94 \\usepackage{longtable}
95 \\usepackage{hyperref}"
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,a4paper]{report}
103 \\usepackage[utf8]{inputenc}
104 \\usepackage[T1]{fontenc}
105 \\usepackage{graphicx}
106 \\usepackage{longtable}
107 \\usepackage{hyperref}"
108 ("\\part{%s}" . "\\part*{%s}")
109 ("\\chapter{%s}" . "\\chapter*{%s}")
110 ("\\section{%s}" . "\\section*{%s}")
111 ("\\subsection{%s}" . "\\subsection*{%s}")
112 ("\\subsubsection{%s}" . "\\subsubsection*{%s}"))
113 ("book"
114 "\\documentclass[11pt,a4paper]{book}
115 \\usepackage[utf8]{inputenc}
116 \\usepackage[T1]{fontenc}
117 \\usepackage{graphicx}
118 \\usepackage{longtable}
119 \\usepackage{hyperref}"
120 ("\\part{%s}" . "\\part*{%s}")
121 ("\\chapter{%s}" . "\\chapter*{%s}")
122 ("\\section{%s}" . "\\section*{%s}")
123 ("\\subsection{%s}" . "\\subsection*{%s}")
124 ("\\subsubsection{%s}" . "\\subsubsection*{%s}")))
125 "Alist of LaTeX classes and associated header and structure.
126 If #+LaTeX_CLASS is set in the buffer, use its value and the
127 associated information. Here is the structure of each cell:
129 \(class-name
130 header-string
131 (numbered-section . unnumbered-section\)
132 ...\)
134 A %s formatter is mandatory in each section string and will be
135 replaced by the title of the section.
137 Instead of a cons cell (numbered . unnumbered), you can also provide a list
138 of 2-4 elements,
140 (numbered-open numbered-close)
144 (numbered-open numbered-close unnumbered-open unnumbered-close)
146 providing opening and closing strings for an environment that should
147 represent the document section. The opening clause should have a %s
148 to represent the section title."
149 :group 'org-export-latex
150 :type '(repeat
151 (list (string :tag "LaTeX class")
152 (string :tag "LaTeX header")
153 (repeat :tag "Levels" :inline t
154 (choice
155 (cons :tag "Heading"
156 (string :tag "numbered")
157 (string :tag "unnumbered)"))
158 (list :tag "Environment"
159 (string :tag "Opening (numbered) ")
160 (string :tag "Closing (numbered) ")
161 (string :tag "Opening (unnumbered)")
162 (string :tag "Closing (unnumbered)")))))))
164 (defcustom org-export-latex-emphasis-alist
165 '(("*" "\\textbf{%s}" nil)
166 ("/" "\\emph{%s}" nil)
167 ("_" "\\underline{%s}" nil)
168 ("+" "\\texttt{%s}" nil)
169 ("=" "\\verb|%s|" nil)
170 ("~" "\\verb|%s|" t))
171 "Alist of LaTeX expressions to convert emphasis fontifiers.
172 Each element of the list is a list of three elements.
173 The first element is the character used as a marker for fontification.
174 The second element is a formatting string to wrap fontified text with.
175 The third element decides whether to protect converted text from other
176 conversions."
177 :group 'org-export-latex
178 :type 'alist)
180 (defcustom org-export-latex-title-command "\\maketitle"
181 "The command used to insert the title just after \\begin{document}.
182 If this string contains the formatting specification \"%s\" then
183 it will be used as a formatting string, passing the title as an
184 argument."
185 :group 'org-export-latex
186 :type 'string)
188 (defcustom org-export-latex-date-format
189 "%d %B %Y"
190 "Format string for \\date{...}."
191 :group 'org-export-latex
192 :type 'string)
194 (defcustom org-export-latex-tables-verbatim nil
195 "When non-nil, tables are exported verbatim."
196 :group 'org-export-latex
197 :type 'boolean)
199 (defcustom org-export-latex-tables-column-borders nil
200 "When non-nil, group of columns are surrounded with borders."
201 :group 'org-export-latex
202 :type 'boolean)
204 (defcustom org-export-latex-packages-alist nil
205 "Alist of packages to be inserted in the header.
206 Each cell is of the forma \( \"option\" . \"package\" \)."
207 :group 'org-export-latex
208 :type 'alist)
210 (defcustom org-export-latex-low-levels 'description
211 "How to convert sections below the current level of sectioning.
212 This is specified by the `org-export-headline-levels' option or the
213 value of \"H:\" in Org's #+OPTION line.
215 This can be either nil (skip the sections), 'description (convert
216 the sections as descriptive lists) or a string to be used instead
217 of \\section{%s}. In this latter case, the %s stands here for the
218 inserted headline and is mandatory."
219 :group 'org-export-latex
220 :type '(choice (const :tag "Ignore" nil)
221 (symbol :tag "Convert as descriptive list" description)
222 (string :tag "Use a section string" :value "\\subparagraph{%s}")))
224 (defcustom org-export-latex-list-parameters
225 '(:cbon "\\texttt{[ ]}" :cboff "\\texttt{[ ]}")
226 "Parameters for the LaTeX list exporter.
227 These parameters will be passed on to `org-list-to-latex', which in turn
228 will pass them (combined with the LaTeX default list parameters) to
229 `org-list-to-generic'."
230 :group 'org-export-latex
231 :type 'plist)
233 (defcustom org-export-latex-remove-from-headlines
234 '(:todo nil :priority nil :tags nil)
235 "A plist of keywords to remove from headlines. OBSOLETE.
236 Non-nil means remove this keyword type from the headline.
238 Don't remove the keys, just change their values.
240 Obsolete, this variable is no longer used. Use the separate
241 variables `org-export-with-todo-keywords', `org-export-with-priority',
242 and `org-export-with-tags' instead."
243 :type 'plist
244 :group 'org-export-latex)
246 (defcustom org-export-latex-image-default-option "width=10em"
247 "Default option for images."
248 :group 'org-export-latex
249 :type 'string)
251 (defcustom org-export-latex-coding-system nil
252 "Coding system for the exported LaTex file."
253 :group 'org-export-latex
254 :type 'coding-system)
256 (defgroup org-export-pdf nil
257 "Options for exporting Org-mode files to PDF, via LaTeX."
258 :tag "Org Export LaTeX"
259 :group 'org-export-latex
260 :group 'org-export)
262 (defcustom org-export-pdf-remove-logfiles t
263 "Non-nil means, remove the logfiles produced by PDF production.
264 These are the .aux, .log, .out, and .toc files."
265 :group 'org-export-latex
266 :type 'boolean)
268 ;;; Autoload functions:
270 ;;;###autoload
271 (defun org-export-as-latex-batch ()
272 "Call `org-export-as-latex', may be used in batch processing.
273 For example:
275 emacs --batch
276 --load=$HOME/lib/emacs/org.el
277 --eval \"(setq org-export-headline-levels 2)\"
278 --visit=MyFile --funcall org-export-as-latex-batch"
279 (org-export-as-latex org-export-headline-levels 'hidden))
281 ;;;###autoload
282 (defun org-export-as-latex-to-buffer (arg)
283 "Call `org-export-as-latex` with output to a temporary buffer.
284 No file is created. The prefix ARG is passed through to `org-export-as-latex'."
285 (interactive "P")
286 (org-export-as-latex arg nil nil "*Org LaTeX Export*")
287 (switch-to-buffer-other-window "*Org LaTeX Export*"))
289 ;;;###autoload
290 (defun org-replace-region-by-latex (beg end)
291 "Replace the region from BEG to END with its LaTeX export.
292 It assumes the region has `org-mode' syntax, and then convert it to
293 LaTeX. This can be used in any buffer. For example, you could
294 write an itemized list in `org-mode' syntax in an LaTeX buffer and
295 then use this command to convert it."
296 (interactive "r")
297 (let (reg latex buf)
298 (save-window-excursion
299 (if (org-mode-p)
300 (setq latex (org-export-region-as-latex
301 beg end t 'string))
302 (setq reg (buffer-substring beg end)
303 buf (get-buffer-create "*Org tmp*"))
304 (save-excursion
305 (set-buffer buf)
306 (erase-buffer)
307 (insert reg)
308 (org-mode)
309 (setq latex (org-export-region-as-latex
310 (point-min) (point-max) t 'string)))
311 (kill-buffer buf)))
312 (delete-region beg end)
313 (insert latex)))
315 ;;;###autoload
316 (defun org-export-region-as-latex (beg end &optional body-only buffer)
317 "Convert region from BEG to END in `org-mode' buffer to LaTeX.
318 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
319 contents, and only produce the region of converted text, useful for
320 cut-and-paste operations.
321 If BUFFER is a buffer or a string, use/create that buffer as a target
322 of the converted LaTeX. If BUFFER is the symbol `string', return the
323 produced LaTeX as a string and leave not buffer behind. For example,
324 a Lisp program could call this function in the following way:
326 (setq latex (org-export-region-as-latex beg end t 'string))
328 When called interactively, the output buffer is selected, and shown
329 in a window. A non-interactive call will only retunr the buffer."
330 (interactive "r\nP")
331 (when (interactive-p)
332 (setq buffer "*Org LaTeX Export*"))
333 (let ((transient-mark-mode t) (zmacs-regions t)
334 rtn)
335 (goto-char end)
336 (set-mark (point)) ;; to activate the region
337 (goto-char beg)
338 (setq rtn (org-export-as-latex
339 nil nil nil
340 buffer body-only))
341 (if (fboundp 'deactivate-mark) (deactivate-mark))
342 (if (and (interactive-p) (bufferp rtn))
343 (switch-to-buffer-other-window rtn)
344 rtn)))
346 ;;;###autoload
347 (defun org-export-as-latex (arg &optional hidden ext-plist
348 to-buffer body-only pub-dir)
349 "Export current buffer to a LaTeX file.
350 If there is an active region, export only the region. The prefix
351 ARG specifies how many levels of the outline should become
352 headlines. The default is 3. Lower levels will be exported
353 depending on `org-export-latex-low-levels'. The default is to
354 convert them as description lists. When HIDDEN is non-nil, don't
355 display the LaTeX buffer. EXT-PLIST is a property list with
356 external parameters overriding org-mode's default settings, but
357 still inferior to file-local settings. When TO-BUFFER is
358 non-nil, create a buffer with that name and export to that
359 buffer. If TO-BUFFER is the symbol `string', don't leave any
360 buffer behind but just return the resulting LaTeX as a string.
361 When BODY-ONLY is set, don't produce the file header and footer,
362 simply return the content of \begin{document}...\end{document},
363 without even the \begin{document} and \end{document} commands.
364 when PUB-DIR is set, use this as the publishing directory."
365 (interactive "P")
366 ;; Make sure we have a file name when we need it.
367 (when (and (not (or to-buffer body-only))
368 (not buffer-file-name))
369 (if (buffer-base-buffer)
370 (org-set-local 'buffer-file-name
371 (with-current-buffer (buffer-base-buffer)
372 buffer-file-name))
373 (error "Need a file name to be able to export")))
375 (message "Exporting to LaTeX...")
376 (remove-text-properties (point-min) (point-max)
377 '(:org-license-to-kill nil))
378 (org-update-radio-target-regexp)
379 (org-export-latex-set-initial-vars ext-plist arg)
380 (let* ((wcf (current-window-configuration))
381 (opt-plist org-export-latex-options-plist)
382 (region-p (org-region-active-p))
383 (rbeg (and region-p (region-beginning)))
384 (rend (and region-p (region-end)))
385 (subtree-p
386 (when region-p
387 (save-excursion
388 (goto-char rbeg)
389 (and (org-at-heading-p)
390 (>= (org-end-of-subtree t t) rend)))))
391 (opt-plist (if subtree-p
392 (org-export-add-subtree-options opt-plist rbeg)
393 opt-plist))
394 ;; Make sure the variable contains the updated values.
395 (org-export-latex-options-plist opt-plist)
396 (title (or (and subtree-p (org-export-get-title-from-subtree))
397 (plist-get opt-plist :title)
398 (and (not
399 (plist-get opt-plist :skip-before-1st-heading))
400 (org-export-grab-title-from-buffer))
401 (file-name-sans-extension
402 (file-name-nondirectory buffer-file-name))))
403 (filename (concat (file-name-as-directory
404 (or pub-dir
405 (org-export-directory :LaTeX ext-plist)))
406 (file-name-sans-extension
407 (or (and subtree-p
408 (org-entry-get rbeg "EXPORT_FILE_NAME" t))
409 (file-name-nondirectory ;sans-extension
410 buffer-file-name)))
411 ".tex"))
412 (filename (if (equal (file-truename filename)
413 (file-truename buffer-file-name))
414 (concat filename ".tex")
415 filename))
416 (buffer (if to-buffer
417 (cond
418 ((eq to-buffer 'string) (get-buffer-create
419 "*Org LaTeX Export*"))
420 (t (get-buffer-create to-buffer)))
421 (find-file-noselect filename)))
422 (odd org-odd-levels-only)
423 (header (org-export-latex-make-header title opt-plist))
424 (skip (cond (subtree-p nil)
425 (region-p nil)
426 (t (plist-get opt-plist :skip-before-1st-heading))))
427 (text (plist-get opt-plist :text))
428 (first-lines (if skip "" (org-export-latex-first-lines rbeg)))
429 (coding-system (and (boundp 'buffer-file-coding-system)
430 buffer-file-coding-system))
431 (coding-system-for-write (or org-export-latex-coding-system
432 coding-system))
433 (save-buffer-coding-system (or org-export-latex-coding-system
434 coding-system))
435 (region (buffer-substring
436 (if region-p (region-beginning) (point-min))
437 (if region-p (region-end) (point-max))))
438 (string-for-export
439 (org-export-preprocess-string
440 region
441 :emph-multiline t
442 :for-LaTeX t
443 :comments nil
444 :tags (plist-get opt-plist :tags)
445 :priority (plist-get opt-plist :priority)
446 :footnotes (plist-get opt-plist :footnotes)
447 :timestamps (plist-get opt-plist :timestamps)
448 :todo-keywords (plist-get opt-plist :todo-keywords)
449 :add-text (if (eq to-buffer 'string) nil text)
450 :skip-before-1st-heading skip
451 :select-tags (plist-get opt-plist :select-tags)
452 :exclude-tags (plist-get opt-plist :exclude-tags)
453 :LaTeX-fragments nil)))
455 (set-buffer buffer)
456 (erase-buffer)
458 (and (fboundp 'set-buffer-file-coding-system)
459 (set-buffer-file-coding-system coding-system-for-write))
461 ;; insert the header and initial document commands
462 (unless (or (eq to-buffer 'string) body-only)
463 (insert header))
465 ;; insert text found in #+TEXT
466 (when (and text (not (eq to-buffer 'string)))
467 (insert (org-export-latex-content
468 text '(lists tables fixed-width keywords))
469 "\n\n"))
471 ;; insert lines before the first headline
472 (unless (or skip (eq to-buffer 'string))
473 (insert first-lines))
475 ;; export the content of headlines
476 (org-export-latex-global
477 (with-temp-buffer
478 (insert string-for-export)
479 (goto-char (point-min))
480 (when (re-search-forward "^\\(\\*+\\) " nil t)
481 (let* ((asters (length (match-string 1)))
482 (level (if odd (- asters 2) (- asters 1))))
483 (setq org-export-latex-add-level
484 (if odd (1- (/ (1+ asters) 2)) (1- asters)))
485 (org-export-latex-parse-global level odd)))))
487 ;; finalization
488 (unless body-only (insert "\n\\end{document}"))
489 (or to-buffer (save-buffer))
490 (goto-char (point-min))
491 (message "Exporting to LaTeX...done")
492 (prog1
493 (if (eq to-buffer 'string)
494 (prog1 (buffer-substring (point-min) (point-max))
495 (kill-buffer (current-buffer)))
496 (current-buffer))
497 (set-window-configuration wcf))))
499 ;;;###autoload
500 (defun org-export-as-pdf (arg &optional hidden ext-plist
501 to-buffer body-only pub-dir)
502 "Export as LaTeX, then process through to PDF."
503 (interactive "P")
504 (message "Exporting to PDF...")
505 (let* ((wconfig (current-window-configuration))
506 (lbuf (org-export-as-latex arg hidden ext-plist
507 to-buffer body-only pub-dir))
508 (file (buffer-file-name lbuf))
509 (base (file-name-sans-extension (buffer-file-name lbuf)))
510 (pdffile (concat base ".pdf")))
511 (and (file-exists-p pdffile) (delete-file pdffile))
512 (message "Processing LaTeX file...")
513 (shell-command (format "pdflatex -interaction nonstopmode %s"
514 (shell-quote-argument file)))
515 (shell-command (format "pdflatex -interaction nonstopmode %s"
516 (shell-quote-argument file)))
517 (message "Processing LaTeX file...done")
518 (if (not (file-exists-p pdffile))
519 (error "PDF file was not produced")
520 (set-window-configuration wconfig)
521 (when org-export-pdf-remove-logfiles
522 (dolist (ext '("aux" "log" "out" "toc"))
523 (setq file (concat base "." ext))
524 (and (file-exists-p file) (delete-file file))))
525 (message "Exporting to PDF...done")
526 pdffile)))
528 ;;;###autoload
529 (defun org-export-as-pdf-and-open (arg)
530 "Export as LaTeX, then process through to PDF, and open."
531 (interactive "P")
532 (let ((pdffile (org-export-as-pdf arg)))
533 (if pdffile
534 (org-open-file pdffile)
535 (error "PDF file was not produced"))))
537 ;;; Parsing functions:
539 (defun org-export-latex-parse-global (level odd)
540 "Parse the current buffer recursively, starting at LEVEL.
541 If ODD is non-nil, assume the buffer only contains odd sections.
542 Return a list reflecting the document structure."
543 (save-excursion
544 (goto-char (point-min))
545 (let* ((cnt 0) output
546 (depth org-export-latex-sectioning-depth))
547 (while (re-search-forward
548 (concat "^\\(\\(?:\\*\\)\\{"
549 (number-to-string (+ (if odd 2 1) level))
550 "\\}\\) \\(.*\\)$")
551 ;; make sure that there is no upper heading
552 (when (> level 0)
553 (save-excursion
554 (save-match-data
555 (re-search-forward
556 (concat "^\\(\\(?:\\*\\)\\{"
557 (number-to-string level)
558 "\\}\\) \\(.*\\)$") nil t)))) t)
559 (setq cnt (1+ cnt))
560 (let* ((pos (match-beginning 0))
561 (heading (match-string 2))
562 (nlevel (if odd (/ (+ 3 level) 2) (1+ level))))
563 (save-excursion
564 (narrow-to-region
565 (point)
566 (save-match-data
567 (if (re-search-forward
568 (concat "^\\(\\(?:\\*\\)\\{"
569 (number-to-string (+ (if odd 2 1) level))
570 "\\}\\) \\(.*\\)$") nil t)
571 (match-beginning 0)
572 (point-max))))
573 (goto-char (point-min))
574 (setq output
575 (append output
576 (list
577 (list
578 `(pos . ,pos)
579 `(level . ,nlevel)
580 `(occur . ,cnt)
581 `(heading . ,heading)
582 `(content . ,(org-export-latex-parse-content))
583 `(subcontent . ,(org-export-latex-parse-subcontent
584 level odd)))))))
585 (widen)))
586 (list output))))
588 (defun org-export-latex-parse-content ()
589 "Extract the content of a section."
590 (let ((beg (point))
591 (end (if (re-search-forward "^\\(\\*\\)+ .*$" nil t)
592 (progn (beginning-of-line) (point))
593 (point-max))))
594 (buffer-substring beg end)))
596 (defun org-export-latex-parse-subcontent (level odd)
597 "Extract the subcontent of a section at LEVEL.
598 If ODD Is non-nil, assume subcontent only contains odd sections."
599 (if (not (re-search-forward
600 (concat "^\\(\\(?:\\*\\)\\{"
601 (number-to-string (+ (if odd 4 2) level))
602 "\\}\\) \\(.*\\)$")
603 nil t))
604 nil ; subcontent is nil
605 (org-export-latex-parse-global (+ (if odd 2 1) level) odd)))
607 ;;; Rendering functions:
608 (defun org-export-latex-global (content)
609 "Export CONTENT to LaTeX.
610 CONTENT is an element of the list produced by
611 `org-export-latex-parse-global'."
612 (if (eq (car content) 'subcontent)
613 (mapc 'org-export-latex-sub (cdr content))
614 (org-export-latex-sub (car content))))
616 (defun org-export-latex-sub (subcontent)
617 "Export the list SUBCONTENT to LaTeX.
618 SUBCONTENT is an alist containing information about the headline
619 and its content."
620 (let ((num (plist-get org-export-latex-options-plist :section-numbers)))
621 (mapc (lambda(x) (org-export-latex-subcontent x num)) subcontent)))
623 (defun org-export-latex-subcontent (subcontent num)
624 "Export each cell of SUBCONTENT to LaTeX.
625 If NUM, export sections as numerical sections."
626 (let* ((heading (org-export-latex-fontify-headline
627 (cdr (assoc 'heading subcontent))))
628 (level (- (cdr (assoc 'level subcontent))
629 org-export-latex-add-level))
630 (occur (number-to-string (cdr (assoc 'occur subcontent))))
631 (content (cdr (assoc 'content subcontent)))
632 (subcontent (cadr (assoc 'subcontent subcontent)))
633 (label (org-get-text-property-any 0 'target heading))
634 (label-list (cons label (cdr (assoc label
635 org-export-target-aliases)))))
636 (cond
637 ;; Normal conversion
638 ((<= level org-export-latex-sectioning-depth)
639 (let* ((sec (nth (1- level) org-export-latex-sectioning))
640 start end)
641 (if (consp (cdr sec))
642 (setq start (nth (if num 0 2) sec)
643 end (nth (if num 1 3) sec))
644 (setq start (if num (car sec) (cdr sec))))
645 (insert (format start heading) "\n")
646 (when label
647 (insert (mapconcat (lambda (l) (format "\\label{%s}" l))
648 label-list "\n") "\n"))
649 (insert (org-export-latex-content content))
650 (cond ((stringp subcontent) (insert subcontent))
651 ((listp subcontent) (org-export-latex-sub subcontent)))
652 (if end (insert end "\n"))))
653 ;; At a level under the hl option: we can drop this subsection
654 ((> level org-export-latex-sectioning-depth)
655 (cond ((eq org-export-latex-low-levels 'description)
656 (insert (format "\\begin{description}\n\n\\item[%s]%s\n\n"
657 heading
658 (if label (format "\\label{%s}" label) "")))
659 (insert (org-export-latex-content content))
660 (cond ((stringp subcontent) (insert subcontent))
661 ((listp subcontent) (org-export-latex-sub subcontent)))
662 (insert "\\end{description}\n"))
663 ((stringp org-export-latex-low-levels)
664 (insert (format org-export-latex-low-levels heading) "\n")
665 (when label (insert (format "\\label{%s}\n" label)))
666 (insert (org-export-latex-content content))
667 (cond ((stringp subcontent) (insert subcontent))
668 ((listp subcontent) (org-export-latex-sub subcontent)))))))))
670 ;;; Exporting internals:
671 (defun org-export-latex-set-initial-vars (ext-plist level)
672 "Store org local variables required for LaTeX export.
673 EXT-PLIST is an optional additional plist.
674 LEVEL indicates the default depth for export."
675 (setq org-export-latex-todo-keywords-1 org-todo-keywords-1
676 org-export-latex-all-targets-re
677 (org-make-target-link-regexp (org-all-targets))
678 org-export-latex-options-plist
679 (org-combine-plists (org-default-export-plist) ext-plist
680 (org-infile-export-plist))
681 org-export-latex-class
682 (save-excursion
683 (goto-char (point-min))
684 (if (and (re-search-forward "^#\\+LaTeX_CLASS:[ \t]*\\([a-zA-Z]+\\)" nil t)
685 (assoc (match-string 1) org-export-latex-classes))
686 (match-string 1)
687 org-export-latex-default-class))
688 org-export-latex-header
689 (cadr (assoc org-export-latex-class org-export-latex-classes))
690 org-export-latex-sectioning
691 (cddr (assoc org-export-latex-class org-export-latex-classes))
692 org-export-latex-sectioning-depth
693 (or level
694 (let ((hl-levels
695 (plist-get org-export-latex-options-plist :headline-levels))
696 (sec-depth (length org-export-latex-sectioning)))
697 (if (> hl-levels sec-depth) sec-depth hl-levels)))))
699 (defun org-export-latex-make-header (title opt-plist)
700 "Make the LaTeX header and return it as a string.
701 TITLE is the current title from the buffer or region.
702 OPT-PLIST is the options plist for current buffer."
703 (let ((toc (plist-get opt-plist :table-of-contents))
704 (author (plist-get opt-plist :author)))
705 (concat
706 (if (plist-get opt-plist :time-stamp-file)
707 (format-time-string "%% Created %Y-%m-%d %a %H:%M\n"))
708 ;; insert LaTeX custom header
709 org-export-latex-header
710 "\n"
711 ;; insert information on LaTeX packages
712 (when org-export-latex-packages-alist
713 (mapconcat (lambda(p)
714 (if (equal "" (car p))
715 (format "\\usepackage{%s}" (cadr p))
716 (format "\\usepackage[%s]{%s}"
717 (car p) (cadr p))))
718 org-export-latex-packages-alist "\n"))
719 ;; insert additional commands in the header
720 (plist-get opt-plist :latex-header-extra)
721 org-export-latex-append-header
722 ;; insert the title
723 (format
724 "\n\n\\title{%s}\n"
725 ;; convert the title
726 (org-export-latex-content
727 title '(lists tables fixed-width keywords)))
728 ;; insert author info
729 (if (plist-get opt-plist :author-info)
730 (format "\\author{%s}\n"
731 (or author user-full-name))
732 (format "%%\\author{%s}\n"
733 (or author user-full-name)))
734 ;; insert the date
735 (format "\\date{%s}\n"
736 (format-time-string
737 (or (plist-get opt-plist :date)
738 org-export-latex-date-format)))
739 ;; beginning of the document
740 "\n\\begin{document}\n\n"
741 ;; insert the title command
742 (if (string-match "%s" org-export-latex-title-command)
743 (format org-export-latex-title-command title)
744 org-export-latex-title-command)
745 "\n\n"
746 ;; table of contents
747 (when (and org-export-with-toc
748 (plist-get opt-plist :section-numbers))
749 (cond ((numberp toc)
750 (format "\\setcounter{tocdepth}{%s}\n\\tableofcontents\n\\vspace*{1cm}\n"
751 (min toc (plist-get opt-plist :headline-levels))))
752 (toc (format "\\setcounter{tocdepth}{%s}\n\\tableofcontents\n\\vspace*{1cm}\n"
753 (plist-get opt-plist :headline-levels))))))))
755 (defun org-export-latex-first-lines (&optional beg)
756 "Export the first lines before first headline.
757 If BEG is non-nil, the is the beginning of he region."
758 (save-excursion
759 (goto-char (or beg (point-min)))
760 (if (org-at-heading-p) (beginning-of-line 2))
761 (let* ((pt (point))
762 (end (if (re-search-forward "^\\*+ " nil t)
763 (goto-char (match-beginning 0))
764 (goto-char (point-max)))))
765 (prog1
766 (org-export-latex-content
767 (org-export-preprocess-string
768 (buffer-substring pt end)
769 :for-LaTeX t
770 :emph-multiline t
771 :add-text nil
772 :comments nil
773 :skip-before-1st-heading nil
774 :LaTeX-fragments nil))
775 (add-text-properties pt (max pt (1- end))
776 '(:org-license-to-kill t))))))
778 (defun org-export-latex-content (content &optional exclude-list)
779 "Convert CONTENT string to LaTeX.
780 Don't perform conversions that are in EXCLUDE-LIST. Recognized
781 conversion types are: quotation-marks, emphasis, sub-superscript,
782 links, keywords, lists, tables, fixed-width"
783 (with-temp-buffer
784 (insert content)
785 (unless (memq 'quotation-marks exclude-list)
786 (org-export-latex-quotation-marks))
787 (unless (memq 'emphasis exclude-list)
788 (when (plist-get org-export-latex-options-plist :emphasize)
789 (org-export-latex-fontify)))
790 (unless (memq 'sub-superscript exclude-list)
791 (org-export-latex-special-chars
792 (plist-get org-export-latex-options-plist :sub-superscript)))
793 (unless (memq 'links exclude-list)
794 (org-export-latex-links))
795 (unless (memq 'keywords exclude-list)
796 (org-export-latex-keywords))
797 (unless (memq 'lists exclude-list)
798 (org-export-latex-lists))
799 (unless (memq 'tables exclude-list)
800 (org-export-latex-tables
801 (plist-get org-export-latex-options-plist :tables)))
802 (unless (memq 'fixed-width exclude-list)
803 (org-export-latex-fixed-width
804 (plist-get org-export-latex-options-plist :fixed-width)))
805 ;; return string
806 (buffer-substring (point-min) (point-max))))
808 (defun org-export-latex-protect-string (s)
809 "Add the org-protected property to string S."
810 (add-text-properties 0 (length s) '(org-protected t) s) s)
812 (defun org-export-latex-protect-char-in-string (char-list string)
813 "Add org-protected text-property to char from CHAR-LIST in STRING."
814 (with-temp-buffer
815 (save-match-data
816 (insert string)
817 (goto-char (point-min))
818 (while (re-search-forward (regexp-opt char-list) nil t)
819 (add-text-properties (match-beginning 0)
820 (match-end 0) '(org-protected t)))
821 (buffer-string))))
823 (defun org-export-latex-keywords-maybe (&optional remove-list)
824 "Maybe remove keywords depending on rules in REMOVE-LIST."
825 (goto-char (point-min))
826 (let ((re-todo (mapconcat 'identity org-export-latex-todo-keywords-1 "\\|"))
827 (case-fold-search nil))
828 ;; convert TODO keywords
829 (when (re-search-forward (concat "^\\(" re-todo "\\)") nil t)
830 (if (plist-get remove-list :todo)
831 (replace-match "")
832 (replace-match (format "\\textbf{%s}" (match-string 1)) t t)))
833 ;; convert priority string
834 (when (re-search-forward "\\[\\\\#.\\]" nil t)
835 (if (plist-get remove-list :priority)
836 (replace-match "")
837 (replace-match (format "\\textbf{%s}" (match-string 0)) t t)))
838 ;; convert tags
839 (when (re-search-forward "\\(:[a-zA-Z0-9_@]+\\)+:" nil t)
840 (if (or (not org-export-with-tags)
841 (plist-get remove-list :tags))
842 (replace-match "")
843 (replace-match
844 (org-export-latex-protect-string
845 (format "\\textbf{%s}"
846 (save-match-data
847 (replace-regexp-in-string
848 "_" "\\\\_" (match-string 0)))))
849 t t)))))
851 (defun org-export-latex-fontify-headline (string)
852 "Fontify special words in STRING."
853 (with-temp-buffer
854 ;; FIXME: org-inside-LaTeX-fragment-p doesn't work when the $...$ is at
855 ;; the beginning of the buffer - inserting "\n" is safe here though.
856 (insert "\n" string)
857 (goto-char (point-min))
858 (when (plist-get org-export-latex-options-plist :emphasize)
859 (org-export-latex-fontify))
860 (org-export-latex-keywords-maybe)
861 (org-export-latex-special-chars
862 (plist-get org-export-latex-options-plist :sub-superscript))
863 (org-export-latex-links)
864 ; (org-trim (buffer-substring-no-properties (point-min) (point-max)))))
865 (org-trim (buffer-string))))
867 (defun org-export-latex-quotation-marks ()
868 "Export quotation marks depending on language conventions."
869 (let* ((lang (plist-get org-export-latex-options-plist :language))
870 (quote-rpl (if (equal lang "fr")
871 '(("\\(\\s-\\)\"" "«~")
872 ("\\(\\S-\\)\"" "~»")
873 ("\\(\\s-\\)'" "`"))
874 '(("\\(\\s-\\)\"" "``")
875 ("\\(\\S-\\)\"" "''")
876 ("\\(\\s-\\)'" "`")))))
877 (mapc (lambda(l) (goto-char (point-min))
878 (while (re-search-forward (car l) nil t)
879 (let ((rpl (concat (match-string 1) (cadr l))))
880 (org-export-latex-protect-string rpl)
881 (org-if-unprotected
882 (replace-match rpl t t))))) quote-rpl)))
884 (defun org-export-latex-special-chars (sub-superscript)
885 "Export special characters to LaTeX.
886 If SUB-SUPERSCRIPT is non-nil, convert \\ and ^.
887 See the `org-export-latex.el' code for a complete conversion table."
888 (goto-char (point-min))
889 (mapc (lambda(c)
890 (goto-char (point-min))
891 (while (re-search-forward c nil t)
892 ;; Put the point where to check for org-protected
893 ; (unless (or (get-text-property (match-beginning 2) 'org-protected);
894 ; (org-at-table-p))
895 (unless (get-text-property (match-beginning 2) 'org-protected)
896 (cond ((member (match-string 2) '("\\$" "$"))
897 (if (equal (match-string 2) "\\$")
899 (replace-match "\\$" t t)))
900 ((member (match-string 2) '("&" "%" "#"))
901 (if (equal (match-string 1) "\\")
902 (replace-match (match-string 2) t t)
903 (replace-match (concat (match-string 1) "\\"
904 (match-string 2)) t t)))
905 ((equal (match-string 2) "...")
906 (replace-match
907 (concat (match-string 1)
908 (org-export-latex-protect-string "\\ldots{}")) t t))
909 ((equal (match-string 2) "~")
910 (cond ((equal (match-string 1) "\\") nil)
911 ((eq 'org-link (get-text-property 0 'face (match-string 2)))
912 (replace-match (concat (match-string 1) "\\~") t t))
913 (t (replace-match
914 (org-export-latex-protect-string
915 (concat (match-string 1) "\\~{}")) t t))))
916 ((member (match-string 2) '("{" "}"))
917 (unless (save-match-data (org-inside-latex-math-p))
918 (if (equal (match-string 1) "\\")
919 (replace-match (match-string 2) t t)
920 (replace-match (concat (match-string 1) "\\"
921 (match-string 2)) t t)))))
922 (unless (save-match-data (org-inside-latex-math-p))
923 (cond ((equal (match-string 2) "\\")
924 (replace-match (or (save-match-data
925 (org-export-latex-treat-backslash-char
926 (match-string 1)
927 (or (match-string 3) "")))
928 "") t t))
929 ((member (match-string 2) '("_" "^"))
930 (replace-match (or (save-match-data
931 (org-export-latex-treat-sub-super-char
932 sub-superscript
933 (match-string 2)
934 (match-string 1)
935 (match-string 3))) "") t t)))))))
936 '(;"^\\([^\n$]*?\\|^\\)\\(\\\\?\\$\\)\\([^\n$]*\\)$"
937 "\\(\\(\\\\?\\$\\)\\)"
938 "\\([a-za-z0-9]+\\|[ \t\n]\\|\\b\\|\\\\\\)\\(_\\|\\^\\)\\([a-za-z0-9]+\\|[ \t\n]\\|[:punct:]\\|{[a-za-z0-9]+}\\|([a-za-z0-9]+)\\)"
939 "\\(.\\|^\\)\\(\\\\\\)\\([ \t\n]\\|[a-zA-Z&#%{}\"]+\\)"
940 "\\(.\\|^\\)\\(&\\)"
941 "\\(.\\|^\\)\\(#\\)"
942 "\\(.\\|^\\)\\(%\\)"
943 "\\(.\\|^\\)\\({\\)"
944 "\\(.\\|^\\)\\(}\\)"
945 "\\(.\\|^\\)\\(~\\)"
946 "\\(.\\|^\\)\\(\\.\\.\\.\\)"
947 ;; (?\< . "\\textless{}")
948 ;; (?\> . "\\textgreater{}")
951 (defun org-inside-latex-math-p ()
952 (get-text-property (point) 'org-latex-math))
954 (defun org-export-latex-treat-sub-super-char
955 (subsup char string-before string-after)
956 "Convert the \"_\" and \"^\" characters to LaTeX.
957 SUBSUP corresponds to the ^: option in the #+OPTIONS line.
958 Convert CHAR depending on STRING-BEFORE and STRING-AFTER."
959 (cond ((equal string-before "\\")
960 (concat string-before char string-after))
961 ;; this is part of a math formula
962 ((and (string-match "\\S-+" string-before)
963 (string-match "\\S-+" string-after))
964 (cond ((eq 'org-link (get-text-property 0 'face char))
965 (concat string-before "\\" char string-after))
966 ((save-match-data (org-inside-latex-math-p))
967 (if subsup
968 (cond ((eq 1 (length string-after))
969 (concat string-before char string-after))
970 ((string-match "[({]?\\([^)}]+\\)[)}]?" string-after)
971 (format "%s%s{%s}" string-before char
972 (match-string 1 string-after))))))
973 ((and (> (length string-after) 1)
974 (or (eq subsup t)
975 (and (equal subsup '{}) (eq (string-to-char string-after) ?\{)))
976 (string-match "[({]?\\([^)}]+\\)[)}]?" string-after))
977 (format "%s$%s{%s}$" string-before char
978 (if (> (match-end 1) (1+ (match-beginning 1)))
979 (concat "\\mathrm{" (match-string 1 string-after) "}")
980 (match-string 1 string-after))))
981 ((eq subsup t) (concat string-before "$" char string-after "$"))
982 (t (org-export-latex-protect-string
983 (concat string-before "\\" char "{}" string-after)))))
984 (t (org-export-latex-protect-string
985 (concat string-before "\\" char "{}" string-after)))))
987 (defun org-export-latex-treat-backslash-char (string-before string-after)
988 "Convert the \"$\" special character to LaTeX.
989 The conversion is made depending of STRING-BEFORE and STRING-AFTER."
990 (cond ((member (list string-after) org-html-entities)
991 ;; backslash is part of a special entity (like "\alpha")
992 (concat string-before "$\\"
993 (or (cdar (member (list string-after) org-html-entities))
994 string-after) "$"))
995 ((and (not (string-match "^[ \n\t]" string-after))
996 (not (string-match "[ \t]\\'\\|^" string-before)))
997 ;; backslash is inside a word
998 (org-export-latex-protect-string
999 (concat string-before "\\textbackslash{}" string-after)))
1000 ((not (or (equal string-after "")
1001 (string-match "^[ \t\n]" string-after)))
1002 ;; backslash might escape a character (like \#) or a user TeX
1003 ;; macro (like \setcounter)
1004 (org-export-latex-protect-string
1005 (concat string-before "\\" string-after)))
1006 ((and (string-match "^[ \t\n]" string-after)
1007 (string-match "[ \t\n]\\'" string-before))
1008 ;; backslash is alone, convert it to $\backslash$
1009 (org-export-latex-protect-string
1010 (concat string-before "\\textbackslash{}" string-after)))
1011 (t (org-export-latex-protect-string
1012 (concat string-before "\\textbackslash{}" string-after)))))
1014 (defun org-export-latex-keywords ()
1015 "Convert special keywords to LaTeX.
1016 Regexps are those from `org-export-latex-special-string-regexps'.
1017 If TIMESTAMPS, convert timestamps, otherwise delete them."
1018 (goto-char (point-min))
1019 (let ((re (concat org-maybe-keyword-time-regexp ".*")))
1020 (while (re-search-forward re nil t)
1021 (replace-match (format "\\\\texttt{%s}" (match-string 0)) t))))
1023 (defun org-export-latex-fixed-width (opt)
1024 "When OPT is non-nil convert fixed-width sections to LaTeX."
1025 (goto-char (point-min))
1026 (while (re-search-forward "^[ \t]*:" nil t)
1027 (if opt
1028 (progn (goto-char (match-beginning 0))
1029 (insert "\\begin{verbatim}\n")
1030 (while (looking-at "^\\([ \t]*\\):\\(.*\\)$")
1031 (replace-match (concat (match-string 1)
1032 (match-string 2)) t t)
1033 (forward-line))
1034 (insert "\\end{verbatim}\n\n"))
1035 (progn (goto-char (match-beginning 0))
1036 (while (looking-at "^\\([ \t]*\\):\\(.*\\)$")
1037 (replace-match (concat "%" (match-string 1)
1038 (match-string 2)) t t)
1039 (forward-line))))))
1042 (defvar org-table-last-alignment) ; defined in org-table.el
1043 (declare-function orgtbl-to-latex "org-table" (table params) t)
1044 (defun org-export-latex-tables (insert)
1045 "Convert tables to LaTeX and INSERT it."
1046 (goto-char (point-min))
1047 (while (re-search-forward "^\\([ \t]*\\)|" nil t)
1048 ;; FIXME really need to save-excursion?
1049 (save-excursion (org-table-align))
1050 (let* ((beg (org-table-begin))
1051 (end (org-table-end))
1052 (raw-table (buffer-substring beg end))
1053 fnum fields line lines olines gr colgropen line-fmt align
1054 caption label attr floatp longtblp)
1055 (if org-export-latex-tables-verbatim
1056 (let* ((tbl (concat "\\begin{verbatim}\n" raw-table
1057 "\\end{verbatim}\n")))
1058 (apply 'delete-region (list beg end))
1059 (insert (org-export-latex-protect-string tbl)))
1060 (progn
1061 (setq caption (org-find-text-property-in-string
1062 'org-caption raw-table)
1063 attr (org-find-text-property-in-string
1064 'org-attributes raw-table)
1065 label (org-find-text-property-in-string
1066 'org-label raw-table)
1067 longtblp (and attr (stringp attr)
1068 (string-match "\\<longtable\\>" attr))
1069 align (and attr (stringp attr)
1070 (string-match "\\<align=\\([^ \t\n\r,]+\\)" attr)
1071 (match-string 1 attr))
1072 floatp (or caption label))
1073 (setq lines (split-string raw-table "\n" t))
1074 (apply 'delete-region (list beg end))
1075 (when org-export-table-remove-special-lines
1076 (setq lines (org-table-clean-before-export lines)))
1077 ;; make a formatting string to reflect aligment
1078 (setq olines lines)
1079 (while (and (not line-fmt) (setq line (pop olines)))
1080 (unless (string-match "^[ \t]*|-" line)
1081 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
1082 (setq fnum (make-vector (length fields) 0))
1083 (setq line-fmt
1084 (mapconcat
1085 (lambda (x)
1086 (setq gr (pop org-table-colgroup-info))
1087 (format "%s%%s%s"
1088 (cond ((eq gr ':start)
1089 (prog1 (if colgropen "|" "")
1090 (setq colgropen t)))
1091 ((eq gr ':startend)
1092 (prog1 (if colgropen "|" "|")
1093 (setq colgropen nil)))
1094 (t ""))
1095 (if (memq gr '(:end :startend))
1096 (progn (setq colgropen nil) "|")
1097 "")))
1098 fnum ""))))
1099 ;; fix double || in line-fmt
1100 (setq line-fmt (replace-regexp-in-string "||" "|" line-fmt))
1101 ;; maybe remove the first and last "|"
1102 (when (and (not org-export-latex-tables-column-borders)
1103 (string-match "^\\(|\\)?\\(.+\\)|$" line-fmt))
1104 (setq line-fmt (match-string 2 line-fmt)))
1105 ;; format alignment
1106 (unless align
1107 (setq align (apply 'format
1108 (cons line-fmt
1109 (mapcar (lambda (x) (if x "r" "l"))
1110 org-table-last-alignment)))))
1111 ;; prepare the table to send to orgtbl-to-latex
1112 (setq lines
1113 (mapcar
1114 (lambda(elem)
1115 (or (and (string-match "[ \t]*|-+" elem) 'hline)
1116 (split-string (org-trim elem) "|" t)))
1117 lines))
1118 (when insert
1119 (insert (org-export-latex-protect-string
1120 (concat
1121 (if longtblp
1122 (concat "\\begin{longtable}{" align "}\n")
1123 (if floatp "\\begin{table}[htb]\n"))
1124 (if (or floatp longtblp)
1125 (format
1126 "\\caption{%s%s}"
1127 (if label (concat "\\\label{" label "}") "")
1128 (or caption "")))
1129 (if longtblp "\\\\\n" "\n")
1130 (if (not longtblp) "\\begin{center}\n")
1131 (if (not longtblp) (concat "\\begin{tabular}{" align "}\n"))
1132 (orgtbl-to-latex
1133 lines
1134 `(:tstart nil :tend nil
1135 :hlend ,(if longtblp
1136 (format "\\\\
1137 \\hline
1138 \\endhead
1139 \\hline\\multicolumn{%d}{r}{Continued on next page}\\
1140 \\endfoot
1141 \\endlastfoot" (length org-table-last-alignment))
1142 nil)))
1143 (if (not longtblp) (concat "\n\\end{tabular}"))
1144 (if longtblp "\n" "\n\\end{center}\n")
1145 (if longtblp
1146 "\\end{longtable}"
1147 (if floatp "\\end{table}"))))
1148 "\n\n")))))))
1150 (defun org-export-latex-fontify ()
1151 "Convert fontification to LaTeX."
1152 (goto-char (point-min))
1153 (while (re-search-forward org-emph-re nil t)
1154 ;; The match goes one char after the *string*
1155 (let ((emph (assoc (match-string 3)
1156 org-export-latex-emphasis-alist))
1157 rpl)
1158 (unless (get-text-property (1- (point)) 'org-protected)
1159 (setq rpl (concat (match-string 1)
1160 (format (org-export-latex-protect-char-in-string
1161 '("\\" "{" "}") (cadr emph))
1162 (match-string 4))
1163 (match-string 5)))
1164 (if (caddr emph)
1165 (setq rpl (org-export-latex-protect-string rpl)))
1166 (replace-match rpl t t)))
1167 (backward-char)))
1169 (defun org-export-latex-links ()
1170 ;; Make sure to use the LaTeX hyperref and graphicx package
1171 ;; or send some warnings.
1172 "Convert links to LaTeX."
1173 (goto-char (point-min))
1174 (while (re-search-forward org-bracket-link-analytic-regexp++ nil t)
1175 (org-if-unprotected
1176 (goto-char (match-beginning 0))
1177 (let* ((re-radio org-export-latex-all-targets-re)
1178 (remove (list (match-beginning 0) (match-end 0)))
1179 (raw-path (org-extract-attributes (match-string 3)))
1180 (full-raw-path (concat (match-string 1) raw-path))
1181 (desc (match-string 5))
1182 (type (or (match-string 2)
1183 (if (or (file-name-absolute-p raw-path)
1184 (string-match "^\\.\\.?/" raw-path))
1185 "file")))
1186 (coderefp (equal type "coderef"))
1187 (caption (org-find-text-property-in-string 'org-caption raw-path))
1188 (attr (org-find-text-property-in-string 'org-attributes raw-path))
1189 (label (org-find-text-property-in-string 'org-label raw-path))
1190 (floatp (or label caption))
1191 imgp radiop
1192 ;; define the path of the link
1193 (path (cond
1194 ((member type '("coderef"))
1195 raw-path)
1196 ((member type '("http" "https" "ftp"))
1197 (concat type ":" raw-path))
1198 ((and re-radio (string-match re-radio raw-path))
1199 (setq radiop t))
1200 ((equal type "mailto")
1201 (concat type ":" raw-path))
1202 ((equal type "file")
1203 (if (and (or (org-file-image-p (expand-file-name raw-path))
1204 (string-match "\\.\\(pdf\\|jpg\\|ps\\|eps\\)$"
1205 raw-path))
1206 (equal desc full-raw-path))
1207 (setq imgp t)
1208 (progn (when (string-match "\\(.+\\)::.+" raw-path)
1209 (setq raw-path (match-string 1 raw-path)))
1210 (if (file-exists-p raw-path)
1211 (concat type "://" (expand-file-name raw-path))
1212 (concat type "://" (org-export-directory
1213 :LaTeX org-export-latex-options-plist)
1214 raw-path))))))))
1215 ;; process with link inserting
1216 (apply 'delete-region remove)
1217 (cond ((and imgp (plist-get org-export-latex-options-plist :inline-images))
1218 (insert
1219 (concat
1220 (if floatp "\\begin{figure}[htb]\n")
1221 (format "\\centerline{\\includegraphics[%s]{%s}}\n"
1222 (or attr org-export-latex-image-default-option)
1223 (expand-file-name raw-path))
1224 (if floatp
1225 (format "\\caption{%s%s}\n"
1226 (if label (concat "\\label{" label "}") "")
1227 (or caption "")))
1228 (if floatp "\\end{figure}\n"))))
1229 (coderefp
1230 (insert (format
1231 (org-export-get-coderef-format path desc)
1232 (cdr (assoc path org-export-code-refs)))))
1233 (radiop (insert (format "\\hyperref[%s]{%s}"
1234 (org-solidify-link-text raw-path) desc)))
1235 ((not type)
1236 (insert (format "\\hyperref[%s]{%s}"
1237 (org-solidify-link-text raw-path) desc)))
1238 (path (insert (format "\\href{%s}{%s}" path desc)))
1239 (t (insert "\\texttt{" desc "}")))))))
1241 (defvar org-latex-entities) ; defined below
1242 (defvar org-latex-entities-regexp) ; defined below
1244 (defun org-export-latex-preprocess ()
1245 "Clean stuff in the LaTeX export."
1246 ;; Preserve line breaks
1247 (goto-char (point-min))
1248 (while (re-search-forward "\\\\\\\\" nil t)
1249 (add-text-properties (match-beginning 0) (match-end 0)
1250 '(org-protected t)))
1252 ;; Preserve latex environments
1253 (goto-char (point-min))
1254 (while (re-search-forward "^[ \t]*\\begin{\\([a-zA-Z]+\\)}" nil t)
1255 (let* ((start (progn (beginning-of-line) (point)))
1256 (end (or (and (re-search-forward
1257 (concat "^[ \t]*\\end{" (match-string 1) "}" nil t)
1258 (point-at-eol)))
1259 (point-max))))
1260 (add-text-properties start end '(org-protected t))))
1262 ;; Preserve math snippets
1264 (let* ((matchers (plist-get org-format-latex-options :matchers))
1265 (re-list org-latex-regexps)
1266 beg end re e m n block off)
1267 ;; Check the different regular expressions
1268 (while (setq e (pop re-list))
1269 (setq m (car e) re (nth 1 e) n (nth 2 e)
1270 block (if (nth 3 e) "\n\n" ""))
1271 (setq off (if (equal m "$") 1 0))
1272 (when (and (member m matchers) (not (equal m "begin")))
1273 (goto-char (point-min))
1274 (while (re-search-forward re nil t)
1275 (setq beg (+ (match-beginning 0) off) end (- (match-end 0) off))
1276 (add-text-properties beg end '(org-protected t org-latex-math t))))))
1278 ;; Convert LaTeX to \LaTeX{}
1279 (goto-char (point-min))
1280 (let ((case-fold-search nil) rpl)
1281 (while (re-search-forward "\\([^+_]\\)LaTeX" nil t)
1282 (replace-match (org-export-latex-protect-string
1283 (concat (match-string 1) "\\LaTeX{}")) t t)))
1285 ;; Convert blockquotes
1286 (goto-char (point-min))
1287 (while (search-forward "ORG-BLOCKQUOTE-START" nil t)
1288 (replace-match "\\begin{quote}" t t))
1289 (goto-char (point-min))
1290 (while (search-forward "ORG-BLOCKQUOTE-END" nil t)
1291 (replace-match "\\end{quote}" t t))
1293 ;; Convert verse
1294 (goto-char (point-min))
1295 (while (search-forward "ORG-VERSE-START" nil t)
1296 (replace-match "\\begin{verse}" t t))
1297 (goto-char (point-min))
1298 (while (search-forward "ORG-VERSE-END" nil t)
1299 (replace-match "\\end{verse}" t t))
1301 ;; Convert horizontal rules
1302 (goto-char (point-min))
1303 (while (re-search-forward "^----+.$" nil t)
1304 (replace-match (org-export-latex-protect-string "\\hrule") t t))
1306 ;; Protect LaTeX commands like \command[...]{...} or \command{...}
1307 (goto-char (point-min))
1308 (while (re-search-forward "\\\\[a-zA-Z]+\\(?:\\[.*\\]\\)?{.*}" nil t)
1309 (add-text-properties (match-beginning 0) (match-end 0)
1310 '(org-protected t)))
1312 ;; Protect LaTeX entities
1313 (goto-char (point-min))
1314 (while (re-search-forward org-latex-entities-regexp nil t)
1315 (add-text-properties (match-beginning 0) (match-end 0)
1316 '(org-protected t)))
1318 ;; Replace radio links
1319 (goto-char (point-min))
1320 (while (re-search-forward
1321 (concat "<<<?" org-export-latex-all-targets-re
1322 ">>>?\\((INVISIBLE)\\)?") nil t)
1323 (replace-match
1324 (org-export-latex-protect-string
1325 (format "\\label{%s}%s" (save-match-data (org-solidify-link-text
1326 (match-string 1)))
1327 (if (match-string 2) "" (match-string 1)))) t t))
1329 ;; Delete @<...> constructs
1330 ;; Thanks to Daniel Clemente for this regexp
1331 (goto-char (point-min))
1332 (while (re-search-forward "@<\\(?:[^\"\n]\\|\".*\"\\)*?>" nil t)
1333 (replace-match ""))
1335 ;; When converting to LaTeX, replace footnotes
1336 ;; FIXME: don't protect footnotes from conversion
1337 (when (plist-get org-export-latex-options-plist :footnotes)
1338 (goto-char (point-min))
1339 (while (re-search-forward "\\[\\([0-9]+\\)\\]" nil t)
1340 (when (save-match-data
1341 (save-excursion (beginning-of-line)
1342 (looking-at "[^:|#]")))
1343 (let ((foot-beg (match-beginning 0))
1344 (foot-end (match-end 0))
1345 (foot-prefix (match-string 0))
1346 footnote footnote-rpl)
1347 (save-excursion
1348 (if (not (re-search-forward (concat "^" (regexp-quote foot-prefix))
1349 nil t))
1350 (replace-match "$^{\\1}$")
1351 (replace-match "")
1352 (let ((end (save-excursion
1353 (if (re-search-forward "^$\\|^#.*$\\|\\[[0-9]+\\]" nil t)
1354 (match-beginning 0) (point-max)))))
1355 (setq footnote (concat (org-trim (buffer-substring (point) end))
1356 " ")) ; prevent last } being part of a link
1357 (delete-region (point) end))
1358 (goto-char foot-beg)
1359 (delete-region foot-beg foot-end)
1360 (unless (null footnote)
1361 (setq footnote-rpl (format "\\footnote{%s}" footnote))
1362 (add-text-properties 0 10 '(org-protected t) footnote-rpl)
1363 (add-text-properties (1- (length footnote-rpl))
1364 (length footnote-rpl)
1365 '(org-protected t) footnote-rpl)
1366 (insert footnote-rpl)))
1367 ))))
1369 ;; Remove footnote section tag for LaTeX
1370 (goto-char (point-min))
1371 (while (re-search-forward
1372 (concat "^" footnote-section-tag-regexp) nil t)
1373 (replace-match ""))))
1375 ;;; List handling:
1377 (defun org-export-latex-lists ()
1378 "Convert plain text lists in current buffer into LaTeX lists."
1379 (goto-char (point-min))
1380 (while (re-search-forward org-list-beginning-re nil t)
1381 (org-if-unprotected
1382 (beginning-of-line)
1383 (insert (org-list-to-latex (org-list-parse-list t)
1384 org-export-latex-list-parameters))
1385 "\n")))
1387 (defconst org-latex-entities
1388 '("\\!"
1389 "\\'"
1390 "\\+"
1391 "\\,"
1392 "\\-"
1393 "\\:"
1394 "\\;"
1395 "\\<"
1396 "\\="
1397 "\\>"
1398 "\\Huge"
1399 "\\LARGE"
1400 "\\Large"
1401 "\\Styles"
1402 "\\\\"
1403 "\\`"
1404 "\\addcontentsline"
1405 "\\address"
1406 "\\addtocontents"
1407 "\\addtocounter"
1408 "\\addtolength"
1409 "\\addvspace"
1410 "\\alph"
1411 "\\appendix"
1412 "\\arabic"
1413 "\\author"
1414 "\\begin{array}"
1415 "\\begin{center}"
1416 "\\begin{description}"
1417 "\\begin{enumerate}"
1418 "\\begin{eqnarray}"
1419 "\\begin{equation}"
1420 "\\begin{figure}"
1421 "\\begin{flushleft}"
1422 "\\begin{flushright}"
1423 "\\begin{itemize}"
1424 "\\begin{list}"
1425 "\\begin{minipage}"
1426 "\\begin{picture}"
1427 "\\begin{quotation}"
1428 "\\begin{quote}"
1429 "\\begin{tabbing}"
1430 "\\begin{table}"
1431 "\\begin{tabular}"
1432 "\\begin{thebibliography}"
1433 "\\begin{theorem}"
1434 "\\begin{titlepage}"
1435 "\\begin{verbatim}"
1436 "\\begin{verse}"
1437 "\\bf"
1438 "\\bf"
1439 "\\bibitem"
1440 "\\bigskip"
1441 "\\cdots"
1442 "\\centering"
1443 "\\circle"
1444 "\\cite"
1445 "\\cleardoublepage"
1446 "\\clearpage"
1447 "\\cline"
1448 "\\closing"
1449 "\\dashbox"
1450 "\\date"
1451 "\\ddots"
1452 "\\dotfill"
1453 "\\em"
1454 "\\fbox"
1455 "\\flushbottom"
1456 "\\fnsymbol"
1457 "\\footnote"
1458 "\\footnotemark"
1459 "\\footnotesize"
1460 "\\footnotetext"
1461 "\\frac"
1462 "\\frame"
1463 "\\framebox"
1464 "\\hfill"
1465 "\\hline"
1466 "\\hrulespace"
1467 "\\hspace"
1468 "\\huge"
1469 "\\hyphenation"
1470 "\\include"
1471 "\\includeonly"
1472 "\\indent"
1473 "\\input"
1474 "\\it"
1475 "\\kill"
1476 "\\label"
1477 "\\large"
1478 "\\ldots"
1479 "\\line"
1480 "\\linebreak"
1481 "\\linethickness"
1482 "\\listoffigures"
1483 "\\listoftables"
1484 "\\location"
1485 "\\makebox"
1486 "\\maketitle"
1487 "\\mark"
1488 "\\mbox"
1489 "\\medskip"
1490 "\\multicolumn"
1491 "\\multiput"
1492 "\\newcommand"
1493 "\\newcounter"
1494 "\\newenvironment"
1495 "\\newfont"
1496 "\\newlength"
1497 "\\newline"
1498 "\\newpage"
1499 "\\newsavebox"
1500 "\\newtheorem"
1501 "\\nocite"
1502 "\\nofiles"
1503 "\\noindent"
1504 "\\nolinebreak"
1505 "\\nopagebreak"
1506 "\\normalsize"
1507 "\\onecolumn"
1508 "\\opening"
1509 "\\oval"
1510 "\\overbrace"
1511 "\\overline"
1512 "\\pagebreak"
1513 "\\pagenumbering"
1514 "\\pageref"
1515 "\\pagestyle"
1516 "\\par"
1517 "\\parbox"
1518 "\\put"
1519 "\\raggedbottom"
1520 "\\raggedleft"
1521 "\\raggedright"
1522 "\\raisebox"
1523 "\\ref"
1524 "\\rm"
1525 "\\roman"
1526 "\\rule"
1527 "\\savebox"
1528 "\\sc"
1529 "\\scriptsize"
1530 "\\setcounter"
1531 "\\setlength"
1532 "\\settowidth"
1533 "\\sf"
1534 "\\shortstack"
1535 "\\signature"
1536 "\\sl"
1537 "\\small"
1538 "\\smallskip"
1539 "\\sqrt"
1540 "\\tableofcontents"
1541 "\\telephone"
1542 "\\thanks"
1543 "\\thispagestyle"
1544 "\\tiny"
1545 "\\title"
1546 "\\tt"
1547 "\\twocolumn"
1548 "\\typein"
1549 "\\typeout"
1550 "\\underbrace"
1551 "\\underline"
1552 "\\usebox"
1553 "\\usecounter"
1554 "\\value"
1555 "\\vdots"
1556 "\\vector"
1557 "\\verb"
1558 "\\vfill"
1559 "\\vline"
1560 "\\vspace")
1561 "A list of LaTeX commands to be protected when performing conversion.")
1563 (defconst org-latex-entities-regexp
1564 (let (names rest)
1565 (dolist (x org-latex-entities)
1566 (if (string-match "[a-z][A-Z]$" x)
1567 (push x names)
1568 (push x rest)))
1569 (concat "\\(" (regexp-opt (nreverse names)) "\\>\\)"
1570 "\\|\\(" (regexp-opt (nreverse rest)) "\\)")))
1572 (provide 'org-export-latex)
1574 ;; arch-tag: 23c2b87d-da04-4c2d-ad2d-1eb6487bc3ad
1576 ;;; org-export-latex.el ends here