Release 5.10a
[org-mode.git] / org-export-latex.el
blob0fbd514fc5c6347610b5e5d07dbe8dc0e7eedf0e
1 ;;; org-export-latex.el --- latex exporter for org-mode
2 ;; copyright (c) 2007 free software foundation, inc.
3 ;;
4 ;; Author: Bastien Guerry <bzg AT altern DOT org>
5 ;; Keywords: Org organizer latex export convert
6 ;; Homepage: http://www.cognition.ens.fr/~guerry/u/org-export-latex.el
7 ;; Version: 5.10
8 ;;
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software; you can redistribute it and/or modify it
12 ;; under the terms of the GNU General Public License as published by the
13 ;; Free Software Foundation; either version 3, or (at your option) any
14 ;; later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful, but WITHOUT
17 ;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
18 ;; FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
19 ;; more details.
20 ;;
21 ;; You should have received a copy of the GNU General Public License along
22 ;; with GNU Emacs; see the file COPYING. If not, write to the Free Software
23 ;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
24 ;; 02110-1301, USA.
26 ;;; Commentary:
28 ;; This library implements a LaTeX exporter for org-mode.
29 ;;
30 ;; Put this file into your load-path and the following into your ~/.emacs:
31 ;; (require 'org-export-latex)
32 ;;
33 ;; The interactive functions are similar to those of the HTML exporter:
34 ;;
35 ;; M-x `org-export-as-latex'
36 ;; M-x `org-export-as-latex-batch'
37 ;; M-x `org-export-as-latex-to-buffer'
38 ;; M-x `org-export-region-as-latex'
39 ;; M-x `org-replace-region-by-latex'
41 ;;; Code:
43 (eval-when-compile
44 (require 'cl))
46 (require 'footnote)
47 (require 'org)
49 ;;; Variables:
50 (defvar org-latex-options-plist nil)
51 (defvar org-latex-todo-keywords-1 nil)
52 (defvar org-latex-all-targets-regexp nil)
53 (defvar org-latex-add-level 0)
54 (defvar org-latex-sectioning-depth 0)
55 (defvar org-export-latex-list-beginning-re
56 "^\\([ \t]*\\)\\([-+]\\|[0-9]+\\(?:\\.\\|)\\)\\) *?")
58 (defvar org-latex-special-string-regexps
59 '(org-ts-regexp
60 org-scheduled-string
61 org-deadline-string
62 org-clock-string)
63 "A list of regexps to convert as special keywords.")
65 (defvar latexp) ; dynamically scoped from org.el
66 (defvar re-quote) ; dynamically scoped from org.el
67 (defvar commentsp) ; dynamically scoped from org.el
69 ;;; Custom variables:
70 (defcustom org-export-latex-sectioning-alist
71 '((1 "\\section{%s}" "\\section*{%s}")
72 (2 "\\subsection{%s}" "\\subsection*{%s}")
73 (3 "\\subsubsection{%s}" "\\subsubsection*{%s}")
74 (4 "\\paragraph{%s}" "\\paragraph*{%s}")
75 (5 "\\subparagraph{%s}" "\\subparagraph*{%s}"))
76 "Alist of LaTeX commands for inserting sections.
77 Here is the structure of each cell:
79 \(level unnumbered-section numbered-section\)
81 The %s formatter will be replaced by the title of the section."
82 :group 'org-export-latex
83 :type 'alist)
85 (defcustom org-export-latex-emphasis-alist
86 '(("*" "\\textbf{%s}" nil)
87 ("/" "\\emph{%s}" nil)
88 ("_" "\\underline{%s}" nil)
89 ("+" "\\texttt{%s}" nil)
90 ("=" "\\texttt{%s}" t))
91 "Alist of LaTeX expressions to convert emphasis fontifiers.
92 Each element of the list is a list of three elements.
93 The first element is the character used as a marker for fontification.
94 The second element is a formatting string to wrap fontified text with.
95 If non-nil the third element tells to protect converted text from other
96 conversions."
97 :group 'org-export-latex
98 :type 'alist)
100 (defcustom org-export-latex-preamble
101 "\\documentclass[11pt,a4paper]{article}
102 \\usepackage[utf8]{inputenc}
103 \\usepackage[T1]{fontenc}
104 \\usepackage{hyperref}"
105 "Preamble to be inserted at the very beginning of the LaTeX export."
106 :group 'org-export-latex
107 :type 'string)
109 (defcustom org-export-latex-date-format
110 "%d %B %Y"
111 "Format string for \\date{...}."
112 :group 'org-export-latex
113 :type 'string)
115 (defcustom org-export-latex-tables-verbatim nil
116 "When non-nil, export tables as verbatim."
117 :group 'org-export-latex
118 :type 'boolean)
120 (defcustom org-export-latex-packages-alist nil
121 "Alist of packages to be inserted in the preamble.
122 Each cell is of the forma \( option . package \).
124 For example:
126 \(setq org-export-latex-packages-alist
127 '((\"french\" \"babel\"))"
128 :group 'org-export-latex
129 :type 'alist)
131 (defcustom org-export-latex-low-levels 'description
132 "Choice for converting sections that are below the current
133 admitted level of sectioning. This can be either nil (ignore the
134 sections), 'description (convert them as description lists) or a
135 string to be used instead of \\section{%s} (a %s for inserted the
136 headline is mandatory)."
137 :group 'org-export-latex
138 :type '(choice (const :tag "Ignore" nil)
139 (symbol :tag "Convert as descriptive list" description)
140 (string :tag "Use a section string" :value "\\subparagraph{%s}")))
142 (defcustom org-export-latex-remove-from-headlines
143 '(:todo t :priority t :tags t)
144 "A plist of keywords to remove from headlines.
145 Non-nil means remove this keyword type from the headline.
147 Don't remove the keys, just change their values."
148 :type 'plist
149 :group 'org-export-latex)
151 (defcustom org-export-latex-image-default-option "width=10em"
152 "Default option for images."
153 :group 'org-export-latex
154 :type '(string))
156 (defcustom org-export-latex-coding-system nil
157 "Coding system for the exported LaTex file."
158 :group 'org-export-latex
159 :type 'coding-system)
161 ;; FIXME Do we want this one?
162 ;; (defun org-export-as-latex-and-open (arg) ...)
164 ;;; Autoload functions:
165 ;;;###autoload
166 (defun org-export-as-latex-batch ()
167 "Call `org-export-as-latex', may be used in batch processing as
168 emacs --batch
169 --load=$HOME/lib/emacs/org.el
170 --eval \"(setq org-export-headline-levels 2)\"
171 --visit=MyFile --funcall org-export-as-latex-batch"
172 (org-export-as-latex org-export-headline-levels 'hidden))
174 ;;;###autoload
175 (defun org-export-as-latex-to-buffer (arg)
176 "Call `org-exort-as-latex` with output to a temporary buffer.
177 No file is created. The prefix ARG is passed through to `org-export-as-latex'."
178 (interactive "P")
179 (org-export-as-latex arg nil nil "*Org LaTeX Export*")
180 (switch-to-buffer-other-window "*Org LaTeX Export*"))
182 ;;;###autoload
183 (defun org-replace-region-by-latex (beg end)
184 "Replace the region from BEG to END with its LaTeX export.
185 It assumes the region has `org-mode' syntax, and then convert it to
186 LaTeX. This can be used in any buffer. For example, you could
187 write an itemized list in `org-mode' syntax in an LaTeX buffer and
188 then use this command to convert it."
189 (interactive "r")
190 (let (reg latex buf)
191 (save-window-excursion
192 (if (org-mode-p)
193 (setq latex (org-export-region-as-latex
194 beg end t 'string))
195 (setq reg (buffer-substring beg end)
196 buf (get-buffer-create "*Org tmp*"))
197 (save-excursion
198 (set-buffer buf)
199 (erase-buffer)
200 (insert reg)
201 (org-mode)
202 (setq latex (org-export-region-as-latex
203 (point-min) (point-max) t 'string)))
204 (kill-buffer buf)))
205 (delete-region beg end)
206 (insert latex)))
208 ;;;###autoload
209 (defun org-export-region-as-latex (beg end &optional body-only buffer)
210 "Convert region from BEG to END in `org-mode' buffer to LaTeX.
211 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
212 contents, and only produce the region of converted text, useful for
213 cut-and-paste operations.
214 If BUFFER is a buffer or a string, use/create that buffer as a target
215 of the converted LaTeX. If BUFFER is the symbol `string', return the
216 produced LaTeX as a string and leave not buffer behind. For example,
217 a Lisp program could call this function in the following way:
219 (setq latex (org-export-region-as-latex beg end t 'string))
221 When called interactively, the output buffer is selected, and shown
222 in a window. A non-interactive call will only retunr the buffer."
223 (interactive "r\nP")
224 (when (interactive-p)
225 (setq buffer "*Org LaTeX Export*"))
226 (let ((transient-mark-mode t) (zmacs-regions t)
227 rtn)
228 (goto-char end)
229 (set-mark (point)) ;; to activate the region
230 (goto-char beg)
231 (setq rtn (org-export-as-latex
232 nil nil nil
233 buffer body-only))
234 (if (fboundp 'deactivate-mark) (deactivate-mark))
235 (if (and (interactive-p) (bufferp rtn))
236 (switch-to-buffer-other-window rtn)
237 rtn)))
239 ;;;###autoload
240 (defun org-export-as-latex (arg &optional hidden ext-plist
241 to-buffer body-only)
242 "Export current buffer to a LaTeX file."
243 (interactive "P")
244 ;; Make sure we have a file name when we need it.
245 (when (and (not (or to-buffer body-only))
246 (not buffer-file-name))
247 (if (buffer-base-buffer)
248 (org-set-local 'buffer-file-name
249 (with-current-buffer (buffer-base-buffer)
250 buffer-file-name))
251 (error "Need a file name to be able to export")))
253 (message "Exporting to LaTeX...")
254 (org-update-radio-target-regexp)
255 (org-export-latex-set-initial-vars ext-plist)
256 (let* ((opt-plist org-latex-options-plist)
257 (filename (concat (file-name-as-directory
258 (org-export-directory :LaTeX ext-plist))
259 (file-name-sans-extension
260 (file-name-nondirectory ;sans-extension
261 buffer-file-name)) ".tex"))
262 (filename (if (equal (file-truename filename)
263 (file-truename buffer-file-name))
264 (concat filename ".tex")
265 filename))
266 (buffer (if to-buffer
267 (cond
268 ((eq to-buffer 'string) (get-buffer-create
269 "*Org LaTeX Export*"))
270 (t (get-buffer-create to-buffer)))
271 (find-file-noselect filename)))
272 (region-p (org-region-active-p))
273 (odd org-odd-levels-only)
274 (preamble (org-export-latex-make-preamble opt-plist))
275 (skip (plist-get opt-plist :skip-before-1st-heading))
276 (text (plist-get opt-plist :text))
277 (first-lines (if skip "" (org-export-latex-first-lines)))
278 (coding-system (and (boundp 'buffer-file-coding-system)
279 buffer-file-coding-system))
280 (coding-system-for-write (or org-export-latex-coding-system
281 coding-system))
282 (save-buffer-coding-system (or org-export-latex-coding-system
283 coding-system))
284 (region (buffer-substring
285 (if region-p (region-beginning) (point-min))
286 (if region-p (region-end) (point-max))))
287 (string-for-export
288 (org-cleaned-string-for-export
289 region :emph-multiline t
290 :for-LaTeX t
291 :comments nil
292 :add-text text
293 :skip-before-1st-heading skip
294 :LaTeX-fragments nil)))
295 (set-buffer buffer)
296 (erase-buffer)
298 (unless body-only (insert preamble))
299 (when text (insert (org-export-latex-content text) "\n\n"))
300 (unless skip (insert first-lines))
302 ;; handle the case where the region does not begin with a section
303 (when region-p
304 (insert (with-temp-buffer
305 (insert string-for-export)
306 (org-export-latex-first-lines))))
308 (org-export-latex-global
309 (with-temp-buffer
310 (insert string-for-export)
311 (goto-char (point-min))
312 (re-search-forward "^\\(\\*+\\) " nil t)
313 (let* ((asters (length (match-string 1)))
314 (level (if odd (- asters 2) (- asters 1))))
315 (setq org-latex-add-level
316 (if odd (1- (/ (1+ asters) 2)) (1- asters)))
317 (org-export-latex-parse-global level odd))))
319 (unless body-only (insert "\n\\end{document}"))
320 (or to-buffer (save-buffer))
321 (goto-char (point-min))
322 (message "Exporting to LaTeX...done")
323 (if (eq to-buffer 'string)
324 (prog1 (buffer-substring (point-min) (point-max))
325 (kill-buffer (current-buffer)))
326 (current-buffer))))
329 ;;; Parsing functions:
330 (defun org-export-latex-parse-global (level odd)
331 "Parse the current buffer recursively, starting at LEVEL.
332 If ODD is non-nil, assume the buffer only contains odd sections.
333 Return A list reflecting the document structure."
334 (save-excursion
335 (goto-char (point-min))
336 (let* ((cnt 0) output
337 (depth org-latex-sectioning-depth))
338 (while (re-search-forward
339 (concat "^\\(\\(?:\\*\\)\\{"
340 (number-to-string (+ (if odd 2 1) level))
341 "\\}\\) \\(.*\\)$")
342 ;; make sure that there is no upper heading
343 (when (> level 0)
344 (save-excursion
345 (save-match-data
346 (re-search-forward
347 (concat "^\\(\\(?:\\*\\)\\{"
348 (number-to-string level)
349 "\\}\\) \\(.*\\)$") nil t)))) t)
350 (setq cnt (1+ cnt))
351 (let* ((pos (match-beginning 0))
352 (heading (match-string 2))
353 (nlevel (if odd (/ (+ 3 level) 2) (1+ level))))
354 (save-excursion
355 (narrow-to-region
356 (point)
357 (save-match-data
358 (if (re-search-forward
359 (concat "^\\(\\(?:\\*\\)\\{"
360 (number-to-string (+ (if odd 2 1) level))
361 "\\}\\) \\(.*\\)$") nil t)
362 (match-beginning 0)
363 (point-max))))
364 (goto-char (point-min))
365 (setq output
366 (append output
367 (list
368 (list
369 `(pos . ,pos)
370 `(level . ,nlevel)
371 `(occur . ,cnt)
372 `(heading . ,heading)
373 `(content . ,(org-export-latex-parse-content))
374 `(subcontent . ,(org-export-latex-parse-subcontent
375 level odd)))))))
376 (widen)))
377 (list output))))
379 (defun org-export-latex-parse-list (&optional delete)
380 "Parse the list at point.
381 Return a list containing first level items as strings and
382 sublevels as list of strings."
383 (let ((start (point))
384 ;; Find the end of the list
385 (end (save-excursion
386 (catch 'exit
387 (while (or (looking-at org-export-latex-list-beginning-re)
388 (looking-at "^[ \t]+\\|^$"))
389 (if (eq (point) (point-max))
390 (throw 'exit (point-max)))
391 (forward-line 1))) (point)))
392 output itemsep)
393 (while (re-search-forward org-export-latex-list-beginning-re end t)
394 (setq itemsep (if (save-match-data
395 (string-match "^[0-9]" (match-string 2)))
396 "[0-9]+\\(?:\\.\\|)\\)" "[-+]"))
397 (let* ((indent1 (match-string 1))
398 (nextitem (save-excursion
399 (save-match-data
400 (or (and (re-search-forward
401 (concat "^" indent1 itemsep " *?") end t)
402 (match-beginning 0)) end))))
403 (item (buffer-substring
404 (point)
405 (or (and (re-search-forward
406 org-export-latex-list-beginning-re end t)
407 (goto-char (match-beginning 0)))
408 (goto-char end))))
409 (nextindent (match-string 1))
410 (item (org-trim item))
411 (item (if (string-match "^\\[.+\\]" item)
412 (replace-match "\\\\texttt{\\&}"
413 t nil item) item)))
414 (push item output)
415 (when (> (length nextindent)
416 (length indent1))
417 (narrow-to-region (point) nextitem)
418 (push (org-export-latex-parse-list) output)
419 (widen))))
420 (when delete (delete-region start end))
421 (setq output (nreverse output))
422 (push (if (string-match "^\\[0" itemsep)
423 'ordered 'unordered) output)))
425 (defun org-export-latex-parse-content ()
426 "Extract the content of a section."
427 (let ((beg (point))
428 (end (if (re-search-forward "^\\(\\*\\)+ .*$" nil t)
429 (progn (beginning-of-line) (point))
430 (point-max))))
431 (buffer-substring beg end)))
433 (defun org-export-latex-parse-subcontent (level odd)
434 "Extract the subcontent of a section at LEVEL.
435 If ODD Is non-nil, assume subcontent only contains odd sections."
436 (if (not (re-search-forward
437 (concat "^\\(\\(?:\\*\\)\\{"
438 (number-to-string (+ (if odd 4 2) level))
439 "\\}\\) \\(.*\\)$")
440 nil t))
441 nil ; subcontent is nil
442 (org-export-latex-parse-global (+ (if odd 2 1) level) odd)))
444 ;;; Rendering functions:
445 (defun org-export-latex-global (content)
446 "Export CONTENT to LaTeX.
447 CONTENT is an element of the list produced by
448 `org-export-latex-parse-global'."
449 (if (eq (car content) 'subcontent)
450 (mapc 'org-export-latex-sub (cdr content))
451 (org-export-latex-sub (car content))))
453 (defun org-export-latex-sub (subcontent)
454 "Export the list SUBCONTENT to LaTeX.
455 SUBCONTENT is an alist containing information about the headline
456 and its content."
457 (let ((num (plist-get org-latex-options-plist :section-numbers)))
458 (mapc (lambda(x) (org-export-latex-subcontent x num)) subcontent)))
460 (defun org-export-latex-subcontent (subcontent num)
461 "Export each cell of SUBCONTENT to LaTeX."
462 (let ((heading (org-export-latex-fontify-headline
463 (cdr (assoc 'heading subcontent))))
464 (level (- (cdr (assoc 'level subcontent))
465 org-latex-add-level))
466 (occur (number-to-string (cdr (assoc 'occur subcontent))))
467 (content (cdr (assoc 'content subcontent)))
468 (subcontent (cadr (assoc 'subcontent subcontent))))
469 (cond
470 ;; Normal conversion
471 ((<= level org-latex-sectioning-depth)
472 (let ((sec (assoc level org-export-latex-sectioning-alist)))
473 (insert (format (if num (cadr sec) (caddr sec)) heading) "\n"))
474 (insert (org-export-latex-content content))
475 (cond ((stringp subcontent) (insert subcontent))
476 ((listp subcontent) (org-export-latex-sub subcontent))))
477 ;; At a level under the hl option: we can drop this subsection
478 ((> level org-latex-sectioning-depth)
479 (cond ((eq org-export-latex-low-levels 'description)
480 (insert (format "\\begin{description}\n\n\\item[%s]\n\n" heading))
481 (insert (org-export-latex-content content))
482 (cond ((stringp subcontent) (insert subcontent))
483 ((listp subcontent) (org-export-latex-sub subcontent)))
484 (insert "\\end{description}\n"))
485 ((stringp org-export-latex-low-levels)
486 (insert (format org-export-latex-low-levels heading) "\n")
487 (insert (org-export-latex-content content))
488 (cond ((stringp subcontent) (insert subcontent))
489 ((listp subcontent) (org-export-latex-sub subcontent)))))))))
492 ;;; Exporting internals:
493 (defun org-latex-protect (string)
494 (add-text-properties 0 (length string) '(org-protected t) string) string)
496 (defun org-export-latex-protect-char-in-string (char-list string)
497 "Add org-protected text-property to char from CHAR-LIST in STRING."
498 (with-temp-buffer
499 (save-match-data
500 (insert string)
501 (goto-char (point-min))
502 (while (re-search-forward (regexp-opt char-list) nil t)
503 (add-text-properties (match-beginning 0)
504 (match-end 0) '(org-protected t)))
505 (buffer-string))))
507 (defun org-export-latex-set-initial-vars (ext-plist)
508 "Store org local variables required for LaTeX export.
509 EXT-PLIST is an optional additional plist."
510 (setq org-latex-todo-keywords-1 org-todo-keywords-1
511 org-latex-all-targets-regexp
512 (org-make-target-link-regexp (org-all-targets))
513 org-latex-options-plist
514 (org-combine-plists (org-default-export-plist) ext-plist
515 (org-infile-export-plist))
516 org-latex-sectioning-depth
517 (let ((hl-levels (plist-get org-latex-options-plist :headline-levels))
518 (sec-depth (length org-export-latex-sectioning-alist)))
519 ;; Fall back on org-export-latex-sectioning-alist length if
520 ;; headline-levels goes beyond it
521 (if (> hl-levels sec-depth) sec-depth hl-levels))))
523 (defun org-export-latex-make-preamble (opt-plist)
524 "Make the LaTeX preamble and return it as a string.
525 Argument OPT-PLIST is the options plist for current buffer."
526 (let ((toc (plist-get opt-plist :table-of-contents)))
527 (concat (if (plist-get opt-plist :time-stamp-file)
528 (format-time-string "% Created %Y-%m-%d %a %H:%M\n"))
530 ;; LaTeX custom preamble
531 org-export-latex-preamble "\n"
533 ;; LaTeX packages
534 (if org-export-latex-packages-alist
535 (mapconcat (lambda(p)
536 (if (equal "" (car p))
537 (format "\\usepackage{%s}" (cadr p))
538 (format "\\usepackage[%s]{%s}"
539 (car p) (cadr p))))
540 org-export-latex-packages-alist "\n") "")
541 "\n\\begin{document}\n\n"
543 ;; title
544 (format
545 "\\title{%s}\n"
546 (or (plist-get opt-plist :title)
547 (and (not
548 (plist-get opt-plist :skip-before-1st-heading))
549 (org-export-grab-title-from-buffer))
550 (and buffer-file-name
551 (file-name-sans-extension
552 (file-name-nondirectory buffer-file-name)))
553 "UNTITLED"))
555 ;; author info
556 (if (plist-get opt-plist :author-info)
557 (format "\\author{%s}\n"
558 (or (plist-get opt-plist :author) user-full-name))
559 (format "%%\\author{%s}\n"
560 (or (plist-get opt-plist :author) user-full-name)))
562 ;; date
563 (format "\\date{%s}\n"
564 (format-time-string
565 (or (plist-get opt-plist :date)
566 org-export-latex-date-format)))
568 "\\maketitle\n\n"
569 ;; table of contents
570 (if (and (plist-get opt-plist :section-numbers) toc)
571 (format "\\setcounter{tocdepth}{%s}\n"
572 (min toc (plist-get opt-plist :headline-levels))) "")
573 (if (and (plist-get opt-plist :section-numbers) toc)
574 "\\tableofcontents\n" "\n"))))
576 (defun org-export-latex-first-lines (&optional comments)
577 "Export the first lines before first headline.
578 COMMENTS is either nil to replace them with the empty string or a
579 formatting string like %%%%s if we want to comment them out."
580 (save-excursion
581 (goto-char (point-min))
582 (let* ((end (if (re-search-forward "^\\*" nil t)
583 (goto-char (match-beginning 0))
584 (goto-char (point-max)))))
585 (org-export-latex-content
586 (org-cleaned-string-for-export
587 (buffer-substring (point-min) end)
588 :for-LaTeX t
589 :emph-multiline t
590 :add-text nil
591 :comments nil
592 :skip-before-1st-heading nil
593 :LaTeX-fragments nil)))))
595 (defun org-export-latex-keywords-maybe (remove-list)
596 "Maybe remove keywords depending on rules in REMOVE-LIST."
597 (goto-char (point-min))
598 (let ((re-todo (mapconcat 'identity org-latex-todo-keywords-1 "\\|")))
599 ;; convert TODO keywords
600 (when (re-search-forward (concat "^\\(" re-todo "\\)") nil t)
601 (if (plist-get remove-list :todo)
602 (replace-match "")
603 (replace-match (format "\\texttt{%s}" (match-string 1)) t t)))
604 ;; convert priority string
605 (when (re-search-forward "\\[\\\\#.\\]" nil t)
606 (if (plist-get remove-list :priority)
607 (replace-match "")
608 (replace-match (format "\\texttt{%s}" (match-string 0)) t t)))
609 ;; convert tags
610 (when (re-search-forward "\\(:[a-zA-Z0-9]+\\)+:" nil t)
611 (if (or (not org-export-with-tags)
612 (plist-get remove-list :tags))
613 (replace-match "")
614 (replace-match (format "\\texttt{%s}" (match-string 0)) t t)))))
616 (defun org-export-latex-fontify-headline (headline)
617 "Fontify special words in a HEADLINE."
618 (with-temp-buffer
619 ;; FIXME: org-inside-LaTeX-fragment-p doesn't work when the $...$ is at
620 ;; the beginning of the buffer - inserting "\n" is safe here though.
621 (insert "\n" headline)
622 (goto-char (point-min))
623 (when (plist-get org-latex-options-plist :emphasize)
624 (org-export-latex-fontify))
625 (org-export-latex-special-chars
626 (plist-get org-latex-options-plist :sub-superscript))
627 (org-export-latex-keywords-maybe
628 org-export-latex-remove-from-headlines)
629 (org-export-latex-links)
630 (org-trim (buffer-substring-no-properties (point-min) (point-max)))))
632 (defun org-export-latex-content (content)
633 "Convert CONTENT string to LaTeX."
634 (with-temp-buffer
635 (insert content)
636 (org-export-latex-quotation-marks)
637 (when (plist-get org-latex-options-plist :emphasize)
638 (org-export-latex-fontify))
639 (org-export-latex-special-chars
640 (plist-get org-latex-options-plist :sub-superscript))
641 (org-export-latex-links)
642 (org-export-latex-keywords
643 (plist-get org-latex-options-plist :timestamps))
644 (org-export-latex-lists)
645 (org-export-latex-tables
646 (plist-get org-latex-options-plist :tables))
647 (org-export-latex-fixed-width
648 (plist-get org-latex-options-plist :fixed-width))
649 (buffer-substring (point-min) (point-max))))
651 (defun org-export-latex-quotation-marks ()
652 "Export question marks depending on language conventions.
653 Local definition of the language overrides
654 `org-export-latex-quotation-marks-convention' which overrides
655 `org-export-default-language'."
656 (let* ((lang (plist-get org-latex-options-plist :language))
657 (quote-rpl (if (equal lang "fr")
658 '(("\\(\\s-\\)\"" "«~")
659 ("\\(\\S-\\)\"" "~»")
660 ("\\(\\s-\\)'" "`"))
661 '(("\\(\\s-\\)\"" "``")
662 ("\\(\\S-\\)\"" "''")
663 ("\\(\\s-\\)'" "`")))))
664 (mapc (lambda(l) (goto-char (point-min))
665 (while (re-search-forward (car l) nil t)
666 (let ((rpl (concat (match-string 1) (cadr l))))
667 (org-latex-protect rpl)
668 (org-if-unprotected
669 (replace-match rpl t t))))) quote-rpl)))
671 ;; | chars/string in Org | normal environment | math environment |
672 ;; |-----------------------+-----------------------+-----------------------|
673 ;; | & # % $ | \& \# \% \$ | \& \# \% \$ |
674 ;; | { } _ ^ \ | \{ \} \_ \^ \\ | { } _ ^ \ |
675 ;; |-----------------------+-----------------------+-----------------------|
676 ;; | a_b and a^b | $a_b$ and $a^b$ | a_b and a^b |
677 ;; | a_abc and a_{abc} | $a_a$bc and $a_{abc}$ | a_abc and a_{abc} |
678 ;; | \tau and \mu | $\tau$ and $\mu$ | \tau and \mu |
679 ;; |-----------------------+-----------------------+-----------------------|
680 ;; | \_ \^ | \_ \^ | \_ \^ |
681 ;; | \(a=\mu\mbox{m}\) | \(a=\mu\mbox{m}\) | \(a=\mu\mbox{m}\) |
682 ;; | \[\beta^2-a=0\] | \[\beta^2-a=0\] | \[\beta^2-a=0\] |
683 ;; | $x=22\tau$ | $x=22\tau$ | $x=22\tau$ |
684 ;; | $$\alpha=\sqrt{a^3}$$ | $$\alpha=\sqrt{a^3}$$ | $$\alpha=\sqrt{a^3}$$ |
686 (defun org-export-latex-special-chars (sub-superscript)
687 "Export special characters to LaTeX.
688 If SUB-SUPERSCRIPT is non-nil, convert \\ and ^.
689 See the `org-export-latex.el' code for a complete conversion table."
690 (goto-char (point-min))
691 (mapc (lambda(c)
692 (goto-char (point-min))
693 (while (re-search-forward c nil t)
694 ;; Put the point where to check for org-protected
695 (unless (get-text-property (match-beginning 2) 'org-protected)
696 (cond ((member (match-string 2) '("\\$" "$"))
697 (if (equal (match-string 2) "\\$")
698 (replace-match (concat (match-string 1) "$"
699 (match-string 3)) t t)
700 (replace-match (concat (match-string 1) "\\$"
701 (match-string 3)) t t)))
702 ((member (match-string 2) '("&" "#" "%"))
703 (if (equal (match-string 1) "\\")
704 (replace-match (match-string 2) t t)
705 (replace-match (concat (match-string 1) "\\"
706 (match-string 2)) t t)))
707 ((equal (match-string 2) "~")
708 (cond ((equal (match-string 1) "\\") nil)
709 ((eq 'org-link (get-text-property 0 'face (match-string 2)))
710 (replace-match (concat (match-string 1) "\\~") t t))
711 (t (replace-match
712 (org-latex-protect
713 (concat (match-string 1) "\\~{}")) t t))))
714 ((member (match-string 2) '("{" "}"))
715 (unless (save-match-data (org-inside-LaTeX-fragment-p))
716 (if (equal (match-string 1) "\\")
717 (replace-match (match-string 2) t t)
718 (replace-match (concat (match-string 1) "\\"
719 (match-string 2)) t t)))))
720 (unless (save-match-data (org-inside-LaTeX-fragment-p))
721 (cond ((equal (match-string 2) "\\")
722 (replace-match (or (save-match-data
723 (org-export-latex-treat-backslash-char
724 (match-string 1)
725 (match-string 3))) "") t t))
726 ((member (match-string 2) '("_" "^"))
727 (replace-match (or (save-match-data
728 (org-export-latex-treat-sub-super-char
729 sub-superscript
730 (match-string 1)
731 (match-string 2)
732 (match-string 3))) "") t t)))))))
733 '("^\\([^\n$]*?\\|^\\)\\(\\\\?\\$\\)\\([^\n$]*\\)$"
734 "\\([a-za-z0-9]+\\|[ \t\n]\\|\\b\\|\\\\\\)\\(_\\|\\^\\)\\([a-za-z0-9]+\\|[ \t\n]\\|[:punct:]\\|{[a-za-z0-9]+}\\|([a-za-z0-9]+)\\)"
735 "\\(.\\|^\\)\\(\\\\\\)\\([ \t\n]\\|[a-zA-Z&#%{}\"]+\\)"
736 "\\(.\\|^\\)\\(&\\)"
737 "\\(.\\|^\\)\\(#\\)"
738 "\\(.\\|^\\)\\(%\\)"
739 "\\(.\\|^\\)\\({\\)"
740 "\\(.\\|^\\)\\(}\\)"
741 "\\(.\\|^\\)\\(~\\)")))
743 (defun org-export-latex-treat-sub-super-char
744 (subsup string-before char string-after)
745 "Convert the \"_\" and \"^\" characters to LaTeX.
746 SUBSUP corresponds to the ^: option in the #+OPTIONS line.
747 Convert CHAR depending on STRING-BEFORE and STRING-AFTER."
748 (cond ((equal string-before "\\")
749 (concat string-before char string-after))
750 ;; this is part of a math formula
751 ((and (string-match "\\S-+" string-before)
752 (string-match "\\S-+" string-after))
753 (cond ((eq 'org-link (get-text-property 0 'face char))
754 (concat string-before "\\" char string-after))
755 ((save-match-data (org-inside-LaTeX-fragment-p))
756 (if subsup
757 (cond ((eq 1 (length string-after))
758 (concat string-before char string-after))
759 ((string-match "[({]?\\([^)}]+\\)[)}]?" string-after)
760 (format "%s%s{%s}" string-before char
761 (match-string 1 string-after))))))
762 ((and subsup
763 (> (length string-after) 1)
764 (string-match "[({]?\\([^)}]+\\)[)}]?" string-after))
765 (format "$%s%s{%s}$" string-before char
766 (match-string 1 string-after)))
767 (subsup (concat "$" string-before char string-after "$"))
768 (t (org-latex-protect
769 (concat string-before "\\" char "{}" string-after)))))
770 (t (org-latex-protect
771 (concat string-before "\\" char "{}" string-after)))))
773 (defun org-export-latex-treat-backslash-char (string-before string-after)
774 "Convert the \"$\" special character to LaTeX.
775 The conversion is made depending of STRING-BEFORE and STRING-AFTER."
776 (cond ((member (list string-after) org-html-entities)
777 ;; backslash is part of a special entity (like "\alpha")
778 (concat string-before "$\\"
779 (or (cdar (member (list string-after) org-html-entities))
780 string-after) "$"))
781 ((and (not (string-match "^[ \n\t]" string-after))
782 (not (string-match "[ \t]\\'\\|^" string-before)))
783 ;; backslash is inside a word
784 (concat string-before "$\\backslash$" string-after))
785 ((not (or (equal string-after "")
786 (string-match "^[ \t\n]" string-after)))
787 ;; backslash might escape a character (like \#) or a user TeX
788 ;; macro (like \setcounter)
789 (concat string-before "\\" string-after))
790 ((and (string-match "^[ \t\n]" string-after)
791 (string-match "[ \t\n]\\'" string-before))
792 ;; backslash is alone, convert it to $\backslash$
793 (concat string-before "$\\backslash$" string-after))
794 (t (concat string-before "$\\backslash$" string-after))))
796 (defun org-export-latex-keywords (timestamps)
797 "Convert special keywords to LaTeX.
798 Regexps are those from `org-latex-special-string-regexps'."
799 (let ((rg org-latex-special-string-regexps) r)
800 (while (setq r (pop rg))
801 (goto-char (point-min))
802 (while (re-search-forward (eval r) nil t)
803 (if (not timestamps)
804 (replace-match (format "\\\\texttt{%s}" (match-string 0)) t)
805 (replace-match ""))))))
807 (defun org-export-latex-fixed-width (opt)
808 "When OPT is non-nil convert fixed-width sections to LaTeX."
809 (goto-char (point-min))
810 (while (re-search-forward "^[ \t]*:" nil t)
811 (if opt
812 (progn (goto-char (match-beginning 0))
813 (insert "\\begin{verbatim}\n")
814 (while (looking-at "^\\([ \t]*\\):\\(.*\\)$")
815 (replace-match (concat (match-string 1)
816 (match-string 2)) t t)
817 (forward-line))
818 (insert "\\end{verbatim}\n\n"))
819 (progn (goto-char (match-beginning 0))
820 (while (looking-at "^\\([ \t]*\\):\\(.*\\)$")
821 (replace-match (concat "%" (match-string 1)
822 (match-string 2)) t t)
823 (forward-line))))))
825 ;; FIXME Use org-export-highlight-first-table-line ?
826 (defun org-export-latex-lists ()
827 "Convert lists to LaTeX."
828 (goto-char (point-min))
829 (while (re-search-forward org-export-latex-list-beginning-re nil t)
830 (beginning-of-line)
831 (org-export-list-to-latex
832 (org-export-latex-parse-list t))))
834 (defun org-export-list-to-generic (list params)
835 "Convert a LIST parsed through `org-export-latex-parse-list' to other formats.
837 Valid parameters are
839 :ustart String to start an unordered list
840 :uend String to end an unordered list
842 :ostart String to start an ordered list
843 :oend String to end an ordered list
845 :splice When set to t, return only list body lines, don't wrap
846 them into :[u/o]start and :[u/o]end. Default is nil.
848 :istart String to start a list item
849 :iend String to end a list item
850 :isep String to separate items
851 :lsep String to separate sublists"
852 (interactive)
853 (let* ((p params) sublist
854 (splicep (plist-get p :splice))
855 (ostart (plist-get p :ostart))
856 (oend (plist-get p :oend))
857 (ustart (plist-get p :ustart))
858 (uend (plist-get p :uend))
859 (istart (plist-get p :istart))
860 (iend (plist-get p :iend))
861 (isep (plist-get p :isep))
862 (lsep (plist-get p :lsep)))
863 (let ((wrapper
864 (cond ((eq (car list) 'ordered)
865 (concat ostart "\n%s" oend "\n"))
866 ((eq (car list) 'unordered)
867 (concat ustart "\n%s" uend "\n"))))
868 rtn)
869 (while (setq sublist (pop list))
870 (cond ((symbolp sublist) nil)
871 ((stringp sublist)
872 (setq rtn (concat rtn istart sublist iend isep)))
874 (setq rtn (concat rtn ;; previous list
875 lsep ;; list separator
876 (org-export-list-to-generic sublist p)
877 lsep ;; list separator
878 )))))
879 (format wrapper rtn))))
881 (defun org-export-list-to-latex (list)
882 "Convert LIST into a LaTeX list."
883 (insert
884 (org-export-list-to-generic
885 list '(:splicep nil :ostart "\\begin{enumerate}" :oend "\\end{enumerate}"
886 :ustart "\\begin{itemize}" :uend "\\end{itemize}"
887 :istart "\\item " :iend ""
888 :isep "\n" :lsep "\n"))
889 ;; Add a trailing \n after list conversion
890 "\n"))
892 (defun org-export-latex-tables (opt)
893 "When OPT is non-nil convert tables to LaTeX."
894 (goto-char (point-min))
895 (while (re-search-forward "^\\([ \t]*\\)|" nil t)
896 ;; Re-align the table to update org-table-last-alignment
897 (save-excursion (save-match-data (org-table-align)))
898 (let (tbl-list
899 (beg (match-beginning 0))
900 (end (save-excursion
901 (re-search-forward
902 (concat "^" (regexp-quote (match-string 1))
903 "[^|]\\|\\'") nil t) (match-beginning 0))))
904 (beginning-of-line)
905 (if org-export-latex-tables-verbatim
906 (let* ((raw-table (buffer-substring beg end))
907 (tbl (concat "\\begin{verbatim}\n" raw-table
908 "\\end{verbatim}\n")))
909 (apply 'delete-region (list beg end))
910 (insert tbl))
911 (progn
912 (while (not (eq end (point)))
913 (if (looking-at "[ \t]*|\\([^-|].+\\)|[ \t]*$")
914 (push (split-string (org-trim (match-string 1)) "|") tbl-list)
915 (push 'hline tbl-list))
916 (forward-line))
917 ;; comment region out instead of deleting it ?
918 (apply 'delete-region (list beg end))
919 (when opt (insert (orgtbl-to-latex (nreverse tbl-list)
920 nil) "\n\n")))))))
922 (defun org-export-latex-fontify ()
923 "Convert fontification to LaTeX."
924 (goto-char (point-min))
925 (while (re-search-forward org-emph-re nil t)
926 ;; The match goes one char after the *string*
927 (let ((emph (assoc (match-string 3)
928 org-export-latex-emphasis-alist))
929 rpl)
930 (unless (get-text-property (1- (point)) 'org-protected)
931 (setq rpl (concat (match-string 1)
932 (format (org-export-latex-protect-char-in-string
933 '("\\" "{" "}") (cadr emph))
934 (match-string 4))
935 (match-string 5)))
936 (if (caddr emph) (setq rpl (org-latex-protect rpl)))
937 (replace-match rpl t t)))
938 (backward-char)))
940 (defun org-export-latex-links ()
941 ;; Make sure to use the LaTeX hyperref and graphicx package
942 ;; or send some warnings.
943 "Convert links to LaTeX."
944 (goto-char (point-min))
945 (while (re-search-forward org-bracket-link-analytic-regexp nil t)
946 (org-if-unprotected
947 (goto-char (match-beginning 0))
948 (let* ((re-radio org-latex-all-targets-regexp)
949 (remove (list (match-beginning 0) (match-end 0)))
950 (type (match-string 2))
951 (raw-path (match-string 3))
952 (full-raw-path (concat (match-string 1) raw-path))
953 (desc (match-string 5))
954 imgp radiop
955 ;; define the path of the link
956 (path (cond
957 ((member type '("http" "https" "ftp"))
958 (concat type ":" raw-path))
959 ((and re-radio (string-match re-radio raw-path))
960 (setq radiop t))
961 ((equal type "mailto")
962 (concat type ":" raw-path))
963 ((equal type "file")
964 (if (and (or (org-file-image-p (expand-file-name raw-path))
965 (string-match "\\.eps$" raw-path))
966 (equal desc full-raw-path))
967 (setq imgp t)
968 (progn (when (string-match "\\(.+\\)::.+" raw-path)
969 (setq raw-path (match-string 1 raw-path)))
970 (if (file-exists-p raw-path)
971 (concat type "://" (expand-file-name raw-path))
972 (concat type "://" (org-export-directory
973 :LaTeX org-latex-options-plist)
974 raw-path))))))))
975 ;; process with link inserting
976 (apply 'delete-region remove)
977 (cond ((and imgp (plist-get org-latex-options-plist :inline-images))
978 (insert (format "\\includegraphics[%s]{%s}"
979 ;; image option should be set be a comment line
980 org-export-latex-image-default-option
981 (expand-file-name raw-path))))
982 ;; FIXME: what about caption? image properties?
983 (radiop (insert (format "\\hyperref[%s]{%s}" raw-path desc)))
984 (path (insert (format "\\href{%s}{%s}" path desc)))
985 (t (insert "\\texttt{" desc "}")))))))
987 (defun org-export-latex-cleaned-string
988 ;; FIXME remove commentsp call in org.el and here
989 (&optional commentsp)
990 "Clean stuff in the LaTeX export."
992 ;; Preserve line breaks
993 (goto-char (point-min))
994 (while (re-search-forward "\\\\\\\\" nil t)
995 (add-text-properties (match-beginning 0) (match-end 0)
996 '(org-protected t)))
998 ;; Convert LaTeX to \LaTeX{}
999 (goto-char (point-min))
1000 (let ((case-fold-search nil) rpl)
1001 (while (re-search-forward "\\([^+_]\\)LaTeX" nil t)
1002 (replace-match (org-latex-protect
1003 (concat (match-string 1) "\\LaTeX{}")) t t)))
1005 ;; Convert horizontal rules
1006 (goto-char (point-min))
1007 (while (re-search-forward "^----+.$" nil t)
1008 (replace-match (org-latex-protect "\\hrule") t t))
1010 ;; Protect LaTeX \commands{...}
1011 (goto-char (point-min))
1012 (while (re-search-forward "\\\\[a-zA-Z]+\\(?:\\[.*\\]\\)?{.*}" nil t)
1013 (add-text-properties (match-beginning 0) (match-end 0)
1014 '(org-protected t)))
1016 ;; Replace radio links
1017 (goto-char (point-min))
1018 (while (re-search-forward
1019 (concat "<<<?" org-latex-all-targets-regexp
1020 ">>>?\\((INVISIBLE)\\)?") nil t)
1021 (replace-match
1022 (org-latex-protect
1023 (format "\\label{%s}%s"(match-string 1)
1024 (if (match-string 2) "" (match-string 1)))) t t))
1026 ;; Delete @<...> constructs
1027 (goto-char (point-min))
1028 ;; Thanks to Daniel Clemente for this regexp
1029 (while (re-search-forward "@<\\(?:[^\"\n]\\|\".*\"\\)*?>" nil t)
1030 (replace-match ""))
1032 ;; When converting to LaTeX, replace footnotes
1033 ;; FIXME: don't protect footnotes from conversion
1034 (when (plist-get org-latex-options-plist :footnotes)
1035 (goto-char (point-min))
1036 (while (re-search-forward "\\[[0-9]+\\]" nil t)
1037 (when (save-match-data
1038 (save-excursion (beginning-of-line)
1039 (looking-at "[^:|#]")))
1040 (let ((foot-beg (match-beginning 0))
1041 (foot-end (match-end 0))
1042 (foot-prefix (match-string 0))
1043 footnote footnote-rpl)
1044 (when (and (re-search-forward (regexp-quote foot-prefix) nil t))
1045 (replace-match "")
1046 (let ((end (save-excursion
1047 (if (re-search-forward "^$\\|\\[[0-9]+\\]" nil t)
1048 (match-beginning 0) (point-max)))))
1049 (setq footnote
1050 (concat
1051 (org-trim (buffer-substring (point) end))
1052 ;; FIXME stupid workaround for cases where
1053 ;; `org-bracket-link-analytic-regexp' matches
1054 ;; }. as part of the link.
1055 " "))
1056 (delete-region (point) end)))
1057 (goto-char foot-beg)
1058 (delete-region foot-beg foot-end)
1059 (setq footnote-rpl (format "\\footnote{%s}" footnote))
1060 (add-text-properties 0 10 '(org-protected t) footnote-rpl)
1061 (add-text-properties (1- (length footnote-rpl))
1062 (length footnote-rpl)
1063 '(org-protected t) footnote-rpl)
1064 (insert footnote-rpl))))
1066 ;; Replace footnote section tag for LaTeX
1067 (goto-char (point-min))
1068 (while (re-search-forward
1069 (concat "^" footnote-section-tag-regexp) nil t)
1070 (replace-match ""))))
1072 (provide 'org-export-latex)
1074 ;; arch-tag: 23c2b87d-da04-4c2d-ad2d-1eb6487bc3ad
1075 ;;; org-export-latex.el ends here