00a5ef58a068c1761f7f045fdce9e4ab60d6b7bf
[org-mode.git] / contrib / lisp / org-export.el
blob00a5ef58a068c1761f7f045fdce9e4ab60d6b7bf
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. See "The Filter System"
45 ;; section for more information.
47 ;; The core function is `org-export-as'. It returns the transcoded
48 ;; buffer as a string.
50 ;; An export back-end is defined with `org-export-define-backend',
51 ;; which defines one mandatory information: his translation table.
52 ;; Its value is an alist whose keys are elements and objects types and
53 ;; values translator functions. See function's docstring for more
54 ;; information about translators.
56 ;; Optionally, `org-export-define-backend' can also support specific
57 ;; buffer keywords, OPTION keyword's items and filters. Also refer to
58 ;; function documentation for more information.
60 ;; If the new back-end shares most properties with another one,
61 ;; `org-export-define-derived-backend' can be used to simplify the
62 ;; process.
64 ;; Any back-end can define its own variables. Among them, those
65 ;; customizable should belong to the `org-export-BACKEND' group.
67 ;; Tools for common tasks across back-ends are implemented in the
68 ;; penultimate part of this file. A dispatcher for standard back-ends
69 ;; is provided in the last one.
71 ;;; Code:
73 (eval-when-compile (require 'cl))
74 (require 'org-element)
75 (require 'ob-exp)
77 (declare-function org-e-publish "org-e-publish" (project &optional force))
78 (declare-function org-e-publish-all "org-e-publish" (&optional force))
79 (declare-function org-e-publish-current-file "org-e-publish" (&optional force))
80 (declare-function org-e-publish-current-project "org-e-publish"
81 (&optional force))
83 (defvar org-e-publish-project-alist)
84 (defvar org-table-number-fraction)
85 (defvar org-table-number-regexp)
89 ;;; Internal Variables
91 ;; Among internal variables, the most important is
92 ;; `org-export-options-alist'. This variable define the global export
93 ;; options, shared between every exporter, and how they are acquired.
95 (defconst org-export-max-depth 19
96 "Maximum nesting depth for headlines, counting from 0.")
98 (defconst org-export-options-alist
99 '((:author "AUTHOR" nil user-full-name t)
100 (:creator "CREATOR" nil org-export-creator-string)
101 (:date "DATE" nil nil t)
102 (:description "DESCRIPTION" nil nil newline)
103 (:email "EMAIL" nil user-mail-address t)
104 (:exclude-tags "EXCLUDE_TAGS" nil org-export-exclude-tags split)
105 (:headline-levels nil "H" org-export-headline-levels)
106 (:keywords "KEYWORDS" nil nil space)
107 (:language "LANGUAGE" nil org-export-default-language t)
108 (:preserve-breaks nil "\\n" org-export-preserve-breaks)
109 (:section-numbers nil "num" org-export-with-section-numbers)
110 (:select-tags "SELECT_TAGS" nil org-export-select-tags split)
111 (:time-stamp-file nil "timestamp" org-export-time-stamp-file)
112 (:title "TITLE" nil nil space)
113 (:with-archived-trees nil "arch" org-export-with-archived-trees)
114 (:with-author nil "author" org-export-with-author)
115 (:with-clocks nil "c" org-export-with-clocks)
116 (:with-creator nil "creator" org-export-with-creator)
117 (:with-date nil "date" org-export-with-date)
118 (:with-drawers nil "d" org-export-with-drawers)
119 (:with-email nil "email" org-export-with-email)
120 (:with-emphasize nil "*" org-export-with-emphasize)
121 (:with-entities nil "e" org-export-with-entities)
122 (:with-fixed-width nil ":" org-export-with-fixed-width)
123 (:with-footnotes nil "f" org-export-with-footnotes)
124 (:with-inlinetasks nil "inline" org-export-with-inlinetasks)
125 (:with-plannings nil "p" org-export-with-planning)
126 (:with-priority nil "pri" org-export-with-priority)
127 (:with-smart-quotes nil "'" org-export-with-smart-quotes)
128 (:with-special-strings nil "-" org-export-with-special-strings)
129 (:with-statistics-cookies nil "stat" org-export-with-statistics-cookies)
130 (:with-sub-superscript nil "^" org-export-with-sub-superscripts)
131 (:with-toc nil "toc" org-export-with-toc)
132 (:with-tables nil "|" org-export-with-tables)
133 (:with-tags nil "tags" org-export-with-tags)
134 (:with-tasks nil "tasks" org-export-with-tasks)
135 (:with-timestamps nil "<" org-export-with-timestamps)
136 (:with-todo-keywords nil "todo" org-export-with-todo-keywords))
137 "Alist between export properties and ways to set them.
139 The CAR of the alist is the property name, and the CDR is a list
140 like (KEYWORD OPTION DEFAULT BEHAVIOUR) where:
142 KEYWORD is a string representing a buffer keyword, or nil. Each
143 property defined this way can also be set, during subtree
144 export, through an headline property named after the keyword
145 with the \"EXPORT_\" prefix (i.e. DATE keyword and EXPORT_DATE
146 property).
147 OPTION is a string that could be found in an #+OPTIONS: line.
148 DEFAULT is the default value for the property.
149 BEHAVIOUR determine how Org should handle multiple keywords for
150 the same property. It is a symbol among:
151 nil Keep old value and discard the new one.
152 t Replace old value with the new one.
153 `space' Concatenate the values, separating them with a space.
154 `newline' Concatenate the values, separating them with
155 a newline.
156 `split' Split values at white spaces, and cons them to the
157 previous list.
159 KEYWORD and OPTION have precedence over DEFAULT.
161 All these properties should be back-end agnostic. Back-end
162 specific properties are set through `org-export-define-backend'.
163 Properties redefined there have precedence over these.")
165 (defconst org-export-special-keywords '("FILETAGS" "SETUP_FILE" "OPTIONS")
166 "List of in-buffer keywords that require special treatment.
167 These keywords are not directly associated to a property. The
168 way they are handled must be hard-coded into
169 `org-export--get-inbuffer-options' function.")
171 (defconst org-export-filters-alist
172 '((:filter-bold . org-export-filter-bold-functions)
173 (:filter-babel-call . org-export-filter-babel-call-functions)
174 (:filter-center-block . org-export-filter-center-block-functions)
175 (:filter-clock . org-export-filter-clock-functions)
176 (:filter-code . org-export-filter-code-functions)
177 (:filter-comment . org-export-filter-comment-functions)
178 (:filter-comment-block . org-export-filter-comment-block-functions)
179 (:filter-diary-sexp . org-export-filter-diary-sexp-functions)
180 (:filter-drawer . org-export-filter-drawer-functions)
181 (:filter-dynamic-block . org-export-filter-dynamic-block-functions)
182 (:filter-entity . org-export-filter-entity-functions)
183 (:filter-example-block . org-export-filter-example-block-functions)
184 (:filter-export-block . org-export-filter-export-block-functions)
185 (:filter-export-snippet . org-export-filter-export-snippet-functions)
186 (:filter-final-output . org-export-filter-final-output-functions)
187 (:filter-fixed-width . org-export-filter-fixed-width-functions)
188 (:filter-footnote-definition . org-export-filter-footnote-definition-functions)
189 (:filter-footnote-reference . org-export-filter-footnote-reference-functions)
190 (:filter-headline . org-export-filter-headline-functions)
191 (:filter-horizontal-rule . org-export-filter-horizontal-rule-functions)
192 (:filter-inline-babel-call . org-export-filter-inline-babel-call-functions)
193 (:filter-inline-src-block . org-export-filter-inline-src-block-functions)
194 (:filter-inlinetask . org-export-filter-inlinetask-functions)
195 (:filter-italic . org-export-filter-italic-functions)
196 (:filter-item . org-export-filter-item-functions)
197 (:filter-keyword . org-export-filter-keyword-functions)
198 (:filter-latex-environment . org-export-filter-latex-environment-functions)
199 (:filter-latex-fragment . org-export-filter-latex-fragment-functions)
200 (:filter-line-break . org-export-filter-line-break-functions)
201 (:filter-link . org-export-filter-link-functions)
202 (:filter-macro . org-export-filter-macro-functions)
203 (:filter-node-property . org-export-filter-node-property-functions)
204 (:filter-paragraph . org-export-filter-paragraph-functions)
205 (:filter-parse-tree . org-export-filter-parse-tree-functions)
206 (:filter-plain-list . org-export-filter-plain-list-functions)
207 (:filter-plain-text . org-export-filter-plain-text-functions)
208 (:filter-planning . org-export-filter-planning-functions)
209 (:filter-property-drawer . org-export-filter-property-drawer-functions)
210 (:filter-quote-block . org-export-filter-quote-block-functions)
211 (:filter-quote-section . org-export-filter-quote-section-functions)
212 (:filter-radio-target . org-export-filter-radio-target-functions)
213 (:filter-section . org-export-filter-section-functions)
214 (:filter-special-block . org-export-filter-special-block-functions)
215 (:filter-src-block . org-export-filter-src-block-functions)
216 (:filter-statistics-cookie . org-export-filter-statistics-cookie-functions)
217 (:filter-strike-through . org-export-filter-strike-through-functions)
218 (:filter-subscript . org-export-filter-subscript-functions)
219 (:filter-superscript . org-export-filter-superscript-functions)
220 (:filter-table . org-export-filter-table-functions)
221 (:filter-table-cell . org-export-filter-table-cell-functions)
222 (:filter-table-row . org-export-filter-table-row-functions)
223 (:filter-target . org-export-filter-target-functions)
224 (:filter-timestamp . org-export-filter-timestamp-functions)
225 (:filter-underline . org-export-filter-underline-functions)
226 (:filter-verbatim . org-export-filter-verbatim-functions)
227 (:filter-verse-block . org-export-filter-verse-block-functions))
228 "Alist between filters properties and initial values.
230 The key of each association is a property name accessible through
231 the communication channel. Its value is a configurable global
232 variable defining initial filters.
234 This list is meant to install user specified filters. Back-end
235 developers may install their own filters using
236 `org-export-define-backend'. Filters defined there will always
237 be prepended to the current list, so they always get applied
238 first.")
240 (defconst org-export-default-inline-image-rule
241 `(("file" .
242 ,(format "\\.%s\\'"
243 (regexp-opt
244 '("png" "jpeg" "jpg" "gif" "tiff" "tif" "xbm"
245 "xpm" "pbm" "pgm" "ppm") t))))
246 "Default rule for link matching an inline image.
247 This rule applies to links with no description. By default, it
248 will be considered as an inline image if it targets a local file
249 whose extension is either \"png\", \"jpeg\", \"jpg\", \"gif\",
250 \"tiff\", \"tif\", \"xbm\", \"xpm\", \"pbm\", \"pgm\" or \"ppm\".
251 See `org-export-inline-image-p' for more information about
252 rules.")
254 (defvar org-export-registered-backends nil
255 "List of backends currently available in the exporter.
257 A backend is stored as a list where CAR is its name, as a symbol,
258 and CDR is a plist with the following properties:
259 `:filters-alist', `:menu-entry', `:options-alist' and
260 `:translate-alist'.
262 This variable is set with `org-export-define-backend' and
263 `org-export-define-derived-backend' functions.")
265 (defvar org-export-dispatch-last-action nil
266 "Last command called from the dispatcher.
267 The value should be a list. Its CAR is the action, as a symbol,
268 and its CDR is a list of export options.")
272 ;;; User-configurable Variables
274 ;; Configuration for the masses.
276 ;; They should never be accessed directly, as their value is to be
277 ;; stored in a property list (cf. `org-export-options-alist').
278 ;; Back-ends will read their value from there instead.
280 (defgroup org-export nil
281 "Options for exporting Org mode files."
282 :tag "Org Export"
283 :group 'org)
285 (defgroup org-export-general nil
286 "General options for export engine."
287 :tag "Org Export General"
288 :group 'org-export)
290 (defcustom org-export-with-archived-trees 'headline
291 "Whether sub-trees with the ARCHIVE tag should be exported.
293 This can have three different values:
294 nil Do not export, pretend this tree is not present.
295 t Do export the entire tree.
296 `headline' Only export the headline, but skip the tree below it.
298 This option can also be set with the #+OPTIONS line,
299 e.g. \"arch:nil\"."
300 :group 'org-export-general
301 :type '(choice
302 (const :tag "Not at all" nil)
303 (const :tag "Headline only" 'headline)
304 (const :tag "Entirely" t)))
306 (defcustom org-export-with-author t
307 "Non-nil means insert author name into the exported file.
308 This option can also be set with the #+OPTIONS line,
309 e.g. \"author:nil\"."
310 :group 'org-export-general
311 :type 'boolean)
313 (defcustom org-export-with-clocks nil
314 "Non-nil means export CLOCK keywords.
315 This option can also be set with the #+OPTIONS line,
316 e.g. \"c:t\"."
317 :group 'org-export-general
318 :type 'boolean)
320 (defcustom org-export-with-creator 'comment
321 "Non-nil means the postamble should contain a creator sentence.
323 The sentence can be set in `org-export-creator-string' and
324 defaults to \"Generated by Org mode XX in Emacs XXX.\".
326 If the value is `comment' insert it as a comment."
327 :group 'org-export-general
328 :type '(choice
329 (const :tag "No creator sentence" nil)
330 (const :tag "Sentence as a comment" 'comment)
331 (const :tag "Insert the sentence" t)))
333 (defcustom org-export-with-date t
334 "Non-nil means insert date in the exported document.
335 This options can also be set with the OPTIONS keyword,
336 e.g. \"date:nil\".")
338 (defcustom org-export-creator-string
339 (format "Generated by Org mode %s in Emacs %s."
340 (if (fboundp 'org-version) (org-version) "(Unknown)")
341 emacs-version)
342 "String to insert at the end of the generated document."
343 :group 'org-export-general
344 :type '(string :tag "Creator string"))
346 (defcustom org-export-with-drawers t
347 "Non-nil means export contents of standard drawers.
349 When t, all drawers are exported. This may also be a list of
350 drawer names to export. This variable doesn't apply to
351 properties drawers.
353 This option can also be set with the #+OPTIONS line,
354 e.g. \"d:nil\"."
355 :group 'org-export-general
356 :type '(choice
357 (const :tag "All drawers" t)
358 (const :tag "None" nil)
359 (repeat :tag "Selected drawers"
360 (string :tag "Drawer name"))))
362 (defcustom org-export-with-email nil
363 "Non-nil means insert author email into the exported file.
364 This option can also be set with the #+OPTIONS line,
365 e.g. \"email:t\"."
366 :group 'org-export-general
367 :type 'boolean)
369 (defcustom org-export-with-emphasize t
370 "Non-nil means interpret *word*, /word/, _word_ and +word+.
372 If the export target supports emphasizing text, the word will be
373 typeset in bold, italic, with an underline or strike-through,
374 respectively.
376 This option can also be set with the #+OPTIONS line, e.g. \"*:nil\"."
377 :group 'org-export-general
378 :type 'boolean)
380 (defcustom org-export-exclude-tags '("noexport")
381 "Tags that exclude a tree from export.
383 All trees carrying any of these tags will be excluded from
384 export. This is without condition, so even subtrees inside that
385 carry one of the `org-export-select-tags' will be removed.
387 This option can also be set with the #+EXCLUDE_TAGS: keyword."
388 :group 'org-export-general
389 :type '(repeat (string :tag "Tag")))
391 (defcustom org-export-with-fixed-width t
392 "Non-nil means lines starting with \":\" will be in fixed width font.
394 This can be used to have pre-formatted text, fragments of code
395 etc. For example:
396 : ;; Some Lisp examples
397 : (while (defc cnt)
398 : (ding))
399 will be looking just like this in also HTML. See also the QUOTE
400 keyword. Not all export backends support this.
402 This option can also be set with the #+OPTIONS line, e.g. \"::nil\"."
403 :group 'org-export-translation
404 :type 'boolean)
406 (defcustom org-export-with-footnotes t
407 "Non-nil means Org footnotes should be exported.
408 This option can also be set with the #+OPTIONS line,
409 e.g. \"f:nil\"."
410 :group 'org-export-general
411 :type 'boolean)
413 (defcustom org-export-headline-levels 3
414 "The last level which is still exported as a headline.
416 Inferior levels will produce itemize lists when exported.
418 This option can also be set with the #+OPTIONS line, e.g. \"H:2\"."
419 :group 'org-export-general
420 :type 'integer)
422 (defcustom org-export-default-language "en"
423 "The default language for export and clocktable translations, as a string.
424 This may have an association in
425 `org-clock-clocktable-language-setup'."
426 :group 'org-export-general
427 :type '(string :tag "Language"))
429 (defcustom org-export-preserve-breaks nil
430 "Non-nil means preserve all line breaks when exporting.
432 Normally, in HTML output paragraphs will be reformatted.
434 This option can also be set with the #+OPTIONS line,
435 e.g. \"\\n:t\"."
436 :group 'org-export-general
437 :type 'boolean)
439 (defcustom org-export-with-entities t
440 "Non-nil means interpret entities when exporting.
442 For example, HTML export converts \\alpha to &alpha; and \\AA to
443 &Aring;.
445 For a list of supported names, see the constant `org-entities'
446 and the user option `org-entities-user'.
448 This option can also be set with the #+OPTIONS line,
449 e.g. \"e:nil\"."
450 :group 'org-export-general
451 :type 'boolean)
453 (defcustom org-export-with-inlinetasks t
454 "Non-nil means inlinetasks should be exported.
455 This option can also be set with the #+OPTIONS line,
456 e.g. \"inline:nil\"."
457 :group 'org-export-general
458 :type 'boolean)
460 (defcustom org-export-with-planning nil
461 "Non-nil means include planning info in export.
462 This option can also be set with the #+OPTIONS: line,
463 e.g. \"p:t\"."
464 :group 'org-export-general
465 :type 'boolean)
467 (defcustom org-export-with-priority nil
468 "Non-nil means include priority cookies in export.
469 This option can also be set with the #+OPTIONS line,
470 e.g. \"pri:t\"."
471 :group 'org-export-general
472 :type 'boolean)
474 (defcustom org-export-with-section-numbers t
475 "Non-nil means add section numbers to headlines when exporting.
477 When set to an integer n, numbering will only happen for
478 headlines whose relative level is higher or equal to n.
480 This option can also be set with the #+OPTIONS line,
481 e.g. \"num:t\"."
482 :group 'org-export-general
483 :type 'boolean)
485 (defcustom org-export-select-tags '("export")
486 "Tags that select a tree for export.
488 If any such tag is found in a buffer, all trees that do not carry
489 one of these tags will be ignored during export. Inside trees
490 that are selected like this, you can still deselect a subtree by
491 tagging it with one of the `org-export-exclude-tags'.
493 This option can also be set with the #+SELECT_TAGS: keyword."
494 :group 'org-export-general
495 :type '(repeat (string :tag "Tag")))
497 (defcustom org-export-with-smart-quotes nil
498 "Non-nil means activate smart quotes during export.
499 This option can also be set with the #+OPTIONS: line,
500 e.g. \"':t\"."
501 :group 'org-export-general
502 :type 'boolean)
504 (defcustom org-export-with-special-strings t
505 "Non-nil means interpret \"\\-\", \"--\" and \"---\" for export.
507 When this option is turned on, these strings will be exported as:
509 Org HTML LaTeX UTF-8
510 -----+----------+--------+-------
511 \\- &shy; \\-
512 -- &ndash; -- –
513 --- &mdash; --- —
514 ... &hellip; \\ldots …
516 This option can also be set with the #+OPTIONS line,
517 e.g. \"-:nil\"."
518 :group 'org-export-general
519 :type 'boolean)
521 (defcustom org-export-with-statistics-cookies t
522 "Non-nil means include statistics cookies in export.
523 This option can also be set with the #+OPTIONS: line,
524 e.g. \"stat:nil\""
525 :group 'org-export-general
526 :type 'boolean)
528 (defcustom org-export-with-sub-superscripts t
529 "Non-nil means interpret \"_\" and \"^\" for export.
531 When this option is turned on, you can use TeX-like syntax for
532 sub- and superscripts. Several characters after \"_\" or \"^\"
533 will be considered as a single item - so grouping with {} is
534 normally not needed. For example, the following things will be
535 parsed as single sub- or superscripts.
537 10^24 or 10^tau several digits will be considered 1 item.
538 10^-12 or 10^-tau a leading sign with digits or a word
539 x^2-y^3 will be read as x^2 - y^3, because items are
540 terminated by almost any nonword/nondigit char.
541 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
543 Still, ambiguity is possible - so when in doubt use {} to enclose
544 the sub/superscript. If you set this variable to the symbol
545 `{}', the braces are *required* in order to trigger
546 interpretations as sub/superscript. This can be helpful in
547 documents that need \"_\" frequently in plain text.
549 This option can also be set with the #+OPTIONS line,
550 e.g. \"^:nil\"."
551 :group 'org-export-general
552 :type '(choice
553 (const :tag "Interpret them" t)
554 (const :tag "Curly brackets only" {})
555 (const :tag "Do not interpret them" nil)))
557 (defcustom org-export-with-toc t
558 "Non-nil means create a table of contents in exported files.
560 The TOC contains headlines with levels up
561 to`org-export-headline-levels'. When an integer, include levels
562 up to N in the toc, this may then be different from
563 `org-export-headline-levels', but it will not be allowed to be
564 larger than the number of headline levels. When nil, no table of
565 contents is made.
567 This option can also be set with the #+OPTIONS line,
568 e.g. \"toc:nil\" or \"toc:3\"."
569 :group 'org-export-general
570 :type '(choice
571 (const :tag "No Table of Contents" nil)
572 (const :tag "Full Table of Contents" t)
573 (integer :tag "TOC to level")))
575 (defcustom org-export-with-tables t
576 "If non-nil, lines starting with \"|\" define a table.
577 For example:
579 | Name | Address | Birthday |
580 |-------------+----------+-----------|
581 | Arthur Dent | England | 29.2.2100 |
583 This option can also be set with the #+OPTIONS line, e.g. \"|:nil\"."
584 :group 'org-export-general
585 :type 'boolean)
587 (defcustom org-export-with-tags t
588 "If nil, do not export tags, just remove them from headlines.
590 If this is the symbol `not-in-toc', tags will be removed from
591 table of contents entries, but still be shown in the headlines of
592 the document.
594 This option can also be set with the #+OPTIONS line,
595 e.g. \"tags:nil\"."
596 :group 'org-export-general
597 :type '(choice
598 (const :tag "Off" nil)
599 (const :tag "Not in TOC" not-in-toc)
600 (const :tag "On" t)))
602 (defcustom org-export-with-tasks t
603 "Non-nil means include TODO items for export.
605 This may have the following values:
606 t include tasks independent of state.
607 `todo' include only tasks that are not yet done.
608 `done' include only tasks that are already done.
609 nil ignore all tasks.
610 list of keywords include tasks with these keywords.
612 This option can also be set with the #+OPTIONS line,
613 e.g. \"tasks:nil\"."
614 :group 'org-export-general
615 :type '(choice
616 (const :tag "All tasks" t)
617 (const :tag "No tasks" nil)
618 (const :tag "Not-done tasks" todo)
619 (const :tag "Only done tasks" done)
620 (repeat :tag "Specific TODO keywords"
621 (string :tag "Keyword"))))
623 (defcustom org-export-time-stamp-file t
624 "Non-nil means insert a time stamp into the exported file.
625 The time stamp shows when the file was created.
627 This option can also be set with the #+OPTIONS line,
628 e.g. \"timestamp:nil\"."
629 :group 'org-export-general
630 :type 'boolean)
632 (defcustom org-export-with-timestamps t
633 "Non nil means allow timestamps in export.
635 It can be set to `active', `inactive', t or nil, in order to
636 export, respectively, only active timestamps, only inactive ones,
637 all of them or none.
639 This option can also be set with the #+OPTIONS line, e.g.
640 \"<:nil\"."
641 :group 'org-export-general
642 :type '(choice
643 (const :tag "All timestamps" t)
644 (const :tag "Only active timestamps" active)
645 (const :tag "Only inactive timestamps" inactive)
646 (const :tag "No timestamp" nil)))
648 (defcustom org-export-with-todo-keywords t
649 "Non-nil means include TODO keywords in export.
650 When nil, remove all these keywords from the export."
651 :group 'org-export-general
652 :type 'boolean)
654 (defcustom org-export-allow-BIND 'confirm
655 "Non-nil means allow #+BIND to define local variable values for export.
656 This is a potential security risk, which is why the user must
657 confirm the use of these lines."
658 :group 'org-export-general
659 :type '(choice
660 (const :tag "Never" nil)
661 (const :tag "Always" t)
662 (const :tag "Ask a confirmation for each file" confirm)))
664 (defcustom org-export-snippet-translation-alist nil
665 "Alist between export snippets back-ends and exporter back-ends.
667 This variable allows to provide shortcuts for export snippets.
669 For example, with a value of '\(\(\"h\" . \"e-html\"\)\), the
670 HTML back-end will recognize the contents of \"@@h:<b>@@\" as
671 HTML code while every other back-end will ignore it."
672 :group 'org-export-general
673 :type '(repeat
674 (cons
675 (string :tag "Shortcut")
676 (string :tag "Back-end"))))
678 (defcustom org-export-coding-system nil
679 "Coding system for the exported file."
680 :group 'org-export-general
681 :type 'coding-system)
683 (defcustom org-export-copy-to-kill-ring t
684 "Non-nil means exported stuff will also be pushed onto the kill ring."
685 :group 'org-export-general
686 :type 'boolean)
688 (defcustom org-export-initial-scope 'buffer
689 "The initial scope when exporting with `org-export-dispatch'.
690 This variable can be either set to `buffer' or `subtree'."
691 :group 'org-export-general
692 :type '(choice
693 (const :tag "Export current buffer" 'buffer)
694 (const :tag "Export current subtree" 'subtree)))
696 (defcustom org-export-show-temporary-export-buffer t
697 "Non-nil means show buffer after exporting to temp buffer.
698 When Org exports to a file, the buffer visiting that file is ever
699 shown, but remains buried. However, when exporting to
700 a temporary buffer, that buffer is popped up in a second window.
701 When this variable is nil, the buffer remains buried also in
702 these cases."
703 :group 'org-export-general
704 :type 'boolean)
706 (defcustom org-export-dispatch-use-expert-ui nil
707 "Non-nil means using a non-intrusive `org-export-dispatch'.
708 In that case, no help buffer is displayed. Though, an indicator
709 for current export scope is added to the prompt (\"b\" when
710 output is restricted to body only, \"s\" when it is restricted to
711 the current subtree, \"v\" when only visible elements are
712 considered for export and \"f\" when publishing functions should
713 be passed the FORCE argument). Also, \[?] allows to switch back
714 to standard mode."
715 :group 'org-export-general
716 :type 'boolean)
720 ;;; Defining Back-ends
722 ;; `org-export-define-backend' is the standard way to define an export
723 ;; back-end. It allows to specify translators, filters, buffer
724 ;; options and a menu entry. If the new back-end shares translators
725 ;; with another back-end, `org-export-define-derived-backend' may be
726 ;; used instead.
728 ;; Internally, a back-end is stored as a list, of which CAR is the
729 ;; name of the back-end, as a symbol, and CDR a plist. Accessors to
730 ;; properties of a given back-end are: `org-export-backend-filters',
731 ;; `org-export-backend-menu', `org-export-backend-options' and
732 ;; `org-export-backend-translate-table'.
734 ;; Eventually `org-export-barf-if-invalid-backend' returns an error
735 ;; when a given back-end hasn't been registered yet.
737 (defmacro org-export-define-backend (backend translators &rest body)
738 "Define a new back-end BACKEND.
740 TRANSLATORS is an alist between object or element types and
741 functions handling them.
743 These functions should return a string without any trailing
744 space, or nil. They must accept three arguments: the object or
745 element itself, its contents or nil when it isn't recursive and
746 the property list used as a communication channel.
748 Contents, when not nil, are stripped from any global indentation
749 \(although the relative one is preserved). They also always end
750 with a single newline character.
752 If, for a given type, no function is found, that element or
753 object type will simply be ignored, along with any blank line or
754 white space at its end. The same will happen if the function
755 returns the nil value. If that function returns the empty
756 string, the type will be ignored, but the blank lines or white
757 spaces will be kept.
759 In addition to element and object types, one function can be
760 associated to the `template' symbol and another one to the
761 `plain-text' symbol.
763 The former returns the final transcoded string, and can be used
764 to add a preamble and a postamble to document's body. It must
765 accept two arguments: the transcoded string and the property list
766 containing export options.
768 The latter, when defined, is to be called on every text not
769 recognized as an element or an object. It must accept two
770 arguments: the text string and the information channel. It is an
771 appropriate place to protect special chars relative to the
772 back-end.
774 BODY can start with pre-defined keyword arguments. The following
775 keywords are understood:
777 :export-block
779 String, or list of strings, representing block names that
780 will not be parsed. This is used to specify blocks that will
781 contain raw code specific to the back-end. These blocks
782 still have to be handled by the relative `export-block' type
783 translator.
785 :filters-alist
787 Alist between filters and function, or list of functions,
788 specific to the back-end. See `org-export-filters-alist' for
789 a list of all allowed filters. Filters defined here
790 shouldn't make a back-end test, as it may prevent back-ends
791 derived from this one to behave properly.
793 :menu-entry
795 Menu entry for the export dispatcher. It should be a list
796 like:
798 \(KEY DESCRIPTION-OR-ORDINAL ACTION-OR-MENU)
800 where :
802 KEY is a free character selecting the back-end.
804 DESCRIPTION-OR-ORDINAL is either a string or a number.
806 If it is a string, is will be used to name the back-end in
807 its menu entry. If it is a number, the following menu will
808 be displayed as a sub-menu of the back-end with the same
809 KEY. Also, the number will be used to determine in which
810 order such sub-menus will appear (lowest first).
812 ACTION-OR-MENU is either a function or an alist.
814 If it is an action, it will be called with three arguments:
815 SUBTREEP, VISIBLE-ONLY and BODY-ONLY. See `org-export-as'
816 for further explanations.
818 If it is an alist, associations should follow the
819 pattern:
821 \(KEY DESCRIPTION ACTION)
823 where KEY, DESCRIPTION and ACTION are described above.
825 Valid values include:
827 \(?m \"My Special Back-end\" my-special-export-function)
831 \(?l \"Export to LaTeX\"
832 \((?b \"TEX (buffer)\" org-e-latex-export-as-latex)
833 \(?l \"TEX (file)\" org-e-latex-export-to-latex)
834 \(?p \"PDF file\" org-e-latex-export-to-pdf)
835 \(?o \"PDF file and open\"
836 \(lambda (subtree visible body-only)
837 \(org-open-file
838 \(org-e-latex-export-to-pdf subtree visible body-only))))))
840 :options-alist
842 Alist between back-end specific properties introduced in
843 communication channel and how their value are acquired. See
844 `org-export-options-alist' for more information about
845 structure of the values."
846 (declare (debug (&define name sexp [&rest [keywordp sexp]] defbody))
847 (indent 1))
848 (let (export-block filters menu-entry options contents)
849 (while (keywordp (car body))
850 (case (pop body)
851 (:export-block (let ((names (pop body)))
852 (setq export-block
853 (if (consp names) (mapcar 'upcase names)
854 (list (upcase names))))))
855 (:filters-alist (setq filters (pop body)))
856 (:menu-entry (setq menu-entry (pop body)))
857 (:options-alist (setq options (pop body)))
858 (t (pop body))))
859 (setq contents (append (list :translate-alist translators)
860 (and filters (list :filters-alist filters))
861 (and options (list :options-alist options))
862 (and menu-entry (list :menu-entry menu-entry))))
863 `(progn
864 ;; Register back-end.
865 (let ((registeredp (assq ',backend org-export-registered-backends)))
866 (if registeredp (setcdr registeredp ',contents)
867 (push (cons ',backend ',contents) org-export-registered-backends)))
868 ;; Tell parser to not parse EXPORT-BLOCK blocks.
869 ,(when export-block
870 `(mapc
871 (lambda (name)
872 (add-to-list 'org-element-block-name-alist
873 `(,name . org-element-export-block-parser)))
874 ',export-block))
875 ;; Splice in the body, if any.
876 ,@body)))
878 (defmacro org-export-define-derived-backend (child parent &rest body)
879 "Create a new back-end as a variant of an existing one.
881 CHILD is the name of the derived back-end. PARENT is the name of
882 the parent back-end.
884 BODY can start with pre-defined keyword arguments. The following
885 keywords are understood:
887 :export-block
889 String, or list of strings, representing block names that
890 will not be parsed. This is used to specify blocks that will
891 contain raw code specific to the back-end. These blocks
892 still have to be handled by the relative `export-block' type
893 translator.
895 :filters-alist
897 Alist of filters that will overwrite or complete filters
898 defined in PARENT back-end. See `org-export-filters-alist'
899 for a list of allowed filters.
901 :menu-entry
903 Menu entry for the export dispatcher. See
904 `org-export-define-backend' for more information about the
905 expected value.
907 :options-alist
909 Alist of back-end specific properties that will overwrite or
910 complete those defined in PARENT back-end. Refer to
911 `org-export-options-alist' for more information about
912 structure of the values.
914 :translate-alist
916 Alist of element and object types and transcoders that will
917 overwrite or complete transcode table from PARENT back-end.
918 Refer to `org-export-define-backend' for detailed information
919 about transcoders.
921 As an example, here is how one could define \"my-latex\" back-end
922 as a variant of `e-latex' back-end with a custom template
923 function:
925 \(org-export-define-derived-backend my-latex e-latex
926 :translate-alist ((template . my-latex-template-fun)))
928 The back-end could then be called with, for example:
930 \(org-export-to-buffer 'my-latex \"*Test my-latex*\")"
931 (declare (debug (&define name sexp [&rest [keywordp sexp]] def-body))
932 (indent 2))
933 (org-export-barf-if-invalid-backend parent)
934 (let (export-block filters menu-entry options translators contents)
935 (while (keywordp (car body))
936 (case (pop body)
937 (:export-block (let ((names (pop body)))
938 (setq export-block
939 (if (consp names) (mapcar 'upcase names)
940 (list (upcase names))))))
941 (:filters-alist (setq filters (pop body)))
942 (:menu-entry (setq menu-entry (pop body)))
943 (:options-alist (setq options (pop body)))
944 (:translate-alist (setq translators (pop body)))
945 (t (pop body))))
946 (setq contents (append
947 (list :parent parent)
948 (let ((p-table (org-export-backend-translate-table parent)))
949 (list :translate-alist (append translators p-table)))
950 (let ((p-filters (org-export-backend-filters parent)))
951 (list :filters-alist (append filters p-filters)))
952 (let ((p-options (org-export-backend-options parent)))
953 (list :options-alist (append options p-options)))
954 (and menu-entry (list :menu-entry menu-entry))))
955 `(progn
956 ;; Register back-end.
957 (let ((registeredp (assq ',child org-export-registered-backends)))
958 (if registeredp (setcdr registeredp ',contents)
959 (push (cons ',child ',contents) org-export-registered-backends)))
960 ;; Tell parser to not parse EXPORT-BLOCK blocks.
961 ,(when export-block
962 `(mapc
963 (lambda (name)
964 (add-to-list 'org-element-block-name-alist
965 `(,name . org-element-export-block-parser)))
966 ',export-block))
967 ;; Splice in the body, if any.
968 ,@body)))
970 (defun org-export-backend-filters (backend)
971 "Return filters for BACKEND."
972 (plist-get (cdr (assq backend org-export-registered-backends))
973 :filters-alist))
975 (defun org-export-backend-menu (backend)
976 "Return menu entry for BACKEND."
977 (plist-get (cdr (assq backend org-export-registered-backends))
978 :menu-entry))
980 (defun org-export-backend-options (backend)
981 "Return export options for BACKEND."
982 (plist-get (cdr (assq backend org-export-registered-backends))
983 :options-alist))
985 (defun org-export-backend-translate-table (backend)
986 "Return translate table for BACKEND."
987 (plist-get (cdr (assq backend org-export-registered-backends))
988 :translate-alist))
990 (defun org-export-barf-if-invalid-backend (backend)
991 "Signal an error if BACKEND isn't defined."
992 (unless (org-export-backend-translate-table backend)
993 (error "Unknown \"%s\" back-end: Aborting export" backend)))
995 (defun org-export-derived-backend-p (backend &rest backends)
996 "Non-nil if BACKEND is derived from one of BACKENDS."
997 (let ((parent backend))
998 (while (and (not (memq parent backends))
999 (setq parent
1000 (plist-get (cdr (assq parent
1001 org-export-registered-backends))
1002 :parent))))
1003 parent))
1007 ;;; The Communication Channel
1009 ;; During export process, every function has access to a number of
1010 ;; properties. They are of two types:
1012 ;; 1. Environment options are collected once at the very beginning of
1013 ;; the process, out of the original buffer and configuration.
1014 ;; Collecting them is handled by `org-export-get-environment'
1015 ;; function.
1017 ;; Most environment options are defined through the
1018 ;; `org-export-options-alist' variable.
1020 ;; 2. Tree properties are extracted directly from the parsed tree,
1021 ;; just before export, by `org-export-collect-tree-properties'.
1023 ;; Here is the full list of properties available during transcode
1024 ;; process, with their category and their value type.
1026 ;; + `:author' :: Author's name.
1027 ;; - category :: option
1028 ;; - type :: string
1030 ;; + `:back-end' :: Current back-end used for transcoding.
1031 ;; - category :: tree
1032 ;; - type :: symbol
1034 ;; + `:creator' :: String to write as creation information.
1035 ;; - category :: option
1036 ;; - type :: string
1038 ;; + `:date' :: String to use as date.
1039 ;; - category :: option
1040 ;; - type :: string
1042 ;; + `:description' :: Description text for the current data.
1043 ;; - category :: option
1044 ;; - type :: string
1046 ;; + `:email' :: Author's email.
1047 ;; - category :: option
1048 ;; - type :: string
1050 ;; + `:exclude-tags' :: Tags for exclusion of subtrees from export
1051 ;; process.
1052 ;; - category :: option
1053 ;; - type :: list of strings
1055 ;; + `:exported-data' :: Hash table used for memoizing
1056 ;; `org-export-data'.
1057 ;; - category :: tree
1058 ;; - type :: hash table
1060 ;; + `:filetags' :: List of global tags for buffer. Used by
1061 ;; `org-export-get-tags' to get tags with inheritance.
1062 ;; - category :: option
1063 ;; - type :: list of strings
1065 ;; + `:footnote-definition-alist' :: Alist between footnote labels and
1066 ;; their definition, as parsed data. Only non-inlined footnotes
1067 ;; are represented in this alist. Also, every definition isn't
1068 ;; guaranteed to be referenced in the parse tree. The purpose of
1069 ;; this property is to preserve definitions from oblivion
1070 ;; (i.e. when the parse tree comes from a part of the original
1071 ;; buffer), it isn't meant for direct use in a back-end. To
1072 ;; retrieve a definition relative to a reference, use
1073 ;; `org-export-get-footnote-definition' instead.
1074 ;; - category :: option
1075 ;; - type :: alist (STRING . LIST)
1077 ;; + `:headline-levels' :: Maximum level being exported as an
1078 ;; headline. Comparison is done with the relative level of
1079 ;; headlines in the parse tree, not necessarily with their
1080 ;; actual level.
1081 ;; - category :: option
1082 ;; - type :: integer
1084 ;; + `:headline-offset' :: Difference between relative and real level
1085 ;; of headlines in the parse tree. For example, a value of -1
1086 ;; means a level 2 headline should be considered as level
1087 ;; 1 (cf. `org-export-get-relative-level').
1088 ;; - category :: tree
1089 ;; - type :: integer
1091 ;; + `:headline-numbering' :: Alist between headlines and their
1092 ;; numbering, as a list of numbers
1093 ;; (cf. `org-export-get-headline-number').
1094 ;; - category :: tree
1095 ;; - type :: alist (INTEGER . LIST)
1097 ;; + `:id-alist' :: Alist between ID strings and destination file's
1098 ;; path, relative to current directory. It is used by
1099 ;; `org-export-resolve-id-link' to resolve ID links targeting an
1100 ;; external file.
1101 ;; - category :: option
1102 ;; - type :: alist (STRING . STRING)
1104 ;; + `:ignore-list' :: List of elements and objects that should be
1105 ;; ignored during export.
1106 ;; - category :: tree
1107 ;; - type :: list of elements and objects
1109 ;; + `:input-file' :: Full path to input file, if any.
1110 ;; - category :: option
1111 ;; - type :: string or nil
1113 ;; + `:keywords' :: List of keywords attached to data.
1114 ;; - category :: option
1115 ;; - type :: string
1117 ;; + `:language' :: Default language used for translations.
1118 ;; - category :: option
1119 ;; - type :: string
1121 ;; + `:parse-tree' :: Whole parse tree, available at any time during
1122 ;; transcoding.
1123 ;; - category :: option
1124 ;; - type :: list (as returned by `org-element-parse-buffer')
1126 ;; + `:preserve-breaks' :: Non-nil means transcoding should preserve
1127 ;; all line breaks.
1128 ;; - category :: option
1129 ;; - type :: symbol (nil, t)
1131 ;; + `:section-numbers' :: Non-nil means transcoding should add
1132 ;; section numbers to headlines.
1133 ;; - category :: option
1134 ;; - type :: symbol (nil, t)
1136 ;; + `:select-tags' :: List of tags enforcing inclusion of sub-trees
1137 ;; in transcoding. When such a tag is present, subtrees without
1138 ;; it are de facto excluded from the process. See
1139 ;; `use-select-tags'.
1140 ;; - category :: option
1141 ;; - type :: list of strings
1143 ;; + `:target-list' :: List of targets encountered in the parse tree.
1144 ;; This is used to partly resolve "fuzzy" links
1145 ;; (cf. `org-export-resolve-fuzzy-link').
1146 ;; - category :: tree
1147 ;; - type :: list of strings
1149 ;; + `:time-stamp-file' :: Non-nil means transcoding should insert
1150 ;; a time stamp in the output.
1151 ;; - category :: option
1152 ;; - type :: symbol (nil, t)
1154 ;; + `:translate-alist' :: Alist between element and object types and
1155 ;; transcoding functions relative to the current back-end.
1156 ;; Special keys `template' and `plain-text' are also possible.
1157 ;; - category :: option
1158 ;; - type :: alist (SYMBOL . FUNCTION)
1160 ;; + `:with-archived-trees' :: Non-nil when archived subtrees should
1161 ;; also be transcoded. If it is set to the `headline' symbol,
1162 ;; only the archived headline's name is retained.
1163 ;; - category :: option
1164 ;; - type :: symbol (nil, t, `headline')
1166 ;; + `:with-author' :: Non-nil means author's name should be included
1167 ;; in the output.
1168 ;; - category :: option
1169 ;; - type :: symbol (nil, t)
1171 ;; + `:with-clocks' :: Non-nil means clock keywords should be exported.
1172 ;; - category :: option
1173 ;; - type :: symbol (nil, t)
1175 ;; + `:with-creator' :: Non-nil means a creation sentence should be
1176 ;; inserted at the end of the transcoded string. If the value
1177 ;; is `comment', it should be commented.
1178 ;; - category :: option
1179 ;; - type :: symbol (`comment', nil, t)
1181 ;; + `:with-date' :: Non-nil means output should contain a date.
1182 ;; - category :: option
1183 ;; - type :. symbol (nil, t)
1185 ;; + `:with-drawers' :: Non-nil means drawers should be exported. If
1186 ;; its value is a list of names, only drawers with such names
1187 ;; will be transcoded.
1188 ;; - category :: option
1189 ;; - type :: symbol (nil, t) or list of strings
1191 ;; + `:with-email' :: Non-nil means output should contain author's
1192 ;; email.
1193 ;; - category :: option
1194 ;; - type :: symbol (nil, t)
1196 ;; + `:with-emphasize' :: Non-nil means emphasized text should be
1197 ;; interpreted.
1198 ;; - category :: option
1199 ;; - type :: symbol (nil, t)
1201 ;; + `:with-fixed-width' :: Non-nil if transcoder should interpret
1202 ;; strings starting with a colon as a fixed-with (verbatim) area.
1203 ;; - category :: option
1204 ;; - type :: symbol (nil, t)
1206 ;; + `:with-footnotes' :: Non-nil if transcoder should interpret
1207 ;; footnotes.
1208 ;; - category :: option
1209 ;; - type :: symbol (nil, t)
1211 ;; + `:with-plannings' :: Non-nil means transcoding should include
1212 ;; planning info.
1213 ;; - category :: option
1214 ;; - type :: symbol (nil, t)
1216 ;; + `:with-priority' :: Non-nil means transcoding should include
1217 ;; priority cookies.
1218 ;; - category :: option
1219 ;; - type :: symbol (nil, t)
1221 ;; + `:with-smart-quotes' :: Non-nil means activate smart quotes in
1222 ;; plain text.
1223 ;; - category :: option
1224 ;; - type :: symbol (nil, t)
1226 ;; + `:with-special-strings' :: Non-nil means transcoding should
1227 ;; interpret special strings in plain text.
1228 ;; - category :: option
1229 ;; - type :: symbol (nil, t)
1231 ;; + `:with-sub-superscript' :: Non-nil means transcoding should
1232 ;; interpret subscript and superscript. With a value of "{}",
1233 ;; only interpret those using curly brackets.
1234 ;; - category :: option
1235 ;; - type :: symbol (nil, {}, t)
1237 ;; + `:with-tables' :: Non-nil means transcoding should interpret
1238 ;; tables.
1239 ;; - category :: option
1240 ;; - type :: symbol (nil, t)
1242 ;; + `:with-tags' :: Non-nil means transcoding should keep tags in
1243 ;; headlines. A `not-in-toc' value will remove them from the
1244 ;; table of contents, if any, nonetheless.
1245 ;; - category :: option
1246 ;; - type :: symbol (nil, t, `not-in-toc')
1248 ;; + `:with-tasks' :: Non-nil means transcoding should include
1249 ;; headlines with a TODO keyword. A `todo' value will only
1250 ;; include headlines with a todo type keyword while a `done'
1251 ;; value will do the contrary. If a list of strings is provided,
1252 ;; only tasks with keywords belonging to that list will be kept.
1253 ;; - category :: option
1254 ;; - type :: symbol (t, todo, done, nil) or list of strings
1256 ;; + `:with-timestamps' :: Non-nil means transcoding should include
1257 ;; time stamps. Special value `active' (resp. `inactive') ask to
1258 ;; export only active (resp. inactive) timestamps. Otherwise,
1259 ;; completely remove them.
1260 ;; - category :: option
1261 ;; - type :: symbol: (`active', `inactive', t, nil)
1263 ;; + `:with-toc' :: Non-nil means that a table of contents has to be
1264 ;; added to the output. An integer value limits its depth.
1265 ;; - category :: option
1266 ;; - type :: symbol (nil, t or integer)
1268 ;; + `:with-todo-keywords' :: Non-nil means transcoding should
1269 ;; include TODO keywords.
1270 ;; - category :: option
1271 ;; - type :: symbol (nil, t)
1274 ;;;; Environment Options
1276 ;; Environment options encompass all parameters defined outside the
1277 ;; scope of the parsed data. They come from five sources, in
1278 ;; increasing precedence order:
1280 ;; - Global variables,
1281 ;; - Buffer's attributes,
1282 ;; - Options keyword symbols,
1283 ;; - Buffer keywords,
1284 ;; - Subtree properties.
1286 ;; The central internal function with regards to environment options
1287 ;; is `org-export-get-environment'. It updates global variables with
1288 ;; "#+BIND:" keywords, then retrieve and prioritize properties from
1289 ;; the different sources.
1291 ;; The internal functions doing the retrieval are:
1292 ;; `org-export--get-global-options',
1293 ;; `org-export--get-buffer-attributes',
1294 ;; `org-export--parse-option-keyword',
1295 ;; `org-export--get-subtree-options' and
1296 ;; `org-export--get-inbuffer-options'
1298 ;; Also, `org-export--confirm-letbind' and `org-export--install-letbind'
1299 ;; take care of the part relative to "#+BIND:" keywords.
1301 (defun org-export-get-environment (&optional backend subtreep ext-plist)
1302 "Collect export options from the current buffer.
1304 Optional argument BACKEND is a symbol specifying which back-end
1305 specific options to read, if any.
1307 When optional argument SUBTREEP is non-nil, assume the export is
1308 done against the current sub-tree.
1310 Third optional argument EXT-PLIST is a property list with
1311 external parameters overriding Org default settings, but still
1312 inferior to file-local settings."
1313 ;; First install #+BIND variables.
1314 (org-export--install-letbind-maybe)
1315 ;; Get and prioritize export options...
1316 (org-combine-plists
1317 ;; ... from global variables...
1318 (org-export--get-global-options backend)
1319 ;; ... from an external property list...
1320 ext-plist
1321 ;; ... from in-buffer settings...
1322 (org-export--get-inbuffer-options
1323 backend
1324 (and buffer-file-name (org-remove-double-quotes buffer-file-name)))
1325 ;; ... and from subtree, when appropriate.
1326 (and subtreep (org-export--get-subtree-options backend))
1327 ;; Eventually add misc. properties.
1328 (list
1329 :back-end
1330 backend
1331 :translate-alist
1332 (org-export-backend-translate-table backend)
1333 :footnote-definition-alist
1334 ;; Footnotes definitions must be collected in the original
1335 ;; buffer, as there's no insurance that they will still be in
1336 ;; the parse tree, due to possible narrowing.
1337 (let (alist)
1338 (org-with-wide-buffer
1339 (goto-char (point-min))
1340 (while (re-search-forward org-footnote-definition-re nil t)
1341 (let ((def (save-match-data (org-element-at-point))))
1342 (when (eq (org-element-type def) 'footnote-definition)
1343 (push
1344 (cons (org-element-property :label def)
1345 (let ((cbeg (org-element-property :contents-begin def)))
1346 (when cbeg
1347 (org-element--parse-elements
1348 cbeg (org-element-property :contents-end def)
1349 nil nil nil nil (list 'org-data nil)))))
1350 alist))))
1351 alist))
1352 :id-alist
1353 ;; Collect id references.
1354 (let (alist)
1355 (org-with-wide-buffer
1356 (goto-char (point-min))
1357 (while (re-search-forward "\\[\\[id:\\S-+?\\]" nil t)
1358 (let ((link (org-element-context)))
1359 (when (eq (org-element-type link) 'link)
1360 (let* ((id (org-element-property :path link))
1361 (file (org-id-find-id-file id)))
1362 (when file
1363 (push (cons id (file-relative-name file)) alist)))))))
1364 alist))))
1366 (defun org-export--parse-option-keyword (options &optional backend)
1367 "Parse an OPTIONS line and return values as a plist.
1368 Optional argument BACKEND is a symbol specifying which back-end
1369 specific items to read, if any."
1370 (let* ((all (append org-export-options-alist
1371 (and backend (org-export-backend-options backend))))
1372 ;; Build an alist between #+OPTION: item and property-name.
1373 (alist (delq nil
1374 (mapcar (lambda (e)
1375 (when (nth 2 e) (cons (regexp-quote (nth 2 e))
1376 (car e))))
1377 all)))
1378 plist)
1379 (mapc (lambda (e)
1380 (when (string-match (concat "\\(\\`\\|[ \t]\\)"
1381 (car e)
1382 ":\\(([^)\n]+)\\|[^ \t\n\r;,.]*\\)")
1383 options)
1384 (setq plist (plist-put plist
1385 (cdr e)
1386 (car (read-from-string
1387 (match-string 2 options)))))))
1388 alist)
1389 plist))
1391 (defun org-export--get-subtree-options (&optional backend)
1392 "Get export options in subtree at point.
1393 Optional argument BACKEND is a symbol specifying back-end used
1394 for export. Return options as a plist."
1395 ;; For each buffer keyword, create an headline property setting the
1396 ;; same property in communication channel. The name for the property
1397 ;; is the keyword with "EXPORT_" appended to it.
1398 (org-with-wide-buffer
1399 (let (prop plist)
1400 ;; Make sure point is at an heading.
1401 (unless (org-at-heading-p) (org-back-to-heading t))
1402 ;; Take care of EXPORT_TITLE. If it isn't defined, use headline's
1403 ;; title as its fallback value.
1404 (when (setq prop (or (org-entry-get (point) "EXPORT_TITLE")
1405 (progn (looking-at org-todo-line-regexp)
1406 (org-match-string-no-properties 3))))
1407 (setq plist
1408 (plist-put
1409 plist :title
1410 (org-element-parse-secondary-string
1411 prop (org-element-restriction 'keyword)))))
1412 ;; EXPORT_OPTIONS are parsed in a non-standard way.
1413 (when (setq prop (org-entry-get (point) "EXPORT_OPTIONS"))
1414 (setq plist
1415 (nconc plist (org-export--parse-option-keyword prop backend))))
1416 ;; Handle other keywords. TITLE keyword is excluded as it has
1417 ;; been handled already.
1418 (let ((seen '("TITLE")))
1419 (mapc
1420 (lambda (option)
1421 (let ((property (nth 1 option)))
1422 (when (and property (not (member property seen)))
1423 (let* ((subtree-prop (concat "EXPORT_" property))
1424 ;; Export properties are not case-sensitive.
1425 (value (let ((case-fold-search t))
1426 (org-entry-get (point) subtree-prop))))
1427 (push property seen)
1428 (when value
1429 (setq plist
1430 (plist-put
1431 plist
1432 (car option)
1433 (cond
1434 ;; Parse VALUE if required.
1435 ((member property org-element-document-properties)
1436 (org-element-parse-secondary-string
1437 value (org-element-restriction 'keyword)))
1438 ;; If BEHAVIOUR is `split' expected value is
1439 ;; a list of strings, not a string.
1440 ((eq (nth 4 option) 'split) (org-split-string value))
1441 (t value)))))))))
1442 ;; Also look for both general keywords and back-end specific
1443 ;; options if BACKEND is provided.
1444 (append (and backend (org-export-backend-options backend))
1445 org-export-options-alist)))
1446 ;; Return value.
1447 plist)))
1449 (defun org-export--get-inbuffer-options (&optional backend files)
1450 "Return current buffer export options, as a plist.
1452 Optional argument BACKEND, when non-nil, is a symbol specifying
1453 which back-end specific options should also be read in the
1454 process.
1456 Optional argument FILES is a list of setup files names read so
1457 far, used to avoid circular dependencies.
1459 Assume buffer is in Org mode. Narrowing, if any, is ignored."
1460 (org-with-wide-buffer
1461 (goto-char (point-min))
1462 (let ((case-fold-search t) plist)
1463 ;; 1. Special keywords, as in `org-export-special-keywords'.
1464 (let ((special-re
1465 (format "^[ \t]*#\\+%s:" (regexp-opt org-export-special-keywords))))
1466 (while (re-search-forward special-re nil t)
1467 (let ((element (org-element-at-point)))
1468 (when (eq (org-element-type element) 'keyword)
1469 (let* ((key (org-element-property :key element))
1470 (val (org-element-property :value element))
1471 (prop
1472 (cond
1473 ((equal key "SETUP_FILE")
1474 (let ((file
1475 (expand-file-name
1476 (org-remove-double-quotes (org-trim val)))))
1477 ;; Avoid circular dependencies.
1478 (unless (member file files)
1479 (with-temp-buffer
1480 (insert (org-file-contents file 'noerror))
1481 (org-mode)
1482 (org-export--get-inbuffer-options
1483 backend (cons file files))))))
1484 ((equal key "OPTIONS")
1485 (org-export--parse-option-keyword val backend))
1486 ((equal key "FILETAGS")
1487 (list :filetags
1488 (org-uniquify
1489 (append (org-split-string val ":")
1490 (plist-get plist :filetags))))))))
1491 (setq plist (org-combine-plists plist prop)))))))
1492 ;; 2. Standard options, as in `org-export-options-alist'.
1493 (let* ((all (append org-export-options-alist
1494 ;; Also look for back-end specific options if
1495 ;; BACKEND is defined.
1496 (and backend (org-export-backend-options backend))))
1497 ;; Build ALIST between keyword name and property name.
1498 (alist
1499 (delq nil (mapcar
1500 (lambda (e) (when (nth 1 e) (cons (nth 1 e) (car e))))
1501 all)))
1502 ;; Build regexp matching all keywords associated to export
1503 ;; options. Note: the search is case insensitive.
1504 (opt-re (format "^[ \t]*#\\+%s:"
1505 (regexp-opt
1506 (delq nil (mapcar (lambda (e) (nth 1 e)) all))))))
1507 (goto-char (point-min))
1508 (while (re-search-forward opt-re nil t)
1509 (let ((element (org-element-at-point)))
1510 (when (eq (org-element-type element) 'keyword)
1511 (let* ((key (org-element-property :key element))
1512 (val (org-element-property :value element))
1513 (prop (cdr (assoc key alist)))
1514 (behaviour (nth 4 (assq prop all))))
1515 (setq plist
1516 (plist-put
1517 plist prop
1518 ;; Handle value depending on specified BEHAVIOUR.
1519 (case behaviour
1520 (space
1521 (if (not (plist-get plist prop)) (org-trim val)
1522 (concat (plist-get plist prop) " " (org-trim val))))
1523 (newline
1524 (org-trim
1525 (concat (plist-get plist prop) "\n" (org-trim val))))
1526 (split
1527 `(,@(plist-get plist prop) ,@(org-split-string val)))
1528 ('t val)
1529 (otherwise (if (not (plist-member plist prop)) val
1530 (plist-get plist prop))))))))))
1531 ;; Parse keywords specified in
1532 ;; `org-element-document-properties'.
1533 (mapc
1534 (lambda (key)
1535 (let* ((prop (cdr (assoc key alist)))
1536 (value (and prop (plist-get plist prop))))
1537 (when (stringp value)
1538 (setq plist
1539 (plist-put
1540 plist prop
1541 (org-element-parse-secondary-string
1542 value (org-element-restriction 'keyword)))))))
1543 org-element-document-properties))
1544 ;; 3. Return final value.
1545 plist)))
1547 (defun org-export--get-buffer-attributes ()
1548 "Return properties related to buffer attributes, as a plist."
1549 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
1550 (list
1551 ;; Store full path of input file name, or nil. For internal use.
1552 :input-file visited-file
1553 :title (or (and visited-file
1554 (file-name-sans-extension
1555 (file-name-nondirectory visited-file)))
1556 (buffer-name (buffer-base-buffer))))))
1558 (defun org-export--get-global-options (&optional backend)
1559 "Return global export options as a plist.
1561 Optional argument BACKEND, if non-nil, is a symbol specifying
1562 which back-end specific export options should also be read in the
1563 process."
1564 (let ((all (append org-export-options-alist
1565 (and backend (org-export-backend-options backend))))
1566 ;; Output value.
1567 plist)
1568 (mapc
1569 (lambda (cell)
1570 (setq plist
1571 (plist-put
1572 plist
1573 (car cell)
1574 ;; Eval default value provided. If keyword is a member
1575 ;; of `org-element-document-properties', parse it as
1576 ;; a secondary string before storing it.
1577 (let ((value (eval (nth 3 cell))))
1578 (if (not (stringp value)) value
1579 (let ((keyword (nth 1 cell)))
1580 (if (not (member keyword org-element-document-properties))
1581 value
1582 (org-element-parse-secondary-string
1583 value (org-element-restriction 'keyword)))))))))
1584 all)
1585 ;; Return value.
1586 plist))
1588 (defvar org-export--allow-BIND-local nil)
1589 (defun org-export--confirm-letbind ()
1590 "Can we use #+BIND values during export?
1591 By default this will ask for confirmation by the user, to divert
1592 possible security risks."
1593 (cond
1594 ((not org-export-allow-BIND) nil)
1595 ((eq org-export-allow-BIND t) t)
1596 ((local-variable-p 'org-export--allow-BIND-local)
1597 org-export--allow-BIND-local)
1598 (t (org-set-local 'org-export--allow-BIND-local
1599 (yes-or-no-p "Allow BIND values in this buffer? ")))))
1601 (defun org-export--install-letbind-maybe ()
1602 "Install the values from #+BIND lines as local variables.
1603 Variables must be installed before in-buffer options are
1604 retrieved."
1605 (let ((case-fold-search t) letbind pair)
1606 (org-with-wide-buffer
1607 (goto-char (point-min))
1608 (while (re-search-forward "^[ \t]*#\\+BIND:" nil t)
1609 (let* ((element (org-element-at-point))
1610 (value (org-element-property :value element)))
1611 (when (and (eq (org-element-type element) 'keyword)
1612 (not (equal value ""))
1613 (org-export--confirm-letbind))
1614 (push (read (format "(%s)" value)) letbind)))))
1615 (dolist (pair (nreverse letbind))
1616 (org-set-local (car pair) (nth 1 pair)))))
1619 ;;;; Tree Properties
1621 ;; Tree properties are information extracted from parse tree. They
1622 ;; are initialized at the beginning of the transcoding process by
1623 ;; `org-export-collect-tree-properties'.
1625 ;; Dedicated functions focus on computing the value of specific tree
1626 ;; properties during initialization. Thus,
1627 ;; `org-export--populate-ignore-list' lists elements and objects that
1628 ;; should be skipped during export, `org-export--get-min-level' gets
1629 ;; the minimal exportable level, used as a basis to compute relative
1630 ;; level for headlines. Eventually
1631 ;; `org-export--collect-headline-numbering' builds an alist between
1632 ;; headlines and their numbering.
1634 (defun org-export-collect-tree-properties (data info)
1635 "Extract tree properties from parse tree.
1637 DATA is the parse tree from which information is retrieved. INFO
1638 is a list holding export options.
1640 Following tree properties are set or updated:
1642 `:exported-data' Hash table used to memoize results from
1643 `org-export-data'.
1645 `:footnote-definition-alist' List of footnotes definitions in
1646 original buffer and current parse tree.
1648 `:headline-offset' Offset between true level of headlines and
1649 local level. An offset of -1 means an headline
1650 of level 2 should be considered as a level
1651 1 headline in the context.
1653 `:headline-numbering' Alist of all headlines as key an the
1654 associated numbering as value.
1656 `:ignore-list' List of elements that should be ignored during
1657 export.
1659 `:target-list' List of all targets in the parse tree.
1661 Return updated plist."
1662 ;; Install the parse tree in the communication channel, in order to
1663 ;; use `org-export-get-genealogy' and al.
1664 (setq info (plist-put info :parse-tree data))
1665 ;; Get the list of elements and objects to ignore, and put it into
1666 ;; `:ignore-list'. Do not overwrite any user ignore that might have
1667 ;; been done during parse tree filtering.
1668 (setq info
1669 (plist-put info
1670 :ignore-list
1671 (append (org-export--populate-ignore-list data info)
1672 (plist-get info :ignore-list))))
1673 ;; Compute `:headline-offset' in order to be able to use
1674 ;; `org-export-get-relative-level'.
1675 (setq info
1676 (plist-put info
1677 :headline-offset
1678 (- 1 (org-export--get-min-level data info))))
1679 ;; Update footnotes definitions list with definitions in parse tree.
1680 ;; This is required since buffer expansion might have modified
1681 ;; boundaries of footnote definitions contained in the parse tree.
1682 ;; This way, definitions in `footnote-definition-alist' are bound to
1683 ;; match those in the parse tree.
1684 (let ((defs (plist-get info :footnote-definition-alist)))
1685 (org-element-map
1686 data 'footnote-definition
1687 (lambda (fn)
1688 (push (cons (org-element-property :label fn)
1689 `(org-data nil ,@(org-element-contents fn)))
1690 defs)))
1691 (setq info (plist-put info :footnote-definition-alist defs)))
1692 ;; Properties order doesn't matter: get the rest of the tree
1693 ;; properties.
1694 (nconc
1695 `(:target-list
1696 ,(org-element-map
1697 data '(keyword target)
1698 (lambda (blob)
1699 (when (or (eq (org-element-type blob) 'target)
1700 (string= (org-element-property :key blob) "TARGET"))
1701 blob)) info)
1702 :headline-numbering ,(org-export--collect-headline-numbering data info)
1703 :exported-data ,(make-hash-table :test 'eq :size 4001))
1704 info))
1706 (defun org-export--get-min-level (data options)
1707 "Return minimum exportable headline's level in DATA.
1708 DATA is parsed tree as returned by `org-element-parse-buffer'.
1709 OPTIONS is a plist holding export options."
1710 (catch 'exit
1711 (let ((min-level 10000))
1712 (mapc
1713 (lambda (blob)
1714 (when (and (eq (org-element-type blob) 'headline)
1715 (not (memq blob (plist-get options :ignore-list))))
1716 (setq min-level
1717 (min (org-element-property :level blob) min-level)))
1718 (when (= min-level 1) (throw 'exit 1)))
1719 (org-element-contents data))
1720 ;; If no headline was found, for the sake of consistency, set
1721 ;; minimum level to 1 nonetheless.
1722 (if (= min-level 10000) 1 min-level))))
1724 (defun org-export--collect-headline-numbering (data options)
1725 "Return numbering of all exportable headlines in a parse tree.
1727 DATA is the parse tree. OPTIONS is the plist holding export
1728 options.
1730 Return an alist whose key is an headline and value is its
1731 associated numbering \(in the shape of a list of numbers\)."
1732 (let ((numbering (make-vector org-export-max-depth 0)))
1733 (org-element-map
1734 data
1735 'headline
1736 (lambda (headline)
1737 (let ((relative-level
1738 (1- (org-export-get-relative-level headline options))))
1739 (cons
1740 headline
1741 (loop for n across numbering
1742 for idx from 0 to org-export-max-depth
1743 when (< idx relative-level) collect n
1744 when (= idx relative-level) collect (aset numbering idx (1+ n))
1745 when (> idx relative-level) do (aset numbering idx 0)))))
1746 options)))
1748 (defun org-export--populate-ignore-list (data options)
1749 "Return list of elements and objects to ignore during export.
1750 DATA is the parse tree to traverse. OPTIONS is the plist holding
1751 export options."
1752 (let* (ignore
1753 walk-data
1754 ;; First find trees containing a select tag, if any.
1755 (selected (org-export--selected-trees data options))
1756 (walk-data
1757 (lambda (data)
1758 ;; Collect ignored elements or objects into IGNORE-LIST.
1759 (let ((type (org-element-type data)))
1760 (if (org-export--skip-p data options selected) (push data ignore)
1761 (if (and (eq type 'headline)
1762 (eq (plist-get options :with-archived-trees) 'headline)
1763 (org-element-property :archivedp data))
1764 ;; If headline is archived but tree below has
1765 ;; to be skipped, add it to ignore list.
1766 (mapc (lambda (e) (push e ignore))
1767 (org-element-contents data))
1768 ;; Move into secondary string, if any.
1769 (let ((sec-prop
1770 (cdr (assq type org-element-secondary-value-alist))))
1771 (when sec-prop
1772 (mapc walk-data (org-element-property sec-prop data))))
1773 ;; Move into recursive objects/elements.
1774 (mapc walk-data (org-element-contents data))))))))
1775 ;; Main call.
1776 (funcall walk-data data)
1777 ;; Return value.
1778 ignore))
1780 (defun org-export--selected-trees (data info)
1781 "Return list of headlines containing a select tag in their tree.
1782 DATA is parsed data as returned by `org-element-parse-buffer'.
1783 INFO is a plist holding export options."
1784 (let* (selected-trees
1785 walk-data ; for byte-compiler.
1786 (walk-data
1787 (function
1788 (lambda (data genealogy)
1789 (case (org-element-type data)
1790 (org-data (mapc (lambda (el) (funcall walk-data el genealogy))
1791 (org-element-contents data)))
1792 (headline
1793 (let ((tags (org-element-property :tags data)))
1794 (if (loop for tag in (plist-get info :select-tags)
1795 thereis (member tag tags))
1796 ;; When a select tag is found, mark full
1797 ;; genealogy and every headline within the tree
1798 ;; as acceptable.
1799 (setq selected-trees
1800 (append
1801 genealogy
1802 (org-element-map data 'headline 'identity)
1803 selected-trees))
1804 ;; Else, continue searching in tree, recursively.
1805 (mapc
1806 (lambda (el) (funcall walk-data el (cons data genealogy)))
1807 (org-element-contents data))))))))))
1808 (funcall walk-data data nil) selected-trees))
1810 (defun org-export--skip-p (blob options selected)
1811 "Non-nil when element or object BLOB should be skipped during export.
1812 OPTIONS is the plist holding export options. SELECTED, when
1813 non-nil, is a list of headlines belonging to a tree with a select
1814 tag."
1815 (case (org-element-type blob)
1816 (clock (not (plist-get options :with-clocks)))
1817 (drawer
1818 (or (not (plist-get options :with-drawers))
1819 (and (consp (plist-get options :with-drawers))
1820 (not (member (org-element-property :drawer-name blob)
1821 (plist-get options :with-drawers))))))
1822 (headline
1823 (let ((with-tasks (plist-get options :with-tasks))
1824 (todo (org-element-property :todo-keyword blob))
1825 (todo-type (org-element-property :todo-type blob))
1826 (archived (plist-get options :with-archived-trees))
1827 (tags (org-element-property :tags blob)))
1829 ;; Ignore subtrees with an exclude tag.
1830 (loop for k in (plist-get options :exclude-tags)
1831 thereis (member k tags))
1832 ;; When a select tag is present in the buffer, ignore any tree
1833 ;; without it.
1834 (and selected (not (memq blob selected)))
1835 ;; Ignore commented sub-trees.
1836 (org-element-property :commentedp blob)
1837 ;; Ignore archived subtrees if `:with-archived-trees' is nil.
1838 (and (not archived) (org-element-property :archivedp blob))
1839 ;; Ignore tasks, if specified by `:with-tasks' property.
1840 (and todo
1841 (or (not with-tasks)
1842 (and (memq with-tasks '(todo done))
1843 (not (eq todo-type with-tasks)))
1844 (and (consp with-tasks) (not (member todo with-tasks))))))))
1845 (inlinetask (not (plist-get options :with-inlinetasks)))
1846 (planning (not (plist-get options :with-plannings)))
1847 (statistics-cookie (not (plist-get options :with-statistics-cookies)))
1848 (table-cell
1849 (and (org-export-table-has-special-column-p
1850 (org-export-get-parent-table blob))
1851 (not (org-export-get-previous-element blob options))))
1852 (table-row (org-export-table-row-is-special-p blob options))
1853 (timestamp
1854 (case (plist-get options :with-timestamps)
1855 ;; No timestamp allowed.
1856 ('nil t)
1857 ;; Only active timestamps allowed and the current one isn't
1858 ;; active.
1859 (active
1860 (not (memq (org-element-property :type blob)
1861 '(active active-range))))
1862 ;; Only inactive timestamps allowed and the current one isn't
1863 ;; inactive.
1864 (inactive
1865 (not (memq (org-element-property :type blob)
1866 '(inactive inactive-range))))))))
1870 ;;; The Transcoder
1872 ;; `org-export-data' reads a parse tree (obtained with, i.e.
1873 ;; `org-element-parse-buffer') and transcodes it into a specified
1874 ;; back-end output. It takes care of filtering out elements or
1875 ;; objects according to export options and organizing the output blank
1876 ;; lines and white space are preserved. The function memoizes its
1877 ;; results, so it is cheap to call it within translators.
1879 ;; Internally, three functions handle the filtering of objects and
1880 ;; elements during the export. In particular,
1881 ;; `org-export-ignore-element' marks an element or object so future
1882 ;; parse tree traversals skip it, `org-export--interpret-p' tells which
1883 ;; elements or objects should be seen as real Org syntax and
1884 ;; `org-export-expand' transforms the others back into their original
1885 ;; shape
1887 ;; `org-export-transcoder' is an accessor returning appropriate
1888 ;; translator function for a given element or object.
1890 (defun org-export-transcoder (blob info)
1891 "Return appropriate transcoder for BLOB.
1892 INFO is a plist containing export directives."
1893 (let ((type (org-element-type blob)))
1894 ;; Return contents only for complete parse trees.
1895 (if (eq type 'org-data) (lambda (blob contents info) contents)
1896 (let ((transcoder (cdr (assq type (plist-get info :translate-alist)))))
1897 (and (functionp transcoder) transcoder)))))
1899 (defun org-export-data (data info)
1900 "Convert DATA into current back-end format.
1902 DATA is a parse tree, an element or an object or a secondary
1903 string. INFO is a plist holding export options.
1905 Return transcoded string."
1906 (let ((memo (gethash data (plist-get info :exported-data) 'no-memo)))
1907 (if (not (eq memo 'no-memo)) memo
1908 (let* ((type (org-element-type data))
1909 (results
1910 (cond
1911 ;; Ignored element/object.
1912 ((memq data (plist-get info :ignore-list)) nil)
1913 ;; Plain text. All residual text properties from parse
1914 ;; tree (i.e. `:parent' property) are removed.
1915 ((eq type 'plain-text)
1916 (org-no-properties
1917 (org-export-filter-apply-functions
1918 (plist-get info :filter-plain-text)
1919 (let ((transcoder (org-export-transcoder data info)))
1920 (if transcoder (funcall transcoder data info) data))
1921 info)))
1922 ;; Uninterpreted element/object: change it back to Org
1923 ;; syntax and export again resulting raw string.
1924 ((not (org-export--interpret-p data info))
1925 (org-export-data
1926 (org-export-expand
1927 data
1928 (mapconcat (lambda (blob) (org-export-data blob info))
1929 (org-element-contents data)
1930 ""))
1931 info))
1932 ;; Secondary string.
1933 ((not type)
1934 (mapconcat (lambda (obj) (org-export-data obj info)) data ""))
1935 ;; Element/Object without contents or, as a special case,
1936 ;; headline with archive tag and archived trees restricted
1937 ;; to title only.
1938 ((or (not (org-element-contents data))
1939 (and (eq type 'headline)
1940 (eq (plist-get info :with-archived-trees) 'headline)
1941 (org-element-property :archivedp data)))
1942 (let ((transcoder (org-export-transcoder data info)))
1943 (and (functionp transcoder)
1944 (funcall transcoder data nil info))))
1945 ;; Element/Object with contents.
1947 (let ((transcoder (org-export-transcoder data info)))
1948 (when transcoder
1949 (let* ((greaterp (memq type org-element-greater-elements))
1950 (objectp
1951 (and (not greaterp)
1952 (memq type org-element-recursive-objects)))
1953 (contents
1954 (mapconcat
1955 (lambda (element) (org-export-data element info))
1956 (org-element-contents
1957 (if (or greaterp objectp) data
1958 ;; Elements directly containing objects
1959 ;; must have their indentation normalized
1960 ;; first.
1961 (org-element-normalize-contents
1962 data
1963 ;; When normalizing contents of the first
1964 ;; paragraph in an item or a footnote
1965 ;; definition, ignore first line's
1966 ;; indentation: there is none and it
1967 ;; might be misleading.
1968 (when (eq type 'paragraph)
1969 (let ((parent (org-export-get-parent data)))
1970 (and
1971 (eq (car (org-element-contents parent))
1972 data)
1973 (memq (org-element-type parent)
1974 '(footnote-definition item))))))))
1975 "")))
1976 (funcall transcoder data
1977 (if (not greaterp) contents
1978 (org-element-normalize-string contents))
1979 info))))))))
1980 ;; Final result will be memoized before being returned.
1981 (puthash
1982 data
1983 (cond
1984 ((not results) nil)
1985 ((memq type '(org-data plain-text nil)) results)
1986 ;; Append the same white space between elements or objects as in
1987 ;; the original buffer, and call appropriate filters.
1989 (let ((results
1990 (org-export-filter-apply-functions
1991 (plist-get info (intern (format ":filter-%s" type)))
1992 (let ((post-blank (or (org-element-property :post-blank data)
1993 0)))
1994 (if (memq type org-element-all-elements)
1995 (concat (org-element-normalize-string results)
1996 (make-string post-blank ?\n))
1997 (concat results (make-string post-blank ? ))))
1998 info)))
1999 results)))
2000 (plist-get info :exported-data))))))
2002 (defun org-export--interpret-p (blob info)
2003 "Non-nil if element or object BLOB should be interpreted as Org syntax.
2004 Check is done according to export options INFO, stored as
2005 a plist."
2006 (case (org-element-type blob)
2007 ;; ... entities...
2008 (entity (plist-get info :with-entities))
2009 ;; ... emphasis...
2010 ((bold italic strike-through underline)
2011 (plist-get info :with-emphasize))
2012 ;; ... fixed-width areas.
2013 (fixed-width (plist-get info :with-fixed-width))
2014 ;; ... footnotes...
2015 ((footnote-definition footnote-reference)
2016 (plist-get info :with-footnotes))
2017 ;; ... sub/superscripts...
2018 ((subscript superscript)
2019 (let ((sub/super-p (plist-get info :with-sub-superscript)))
2020 (if (eq sub/super-p '{})
2021 (org-element-property :use-brackets-p blob)
2022 sub/super-p)))
2023 ;; ... tables...
2024 (table (plist-get info :with-tables))
2025 (otherwise t)))
2027 (defun org-export-expand (blob contents)
2028 "Expand a parsed element or object to its original state.
2029 BLOB is either an element or an object. CONTENTS is its
2030 contents, as a string or nil."
2031 (funcall
2032 (intern (format "org-element-%s-interpreter" (org-element-type blob)))
2033 blob contents))
2035 (defun org-export-ignore-element (element info)
2036 "Add ELEMENT to `:ignore-list' in INFO.
2038 Any element in `:ignore-list' will be skipped when using
2039 `org-element-map'. INFO is modified by side effects."
2040 (plist-put info :ignore-list (cons element (plist-get info :ignore-list))))
2044 ;;; The Filter System
2046 ;; Filters allow end-users to tweak easily the transcoded output.
2047 ;; They are the functional counterpart of hooks, as every filter in
2048 ;; a set is applied to the return value of the previous one.
2050 ;; Every set is back-end agnostic. Although, a filter is always
2051 ;; called, in addition to the string it applies to, with the back-end
2052 ;; used as argument, so it's easy for the end-user to add back-end
2053 ;; specific filters in the set. The communication channel, as
2054 ;; a plist, is required as the third argument.
2056 ;; From the developer side, filters sets can be installed in the
2057 ;; process with the help of `org-export-define-backend', which
2058 ;; internally stores filters as an alist. Each association has a key
2059 ;; among the following symbols and a function or a list of functions
2060 ;; as value.
2062 ;; - `:filter-parse-tree' applies directly on the complete parsed
2063 ;; tree. It's the only filters set that doesn't apply to a string.
2064 ;; Users can set it through `org-export-filter-parse-tree-functions'
2065 ;; variable.
2067 ;; - `:filter-final-output' applies to the final transcoded string.
2068 ;; Users can set it with `org-export-filter-final-output-functions'
2069 ;; variable
2071 ;; - `:filter-plain-text' applies to any string not recognized as Org
2072 ;; syntax. `org-export-filter-plain-text-functions' allows users to
2073 ;; configure it.
2075 ;; - `:filter-TYPE' applies on the string returned after an element or
2076 ;; object of type TYPE has been transcoded. An user can modify
2077 ;; `org-export-filter-TYPE-functions'
2079 ;; All filters sets are applied with
2080 ;; `org-export-filter-apply-functions' function. Filters in a set are
2081 ;; applied in a LIFO fashion. It allows developers to be sure that
2082 ;; their filters will be applied first.
2084 ;; Filters properties are installed in communication channel with
2085 ;; `org-export-install-filters' function.
2087 ;; Eventually, two hooks (`org-export-before-processing-hook' and
2088 ;; `org-export-before-parsing-hook') are run at the beginning of the
2089 ;; export process and just before parsing to allow for heavy structure
2090 ;; modifications.
2093 ;;;; Hooks
2095 (defvar org-export-before-processing-hook nil
2096 "Hook run at the beginning of the export process.
2098 This is run before include keywords and macros are expanded and
2099 Babel code blocks executed, on a copy of the original buffer
2100 being exported. Visibility and narrowing are preserved. Point
2101 is at the beginning of the buffer.
2103 Every function in this hook will be called with one argument: the
2104 back-end currently used, as a symbol.")
2106 (defvar org-export-before-parsing-hook nil
2107 "Hook run before parsing an export buffer.
2109 This is run after include keywords and macros have been expanded
2110 and Babel code blocks executed, on a copy of the original buffer
2111 being exported. Visibility and narrowing are preserved. Point
2112 is at the beginning of the buffer.
2114 Every function in this hook will be called with one argument: the
2115 back-end currently used, as a symbol.")
2118 ;;;; Special Filters
2120 (defvar org-export-filter-parse-tree-functions nil
2121 "List of functions applied to the parsed tree.
2122 Each filter is called with three arguments: the parse tree, as
2123 returned by `org-element-parse-buffer', the back-end, as
2124 a symbol, and the communication channel, as a plist. It must
2125 return the modified parse tree to transcode.")
2127 (defvar org-export-filter-final-output-functions nil
2128 "List of functions applied to the transcoded string.
2129 Each filter is called with three arguments: the full transcoded
2130 string, the back-end, as a symbol, and the communication channel,
2131 as a plist. It must return a string that will be used as the
2132 final export output.")
2134 (defvar org-export-filter-plain-text-functions nil
2135 "List of functions applied to plain text.
2136 Each filter is called with three arguments: a string which
2137 contains no Org syntax, the back-end, as a symbol, and the
2138 communication channel, as a plist. It must return a string or
2139 nil.")
2142 ;;;; Elements Filters
2144 (defvar org-export-filter-babel-call-functions nil
2145 "List of functions applied to a transcoded babel-call.
2146 Each filter is called with three arguments: the transcoded data,
2147 as a string, the back-end, as a symbol, and the communication
2148 channel, as a plist. It must return a string or nil.")
2150 (defvar org-export-filter-center-block-functions nil
2151 "List of functions applied to a transcoded center block.
2152 Each filter is called with three arguments: the transcoded data,
2153 as a string, the back-end, as a symbol, and the communication
2154 channel, as a plist. It must return a string or nil.")
2156 (defvar org-export-filter-clock-functions nil
2157 "List of functions applied to a transcoded clock.
2158 Each filter is called with three arguments: the transcoded data,
2159 as a string, the back-end, as a symbol, and the communication
2160 channel, as a plist. It must return a string or nil.")
2162 (defvar org-export-filter-comment-functions nil
2163 "List of functions applied to a transcoded comment.
2164 Each filter is called with three arguments: the transcoded data,
2165 as a string, the back-end, as a symbol, and the communication
2166 channel, as a plist. It must return a string or nil.")
2168 (defvar org-export-filter-comment-block-functions nil
2169 "List of functions applied to a transcoded comment-block.
2170 Each filter is called with three arguments: the transcoded data,
2171 as a string, the back-end, as a symbol, and the communication
2172 channel, as a plist. It must return a string or nil.")
2174 (defvar org-export-filter-diary-sexp-functions nil
2175 "List of functions applied to a transcoded diary-sexp.
2176 Each filter is called with three arguments: the transcoded data,
2177 as a string, the back-end, as a symbol, and the communication
2178 channel, as a plist. It must return a string or nil.")
2180 (defvar org-export-filter-drawer-functions nil
2181 "List of functions applied to a transcoded drawer.
2182 Each filter is called with three arguments: the transcoded data,
2183 as a string, the back-end, as a symbol, and the communication
2184 channel, as a plist. It must return a string or nil.")
2186 (defvar org-export-filter-dynamic-block-functions nil
2187 "List of functions applied to a transcoded dynamic-block.
2188 Each filter is called with three arguments: the transcoded data,
2189 as a string, the back-end, as a symbol, and the communication
2190 channel, as a plist. It must return a string or nil.")
2192 (defvar org-export-filter-example-block-functions nil
2193 "List of functions applied to a transcoded example-block.
2194 Each filter is called with three arguments: the transcoded data,
2195 as a string, the back-end, as a symbol, and the communication
2196 channel, as a plist. It must return a string or nil.")
2198 (defvar org-export-filter-export-block-functions nil
2199 "List of functions applied to a transcoded export-block.
2200 Each filter is called with three arguments: the transcoded data,
2201 as a string, the back-end, as a symbol, and the communication
2202 channel, as a plist. It must return a string or nil.")
2204 (defvar org-export-filter-fixed-width-functions nil
2205 "List of functions applied to a transcoded fixed-width.
2206 Each filter is called with three arguments: the transcoded data,
2207 as a string, the back-end, as a symbol, and the communication
2208 channel, as a plist. It must return a string or nil.")
2210 (defvar org-export-filter-footnote-definition-functions nil
2211 "List of functions applied to a transcoded footnote-definition.
2212 Each filter is called with three arguments: the transcoded data,
2213 as a string, the back-end, as a symbol, and the communication
2214 channel, as a plist. It must return a string or nil.")
2216 (defvar org-export-filter-headline-functions nil
2217 "List of functions applied to a transcoded headline.
2218 Each filter is called with three arguments: the transcoded data,
2219 as a string, the back-end, as a symbol, and the communication
2220 channel, as a plist. It must return a string or nil.")
2222 (defvar org-export-filter-horizontal-rule-functions nil
2223 "List of functions applied to a transcoded horizontal-rule.
2224 Each filter is called with three arguments: the transcoded data,
2225 as a string, the back-end, as a symbol, and the communication
2226 channel, as a plist. It must return a string or nil.")
2228 (defvar org-export-filter-inlinetask-functions nil
2229 "List of functions applied to a transcoded inlinetask.
2230 Each filter is called with three arguments: the transcoded data,
2231 as a string, the back-end, as a symbol, and the communication
2232 channel, as a plist. It must return a string or nil.")
2234 (defvar org-export-filter-item-functions nil
2235 "List of functions applied to a transcoded item.
2236 Each filter is called with three arguments: the transcoded data,
2237 as a string, the back-end, as a symbol, and the communication
2238 channel, as a plist. It must return a string or nil.")
2240 (defvar org-export-filter-keyword-functions nil
2241 "List of functions applied to a transcoded keyword.
2242 Each filter is called with three arguments: the transcoded data,
2243 as a string, the back-end, as a symbol, and the communication
2244 channel, as a plist. It must return a string or nil.")
2246 (defvar org-export-filter-latex-environment-functions nil
2247 "List of functions applied to a transcoded latex-environment.
2248 Each filter is called with three arguments: the transcoded data,
2249 as a string, the back-end, as a symbol, and the communication
2250 channel, as a plist. It must return a string or nil.")
2252 (defvar org-export-filter-node-property-functions nil
2253 "List of functions applied to a transcoded node-property.
2254 Each filter is called with three arguments: the transcoded data,
2255 as a string, the back-end, as a symbol, and the communication
2256 channel, as a plist. It must return a string or nil.")
2258 (defvar org-export-filter-paragraph-functions nil
2259 "List of functions applied to a transcoded paragraph.
2260 Each filter is called with three arguments: the transcoded data,
2261 as a string, the back-end, as a symbol, and the communication
2262 channel, as a plist. It must return a string or nil.")
2264 (defvar org-export-filter-plain-list-functions nil
2265 "List of functions applied to a transcoded plain-list.
2266 Each filter is called with three arguments: the transcoded data,
2267 as a string, the back-end, as a symbol, and the communication
2268 channel, as a plist. It must return a string or nil.")
2270 (defvar org-export-filter-planning-functions nil
2271 "List of functions applied to a transcoded planning.
2272 Each filter is called with three arguments: the transcoded data,
2273 as a string, the back-end, as a symbol, and the communication
2274 channel, as a plist. It must return a string or nil.")
2276 (defvar org-export-filter-property-drawer-functions nil
2277 "List of functions applied to a transcoded property-drawer.
2278 Each filter is called with three arguments: the transcoded data,
2279 as a string, the back-end, as a symbol, and the communication
2280 channel, as a plist. It must return a string or nil.")
2282 (defvar org-export-filter-quote-block-functions nil
2283 "List of functions applied to a transcoded quote block.
2284 Each filter is called with three arguments: the transcoded quote
2285 data, as a string, the back-end, as a symbol, and the
2286 communication channel, as a plist. It must return a string or
2287 nil.")
2289 (defvar org-export-filter-quote-section-functions nil
2290 "List of functions applied to a transcoded quote-section.
2291 Each filter is called with three arguments: the transcoded data,
2292 as a string, the back-end, as a symbol, and the communication
2293 channel, as a plist. It must return a string or nil.")
2295 (defvar org-export-filter-section-functions nil
2296 "List of functions applied to a transcoded section.
2297 Each filter is called with three arguments: the transcoded data,
2298 as a string, the back-end, as a symbol, and the communication
2299 channel, as a plist. It must return a string or nil.")
2301 (defvar org-export-filter-special-block-functions nil
2302 "List of functions applied to a transcoded special block.
2303 Each filter is called with three arguments: the transcoded data,
2304 as a string, the back-end, as a symbol, and the communication
2305 channel, as a plist. It must return a string or nil.")
2307 (defvar org-export-filter-src-block-functions nil
2308 "List of functions applied to a transcoded src-block.
2309 Each filter is called with three arguments: the transcoded data,
2310 as a string, the back-end, as a symbol, and the communication
2311 channel, as a plist. It must return a string or nil.")
2313 (defvar org-export-filter-table-functions nil
2314 "List of functions applied to a transcoded table.
2315 Each filter is called with three arguments: the transcoded data,
2316 as a string, the back-end, as a symbol, and the communication
2317 channel, as a plist. It must return a string or nil.")
2319 (defvar org-export-filter-table-cell-functions nil
2320 "List of functions applied to a transcoded table-cell.
2321 Each filter is called with three arguments: the transcoded data,
2322 as a string, the back-end, as a symbol, and the communication
2323 channel, as a plist. It must return a string or nil.")
2325 (defvar org-export-filter-table-row-functions nil
2326 "List of functions applied to a transcoded table-row.
2327 Each filter is called with three arguments: the transcoded data,
2328 as a string, the back-end, as a symbol, and the communication
2329 channel, as a plist. It must return a string or nil.")
2331 (defvar org-export-filter-verse-block-functions nil
2332 "List of functions applied to a transcoded verse block.
2333 Each filter is called with three arguments: the transcoded data,
2334 as a string, the back-end, as a symbol, and the communication
2335 channel, as a plist. It must return a string or nil.")
2338 ;;;; Objects Filters
2340 (defvar org-export-filter-bold-functions nil
2341 "List of functions applied to transcoded bold text.
2342 Each filter is called with three arguments: the transcoded data,
2343 as a string, the back-end, as a symbol, and the communication
2344 channel, as a plist. It must return a string or nil.")
2346 (defvar org-export-filter-code-functions nil
2347 "List of functions applied to transcoded code text.
2348 Each filter is called with three arguments: the transcoded data,
2349 as a string, the back-end, as a symbol, and the communication
2350 channel, as a plist. It must return a string or nil.")
2352 (defvar org-export-filter-entity-functions nil
2353 "List of functions applied to a transcoded entity.
2354 Each filter is called with three arguments: the transcoded data,
2355 as a string, the back-end, as a symbol, and the communication
2356 channel, as a plist. It must return a string or nil.")
2358 (defvar org-export-filter-export-snippet-functions nil
2359 "List of functions applied to a transcoded export-snippet.
2360 Each filter is called with three arguments: the transcoded data,
2361 as a string, the back-end, as a symbol, and the communication
2362 channel, as a plist. It must return a string or nil.")
2364 (defvar org-export-filter-footnote-reference-functions nil
2365 "List of functions applied to a transcoded footnote-reference.
2366 Each filter is called with three arguments: the transcoded data,
2367 as a string, the back-end, as a symbol, and the communication
2368 channel, as a plist. It must return a string or nil.")
2370 (defvar org-export-filter-inline-babel-call-functions nil
2371 "List of functions applied to a transcoded inline-babel-call.
2372 Each filter is called with three arguments: the transcoded data,
2373 as a string, the back-end, as a symbol, and the communication
2374 channel, as a plist. It must return a string or nil.")
2376 (defvar org-export-filter-inline-src-block-functions nil
2377 "List of functions applied to a transcoded inline-src-block.
2378 Each filter is called with three arguments: the transcoded data,
2379 as a string, the back-end, as a symbol, and the communication
2380 channel, as a plist. It must return a string or nil.")
2382 (defvar org-export-filter-italic-functions nil
2383 "List of functions applied to transcoded italic text.
2384 Each filter is called with three arguments: the transcoded data,
2385 as a string, the back-end, as a symbol, and the communication
2386 channel, as a plist. It must return a string or nil.")
2388 (defvar org-export-filter-latex-fragment-functions nil
2389 "List of functions applied to a transcoded latex-fragment.
2390 Each filter is called with three arguments: the transcoded data,
2391 as a string, the back-end, as a symbol, and the communication
2392 channel, as a plist. It must return a string or nil.")
2394 (defvar org-export-filter-line-break-functions nil
2395 "List of functions applied to a transcoded line-break.
2396 Each filter is called with three arguments: the transcoded data,
2397 as a string, the back-end, as a symbol, and the communication
2398 channel, as a plist. It must return a string or nil.")
2400 (defvar org-export-filter-link-functions nil
2401 "List of functions applied to a transcoded link.
2402 Each filter is called with three arguments: the transcoded data,
2403 as a string, the back-end, as a symbol, and the communication
2404 channel, as a plist. It must return a string or nil.")
2406 (defvar org-export-filter-macro-functions nil
2407 "List of functions applied to a transcoded macro.
2408 Each filter is called with three arguments: the transcoded data,
2409 as a string, the back-end, as a symbol, and the communication
2410 channel, as a plist. It must return a string or nil.")
2412 (defvar org-export-filter-radio-target-functions nil
2413 "List of functions applied to a transcoded radio-target.
2414 Each filter is called with three arguments: the transcoded data,
2415 as a string, the back-end, as a symbol, and the communication
2416 channel, as a plist. It must return a string or nil.")
2418 (defvar org-export-filter-statistics-cookie-functions nil
2419 "List of functions applied to a transcoded statistics-cookie.
2420 Each filter is called with three arguments: the transcoded data,
2421 as a string, the back-end, as a symbol, and the communication
2422 channel, as a plist. It must return a string or nil.")
2424 (defvar org-export-filter-strike-through-functions nil
2425 "List of functions applied to transcoded strike-through text.
2426 Each filter is called with three arguments: the transcoded data,
2427 as a string, the back-end, as a symbol, and the communication
2428 channel, as a plist. It must return a string or nil.")
2430 (defvar org-export-filter-subscript-functions nil
2431 "List of functions applied to a transcoded subscript.
2432 Each filter is called with three arguments: the transcoded data,
2433 as a string, the back-end, as a symbol, and the communication
2434 channel, as a plist. It must return a string or nil.")
2436 (defvar org-export-filter-superscript-functions nil
2437 "List of functions applied to a transcoded superscript.
2438 Each filter is called with three arguments: the transcoded data,
2439 as a string, the back-end, as a symbol, and the communication
2440 channel, as a plist. It must return a string or nil.")
2442 (defvar org-export-filter-target-functions nil
2443 "List of functions applied to a transcoded target.
2444 Each filter is called with three arguments: the transcoded data,
2445 as a string, the back-end, as a symbol, and the communication
2446 channel, as a plist. It must return a string or nil.")
2448 (defvar org-export-filter-timestamp-functions nil
2449 "List of functions applied to a transcoded timestamp.
2450 Each filter is called with three arguments: the transcoded data,
2451 as a string, the back-end, as a symbol, and the communication
2452 channel, as a plist. It must return a string or nil.")
2454 (defvar org-export-filter-underline-functions nil
2455 "List of functions applied to transcoded underline text.
2456 Each filter is called with three arguments: the transcoded data,
2457 as a string, the back-end, as a symbol, and the communication
2458 channel, as a plist. It must return a string or nil.")
2460 (defvar org-export-filter-verbatim-functions nil
2461 "List of functions applied to transcoded verbatim text.
2462 Each filter is called with three arguments: the transcoded data,
2463 as a string, the back-end, as a symbol, and the communication
2464 channel, as a plist. It must return a string or nil.")
2467 ;;;; Filters Tools
2469 ;; Internal function `org-export-install-filters' installs filters
2470 ;; hard-coded in back-ends (developer filters) and filters from global
2471 ;; variables (user filters) in the communication channel.
2473 ;; Internal function `org-export-filter-apply-functions' takes care
2474 ;; about applying each filter in order to a given data. It ignores
2475 ;; filters returning a nil value but stops whenever a filter returns
2476 ;; an empty string.
2478 (defun org-export-filter-apply-functions (filters value info)
2479 "Call every function in FILTERS.
2481 Functions are called with arguments VALUE, current export
2482 back-end and INFO. A function returning a nil value will be
2483 skipped. If it returns the empty string, the process ends and
2484 VALUE is ignored.
2486 Call is done in a LIFO fashion, to be sure that developer
2487 specified filters, if any, are called first."
2488 (catch 'exit
2489 (dolist (filter filters value)
2490 (let ((result (funcall filter value (plist-get info :back-end) info)))
2491 (cond ((not result) value)
2492 ((equal value "") (throw 'exit nil))
2493 (t (setq value result)))))))
2495 (defun org-export-install-filters (info)
2496 "Install filters properties in communication channel.
2498 INFO is a plist containing the current communication channel.
2500 Return the updated communication channel."
2501 (let (plist)
2502 ;; Install user defined filters with `org-export-filters-alist'.
2503 (mapc (lambda (p)
2504 (setq plist (plist-put plist (car p) (eval (cdr p)))))
2505 org-export-filters-alist)
2506 ;; Prepend back-end specific filters to that list.
2507 (mapc (lambda (p)
2508 ;; Single values get consed, lists are prepended.
2509 (let ((key (car p)) (value (cdr p)))
2510 (when value
2511 (setq plist
2512 (plist-put
2513 plist key
2514 (if (atom value) (cons value (plist-get plist key))
2515 (append value (plist-get plist key))))))))
2516 (org-export-backend-filters (plist-get info :back-end)))
2517 ;; Return new communication channel.
2518 (org-combine-plists info plist)))
2522 ;;; Core functions
2524 ;; This is the room for the main function, `org-export-as', along with
2525 ;; its derivatives, `org-export-to-buffer' and `org-export-to-file'.
2526 ;; They differ only by the way they output the resulting code.
2528 ;; `org-export-output-file-name' is an auxiliary function meant to be
2529 ;; used with `org-export-to-file'. With a given extension, it tries
2530 ;; to provide a canonical file name to write export output to.
2532 ;; Note that `org-export-as' doesn't really parse the current buffer,
2533 ;; but a copy of it (with the same buffer-local variables and
2534 ;; visibility), where macros and include keywords are expanded and
2535 ;; Babel blocks are executed, if appropriate.
2536 ;; `org-export-with-current-buffer-copy' macro prepares that copy.
2538 ;; File inclusion is taken care of by
2539 ;; `org-export-expand-include-keyword' and
2540 ;; `org-export--prepare-file-contents'. Structure wise, including
2541 ;; a whole Org file in a buffer often makes little sense. For
2542 ;; example, if the file contains an headline and the include keyword
2543 ;; was within an item, the item should contain the headline. That's
2544 ;; why file inclusion should be done before any structure can be
2545 ;; associated to the file, that is before parsing.
2547 (defun org-export-as
2548 (backend &optional subtreep visible-only body-only ext-plist noexpand)
2549 "Transcode current Org buffer into BACKEND code.
2551 If narrowing is active in the current buffer, only transcode its
2552 narrowed part.
2554 If a region is active, transcode that region.
2556 When optional argument SUBTREEP is non-nil, transcode the
2557 sub-tree at point, extracting information from the headline
2558 properties first.
2560 When optional argument VISIBLE-ONLY is non-nil, don't export
2561 contents of hidden elements.
2563 When optional argument BODY-ONLY is non-nil, only return body
2564 code, without preamble nor postamble.
2566 Optional argument EXT-PLIST, when provided, is a property list
2567 with external parameters overriding Org default settings, but
2568 still inferior to file-local settings.
2570 Optional argument NOEXPAND, when non-nil, prevents included files
2571 to be expanded and Babel code to be executed.
2573 Return code as a string."
2574 ;; Barf if BACKEND isn't registered.
2575 (org-export-barf-if-invalid-backend backend)
2576 (save-excursion
2577 (save-restriction
2578 ;; Narrow buffer to an appropriate region or subtree for
2579 ;; parsing. If parsing subtree, be sure to remove main headline
2580 ;; too.
2581 (cond ((org-region-active-p)
2582 (narrow-to-region (region-beginning) (region-end)))
2583 (subtreep
2584 (org-narrow-to-subtree)
2585 (goto-char (point-min))
2586 (forward-line)
2587 (narrow-to-region (point) (point-max))))
2588 ;; Initialize communication channel with original buffer
2589 ;; attributes, unavailable in its copy.
2590 (let ((info (org-export--get-buffer-attributes)) tree)
2591 (org-export-with-current-buffer-copy
2592 ;; Run first hook with current back-end as argument.
2593 (run-hook-with-args 'org-export-before-processing-hook backend)
2594 ;; Update communication channel and get parse tree. Buffer
2595 ;; isn't parsed directly. Instead, a temporary copy is
2596 ;; created, where include keywords, macros are expanded and
2597 ;; code blocks are evaluated.
2598 (unless noexpand
2599 (org-export-expand-include-keyword)
2600 ;; Update macro templates since #+INCLUDE keywords might
2601 ;; have added some new ones.
2602 (org-macro-initialize-templates)
2603 (org-macro-replace-all org-macro-templates)
2604 (org-export-execute-babel-code))
2605 ;; Update radio targets since keyword inclusion might have
2606 ;; added some more.
2607 (org-update-radio-target-regexp)
2608 ;; Run last hook with current back-end as argument.
2609 (goto-char (point-min))
2610 (run-hook-with-args 'org-export-before-parsing-hook backend)
2611 ;; Update communication channel with environment. Also
2612 ;; install user's and developer's filters.
2613 (setq info
2614 (org-export-install-filters
2615 (org-combine-plists
2616 info (org-export-get-environment backend subtreep ext-plist))))
2617 ;; Expand export-specific set of macros: {{{author}}},
2618 ;; {{{date}}}, {{{email}}} and {{{title}}}. It must be done
2619 ;; once regular macros have been expanded, since document
2620 ;; keywords may contain one of them.
2621 (unless noexpand
2622 (org-macro-replace-all
2623 (list (cons "author"
2624 (org-element-interpret-data (plist-get info :author)))
2625 (cons "date"
2626 (org-element-interpret-data (plist-get info :date)))
2627 ;; EMAIL is not a parsed keyword: store it as-is.
2628 (cons "email" (or (plist-get info :email) ""))
2629 (cons "title"
2630 (org-element-interpret-data (plist-get info :title))))))
2631 ;; Eventually parse buffer. Call parse-tree filters to get
2632 ;; the final tree.
2633 (setq tree
2634 (org-export-filter-apply-functions
2635 (plist-get info :filter-parse-tree)
2636 (org-element-parse-buffer nil visible-only) info)))
2637 ;; Now tree is complete, compute its properties and add them
2638 ;; to communication channel.
2639 (setq info
2640 (org-combine-plists
2641 info (org-export-collect-tree-properties tree info)))
2642 ;; Eventually transcode TREE. Wrap the resulting string into
2643 ;; a template, if required. Finally call final-output filter.
2644 (let* ((body (org-element-normalize-string
2645 (or (org-export-data tree info) "")))
2646 (template (cdr (assq 'template
2647 (plist-get info :translate-alist))))
2648 (output (org-export-filter-apply-functions
2649 (plist-get info :filter-final-output)
2650 (if (or (not (functionp template)) body-only) body
2651 (funcall template body info))
2652 info)))
2653 ;; Maybe add final OUTPUT to kill ring, then return it.
2654 (when (and org-export-copy-to-kill-ring (org-string-nw-p output))
2655 (org-kill-new output))
2656 output)))))
2658 (defun org-export-to-buffer
2659 (backend buffer &optional subtreep visible-only body-only ext-plist noexpand)
2660 "Call `org-export-as' with output to a specified buffer.
2662 BACKEND is the back-end used for transcoding, as a symbol.
2664 BUFFER is the output buffer. If it already exists, it will be
2665 erased first, otherwise, it will be created.
2667 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY, EXT-PLIST
2668 and NOEXPAND are similar to those used in `org-export-as', which
2669 see.
2671 Return buffer."
2672 (let ((out (org-export-as
2673 backend subtreep visible-only body-only ext-plist noexpand))
2674 (buffer (get-buffer-create buffer)))
2675 (with-current-buffer buffer
2676 (erase-buffer)
2677 (insert out)
2678 (goto-char (point-min)))
2679 buffer))
2681 (defun org-export-to-file
2682 (backend file &optional subtreep visible-only body-only ext-plist noexpand)
2683 "Call `org-export-as' with output to a specified file.
2685 BACKEND is the back-end used for transcoding, as a symbol. FILE
2686 is the name of the output file, as a string.
2688 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY, EXT-PLIST
2689 and NOEXPAND are similar to those used in `org-export-as', which
2690 see.
2692 Return output file's name."
2693 ;; Checks for FILE permissions. `write-file' would do the same, but
2694 ;; we'd rather avoid needless transcoding of parse tree.
2695 (unless (file-writable-p file) (error "Output file not writable"))
2696 ;; Insert contents to a temporary buffer and write it to FILE.
2697 (let ((out (org-export-as
2698 backend subtreep visible-only body-only ext-plist noexpand)))
2699 (with-temp-buffer
2700 (insert out)
2701 (let ((coding-system-for-write org-export-coding-system))
2702 (write-file file))))
2703 ;; Return full path.
2704 file)
2706 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
2707 "Return output file's name according to buffer specifications.
2709 EXTENSION is a string representing the output file extension,
2710 with the leading dot.
2712 With a non-nil optional argument SUBTREEP, try to determine
2713 output file's name by looking for \"EXPORT_FILE_NAME\" property
2714 of subtree at point.
2716 When optional argument PUB-DIR is set, use it as the publishing
2717 directory.
2719 When optional argument VISIBLE-ONLY is non-nil, don't export
2720 contents of hidden elements.
2722 Return file name as a string, or nil if it couldn't be
2723 determined."
2724 (let ((base-name
2725 ;; File name may come from EXPORT_FILE_NAME subtree property,
2726 ;; assuming point is at beginning of said sub-tree.
2727 (file-name-sans-extension
2728 (or (and subtreep
2729 (org-entry-get
2730 (save-excursion
2731 (ignore-errors (org-back-to-heading) (point)))
2732 "EXPORT_FILE_NAME" t))
2733 ;; File name may be extracted from buffer's associated
2734 ;; file, if any.
2735 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
2736 (and visited-file (file-name-nondirectory visited-file)))
2737 ;; Can't determine file name on our own: Ask user.
2738 (let ((read-file-name-function
2739 (and org-completion-use-ido 'ido-read-file-name)))
2740 (read-file-name
2741 "Output file: " pub-dir nil nil nil
2742 (lambda (name)
2743 (string= (file-name-extension name t) extension))))))))
2744 ;; Build file name. Enforce EXTENSION over whatever user may have
2745 ;; come up with. PUB-DIR, if defined, always has precedence over
2746 ;; any provided path.
2747 (cond
2748 (pub-dir
2749 (concat (file-name-as-directory pub-dir)
2750 (file-name-nondirectory base-name)
2751 extension))
2752 ((file-name-absolute-p base-name) (concat base-name extension))
2753 (t (concat (file-name-as-directory ".") base-name extension)))))
2755 (defmacro org-export-with-current-buffer-copy (&rest body)
2756 "Apply BODY in a copy of the current buffer.
2758 The copy preserves local variables and visibility of the original
2759 buffer.
2761 Point is at buffer's beginning when BODY is applied."
2762 (declare (debug (body)))
2763 (org-with-gensyms (original-buffer offset buffer-string overlays region)
2764 `(let* ((,original-buffer (current-buffer))
2765 (,region (list (point-min) (point-max)))
2766 (,buffer-string (org-with-wide-buffer (buffer-string)))
2767 (,overlays (mapcar 'copy-overlay (apply 'overlays-in ,region))))
2768 (with-temp-buffer
2769 (let ((buffer-invisibility-spec nil))
2770 (org-clone-local-variables
2771 ,original-buffer
2772 "^\\(org-\\|orgtbl-\\|major-mode$\\|outline-\\(regexp\\|level\\)$\\)")
2773 (insert ,buffer-string)
2774 (apply 'narrow-to-region ,region)
2775 (mapc (lambda (ov)
2776 (move-overlay
2777 ov (overlay-start ov) (overlay-end ov) (current-buffer)))
2778 ,overlays)
2779 (goto-char (point-min))
2780 (progn ,@body))))))
2782 (defun org-export-expand-include-keyword (&optional included dir)
2783 "Expand every include keyword in buffer.
2784 Optional argument INCLUDED is a list of included file names along
2785 with their line restriction, when appropriate. It is used to
2786 avoid infinite recursion. Optional argument DIR is the current
2787 working directory. It is used to properly resolve relative
2788 paths."
2789 (let ((case-fold-search t))
2790 (goto-char (point-min))
2791 (while (re-search-forward "^[ \t]*#\\+INCLUDE: +\\(.*\\)[ \t]*$" nil t)
2792 (when (eq (org-element-type (save-match-data (org-element-at-point)))
2793 'keyword)
2794 (beginning-of-line)
2795 ;; Extract arguments from keyword's value.
2796 (let* ((value (match-string 1))
2797 (ind (org-get-indentation))
2798 (file (and (string-match "^\"\\(\\S-+\\)\"" value)
2799 (prog1 (expand-file-name (match-string 1 value) dir)
2800 (setq value (replace-match "" nil nil value)))))
2801 (lines
2802 (and (string-match
2803 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\"" value)
2804 (prog1 (match-string 1 value)
2805 (setq value (replace-match "" nil nil value)))))
2806 (env (cond ((string-match "\\<example\\>" value) 'example)
2807 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
2808 (match-string 1 value))))
2809 ;; Minimal level of included file defaults to the child
2810 ;; level of the current headline, if any, or one. It
2811 ;; only applies is the file is meant to be included as
2812 ;; an Org one.
2813 (minlevel
2814 (and (not env)
2815 (if (string-match ":minlevel +\\([0-9]+\\)" value)
2816 (prog1 (string-to-number (match-string 1 value))
2817 (setq value (replace-match "" nil nil value)))
2818 (let ((cur (org-current-level)))
2819 (if cur (1+ (org-reduced-level cur)) 1))))))
2820 ;; Remove keyword.
2821 (delete-region (point) (progn (forward-line) (point)))
2822 (cond
2823 ((not file) (error "Invalid syntax in INCLUDE keyword"))
2824 ((not (file-readable-p file)) (error "Cannot include file %s" file))
2825 ;; Check if files has already been parsed. Look after
2826 ;; inclusion lines too, as different parts of the same file
2827 ;; can be included too.
2828 ((member (list file lines) included)
2829 (error "Recursive file inclusion: %s" file))
2831 (cond
2832 ((eq env 'example)
2833 (insert
2834 (let ((ind-str (make-string ind ? ))
2835 (contents
2836 (org-escape-code-in-string
2837 (org-export--prepare-file-contents file lines))))
2838 (format "%s#+BEGIN_EXAMPLE\n%s%s#+END_EXAMPLE\n"
2839 ind-str contents ind-str))))
2840 ((stringp env)
2841 (insert
2842 (let ((ind-str (make-string ind ? ))
2843 (contents
2844 (org-escape-code-in-string
2845 (org-export--prepare-file-contents file lines))))
2846 (format "%s#+BEGIN_SRC %s\n%s%s#+END_SRC\n"
2847 ind-str env contents ind-str))))
2849 (insert
2850 (with-temp-buffer
2851 (org-mode)
2852 (insert
2853 (org-export--prepare-file-contents file lines ind minlevel))
2854 (org-export-expand-include-keyword
2855 (cons (list file lines) included)
2856 (file-name-directory file))
2857 (buffer-string))))))))))))
2859 (defun org-export--prepare-file-contents (file &optional lines ind minlevel)
2860 "Prepare the contents of FILE for inclusion and return them as a string.
2862 When optional argument LINES is a string specifying a range of
2863 lines, include only those lines.
2865 Optional argument IND, when non-nil, is an integer specifying the
2866 global indentation of returned contents. Since its purpose is to
2867 allow an included file to stay in the same environment it was
2868 created \(i.e. a list item), it doesn't apply past the first
2869 headline encountered.
2871 Optional argument MINLEVEL, when non-nil, is an integer
2872 specifying the level that any top-level headline in the included
2873 file should have."
2874 (with-temp-buffer
2875 (insert-file-contents file)
2876 (when lines
2877 (let* ((lines (split-string lines "-"))
2878 (lbeg (string-to-number (car lines)))
2879 (lend (string-to-number (cadr lines)))
2880 (beg (if (zerop lbeg) (point-min)
2881 (goto-char (point-min))
2882 (forward-line (1- lbeg))
2883 (point)))
2884 (end (if (zerop lend) (point-max)
2885 (goto-char (point-min))
2886 (forward-line (1- lend))
2887 (point))))
2888 (narrow-to-region beg end)))
2889 ;; Remove blank lines at beginning and end of contents. The logic
2890 ;; behind that removal is that blank lines around include keyword
2891 ;; override blank lines in included file.
2892 (goto-char (point-min))
2893 (org-skip-whitespace)
2894 (beginning-of-line)
2895 (delete-region (point-min) (point))
2896 (goto-char (point-max))
2897 (skip-chars-backward " \r\t\n")
2898 (forward-line)
2899 (delete-region (point) (point-max))
2900 ;; If IND is set, preserve indentation of include keyword until
2901 ;; the first headline encountered.
2902 (when ind
2903 (unless (eq major-mode 'org-mode) (org-mode))
2904 (goto-char (point-min))
2905 (let ((ind-str (make-string ind ? )))
2906 (while (not (or (eobp) (looking-at org-outline-regexp-bol)))
2907 ;; Do not move footnote definitions out of column 0.
2908 (unless (and (looking-at org-footnote-definition-re)
2909 (eq (org-element-type (org-element-at-point))
2910 'footnote-definition))
2911 (insert ind-str))
2912 (forward-line))))
2913 ;; When MINLEVEL is specified, compute minimal level for headlines
2914 ;; in the file (CUR-MIN), and remove stars to each headline so
2915 ;; that headlines with minimal level have a level of MINLEVEL.
2916 (when minlevel
2917 (unless (eq major-mode 'org-mode) (org-mode))
2918 (org-with-limited-levels
2919 (let ((levels (org-map-entries
2920 (lambda () (org-reduced-level (org-current-level))))))
2921 (when levels
2922 (let ((offset (- minlevel (apply 'min levels))))
2923 (unless (zerop offset)
2924 (when org-odd-levels-only (setq offset (* offset 2)))
2925 ;; Only change stars, don't bother moving whole
2926 ;; sections.
2927 (org-map-entries
2928 (lambda () (if (< offset 0) (delete-char (abs offset))
2929 (insert (make-string offset ?*)))))))))))
2930 (org-element-normalize-string (buffer-string))))
2932 (defun org-export-execute-babel-code ()
2933 "Execute every Babel code in the visible part of current buffer.
2934 This function will return an error if the current buffer is
2935 visiting a file."
2936 ;; Get a pristine copy of current buffer so Babel references can be
2937 ;; properly resolved.
2938 (let* (clone-buffer-hook (reference (clone-buffer)))
2939 (unwind-protect (let ((org-current-export-file reference))
2940 (org-export-blocks-preprocess))
2941 (kill-buffer reference))))
2945 ;;; Tools For Back-Ends
2947 ;; A whole set of tools is available to help build new exporters. Any
2948 ;; function general enough to have its use across many back-ends
2949 ;; should be added here.
2951 ;;;; For Affiliated Keywords
2953 ;; `org-export-read-attribute' reads a property from a given element
2954 ;; as a plist. It can be used to normalize affiliated keywords'
2955 ;; syntax.
2957 ;; Since captions can span over multiple lines and accept dual values,
2958 ;; their internal representation is a bit tricky. Therefore,
2959 ;; `org-export-get-caption' transparently returns a given element's
2960 ;; caption as a secondary string.
2962 (defun org-export-read-attribute (attribute element &optional property)
2963 "Turn ATTRIBUTE property from ELEMENT into a plist.
2965 When optional argument PROPERTY is non-nil, return the value of
2966 that property within attributes.
2968 This function assumes attributes are defined as \":keyword
2969 value\" pairs. It is appropriate for `:attr_html' like
2970 properties."
2971 (let ((attributes
2972 (let ((value (org-element-property attribute element)))
2973 (and value
2974 (read (format "(%s)" (mapconcat 'identity value " ")))))))
2975 (if property (plist-get attributes property) attributes)))
2977 (defun org-export-get-caption (element &optional shortp)
2978 "Return caption from ELEMENT as a secondary string.
2980 When optional argument SHORTP is non-nil, return short caption,
2981 as a secondary string, instead.
2983 Caption lines are separated by a white space."
2984 (let ((full-caption (org-element-property :caption element)) caption)
2985 (dolist (line full-caption (cdr caption))
2986 (let ((cap (funcall (if shortp 'cdr 'car) line)))
2987 (when cap
2988 (setq caption (nconc (list " ") (copy-sequence cap) caption)))))))
2991 ;;;; For Derived Back-ends
2993 ;; `org-export-with-backend' is a function allowing to locally use
2994 ;; another back-end to transcode some object or element. In a derived
2995 ;; back-end, it may be used as a fall-back function once all specific
2996 ;; cases have been treated.
2998 (defun org-export-with-backend (back-end data &optional contents info)
2999 "Call a transcoder from BACK-END on DATA.
3000 CONTENTS, when non-nil, is the transcoded contents of DATA
3001 element, as a string. INFO, when non-nil, is the communication
3002 channel used for export, as a plist.."
3003 (org-export-barf-if-invalid-backend back-end)
3004 (let ((type (org-element-type data)))
3005 (if (memq type '(nil org-data)) (error "No foreign transcoder available")
3006 (let ((transcoder
3007 (cdr (assq type (org-export-backend-translate-table back-end)))))
3008 (if (functionp transcoder) (funcall transcoder data contents info)
3009 (error "No foreign transcoder available"))))))
3012 ;;;; For Export Snippets
3014 ;; Every export snippet is transmitted to the back-end. Though, the
3015 ;; latter will only retain one type of export-snippet, ignoring
3016 ;; others, based on the former's target back-end. The function
3017 ;; `org-export-snippet-backend' returns that back-end for a given
3018 ;; export-snippet.
3020 (defun org-export-snippet-backend (export-snippet)
3021 "Return EXPORT-SNIPPET targeted back-end as a symbol.
3022 Translation, with `org-export-snippet-translation-alist', is
3023 applied."
3024 (let ((back-end (org-element-property :back-end export-snippet)))
3025 (intern
3026 (or (cdr (assoc back-end org-export-snippet-translation-alist))
3027 back-end))))
3030 ;;;; For Footnotes
3032 ;; `org-export-collect-footnote-definitions' is a tool to list
3033 ;; actually used footnotes definitions in the whole parse tree, or in
3034 ;; an headline, in order to add footnote listings throughout the
3035 ;; transcoded data.
3037 ;; `org-export-footnote-first-reference-p' is a predicate used by some
3038 ;; back-ends, when they need to attach the footnote definition only to
3039 ;; the first occurrence of the corresponding label.
3041 ;; `org-export-get-footnote-definition' and
3042 ;; `org-export-get-footnote-number' provide easier access to
3043 ;; additional information relative to a footnote reference.
3045 (defun org-export-collect-footnote-definitions (data info)
3046 "Return an alist between footnote numbers, labels and definitions.
3048 DATA is the parse tree from which definitions are collected.
3049 INFO is the plist used as a communication channel.
3051 Definitions are sorted by order of references. They either
3052 appear as Org data or as a secondary string for inlined
3053 footnotes. Unreferenced definitions are ignored."
3054 (let* (num-alist
3055 collect-fn ; for byte-compiler.
3056 (collect-fn
3057 (function
3058 (lambda (data)
3059 ;; Collect footnote number, label and definition in DATA.
3060 (org-element-map
3061 data 'footnote-reference
3062 (lambda (fn)
3063 (when (org-export-footnote-first-reference-p fn info)
3064 (let ((def (org-export-get-footnote-definition fn info)))
3065 (push
3066 (list (org-export-get-footnote-number fn info)
3067 (org-element-property :label fn)
3068 def)
3069 num-alist)
3070 ;; Also search in definition for nested footnotes.
3071 (when (eq (org-element-property :type fn) 'standard)
3072 (funcall collect-fn def)))))
3073 ;; Don't enter footnote definitions since it will happen
3074 ;; when their first reference is found.
3075 info nil 'footnote-definition)))))
3076 (funcall collect-fn (plist-get info :parse-tree))
3077 (reverse num-alist)))
3079 (defun org-export-footnote-first-reference-p (footnote-reference info)
3080 "Non-nil when a footnote reference is the first one for its label.
3082 FOOTNOTE-REFERENCE is the footnote reference being considered.
3083 INFO is the plist used as a communication channel."
3084 (let ((label (org-element-property :label footnote-reference)))
3085 ;; Anonymous footnotes are always a first reference.
3086 (if (not label) t
3087 ;; Otherwise, return the first footnote with the same LABEL and
3088 ;; test if it is equal to FOOTNOTE-REFERENCE.
3089 (let* (search-refs ; for byte-compiler.
3090 (search-refs
3091 (function
3092 (lambda (data)
3093 (org-element-map
3094 data 'footnote-reference
3095 (lambda (fn)
3096 (cond
3097 ((string= (org-element-property :label fn) label)
3098 (throw 'exit fn))
3099 ;; If FN isn't inlined, be sure to traverse its
3100 ;; definition before resuming search. See
3101 ;; comments in `org-export-get-footnote-number'
3102 ;; for more information.
3103 ((eq (org-element-property :type fn) 'standard)
3104 (funcall search-refs
3105 (org-export-get-footnote-definition fn info)))))
3106 ;; Don't enter footnote definitions since it will
3107 ;; happen when their first reference is found.
3108 info 'first-match 'footnote-definition)))))
3109 (eq (catch 'exit (funcall search-refs (plist-get info :parse-tree)))
3110 footnote-reference)))))
3112 (defun org-export-get-footnote-definition (footnote-reference info)
3113 "Return definition of FOOTNOTE-REFERENCE as parsed data.
3114 INFO is the plist used as a communication channel."
3115 (let ((label (org-element-property :label footnote-reference)))
3116 (or (org-element-property :inline-definition footnote-reference)
3117 (cdr (assoc label (plist-get info :footnote-definition-alist))))))
3119 (defun org-export-get-footnote-number (footnote info)
3120 "Return number associated to a footnote.
3122 FOOTNOTE is either a footnote reference or a footnote definition.
3123 INFO is the plist used as a communication channel."
3124 (let* ((label (org-element-property :label footnote))
3125 seen-refs
3126 search-ref ; For byte-compiler.
3127 (search-ref
3128 (function
3129 (lambda (data)
3130 ;; Search footnote references through DATA, filling
3131 ;; SEEN-REFS along the way.
3132 (org-element-map
3133 data 'footnote-reference
3134 (lambda (fn)
3135 (let ((fn-lbl (org-element-property :label fn)))
3136 (cond
3137 ;; Anonymous footnote match: return number.
3138 ((and (not fn-lbl) (eq fn footnote))
3139 (throw 'exit (1+ (length seen-refs))))
3140 ;; Labels match: return number.
3141 ((and label (string= label fn-lbl))
3142 (throw 'exit (1+ (length seen-refs))))
3143 ;; Anonymous footnote: it's always a new one. Also,
3144 ;; be sure to return nil from the `cond' so
3145 ;; `first-match' doesn't get us out of the loop.
3146 ((not fn-lbl) (push 'inline seen-refs) nil)
3147 ;; Label not seen so far: add it so SEEN-REFS.
3149 ;; Also search for subsequent references in
3150 ;; footnote definition so numbering follows reading
3151 ;; logic. Note that we don't have to care about
3152 ;; inline definitions, since `org-element-map'
3153 ;; already traverses them at the right time.
3155 ;; Once again, return nil to stay in the loop.
3156 ((not (member fn-lbl seen-refs))
3157 (push fn-lbl seen-refs)
3158 (funcall search-ref
3159 (org-export-get-footnote-definition fn info))
3160 nil))))
3161 ;; Don't enter footnote definitions since it will happen
3162 ;; when their first reference is found.
3163 info 'first-match 'footnote-definition)))))
3164 (catch 'exit (funcall search-ref (plist-get info :parse-tree)))))
3167 ;;;; For Headlines
3169 ;; `org-export-get-relative-level' is a shortcut to get headline
3170 ;; level, relatively to the lower headline level in the parsed tree.
3172 ;; `org-export-get-headline-number' returns the section number of an
3173 ;; headline, while `org-export-number-to-roman' allows to convert it
3174 ;; to roman numbers.
3176 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
3177 ;; `org-export-last-sibling-p' are three useful predicates when it
3178 ;; comes to fulfill the `:headline-levels' property.
3180 ;; `org-export-get-tags', `org-export-get-category' and
3181 ;; `org-export-get-node-property' extract useful information from an
3182 ;; headline or a parent headline. They all handle inheritance.
3184 (defun org-export-get-relative-level (headline info)
3185 "Return HEADLINE relative level within current parsed tree.
3186 INFO is a plist holding contextual information."
3187 (+ (org-element-property :level headline)
3188 (or (plist-get info :headline-offset) 0)))
3190 (defun org-export-low-level-p (headline info)
3191 "Non-nil when HEADLINE is considered as low level.
3193 INFO is a plist used as a communication channel.
3195 A low level headlines has a relative level greater than
3196 `:headline-levels' property value.
3198 Return value is the difference between HEADLINE relative level
3199 and the last level being considered as high enough, or nil."
3200 (let ((limit (plist-get info :headline-levels)))
3201 (when (wholenump limit)
3202 (let ((level (org-export-get-relative-level headline info)))
3203 (and (> level limit) (- level limit))))))
3205 (defun org-export-get-headline-number (headline info)
3206 "Return HEADLINE numbering as a list of numbers.
3207 INFO is a plist holding contextual information."
3208 (cdr (assoc headline (plist-get info :headline-numbering))))
3210 (defun org-export-numbered-headline-p (headline info)
3211 "Return a non-nil value if HEADLINE element should be numbered.
3212 INFO is a plist used as a communication channel."
3213 (let ((sec-num (plist-get info :section-numbers))
3214 (level (org-export-get-relative-level headline info)))
3215 (if (wholenump sec-num) (<= level sec-num) sec-num)))
3217 (defun org-export-number-to-roman (n)
3218 "Convert integer N into a roman numeral."
3219 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
3220 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
3221 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
3222 ( 1 . "I")))
3223 (res ""))
3224 (if (<= n 0)
3225 (number-to-string n)
3226 (while roman
3227 (if (>= n (caar roman))
3228 (setq n (- n (caar roman))
3229 res (concat res (cdar roman)))
3230 (pop roman)))
3231 res)))
3233 (defun org-export-get-tags (element info &optional tags inherited)
3234 "Return list of tags associated to ELEMENT.
3236 ELEMENT has either an `headline' or an `inlinetask' type. INFO
3237 is a plist used as a communication channel.
3239 Select tags (see `org-export-select-tags') and exclude tags (see
3240 `org-export-exclude-tags') are removed from the list.
3242 When non-nil, optional argument TAGS should be a list of strings.
3243 Any tag belonging to this list will also be removed.
3245 When optional argument INHERITED is non-nil, tags can also be
3246 inherited from parent headlines and FILETAGS keywords."
3247 (org-remove-if
3248 (lambda (tag) (or (member tag (plist-get info :select-tags))
3249 (member tag (plist-get info :exclude-tags))
3250 (member tag tags)))
3251 (if (not inherited) (org-element-property :tags element)
3252 ;; Build complete list of inherited tags.
3253 (let ((current-tag-list (org-element-property :tags element)))
3254 (mapc
3255 (lambda (parent)
3256 (mapc
3257 (lambda (tag)
3258 (when (and (memq (org-element-type parent) '(headline inlinetask))
3259 (not (member tag current-tag-list)))
3260 (push tag current-tag-list)))
3261 (org-element-property :tags parent)))
3262 (org-export-get-genealogy element))
3263 ;; Add FILETAGS keywords and return results.
3264 (org-uniquify (append (plist-get info :filetags) current-tag-list))))))
3266 (defun org-export-get-node-property (property blob &optional inherited)
3267 "Return node PROPERTY value for BLOB.
3269 PROPERTY is normalized symbol (i.e. `:cookie-data'). BLOB is an
3270 element or object.
3272 If optional argument INHERITED is non-nil, the value can be
3273 inherited from a parent headline.
3275 Return value is a string or nil."
3276 (let ((headline (if (eq (org-element-type blob) 'headline) blob
3277 (org-export-get-parent-headline blob))))
3278 (if (not inherited) (org-element-property property blob)
3279 (let ((parent headline) value)
3280 (catch 'found
3281 (while parent
3282 (when (plist-member (nth 1 parent) property)
3283 (throw 'found (org-element-property property parent)))
3284 (setq parent (org-element-property :parent parent))))))))
3286 (defun org-export-get-category (blob info)
3287 "Return category for element or object BLOB.
3289 INFO is a plist used as a communication channel.
3291 CATEGORY is automatically inherited from a parent headline, from
3292 #+CATEGORY: keyword or created out of original file name. If all
3293 fail, the fall-back value is \"???\"."
3294 (or (let ((headline (if (eq (org-element-type blob) 'headline) blob
3295 (org-export-get-parent-headline blob))))
3296 ;; Almost like `org-export-node-property', but we cannot trust
3297 ;; `plist-member' as every headline has a `:category'
3298 ;; property, would it be nil or equal to "???" (which has the
3299 ;; same meaning).
3300 (let ((parent headline) value)
3301 (catch 'found
3302 (while parent
3303 (let ((category (org-element-property :category parent)))
3304 (and category (not (equal "???" category))
3305 (throw 'found category)))
3306 (setq parent (org-element-property :parent parent))))))
3307 (org-element-map
3308 (plist-get info :parse-tree) 'keyword
3309 (lambda (kwd)
3310 (when (equal (org-element-property :key kwd) "CATEGORY")
3311 (org-element-property :value kwd)))
3312 info 'first-match)
3313 (let ((file (plist-get info :input-file)))
3314 (and file (file-name-sans-extension (file-name-nondirectory file))))
3315 "???"))
3317 (defun org-export-first-sibling-p (headline info)
3318 "Non-nil when HEADLINE is the first sibling in its sub-tree.
3319 INFO is a plist used as a communication channel."
3320 (not (eq (org-element-type (org-export-get-previous-element headline info))
3321 'headline)))
3323 (defun org-export-last-sibling-p (headline info)
3324 "Non-nil when HEADLINE is the last sibling in its sub-tree.
3325 INFO is a plist used as a communication channel."
3326 (not (org-export-get-next-element headline info)))
3329 ;;;; For Links
3331 ;; `org-export-solidify-link-text' turns a string into a safer version
3332 ;; for links, replacing most non-standard characters with hyphens.
3334 ;; `org-export-get-coderef-format' returns an appropriate format
3335 ;; string for coderefs.
3337 ;; `org-export-inline-image-p' returns a non-nil value when the link
3338 ;; provided should be considered as an inline image.
3340 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
3341 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
3342 ;; returns an appropriate unique identifier when found, or nil.
3344 ;; `org-export-resolve-id-link' returns the first headline with
3345 ;; specified id or custom-id in parse tree, the path to the external
3346 ;; file with the id or nil when neither was found.
3348 ;; `org-export-resolve-coderef' associates a reference to a line
3349 ;; number in the element it belongs, or returns the reference itself
3350 ;; when the element isn't numbered.
3352 (defun org-export-solidify-link-text (s)
3353 "Take link text S and make a safe target out of it."
3354 (save-match-data
3355 (mapconcat 'identity (org-split-string s "[^a-zA-Z0-9_.-:]+") "-")))
3357 (defun org-export-get-coderef-format (path desc)
3358 "Return format string for code reference link.
3359 PATH is the link path. DESC is its description."
3360 (save-match-data
3361 (cond ((not desc) "%s")
3362 ((string-match (regexp-quote (concat "(" path ")")) desc)
3363 (replace-match "%s" t t desc))
3364 (t desc))))
3366 (defun org-export-inline-image-p (link &optional rules)
3367 "Non-nil if LINK object points to an inline image.
3369 Optional argument is a set of RULES defining inline images. It
3370 is an alist where associations have the following shape:
3372 \(TYPE . REGEXP)
3374 Applying a rule means apply REGEXP against LINK's path when its
3375 type is TYPE. The function will return a non-nil value if any of
3376 the provided rules is non-nil. The default rule is
3377 `org-export-default-inline-image-rule'.
3379 This only applies to links without a description."
3380 (and (not (org-element-contents link))
3381 (let ((case-fold-search t)
3382 (rules (or rules org-export-default-inline-image-rule)))
3383 (catch 'exit
3384 (mapc
3385 (lambda (rule)
3386 (and (string= (org-element-property :type link) (car rule))
3387 (string-match (cdr rule)
3388 (org-element-property :path link))
3389 (throw 'exit t)))
3390 rules)
3391 ;; Return nil if no rule matched.
3392 nil))))
3394 (defun org-export-resolve-coderef (ref info)
3395 "Resolve a code reference REF.
3397 INFO is a plist used as a communication channel.
3399 Return associated line number in source code, or REF itself,
3400 depending on src-block or example element's switches."
3401 (org-element-map
3402 (plist-get info :parse-tree) '(example-block src-block)
3403 (lambda (el)
3404 (with-temp-buffer
3405 (insert (org-trim (org-element-property :value el)))
3406 (let* ((label-fmt (regexp-quote
3407 (or (org-element-property :label-fmt el)
3408 org-coderef-label-format)))
3409 (ref-re
3410 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
3411 (replace-regexp-in-string "%s" ref label-fmt nil t))))
3412 ;; Element containing REF is found. Resolve it to either
3413 ;; a label or a line number, as needed.
3414 (when (re-search-backward ref-re nil t)
3415 (cond
3416 ((org-element-property :use-labels el) ref)
3417 ((eq (org-element-property :number-lines el) 'continued)
3418 (+ (org-export-get-loc el info) (line-number-at-pos)))
3419 (t (line-number-at-pos)))))))
3420 info 'first-match))
3422 (defun org-export-resolve-fuzzy-link (link info)
3423 "Return LINK destination.
3425 INFO is a plist holding contextual information.
3427 Return value can be an object, an element, or nil:
3429 - If LINK path matches a target object (i.e. <<path>>) or
3430 element (i.e. \"#+TARGET: path\"), return it.
3432 - If LINK path exactly matches the name affiliated keyword
3433 \(i.e. #+NAME: path) of an element, return that element.
3435 - If LINK path exactly matches any headline name, return that
3436 element. If more than one headline share that name, priority
3437 will be given to the one with the closest common ancestor, if
3438 any, or the first one in the parse tree otherwise.
3440 - Otherwise, return nil.
3442 Assume LINK type is \"fuzzy\"."
3443 (let* ((path (org-element-property :path link))
3444 (match-title-p (eq (aref path 0) ?*)))
3445 (cond
3446 ;; First try to find a matching "<<path>>" unless user specified
3447 ;; he was looking for an headline (path starts with a *
3448 ;; character).
3449 ((and (not match-title-p)
3450 (loop for target in (plist-get info :target-list)
3451 when (string= (org-element-property :value target) path)
3452 return target)))
3453 ;; Then try to find an element with a matching "#+NAME: path"
3454 ;; affiliated keyword.
3455 ((and (not match-title-p)
3456 (org-element-map
3457 (plist-get info :parse-tree) org-element-all-elements
3458 (lambda (el)
3459 (when (string= (org-element-property :name el) path) el))
3460 info 'first-match)))
3461 ;; Last case: link either points to an headline or to
3462 ;; nothingness. Try to find the source, with priority given to
3463 ;; headlines with the closest common ancestor. If such candidate
3464 ;; is found, return it, otherwise return nil.
3466 (let ((find-headline
3467 (function
3468 ;; Return first headline whose `:raw-value' property
3469 ;; is NAME in parse tree DATA, or nil.
3470 (lambda (name data)
3471 (org-element-map
3472 data 'headline
3473 (lambda (headline)
3474 (when (string=
3475 (org-element-property :raw-value headline)
3476 name)
3477 headline))
3478 info 'first-match)))))
3479 ;; Search among headlines sharing an ancestor with link,
3480 ;; from closest to farthest.
3481 (or (catch 'exit
3482 (mapc
3483 (lambda (parent)
3484 (when (eq (org-element-type parent) 'headline)
3485 (let ((foundp (funcall find-headline path parent)))
3486 (when foundp (throw 'exit foundp)))))
3487 (org-export-get-genealogy link)) nil)
3488 ;; No match with a common ancestor: try the full parse-tree.
3489 (funcall find-headline
3490 (if match-title-p (substring path 1) path)
3491 (plist-get info :parse-tree))))))))
3493 (defun org-export-resolve-id-link (link info)
3494 "Return headline referenced as LINK destination.
3496 INFO is a plist used as a communication channel.
3498 Return value can be the headline element matched in current parse
3499 tree, a file name or nil. Assume LINK type is either \"id\" or
3500 \"custom-id\"."
3501 (let ((id (org-element-property :path link)))
3502 ;; First check if id is within the current parse tree.
3503 (or (org-element-map
3504 (plist-get info :parse-tree) 'headline
3505 (lambda (headline)
3506 (when (or (string= (org-element-property :id headline) id)
3507 (string= (org-element-property :custom-id headline) id))
3508 headline))
3509 info 'first-match)
3510 ;; Otherwise, look for external files.
3511 (cdr (assoc id (plist-get info :id-alist))))))
3513 (defun org-export-resolve-radio-link (link info)
3514 "Return radio-target object referenced as LINK destination.
3516 INFO is a plist used as a communication channel.
3518 Return value can be a radio-target object or nil. Assume LINK
3519 has type \"radio\"."
3520 (let ((path (org-element-property :path link)))
3521 (org-element-map
3522 (plist-get info :parse-tree) 'radio-target
3523 (lambda (radio)
3524 (when (equal (org-element-property :value radio) path) radio))
3525 info 'first-match)))
3528 ;;;; For References
3530 ;; `org-export-get-ordinal' associates a sequence number to any object
3531 ;; or element.
3533 (defun org-export-get-ordinal (element info &optional types predicate)
3534 "Return ordinal number of an element or object.
3536 ELEMENT is the element or object considered. INFO is the plist
3537 used as a communication channel.
3539 Optional argument TYPES, when non-nil, is a list of element or
3540 object types, as symbols, that should also be counted in.
3541 Otherwise, only provided element's type is considered.
3543 Optional argument PREDICATE is a function returning a non-nil
3544 value if the current element or object should be counted in. It
3545 accepts two arguments: the element or object being considered and
3546 the plist used as a communication channel. This allows to count
3547 only a certain type of objects (i.e. inline images).
3549 Return value is a list of numbers if ELEMENT is an headline or an
3550 item. It is nil for keywords. It represents the footnote number
3551 for footnote definitions and footnote references. If ELEMENT is
3552 a target, return the same value as if ELEMENT was the closest
3553 table, item or headline containing the target. In any other
3554 case, return the sequence number of ELEMENT among elements or
3555 objects of the same type."
3556 ;; A target keyword, representing an invisible target, never has
3557 ;; a sequence number.
3558 (unless (eq (org-element-type element) 'keyword)
3559 ;; Ordinal of a target object refer to the ordinal of the closest
3560 ;; table, item, or headline containing the object.
3561 (when (eq (org-element-type element) 'target)
3562 (setq element
3563 (loop for parent in (org-export-get-genealogy element)
3564 when
3565 (memq
3566 (org-element-type parent)
3567 '(footnote-definition footnote-reference headline item
3568 table))
3569 return parent)))
3570 (case (org-element-type element)
3571 ;; Special case 1: An headline returns its number as a list.
3572 (headline (org-export-get-headline-number element info))
3573 ;; Special case 2: An item returns its number as a list.
3574 (item (let ((struct (org-element-property :structure element)))
3575 (org-list-get-item-number
3576 (org-element-property :begin element)
3577 struct
3578 (org-list-prevs-alist struct)
3579 (org-list-parents-alist struct))))
3580 ((footnote-definition footnote-reference)
3581 (org-export-get-footnote-number element info))
3582 (otherwise
3583 (let ((counter 0))
3584 ;; Increment counter until ELEMENT is found again.
3585 (org-element-map
3586 (plist-get info :parse-tree) (or types (org-element-type element))
3587 (lambda (el)
3588 (cond
3589 ((eq element el) (1+ counter))
3590 ((not predicate) (incf counter) nil)
3591 ((funcall predicate el info) (incf counter) nil)))
3592 info 'first-match))))))
3595 ;;;; For Src-Blocks
3597 ;; `org-export-get-loc' counts number of code lines accumulated in
3598 ;; src-block or example-block elements with a "+n" switch until
3599 ;; a given element, excluded. Note: "-n" switches reset that count.
3601 ;; `org-export-unravel-code' extracts source code (along with a code
3602 ;; references alist) from an `element-block' or `src-block' type
3603 ;; element.
3605 ;; `org-export-format-code' applies a formatting function to each line
3606 ;; of code, providing relative line number and code reference when
3607 ;; appropriate. Since it doesn't access the original element from
3608 ;; which the source code is coming, it expects from the code calling
3609 ;; it to know if lines should be numbered and if code references
3610 ;; should appear.
3612 ;; Eventually, `org-export-format-code-default' is a higher-level
3613 ;; function (it makes use of the two previous functions) which handles
3614 ;; line numbering and code references inclusion, and returns source
3615 ;; code in a format suitable for plain text or verbatim output.
3617 (defun org-export-get-loc (element info)
3618 "Return accumulated lines of code up to ELEMENT.
3620 INFO is the plist used as a communication channel.
3622 ELEMENT is excluded from count."
3623 (let ((loc 0))
3624 (org-element-map
3625 (plist-get info :parse-tree)
3626 `(src-block example-block ,(org-element-type element))
3627 (lambda (el)
3628 (cond
3629 ;; ELEMENT is reached: Quit the loop.
3630 ((eq el element))
3631 ;; Only count lines from src-block and example-block elements
3632 ;; with a "+n" or "-n" switch. A "-n" switch resets counter.
3633 ((not (memq (org-element-type el) '(src-block example-block))) nil)
3634 ((let ((linums (org-element-property :number-lines el)))
3635 (when linums
3636 ;; Accumulate locs or reset them.
3637 (let ((lines (org-count-lines
3638 (org-trim (org-element-property :value el)))))
3639 (setq loc (if (eq linums 'new) lines (+ loc lines))))))
3640 ;; Return nil to stay in the loop.
3641 nil)))
3642 info 'first-match)
3643 ;; Return value.
3644 loc))
3646 (defun org-export-unravel-code (element)
3647 "Clean source code and extract references out of it.
3649 ELEMENT has either a `src-block' an `example-block' type.
3651 Return a cons cell whose CAR is the source code, cleaned from any
3652 reference and protective comma and CDR is an alist between
3653 relative line number (integer) and name of code reference on that
3654 line (string)."
3655 (let* ((line 0) refs
3656 ;; Get code and clean it. Remove blank lines at its
3657 ;; beginning and end.
3658 (code (let ((c (replace-regexp-in-string
3659 "\\`\\([ \t]*\n\\)+" ""
3660 (replace-regexp-in-string
3661 "\\(:?[ \t]*\n\\)*[ \t]*\\'" "\n"
3662 (org-element-property :value element)))))
3663 ;; If appropriate, remove global indentation.
3664 (if (or org-src-preserve-indentation
3665 (org-element-property :preserve-indent element))
3667 (org-remove-indentation c))))
3668 ;; Get format used for references.
3669 (label-fmt (regexp-quote
3670 (or (org-element-property :label-fmt element)
3671 org-coderef-label-format)))
3672 ;; Build a regexp matching a loc with a reference.
3673 (with-ref-re
3674 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)[ \t]*\\)$"
3675 (replace-regexp-in-string
3676 "%s" "\\([-a-zA-Z0-9_ ]+\\)" label-fmt nil t))))
3677 ;; Return value.
3678 (cons
3679 ;; Code with references removed.
3680 (org-element-normalize-string
3681 (mapconcat
3682 (lambda (loc)
3683 (incf line)
3684 (if (not (string-match with-ref-re loc)) loc
3685 ;; Ref line: remove ref, and signal its position in REFS.
3686 (push (cons line (match-string 3 loc)) refs)
3687 (replace-match "" nil nil loc 1)))
3688 (org-split-string code "\n") "\n"))
3689 ;; Reference alist.
3690 refs)))
3692 (defun org-export-format-code (code fun &optional num-lines ref-alist)
3693 "Format CODE by applying FUN line-wise and return it.
3695 CODE is a string representing the code to format. FUN is
3696 a function. It must accept three arguments: a line of
3697 code (string), the current line number (integer) or nil and the
3698 reference associated to the current line (string) or nil.
3700 Optional argument NUM-LINES can be an integer representing the
3701 number of code lines accumulated until the current code. Line
3702 numbers passed to FUN will take it into account. If it is nil,
3703 FUN's second argument will always be nil. This number can be
3704 obtained with `org-export-get-loc' function.
3706 Optional argument REF-ALIST can be an alist between relative line
3707 number (i.e. ignoring NUM-LINES) and the name of the code
3708 reference on it. If it is nil, FUN's third argument will always
3709 be nil. It can be obtained through the use of
3710 `org-export-unravel-code' function."
3711 (let ((--locs (org-split-string code "\n"))
3712 (--line 0))
3713 (org-element-normalize-string
3714 (mapconcat
3715 (lambda (--loc)
3716 (incf --line)
3717 (let ((--ref (cdr (assq --line ref-alist))))
3718 (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
3719 --locs "\n"))))
3721 (defun org-export-format-code-default (element info)
3722 "Return source code from ELEMENT, formatted in a standard way.
3724 ELEMENT is either a `src-block' or `example-block' element. INFO
3725 is a plist used as a communication channel.
3727 This function takes care of line numbering and code references
3728 inclusion. Line numbers, when applicable, appear at the
3729 beginning of the line, separated from the code by two white
3730 spaces. Code references, on the other hand, appear flushed to
3731 the right, separated by six white spaces from the widest line of
3732 code."
3733 ;; Extract code and references.
3734 (let* ((code-info (org-export-unravel-code element))
3735 (code (car code-info))
3736 (code-lines (org-split-string code "\n"))
3737 (refs (and (org-element-property :retain-labels element)
3738 (cdr code-info)))
3739 ;; Handle line numbering.
3740 (num-start (case (org-element-property :number-lines element)
3741 (continued (org-export-get-loc element info))
3742 (new 0)))
3743 (num-fmt
3744 (and num-start
3745 (format "%%%ds "
3746 (length (number-to-string
3747 (+ (length code-lines) num-start))))))
3748 ;; Prepare references display, if required. Any reference
3749 ;; should start six columns after the widest line of code,
3750 ;; wrapped with parenthesis.
3751 (max-width
3752 (+ (apply 'max (mapcar 'length code-lines))
3753 (if (not num-start) 0 (length (format num-fmt num-start))))))
3754 (org-export-format-code
3755 code
3756 (lambda (loc line-num ref)
3757 (let ((number-str (and num-fmt (format num-fmt line-num))))
3758 (concat
3759 number-str
3761 (and ref
3762 (concat (make-string
3763 (- (+ 6 max-width)
3764 (+ (length loc) (length number-str))) ? )
3765 (format "(%s)" ref))))))
3766 num-start refs)))
3769 ;;;; For Tables
3771 ;; `org-export-table-has-special-column-p' and and
3772 ;; `org-export-table-row-is-special-p' are predicates used to look for
3773 ;; meta-information about the table structure.
3775 ;; `org-table-has-header-p' tells when the rows before the first rule
3776 ;; should be considered as table's header.
3778 ;; `org-export-table-cell-width', `org-export-table-cell-alignment'
3779 ;; and `org-export-table-cell-borders' extract information from
3780 ;; a table-cell element.
3782 ;; `org-export-table-dimensions' gives the number on rows and columns
3783 ;; in the table, ignoring horizontal rules and special columns.
3784 ;; `org-export-table-cell-address', given a table-cell object, returns
3785 ;; the absolute address of a cell. On the other hand,
3786 ;; `org-export-get-table-cell-at' does the contrary.
3788 ;; `org-export-table-cell-starts-colgroup-p',
3789 ;; `org-export-table-cell-ends-colgroup-p',
3790 ;; `org-export-table-row-starts-rowgroup-p',
3791 ;; `org-export-table-row-ends-rowgroup-p',
3792 ;; `org-export-table-row-starts-header-p' and
3793 ;; `org-export-table-row-ends-header-p' indicate position of current
3794 ;; row or cell within the table.
3796 (defun org-export-table-has-special-column-p (table)
3797 "Non-nil when TABLE has a special column.
3798 All special columns will be ignored during export."
3799 ;; The table has a special column when every first cell of every row
3800 ;; has an empty value or contains a symbol among "/", "#", "!", "$",
3801 ;; "*" "_" and "^". Though, do not consider a first row containing
3802 ;; only empty cells as special.
3803 (let ((special-column-p 'empty))
3804 (catch 'exit
3805 (mapc
3806 (lambda (row)
3807 (when (eq (org-element-property :type row) 'standard)
3808 (let ((value (org-element-contents
3809 (car (org-element-contents row)))))
3810 (cond ((member value '(("/") ("#") ("!") ("$") ("*") ("_") ("^")))
3811 (setq special-column-p 'special))
3812 ((not value))
3813 (t (throw 'exit nil))))))
3814 (org-element-contents table))
3815 (eq special-column-p 'special))))
3817 (defun org-export-table-has-header-p (table info)
3818 "Non-nil when TABLE has an header.
3820 INFO is a plist used as a communication channel.
3822 A table has an header when it contains at least two row groups."
3823 (let ((rowgroup 1) row-flag)
3824 (org-element-map
3825 table 'table-row
3826 (lambda (row)
3827 (cond
3828 ((> rowgroup 1) t)
3829 ((and row-flag (eq (org-element-property :type row) 'rule))
3830 (incf rowgroup) (setq row-flag nil))
3831 ((and (not row-flag) (eq (org-element-property :type row) 'standard))
3832 (setq row-flag t) nil)))
3833 info)))
3835 (defun org-export-table-row-is-special-p (table-row info)
3836 "Non-nil if TABLE-ROW is considered special.
3838 INFO is a plist used as the communication channel.
3840 All special rows will be ignored during export."
3841 (when (eq (org-element-property :type table-row) 'standard)
3842 (let ((first-cell (org-element-contents
3843 (car (org-element-contents table-row)))))
3844 ;; A row is special either when...
3846 ;; ... it starts with a field only containing "/",
3847 (equal first-cell '("/"))
3848 ;; ... the table contains a special column and the row start
3849 ;; with a marking character among, "^", "_", "$" or "!",
3850 (and (org-export-table-has-special-column-p
3851 (org-export-get-parent table-row))
3852 (member first-cell '(("^") ("_") ("$") ("!"))))
3853 ;; ... it contains only alignment cookies and empty cells.
3854 (let ((special-row-p 'empty))
3855 (catch 'exit
3856 (mapc
3857 (lambda (cell)
3858 (let ((value (org-element-contents cell)))
3859 ;; Since VALUE is a secondary string, the following
3860 ;; checks avoid expanding it with `org-export-data'.
3861 (cond ((not value))
3862 ((and (not (cdr value))
3863 (stringp (car value))
3864 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'"
3865 (car value)))
3866 (setq special-row-p 'cookie))
3867 (t (throw 'exit nil)))))
3868 (org-element-contents table-row))
3869 (eq special-row-p 'cookie)))))))
3871 (defun org-export-table-row-group (table-row info)
3872 "Return TABLE-ROW's group.
3874 INFO is a plist used as the communication channel.
3876 Return value is the group number, as an integer, or nil special
3877 rows and table rules. Group 1 is also table's header."
3878 (unless (or (eq (org-element-property :type table-row) 'rule)
3879 (org-export-table-row-is-special-p table-row info))
3880 (let ((group 0) row-flag)
3881 (catch 'found
3882 (mapc
3883 (lambda (row)
3884 (cond
3885 ((and (eq (org-element-property :type row) 'standard)
3886 (not (org-export-table-row-is-special-p row info)))
3887 (unless row-flag (incf group) (setq row-flag t)))
3888 ((eq (org-element-property :type row) 'rule)
3889 (setq row-flag nil)))
3890 (when (eq table-row row) (throw 'found group)))
3891 (org-element-contents (org-export-get-parent table-row)))))))
3893 (defun org-export-table-cell-width (table-cell info)
3894 "Return TABLE-CELL contents width.
3896 INFO is a plist used as the communication channel.
3898 Return value is the width given by the last width cookie in the
3899 same column as TABLE-CELL, or nil."
3900 (let* ((row (org-export-get-parent table-cell))
3901 (column (let ((cells (org-element-contents row)))
3902 (- (length cells) (length (memq table-cell cells)))))
3903 (table (org-export-get-parent-table table-cell))
3904 cookie-width)
3905 (mapc
3906 (lambda (row)
3907 (cond
3908 ;; In a special row, try to find a width cookie at COLUMN.
3909 ((org-export-table-row-is-special-p row info)
3910 (let ((value (org-element-contents
3911 (elt (org-element-contents row) column))))
3912 ;; The following checks avoid expanding unnecessarily the
3913 ;; cell with `org-export-data'
3914 (when (and value
3915 (not (cdr value))
3916 (stringp (car value))
3917 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'" (car value))
3918 (match-string 1 (car value)))
3919 (setq cookie-width
3920 (string-to-number (match-string 1 (car value)))))))
3921 ;; Ignore table rules.
3922 ((eq (org-element-property :type row) 'rule))))
3923 (org-element-contents table))
3924 ;; Return value.
3925 cookie-width))
3927 (defun org-export-table-cell-alignment (table-cell info)
3928 "Return TABLE-CELL contents alignment.
3930 INFO is a plist used as the communication channel.
3932 Return alignment as specified by the last alignment cookie in the
3933 same column as TABLE-CELL. If no such cookie is found, a default
3934 alignment value will be deduced from fraction of numbers in the
3935 column (see `org-table-number-fraction' for more information).
3936 Possible values are `left', `right' and `center'."
3937 (let* ((row (org-export-get-parent table-cell))
3938 (column (let ((cells (org-element-contents row)))
3939 (- (length cells) (length (memq table-cell cells)))))
3940 (table (org-export-get-parent-table table-cell))
3941 (number-cells 0)
3942 (total-cells 0)
3943 cookie-align)
3944 (mapc
3945 (lambda (row)
3946 (cond
3947 ;; In a special row, try to find an alignment cookie at
3948 ;; COLUMN.
3949 ((org-export-table-row-is-special-p row info)
3950 (let ((value (org-element-contents
3951 (elt (org-element-contents row) column))))
3952 ;; Since VALUE is a secondary string, the following checks
3953 ;; avoid useless expansion through `org-export-data'.
3954 (when (and value
3955 (not (cdr value))
3956 (stringp (car value))
3957 (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'"
3958 (car value))
3959 (match-string 1 (car value)))
3960 (setq cookie-align (match-string 1 (car value))))))
3961 ;; Ignore table rules.
3962 ((eq (org-element-property :type row) 'rule))
3963 ;; In a standard row, check if cell's contents are expressing
3964 ;; some kind of number. Increase NUMBER-CELLS accordingly.
3965 ;; Though, don't bother if an alignment cookie has already
3966 ;; defined cell's alignment.
3967 ((not cookie-align)
3968 (let ((value (org-export-data
3969 (org-element-contents
3970 (elt (org-element-contents row) column))
3971 info)))
3972 (incf total-cells)
3973 (when (string-match org-table-number-regexp value)
3974 (incf number-cells))))))
3975 (org-element-contents table))
3976 ;; Return value. Alignment specified by cookies has precedence
3977 ;; over alignment deduced from cells contents.
3978 (cond ((equal cookie-align "l") 'left)
3979 ((equal cookie-align "r") 'right)
3980 ((equal cookie-align "c") 'center)
3981 ((>= (/ (float number-cells) total-cells) org-table-number-fraction)
3982 'right)
3983 (t 'left))))
3985 (defun org-export-table-cell-borders (table-cell info)
3986 "Return TABLE-CELL borders.
3988 INFO is a plist used as a communication channel.
3990 Return value is a list of symbols, or nil. Possible values are:
3991 `top', `bottom', `above', `below', `left' and `right'. Note:
3992 `top' (resp. `bottom') only happen for a cell in the first
3993 row (resp. last row) of the table, ignoring table rules, if any.
3995 Returned borders ignore special rows."
3996 (let* ((row (org-export-get-parent table-cell))
3997 (table (org-export-get-parent-table table-cell))
3998 borders)
3999 ;; Top/above border? TABLE-CELL has a border above when a rule
4000 ;; used to demarcate row groups can be found above. Hence,
4001 ;; finding a rule isn't sufficient to push `above' in BORDERS:
4002 ;; another regular row has to be found above that rule.
4003 (let (rule-flag)
4004 (catch 'exit
4005 (mapc (lambda (row)
4006 (cond ((eq (org-element-property :type row) 'rule)
4007 (setq rule-flag t))
4008 ((not (org-export-table-row-is-special-p row info))
4009 (if rule-flag (throw 'exit (push 'above borders))
4010 (throw 'exit nil)))))
4011 ;; Look at every row before the current one.
4012 (cdr (memq row (reverse (org-element-contents table)))))
4013 ;; No rule above, or rule found starts the table (ignoring any
4014 ;; special row): TABLE-CELL is at the top of the table.
4015 (when rule-flag (push 'above borders))
4016 (push 'top borders)))
4017 ;; Bottom/below border? TABLE-CELL has a border below when next
4018 ;; non-regular row below is a rule.
4019 (let (rule-flag)
4020 (catch 'exit
4021 (mapc (lambda (row)
4022 (cond ((eq (org-element-property :type row) 'rule)
4023 (setq rule-flag t))
4024 ((not (org-export-table-row-is-special-p row info))
4025 (if rule-flag (throw 'exit (push 'below borders))
4026 (throw 'exit nil)))))
4027 ;; Look at every row after the current one.
4028 (cdr (memq row (org-element-contents table))))
4029 ;; No rule below, or rule found ends the table (modulo some
4030 ;; special row): TABLE-CELL is at the bottom of the table.
4031 (when rule-flag (push 'below borders))
4032 (push 'bottom borders)))
4033 ;; Right/left borders? They can only be specified by column
4034 ;; groups. Column groups are defined in a row starting with "/".
4035 ;; Also a column groups row only contains "<", "<>", ">" or blank
4036 ;; cells.
4037 (catch 'exit
4038 (let ((column (let ((cells (org-element-contents row)))
4039 (- (length cells) (length (memq table-cell cells))))))
4040 (mapc
4041 (lambda (row)
4042 (unless (eq (org-element-property :type row) 'rule)
4043 (when (equal (org-element-contents
4044 (car (org-element-contents row)))
4045 '("/"))
4046 (let ((column-groups
4047 (mapcar
4048 (lambda (cell)
4049 (let ((value (org-element-contents cell)))
4050 (when (member value '(("<") ("<>") (">") nil))
4051 (car value))))
4052 (org-element-contents row))))
4053 ;; There's a left border when previous cell, if
4054 ;; any, ends a group, or current one starts one.
4055 (when (or (and (not (zerop column))
4056 (member (elt column-groups (1- column))
4057 '(">" "<>")))
4058 (member (elt column-groups column) '("<" "<>")))
4059 (push 'left borders))
4060 ;; There's a right border when next cell, if any,
4061 ;; starts a group, or current one ends one.
4062 (when (or (and (/= (1+ column) (length column-groups))
4063 (member (elt column-groups (1+ column))
4064 '("<" "<>")))
4065 (member (elt column-groups column) '(">" "<>")))
4066 (push 'right borders))
4067 (throw 'exit nil)))))
4068 ;; Table rows are read in reverse order so last column groups
4069 ;; row has precedence over any previous one.
4070 (reverse (org-element-contents table)))))
4071 ;; Return value.
4072 borders))
4074 (defun org-export-table-cell-starts-colgroup-p (table-cell info)
4075 "Non-nil when TABLE-CELL is at the beginning of a row group.
4076 INFO is a plist used as a communication channel."
4077 ;; A cell starts a column group either when it is at the beginning
4078 ;; of a row (or after the special column, if any) or when it has
4079 ;; a left border.
4080 (or (eq (org-element-map
4081 (org-export-get-parent table-cell)
4082 'table-cell 'identity info 'first-match)
4083 table-cell)
4084 (memq 'left (org-export-table-cell-borders table-cell info))))
4086 (defun org-export-table-cell-ends-colgroup-p (table-cell info)
4087 "Non-nil when TABLE-CELL is at the end of a row group.
4088 INFO is a plist used as a communication channel."
4089 ;; A cell ends a column group either when it is at the end of a row
4090 ;; or when it has a right border.
4091 (or (eq (car (last (org-element-contents
4092 (org-export-get-parent table-cell))))
4093 table-cell)
4094 (memq 'right (org-export-table-cell-borders table-cell info))))
4096 (defun org-export-table-row-starts-rowgroup-p (table-row info)
4097 "Non-nil when TABLE-ROW is at the beginning of a column group.
4098 INFO is a plist used as a communication channel."
4099 (unless (or (eq (org-element-property :type table-row) 'rule)
4100 (org-export-table-row-is-special-p table-row info))
4101 (let ((borders (org-export-table-cell-borders
4102 (car (org-element-contents table-row)) info)))
4103 (or (memq 'top borders) (memq 'above borders)))))
4105 (defun org-export-table-row-ends-rowgroup-p (table-row info)
4106 "Non-nil when TABLE-ROW is at the end of a column group.
4107 INFO is a plist used as a communication channel."
4108 (unless (or (eq (org-element-property :type table-row) 'rule)
4109 (org-export-table-row-is-special-p table-row info))
4110 (let ((borders (org-export-table-cell-borders
4111 (car (org-element-contents table-row)) info)))
4112 (or (memq 'bottom borders) (memq 'below borders)))))
4114 (defun org-export-table-row-starts-header-p (table-row info)
4115 "Non-nil when TABLE-ROW is the first table header's row.
4116 INFO is a plist used as a communication channel."
4117 (and (org-export-table-has-header-p
4118 (org-export-get-parent-table table-row) info)
4119 (org-export-table-row-starts-rowgroup-p table-row info)
4120 (= (org-export-table-row-group table-row info) 1)))
4122 (defun org-export-table-row-ends-header-p (table-row info)
4123 "Non-nil when TABLE-ROW is the last table header's row.
4124 INFO is a plist used as a communication channel."
4125 (and (org-export-table-has-header-p
4126 (org-export-get-parent-table table-row) info)
4127 (org-export-table-row-ends-rowgroup-p table-row info)
4128 (= (org-export-table-row-group table-row info) 1)))
4130 (defun org-export-table-dimensions (table info)
4131 "Return TABLE dimensions.
4133 INFO is a plist used as a communication channel.
4135 Return value is a CONS like (ROWS . COLUMNS) where
4136 ROWS (resp. COLUMNS) is the number of exportable
4137 rows (resp. columns)."
4138 (let (first-row (columns 0) (rows 0))
4139 ;; Set number of rows, and extract first one.
4140 (org-element-map
4141 table 'table-row
4142 (lambda (row)
4143 (when (eq (org-element-property :type row) 'standard)
4144 (incf rows)
4145 (unless first-row (setq first-row row)))) info)
4146 ;; Set number of columns.
4147 (org-element-map first-row 'table-cell (lambda (cell) (incf columns)) info)
4148 ;; Return value.
4149 (cons rows columns)))
4151 (defun org-export-table-cell-address (table-cell info)
4152 "Return address of a regular TABLE-CELL object.
4154 TABLE-CELL is the cell considered. INFO is a plist used as
4155 a communication channel.
4157 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4158 zero-based index. Only exportable cells are considered. The
4159 function returns nil for other cells."
4160 (let* ((table-row (org-export-get-parent table-cell))
4161 (table (org-export-get-parent-table table-cell)))
4162 ;; Ignore cells in special rows or in special column.
4163 (unless (or (org-export-table-row-is-special-p table-row info)
4164 (and (org-export-table-has-special-column-p table)
4165 (eq (car (org-element-contents table-row)) table-cell)))
4166 (cons
4167 ;; Row number.
4168 (let ((row-count 0))
4169 (org-element-map
4170 table 'table-row
4171 (lambda (row)
4172 (cond ((eq (org-element-property :type row) 'rule) nil)
4173 ((eq row table-row) row-count)
4174 (t (incf row-count) nil)))
4175 info 'first-match))
4176 ;; Column number.
4177 (let ((col-count 0))
4178 (org-element-map
4179 table-row 'table-cell
4180 (lambda (cell)
4181 (if (eq cell table-cell) col-count (incf col-count) nil))
4182 info 'first-match))))))
4184 (defun org-export-get-table-cell-at (address table info)
4185 "Return regular table-cell object at ADDRESS in TABLE.
4187 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4188 zero-based index. TABLE is a table type element. INFO is
4189 a plist used as a communication channel.
4191 If no table-cell, among exportable cells, is found at ADDRESS,
4192 return nil."
4193 (let ((column-pos (cdr address)) (column-count 0))
4194 (org-element-map
4195 ;; Row at (car address) or nil.
4196 (let ((row-pos (car address)) (row-count 0))
4197 (org-element-map
4198 table 'table-row
4199 (lambda (row)
4200 (cond ((eq (org-element-property :type row) 'rule) nil)
4201 ((= row-count row-pos) row)
4202 (t (incf row-count) nil)))
4203 info 'first-match))
4204 'table-cell
4205 (lambda (cell)
4206 (if (= column-count column-pos) cell
4207 (incf column-count) nil))
4208 info 'first-match)))
4211 ;;;; For Tables Of Contents
4213 ;; `org-export-collect-headlines' builds a list of all exportable
4214 ;; headline elements, maybe limited to a certain depth. One can then
4215 ;; easily parse it and transcode it.
4217 ;; Building lists of tables, figures or listings is quite similar.
4218 ;; Once the generic function `org-export-collect-elements' is defined,
4219 ;; `org-export-collect-tables', `org-export-collect-figures' and
4220 ;; `org-export-collect-listings' can be derived from it.
4222 (defun org-export-collect-headlines (info &optional n)
4223 "Collect headlines in order to build a table of contents.
4225 INFO is a plist used as a communication channel.
4227 When optional argument N is an integer, it specifies the depth of
4228 the table of contents. Otherwise, it is set to the value of the
4229 last headline level. See `org-export-headline-levels' for more
4230 information.
4232 Return a list of all exportable headlines as parsed elements."
4233 (unless (wholenump n) (setq n (plist-get info :headline-levels)))
4234 (org-element-map
4235 (plist-get info :parse-tree)
4236 'headline
4237 (lambda (headline)
4238 ;; Strip contents from HEADLINE.
4239 (let ((relative-level (org-export-get-relative-level headline info)))
4240 (unless (> relative-level n) headline)))
4241 info))
4243 (defun org-export-collect-elements (type info &optional predicate)
4244 "Collect referenceable elements of a determined type.
4246 TYPE can be a symbol or a list of symbols specifying element
4247 types to search. Only elements with a caption are collected.
4249 INFO is a plist used as a communication channel.
4251 When non-nil, optional argument PREDICATE is a function accepting
4252 one argument, an element of type TYPE. It returns a non-nil
4253 value when that element should be collected.
4255 Return a list of all elements found, in order of appearance."
4256 (org-element-map
4257 (plist-get info :parse-tree) type
4258 (lambda (element)
4259 (and (org-element-property :caption element)
4260 (or (not predicate) (funcall predicate element))
4261 element))
4262 info))
4264 (defun org-export-collect-tables (info)
4265 "Build a list of tables.
4266 INFO is a plist used as a communication channel.
4268 Return a list of table elements with a caption."
4269 (org-export-collect-elements 'table info))
4271 (defun org-export-collect-figures (info predicate)
4272 "Build a list of figures.
4274 INFO is a plist used as a communication channel. PREDICATE is
4275 a function which accepts one argument: a paragraph element and
4276 whose return value is non-nil when that element should be
4277 collected.
4279 A figure is a paragraph type element, with a caption, verifying
4280 PREDICATE. The latter has to be provided since a \"figure\" is
4281 a vague concept that may depend on back-end.
4283 Return a list of elements recognized as figures."
4284 (org-export-collect-elements 'paragraph info predicate))
4286 (defun org-export-collect-listings (info)
4287 "Build a list of src blocks.
4289 INFO is a plist used as a communication channel.
4291 Return a list of src-block elements with a caption."
4292 (org-export-collect-elements 'src-block info))
4295 ;;;; For Timestamps
4297 ;; `org-export-timestamp-has-time-p' is a predicate to know if hours
4298 ;; and minutes are defined in a given timestamp.
4300 ;; `org-export-format-timestamp' allows to format a timestamp object
4301 ;; with an arbitrary format string.
4303 (defun org-export-timestamp-has-time-p (timestamp)
4304 "Non-nil when TIMESTAMP has a time specified."
4305 (org-element-property :hour-start timestamp))
4307 (defun org-export-format-timestamp (timestamp format &optional end utc)
4308 "Format a TIMESTAMP element into a string.
4310 FORMAT is a format specifier to be passed to
4311 `format-time-string'.
4313 When optional argument END is non-nil, use end of date-range or
4314 time-range, if possible.
4316 When optional argument UTC is non-nil, time will be expressed as
4317 Universal Time."
4318 (format-time-string
4319 format
4320 (apply 'encode-time
4321 (cons 0
4322 (mapcar
4323 (lambda (prop) (or (org-element-property prop timestamp) 0))
4324 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
4325 '(:minute-start :hour-start :day-start :month-start
4326 :year-start)))))
4327 utc))
4329 (defun org-export-split-timestamp-range (timestamp &optional end)
4330 "Extract a timestamp object from a date or time range.
4332 TIMESTAMP is a timestamp object. END, when non-nil, means extract
4333 the end of the range. Otherwise, extract its start.
4335 Return a new timestamp object sharing the same parent as
4336 TIMESTAMP."
4337 (let ((type (org-element-property :type timestamp)))
4338 (if (memq type '(active inactive diary)) timestamp
4339 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
4340 ;; Set new type.
4341 (org-element-put-property
4342 split-ts :type (if (eq type 'active-range) 'active 'inactive))
4343 ;; Copy start properties over end properties if END is
4344 ;; non-nil. Otherwise, copy end properties over `start' ones.
4345 (let ((p-alist '((:minute-start . :minute-end)
4346 (:hour-start . :hour-end)
4347 (:day-start . :day-end)
4348 (:month-start . :month-end)
4349 (:year-start . :year-end))))
4350 (dolist (p-cell p-alist)
4351 (org-element-put-property
4352 split-ts
4353 (funcall (if end 'car 'cdr) p-cell)
4354 (org-element-property
4355 (funcall (if end 'cdr 'car) p-cell) split-ts)))
4356 ;; Eventually refresh `:raw-value'.
4357 (org-element-put-property split-ts :raw-value nil)
4358 (org-element-put-property
4359 split-ts :raw-value (org-element-interpret-data split-ts)))))))
4361 (defun org-export-translate-timestamp (timestamp &optional boundary)
4362 "Apply `org-translate-time' on a TIMESTAMP object.
4363 When optional argument BOUNDARY is non-nil, it is either the
4364 symbol `start' or `end'. In this case, only translate the
4365 starting or ending part of TIMESTAMP if it is a date or time
4366 range. Otherwise, translate both parts."
4367 (if (and (not boundary)
4368 (memq (org-element-property :type timestamp)
4369 '(active-range inactive-range)))
4370 (concat
4371 (org-translate-time
4372 (org-element-property :raw-value
4373 (org-export-split-timestamp-range timestamp)))
4374 "--"
4375 (org-translate-time
4376 (org-element-property :raw-value
4377 (org-export-split-timestamp-range timestamp t))))
4378 (org-translate-time
4379 (org-element-property
4380 :raw-value
4381 (if (not boundary) timestamp
4382 (org-export-split-timestamp-range timestamp (eq boundary 'end)))))))
4385 ;;;; Smart Quotes
4387 ;; The main function for the smart quotes sub-system is
4388 ;; `org-export-activate-smart-quotes', which replaces every quote in
4389 ;; a given string from the parse tree with its "smart" counterpart.
4391 ;; Dictionary for smart quotes is stored in
4392 ;; `org-export-smart-quotes-alist'.
4394 ;; Internally, regexps matching potential smart quotes (checks at
4395 ;; string boundaries are also necessary) are defined in
4396 ;; `org-export-smart-quotes-regexps'.
4398 (defconst org-export-smart-quotes-alist
4399 '(("de"
4400 (opening-double-quote :utf-8 "„" :html "&bdquo;" :latex "\"`"
4401 :texinfo "@quotedblbase{}")
4402 (closing-double-quote :utf-8 "“" :html "&ldquo;" :latex "\"'"
4403 :texinfo "@quotedblleft{}")
4404 (opening-single-quote :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}"
4405 :texinfo "@quotesinglbase{}")
4406 (closing-single-quote :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}"
4407 :texinfo "@quoteleft{}")
4408 (apostrophe :utf-8 "’" :html "&rsquo;"))
4409 ("en"
4410 (opening-double-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
4411 (closing-double-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
4412 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
4413 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
4414 (apostrophe :utf-8 "’" :html "&rsquo;"))
4415 ("es"
4416 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
4417 :texinfo "@guillemetleft{}")
4418 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
4419 :texinfo "@guillemetright{}")
4420 (opening-single-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
4421 (closing-single-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
4422 (apostrophe :utf-8 "’" :html "&rsquo;"))
4423 ("fr"
4424 (opening-double-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
4425 :texinfo "@guillemetleft{}@tie{}")
4426 (closing-double-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
4427 :texinfo "@tie{}@guillemetright{}")
4428 (opening-single-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
4429 :texinfo "@guillemetleft{}@tie{}")
4430 (closing-single-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
4431 :texinfo "@tie{}@guillemetright{}")
4432 (apostrophe :utf-8 "’" :html "&rsquo;")))
4433 "Smart quotes translations.
4435 Alist whose CAR is a language string and CDR is an alist with
4436 quote type as key and a plist associating various encodings to
4437 their translation as value.
4439 A quote type can be any symbol among `opening-double-quote',
4440 `closing-double-quote', `opening-single-quote',
4441 `closing-single-quote' and `apostrophe'.
4443 Valid encodings include `:utf-8', `:html', `:latex' and
4444 `:texinfo'.
4446 If no translation is found, the quote character is left as-is.")
4448 (defconst org-export-smart-quotes-regexps
4449 (list
4450 ;; Possible opening quote at beginning of string.
4451 "\\`\\([\"']\\)\\(\\w\\|\\s.\\|\\s_\\)"
4452 ;; Possible closing quote at beginning of string.
4453 "\\`\\([\"']\\)\\(\\s-\\|\\s)\\|\\s.\\)"
4454 ;; Possible apostrophe at beginning of string.
4455 "\\`\\('\\)\\S-"
4456 ;; Opening single and double quotes.
4457 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\(?:\\w\\|\\s.\\|\\s_\\)"
4458 ;; Closing single and double quotes.
4459 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\(?:\\s-\\|\\s)\\|\\s.\\)"
4460 ;; Apostrophe.
4461 "\\S-\\('\\)\\S-"
4462 ;; Possible opening quote at end of string.
4463 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\'"
4464 ;; Possible closing quote at end of string.
4465 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\'"
4466 ;; Possible apostrophe at end of string.
4467 "\\S-\\('\\)\\'")
4468 "List of regexps matching a quote or an apostrophe.
4469 In every regexp, quote or apostrophe matched is put in group 1.")
4471 (defun org-export-activate-smart-quotes (s encoding info &optional original)
4472 "Replace regular quotes with \"smart\" quotes in string S.
4474 ENCODING is a symbol among `:html', `:latex', `:texinfo' and
4475 `:utf-8'. INFO is a plist used as a communication channel.
4477 The function has to retrieve information about string
4478 surroundings in parse tree. It can only happen with an
4479 unmodified string. Thus, if S has already been through another
4480 process, a non-nil ORIGINAL optional argument will provide that
4481 original string.
4483 Return the new string."
4484 (if (equal s "") ""
4485 (let* ((prev (org-export-get-previous-element (or original s) info))
4486 (pre-blank (and prev (org-element-property :post-blank prev)))
4487 (next (org-export-get-next-element (or original s) info))
4488 (get-smart-quote
4489 (lambda (q type)
4490 ;; Return smart quote associated to a give quote Q, as
4491 ;; a string. TYPE is a symbol among `open', `close' and
4492 ;; `apostrophe'.
4493 (let ((key (case type
4494 (apostrophe 'apostrophe)
4495 (open (if (equal "'" q) 'opening-single-quote
4496 'opening-double-quote))
4497 (otherwise (if (equal "'" q) 'closing-single-quote
4498 'closing-double-quote)))))
4499 (or (plist-get
4500 (cdr (assq key
4501 (cdr (assoc (plist-get info :language)
4502 org-export-smart-quotes-alist))))
4503 encoding)
4504 q)))))
4505 (if (or (equal "\"" s) (equal "'" s))
4506 ;; Only a quote: no regexp can match. We have to check both
4507 ;; sides and decide what to do.
4508 (cond ((and (not prev) (not next)) s)
4509 ((not prev) (funcall get-smart-quote s 'open))
4510 ((and (not next) (zerop pre-blank))
4511 (funcall get-smart-quote s 'close))
4512 ((not next) s)
4513 ((zerop pre-blank) (funcall get-smart-quote s 'apostrophe))
4514 (t (funcall get-smart-quote 'open)))
4515 ;; 1. Replace quote character at the beginning of S.
4516 (cond
4517 ;; Apostrophe?
4518 ((and prev (zerop pre-blank)
4519 (string-match (nth 2 org-export-smart-quotes-regexps) s))
4520 (setq s (replace-match
4521 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
4522 nil t s 1)))
4523 ;; Closing quote?
4524 ((and prev (zerop pre-blank)
4525 (string-match (nth 1 org-export-smart-quotes-regexps) s))
4526 (setq s (replace-match
4527 (funcall get-smart-quote (match-string 1 s) 'close)
4528 nil t s 1)))
4529 ;; Opening quote?
4530 ((and (or (not prev) (> pre-blank 0))
4531 (string-match (nth 0 org-export-smart-quotes-regexps) s))
4532 (setq s (replace-match
4533 (funcall get-smart-quote (match-string 1 s) 'open)
4534 nil t s 1))))
4535 ;; 2. Replace quotes in the middle of the string.
4536 (setq s (replace-regexp-in-string
4537 ;; Opening quotes.
4538 (nth 3 org-export-smart-quotes-regexps)
4539 (lambda (text)
4540 (funcall get-smart-quote (match-string 1 text) 'open))
4541 s nil t 1))
4542 (setq s (replace-regexp-in-string
4543 ;; Closing quotes.
4544 (nth 4 org-export-smart-quotes-regexps)
4545 (lambda (text)
4546 (funcall get-smart-quote (match-string 1 text) 'close))
4547 s nil t 1))
4548 (setq s (replace-regexp-in-string
4549 ;; Apostrophes.
4550 (nth 5 org-export-smart-quotes-regexps)
4551 (lambda (text)
4552 (funcall get-smart-quote (match-string 1 text) 'apostrophe))
4553 s nil t 1))
4554 ;; 3. Replace quote character at the end of S.
4555 (cond
4556 ;; Apostrophe?
4557 ((and next (string-match (nth 8 org-export-smart-quotes-regexps) s))
4558 (setq s (replace-match
4559 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
4560 nil t s 1)))
4561 ;; Closing quote?
4562 ((and (not next)
4563 (string-match (nth 7 org-export-smart-quotes-regexps) s))
4564 (setq s (replace-match
4565 (funcall get-smart-quote (match-string 1 s) 'close)
4566 nil t s 1)))
4567 ;; Opening quote?
4568 ((and next (string-match (nth 6 org-export-smart-quotes-regexps) s))
4569 (setq s (replace-match
4570 (funcall get-smart-quote (match-string 1 s) 'open)
4571 nil t s 1))))
4572 ;; Return string with smart quotes.
4573 s))))
4575 ;;;; Topology
4577 ;; Here are various functions to retrieve information about the
4578 ;; neighbourhood of a given element or object. Neighbours of interest
4579 ;; are direct parent (`org-export-get-parent'), parent headline
4580 ;; (`org-export-get-parent-headline'), first element containing an
4581 ;; object, (`org-export-get-parent-element'), parent table
4582 ;; (`org-export-get-parent-table'), previous element or object
4583 ;; (`org-export-get-previous-element') and next element or object
4584 ;; (`org-export-get-next-element').
4586 ;; `org-export-get-genealogy' returns the full genealogy of a given
4587 ;; element or object, from closest parent to full parse tree.
4589 (defun org-export-get-parent (blob)
4590 "Return BLOB parent or nil.
4591 BLOB is the element or object considered."
4592 (org-element-property :parent blob))
4594 (defun org-export-get-genealogy (blob)
4595 "Return full genealogy relative to a given element or object.
4597 BLOB is the element or object being considered.
4599 Ancestors are returned from closest to farthest, the last one
4600 being the full parse tree."
4601 (let (genealogy (parent blob))
4602 (while (setq parent (org-element-property :parent parent))
4603 (push parent genealogy))
4604 (nreverse genealogy)))
4606 (defun org-export-get-parent-headline (blob)
4607 "Return BLOB parent headline or nil.
4608 BLOB is the element or object being considered."
4609 (let ((parent blob))
4610 (while (and (setq parent (org-element-property :parent parent))
4611 (not (eq (org-element-type parent) 'headline))))
4612 parent))
4614 (defun org-export-get-parent-element (object)
4615 "Return first element containing OBJECT or nil.
4616 OBJECT is the object to consider."
4617 (let ((parent object))
4618 (while (and (setq parent (org-element-property :parent parent))
4619 (memq (org-element-type parent) org-element-all-objects)))
4620 parent))
4622 (defun org-export-get-parent-table (object)
4623 "Return OBJECT parent table or nil.
4624 OBJECT is either a `table-cell' or `table-element' type object."
4625 (let ((parent object))
4626 (while (and (setq parent (org-element-property :parent parent))
4627 (not (eq (org-element-type parent) 'table))))
4628 parent))
4630 (defun org-export-get-previous-element (blob info)
4631 "Return previous element or object.
4632 BLOB is an element or object. INFO is a plist used as
4633 a communication channel. Return previous exportable element or
4634 object, a string, or nil."
4635 (let (prev)
4636 (catch 'exit
4637 (mapc (lambda (obj)
4638 (cond ((eq obj blob) (throw 'exit prev))
4639 ((memq obj (plist-get info :ignore-list)))
4640 (t (setq prev obj))))
4641 ;; An object can belong to the contents of its parent or
4642 ;; to a secondary string. We check the latter option
4643 ;; first.
4644 (let ((parent (org-export-get-parent blob)))
4645 (or (and (not (memq (org-element-type blob)
4646 org-element-all-elements))
4647 (let ((sec-value
4648 (org-element-property
4649 (cdr (assq (org-element-type parent)
4650 org-element-secondary-value-alist))
4651 parent)))
4652 (and (memq blob sec-value) sec-value)))
4653 (org-element-contents parent)))))))
4655 (defun org-export-get-next-element (blob info)
4656 "Return next element or object.
4657 BLOB is an element or object. INFO is a plist used as
4658 a communication channel. Return next exportable element or
4659 object, a string, or nil."
4660 (catch 'found
4661 (mapc (lambda (obj)
4662 (unless (memq obj (plist-get info :ignore-list))
4663 (throw 'found obj)))
4664 ;; An object can belong to the contents of its parent or to
4665 ;; a secondary string. We check the latter option first.
4666 (let ((parent (org-export-get-parent blob)))
4667 (or (and (not (memq (org-element-type blob)
4668 org-element-all-objects))
4669 (let ((sec-value
4670 (org-element-property
4671 (cdr (assq (org-element-type parent)
4672 org-element-secondary-value-alist))
4673 parent)))
4674 (cdr (memq blob sec-value))))
4675 (cdr (memq blob (org-element-contents parent))))))
4676 nil))
4679 ;;;; Translation
4681 ;; `org-export-translate' translates a string according to language
4682 ;; specified by LANGUAGE keyword or `org-export-language-setup'
4683 ;; variable and a specified charset. `org-export-dictionary' contains
4684 ;; the dictionary used for the translation.
4686 (defconst org-export-dictionary
4687 '(("Author"
4688 ("ca" :default "Autor")
4689 ("cs" :default "Autor")
4690 ("da" :default "Ophavsmand")
4691 ("de" :default "Autor")
4692 ("eo" :html "A&#365;toro")
4693 ("es" :default "Autor")
4694 ("fi" :html "Tekij&auml;")
4695 ("fr" :default "Auteur")
4696 ("hu" :default "Szerz&otilde;")
4697 ("is" :html "H&ouml;fundur")
4698 ("it" :default "Autore")
4699 ("ja" :html "&#33879;&#32773;" :utf-8 "著者")
4700 ("nl" :default "Auteur")
4701 ("no" :default "Forfatter")
4702 ("nb" :default "Forfatter")
4703 ("nn" :default "Forfattar")
4704 ("pl" :default "Autor")
4705 ("ru" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
4706 ("sv" :html "F&ouml;rfattare")
4707 ("uk" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
4708 ("zh-CN" :html "&#20316;&#32773;" :utf-8 "作者")
4709 ("zh-TW" :html "&#20316;&#32773;" :utf-8 "作者"))
4710 ("Date"
4711 ("ca" :default "Data")
4712 ("cs" :default "Datum")
4713 ("da" :default "Dato")
4714 ("de" :default "Datum")
4715 ("eo" :default "Dato")
4716 ("es" :default "Fecha")
4717 ("fi" :html "P&auml;iv&auml;m&auml;&auml;r&auml;")
4718 ("hu" :html "D&aacute;tum")
4719 ("is" :default "Dagsetning")
4720 ("it" :default "Data")
4721 ("ja" :html "&#26085;&#20184;" :utf-8 "日付")
4722 ("nl" :default "Datum")
4723 ("no" :default "Dato")
4724 ("nb" :default "Dato")
4725 ("nn" :default "Dato")
4726 ("pl" :default "Data")
4727 ("ru" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
4728 ("sv" :default "Datum")
4729 ("uk" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
4730 ("zh-CN" :html "&#26085;&#26399;" :utf-8 "日期")
4731 ("zh-TW" :html "&#26085;&#26399;" :utf-8 "日期"))
4732 ("Equation"
4733 ("fr" :ascii "Equation" :default "Équation"))
4734 ("Figure")
4735 ("Footnotes"
4736 ("ca" :html "Peus de p&agrave;gina")
4737 ("cs" :default "Pozn\xe1mky pod carou")
4738 ("da" :default "Fodnoter")
4739 ("de" :html "Fu&szlig;noten")
4740 ("eo" :default "Piednotoj")
4741 ("es" :html "Pies de p&aacute;gina")
4742 ("fi" :default "Alaviitteet")
4743 ("fr" :default "Notes de bas de page")
4744 ("hu" :html "L&aacute;bjegyzet")
4745 ("is" :html "Aftanm&aacute;lsgreinar")
4746 ("it" :html "Note a pi&egrave; di pagina")
4747 ("ja" :html "&#33050;&#27880;" :utf-8 "脚注")
4748 ("nl" :default "Voetnoten")
4749 ("no" :default "Fotnoter")
4750 ("nb" :default "Fotnoter")
4751 ("nn" :default "Fotnotar")
4752 ("pl" :default "Przypis")
4753 ("ru" :html "&#1057;&#1085;&#1086;&#1089;&#1082;&#1080;" :utf-8 "Сноски")
4754 ("sv" :default "Fotnoter")
4755 ("uk" :html "&#1055;&#1088;&#1080;&#1084;&#1110;&#1090;&#1082;&#1080;"
4756 :utf-8 "Примітки")
4757 ("zh-CN" :html "&#33050;&#27880;" :utf-8 "脚注")
4758 ("zh-TW" :html "&#33139;&#35387;" :utf-8 "腳註"))
4759 ("List of Listings"
4760 ("fr" :default "Liste des programmes"))
4761 ("List of Tables"
4762 ("fr" :default "Liste des tableaux"))
4763 ("Listing %d:"
4764 ("fr"
4765 :ascii "Programme %d :" :default "Programme nº %d :"
4766 :latin1 "Programme %d :"))
4767 ("Listing %d: %s"
4768 ("fr"
4769 :ascii "Programme %d : %s" :default "Programme nº %d : %s"
4770 :latin1 "Programme %d : %s"))
4771 ("See section %s"
4772 ("fr" :default "cf. section %s"))
4773 ("Table %d:"
4774 ("fr"
4775 :ascii "Tableau %d :" :default "Tableau nº %d :" :latin1 "Tableau %d :"))
4776 ("Table %d: %s"
4777 ("fr"
4778 :ascii "Tableau %d : %s" :default "Tableau nº %d : %s"
4779 :latin1 "Tableau %d : %s"))
4780 ("Table of Contents"
4781 ("ca" :html "&Iacute;ndex")
4782 ("cs" :default "Obsah")
4783 ("da" :default "Indhold")
4784 ("de" :default "Inhaltsverzeichnis")
4785 ("eo" :default "Enhavo")
4786 ("es" :html "&Iacute;ndice")
4787 ("fi" :html "Sis&auml;llysluettelo")
4788 ("fr" :ascii "Sommaire" :default "Table des matières")
4789 ("hu" :html "Tartalomjegyz&eacute;k")
4790 ("is" :default "Efnisyfirlit")
4791 ("it" :default "Indice")
4792 ("ja" :html "&#30446;&#27425;" :utf-8 "目次")
4793 ("nl" :default "Inhoudsopgave")
4794 ("no" :default "Innhold")
4795 ("nb" :default "Innhold")
4796 ("nn" :default "Innhald")
4797 ("pl" :html "Spis tre&#x015b;ci")
4798 ("ru" :html "&#1057;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1077;"
4799 :utf-8 "Содержание")
4800 ("sv" :html "Inneh&aring;ll")
4801 ("uk" :html "&#1047;&#1084;&#1110;&#1089;&#1090;" :utf-8 "Зміст")
4802 ("zh-CN" :html "&#30446;&#24405;" :utf-8 "目录")
4803 ("zh-TW" :html "&#30446;&#37636;" :utf-8 "目錄"))
4804 ("Unknown reference"
4805 ("fr" :ascii "Destination inconnue" :default "Référence inconnue")))
4806 "Dictionary for export engine.
4808 Alist whose CAR is the string to translate and CDR is an alist
4809 whose CAR is the language string and CDR is a plist whose
4810 properties are possible charsets and values translated terms.
4812 It is used as a database for `org-export-translate'. Since this
4813 function returns the string as-is if no translation was found,
4814 the variable only needs to record values different from the
4815 entry.")
4817 (defun org-export-translate (s encoding info)
4818 "Translate string S according to language specification.
4820 ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1'
4821 and `:utf-8'. INFO is a plist used as a communication channel.
4823 Translation depends on `:language' property. Return the
4824 translated string. If no translation is found, try to fall back
4825 to `:default' encoding. If it fails, return S."
4826 (let* ((lang (plist-get info :language))
4827 (translations (cdr (assoc lang
4828 (cdr (assoc s org-export-dictionary))))))
4829 (or (plist-get translations encoding)
4830 (plist-get translations :default)
4831 s)))
4835 ;;; The Dispatcher
4837 ;; `org-export-dispatch' is the standard interactive way to start an
4838 ;; export process. It uses `org-export-dispatch-ui' as a subroutine
4839 ;; for its interface, which, in turn, delegates response to key
4840 ;; pressed to `org-export-dispatch-action'.
4842 ;;;###autoload
4843 (defun org-export-dispatch (&optional arg)
4844 "Export dispatcher for Org mode.
4846 It provides an access to common export related tasks in a buffer.
4847 Its interface comes in two flavours: standard and expert. While
4848 both share the same set of bindings, only the former displays the
4849 valid keys associations. Set `org-export-dispatch-use-expert-ui'
4850 to switch to one or the other.
4852 When called with C-u prefix ARG, repeat the last export action,
4853 with the same set of options used back then, on the current
4854 buffer."
4855 (interactive "P")
4856 (let* ((input (or (and arg org-export-dispatch-last-action)
4857 (save-window-excursion
4858 (unwind-protect
4859 ;; Store this export command.
4860 (setq org-export-dispatch-last-action
4861 (org-export-dispatch-ui
4862 (list org-export-initial-scope)
4864 org-export-dispatch-use-expert-ui))
4865 (and (get-buffer "*Org Export Dispatcher*")
4866 (kill-buffer "*Org Export Dispatcher*"))))))
4867 (action (car input))
4868 (optns (cdr input)))
4869 (case action
4870 ;; First handle special hard-coded actions.
4871 (publish-current-file (org-e-publish-current-file (memq 'force optns)))
4872 (publish-current-project
4873 (org-e-publish-current-project (memq 'force optns)))
4874 (publish-choose-project
4875 (org-e-publish (assoc (org-icompleting-read
4876 "Publish project: "
4877 org-e-publish-project-alist nil t)
4878 org-e-publish-project-alist)
4879 (memq 'force optns)))
4880 (publish-all (org-e-publish-all (memq 'force optns)))
4881 (otherwise
4882 (funcall action
4883 (memq 'subtree optns)
4884 (memq 'visible optns)
4885 (memq 'body optns))))))
4887 (defun org-export-dispatch-ui (options first-key expertp)
4888 "Handle interface for `org-export-dispatch'.
4890 OPTIONS is a list containing current interactive options set for
4891 export. It can contain any of the following symbols:
4892 `body' toggles a body-only export
4893 `subtree' restricts export to current subtree
4894 `visible' restricts export to visible part of buffer.
4895 `force' force publishing files.
4897 FIRST-KEY is the key pressed to select the first level menu. It
4898 is nil when this menu hasn't been selected yet.
4900 EXPERTP, when non-nil, triggers expert UI. In that case, no help
4901 buffer is provided, but indications about currently active
4902 options are given in the prompt. Moreover, \[?] allows to switch
4903 back to standard interface."
4904 (let* ((fontify-key
4905 (lambda (key &optional access-key)
4906 ;; Fontify KEY string. Optional argument ACCESS-KEY, when
4907 ;; non-nil is the required first-level key to activate
4908 ;; KEY. When its value is t, activate KEY independently
4909 ;; on the first key, if any. A nil value means KEY will
4910 ;; only be activated at first level.
4911 (if (or (eq access-key t) (eq access-key first-key))
4912 (org-add-props key nil 'face 'org-warning)
4913 (org-no-properties key))))
4914 ;; Prepare menu entries by extracting them from
4915 ;; `org-export-registered-backends', and sorting them by
4916 ;; access key and by ordinal, if any.
4917 (backends (sort
4918 (sort
4919 (delq nil
4920 (mapcar (lambda (b)
4921 (org-export-backend-menu (car b)))
4922 org-export-registered-backends))
4923 (lambda (a b)
4924 (let ((key-a (nth 1 a))
4925 (key-b (nth 1 b)))
4926 (cond ((and (numberp key-a) (numberp key-b))
4927 (< key-a key-b))
4928 ((numberp key-b) t)))))
4929 (lambda (a b) (< (car a) (car b)))))
4930 ;; Compute a list of allowed keys based on the first key
4931 ;; pressed, if any. Some keys (?1, ?2, ?3, ?4 and ?q) are
4932 ;; always available.
4933 (allowed-keys
4934 (nconc (list ?1 ?2 ?3 ?4)
4935 (if (not first-key) (org-uniquify (mapcar 'car backends))
4936 (let (sub-menu)
4937 (dolist (backend backends (sort (mapcar 'car sub-menu) '<))
4938 (when (eq (car backend) first-key)
4939 (setq sub-menu (append (nth 2 backend) sub-menu))))))
4940 (cond ((eq first-key ?P) (list ?f ?p ?x ?a))
4941 ((not first-key) (list ?P)))
4942 (when expertp (list ??))
4943 (list ?q)))
4944 ;; Build the help menu for standard UI.
4945 (help
4946 (unless expertp
4947 (concat
4948 ;; Options are hard-coded.
4949 (format "Options
4950 [%s] Body only: %s [%s] Visible only: %s
4951 [%s] Export scope: %s [%s] Force publishing: %s\n"
4952 (funcall fontify-key "1" t)
4953 (if (memq 'body options) "On " "Off")
4954 (funcall fontify-key "2" t)
4955 (if (memq 'visible options) "On " "Off")
4956 (funcall fontify-key "3" t)
4957 (if (memq 'subtree options) "Subtree" "Buffer ")
4958 (funcall fontify-key "4" t)
4959 (if (memq 'force options) "On " "Off"))
4960 ;; Display registered back-end entries. When a key
4961 ;; appears for the second time, do not create another
4962 ;; entry, but append its sub-menu to existing menu.
4963 (let (last-key)
4964 (mapconcat
4965 (lambda (entry)
4966 (let ((top-key (car entry)))
4967 (concat
4968 (unless (eq top-key last-key)
4969 (setq last-key top-key)
4970 (format "\n[%s] %s\n"
4971 (funcall fontify-key (char-to-string top-key))
4972 (nth 1 entry)))
4973 (let ((sub-menu (nth 2 entry)))
4974 (unless (functionp sub-menu)
4975 ;; Split sub-menu into two columns.
4976 (let ((index -1))
4977 (concat
4978 (mapconcat
4979 (lambda (sub-entry)
4980 (incf index)
4981 (format
4982 (if (zerop (mod index 2)) " [%s] %-24s"
4983 "[%s] %s\n")
4984 (funcall fontify-key
4985 (char-to-string (car sub-entry))
4986 top-key)
4987 (nth 1 sub-entry)))
4988 sub-menu "")
4989 (when (zerop (mod index 2)) "\n"))))))))
4990 backends ""))
4991 ;; Publishing menu is hard-coded.
4992 (format "\n[%s] Publish
4993 [%s] Current file [%s] Current project
4994 [%s] Choose project [%s] All projects\n\n"
4995 (funcall fontify-key "P")
4996 (funcall fontify-key "f" ?P)
4997 (funcall fontify-key "p" ?P)
4998 (funcall fontify-key "x" ?P)
4999 (funcall fontify-key "a" ?P))
5000 (format "\[%s] %s"
5001 (funcall fontify-key "q" t)
5002 (if first-key "Main menu" "Exit")))))
5003 ;; Build prompts for both standard and expert UI.
5004 (standard-prompt (unless expertp "Export command: "))
5005 (expert-prompt
5006 (when expertp
5007 (format
5008 "Export command (Options: %s%s%s%s) [%s]: "
5009 (if (memq 'body options) (funcall fontify-key "b" t) "-")
5010 (if (memq 'visible options) (funcall fontify-key "v" t) "-")
5011 (if (memq 'subtree options) (funcall fontify-key "s" t) "-")
5012 (if (memq 'force options) (funcall fontify-key "f" t) "-")
5013 (concat allowed-keys)))))
5014 ;; With expert UI, just read key with a fancy prompt. In standard
5015 ;; UI, display an intrusive help buffer.
5016 (if expertp
5017 (org-export-dispatch-action
5018 expert-prompt allowed-keys backends options first-key expertp)
5019 ;; At first call, create frame layout in order to display menu.
5020 (unless (get-buffer "*Org Export Dispatcher*")
5021 (delete-other-windows)
5022 (org-switch-to-buffer-other-window
5023 (get-buffer-create "*Org Export Dispatcher*"))
5024 (setq cursor-type nil))
5025 ;; At this point, the buffer containing the menu exists and is
5026 ;; visible in the current window. So, refresh it.
5027 (with-current-buffer "*Org Export Dispatcher*"
5028 (erase-buffer)
5029 (insert help))
5030 (org-fit-window-to-buffer)
5031 (org-export-dispatch-action
5032 standard-prompt allowed-keys backends options first-key expertp))))
5034 (defun org-export-dispatch-action
5035 (prompt allowed-keys backends options first-key expertp)
5036 "Read a character from command input and act accordingly.
5038 PROMPT is the displayed prompt, as a string. ALLOWED-KEYS is
5039 a list of characters available at a given step in the process.
5040 BACKENDS is a list of menu entries. OPTIONS, FIRST-KEY and
5041 EXPERTP are the same as defined in `org-export-dispatch-ui',
5042 which see.
5044 Toggle export options when required. Otherwise, return value is
5045 a list with action as CAR and a list of interactive export
5046 options as CDR."
5047 (let ((key (let ((k (read-char-exclusive prompt)))
5048 ;; Translate "C-a", "C-b"... into "a", "b"... Then take action
5049 ;; depending on user's key pressed.
5050 (if (< k 27) (+ k 96) k))))
5051 (cond
5052 ;; Ignore non-standard characters (i.e. "M-a") and
5053 ;; undefined associations.
5054 ((not (memq key allowed-keys))
5055 (ding)
5056 (unless expertp (message "Invalid key") (sit-for 1))
5057 (org-export-dispatch-ui options first-key expertp))
5058 ;; q key at first level aborts export. At second
5059 ;; level, cancel first key instead.
5060 ((eq key ?q) (if (not first-key) (error "Export aborted")
5061 (org-export-dispatch-ui options nil expertp)))
5062 ;; Help key: Switch back to standard interface if
5063 ;; expert UI was active.
5064 ((eq key ??) (org-export-dispatch-ui options first-key nil))
5065 ;; Toggle export options.
5066 ((memq key '(?1 ?2 ?3 ?4))
5067 (org-export-dispatch-ui
5068 (let ((option (case key (?1 'body) (?2 'visible) (?3 'subtree)
5069 (?4 'force))))
5070 (if (memq option options) (remq option options)
5071 (cons option options)))
5072 first-key expertp))
5073 ;; Action selected: Send key and options back to
5074 ;; `org-export-dispatch'.
5075 ((or first-key (functionp (nth 2 (assq key backends))))
5076 (cons (cond
5077 ((not first-key) (nth 2 (assq key backends)))
5078 ;; Publishing actions are hard-coded. Send a special
5079 ;; signal to `org-export-dispatch'.
5080 ((eq first-key ?P)
5081 (case key
5082 (?f 'publish-current-file)
5083 (?p 'publish-current-project)
5084 (?x 'publish-choose-project)
5085 (?a 'publish-all)))
5086 ;; Return first action associated to FIRST-KEY + KEY
5087 ;; path. Indeed, derived backends can share the same
5088 ;; FIRST-KEY.
5089 (t (catch 'found
5090 (mapc (lambda (backend)
5091 (let ((match (assq key (nth 2 backend))))
5092 (when match (throw 'found (nth 2 match)))))
5093 (member (assq first-key backends) backends)))))
5094 options))
5095 ;; Otherwise, enter sub-menu.
5096 (t (org-export-dispatch-ui options key expertp)))))
5099 (provide 'org-export)
5100 ;;; org-export.el ends here