Move EXPERIMENTAL/* into contrib/lisp/ and change org-export.el accordingly.
[org-mode.git] / contrib / lisp / org-export.el
blob142b0faf3627c1f827beda7228d52fe16ce52322
1 ;;; org-export.el --- Generic Export Engine For Org
3 ;; Copyright (C) 2012 Free Software Foundation, Inc.
5 ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
6 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; This program is free software; you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation, either version 3 of the License, or
11 ;; (at your option) any later version.
13 ;; This program is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 ;; GNU General Public License for more details.
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
21 ;;; Commentary:
23 ;; This library implements a generic export engine for Org, built on
24 ;; its syntactical parser: Org Elements.
26 ;; Besides that parser, the generic exporter is made of three distinct
27 ;; parts:
29 ;; - The communication channel consists in a property list, which is
30 ;; created and updated during the process. Its use is to offer
31 ;; every piece of information, would it be about initial environment
32 ;; or contextual data, all in a single place. The exhaustive list
33 ;; of properties is given in "The Communication Channel" section of
34 ;; this file.
36 ;; - The transcoder walks the parse tree, ignores or treat as plain
37 ;; text elements and objects according to export options, and
38 ;; eventually calls back-end specific functions to do the real
39 ;; transcoding, concatenating their return value along the way.
41 ;; - The filter system is activated at the very beginning and the very
42 ;; end of the export process, and each time an element or an object
43 ;; has been converted. It is the entry point to fine-tune standard
44 ;; output from back-end transcoders.
46 ;; The core function is `org-export-as'. It returns the transcoded
47 ;; buffer as a string.
49 ;; In order to derive an exporter out of this generic implementation,
50 ;; one can define a transcode function for each element or object.
51 ;; Such function should return a string for the corresponding element,
52 ;; without any trailing space, or nil. It must accept three
53 ;; arguments:
54 ;; 1. the element or object itself,
55 ;; 2. its contents, or nil when it isn't recursive,
56 ;; 3. the property list used as a communication channel.
58 ;; If no such function is found, that element or object type will
59 ;; simply be ignored, along with any separating blank line. The same
60 ;; will happen if the function returns the nil value. If that
61 ;; function returns the empty string, the type will be ignored, but
62 ;; the blank lines will be kept.
64 ;; Contents, when not nil, are stripped from any global indentation
65 ;; (although the relative one is preserved). They also always end
66 ;; with a single newline character.
68 ;; These functions must follow a strict naming convention:
69 ;; `org-BACKEND-TYPE' where, obviously, BACKEND is the name of the
70 ;; export back-end and TYPE the type of the element or object handled.
72 ;; Moreover, two additional functions can be defined. On the one
73 ;; hand, `org-BACKEND-template' returns the final transcoded string,
74 ;; and can be used to add a preamble and a postamble to document's
75 ;; body. It must accept two arguments: the transcoded string and the
76 ;; property list containing export options. On the other hand,
77 ;; `org-BACKEND-plain-text', when defined, is to be called on every
78 ;; text not recognized as an element or an object. It must accept two
79 ;; arguments: the text string and the information channel.
81 ;; Any back-end can define its own variables. Among them, those
82 ;; customizables should belong to the `org-export-BACKEND' group.
83 ;; Also, a special variable, `org-BACKEND-option-alist', allows to
84 ;; define buffer keywords and "#+options:" items specific to that
85 ;; back-end. See `org-export-option-alist' for supported defaults and
86 ;; syntax.
88 ;; Tools for common tasks across back-ends are implemented in the
89 ;; penultimate part of this file. A dispatcher for standard back-ends
90 ;; is provided in the last one.
92 ;;; Code:
93 (eval-when-compile (require 'cl))
94 (require 'org-element)
95 ;; Require major back-ends and publishing tools
96 (require 'org-e-ascii "./org-e-ascii.el")
97 (require 'org-e-html "./org-e-html.el")
98 (require 'org-e-latex "./org-e-latex.el")
99 (require 'org-e-odt "./org-e-odt.el")
100 (require 'org-e-publish "../org-e-publish.el")
104 ;;; Internal Variables
106 ;; Among internal variables, the most important is
107 ;; `org-export-option-alist'. This variable define the global export
108 ;; options, shared between every exporter, and how they are acquired.
110 (defconst org-export-max-depth 19
111 "Maximum nesting depth for headlines, counting from 0.")
113 (defconst org-export-option-alist
114 '((:author "AUTHOR" nil user-full-name t)
115 (:creator "CREATOR" nil org-export-creator-string)
116 (:date "DATE" nil nil t)
117 (:description "DESCRIPTION" nil nil newline)
118 (:email "EMAIL" nil user-mail-address t)
119 (:exclude-tags "EXPORT_EXCLUDE_TAGS" nil org-export-exclude-tags split)
120 (:headline-levels nil "H" org-export-headline-levels)
121 (:keywords "KEYWORDS" nil nil space)
122 (:language "LANGUAGE" nil org-export-default-language t)
123 (:preserve-breaks nil "\\n" org-export-preserve-breaks)
124 (:section-numbers nil "num" org-export-with-section-numbers)
125 (:select-tags "EXPORT_SELECT_TAGS" nil org-export-select-tags split)
126 (:time-stamp-file nil "timestamp" org-export-time-stamp-file)
127 (:title "TITLE" nil nil space)
128 (:with-archived-trees nil "arch" org-export-with-archived-trees)
129 (:with-author nil "author" org-export-with-author)
130 (:with-creator nil "creator" org-export-with-creator)
131 (:with-drawers nil "d" org-export-with-drawers)
132 (:with-email nil "email" org-export-with-email)
133 (:with-emphasize nil "*" org-export-with-emphasize)
134 (:with-entities nil "e" org-export-with-entities)
135 (:with-fixed-width nil ":" org-export-with-fixed-width)
136 (:with-footnotes nil "f" org-export-with-footnotes)
137 (:with-priority nil "pri" org-export-with-priority)
138 (:with-special-strings nil "-" org-export-with-special-strings)
139 (:with-sub-superscript nil "^" org-export-with-sub-superscripts)
140 (:with-toc nil "toc" org-export-with-toc)
141 (:with-tables nil "|" org-export-with-tables)
142 (:with-tags nil "tags" org-export-with-tags)
143 (:with-tasks nil "tasks" org-export-with-tasks)
144 (:with-timestamps nil "<" org-export-with-timestamps)
145 (:with-todo-keywords nil "todo" org-export-with-todo-keywords))
146 "Alist between export properties and ways to set them.
148 The car of the alist is the property name, and the cdr is a list
149 like \(KEYWORD OPTION DEFAULT BEHAVIOUR\) where:
151 KEYWORD is a string representing a buffer keyword, or nil.
152 OPTION is a string that could be found in an #+OPTIONS: line.
153 DEFAULT is the default value for the property.
154 BEHAVIOUR determine how Org should handle multiple keywords for
155 the same property. It is a symbol among:
156 nil Keep old value and discard the new one.
157 t Replace old value with the new one.
158 `space' Concatenate the values, separating them with a space.
159 `newline' Concatenate the values, separating them with
160 a newline.
161 `split' Split values at white spaces, and cons them to the
162 previous list.
164 KEYWORD and OPTION have precedence over DEFAULT.
166 All these properties should be back-end agnostic. For back-end
167 specific properties, define a similar variable named
168 `org-BACKEND-option-alist', replacing BACKEND with the name of
169 the appropriate back-end. You can also redefine properties
170 there, as they have precedence over these.")
172 (defconst org-export-special-keywords
173 '("SETUP_FILE" "OPTIONS" "MACRO")
174 "List of in-buffer keywords that require special treatment.
175 These keywords are not directly associated to a property. The
176 way they are handled must be hard-coded into
177 `org-export-get-inbuffer-options' function.")
179 (defconst org-export-filters-alist
180 '((:filter-babel-call . org-export-filter-babel-call-functions)
181 (:filter-center-block . org-export-filter-center-block-functions)
182 (:filter-comment . org-export-filter-comment-functions)
183 (:filter-comment-block . org-export-filter-comment-block-functions)
184 (:filter-drawer . org-export-filter-drawer-functions)
185 (:filter-dynamic-block . org-export-filter-dynamic-block-functions)
186 (:filter-emphasis . org-export-filter-emphasis-functions)
187 (:filter-entity . org-export-filter-entity-functions)
188 (:filter-example-block . org-export-filter-example-block-functions)
189 (:filter-export-block . org-export-filter-export-block-functions)
190 (:filter-export-snippet . org-export-filter-export-snippet-functions)
191 (:filter-final-output . org-export-filter-final-output-functions)
192 (:filter-fixed-width . org-export-filter-fixed-width-functions)
193 (:filter-footnote-definition . org-export-filter-footnote-definition-functions)
194 (:filter-footnote-reference . org-export-filter-footnote-reference-functions)
195 (:filter-headline . org-export-filter-headline-functions)
196 (:filter-horizontal-rule . org-export-filter-horizontal-rule-functions)
197 (:filter-inline-babel-call . org-export-filter-inline-babel-call-functions)
198 (:filter-inline-src-block . org-export-filter-inline-src-block-functions)
199 (:filter-inlinetask . org-export-filter-inlinetask-functions)
200 (:filter-item . org-export-filter-item-functions)
201 (:filter-keyword . org-export-filter-keyword-functions)
202 (:filter-latex-environment . org-export-filter-latex-environment-functions)
203 (:filter-latex-fragment . org-export-filter-latex-fragment-functions)
204 (:filter-line-break . org-export-filter-line-break-functions)
205 (:filter-link . org-export-filter-link-functions)
206 (:filter-macro . org-export-filter-macro-functions)
207 (:filter-paragraph . org-export-filter-paragraph-functions)
208 (:filter-parse-tree . org-export-filter-parse-tree-functions)
209 (:filter-plain-list . org-export-filter-plain-list-functions)
210 (:filter-plain-text . org-export-filter-plain-text-functions)
211 (:filter-property-drawer . org-export-filter-property-drawer-functions)
212 (:filter-quote-block . org-export-filter-quote-block-functions)
213 (:filter-quote-section . org-export-filter-quote-section-functions)
214 (:filter-radio-target . org-export-filter-radio-target-functions)
215 (:filter-section . org-export-filter-section-functions)
216 (:filter-special-block . org-export-filter-special-block-functions)
217 (:filter-src-block . org-export-filter-src-block-functions)
218 (:filter-statistics-cookie . org-export-filter-statistics-cookie-functions)
219 (:filter-subscript . org-export-filter-subscript-functions)
220 (:filter-superscript . org-export-filter-superscript-functions)
221 (:filter-table . org-export-filter-table-functions)
222 (:filter-target . org-export-filter-target-functions)
223 (:filter-time-stamp . org-export-filter-time-stamp-functions)
224 (:filter-verbatim . org-export-filter-verbatim-functions)
225 (:filter-verse-block . org-export-filter-verse-block-functions))
226 "Alist between filters properties and initial values.
228 The key of each association is a property name accessible through
229 the communication channel its value is a configurable global
230 variable defining initial filters.
232 This list is meant to install user specified filters. Back-end
233 developers may install their own filters using
234 `org-BACKEND-filters-alist', where BACKEND is the name of the
235 considered back-end. Filters defined there will always be
236 prepended to the current list, so they always get applied
237 first.")
239 (defconst org-export-default-inline-image-rule
240 `(("file" .
241 ,(format "\\.%s\\'"
242 (regexp-opt
243 '("png" "jpeg" "jpg" "gif" "tiff" "tif" "xbm"
244 "xpm" "pbm" "pgm" "ppm") t))))
245 "Default rule for link matching an inline image.
246 This rule applies to links with no description. By default, it
247 will be considered as an inline image if it targets a local file
248 whose extension is either \"png\", \"jpeg\", \"jpg\", \"gif\",
249 \"tiff\", \"tif\", \"xbm\", \"xpm\", \"pbm\", \"pgm\" or \"ppm\".
250 See `org-export-inline-image-p' for more information about
251 rules.")
255 ;;; User-configurable Variables
257 ;; Configuration for the masses.
259 ;; They should never be evaled directly, as their value is to be
260 ;; stored in a property list (cf. `org-export-option-alist').
262 (defgroup org-export nil
263 "Options for exporting Org mode files."
264 :tag "Org Export"
265 :group 'org)
267 (defgroup org-export-general nil
268 "General options for export engine."
269 :tag "Org Export General"
270 :group 'org-export)
272 (defcustom org-export-with-archived-trees 'headline
273 "Whether sub-trees with the ARCHIVE tag should be exported.
275 This can have three different values:
276 nil Do not export, pretend this tree is not present.
277 t Do export the entire tree.
278 `headline' Only export the headline, but skip the tree below it.
280 This option can also be set with the #+OPTIONS line,
281 e.g. \"arch:nil\"."
282 :group 'org-export-general
283 :type '(choice
284 (const :tag "Not at all" nil)
285 (const :tag "Headline only" 'headline)
286 (const :tag "Entirely" t)))
288 (defcustom org-export-with-author t
289 "Non-nil means insert author name into the exported file.
290 This option can also be set with the #+OPTIONS line,
291 e.g. \"author:nil\"."
292 :group 'org-export-general
293 :type 'boolean)
295 (defcustom org-export-with-creator 'comment
296 "Non-nil means the postamble should contain a creator sentence.
298 The sentence can be set in `org-export-creator-string' and
299 defaults to \"Generated by Org mode XX in Emacs XXX.\".
301 If the value is `comment' insert it as a comment."
302 :group 'org-export-general
303 :type '(choice
304 (const :tag "No creator sentence" nil)
305 (const :tag "Sentence as a comment" 'comment)
306 (const :tag "Insert the sentence" t)))
308 (defcustom org-export-creator-string
309 (format "Generated by Org mode %s in Emacs %s." org-version emacs-version)
310 "String to insert at the end of the generated document."
311 :group 'org-export-general
312 :type '(string :tag "Creator string"))
314 (defcustom org-export-with-drawers t
315 "Non-nil means export contents of standard drawers.
317 When t, all drawers are exported. This may also be a list of
318 drawer names to export. This variable doesn't apply to
319 properties drawers.
321 This option can also be set with the #+OPTIONS line,
322 e.g. \"d:nil\"."
323 :group 'org-export-general
324 :type '(choice
325 (const :tag "All drawers" t)
326 (const :tag "None" nil)
327 (repeat :tag "Selected drawers"
328 (string :tag "Drawer name"))))
330 (defcustom org-export-with-email nil
331 "Non-nil means insert author email into the exported file.
332 This option can also be set with the #+OPTIONS line,
333 e.g. \"email:t\"."
334 :group 'org-export-general
335 :type 'boolean)
337 (defcustom org-export-with-emphasize t
338 "Non-nil means interpret *word*, /word/, and _word_ as emphasized text.
340 If the export target supports emphasizing text, the word will be
341 typeset in bold, italic, or underlined, respectively. Not all
342 export backends support this.
344 This option can also be set with the #+OPTIONS line, e.g. \"*:nil\"."
345 :group 'org-export-general
346 :type 'boolean)
348 (defcustom org-export-exclude-tags '("noexport")
349 "Tags that exclude a tree from export.
351 All trees carrying any of these tags will be excluded from
352 export. This is without condition, so even subtrees inside that
353 carry one of the `org-export-select-tags' will be removed.
355 This option can also be set with the #+EXPORT_EXCLUDE_TAGS:
356 keyword."
357 :group 'org-export-general
358 :type '(repeat (string :tag "Tag")))
360 (defcustom org-export-with-fixed-width t
361 "Non-nil means lines starting with \":\" will be in fixed width font.
363 This can be used to have pre-formatted text, fragments of code
364 etc. For example:
365 : ;; Some Lisp examples
366 : (while (defc cnt)
367 : (ding))
368 will be looking just like this in also HTML. See also the QUOTE
369 keyword. Not all export backends support this.
371 This option can also be set with the #+OPTIONS line, e.g. \"::nil\"."
372 :group 'org-export-translation
373 :type 'boolean)
375 (defcustom org-export-with-footnotes t
376 "Non-nil means Org footnotes should be exported.
377 This option can also be set with the #+OPTIONS line,
378 e.g. \"f:nil\"."
379 :group 'org-export-general
380 :type 'boolean)
382 (defcustom org-export-headline-levels 3
383 "The last level which is still exported as a headline.
385 Inferior levels will produce itemize lists when exported. Note
386 that a numeric prefix argument to an exporter function overrides
387 this setting.
389 This option can also be set with the #+OPTIONS line, e.g. \"H:2\"."
390 :group 'org-export-general
391 :type 'integer)
393 (defcustom org-export-default-language "en"
394 "The default language for export and clocktable translations, as a string.
395 This may have an association in
396 `org-clock-clocktable-language-setup'."
397 :group 'org-export-general
398 :type '(string :tag "Language"))
400 (defcustom org-export-preserve-breaks nil
401 "Non-nil means preserve all line breaks when exporting.
403 Normally, in HTML output paragraphs will be reformatted.
405 This option can also be set with the #+OPTIONS line,
406 e.g. \"\\n:t\"."
407 :group 'org-export-general
408 :type 'boolean)
410 (defcustom org-export-with-entities t
411 "Non-nil means interpret entities when exporting.
413 For example, HTML export converts \\alpha to &alpha; and \\AA to
414 &Aring;.
416 For a list of supported names, see the constant `org-entities'
417 and the user option `org-entities-user'.
419 This option can also be set with the #+OPTIONS line,
420 e.g. \"e:nil\"."
421 :group 'org-export-general
422 :type 'boolean)
424 (defcustom org-export-with-priority nil
425 "Non-nil means include priority cookies in export.
427 When nil, remove priority cookies for export.
429 This option can also be set with the #+OPTIONS line,
430 e.g. \"pri:t\"."
431 :group 'org-export-general
432 :type 'boolean)
434 (defcustom org-export-with-section-numbers t
435 "Non-nil means add section numbers to headlines when exporting.
437 When set to an integer n, numbering will only happen for
438 headlines whose relative level is higher or equal to n.
440 This option can also be set with the #+OPTIONS line,
441 e.g. \"num:t\"."
442 :group 'org-export-general
443 :type 'boolean)
445 (defcustom org-export-select-tags '("export")
446 "Tags that select a tree for export.
448 If any such tag is found in a buffer, all trees that do not carry
449 one of these tags will be ignored during export. Inside trees
450 that are selected like this, you can still deselect a subtree by
451 tagging it with one of the `org-export-exclude-tags'.
453 This option can also be set with the #+EXPORT_SELECT_TAGS:
454 keyword."
455 :group 'org-export-general
456 :type '(repeat (string :tag "Tag")))
458 (defcustom org-export-with-special-strings t
459 "Non-nil means interpret \"\-\", \"--\" and \"---\" for export.
461 When this option is turned on, these strings will be exported as:
463 Org HTML LaTeX
464 -----+----------+--------
465 \\- &shy; \\-
466 -- &ndash; --
467 --- &mdash; ---
468 ... &hellip; \ldots
470 This option can also be set with the #+OPTIONS line,
471 e.g. \"-:nil\"."
472 :group 'org-export-general
473 :type 'boolean)
475 (defcustom org-export-with-sub-superscripts t
476 "Non-nil means interpret \"_\" and \"^\" for export.
478 When this option is turned on, you can use TeX-like syntax for
479 sub- and superscripts. Several characters after \"_\" or \"^\"
480 will be considered as a single item - so grouping with {} is
481 normally not needed. For example, the following things will be
482 parsed as single sub- or superscripts.
484 10^24 or 10^tau several digits will be considered 1 item.
485 10^-12 or 10^-tau a leading sign with digits or a word
486 x^2-y^3 will be read as x^2 - y^3, because items are
487 terminated by almost any nonword/nondigit char.
488 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
490 Still, ambiguity is possible - so when in doubt use {} to enclose
491 the sub/superscript. If you set this variable to the symbol
492 `{}', the braces are *required* in order to trigger
493 interpretations as sub/superscript. This can be helpful in
494 documents that need \"_\" frequently in plain text.
496 This option can also be set with the #+OPTIONS line,
497 e.g. \"^:nil\"."
498 :group 'org-export-general
499 :type '(choice
500 (const :tag "Interpret them" t)
501 (const :tag "Curly brackets only" {})
502 (const :tag "Do not interpret them" nil)))
504 (defcustom org-export-with-toc t
505 "Non-nil means create a table of contents in exported files.
507 The TOC contains headlines with levels up
508 to`org-export-headline-levels'. When an integer, include levels
509 up to N in the toc, this may then be different from
510 `org-export-headline-levels', but it will not be allowed to be
511 larger than the number of headline levels. When nil, no table of
512 contents is made.
514 This option can also be set with the #+OPTIONS line,
515 e.g. \"toc:nil\" or \"toc:3\"."
516 :group 'org-export-general
517 :type '(choice
518 (const :tag "No Table of Contents" nil)
519 (const :tag "Full Table of Contents" t)
520 (integer :tag "TOC to level")))
522 (defcustom org-export-with-tables t
523 "If non-nil, lines starting with \"|\" define a table.
524 For example:
526 | Name | Address | Birthday |
527 |-------------+----------+-----------|
528 | Arthur Dent | England | 29.2.2100 |
530 This option can also be set with the #+OPTIONS line, e.g. \"|:nil\"."
531 :group 'org-export-general
532 :type 'boolean)
534 (defcustom org-export-with-tags t
535 "If nil, do not export tags, just remove them from headlines.
537 If this is the symbol `not-in-toc', tags will be removed from
538 table of contents entries, but still be shown in the headlines of
539 the document.
541 This option can also be set with the #+OPTIONS line,
542 e.g. \"tags:nil\"."
543 :group 'org-export-general
544 :type '(choice
545 (const :tag "Off" nil)
546 (const :tag "Not in TOC" not-in-toc)
547 (const :tag "On" t)))
549 (defcustom org-export-with-tasks t
550 "Non-nil means include TODO items for export.
551 This may have the following values:
552 t include tasks independent of state.
553 todo include only tasks that are not yet done.
554 done include only tasks that are already done.
555 nil remove all tasks before export
556 list of keywords keep only tasks with these keywords"
557 :group 'org-export-general
558 :type '(choice
559 (const :tag "All tasks" t)
560 (const :tag "No tasks" nil)
561 (const :tag "Not-done tasks" todo)
562 (const :tag "Only done tasks" done)
563 (repeat :tag "Specific TODO keywords"
564 (string :tag "Keyword"))))
566 (defcustom org-export-time-stamp-file t
567 "Non-nil means insert a time stamp into the exported file.
568 The time stamp shows when the file was created.
570 This option can also be set with the #+OPTIONS line,
571 e.g. \"timestamp:nil\"."
572 :group 'org-export-general
573 :type 'boolean)
575 (defcustom org-export-with-timestamps t
576 "If nil, do not export time stamps and associated keywords."
577 :group 'org-export-general
578 :type 'boolean)
580 (defcustom org-export-with-todo-keywords t
581 "Non-nil means include TODO keywords in export.
582 When nil, remove all these keywords from the export.")
584 (defcustom org-export-allow-BIND 'confirm
585 "Non-nil means allow #+BIND to define local variable values for export.
586 This is a potential security risk, which is why the user must
587 confirm the use of these lines."
588 :group 'org-export-general
589 :type '(choice
590 (const :tag "Never" nil)
591 (const :tag "Always" t)
592 (const :tag "Ask a confirmation for each file" confirm)))
594 (defcustom org-export-snippet-translation-alist nil
595 "Alist between export snippets back-ends and exporter back-ends.
597 This variable allows to provide shortcuts for export snippets.
599 For example, with a value of '\(\(\"h\" . \"html\"\)\), the HTML
600 back-end will recognize the contents of \"@h{<b>}\" as HTML code
601 while every other back-end will ignore it."
602 :group 'org-export-general
603 :type '(repeat
604 (cons
605 (string :tag "Shortcut")
606 (string :tag "Back-end"))))
608 (defcustom org-export-coding-system nil
609 "Coding system for the exported file."
610 :group 'org-export-general
611 :type 'coding-system)
613 (defcustom org-export-copy-to-kill-ring t
614 "Non-nil means exported stuff will also be pushed onto the kill ring."
615 :group 'org-export-general
616 :type 'boolean)
618 (defcustom org-export-initial-scope 'buffer
619 "The initial scope when exporting with `org-export-dispatch'.
620 This variable can be either set to `buffer' or `subtree'."
621 :group 'org-export-general
622 :type '(choice
623 (const :tag "Export current buffer" 'buffer)
624 (const :tag "Export current subtree" 'subtree)))
626 (defcustom org-export-show-temporary-export-buffer t
627 "Non-nil means show buffer after exporting to temp buffer.
628 When Org exports to a file, the buffer visiting that file is ever
629 shown, but remains buried. However, when exporting to a temporary
630 buffer, that buffer is popped up in a second window. When this variable
631 is nil, the buffer remains buried also in these cases."
632 :group 'org-export-general
633 :type 'boolean)
635 (defcustom org-export-dispatch-use-expert-ui nil
636 "Non-nil means using a non-intrusive `org-export-dispatch'.
637 In that case, no help buffer is displayed. Though, an indicator
638 for current export scope is added to the prompt \(i.e. \"b\" when
639 output is restricted to body only, \"s\" when it is restricted to
640 the current subtree and \"v\" when only visible elements are
641 considered for export\). Also, \[?] allows to switch back to
642 standard mode."
643 :group 'org-export-general
644 :type 'boolean)
648 ;;; The Communication Channel
650 ;; During export process, every function has access to a number of
651 ;; properties. They are of three types:
653 ;; 1. Environment options are collected once at the very beginning of
654 ;; the process, out of the original buffer and configuration.
655 ;; Collecting them is handled by `org-export-get-environment'
656 ;; function.
658 ;; Most environment options are defined through the
659 ;; `org-export-option-alist' variable.
661 ;; 2. Tree properties are extracted directly from the parsed tree,
662 ;; just before export, by `org-export-collect-tree-properties'.
664 ;; 3. Local options are updated during parsing, and their value
665 ;; depends on the level of recursion. For now, only `:ignore-list'
666 ;; belongs to that category.
668 ;; Here is the full list of properties available during transcode
669 ;; process, with their category (option, tree or local) and their
670 ;; value type.
672 ;; + `:author' :: Author's name.
673 ;; - category :: option
674 ;; - type :: string
676 ;; + `:back-end' :: Current back-end used for transcoding.
677 ;; - category :: tree
678 ;; - type :: symbol
680 ;; + `:creator' :: String to write as creation information.
681 ;; - category :: option
682 ;; - type :: string
684 ;; + `:date' :: String to use as date.
685 ;; - category :: option
686 ;; - type :: string
688 ;; + `:description' :: Description text for the current data.
689 ;; - category :: option
690 ;; - type :: string
692 ;; + `:email' :: Author's email.
693 ;; - category :: option
694 ;; - type :: string
696 ;; + `:exclude-tags' :: Tags for exclusion of subtrees from export
697 ;; process.
698 ;; - category :: option
699 ;; - type :: list of strings
701 ;; + `:footnote-definition-alist' :: Alist between footnote labels and
702 ;; their definition, as parsed data. Only non-inlined footnotes
703 ;; are represented in this alist. Also, every definition isn't
704 ;; guaranteed to be referenced in the parse tree. The purpose of
705 ;; this property is to preserve definitions from oblivion
706 ;; (i.e. when the parse tree comes from a part of the original
707 ;; buffer), it isn't meant for direct use in a back-end. To
708 ;; retrieve a definition relative to a reference, use
709 ;; `org-export-get-footnote-definition' instead.
710 ;; - category :: option
711 ;; - type :: alist (STRING . LIST)
713 ;; + `:headline-levels' :: Maximum level being exported as an
714 ;; headline. Comparison is done with the relative level of
715 ;; headlines in the parse tree, not necessarily with their
716 ;; actual level.
717 ;; - category :: option
718 ;; - type :: integer
720 ;; + `:headline-offset' :: Difference between relative and real level
721 ;; of headlines in the parse tree. For example, a value of -1
722 ;; means a level 2 headline should be considered as level
723 ;; 1 (cf. `org-export-get-relative-level').
724 ;; - category :: tree
725 ;; - type :: integer
727 ;; + `:headline-numbering' :: Alist between headlines and their
728 ;; numbering, as a list of numbers
729 ;; (cf. `org-export-get-headline-number').
730 ;; - category :: tree
731 ;; - type :: alist (INTEGER . LIST)
733 ;; + `:ignore-list' :: List of elements and objects that should be
734 ;; ignored during export.
735 ;; - category :: local
736 ;; - type :: list of elements and objects
738 ;; + `:input-file' :: Full path to input file, if any.
739 ;; - category :: option
740 ;; - type :: string or nil
742 ;; + `:keywords' :: List of keywords attached to data.
743 ;; - category :: option
744 ;; - type :: string
746 ;; + `:language' :: Default language used for translations.
747 ;; - category :: option
748 ;; - type :: string
750 ;; + `:macro-input-file' :: Macro returning file name of input file,
751 ;; or nil.
752 ;; - category :: option
753 ;; - type :: string or nil
755 ;; + `:parse-tree' :: Whole parse tree, available at any time during
756 ;; transcoding.
757 ;; - category :: global
758 ;; - type :: list (as returned by `org-element-parse-buffer')
760 ;; + `:preserve-breaks' :: Non-nil means transcoding should preserve
761 ;; all line breaks.
762 ;; - category :: option
763 ;; - type :: symbol (nil, t)
765 ;; + `:section-numbers' :: Non-nil means transcoding should add
766 ;; section numbers to headlines.
767 ;; - category :: option
768 ;; - type :: symbol (nil, t)
770 ;; + `:select-tags' :: List of tags enforcing inclusion of sub-trees
771 ;; in transcoding. When such a tag is present,
772 ;; subtrees without it are de facto excluded from
773 ;; the process. See `use-select-tags'.
774 ;; - category :: option
775 ;; - type :: list of strings
777 ;; + `:target-list' :: List of targets encountered in the parse tree.
778 ;; This is used to partly resolve "fuzzy" links
779 ;; (cf. `org-export-resolve-fuzzy-link').
780 ;; - category :: tree
781 ;; - type :: list of strings
783 ;; + `:time-stamp-file' :: Non-nil means transcoding should insert
784 ;; a time stamp in the output.
785 ;; - category :: option
786 ;; - type :: symbol (nil, t)
788 ;; + `:with-archived-trees' :: Non-nil when archived subtrees should
789 ;; also be transcoded. If it is set to the `headline' symbol,
790 ;; only the archived headline's name is retained.
791 ;; - category :: option
792 ;; - type :: symbol (nil, t, `headline')
794 ;; + `:with-author' :: Non-nil means author's name should be included
795 ;; in the output.
796 ;; - category :: option
797 ;; - type :: symbol (nil, t)
799 ;; + `:with-creator' :: Non-nild means a creation sentence should be
800 ;; inserted at the end of the transcoded string. If the value
801 ;; is `comment', it should be commented.
802 ;; - category :: option
803 ;; - type :: symbol (`comment', nil, t)
805 ;; + `:with-drawers' :: Non-nil means drawers should be exported. If
806 ;; its value is a list of names, only drawers with such names
807 ;; will be transcoded.
808 ;; - category :: option
809 ;; - type :: symbol (nil, t) or list of strings
811 ;; + `:with-email' :: Non-nil means output should contain author's
812 ;; email.
813 ;; - category :: option
814 ;; - type :: symbol (nil, t)
816 ;; + `:with-emphasize' :: Non-nil means emphasized text should be
817 ;; interpreted.
818 ;; - category :: option
819 ;; - type :: symbol (nil, t)
821 ;; + `:with-fixed-width' :: Non-nil if transcoder should interpret
822 ;; strings starting with a colon as a fixed-with (verbatim) area.
823 ;; - category :: option
824 ;; - type :: symbol (nil, t)
826 ;; + `:with-footnotes' :: Non-nil if transcoder should interpret
827 ;; footnotes.
828 ;; - category :: option
829 ;; - type :: symbol (nil, t)
831 ;; + `:with-priority' :: Non-nil means transcoding should include
832 ;; priority cookies.
833 ;; - category :: option
834 ;; - type :: symbol (nil, t)
836 ;; + `:with-special-strings' :: Non-nil means transcoding should
837 ;; interpret special strings in plain text.
838 ;; - category :: option
839 ;; - type :: symbol (nil, t)
841 ;; + `:with-sub-superscript' :: Non-nil means transcoding should
842 ;; interpret subscript and superscript. With a value of "{}",
843 ;; only interpret those using curly brackets.
844 ;; - category :: option
845 ;; - type :: symbol (nil, {}, t)
847 ;; + `:with-tables' :: Non-nil means transcoding should interpret
848 ;; tables.
849 ;; - category :: option
850 ;; - type :: symbol (nil, t)
852 ;; + `:with-tags' :: Non-nil means transcoding should keep tags in
853 ;; headlines. A `not-in-toc' value will remove them
854 ;; from the table of contents, if any, nonetheless.
855 ;; - category :: option
856 ;; - type :: symbol (nil, t, `not-in-toc')
858 ;; + `:with-tasks' :: Non-nil means transcoding should include
859 ;; headlines with a TODO keyword. A `todo' value
860 ;; will only include headlines with a todo type
861 ;; keyword while a `done' value will do the
862 ;; contrary. If a list of strings is provided, only
863 ;; tasks with keywords belonging to that list will
864 ;; be kept.
865 ;; - category :: option
866 ;; - type :: symbol (t, todo, done, nil) or list of strings
868 ;; + `:with-timestamps' :: Non-nil means transcoding should include
869 ;; time stamps and associated keywords. Otherwise, completely
870 ;; remove them.
871 ;; - category :: option
872 ;; - type :: symbol: (t, nil)
874 ;; + `:with-toc' :: Non-nil means that a table of contents has to be
875 ;; added to the output. An integer value limits its
876 ;; depth.
877 ;; - category :: option
878 ;; - type :: symbol (nil, t or integer)
880 ;; + `:with-todo-keywords' :: Non-nil means transcoding should
881 ;; include TODO keywords.
882 ;; - category :: option
883 ;; - type :: symbol (nil, t)
886 ;;;; Environment Options
888 ;; Environment options encompass all parameters defined outside the
889 ;; scope of the parsed data. They come from five sources, in
890 ;; increasing precedence order:
892 ;; - Global variables,
893 ;; - Buffer's attributes,
894 ;; - Options keyword symbols,
895 ;; - Buffer keywords,
896 ;; - Subtree properties.
898 ;; The central internal function with regards to environment options
899 ;; is `org-export-get-environment'. It updates global variables with
900 ;; "#+BIND:" keywords, then retrieve and prioritize properties from
901 ;; the different sources.
903 ;; The internal functions doing the retrieval are:
904 ;; `org-export-get-global-options',
905 ;; `org-export-get-buffer-attributes',
906 ;; `org-export-parse-option-keyword',
907 ;; `org-export-get-subtree-options' and
908 ;; `org-export-get-inbuffer-options'
910 ;; Also, `org-export-confirm-letbind' and `org-export-install-letbind'
911 ;; take care of the part relative to "#+BIND:" keywords.
913 (defun org-export-get-environment (&optional backend subtreep ext-plist)
914 "Collect export options from the current buffer.
916 Optional argument BACKEND is a symbol specifying which back-end
917 specific options to read, if any.
919 When optional argument SUBTREEP is non-nil, assume the export is
920 done against the current sub-tree.
922 Third optional argument EXT-PLIST is a property list with
923 external parameters overriding Org default settings, but still
924 inferior to file-local settings."
925 ;; First install #+BIND variables.
926 (org-export-install-letbind-maybe)
927 ;; Get and prioritize export options...
928 (let ((options (org-combine-plists
929 ;; ... from global variables...
930 (org-export-get-global-options backend)
931 ;; ... from buffer's attributes...
932 (org-export-get-buffer-attributes)
933 ;; ... from an external property list...
934 ext-plist
935 ;; ... from in-buffer settings...
936 (org-export-get-inbuffer-options
937 backend
938 (and buffer-file-name
939 (org-remove-double-quotes buffer-file-name)))
940 ;; ... and from subtree, when appropriate.
941 (and subtreep (org-export-get-subtree-options)))))
942 ;; Return plist.
943 options))
945 (defun org-export-parse-option-keyword (options &optional backend)
946 "Parse an OPTIONS line and return values as a plist.
947 Optional argument BACKEND is a symbol specifying which back-end
948 specific items to read, if any."
949 (let* ((all
950 (append org-export-option-alist
951 (and backend
952 (let ((var (intern
953 (format "org-%s-option-alist" backend))))
954 (and (boundp var) (eval var))))))
955 ;; Build an alist between #+OPTION: item and property-name.
956 (alist (delq nil
957 (mapcar (lambda (e)
958 (when (nth 2 e) (cons (regexp-quote (nth 2 e))
959 (car e))))
960 all)))
961 plist)
962 (mapc (lambda (e)
963 (when (string-match (concat "\\(\\`\\|[ \t]\\)"
964 (car e)
965 ":\\(([^)\n]+)\\|[^ \t\n\r;,.]*\\)")
966 options)
967 (setq plist (plist-put plist
968 (cdr e)
969 (car (read-from-string
970 (match-string 2 options)))))))
971 alist)
972 plist))
974 (defun org-export-get-subtree-options ()
975 "Get export options in subtree at point.
977 Assume point is at subtree's beginning.
979 Return options as a plist."
980 (let (prop plist)
981 (when (setq prop (progn (looking-at org-todo-line-regexp)
982 (or (save-match-data
983 (org-entry-get (point) "EXPORT_TITLE"))
984 (org-match-string-no-properties 3))))
985 (setq plist
986 (plist-put
987 plist :title
988 (org-element-parse-secondary-string
989 prop
990 (cdr (assq 'keyword org-element-string-restrictions))))))
991 (when (setq prop (org-entry-get (point) "EXPORT_TEXT"))
992 (setq plist (plist-put plist :text prop)))
993 (when (setq prop (org-entry-get (point) "EXPORT_AUTHOR"))
994 (setq plist (plist-put plist :author prop)))
995 (when (setq prop (org-entry-get (point) "EXPORT_DATE"))
996 (setq plist (plist-put plist :date prop)))
997 (when (setq prop (org-entry-get (point) "EXPORT_OPTIONS"))
998 (setq plist (org-export-add-options-to-plist plist prop)))
999 plist))
1001 (defun org-export-get-inbuffer-options (&optional backend files)
1002 "Return current buffer export options, as a plist.
1004 Optional argument BACKEND, when non-nil, is a symbol specifying
1005 which back-end specific options should also be read in the
1006 process.
1008 Optional argument FILES is a list of setup files names read so
1009 far, used to avoid circular dependencies.
1011 Assume buffer is in Org mode. Narrowing, if any, is ignored."
1012 (org-with-wide-buffer
1013 (goto-char (point-min))
1014 (let ((case-fold-search t) plist)
1015 ;; 1. Special keywords, as in `org-export-special-keywords'.
1016 (let ((special-re (org-make-options-regexp org-export-special-keywords)))
1017 (while (re-search-forward special-re nil t)
1018 (let ((element (org-element-at-point)))
1019 (when (eq (org-element-type element) 'keyword)
1020 (let* ((key (org-element-property :key element))
1021 (val (org-element-property :value element))
1022 (prop
1023 (cond
1024 ((string= key "SETUP_FILE")
1025 (let ((file
1026 (expand-file-name
1027 (org-remove-double-quotes (org-trim val)))))
1028 ;; Avoid circular dependencies.
1029 (unless (member file files)
1030 (with-temp-buffer
1031 (insert (org-file-contents file 'noerror))
1032 (org-mode)
1033 (org-export-get-inbuffer-options
1034 backend (cons file files))))))
1035 ((string= key "OPTIONS")
1036 (org-export-parse-option-keyword val backend))
1037 ((string= key "MACRO")
1038 (when (string-match
1039 "^\\([-a-zA-Z0-9_]+\\)\\(?:[ \t]+\\(.*?\\)[ \t]*$\\)?"
1040 val)
1041 (let ((key
1042 (intern
1043 (concat ":macro-"
1044 (downcase (match-string 1 val)))))
1045 (value (org-match-string-no-properties 2 val)))
1046 (cond
1047 ((not value) nil)
1048 ;; Value will be evaled. Leave it as-is.
1049 ((string-match "\\`(eval\\>" value)
1050 (list key value))
1051 ;; Value has to be parsed for nested
1052 ;; macros.
1054 (list
1056 (let ((restr
1057 (cdr
1058 (assq 'macro
1059 org-element-object-restrictions))))
1060 (org-element-parse-secondary-string
1061 ;; If user explicitly asks for
1062 ;; a newline, be sure to preserve it
1063 ;; from further filling with
1064 ;; `hard-newline'. Also replace
1065 ;; "\\n" with "\n", "\\\n" with "\\n"
1066 ;; and so on...
1067 (replace-regexp-in-string
1068 "\\(\\\\\\\\\\)n" "\\\\"
1069 (replace-regexp-in-string
1070 "\\(?:^\\|[^\\\\]\\)\\(\\\\n\\)"
1071 hard-newline value nil nil 1)
1072 nil nil 1)
1073 restr)))))))))))
1074 (setq plist (org-combine-plists plist prop)))))))
1075 ;; 2. Standard options, as in `org-export-option-alist'.
1076 (let* ((all (append org-export-option-alist
1077 ;; Also look for back-end specific options
1078 ;; if BACKEND is defined.
1079 (and backend
1080 (let ((var
1081 (intern
1082 (format "org-%s-option-alist" backend))))
1083 (and (boundp var) (eval var))))))
1084 ;; Build alist between keyword name and property name.
1085 (alist
1086 (delq nil (mapcar
1087 (lambda (e) (when (nth 1 e) (cons (nth 1 e) (car e))))
1088 all)))
1089 ;; Build regexp matching all keywords associated to export
1090 ;; options. Note: the search is case insensitive.
1091 (opt-re (org-make-options-regexp
1092 (delq nil (mapcar (lambda (e) (nth 1 e)) all)))))
1093 (goto-char (point-min))
1094 (while (re-search-forward opt-re nil t)
1095 (let ((element (org-element-at-point)))
1096 (when (eq (org-element-type element) 'keyword)
1097 (let* ((key (org-element-property :key element))
1098 (val (org-element-property :value element))
1099 (prop (cdr (assoc key alist)))
1100 (behaviour (nth 4 (assq prop all))))
1101 (setq plist
1102 (plist-put
1103 plist prop
1104 ;; Handle value depending on specified BEHAVIOUR.
1105 (case behaviour
1106 (space
1107 (if (not (plist-get plist prop)) (org-trim val)
1108 (concat (plist-get plist prop) " " (org-trim val))))
1109 (newline
1110 (org-trim
1111 (concat (plist-get plist prop) "\n" (org-trim val))))
1112 (split
1113 `(,@(plist-get plist prop) ,@(org-split-string val)))
1114 ('t val)
1115 (otherwise (if (not (plist-member plist prop)) val
1116 (plist-get plist prop))))))))))
1117 ;; Parse keywords specified in `org-element-parsed-keywords'.
1118 (mapc
1119 (lambda (key)
1120 (let* ((prop (cdr (assoc key alist)))
1121 (value (and prop (plist-get plist prop))))
1122 (when (stringp value)
1123 (setq plist
1124 (plist-put
1125 plist prop
1126 (org-element-parse-secondary-string
1127 value
1128 (cdr (assq 'keyword org-element-string-restrictions))))))))
1129 org-element-parsed-keywords))
1130 ;; 3. Return final value.
1131 plist)))
1133 (defun org-export-get-buffer-attributes ()
1134 "Return properties related to buffer attributes, as a plist."
1135 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
1136 (list
1137 ;; Store full path of input file name, or nil. For internal use.
1138 :input-file visited-file
1139 :title (or (and visited-file
1140 (file-name-sans-extension
1141 (file-name-nondirectory visited-file)))
1142 (buffer-name (buffer-base-buffer)))
1143 :macro-modification-time
1144 (and visited-file
1145 (file-exists-p visited-file)
1146 (concat "(eval (format-time-string \"$1\" '"
1147 (prin1-to-string (nth 5 (file-attributes visited-file)))
1148 "))"))
1149 ;; Store input file name as a macro.
1150 :macro-input-file (and visited-file (file-name-nondirectory visited-file))
1151 ;; `:macro-date', `:macro-time' and `:macro-property' could as
1152 ;; well be initialized as tree properties, since they don't
1153 ;; depend on buffer properties. Though, it may be more logical
1154 ;; to keep them close to other ":macro-" properties.
1155 :macro-date "(eval (format-time-string \"$1\"))"
1156 :macro-time "(eval (format-time-string \"$1\"))"
1157 :macro-property "(eval (org-entry-get nil \"$1\" 'selective))")))
1159 (defun org-export-get-global-options (&optional backend)
1160 "Return global export options as a plist.
1162 Optional argument BACKEND, if non-nil, is a symbol specifying
1163 which back-end specific export options should also be read in the
1164 process."
1165 (let ((all (append org-export-option-alist
1166 (and backend
1167 (let ((var (intern
1168 (format "org-%s-option-alist" backend))))
1169 (and (boundp var) (eval var))))))
1170 ;; Output value.
1171 plist)
1172 (mapc (lambda (cell)
1173 (setq plist (plist-put plist (car cell) (eval (nth 3 cell)))))
1174 all)
1175 ;; Return value.
1176 plist))
1178 (defun org-export-store-footnote-definitions (info)
1179 "Collect and store footnote definitions from current buffer in INFO.
1181 INFO is a plist containing export options.
1183 Footnotes definitions are stored as a alist whose CAR is
1184 footnote's label, as a string, and CDR the contents, as a parse
1185 tree. This alist will be consed to the value of
1186 `:footnote-definition-alist' in INFO, if any.
1188 The new plist is returned; use
1190 \(setq info (org-export-store-footnote-definitions info))
1192 to be sure to use the new value. INFO is modified by side
1193 effects."
1194 ;; Footnotes definitions must be collected in the original buffer,
1195 ;; as there's no insurance that they will still be in the parse
1196 ;; tree, due to some narrowing.
1197 (plist-put
1198 info :footnote-definition-alist
1199 (let ((alist (plist-get info :footnote-definition-alist)))
1200 (org-with-wide-buffer
1201 (goto-char (point-min))
1202 (while (re-search-forward org-footnote-definition-re nil t)
1203 (let ((def (org-footnote-at-definition-p)))
1204 (when def
1205 (org-skip-whitespace)
1206 (push (cons (car def)
1207 (save-restriction
1208 (narrow-to-region (point) (nth 2 def))
1209 ;; Like `org-element-parse-buffer', but
1210 ;; makes sure the definition doesn't start
1211 ;; with a section element.
1212 (nconc
1213 (list 'org-data nil)
1214 (org-element-parse-elements
1215 (point-min) (point-max) nil nil nil nil nil))))
1216 alist))))
1217 alist))))
1219 (defvar org-export-allow-BIND-local nil)
1220 (defun org-export-confirm-letbind ()
1221 "Can we use #+BIND values during export?
1222 By default this will ask for confirmation by the user, to divert
1223 possible security risks."
1224 (cond
1225 ((not org-export-allow-BIND) nil)
1226 ((eq org-export-allow-BIND t) t)
1227 ((local-variable-p 'org-export-allow-BIND-local) org-export-allow-BIND-local)
1228 (t (org-set-local 'org-export-allow-BIND-local
1229 (yes-or-no-p "Allow BIND values in this buffer? ")))))
1231 (defun org-export-install-letbind-maybe ()
1232 "Install the values from #+BIND lines as local variables.
1233 Variables must be installed before in-buffer options are
1234 retrieved."
1235 (let (letbind pair)
1236 (org-with-wide-buffer
1237 (goto-char (point-min))
1238 (while (re-search-forward (org-make-options-regexp '("BIND")) nil t)
1239 (when (org-export-confirm-letbind)
1240 (push (read (concat "(" (org-match-string-no-properties 2) ")"))
1241 letbind))))
1242 (while (setq pair (pop letbind))
1243 (org-set-local (car pair) (nth 1 pair)))))
1246 ;;;; Tree Properties
1248 ;; Tree properties are infromation extracted from parse tree. They
1249 ;; are initialized at the beginning of the transcoding process by
1250 ;; `org-export-collect-tree-properties'.
1252 ;; Dedicated functions focus on computing the value of specific tree
1253 ;; properties during initialization. Thus,
1254 ;; `org-export-populate-ignore-list' lists elements and objects that
1255 ;; should be skipped during export, `org-export-get-min-level' gets
1256 ;; the minimal exportable level, used as a basis to compute relative
1257 ;; level for headlines. Eventually
1258 ;; `org-export-collect-headline-numbering' builds an alist between
1259 ;; headlines and their numbering.
1261 (defun org-export-collect-tree-properties (data info backend)
1262 "Extract tree properties from parse tree.
1264 DATA is the parse tree from which information is retrieved. INFO
1265 is a list holding export options. BACKEND is the back-end called
1266 for transcoding, as a symbol.
1268 Following tree properties are set or updated:
1269 `:back-end' Back-end used for transcoding.
1271 `:footnote-definition-alist' List of footnotes definitions in
1272 original buffer and current parse tree.
1274 `:headline-offset' Offset between true level of headlines and
1275 local level. An offset of -1 means an headline
1276 of level 2 should be considered as a level
1277 1 headline in the context.
1279 `:headline-numbering' Alist of all headlines as key an the
1280 associated numbering as value.
1282 `:ignore-list' List of elements that should be ignored during
1283 export.
1285 `:parse-tree' Whole parse tree.
1287 `:target-list' List of all targets in the parse tree."
1288 ;; Get the list of elements and objects to ignore, and put it into
1289 ;; `:ignore-list'. Do not overwrite any user ignore that might have
1290 ;; been done during parse tree filtering.
1291 (setq info
1292 (plist-put info
1293 :ignore-list
1294 (append (org-export-populate-ignore-list data info)
1295 (plist-get info :ignore-list))))
1296 ;; Compute `:headline-offset' in order to be able to use
1297 ;; `org-export-get-relative-level'.
1298 (setq info
1299 (plist-put info
1300 :headline-offset (- 1 (org-export-get-min-level data info))))
1301 ;; Update footnotes definitions list with definitions in parse tree.
1302 ;; This is required since buffer expansion might have modified
1303 ;; boundaries of footnote definitions contained in the parse tree.
1304 ;; This way, definitions in `footnote-definition-alist' are bound to
1305 ;; match those in the parse tree.
1306 (let ((defs (plist-get info :footnote-definition-alist)))
1307 (org-element-map
1308 data 'footnote-definition
1309 (lambda (fn)
1310 (push (cons (org-element-property :label fn)
1311 `(org-data nil ,@(org-element-contents fn)))
1312 defs)))
1313 (setq info (plist-put info :footnote-definition-alist defs)))
1314 ;; Properties order doesn't matter: get the rest of the tree
1315 ;; properties.
1316 (nconc
1317 `(:parse-tree
1318 ,data
1319 :target-list
1320 ,(org-element-map
1321 data '(keyword target)
1322 (lambda (blob)
1323 (when (or (eq (org-element-type blob) 'target)
1324 (string= (org-element-property :key blob) "TARGET"))
1325 blob)) info)
1326 :headline-numbering ,(org-export-collect-headline-numbering data info)
1327 :back-end ,backend)
1328 info))
1330 (defun org-export-get-min-level (data options)
1331 "Return minimum exportable headline's level in DATA.
1332 DATA is parsed tree as returned by `org-element-parse-buffer'.
1333 OPTIONS is a plist holding export options."
1334 (catch 'exit
1335 (let ((min-level 10000))
1336 (mapc
1337 (lambda (blob)
1338 (when (and (eq (org-element-type blob) 'headline)
1339 (not (member blob (plist-get options :ignore-list))))
1340 (setq min-level
1341 (min (org-element-property :level blob) min-level)))
1342 (when (= min-level 1) (throw 'exit 1)))
1343 (org-element-contents data))
1344 ;; If no headline was found, for the sake of consistency, set
1345 ;; minimum level to 1 nonetheless.
1346 (if (= min-level 10000) 1 min-level))))
1348 (defun org-export-collect-headline-numbering (data options)
1349 "Return numbering of all exportable headlines in a parse tree.
1351 DATA is the parse tree. OPTIONS is the plist holding export
1352 options.
1354 Return an alist whose key is an headline and value is its
1355 associated numbering \(in the shape of a list of numbers\)."
1356 (let ((numbering (make-vector org-export-max-depth 0)))
1357 (org-element-map
1358 data
1359 'headline
1360 (lambda (headline)
1361 (let ((relative-level
1362 (1- (org-export-get-relative-level headline options))))
1363 (cons
1364 headline
1365 (loop for n across numbering
1366 for idx from 0 to org-export-max-depth
1367 when (< idx relative-level) collect n
1368 when (= idx relative-level) collect (aset numbering idx (1+ n))
1369 when (> idx relative-level) do (aset numbering idx 0)))))
1370 options)))
1372 (defun org-export-populate-ignore-list (data options)
1373 "Return list of elements and objects to ignore during export.
1375 DATA is the parse tree to traverse. OPTIONS is the plist holding
1376 export options.
1378 Return elements or objects to ignore as a list."
1379 (let (ignore
1380 (walk-data
1381 (function
1382 (lambda (data options selected)
1383 ;; Collect ignored elements or objects into IGNORE-LIST.
1384 (mapc
1385 (lambda (el)
1386 (if (org-export--skip-p el options selected) (push el ignore)
1387 (let ((type (org-element-type el)))
1388 (if (and (eq (plist-get info :with-archived-trees) 'headline)
1389 (eq (org-element-type el) 'headline)
1390 (org-element-property :archivedp el))
1391 ;; If headline is archived but tree below has
1392 ;; to be skipped, add it to ignore list.
1393 (mapc (lambda (e) (push e ignore))
1394 (org-element-contents el))
1395 ;; Move into recursive objects/elements.
1396 (when (or (eq type 'org-data)
1397 (memq type org-element-greater-elements)
1398 (memq type org-element-recursive-objects)
1399 (eq type 'paragraph))
1400 (funcall walk-data el options selected))))))
1401 (org-element-contents data))))))
1402 ;; Main call. First find trees containing a select tag, if any.
1403 (funcall walk-data data options (org-export--selected-trees data options))
1404 ;; Return value.
1405 ignore))
1407 (defun org-export--selected-trees (data info)
1408 "Return list of headlines containing a select tag in their tree.
1409 DATA is parsed data as returned by `org-element-parse-buffer'.
1410 INFO is a plist holding export options."
1411 (let (selected-trees
1412 (walk-data
1413 (function
1414 (lambda (data genealogy)
1415 (case (org-element-type data)
1416 (org-data
1417 (funcall walk-data (org-element-contents data) genealogy))
1418 (headline
1419 (let ((tags (org-element-property :tags headline)))
1420 (if (and tags
1421 (loop for tag in (plist-get info :select-tags)
1422 thereis (string-match
1423 (format ":%s:" tag) tags)))
1424 ;; When a select tag is found, mark as acceptable
1425 ;; full genealogy and every headline within the
1426 ;; tree.
1427 (setq selected-trees
1428 (append
1429 (cons data genealogy)
1430 (org-element-map data 'headline 'identity)
1431 selected-trees))
1432 ;; Else, continue searching in tree, recursively.
1433 (funcall walk-data data (cons data genealogy))))))))))
1434 (funcall walk-data data nil) selected-trees))
1436 (defun org-export--skip-p (blob options select-tags)
1437 "Non-nil when element or object BLOB should be skipped during export.
1438 OPTIONS is the plist holding export options."
1439 (case (org-element-type blob)
1440 ;; Check headline.
1441 (headline
1442 (let ((with-tasks (plist-get options :with-tasks))
1443 (todo (org-element-property :todo-keyword blob))
1444 (todo-type (org-element-property :todo-type blob))
1445 (archived (plist-get options :with-archived-trees))
1446 (tag-list (let ((tags (org-element-property :tags blob)))
1447 (and tags (org-split-string tags ":")))))
1449 ;; Ignore subtrees with an exclude tag.
1450 (loop for k in (plist-get options :exclude-tags)
1451 thereis (member k tag-list))
1452 ;; Ignore subtrees without a select tag, when such tag is
1453 ;; found in the buffer.
1454 (member blob select-tags)
1455 ;; Ignore commented sub-trees.
1456 (org-element-property :commentedp blob)
1457 ;; Ignore archived subtrees if `:with-archived-trees' is nil.
1458 (and (not archived) (org-element-property :archivedp blob))
1459 ;; Ignore tasks, if specified by `:with-tasks' property.
1460 (and todo
1461 (or (not with-tasks)
1462 (and (memq with-tasks '(todo done))
1463 (not (eq todo-type with-tasks)))
1464 (and (consp with-tasks) (not (member todo with-tasks))))))))
1465 ;; Check time-stamp.
1466 (time-stamp (not (plist-get options :with-timestamps)))
1467 ;; Check drawer.
1468 (drawer
1469 (or (not (plist-get options :with-drawers))
1470 (and (consp (plist-get options :with-drawers))
1471 (not (member (org-element-property :drawer-name blob)
1472 (plist-get options :with-drawers))))))))
1476 ;;; The Transcoder
1478 ;; This function reads Org data (obtained with, i.e.
1479 ;; `org-element-parse-buffer') and transcodes it into a specified
1480 ;; back-end output. It takes care of updating local properties,
1481 ;; filtering out elements or objects according to export options and
1482 ;; organizing the output blank lines and white space are preserved.
1484 ;; Though, this function is inapropriate for secondary strings, which
1485 ;; require a fresh copy of the plist passed as INFO argument. Thus,
1486 ;; `org-export-secondary-string' is provided for that specific task.
1488 ;; Internally, three functions handle the filtering of objects and
1489 ;; elements during the export. In particular,
1490 ;; `org-export-ignore-element' mark an element or object so future
1491 ;; parse tree traversals skip it, `org-export-interpret-p' tells which
1492 ;; elements or objects should be seen as real Org syntax and
1493 ;; `org-export-expand' transforms the others back into their original
1494 ;; shape.
1496 (defun org-export-data (data backend info)
1497 "Convert DATA to a string into BACKEND format.
1499 DATA is a nested list as returned by `org-element-parse-buffer'.
1501 BACKEND is a symbol among supported exporters.
1503 INFO is a plist holding export options and also used as
1504 a communication channel between elements when walking the nested
1505 list. See `org-export-update-info' function for more
1506 details.
1508 Return transcoded string."
1509 (mapconcat
1510 ;; BLOB can be an element, an object, a string, or nil.
1511 (lambda (blob)
1512 (cond
1513 ((not blob) nil)
1514 ;; BLOB is a string. Check if the optional transcoder for plain
1515 ;; text exists, and call it in that case. Otherwise, simply
1516 ;; return string. Also update INFO and call
1517 ;; `org-export-filter-plain-text-functions'.
1518 ((stringp blob)
1519 (let ((transcoder (intern (format "org-%s-plain-text" backend))))
1520 (org-export-filter-apply-functions
1521 (plist-get info :filter-plain-text)
1522 (if (fboundp transcoder) (funcall transcoder blob info) blob)
1523 backend info)))
1524 ;; BLOB is an element or an object.
1526 (let* ((type (org-element-type blob))
1527 ;; 1. Determine the appropriate TRANSCODER.
1528 (transcoder
1529 (cond
1530 ;; 1.0 A full Org document is inserted.
1531 ((eq type 'org-data) 'identity)
1532 ;; 1.1. BLOB should be ignored.
1533 ((member blob (plist-get info :ignore-list)) nil)
1534 ;; 1.2. BLOB shouldn't be transcoded. Interpret it
1535 ;; back into Org syntax.
1536 ((not (org-export-interpret-p blob info)) 'org-export-expand)
1537 ;; 1.3. Else apply naming convention.
1538 (t (let ((trans (intern (format "org-%s-%s" backend type))))
1539 (and (fboundp trans) trans)))))
1540 ;; 2. Compute CONTENTS of BLOB.
1541 (contents
1542 (cond
1543 ;; Case 0. No transcoder defined: ignore BLOB.
1544 ((not transcoder) nil)
1545 ;; Case 1. Transparently export an Org document.
1546 ((eq type 'org-data) (org-export-data blob backend info))
1547 ;; Case 2. For a recursive object.
1548 ((memq type org-element-recursive-objects)
1549 (org-export-data blob backend info))
1550 ;; Case 3. For a recursive element.
1551 ((memq type org-element-greater-elements)
1552 ;; Ignore contents of an archived tree
1553 ;; when `:with-archived-trees' is `headline'.
1554 (unless (and
1555 (eq type 'headline)
1556 (eq (plist-get info :with-archived-trees) 'headline)
1557 (org-element-property :archivedp blob))
1558 (org-element-normalize-string
1559 (org-export-data blob backend info))))
1560 ;; Case 4. For a paragraph.
1561 ((eq type 'paragraph)
1562 (let ((paragraph
1563 (org-element-normalize-contents
1564 blob
1565 ;; When normalizing contents of an item or
1566 ;; a footnote definition, ignore first line's
1567 ;; indentation: there is none and it might be
1568 ;; misleading.
1569 (and (not (org-export-get-previous-element blob info))
1570 (let ((parent (org-export-get-parent blob info)))
1571 (memq (org-element-type parent)
1572 '(footnote-definition item)))))))
1573 (org-export-data paragraph backend info)))))
1574 ;; 3. Transcode BLOB into RESULTS string.
1575 (results (cond
1576 ((not transcoder) nil)
1577 ((eq transcoder 'org-export-expand)
1578 (org-export-data
1579 `(org-data nil ,(funcall transcoder blob contents))
1580 backend info))
1581 (t (funcall transcoder blob contents info)))))
1582 ;; 4. Return results.
1583 (cond
1584 ((not results) nil)
1585 ;; No filter for a full document.
1586 ((eq type 'org-data) results)
1587 ;; Otherwise, update INFO, append the same white space
1588 ;; between elements or objects as in the original buffer,
1589 ;; and call appropriate filters.
1591 (let ((results
1592 (org-export-filter-apply-functions
1593 (plist-get info (intern (format ":filter-%s" type)))
1594 (let ((post-blank (org-element-property :post-blank blob)))
1595 (if (memq type org-element-all-elements)
1596 (concat (org-element-normalize-string results)
1597 (make-string post-blank ?\n))
1598 (concat results (make-string post-blank ? ))))
1599 backend info)))
1600 ;; Eventually return string.
1601 results)))))))
1602 (org-element-contents data) ""))
1604 (defun org-export-secondary-string (secondary backend info)
1605 "Convert SECONDARY string into BACKEND format.
1607 SECONDARY is a nested list as returned by
1608 `org-element-parse-secondary-string'.
1610 BACKEND is a symbol among supported exporters. INFO is a plist
1611 used as a communication channel.
1613 Return transcoded string."
1614 ;; Make SECONDARY acceptable for `org-export-data'.
1615 (let ((s (if (listp secondary) secondary (list secondary))))
1616 (org-export-data `(org-data nil ,@s) backend (copy-sequence info))))
1618 (defun org-export-interpret-p (blob info)
1619 "Non-nil if element or object BLOB should be interpreted as Org syntax.
1620 Check is done according to export options INFO, stored as
1621 a plist."
1622 (case (org-element-type blob)
1623 ;; ... entities...
1624 (entity (plist-get info :with-entities))
1625 ;; ... emphasis...
1626 (emphasis (plist-get info :with-emphasize))
1627 ;; ... fixed-width areas.
1628 (fixed-width (plist-get info :with-fixed-width))
1629 ;; ... footnotes...
1630 ((footnote-definition footnote-reference)
1631 (plist-get info :with-footnotes))
1632 ;; ... sub/superscripts...
1633 ((subscript superscript)
1634 (let ((sub/super-p (plist-get info :with-sub-superscript)))
1635 (if (eq sub/super-p '{})
1636 (org-element-property :use-brackets-p blob)
1637 sub/super-p)))
1638 ;; ... tables...
1639 (table (plist-get info :with-tables))
1640 (otherwise t)))
1642 (defsubst org-export-expand (blob contents)
1643 "Expand a parsed element or object to its original state.
1644 BLOB is either an element or an object. CONTENTS is its
1645 contents, as a string or nil."
1646 (funcall (intern (format "org-element-%s-interpreter" (org-element-type blob)))
1647 blob contents))
1649 (defun org-export-ignore-element (element info)
1650 "Add ELEMENT to `:ignore-list' in INFO.
1652 Any element in `:ignore-list' will be skipped when using
1653 `org-element-map'. INFO is modified by side effects."
1654 (plist-put info :ignore-list (cons element (plist-get info :ignore-list))))
1658 ;;; The Filter System
1660 ;; Filters allow end-users to tweak easily the transcoded output.
1661 ;; They are the functional counterpart of hooks, as every filter in
1662 ;; a set is applied to the return value of the previous one.
1664 ;; Every set is back-end agnostic. Although, a filter is always
1665 ;; called, in addition to the string it applies to, with the back-end
1666 ;; used as argument, so it's easy enough for the end-user to add
1667 ;; back-end specific filters in the set. The communication channel,
1668 ;; as a plist, is required as the third argument.
1670 ;; Filters sets are defined below. There are of four types:
1672 ;; - `org-export-filter-parse-tree-functions' applies directly on the
1673 ;; complete parsed tree. It's the only filters set that doesn't
1674 ;; apply to a string.
1675 ;; - `org-export-filter-final-output-functions' applies to the final
1676 ;; transcoded string.
1677 ;; - `org-export-filter-plain-text-functions' applies to any string
1678 ;; not recognized as Org syntax.
1679 ;; - `org-export-filter-TYPE-functions' applies on the string returned
1680 ;; after an element or object of type TYPE has been transcoded.
1682 ;; All filters sets are applied through
1683 ;; `org-export-filter-apply-functions' function. Filters in a set are
1684 ;; applied in a LIFO fashion. It allows developers to be sure that
1685 ;; their filters will be applied first.
1687 ;; Filters properties are installed in communication channel just
1688 ;; before parsing, with `org-export-install-filters' function.
1690 ;;;; Special Filters
1691 (defvar org-export-filter-parse-tree-functions nil
1692 "Filter, or list of filters, applied to the parsed tree.
1693 Each filter is called with three arguments: the parse tree, as
1694 returned by `org-element-parse-buffer', the back-end, as
1695 a symbol, and the communication channel, as a plist. It must
1696 return the modified parse tree to transcode.")
1698 (defvar org-export-filter-final-output-functions nil
1699 "Filter, or list of filters, applied to the transcoded string.
1700 Each filter is called with three arguments: the full transcoded
1701 string, the back-end, as a symbol, and the communication channel,
1702 as a plist. It must return a string that will be used as the
1703 final export output.")
1705 (defvar org-export-filter-plain-text-functions nil
1706 "Filter, or list of filters, applied to plain text.
1707 Each filter is called with three arguments: a string which
1708 contains no Org syntax, the back-end, as a symbol, and the
1709 communication channel, as a plist. It must return a string or
1710 nil.")
1713 ;;;; Elements Filters
1715 (defvar org-export-filter-center-block-functions nil
1716 "List of functions applied to a transcoded center block.
1717 Each filter is called with three arguments: the transcoded center
1718 block, as a string, the back-end, as a symbol, and the
1719 communication channel, as a plist. It must return a string or
1720 nil.")
1722 (defvar org-export-filter-drawer-functions nil
1723 "List of functions applied to a transcoded drawer.
1724 Each filter is called with three arguments: the transcoded
1725 drawer, as a string, the back-end, as a symbol, and the
1726 communication channel, as a plist. It must return a string or
1727 nil.")
1729 (defvar org-export-filter-dynamic-block-functions nil
1730 "List of functions applied to a transcoded dynamic-block.
1731 Each filter is called with three arguments: the transcoded
1732 dynamic-block, as a string, the back-end, as a symbol, and the
1733 communication channel, as a plist. It must return a string or
1734 nil.")
1736 (defvar org-export-filter-headline-functions nil
1737 "List of functions applied to a transcoded headline.
1738 Each filter is called with three arguments: the transcoded
1739 headline, as a string, the back-end, as a symbol, and the
1740 communication channel, as a plist. It must return a string or
1741 nil.")
1743 (defvar org-export-filter-inlinetask-functions nil
1744 "List of functions applied to a transcoded inlinetask.
1745 Each filter is called with three arguments: the transcoded
1746 inlinetask, as a string, the back-end, as a symbol, and the
1747 communication channel, as a plist. It must return a string or
1748 nil.")
1750 (defvar org-export-filter-plain-list-functions nil
1751 "List of functions applied to a transcoded plain-list.
1752 Each filter is called with three arguments: the transcoded
1753 plain-list, as a string, the back-end, as a symbol, and the
1754 communication channel, as a plist. It must return a string or
1755 nil.")
1757 (defvar org-export-filter-item-functions nil
1758 "List of functions applied to a transcoded item.
1759 Each filter is called with three arguments: the transcoded item,
1760 as a string, the back-end, as a symbol, and the communication
1761 channel, as a plist. It must return a string or nil.")
1763 (defvar org-export-filter-comment-functions nil
1764 "List of functions applied to a transcoded comment.
1765 Each filter is called with three arguments: the transcoded
1766 comment, as a string, the back-end, as a symbol, and the
1767 communication channel, as a plist. It must return a string or
1768 nil.")
1770 (defvar org-export-filter-comment-block-functions nil
1771 "List of functions applied to a transcoded comment-comment.
1772 Each filter is called with three arguments: the transcoded
1773 comment-block, as a string, the back-end, as a symbol, and the
1774 communication channel, as a plist. It must return a string or
1775 nil.")
1777 (defvar org-export-filter-example-block-functions nil
1778 "List of functions applied to a transcoded example-block.
1779 Each filter is called with three arguments: the transcoded
1780 example-block, as a string, the back-end, as a symbol, and the
1781 communication channel, as a plist. It must return a string or
1782 nil.")
1784 (defvar org-export-filter-export-block-functions nil
1785 "List of functions applied to a transcoded export-block.
1786 Each filter is called with three arguments: the transcoded
1787 export-block, as a string, the back-end, as a symbol, and the
1788 communication channel, as a plist. It must return a string or
1789 nil.")
1791 (defvar org-export-filter-fixed-width-functions nil
1792 "List of functions applied to a transcoded fixed-width.
1793 Each filter is called with three arguments: the transcoded
1794 fixed-width, as a string, the back-end, as a symbol, and the
1795 communication channel, as a plist. It must return a string or
1796 nil.")
1798 (defvar org-export-filter-footnote-definition-functions nil
1799 "List of functions applied to a transcoded footnote-definition.
1800 Each filter is called with three arguments: the transcoded
1801 footnote-definition, as a string, the back-end, as a symbol, and
1802 the communication channel, as a plist. It must return a string
1803 or nil.")
1805 (defvar org-export-filter-horizontal-rule-functions nil
1806 "List of functions applied to a transcoded horizontal-rule.
1807 Each filter is called with three arguments: the transcoded
1808 horizontal-rule, as a string, the back-end, as a symbol, and the
1809 communication channel, as a plist. It must return a string or
1810 nil.")
1812 (defvar org-export-filter-keyword-functions nil
1813 "List of functions applied to a transcoded keyword.
1814 Each filter is called with three arguments: the transcoded
1815 keyword, as a string, the back-end, as a symbol, and the
1816 communication channel, as a plist. It must return a string or
1817 nil.")
1819 (defvar org-export-filter-latex-environment-functions nil
1820 "List of functions applied to a transcoded latex-environment.
1821 Each filter is called with three arguments: the transcoded
1822 latex-environment, as a string, the back-end, as a symbol, and
1823 the communication channel, as a plist. It must return a string
1824 or nil.")
1826 (defvar org-export-filter-babel-call-functions nil
1827 "List of functions applied to a transcoded babel-call.
1828 Each filter is called with three arguments: the transcoded
1829 babel-call, as a string, the back-end, as a symbol, and the
1830 communication channel, as a plist. It must return a string or
1831 nil.")
1833 (defvar org-export-filter-paragraph-functions nil
1834 "List of functions applied to a transcoded paragraph.
1835 Each filter is called with three arguments: the transcoded
1836 paragraph, as a string, the back-end, as a symbol, and the
1837 communication channel, as a plist. It must return a string or
1838 nil.")
1840 (defvar org-export-filter-property-drawer-functions nil
1841 "List of functions applied to a transcoded property-drawer.
1842 Each filter is called with three arguments: the transcoded
1843 property-drawer, as a string, the back-end, as a symbol, and the
1844 communication channel, as a plist. It must return a string or
1845 nil.")
1847 (defvar org-export-filter-quote-block-functions nil
1848 "List of functions applied to a transcoded quote block.
1849 Each filter is called with three arguments: the transcoded quote
1850 block, as a string, the back-end, as a symbol, and the
1851 communication channel, as a plist. It must return a string or
1852 nil.")
1854 (defvar org-export-filter-quote-section-functions nil
1855 "List of functions applied to a transcoded quote-section.
1856 Each filter is called with three arguments: the transcoded
1857 quote-section, as a string, the back-end, as a symbol, and the
1858 communication channel, as a plist. It must return a string or
1859 nil.")
1861 (defvar org-export-filter-section-functions nil
1862 "List of functions applied to a transcoded section.
1863 Each filter is called with three arguments: the transcoded
1864 section, as a string, the back-end, as a symbol, and the
1865 communication channel, as a plist. It must return a string or
1866 nil.")
1868 (defvar org-export-filter-special-block-functions nil
1869 "List of functions applied to a transcoded special block.
1870 Each filter is called with three arguments: the transcoded
1871 special block, as a string, the back-end, as a symbol, and the
1872 communication channel, as a plist. It must return a string or
1873 nil.")
1875 (defvar org-export-filter-src-block-functions nil
1876 "List of functions applied to a transcoded src-block.
1877 Each filter is called with three arguments: the transcoded
1878 src-block, as a string, the back-end, as a symbol, and the
1879 communication channel, as a plist. It must return a string or
1880 nil.")
1882 (defvar org-export-filter-table-functions nil
1883 "List of functions applied to a transcoded table.
1884 Each filter is called with three arguments: the transcoded table,
1885 as a string, the back-end, as a symbol, and the communication
1886 channel, as a plist. It must return a string or nil.")
1888 (defvar org-export-filter-verse-block-functions nil
1889 "List of functions applied to a transcoded verse block.
1890 Each filter is called with three arguments: the transcoded verse
1891 block, as a string, the back-end, as a symbol, and the
1892 communication channel, as a plist. It must return a string or
1893 nil.")
1896 ;;;; Objects Filters
1898 (defvar org-export-filter-emphasis-functions nil
1899 "List of functions applied to a transcoded emphasis.
1900 Each filter is called with three arguments: the transcoded
1901 emphasis, as a string, the back-end, as a symbol, and the
1902 communication channel, as a plist. It must return a string or
1903 nil.")
1905 (defvar org-export-filter-entity-functions nil
1906 "List of functions applied to a transcoded entity.
1907 Each filter is called with three arguments: the transcoded
1908 entity, as a string, the back-end, as a symbol, and the
1909 communication channel, as a plist. It must return a string or
1910 nil.")
1912 (defvar org-export-filter-export-snippet-functions nil
1913 "List of functions applied to a transcoded export-snippet.
1914 Each filter is called with three arguments: the transcoded
1915 export-snippet, as a string, the back-end, as a symbol, and the
1916 communication channel, as a plist. It must return a string or
1917 nil.")
1919 (defvar org-export-filter-footnote-reference-functions nil
1920 "List of functions applied to a transcoded footnote-reference.
1921 Each filter is called with three arguments: the transcoded
1922 footnote-reference, as a string, the back-end, as a symbol, and
1923 the communication channel, as a plist. It must return a string
1924 or nil.")
1926 (defvar org-export-filter-inline-babel-call-functions nil
1927 "List of functions applied to a transcoded inline-babel-call.
1928 Each filter is called with three arguments: the transcoded
1929 inline-babel-call, as a string, the back-end, as a symbol, and
1930 the communication channel, as a plist. It must return a string
1931 or nil.")
1933 (defvar org-export-filter-inline-src-block-functions nil
1934 "List of functions applied to a transcoded inline-src-block.
1935 Each filter is called with three arguments: the transcoded
1936 inline-src-block, as a string, the back-end, as a symbol, and the
1937 communication channel, as a plist. It must return a string or
1938 nil.")
1940 (defvar org-export-filter-latex-fragment-functions nil
1941 "List of functions applied to a transcoded latex-fragment.
1942 Each filter is called with three arguments: the transcoded
1943 latex-fragment, as a string, the back-end, as a symbol, and the
1944 communication channel, as a plist. It must return a string or
1945 nil.")
1947 (defvar org-export-filter-line-break-functions nil
1948 "List of functions applied to a transcoded line-break.
1949 Each filter is called with three arguments: the transcoded
1950 line-break, as a string, the back-end, as a symbol, and the
1951 communication channel, as a plist. It must return a string or
1952 nil.")
1954 (defvar org-export-filter-link-functions nil
1955 "List of functions applied to a transcoded link.
1956 Each filter is called with three arguments: the transcoded link,
1957 as a string, the back-end, as a symbol, and the communication
1958 channel, as a plist. It must return a string or nil.")
1960 (defvar org-export-filter-macro-functions nil
1961 "List of functions applied to a transcoded macro.
1962 Each filter is called with three arguments: the transcoded macro,
1963 as a string, the back-end, as a symbol, and the communication
1964 channel, as a plist. It must return a string or nil.")
1966 (defvar org-export-filter-radio-target-functions nil
1967 "List of functions applied to a transcoded radio-target.
1968 Each filter is called with three arguments: the transcoded
1969 radio-target, as a string, the back-end, as a symbol, and the
1970 communication channel, as a plist. It must return a string or
1971 nil.")
1973 (defvar org-export-filter-statistics-cookie-functions nil
1974 "List of functions applied to a transcoded statistics-cookie.
1975 Each filter is called with three arguments: the transcoded
1976 statistics-cookie, as a string, the back-end, as a symbol, and
1977 the communication channel, as a plist. It must return a string
1978 or nil.")
1980 (defvar org-export-filter-subscript-functions nil
1981 "List of functions applied to a transcoded subscript.
1982 Each filter is called with three arguments: the transcoded
1983 subscript, as a string, the back-end, as a symbol, and the
1984 communication channel, as a plist. It must return a string or
1985 nil.")
1987 (defvar org-export-filter-superscript-functions nil
1988 "List of functions applied to a transcoded superscript.
1989 Each filter is called with three arguments: the transcoded
1990 superscript, as a string, the back-end, as a symbol, and the
1991 communication channel, as a plist. It must return a string or
1992 nil.")
1994 (defvar org-export-filter-target-functions nil
1995 "List of functions applied to a transcoded target.
1996 Each filter is called with three arguments: the transcoded
1997 target, as a string, the back-end, as a symbol, and the
1998 communication channel, as a plist. It must return a string or
1999 nil.")
2001 (defvar org-export-filter-time-stamp-functions nil
2002 "List of functions applied to a transcoded time-stamp.
2003 Each filter is called with three arguments: the transcoded
2004 time-stamp, as a string, the back-end, as a symbol, and the
2005 communication channel, as a plist. It must return a string or
2006 nil.")
2008 (defvar org-export-filter-verbatim-functions nil
2009 "List of functions applied to a transcoded verbatim.
2010 Each filter is called with three arguments: the transcoded
2011 verbatim, as a string, the back-end, as a symbol, and the
2012 communication channel, as a plist. It must return a string or
2013 nil.")
2015 (defun org-export-filter-apply-functions (filters value backend info)
2016 "Call every function in FILTERS with arguments VALUE, BACKEND and INFO.
2017 Functions are called in a LIFO fashion, to be sure that developer
2018 specified filters, if any, are called first."
2019 (loop for filter in filters
2020 if (not value) return nil else
2021 do (setq value (funcall filter value backend info)))
2022 value)
2024 (defun org-export-install-filters (backend info)
2025 "Install filters properties in communication channel.
2027 BACKEND is a symbol specifying which back-end specific filters to
2028 install, if any. INFO is a plist containing the current
2029 communication channel.
2031 Return the updated communication channel."
2032 (let (plist)
2033 ;; Install user defined filters with `org-export-filters-alist'.
2034 (mapc (lambda (p)
2035 (setq plist (plist-put plist (car p) (eval (cdr p)))))
2036 org-export-filters-alist)
2037 ;; Prepend back-end specific filters to that list.
2038 (let ((back-end-filters (intern (format "org-%s-filters-alist" backend))))
2039 (when (boundp back-end-filters)
2040 (mapc (lambda (p)
2041 ;; Single values get consed, lists are prepended.
2042 (let ((key (car p)) (value (cdr p)))
2043 (when value
2044 (setq plist
2045 (plist-put
2046 plist key
2047 (if (atom value) (cons value (plist-get plist key))
2048 (append value (plist-get plist key))))))))
2049 (eval back-end-filters))))
2050 ;; Return new communication channel.
2051 (org-combine-plists info plist)))
2055 ;;; Core functions
2057 ;; This is the room for the main function, `org-export-as', along with
2058 ;; its derivatives, `org-export-to-buffer' and `org-export-to-file'.
2059 ;; They differ only by the way they output the resulting code.
2061 ;; `org-export-output-file-name' is an auxiliary function meant to be
2062 ;; used with `org-export-to-file'. With a given extension, it tries
2063 ;; to provide a canonical file name to write export output to.
2065 ;; Note that `org-export-as' doesn't really parse the current buffer,
2066 ;; but a copy of it (with the same buffer-local variables and
2067 ;; visibility), where include keywords are expanded and Babel blocks
2068 ;; are executed, if appropriate.
2069 ;; `org-export-with-current-buffer-copy' macro prepares that copy.
2071 ;; File inclusion is taken care of by
2072 ;; `org-export-expand-include-keyword' and
2073 ;; `org-export-prepare-file-contents'. Structure wise, including
2074 ;; a whole Org file in a buffer often makes little sense. For
2075 ;; example, if the file contains an headline and the include keyword
2076 ;; was within an item, the item should contain the headline. That's
2077 ;; why file inclusion should be done before any structure can be
2078 ;; associated to the file, that is before parsing.
2080 (defun org-export-as
2081 (backend &optional subtreep visible-only body-only ext-plist noexpand)
2082 "Transcode current Org buffer into BACKEND code.
2084 If narrowing is active in the current buffer, only transcode its
2085 narrowed part.
2087 If a region is active, transcode that region.
2089 When optional argument SUBTREEP is non-nil, transcode the
2090 sub-tree at point, extracting information from the headline
2091 properties first.
2093 When optional argument VISIBLE-ONLY is non-nil, don't export
2094 contents of hidden elements.
2096 When optional argument BODY-ONLY is non-nil, only return body
2097 code, without preamble nor postamble.
2099 Optional argument EXT-PLIST, when provided, is a property list
2100 with external parameters overriding Org default settings, but
2101 still inferior to file-local settings.
2103 Optional argument NOEXPAND, when non-nil, prevents included files
2104 to be expanded and Babel code to be executed.
2106 Return code as a string."
2107 (save-excursion
2108 (save-restriction
2109 ;; Narrow buffer to an appropriate region or subtree for
2110 ;; parsing. If parsing subtree, be sure to remove main headline
2111 ;; too.
2112 (cond ((org-region-active-p)
2113 (narrow-to-region (region-beginning) (region-end)))
2114 (subtreep
2115 (org-narrow-to-subtree)
2116 (goto-char (point-min))
2117 (forward-line)
2118 (narrow-to-region (point) (point-max))))
2119 ;; 1. Get export environment from original buffer. Store
2120 ;; original footnotes definitions in communication channel as
2121 ;; they might not be accessible anymore in a narrowed parse
2122 ;; tree. Also install user's and developer's filters.
2123 (let ((info (org-export-install-filters
2124 backend
2125 (org-export-store-footnote-definitions
2126 (org-export-get-environment backend subtreep ext-plist))))
2127 ;; 2. Get parse tree. If NOEXPAND is non-nil, simply
2128 ;; parse current visible part of buffer.
2129 (tree (if noexpand (org-element-parse-buffer nil visible-only)
2130 ;; Otherwise, buffer isn't parsed directly.
2131 ;; Instead, a temporary copy is created, where
2132 ;; include keywords are expanded and code blocks
2133 ;; are evaluated.
2134 (let ((buf (or (buffer-file-name (buffer-base-buffer))
2135 (current-buffer))))
2136 (org-export-with-current-buffer-copy
2137 (org-export-expand-include-keyword)
2138 ;; Setting `org-current-export-file' is
2139 ;; required by Org Babel to properly resolve
2140 ;; noweb references.
2141 (let ((org-current-export-file buf))
2142 (org-export-blocks-preprocess))
2143 (org-element-parse-buffer nil visible-only))))))
2144 ;; 3. Call parse-tree filters to get the final tree.
2145 (setq tree
2146 (org-export-filter-apply-functions
2147 (plist-get info :filter-parse-tree) tree backend info))
2148 ;; 4. Now tree is complete, compute its properties and add
2149 ;; them to communication channel.
2150 (setq info
2151 (org-combine-plists
2152 info
2153 (org-export-collect-tree-properties tree info backend)))
2154 ;; 5. Eventually transcode TREE. Wrap the resulting string
2155 ;; into a template, if required. Eventually call
2156 ;; final-output filter.
2157 (let* ((body (org-element-normalize-string
2158 (org-export-data tree backend info)))
2159 (template (intern (format "org-%s-template" backend)))
2160 (output (org-export-filter-apply-functions
2161 (plist-get info :filter-final-output)
2162 (if (or (not (fboundp template)) body-only) body
2163 (funcall template body info))
2164 backend info)))
2165 ;; Maybe add final OUTPUT to kill ring, then return it.
2166 (when org-export-copy-to-kill-ring (org-kill-new output))
2167 output)))))
2169 (defun org-export-to-buffer
2170 (backend buffer &optional subtreep visible-only body-only ext-plist noexpand)
2171 "Call `org-export-as' with output to a specified buffer.
2173 BACKEND is the back-end used for transcoding, as a symbol.
2175 BUFFER is the output buffer. If it already exists, it will be
2176 erased first, otherwise, it will be created.
2178 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY, EXT-PLIST
2179 and NOEXPAND are similar to those used in `org-export-as', which
2180 see.
2182 Return buffer."
2183 (let ((out (org-export-as
2184 backend subtreep visible-only body-only ext-plist noexpand))
2185 (buffer (get-buffer-create buffer)))
2186 (with-current-buffer buffer
2187 (erase-buffer)
2188 (insert out)
2189 (goto-char (point-min)))
2190 buffer))
2192 (defun org-export-to-file
2193 (backend file &optional subtreep visible-only body-only ext-plist noexpand)
2194 "Call `org-export-as' with output to a specified file.
2196 BACKEND is the back-end used for transcoding, as a symbol. FILE
2197 is the name of the output file, as a string.
2199 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY, EXT-PLIST
2200 and NOEXPAND are similar to those used in `org-export-as', which
2201 see.
2203 Return output file's name."
2204 ;; Checks for FILE permissions. `write-file' would do the same, but
2205 ;; we'd rather avoid needless transcoding of parse tree.
2206 (unless (file-writable-p file) (error "Output file not writable"))
2207 ;; Insert contents to a temporary buffer and write it to FILE.
2208 (let ((out (org-export-as
2209 backend subtreep visible-only body-only ext-plist noexpand)))
2210 (with-temp-buffer
2211 (insert out)
2212 (let ((coding-system-for-write org-export-coding-system))
2213 (write-file file))))
2214 ;; Return full path.
2215 file)
2217 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
2218 "Return output file's name according to buffer specifications.
2220 EXTENSION is a string representing the output file extension,
2221 with the leading dot.
2223 With a non-nil optional argument SUBTREEP, try to determine
2224 output file's name by looking for \"EXPORT_FILE_NAME\" property
2225 of subtree at point.
2227 When optional argument PUB-DIR is set, use it as the publishing
2228 directory.
2230 Return file name as a string, or nil if it couldn't be
2231 determined."
2232 (let ((base-name
2233 ;; File name may come from EXPORT_FILE_NAME subtree property,
2234 ;; assuming point is at beginning of said sub-tree.
2235 (file-name-sans-extension
2236 (or (and subtreep
2237 (org-entry-get
2238 (save-excursion
2239 (ignore-errors
2240 (org-back-to-heading (not visible-only)) (point)))
2241 "EXPORT_FILE_NAME" t))
2242 ;; File name may be extracted from buffer's associated
2243 ;; file, if any.
2244 (buffer-file-name (buffer-base-buffer))
2245 ;; Can't determine file name on our own: Ask user.
2246 (let ((read-file-name-function
2247 (and org-completion-use-ido 'ido-read-file-name)))
2248 (read-file-name
2249 "Output file: " pub-dir nil nil nil
2250 (lambda (name)
2251 (string= (file-name-extension name t) extension))))))))
2252 ;; Build file name. Enforce EXTENSION over whatever user may have
2253 ;; come up with. PUB-DIR, if defined, always has precedence over
2254 ;; any provided path.
2255 (cond
2256 (pub-dir
2257 (concat (file-name-as-directory pub-dir)
2258 (file-name-nondirectory base-name)
2259 extension))
2260 ((string= (file-name-nondirectory base-name) base-name)
2261 (concat (file-name-as-directory ".") base-name extension))
2262 (t (concat base-name extension)))))
2264 (defmacro org-export-with-current-buffer-copy (&rest body)
2265 "Apply BODY in a copy of the current buffer.
2267 The copy preserves local variables and visibility of the original
2268 buffer.
2270 Point is at buffer's beginning when BODY is applied."
2271 (org-with-gensyms (original-buffer offset buffer-string overlays)
2272 `(let ((,original-buffer ,(current-buffer))
2273 (,offset ,(1- (point-min)))
2274 (,buffer-string ,(buffer-string))
2275 (,overlays (mapcar
2276 'copy-overlay (overlays-in (point-min) (point-max)))))
2277 (with-temp-buffer
2278 (let ((buffer-invisibility-spec nil))
2279 (org-clone-local-variables
2280 ,original-buffer
2281 "^\\(org-\\|orgtbl-\\|major-mode$\\|outline-\\(regexp\\|level\\)$\\)")
2282 (insert ,buffer-string)
2283 (mapc (lambda (ov)
2284 (move-overlay
2286 (- (overlay-start ov) ,offset)
2287 (- (overlay-end ov) ,offset)
2288 (current-buffer)))
2289 ,overlays)
2290 (goto-char (point-min))
2291 (progn ,@body))))))
2292 (def-edebug-spec org-export-with-current-buffer-copy (body))
2294 (defun org-export-expand-include-keyword (&optional included dir)
2295 "Expand every include keyword in buffer.
2296 Optional argument INCLUDED is a list of included file names along
2297 with their line restriction, when appropriate. It is used to
2298 avoid infinite recursion. Optional argument DIR is the current
2299 working directory. It is used to properly resolve relative
2300 paths."
2301 (let ((case-fold-search t))
2302 (goto-char (point-min))
2303 (while (re-search-forward "^[ \t]*#\\+INCLUDE: \\(.*\\)" nil t)
2304 (when (eq (org-element-type (save-match-data (org-element-at-point)))
2305 'keyword)
2306 (beginning-of-line)
2307 ;; Extract arguments from keyword's value.
2308 (let* ((value (match-string 1))
2309 (ind (org-get-indentation))
2310 (file (and (string-match "^\"\\(\\S-+\\)\"" value)
2311 (prog1 (expand-file-name (match-string 1 value) dir)
2312 (setq value (replace-match "" nil nil value)))))
2313 (lines
2314 (and (string-match
2315 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\"" value)
2316 (prog1 (match-string 1 value)
2317 (setq value (replace-match "" nil nil value)))))
2318 (env (cond ((string-match "\\<example\\>" value) 'example)
2319 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
2320 (match-string 1 value))))
2321 ;; Minimal level of included file defaults to the child
2322 ;; level of the current headline, if any, or one. It
2323 ;; only applies is the file is meant to be included as
2324 ;; an Org one.
2325 (minlevel
2326 (and (not env)
2327 (if (string-match ":minlevel +\\([0-9]+\\)" value)
2328 (prog1 (string-to-number (match-string 1 value))
2329 (setq value (replace-match "" nil nil value)))
2330 (let ((cur (org-current-level)))
2331 (if cur (1+ (org-reduced-level cur)) 1))))))
2332 ;; Remove keyword.
2333 (delete-region (point) (progn (forward-line) (point)))
2334 (cond
2335 ((not (file-readable-p file)) (error "Cannot include file %s" file))
2336 ;; Check if files has already been parsed. Look after
2337 ;; inclusion lines too, as different parts of the same file
2338 ;; can be included too.
2339 ((member (list file lines) included)
2340 (error "Recursive file inclusion: %s" file))
2342 (cond
2343 ((eq env 'example)
2344 (insert
2345 (let ((ind-str (make-string ind ? ))
2346 (contents
2347 ;; Protect sensitive contents with commas.
2348 (replace-regexp-in-string
2349 "\\(^\\)\\([*]\\|[ \t]*#\\+\\)" ","
2350 (org-export-prepare-file-contents file lines)
2351 nil nil 1)))
2352 (format "%s#+BEGIN_EXAMPLE\n%s%s#+END_EXAMPLE\n"
2353 ind-str contents ind-str))))
2354 ((stringp env)
2355 (insert
2356 (let ((ind-str (make-string ind ? ))
2357 (contents
2358 ;; Protect sensitive contents with commas.
2359 (replace-regexp-in-string
2360 (if (string= env "org") "\\(^\\)\\(.\\)"
2361 "\\(^\\)\\([*]\\|[ \t]*#\\+\\)") ","
2362 (org-export-prepare-file-contents file lines)
2363 nil nil 1)))
2364 (format "%s#+BEGIN_SRC %s\n%s%s#+END_SRC\n"
2365 ind-str env contents ind-str))))
2367 (insert
2368 (with-temp-buffer
2369 (org-mode)
2370 (insert
2371 (org-export-prepare-file-contents file lines ind minlevel))
2372 (org-export-expand-include-keyword
2373 (cons (list file lines) included)
2374 (file-name-directory file))
2375 (buffer-string))))))))))))
2377 (defun org-export-prepare-file-contents (file &optional lines ind minlevel)
2378 "Prepare the contents of FILE for inclusion and return them as a string.
2380 When optional argument LINES is a string specifying a range of
2381 lines, include only those lines.
2383 Optional argument IND, when non-nil, is an integer specifying the
2384 global indentation of returned contents. Since its purpose is to
2385 allow an included file to stay in the same environment it was
2386 created \(i.e. a list item), it doesn't apply past the first
2387 headline encountered.
2389 Optional argument MINLEVEL, when non-nil, is an integer
2390 specifying the level that any top-level headline in the included
2391 file should have."
2392 (with-temp-buffer
2393 (insert-file-contents file)
2394 (when lines
2395 (let* ((lines (split-string lines "-"))
2396 (lbeg (string-to-number (car lines)))
2397 (lend (string-to-number (cadr lines)))
2398 (beg (if (zerop lbeg) (point-min)
2399 (goto-char (point-min))
2400 (forward-line (1- lbeg))
2401 (point)))
2402 (end (if (zerop lend) (point-max)
2403 (goto-char (point-min))
2404 (forward-line (1- lend))
2405 (point))))
2406 (narrow-to-region beg end)))
2407 ;; Remove blank lines at beginning and end of contents. The logic
2408 ;; behind that removal is that blank lines around include keyword
2409 ;; override blank lines in included file.
2410 (goto-char (point-min))
2411 (org-skip-whitespace)
2412 (beginning-of-line)
2413 (delete-region (point-min) (point))
2414 (goto-char (point-max))
2415 (skip-chars-backward " \r\t\n")
2416 (forward-line)
2417 (delete-region (point) (point-max))
2418 ;; If IND is set, preserve indentation of include keyword until
2419 ;; the first headline encountered.
2420 (when ind
2421 (unless (eq major-mode 'org-mode) (org-mode))
2422 (goto-char (point-min))
2423 (let ((ind-str (make-string ind ? )))
2424 (while (not (or (eobp) (looking-at org-outline-regexp-bol)))
2425 ;; Do not move footnote definitions out of column 0.
2426 (unless (and (looking-at org-footnote-definition-re)
2427 (eq (org-element-type (org-element-at-point))
2428 'footnote-definition))
2429 (insert ind-str))
2430 (forward-line))))
2431 ;; When MINLEVEL is specified, compute minimal level for headlines
2432 ;; in the file (CUR-MIN), and remove stars to each headline so
2433 ;; that headlines with minimal level have a level of MINLEVEL.
2434 (when minlevel
2435 (unless (eq major-mode 'org-mode) (org-mode))
2436 (let ((levels (org-map-entries
2437 (lambda () (org-reduced-level (org-current-level))))))
2438 (when levels
2439 (let ((offset (- minlevel (apply 'min levels))))
2440 (unless (zerop offset)
2441 (when org-odd-levels-only (setq offset (* offset 2)))
2442 ;; Only change stars, don't bother moving whole
2443 ;; sections.
2444 (org-map-entries
2445 (lambda () (if (< offset 0) (delete-char (abs offset))
2446 (insert (make-string offset ?*))))))))))
2447 (buffer-string)))
2450 ;;; Tools For Back-Ends
2452 ;; A whole set of tools is available to help build new exporters. Any
2453 ;; function general enough to have its use across many back-ends
2454 ;; should be added here.
2456 ;; As of now, functions operating on footnotes, headlines, links,
2457 ;; macros, references, src-blocks, tables and tables of contents are
2458 ;; implemented.
2460 ;;;; For Export Snippets
2462 ;; Every export snippet is transmitted to the back-end. Though, the
2463 ;; latter will only retain one type of export-snippet, ignoring
2464 ;; others, based on the former's target back-end. The function
2465 ;; `org-export-snippet-backend' returns that back-end for a given
2466 ;; export-snippet.
2468 (defun org-export-snippet-backend (export-snippet)
2469 "Return EXPORT-SNIPPET targeted back-end as a symbol.
2470 Translation, with `org-export-snippet-translation-alist', is
2471 applied."
2472 (let ((back-end (org-element-property :back-end export-snippet)))
2473 (intern
2474 (or (cdr (assoc back-end org-export-snippet-translation-alist))
2475 back-end))))
2478 ;;;; For Footnotes
2480 ;; `org-export-collect-footnote-definitions' is a tool to list
2481 ;; actually used footnotes definitions in the whole parse tree, or in
2482 ;; an headline, in order to add footnote listings throughout the
2483 ;; transcoded data.
2485 ;; `org-export-footnote-first-reference-p' is a predicate used by some
2486 ;; back-ends, when they need to attach the footnote definition only to
2487 ;; the first occurrence of the corresponding label.
2489 ;; `org-export-get-footnote-definition' and
2490 ;; `org-export-get-footnote-number' provide easier access to
2491 ;; additional information relative to a footnote reference.
2493 (defun org-export-collect-footnote-definitions (data info)
2494 "Return an alist between footnote numbers, labels and definitions.
2496 DATA is the parse tree from which definitions are collected.
2497 INFO is the plist used as a communication channel.
2499 Definitions are sorted by order of references. They either
2500 appear as Org data (transcoded with `org-export-data') or as
2501 a secondary string for inlined footnotes (transcoded with
2502 `org-export-secondary-string'). Unreferenced definitions are
2503 ignored."
2504 (let (num-alist
2505 (collect-fn
2506 (function
2507 (lambda (data)
2508 ;; Collect footnote number, label and definition in DATA.
2509 (org-element-map
2510 data 'footnote-reference
2511 (lambda (fn)
2512 (when (org-export-footnote-first-reference-p fn info)
2513 (let ((def (org-export-get-footnote-definition fn info)))
2514 (push
2515 (list (org-export-get-footnote-number fn info)
2516 (org-element-property :label fn)
2517 def)
2518 num-alist)
2519 ;; Also search in definition for nested footnotes.
2520 (when (eq (org-element-property :type fn) 'standard)
2521 (funcall collect-fn def)))))
2522 ;; Don't enter footnote definitions since it will happen
2523 ;; when their first reference is found.
2524 info nil 'footnote-definition)))))
2525 (funcall collect-fn (plist-get info :parse-tree))
2526 (reverse num-alist)))
2528 (defun org-export-footnote-first-reference-p (footnote-reference info)
2529 "Non-nil when a footnote reference is the first one for its label.
2531 FOOTNOTE-REFERENCE is the footnote reference being considered.
2532 INFO is the plist used as a communication channel."
2533 (let ((label (org-element-property :label footnote-reference)))
2534 ;; Anonymous footnotes are always a first reference.
2535 (if (not label) t
2536 ;; Otherwise, return the first footnote with the same LABEL and
2537 ;; test if it is equal to FOOTNOTE-REFERENCE.
2538 (let ((search-refs
2539 (function
2540 (lambda (data)
2541 (org-element-map
2542 data 'footnote-reference
2543 (lambda (fn)
2544 (cond
2545 ((string= (org-element-property :label fn) label)
2546 (throw 'exit fn))
2547 ;; If FN isn't inlined, be sure to traverse its
2548 ;; definition before resuming search. See
2549 ;; comments in `org-export-get-footnote-number'
2550 ;; for more information.
2551 ((eq (org-element-property :type fn) 'standard)
2552 (funcall search-refs
2553 (org-export-get-footnote-definition fn info)))))
2554 ;; Don't enter footnote definitions since it will
2555 ;; happen when their first reference is found.
2556 info 'first-match 'footnote-definition)))))
2557 (equal (catch 'exit (funcall search-refs (plist-get info :parse-tree)))
2558 footnote-reference)))))
2560 (defun org-export-get-footnote-definition (footnote-reference info)
2561 "Return definition of FOOTNOTE-REFERENCE as parsed data.
2562 INFO is the plist used as a communication channel."
2563 (let ((label (org-element-property :label footnote-reference)))
2564 (or (org-element-property :inline-definition footnote-reference)
2565 (cdr (assoc label (plist-get info :footnote-definition-alist))))))
2567 (defun org-export-get-footnote-number (footnote info)
2568 "Return number associated to a footnote.
2570 FOOTNOTE is either a footnote reference or a footnote definition.
2571 INFO is the plist used as a communication channel."
2572 (let ((label (org-element-property :label footnote))
2573 seen-refs
2574 (search-ref
2575 (function
2576 (lambda (data)
2577 ;; Search footnote references through DATA, filling
2578 ;; SEEN-REFS along the way.
2579 (org-element-map
2580 data 'footnote-reference
2581 (lambda (fn)
2582 (let ((fn-lbl (org-element-property :label fn)))
2583 (cond
2584 ;; Anonymous footnote match: return number.
2585 ((and (not fn-lbl) (equal fn footnote))
2586 (throw 'exit (1+ (length seen-refs))))
2587 ;; Labels match: return number.
2588 ((and label (string= label fn-lbl))
2589 (throw 'exit (1+ (length seen-refs))))
2590 ;; Anonymous footnote: it's always a new one. Also,
2591 ;; be sure to return nil from the `cond' so
2592 ;; `first-match' doesn't get us out of the loop.
2593 ((not fn-lbl) (push 'inline seen-refs) nil)
2594 ;; Label not seen so far: add it so SEEN-REFS.
2596 ;; Also search for subsequent references in footnote
2597 ;; definition so numbering following reading logic.
2598 ;; Note that we don't have to care about inline
2599 ;; definitions, since `org-element-map' already
2600 ;; traverse them at the right time.
2602 ;; Once again, return nil to stay in the loop.
2603 ((not (member fn-lbl seen-refs))
2604 (push fn-lbl seen-refs)
2605 (funcall search-ref
2606 (org-export-get-footnote-definition fn info))
2607 nil))))
2608 ;; Don't enter footnote definitions since it will happen
2609 ;; when their first reference is found.
2610 info 'first-match 'footnote-definition)))))
2611 (catch 'exit (funcall search-ref (plist-get info :parse-tree)))))
2614 ;;;; For Headlines
2616 ;; `org-export-get-relative-level' is a shortcut to get headline
2617 ;; level, relatively to the lower headline level in the parsed tree.
2619 ;; `org-export-get-headline-number' returns the section number of an
2620 ;; headline, while `org-export-number-to-roman' allows to convert it
2621 ;; to roman numbers.
2623 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
2624 ;; `org-export-last-sibling-p' are three useful predicates when it
2625 ;; comes to fulfill the `:headline-levels' property.
2627 (defun org-export-get-relative-level (headline info)
2628 "Return HEADLINE relative level within current parsed tree.
2629 INFO is a plist holding contextual information."
2630 (+ (org-element-property :level headline)
2631 (or (plist-get info :headline-offset) 0)))
2633 (defun org-export-low-level-p (headline info)
2634 "Non-nil when HEADLINE is considered as low level.
2636 INFO is a plist used as a communication channel.
2638 A low level headlines has a relative level greater than
2639 `:headline-levels' property value.
2641 Return value is the difference between HEADLINE relative level
2642 and the last level being considered as high enough, or nil."
2643 (let ((limit (plist-get info :headline-levels)))
2644 (when (wholenump limit)
2645 (let ((level (org-export-get-relative-level headline info)))
2646 (and (> level limit) (- level limit))))))
2648 (defun org-export-get-headline-number (headline info)
2649 "Return HEADLINE numbering as a list of numbers.
2650 INFO is a plist holding contextual information."
2651 (cdr (assoc headline (plist-get info :headline-numbering))))
2653 (defun org-export-numbered-headline-p (headline info)
2654 "Return a non-nil value if HEADLINE element should be numbered.
2655 INFO is a plist used as a communication channel."
2656 (let ((sec-num (plist-get info :section-numbers))
2657 (level (org-export-get-relative-level headline info)))
2658 (if (wholenump sec-num) (<= level sec-num) sec-num)))
2660 (defun org-export-number-to-roman (n)
2661 "Convert integer N into a roman numeral."
2662 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
2663 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
2664 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
2665 ( 1 . "I")))
2666 (res ""))
2667 (if (<= n 0)
2668 (number-to-string n)
2669 (while roman
2670 (if (>= n (caar roman))
2671 (setq n (- n (caar roman))
2672 res (concat res (cdar roman)))
2673 (pop roman)))
2674 res)))
2676 (defun org-export-first-sibling-p (headline info)
2677 "Non-nil when HEADLINE is the first sibling in its sub-tree.
2678 INFO is the plist used as a communication channel."
2679 (not (eq (org-element-type (org-export-get-previous-element headline info))
2680 'headline)))
2682 (defun org-export-last-sibling-p (headline info)
2683 "Non-nil when HEADLINE is the last sibling in its sub-tree.
2684 INFO is the plist used as a communication channel."
2685 (not (org-export-get-next-element headline info)))
2688 ;;;; For Links
2690 ;; `org-export-solidify-link-text' turns a string into a safer version
2691 ;; for links, replacing most non-standard characters with hyphens.
2693 ;; `org-export-get-coderef-format' returns an appropriate format
2694 ;; string for coderefs.
2696 ;; `org-export-inline-image-p' returns a non-nil value when the link
2697 ;; provided should be considered as an inline image.
2699 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
2700 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
2701 ;; returns an appropriate unique identifier when found, or nil.
2703 ;; `org-export-resolve-id-link' returns the first headline with
2704 ;; specified id or custom-id in parse tree, or nil when none was
2705 ;; found.
2707 ;; `org-export-resolve-coderef' associates a reference to a line
2708 ;; number in the element it belongs, or returns the reference itself
2709 ;; when the element isn't numbered.
2711 (defun org-export-solidify-link-text (s)
2712 "Take link text S and make a safe target out of it."
2713 (save-match-data
2714 (mapconcat 'identity (org-split-string s "[^a-zA-Z0-9_.-]+") "-")))
2716 (defun org-export-get-coderef-format (path desc)
2717 "Return format string for code reference link.
2718 PATH is the link path. DESC is its description."
2719 (save-match-data
2720 (cond ((string-match (regexp-quote (concat "(" path ")")) desc)
2721 (replace-match "%s" t t desc))
2722 ((string= desc "") "%s")
2723 (t desc))))
2725 (defun org-export-inline-image-p (link &optional rules)
2726 "Non-nil if LINK object points to an inline image.
2728 Optional argument is a set of RULES defining inline images. It
2729 is an alist where associations have the following shape:
2731 \(TYPE . REGEXP)
2733 Applying a rule means apply REGEXP against LINK's path when its
2734 type is TYPE. The function will return a non-nil value if any of
2735 the provided rules is non-nil. The default rule is
2736 `org-export-default-inline-image-rule'.
2738 This only applies to links without a description."
2739 (and (not (org-element-contents link))
2740 (let ((case-fold-search t)
2741 (rules (or rules org-export-default-inline-image-rule)))
2742 (some
2743 (lambda (rule)
2744 (and (string= (org-element-property :type link) (car rule))
2745 (string-match (cdr rule)
2746 (org-element-property :path link))))
2747 rules))))
2749 (defun org-export-resolve-fuzzy-link (link info)
2750 "Return LINK destination.
2752 INFO is a plist holding contextual information.
2754 Return value can be an object, an element, or nil:
2756 - If LINK path matches a target object (i.e. <<path>>) or
2757 element (i.e. \"#+TARGET: path\"), return it.
2759 - If LINK path exactly matches the name affiliated keyword
2760 \(i.e. #+NAME: path) of an element, return that element.
2762 - If LINK path exactly matches any headline name, return that
2763 element. If more than one headline share that name, priority
2764 will be given to the one with the closest common ancestor, if
2765 any, or the first one in the parse tree otherwise.
2767 - Otherwise, return nil.
2769 Assume LINK type is \"fuzzy\"."
2770 (let ((path (org-element-property :path link)))
2771 (cond
2772 ;; First try to find a matching "<<path>>" unless user specified
2773 ;; he was looking for an headline (path starts with a *
2774 ;; character).
2775 ((and (not (eq (substring path 0 1) ?*))
2776 (loop for target in (plist-get info :target-list)
2777 when (string= (org-element-property :value target) path)
2778 return target)))
2779 ;; Then try to find an element with a matching "#+NAME: path"
2780 ;; affiliated keyword.
2781 ((and (not (eq (substring path 0 1) ?*))
2782 (org-element-map
2783 (plist-get info :parse-tree) org-element-all-elements
2784 (lambda (el)
2785 (when (string= (org-element-property :name el) path) el))
2786 info 'first-match)))
2787 ;; Last case: link either points to an headline or to
2788 ;; nothingness. Try to find the source, with priority given to
2789 ;; headlines with the closest common ancestor. If such candidate
2790 ;; is found, return its beginning position as an unique
2791 ;; identifier, otherwise return nil.
2793 (let ((find-headline
2794 (function
2795 ;; Return first headline whose `:raw-value' property
2796 ;; is NAME in parse tree DATA, or nil.
2797 (lambda (name data)
2798 (org-element-map
2799 data 'headline
2800 (lambda (headline)
2801 (when (string=
2802 (org-element-property :raw-value headline)
2803 name)
2804 headline))
2805 info 'first-match)))))
2806 ;; Search among headlines sharing an ancestor with link,
2807 ;; from closest to farthest.
2808 (or (catch 'exit
2809 (mapc
2810 (lambda (parent)
2811 (when (eq (org-element-type parent) 'headline)
2812 (let ((foundp (funcall find-headline path parent)))
2813 (when foundp (throw 'exit foundp)))))
2814 (org-export-get-genealogy link info)) nil)
2815 ;; No match with a common ancestor: try the full parse-tree.
2816 (funcall find-headline path (plist-get info :parse-tree))))))))
2818 (defun org-export-resolve-id-link (link info)
2819 "Return headline referenced as LINK destination.
2821 INFO is a plist used as a communication channel.
2823 Return value can be an headline element or nil. Assume LINK type
2824 is either \"id\" or \"custom-id\"."
2825 (let ((id (org-element-property :path link)))
2826 (org-element-map
2827 (plist-get info :parse-tree) 'headline
2828 (lambda (headline)
2829 (when (or (string= (org-element-property :id headline) id)
2830 (string= (org-element-property :custom-id headline) id))
2831 headline))
2832 info 'first-match)))
2834 (defun org-export-resolve-coderef (ref info)
2835 "Resolve a code reference REF.
2837 INFO is a plist used as a communication channel.
2839 Return associated line number in source code, or REF itself,
2840 depending on src-block or example element's switches."
2841 (org-element-map
2842 (plist-get info :parse-tree) '(example-block src-block)
2843 (lambda (el)
2844 (with-temp-buffer
2845 (insert (org-trim (org-element-property :value el)))
2846 (let* ((label-fmt (regexp-quote
2847 (or (org-element-property :label-fmt el)
2848 org-coderef-label-format)))
2849 (ref-re
2850 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
2851 (replace-regexp-in-string "%s" ref label-fmt nil t))))
2852 ;; Element containing REF is found. Resolve it to either
2853 ;; a label or a line number, as needed.
2854 (when (re-search-backward ref-re nil t)
2855 (cond
2856 ((org-element-property :use-labels el) ref)
2857 ((eq (org-element-property :number-lines el) 'continued)
2858 (+ (org-export-get-loc el info) (line-number-at-pos)))
2859 (t (line-number-at-pos)))))))
2860 info 'first-match))
2863 ;;;; For Macros
2865 ;; `org-export-expand-macro' simply takes care of expanding macros.
2867 (defun org-export-expand-macro (macro info)
2868 "Expand MACRO and return it as a string.
2869 INFO is a plist holding export options."
2870 (let* ((key (org-element-property :key macro))
2871 (args (org-element-property :args macro))
2872 ;; User's macros are stored in the communication channel with
2873 ;; a ":macro-" prefix. If it's a string leave it as-is.
2874 ;; Otherwise, it's a secondary string that needs to be
2875 ;; expanded recursively.
2876 (value
2877 (let ((val (plist-get info (intern (format ":macro-%s" key)))))
2878 (if (stringp val) val
2879 (org-export-secondary-string
2880 val (plist-get info :back-end) info)))))
2881 ;; Replace arguments in VALUE.
2882 (let ((s 0) n)
2883 (while (string-match "\\$\\([0-9]+\\)" value s)
2884 (setq s (1+ (match-beginning 0))
2885 n (string-to-number (match-string 1 value)))
2886 (and (>= (length args) n)
2887 (setq value (replace-match (nth (1- n) args) t t value)))))
2888 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
2889 (when (string-match "\\`(eval\\>" value)
2890 (setq value (eval (read value))))
2891 ;; Return string.
2892 (format "%s" (or value ""))))
2895 ;;;; For References
2897 ;; `org-export-get-ordinal' associates a sequence number to any object
2898 ;; or element.
2900 (defun org-export-get-ordinal (element info &optional types predicate)
2901 "Return ordinal number of an element or object.
2903 ELEMENT is the element or object considered. INFO is the plist
2904 used as a communication channel.
2906 Optional argument TYPES, when non-nil, is a list of element or
2907 object types, as symbols, that should also be counted in.
2908 Otherwise, only provided element's type is considered.
2910 Optional argument PREDICATE is a function returning a non-nil
2911 value if the current element or object should be counted in. It
2912 accepts two arguments: the element or object being considered and
2913 the plist used as a communication channel. This allows to count
2914 only a certain type of objects (i.e. inline images).
2916 Return value is a list of numbers if ELEMENT is an headline or an
2917 item. It is nil for keywords. It represents the footnote number
2918 for footnote definitions and footnote references. If ELEMENT is
2919 a target, return the same value as if ELEMENT was the closest
2920 table, item or headline containing the target. In any other
2921 case, return the sequence number of ELEMENT among elements or
2922 objects of the same type."
2923 ;; A target keyword, representing an invisible target, never has
2924 ;; a sequence number.
2925 (unless (eq (org-element-type element) 'keyword)
2926 ;; Ordinal of a target object refer to the ordinal of the closest
2927 ;; table, item, or headline containing the object.
2928 (when (eq (org-element-type element) 'target)
2929 (setq element
2930 (loop for parent in (org-export-get-genealogy element info)
2931 when
2932 (memq
2933 (org-element-type parent)
2934 '(footnote-definition footnote-reference headline item
2935 table))
2936 return parent)))
2937 (case (org-element-type element)
2938 ;; Special case 1: An headline returns its number as a list.
2939 (headline (org-export-get-headline-number element info))
2940 ;; Special case 2: An item returns its number as a list.
2941 (item (let ((struct (org-element-property :structure element)))
2942 (org-list-get-item-number
2943 (org-element-property :begin element)
2944 struct
2945 (org-list-prevs-alist struct)
2946 (org-list-parents-alist struct))))
2947 ((footnote definition footnote-reference)
2948 (org-export-get-footnote-number element info))
2949 (otherwise
2950 (let ((counter 0))
2951 ;; Increment counter until ELEMENT is found again.
2952 (org-element-map
2953 (plist-get info :parse-tree) (or types (org-element-type element))
2954 (lambda (el)
2955 (cond
2956 ((equal element el) (1+ counter))
2957 ((not predicate) (incf counter) nil)
2958 ((funcall predicate el info) (incf counter) nil)))
2959 info 'first-match))))))
2962 ;;;; For Src-Blocks
2964 ;; `org-export-get-loc' counts number of code lines accumulated in
2965 ;; src-block or example-block elements with a "+n" switch until
2966 ;; a given element, excluded. Note: "-n" switches reset that count.
2968 ;; `org-export-unravel-code' extracts source code (along with a code
2969 ;; references alist) from an `element-block' or `src-block' type
2970 ;; element.
2972 ;; `org-export-format-code' applies a formatting function to each line
2973 ;; of code, providing relative line number and code reference when
2974 ;; appropriate. Since it doesn't access the original element from
2975 ;; which the source code is coming, it expects from the code calling
2976 ;; it to know if lines should be numbered and if code references
2977 ;; should appear.
2979 ;; Eventually, `org-export-format-code-default' is a higher-level
2980 ;; function (it makes use of the two previous functions) which handles
2981 ;; line numbering and code references inclusion, and returns source
2982 ;; code in a format suitable for plain text or verbatim output.
2984 (defun org-export-get-loc (element info)
2985 "Return accumulated lines of code up to ELEMENT.
2987 INFO is the plist used as a communication channel.
2989 ELEMENT is excluded from count."
2990 (let ((loc 0))
2991 (org-element-map
2992 (plist-get info :parse-tree)
2993 `(src-block example-block ,(org-element-type element))
2994 (lambda (el)
2995 (cond
2996 ;; ELEMENT is reached: Quit the loop.
2997 ((equal el element) t)
2998 ;; Only count lines from src-block and example-block elements
2999 ;; with a "+n" or "-n" switch. A "-n" switch resets counter.
3000 ((not (memq (org-element-type el) '(src-block example-block))) nil)
3001 ((let ((linums (org-element-property :number-lines el)))
3002 (when linums
3003 ;; Accumulate locs or reset them.
3004 (let ((lines (org-count-lines
3005 (org-trim (org-element-property :value el)))))
3006 (setq loc (if (eq linums 'new) lines (+ loc lines))))))
3007 ;; Return nil to stay in the loop.
3008 nil)))
3009 info 'first-match)
3010 ;; Return value.
3011 loc))
3013 (defun org-export-unravel-code (element)
3014 "Clean source code and extract references out of it.
3016 ELEMENT has either a `src-block' an `example-block' type.
3018 Return a cons cell whose CAR is the source code, cleaned from any
3019 reference and protective comma and CDR is an alist between
3020 relative line number (integer) and name of code reference on that
3021 line (string)."
3022 (let* ((line 0) refs
3023 ;; Get code and clean it. Remove blank lines at its
3024 ;; beginning and end. Also remove protective commas.
3025 (code (let ((c (replace-regexp-in-string
3026 "\\`\\([ \t]*\n\\)+" ""
3027 (replace-regexp-in-string
3028 "\\(:?[ \t]*\n\\)*[ \t]*\\'" "\n"
3029 (org-element-property :value element)))))
3030 ;; If appropriate, remove global indentation.
3031 (unless (or org-src-preserve-indentation
3032 (org-element-property :preserve-indent element))
3033 (setq c (org-remove-indentation c)))
3034 ;; Free up the protected lines. Note: Org blocks
3035 ;; have commas at the beginning or every line.
3036 (if (string= (org-element-property :language element) "org")
3037 (replace-regexp-in-string "^," "" c)
3038 (replace-regexp-in-string
3039 "^\\(,\\)\\(:?\\*\\|[ \t]*#\\+\\)" "" c nil nil 1))))
3040 ;; Get format used for references.
3041 (label-fmt (regexp-quote
3042 (or (org-element-property :label-fmt element)
3043 org-coderef-label-format)))
3044 ;; Build a regexp matching a loc with a reference.
3045 (with-ref-re
3046 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)[ \t]*\\)$"
3047 (replace-regexp-in-string
3048 "%s" "\\([-a-zA-Z0-9_ ]+\\)" label-fmt nil t))))
3049 ;; Return value.
3050 (cons
3051 ;; Code with references removed.
3052 (org-element-normalize-string
3053 (mapconcat
3054 (lambda (loc)
3055 (incf line)
3056 (if (not (string-match with-ref-re loc)) loc
3057 ;; Ref line: remove ref, and signal its position in REFS.
3058 (push (cons line (match-string 3 loc)) refs)
3059 (replace-match "" nil nil loc 1)))
3060 (org-split-string code "\n") "\n"))
3061 ;; Reference alist.
3062 refs)))
3064 (defun org-export-format-code (code fun &optional num-lines ref-alist)
3065 "Format CODE by applying FUN line-wise and return it.
3067 CODE is a string representing the code to format. FUN is
3068 a function. It must accept three arguments: a line of
3069 code (string), the current line number (integer) or nil and the
3070 reference associated to the current line (string) or nil.
3072 Optional argument NUM-LINES can be an integer representing the
3073 number of code lines accumulated until the current code. Line
3074 numbers passed to FUN will take it into account. If it is nil,
3075 FUN's second argument will always be nil. This number can be
3076 obtained with `org-export-get-loc' function.
3078 Optional argument REF-ALIST can be an alist between relative line
3079 number (i.e. ignoring NUM-LINES) and the name of the code
3080 reference on it. If it is nil, FUN's third argument will always
3081 be nil. It can be obtained through the use of
3082 `org-export-unravel-code' function."
3083 (let ((--locs (org-split-string code "\n"))
3084 (--line 0))
3085 (org-element-normalize-string
3086 (mapconcat
3087 (lambda (--loc)
3088 (incf --line)
3089 (let ((--ref (cdr (assq --line ref-alist))))
3090 (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
3091 --locs "\n"))))
3093 (defun org-export-format-code-default (element info)
3094 "Return source code from ELEMENT, formatted in a standard way.
3096 ELEMENT is either a `src-block' or `example-block' element. INFO
3097 is a plist used as a communication channel.
3099 This function takes care of line numbering and code references
3100 inclusion. Line numbers, when applicable, appear at the
3101 beginning of the line, separated from the code by two white
3102 spaces. Code references, on the other hand, appear flushed to
3103 the right, separated by six white spaces from the widest line of
3104 code."
3105 ;; Extract code and references.
3106 (let* ((code-info (org-export-unravel-code element))
3107 (code (car code-info))
3108 (code-lines (org-split-string code "\n"))
3109 (refs (and (org-element-property :retain-labels element)
3110 (cdr code-info)))
3111 ;; Handle line numbering.
3112 (num-start (case (org-element-property :number-lines element)
3113 (continued (org-export-get-loc element info))
3114 (new 0)))
3115 (num-fmt
3116 (and num-start
3117 (format "%%%ds "
3118 (length (number-to-string
3119 (+ (length code-lines) num-start))))))
3120 ;; Prepare references display, if required. Any reference
3121 ;; should start six columns after the widest line of code,
3122 ;; wrapped with parenthesis.
3123 (max-width
3124 (+ (apply 'max (mapcar 'length code-lines))
3125 (if (not num-start) 0 (length (format num-fmt num-start))))))
3126 (org-export-format-code
3127 code
3128 (lambda (loc line-num ref)
3129 (let ((number-str (and num-fmt (format num-fmt line-num))))
3130 (concat
3131 number-str
3133 (and ref
3134 (concat (make-string
3135 (- (+ 6 max-width)
3136 (+ (length loc) (length number-str))) ? )
3137 (format "(%s)" ref))))))
3138 num-start refs)))
3141 ;;;; For Tables
3143 ;; `org-export-table-format-info' extracts formatting information
3144 ;; (alignment, column groups and presence of a special column) from
3145 ;; a raw table and returns it as a property list.
3147 ;; `org-export-clean-table' cleans the raw table from any Org
3148 ;; table-specific syntax.
3150 (defun org-export-table-format-info (table)
3151 "Extract info from TABLE.
3152 Return a plist whose properties and values are:
3153 `:alignment' vector of strings among \"r\", \"l\" and \"c\",
3154 `:column-groups' vector of symbols among `start', `end', `start-end',
3155 `:row-groups' list of integers representing row groups.
3156 `:special-column-p' non-nil if table has a special column.
3157 `:width' vector of integers representing desired width of
3158 current column, or nil."
3159 (with-temp-buffer
3160 (insert table)
3161 (goto-char 1)
3162 (org-table-align)
3163 (let ((align (vconcat (mapcar (lambda (c) (if c "r" "l"))
3164 org-table-last-alignment)))
3165 (width (make-vector (length org-table-last-alignment) nil))
3166 (colgroups (make-vector (length org-table-last-alignment) nil))
3167 (row-group 0)
3168 (rowgroups)
3169 (special-column-p 'empty))
3170 (mapc (lambda (row)
3171 (if (string-match "^[ \t]*|[-+]+|[ \t]*$" row)
3172 (incf row-group)
3173 ;; Determine if a special column is present by looking
3174 ;; for special markers in the first column. More
3175 ;; accurately, the first column is considered special
3176 ;; if it only contains special markers and, maybe,
3177 ;; empty cells.
3178 (setq special-column-p
3179 (cond
3180 ((not special-column-p) nil)
3181 ((string-match "^[ \t]*| *\\\\?\\([/#!$*_^]\\) *|" row)
3182 'special)
3183 ((string-match "^[ \t]*| +|" row) special-column-p))))
3184 (cond
3185 ;; Read forced alignment and width information, if any,
3186 ;; and determine final alignment for the table.
3187 ((org-table-cookie-line-p row)
3188 (let ((col 0))
3189 (mapc (lambda (field)
3190 (when (string-match
3191 "<\\([lrc]\\)?\\([0-9]+\\)?>" field)
3192 (let ((align-data (match-string 1 field)))
3193 (when align-data (aset align col align-data)))
3194 (let ((w-data (match-string 2 field)))
3195 (when w-data
3196 (aset width col (string-to-number w-data)))))
3197 (incf col))
3198 (org-split-string row "[ \t]*|[ \t]*"))))
3199 ;; Read column groups information.
3200 ((org-table-colgroup-line-p row)
3201 (let ((col 0))
3202 (mapc (lambda (field)
3203 (aset colgroups col
3204 (cond ((string= "<" field) 'start)
3205 ((string= ">" field) 'end)
3206 ((string= "<>" field) 'start-end)))
3207 (incf col))
3208 (org-split-string row "[ \t]*|[ \t]*"))))
3209 ;; Contents line.
3210 (t (push row-group rowgroups))))
3211 (org-split-string table "\n"))
3212 ;; Return plist.
3213 (list :alignment align
3214 :column-groups colgroups
3215 :row-groups (reverse rowgroups)
3216 :special-column-p (eq special-column-p 'special)
3217 :width width))))
3219 (defun org-export-clean-table (table specialp)
3220 "Clean string TABLE from its formatting elements.
3221 Remove any row containing column groups or formatting cookies and
3222 rows starting with a special marker. If SPECIALP is non-nil,
3223 assume the table contains a special formatting column and remove
3224 it also."
3225 (let ((rows (org-split-string table "\n")))
3226 (mapconcat 'identity
3227 (delq nil
3228 (mapcar
3229 (lambda (row)
3230 (cond
3231 ((org-table-colgroup-line-p row) nil)
3232 ((org-table-cookie-line-p row) nil)
3233 ;; Ignore rows starting with a special marker.
3234 ((string-match "^[ \t]*| *[!_^/$] *|" row) nil)
3235 ;; Remove special column.
3236 ((and specialp
3237 (or (string-match "^\\([ \t]*\\)|-+\\+" row)
3238 (string-match "^\\([ \t]*\\)|[^|]*|" row)))
3239 (replace-match "\\1|" t nil row))
3240 (t row)))
3241 rows))
3242 "\n")))
3245 ;;;; For Tables Of Contents
3247 ;; `org-export-collect-headlines' builds a list of all exportable
3248 ;; headline elements, maybe limited to a certain depth. One can then
3249 ;; easily parse it and transcode it.
3251 ;; Building lists of tables, figures or listings is quite similar.
3252 ;; Once the generic function `org-export-collect-elements' is defined,
3253 ;; `org-export-collect-tables', `org-export-collect-figures' and
3254 ;; `org-export-collect-listings' can be derived from it.
3256 (defun org-export-collect-headlines (info &optional n)
3257 "Collect headlines in order to build a table of contents.
3259 INFO is a plist used as a communication channel.
3261 When non-nil, optional argument N must be an integer. It
3262 specifies the depth of the table of contents.
3264 Return a list of all exportable headlines as parsed elements."
3265 (org-element-map
3266 (plist-get info :parse-tree)
3267 'headline
3268 (lambda (headline)
3269 ;; Strip contents from HEADLINE.
3270 (let ((relative-level (org-export-get-relative-level headline info)))
3271 (unless (and n (> relative-level n)) headline)))
3272 info))
3274 (defun org-export-collect-elements (type info &optional predicate)
3275 "Collect referenceable elements of a determined type.
3277 TYPE can be a symbol or a list of symbols specifying element
3278 types to search. Only elements with a caption or a name are
3279 collected.
3281 INFO is a plist used as a communication channel.
3283 When non-nil, optional argument PREDICATE is a function accepting
3284 one argument, an element of type TYPE. It returns a non-nil
3285 value when that element should be collected.
3287 Return a list of all elements found, in order of appearance."
3288 (org-element-map
3289 (plist-get info :parse-tree) type
3290 (lambda (element)
3291 (and (or (org-element-property :caption element)
3292 (org-element-property :name element))
3293 (or (not predicate) (funcall predicate element))
3294 element)) info))
3296 (defun org-export-collect-tables (info)
3297 "Build a list of tables.
3299 INFO is a plist used as a communication channel.
3301 Return a list of table elements with a caption or a name
3302 affiliated keyword."
3303 (org-export-collect-elements 'table info))
3305 (defun org-export-collect-figures (info predicate)
3306 "Build a list of figures.
3308 INFO is a plist used as a communication channel. PREDICATE is
3309 a function which accepts one argument: a paragraph element and
3310 whose return value is non-nil when that element should be
3311 collected.
3313 A figure is a paragraph type element, with a caption or a name,
3314 verifying PREDICATE. The latter has to be provided since
3315 a \"figure\" is a vague concept that may depend on back-end.
3317 Return a list of elements recognized as figures."
3318 (org-export-collect-elements 'paragraph info predicate))
3320 (defun org-export-collect-listings (info)
3321 "Build a list of src blocks.
3323 INFO is a plist used as a communication channel.
3325 Return a list of src-block elements with a caption or a name
3326 affiliated keyword."
3327 (org-export-collect-elements 'src-block info))
3330 ;;;; Topology
3332 ;; Here are various functions to retrieve information about the
3333 ;; neighbourhood of a given element or object. Neighbours of interest
3334 ;; are direct parent (`org-export-get-parent'), parent headline
3335 ;; (`org-export-get-parent-headline'), parent paragraph
3336 ;; (`org-export-get-parent-paragraph'), previous element or object
3337 ;; (`org-export-get-previous-element') and next element or object
3338 ;; (`org-export-get-next-element').
3340 ;; All of these functions are just a specific use of the more generic
3341 ;; `org-export-get-genealogy', which returns the genealogy relative to
3342 ;; the element or object.
3344 (defun org-export-get-genealogy (blob info)
3345 "Return genealogy relative to a given element or object.
3346 BLOB is the element or object being considered. INFO is a plist
3347 used as a communication channel."
3348 (let* ((type (org-element-type blob))
3349 (end (org-element-property :end blob))
3350 (walk-data
3351 (lambda (data genealogy)
3352 ;; Walk DATA, looking for BLOB. GENEALOGY is the list of
3353 ;; parents of all elements in DATA.
3354 (mapc
3355 (lambda (el)
3356 (cond
3357 ((stringp el) nil)
3358 ((equal el blob) (throw 'exit genealogy))
3359 ((>= (org-element-property :end el) end)
3360 ;; If BLOB is an object and EL contains a secondary
3361 ;; string, be sure to check it.
3362 (when (memq type org-element-all-objects)
3363 (let ((sec-prop
3364 (cdr (assq (org-element-type el)
3365 org-element-secondary-value-alist))))
3366 (when sec-prop
3367 (funcall
3368 walk-data
3369 (cons 'org-data
3370 (cons nil (org-element-property sec-prop el)))
3371 (cons el genealogy)))))
3372 (funcall walk-data el (cons el genealogy)))))
3373 (org-element-contents data)))))
3374 (catch 'exit (funcall walk-data (plist-get info :parse-tree) nil) nil)))
3376 (defun org-export-get-parent (blob info)
3377 "Return BLOB parent or nil.
3378 BLOB is the element or object considered. INFO is a plist used
3379 as a communication channel."
3380 (car (org-export-get-genealogy blob info)))
3382 (defun org-export-get-parent-headline (blob info)
3383 "Return closest parent headline or nil.
3385 BLOB is the element or object being considered. INFO is a plist
3386 used as a communication channel."
3387 (catch 'exit
3388 (mapc
3389 (lambda (el) (when (eq (org-element-type el) 'headline) (throw 'exit el)))
3390 (org-export-get-genealogy blob info))
3391 nil))
3393 (defun org-export-get-parent-paragraph (object info)
3394 "Return parent paragraph or nil.
3396 INFO is a plist used as a communication channel.
3398 Optional argument OBJECT, when provided, is the object to consider.
3399 Otherwise, return the paragraph containing current object.
3401 This is useful for objects, which share attributes with the
3402 paragraph containing them."
3403 (catch 'exit
3404 (mapc
3405 (lambda (el) (when (eq (org-element-type el) 'paragraph) (throw 'exit el)))
3406 (org-export-get-genealogy object info))
3407 nil))
3409 (defun org-export-get-previous-element (blob info)
3410 "Return previous element or object.
3412 BLOB is an element or object. INFO is a plist used as
3413 a communication channel.
3415 Return previous element or object, a string, or nil."
3416 (let ((parent (org-export-get-parent blob info)))
3417 (cadr (member blob (reverse (org-element-contents parent))))))
3419 (defun org-export-get-next-element (blob info)
3420 "Return next element or object.
3422 BLOB is an element or object. INFO is a plist used as
3423 a communication channel.
3425 Return next element or object, a string, or nil."
3426 (let ((parent (org-export-get-parent blob info)))
3427 (cadr (member blob (org-element-contents parent)))))
3431 ;;; The Dispatcher
3433 ;; `org-export-dispatch' is the standard interactive way to start an
3434 ;; export process. It uses `org-export-dispatch-ui' as a subroutine
3435 ;; for its interface. Most commons back-ends should have an entry in
3436 ;; it.
3438 (defun org-export-dispatch ()
3439 "Export dispatcher for Org mode.
3441 It provides an access to common export related tasks in a buffer.
3442 Its interface comes in two flavours: standard and expert. While
3443 both share the same set of bindings, only the former displays the
3444 valid keys associations. Set `org-export-dispatch-use-expert-ui'
3445 to switch to one or the other.
3447 Return an error if key pressed has no associated command."
3448 (interactive)
3449 (let* ((input (org-export-dispatch-ui
3450 (if (listp org-export-initial-scope) org-export-initial-scope
3451 (list org-export-initial-scope))
3452 org-export-dispatch-use-expert-ui))
3453 (raw-key (car input))
3454 (optns (cdr input)))
3455 ;; Translate "C-a", "C-b"... into "a", "b"... Then take action
3456 ;; depending on user's key pressed.
3457 (case (if (< raw-key 27) (+ raw-key 96) raw-key)
3458 ;; Allow to quit with "q" key.
3459 (?q nil)
3460 ;; Export with `e-ascii' back-end.
3461 ((?A ?N ?U)
3462 (let ((outbuf
3463 (org-export-to-buffer
3464 'e-ascii "*Org E-ASCII Export*"
3465 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)
3466 `(:ascii-charset
3467 ,(case raw-key (?A 'ascii) (?N 'latin1) (t 'utf-8))))))
3468 (with-current-buffer outbuf (text-mode))
3469 (when org-export-show-temporary-export-buffer
3470 (switch-to-buffer-other-window outbuf))))
3471 ((?a ?n ?u)
3472 (org-e-ascii-export-to-ascii
3473 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)
3474 `(:ascii-charset ,(case raw-key (?a 'ascii) (?n 'latin1) (t 'utf-8)))))
3475 ;; Export with `e-latex' back-end.
3477 (let ((outbuf
3478 (org-export-to-buffer
3479 'e-latex "*Org E-LaTeX Export*"
3480 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
3481 (with-current-buffer outbuf (latex-mode))
3482 (when org-export-show-temporary-export-buffer
3483 (switch-to-buffer-other-window outbuf))))
3484 (?l (org-e-latex-export-to-latex
3485 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)))
3486 (?p (org-e-latex-export-to-pdf
3487 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)))
3488 (?d (org-open-file
3489 (org-e-latex-export-to-pdf
3490 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
3491 ;; Export with `e-html' back-end.
3493 (let ((outbuf
3494 (org-export-to-buffer
3495 'e-html "*Org E-HTML Export*"
3496 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
3497 ;; set major mode
3498 (with-current-buffer outbuf
3499 (if (featurep 'nxhtml-mode) (nxhtml-mode) (nxml-mode)))
3500 (when org-export-show-temporary-export-buffer
3501 (switch-to-buffer-other-window outbuf))))
3502 (?h (org-e-html-export-to-html
3503 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)))
3504 (?b (org-open-file
3505 (org-e-html-export-to-html
3506 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
3507 ;; Export with `e-odt' back-end.
3508 (?o (org-e-odt-export-to-odt
3509 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)))
3510 (?O (org-open-file
3511 (org-e-odt-export-to-odt
3512 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
3513 ;; Publishing facilities
3514 (?F (org-e-publish-current-file (memq 'force optns)))
3515 (?P (org-e-publish-current-project (memq 'force optns)))
3516 (?X (let ((project
3517 (assoc (org-icompleting-read
3518 "Publish project: " org-e-publish-project-alist nil t)
3519 org-e-publish-project-alist)))
3520 (org-e-publish project (memq 'force optns))))
3521 (?E (org-e-publish-all (memq 'force optns)))
3522 ;; Undefined command.
3523 (t (error "No command associated with key %s"
3524 (char-to-string raw-key))))))
3526 (defun org-export-dispatch-ui (options expertp)
3527 "Handle interface for `org-export-dispatch'.
3529 OPTIONS is a list containing current interactive options set for
3530 export. It can contain any of the following symbols:
3531 `body' toggles a body-only export
3532 `subtree' restricts export to current subtree
3533 `visible' restricts export to visible part of buffer.
3534 `force' force publishing files.
3536 EXPERTP, when non-nil, triggers expert UI. In that case, no help
3537 buffer is provided, but indications about currently active
3538 options are given in the prompt. Moreover, \[?] allows to switch
3539 back to standard interface.
3541 Return value is a list with key pressed as CAR and a list of
3542 final interactive export options as CDR."
3543 (let ((help
3544 (format "---- (Options) -------------------------------------------
3546 \[1] Body only: %s [2] Export scope: %s
3547 \[3] Visible only: %s [4] Force publishing: %s
3550 --- (ASCII/Latin-1/UTF-8 Export) -------------------------
3552 \[a/n/u] to TXT file [A/N/U] to temporary buffer
3554 --- (HTML Export) ----------------------------------------
3556 \[h] to HTML file [b] ... and open it
3557 \[H] to temporary buffer
3559 --- (LaTeX Export) ---------------------------------------
3561 \[l] to TEX file [L] to temporary buffer
3562 \[p] to PDF file [d] ... and open it
3564 --- (ODF Export) -----------------------------------------
3566 \[o] to ODT file [O] ... and open it
3568 --- (Publish) --------------------------------------------
3570 \[F] current file [P] current project
3571 \[X] a project [E] every project"
3572 (if (memq 'body options) "On " "Off")
3573 (if (memq 'subtree options) "Subtree" "Buffer ")
3574 (if (memq 'visible options) "On " "Off")
3575 (if (memq 'force options) "On " "Off")))
3576 (standard-prompt "Export command: ")
3577 (expert-prompt (format "Export command (%s%s%s%s): "
3578 (if (memq 'body options) "b" "-")
3579 (if (memq 'subtree options) "s" "-")
3580 (if (memq 'visible options) "v" "-")
3581 (if (memq 'force options) "f" "-")))
3582 (handle-keypress
3583 (function
3584 ;; Read a character from command input, toggling interactive
3585 ;; options when applicable. PROMPT is the displayed prompt,
3586 ;; as a string.
3587 (lambda (prompt)
3588 (let ((key (read-char-exclusive prompt)))
3589 (cond
3590 ;; Ignore non-standard characters (i.e. "M-a").
3591 ((not (characterp key)) (org-export-dispatch-ui options expertp))
3592 ;; Help key: Switch back to standard interface if
3593 ;; expert UI was active.
3594 ((eq key ??) (org-export-dispatch-ui options nil))
3595 ;; Toggle export options.
3596 ((memq key '(?1 ?2 ?3 ?4))
3597 (org-export-dispatch-ui
3598 (let ((option (case key (?1 'body) (?2 'subtree) (?3 'visible)
3599 (?4 'force))))
3600 (if (memq option options) (remq option options)
3601 (cons option options)))
3602 expertp))
3603 ;; Action selected: Send key and options back to
3604 ;; `org-export-dispatch'.
3605 (t (cons key options))))))))
3606 ;; With expert UI, just read key with a fancy prompt. In standard
3607 ;; UI, display an intrusive help buffer.
3608 (if expertp (funcall handle-keypress expert-prompt)
3609 (save-window-excursion
3610 (delete-other-windows)
3611 (with-output-to-temp-buffer "*Org Export/Publishing Help*" (princ help))
3612 (org-fit-window-to-buffer
3613 (get-buffer-window "*Org Export/Publishing Help*"))
3614 (funcall handle-keypress standard-prompt)))))
3617 (provide 'org-export)
3618 ;;; org-export.el ends here