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