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