cbe40b7a53163eb014b818c02b5e9712491497ee
[org-mode.git] / contrib / lisp / org-export.el
blobcbe40b7a53163eb014b818c02b5e9712491497ee
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.")
267 ;;; User-configurable Variables
269 ;; Configuration for the masses.
271 ;; They should never be accessed directly, as their value is to be
272 ;; stored in a property list (cf. `org-export-options-alist').
273 ;; Back-ends will read their value from there instead.
275 (defgroup org-export nil
276 "Options for exporting Org mode files."
277 :tag "Org Export"
278 :group 'org)
280 (defgroup org-export-general nil
281 "General options for export engine."
282 :tag "Org Export General"
283 :group 'org-export)
285 (defcustom org-export-with-archived-trees 'headline
286 "Whether sub-trees with the ARCHIVE tag should be exported.
288 This can have three different values:
289 nil Do not export, pretend this tree is not present.
290 t Do export the entire tree.
291 `headline' Only export the headline, but skip the tree below it.
293 This option can also be set with the #+OPTIONS line,
294 e.g. \"arch:nil\"."
295 :group 'org-export-general
296 :type '(choice
297 (const :tag "Not at all" nil)
298 (const :tag "Headline only" 'headline)
299 (const :tag "Entirely" t)))
301 (defcustom org-export-with-author t
302 "Non-nil means insert author name into the exported file.
303 This option can also be set with the #+OPTIONS line,
304 e.g. \"author:nil\"."
305 :group 'org-export-general
306 :type 'boolean)
308 (defcustom org-export-with-clocks nil
309 "Non-nil means export CLOCK keywords.
310 This option can also be set with the #+OPTIONS line,
311 e.g. \"c:t\"."
312 :group 'org-export-general
313 :type 'boolean)
315 (defcustom org-export-with-creator 'comment
316 "Non-nil means the postamble should contain a creator sentence.
318 The sentence can be set in `org-export-creator-string' and
319 defaults to \"Generated by Org mode XX in Emacs XXX.\".
321 If the value is `comment' insert it as a comment."
322 :group 'org-export-general
323 :type '(choice
324 (const :tag "No creator sentence" nil)
325 (const :tag "Sentence as a comment" 'comment)
326 (const :tag "Insert the sentence" t)))
328 (defcustom org-export-with-date t
329 "Non-nil means insert date in the exported document.
330 This options can also be set with the OPTIONS keyword,
331 e.g. \"date:nil\".")
333 (defcustom org-export-creator-string
334 (format "Generated by Org mode %s in Emacs %s."
335 (if (fboundp 'org-version) (org-version) "(Unknown)")
336 emacs-version)
337 "String to insert at the end of the generated document."
338 :group 'org-export-general
339 :type '(string :tag "Creator string"))
341 (defcustom org-export-with-drawers t
342 "Non-nil means export contents of standard drawers.
344 When t, all drawers are exported. This may also be a list of
345 drawer names to export. This variable doesn't apply to
346 properties drawers.
348 This option can also be set with the #+OPTIONS line,
349 e.g. \"d:nil\"."
350 :group 'org-export-general
351 :type '(choice
352 (const :tag "All drawers" t)
353 (const :tag "None" nil)
354 (repeat :tag "Selected drawers"
355 (string :tag "Drawer name"))))
357 (defcustom org-export-with-email nil
358 "Non-nil means insert author email into the exported file.
359 This option can also be set with the #+OPTIONS line,
360 e.g. \"email:t\"."
361 :group 'org-export-general
362 :type 'boolean)
364 (defcustom org-export-with-emphasize t
365 "Non-nil means interpret *word*, /word/, and _word_ as emphasized text.
367 If the export target supports emphasizing text, the word will be
368 typeset in bold, italic, or underlined, respectively. Not all
369 export backends support this.
371 This option can also be set with the #+OPTIONS line, e.g. \"*:nil\"."
372 :group 'org-export-general
373 :type 'boolean)
375 (defcustom org-export-exclude-tags '("noexport")
376 "Tags that exclude a tree from export.
378 All trees carrying any of these tags will be excluded from
379 export. This is without condition, so even subtrees inside that
380 carry one of the `org-export-select-tags' will be removed.
382 This option can also be set with the #+EXCLUDE_TAGS: keyword."
383 :group 'org-export-general
384 :type '(repeat (string :tag "Tag")))
386 (defcustom org-export-with-fixed-width t
387 "Non-nil means lines starting with \":\" will be in fixed width font.
389 This can be used to have pre-formatted text, fragments of code
390 etc. For example:
391 : ;; Some Lisp examples
392 : (while (defc cnt)
393 : (ding))
394 will be looking just like this in also HTML. See also the QUOTE
395 keyword. Not all export backends support this.
397 This option can also be set with the #+OPTIONS line, e.g. \"::nil\"."
398 :group 'org-export-translation
399 :type 'boolean)
401 (defcustom org-export-with-footnotes t
402 "Non-nil means Org footnotes should be exported.
403 This option can also be set with the #+OPTIONS line,
404 e.g. \"f:nil\"."
405 :group 'org-export-general
406 :type 'boolean)
408 (defcustom org-export-headline-levels 3
409 "The last level which is still exported as a headline.
411 Inferior levels will produce itemize lists when exported.
413 This option can also be set with the #+OPTIONS line, e.g. \"H:2\"."
414 :group 'org-export-general
415 :type 'integer)
417 (defcustom org-export-default-language "en"
418 "The default language for export and clocktable translations, as a string.
419 This may have an association in
420 `org-clock-clocktable-language-setup'."
421 :group 'org-export-general
422 :type '(string :tag "Language"))
424 (defcustom org-export-preserve-breaks nil
425 "Non-nil means preserve all line breaks when exporting.
427 Normally, in HTML output paragraphs will be reformatted.
429 This option can also be set with the #+OPTIONS line,
430 e.g. \"\\n:t\"."
431 :group 'org-export-general
432 :type 'boolean)
434 (defcustom org-export-with-entities t
435 "Non-nil means interpret entities when exporting.
437 For example, HTML export converts \\alpha to &alpha; and \\AA to
438 &Aring;.
440 For a list of supported names, see the constant `org-entities'
441 and the user option `org-entities-user'.
443 This option can also be set with the #+OPTIONS line,
444 e.g. \"e:nil\"."
445 :group 'org-export-general
446 :type 'boolean)
448 (defcustom org-export-with-inlinetasks t
449 "Non-nil means inlinetasks should be exported.
450 This option can also be set with the #+OPTIONS line,
451 e.g. \"inline:nil\"."
452 :group 'org-export-general
453 :type 'boolean)
455 (defcustom org-export-with-planning nil
456 "Non-nil means include planning info in export.
457 This option can also be set with the #+OPTIONS: line,
458 e.g. \"p:t\"."
459 :group 'org-export-general
460 :type 'boolean)
462 (defcustom org-export-with-priority nil
463 "Non-nil means include priority cookies in export.
464 This option can also be set with the #+OPTIONS line,
465 e.g. \"pri:t\"."
466 :group 'org-export-general
467 :type 'boolean)
469 (defcustom org-export-with-section-numbers t
470 "Non-nil means add section numbers to headlines when exporting.
472 When set to an integer n, numbering will only happen for
473 headlines whose relative level is higher or equal to n.
475 This option can also be set with the #+OPTIONS line,
476 e.g. \"num:t\"."
477 :group 'org-export-general
478 :type 'boolean)
480 (defcustom org-export-select-tags '("export")
481 "Tags that select a tree for export.
483 If any such tag is found in a buffer, all trees that do not carry
484 one of these tags will be ignored during export. Inside trees
485 that are selected like this, you can still deselect a subtree by
486 tagging it with one of the `org-export-exclude-tags'.
488 This option can also be set with the #+SELECT_TAGS: keyword."
489 :group 'org-export-general
490 :type '(repeat (string :tag "Tag")))
492 (defcustom org-export-with-smart-quotes nil
493 "Non-nil means activate smart quotes during export.
494 This option can also be set with the #+OPTIONS: line,
495 e.g. \"':t\"."
496 :group 'org-export-general
497 :type 'boolean)
499 (defcustom org-export-with-special-strings t
500 "Non-nil means interpret \"\\-\", \"--\" and \"---\" for export.
502 When this option is turned on, these strings will be exported as:
504 Org HTML LaTeX UTF-8
505 -----+----------+--------+-------
506 \\- &shy; \\-
507 -- &ndash; -- –
508 --- &mdash; --- —
509 ... &hellip; \\ldots …
511 This option can also be set with the #+OPTIONS line,
512 e.g. \"-:nil\"."
513 :group 'org-export-general
514 :type 'boolean)
516 (defcustom org-export-with-statistics-cookies t
517 "Non-nil means include statistics cookies in export.
518 This option can also be set with the #+OPTIONS: line,
519 e.g. \"stat:nil\""
520 :group 'org-export-general
521 :type 'boolean)
523 (defcustom org-export-with-sub-superscripts t
524 "Non-nil means interpret \"_\" and \"^\" for export.
526 When this option is turned on, you can use TeX-like syntax for
527 sub- and superscripts. Several characters after \"_\" or \"^\"
528 will be considered as a single item - so grouping with {} is
529 normally not needed. For example, the following things will be
530 parsed as single sub- or superscripts.
532 10^24 or 10^tau several digits will be considered 1 item.
533 10^-12 or 10^-tau a leading sign with digits or a word
534 x^2-y^3 will be read as x^2 - y^3, because items are
535 terminated by almost any nonword/nondigit char.
536 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
538 Still, ambiguity is possible - so when in doubt use {} to enclose
539 the sub/superscript. If you set this variable to the symbol
540 `{}', the braces are *required* in order to trigger
541 interpretations as sub/superscript. This can be helpful in
542 documents that need \"_\" frequently in plain text.
544 This option can also be set with the #+OPTIONS line,
545 e.g. \"^:nil\"."
546 :group 'org-export-general
547 :type '(choice
548 (const :tag "Interpret them" t)
549 (const :tag "Curly brackets only" {})
550 (const :tag "Do not interpret them" nil)))
552 (defcustom org-export-with-toc t
553 "Non-nil means create a table of contents in exported files.
555 The TOC contains headlines with levels up
556 to`org-export-headline-levels'. When an integer, include levels
557 up to N in the toc, this may then be different from
558 `org-export-headline-levels', but it will not be allowed to be
559 larger than the number of headline levels. When nil, no table of
560 contents is made.
562 This option can also be set with the #+OPTIONS line,
563 e.g. \"toc:nil\" or \"toc:3\"."
564 :group 'org-export-general
565 :type '(choice
566 (const :tag "No Table of Contents" nil)
567 (const :tag "Full Table of Contents" t)
568 (integer :tag "TOC to level")))
570 (defcustom org-export-with-tables t
571 "If non-nil, lines starting with \"|\" define a table.
572 For example:
574 | Name | Address | Birthday |
575 |-------------+----------+-----------|
576 | Arthur Dent | England | 29.2.2100 |
578 This option can also be set with the #+OPTIONS line, e.g. \"|:nil\"."
579 :group 'org-export-general
580 :type 'boolean)
582 (defcustom org-export-with-tags t
583 "If nil, do not export tags, just remove them from headlines.
585 If this is the symbol `not-in-toc', tags will be removed from
586 table of contents entries, but still be shown in the headlines of
587 the document.
589 This option can also be set with the #+OPTIONS line,
590 e.g. \"tags:nil\"."
591 :group 'org-export-general
592 :type '(choice
593 (const :tag "Off" nil)
594 (const :tag "Not in TOC" not-in-toc)
595 (const :tag "On" t)))
597 (defcustom org-export-with-tasks t
598 "Non-nil means include TODO items for export.
600 This may have the following values:
601 t include tasks independent of state.
602 `todo' include only tasks that are not yet done.
603 `done' include only tasks that are already done.
604 nil ignore all tasks.
605 list of keywords include tasks with these keywords.
607 This option can also be set with the #+OPTIONS line,
608 e.g. \"tasks:nil\"."
609 :group 'org-export-general
610 :type '(choice
611 (const :tag "All tasks" t)
612 (const :tag "No tasks" nil)
613 (const :tag "Not-done tasks" todo)
614 (const :tag "Only done tasks" done)
615 (repeat :tag "Specific TODO keywords"
616 (string :tag "Keyword"))))
618 (defcustom org-export-time-stamp-file t
619 "Non-nil means insert a time stamp into the exported file.
620 The time stamp shows when the file was created.
622 This option can also be set with the #+OPTIONS line,
623 e.g. \"timestamp:nil\"."
624 :group 'org-export-general
625 :type 'boolean)
627 (defcustom org-export-with-timestamps t
628 "Non nil means allow timestamps in export.
630 It can be set to `active', `inactive', t or nil, in order to
631 export, respectively, only active timestamps, only inactive ones,
632 all of them or none.
634 This option can also be set with the #+OPTIONS line, e.g.
635 \"<:nil\"."
636 :group 'org-export-general
637 :type '(choice
638 (const :tag "All timestamps" t)
639 (const :tag "Only active timestamps" active)
640 (const :tag "Only inactive timestamps" inactive)
641 (const :tag "No timestamp" nil)))
643 (defcustom org-export-with-todo-keywords t
644 "Non-nil means include TODO keywords in export.
645 When nil, remove all these keywords from the export."
646 :group 'org-export-general
647 :type 'boolean)
649 (defcustom org-export-allow-BIND 'confirm
650 "Non-nil means allow #+BIND to define local variable values for export.
651 This is a potential security risk, which is why the user must
652 confirm the use of these lines."
653 :group 'org-export-general
654 :type '(choice
655 (const :tag "Never" nil)
656 (const :tag "Always" t)
657 (const :tag "Ask a confirmation for each file" confirm)))
659 (defcustom org-export-snippet-translation-alist nil
660 "Alist between export snippets back-ends and exporter back-ends.
662 This variable allows to provide shortcuts for export snippets.
664 For example, with a value of '\(\(\"h\" . \"e-html\"\)\), the
665 HTML back-end will recognize the contents of \"@@h:<b>@@\" as
666 HTML code while every other back-end will ignore it."
667 :group 'org-export-general
668 :type '(repeat
669 (cons
670 (string :tag "Shortcut")
671 (string :tag "Back-end"))))
673 (defcustom org-export-coding-system nil
674 "Coding system for the exported file."
675 :group 'org-export-general
676 :type 'coding-system)
678 (defcustom org-export-copy-to-kill-ring t
679 "Non-nil means exported stuff will also be pushed onto the kill ring."
680 :group 'org-export-general
681 :type 'boolean)
683 (defcustom org-export-initial-scope 'buffer
684 "The initial scope when exporting with `org-export-dispatch'.
685 This variable can be either set to `buffer' or `subtree'."
686 :group 'org-export-general
687 :type '(choice
688 (const :tag "Export current buffer" 'buffer)
689 (const :tag "Export current subtree" 'subtree)))
691 (defcustom org-export-show-temporary-export-buffer t
692 "Non-nil means show buffer after exporting to temp buffer.
693 When Org exports to a file, the buffer visiting that file is ever
694 shown, but remains buried. However, when exporting to
695 a temporary buffer, that buffer is popped up in a second window.
696 When this variable is nil, the buffer remains buried also in
697 these cases."
698 :group 'org-export-general
699 :type 'boolean)
701 (defcustom org-export-dispatch-use-expert-ui nil
702 "Non-nil means using a non-intrusive `org-export-dispatch'.
703 In that case, no help buffer is displayed. Though, an indicator
704 for current export scope is added to the prompt (\"b\" when
705 output is restricted to body only, \"s\" when it is restricted to
706 the current subtree, \"v\" when only visible elements are
707 considered for export and \"f\" when publishing functions should
708 be passed the FORCE argument). Also, \[?] allows to switch back
709 to standard mode."
710 :group 'org-export-general
711 :type 'boolean)
715 ;;; Defining Back-ends
717 ;; `org-export-define-backend' is the standard way to define an export
718 ;; back-end. It allows to specify translators, filters, buffer
719 ;; options and a menu entry. If the new back-end shares translators
720 ;; with another back-end, `org-export-define-derived-backend' may be
721 ;; used instead.
723 ;; Internally, a back-end is stored as a list, of which CAR is the
724 ;; name of the back-end, as a symbol, and CDR a plist. Accessors to
725 ;; properties of a given back-end are: `org-export-backend-filters',
726 ;; `org-export-backend-menu', `org-export-backend-options' and
727 ;; `org-export-backend-translate-table'.
729 ;; Eventually `org-export-barf-if-invalid-backend' returns an error
730 ;; when a given back-end hasn't been registered yet.
732 (defmacro org-export-define-backend (backend translators &rest body)
733 "Define a new back-end BACKEND.
735 TRANSLATORS is an alist between object or element types and
736 functions handling them.
738 These functions should return a string without any trailing
739 space, or nil. They must accept three arguments: the object or
740 element itself, its contents or nil when it isn't recursive and
741 the property list used as a communication channel.
743 Contents, when not nil, are stripped from any global indentation
744 \(although the relative one is preserved). They also always end
745 with a single newline character.
747 If, for a given type, no function is found, that element or
748 object type will simply be ignored, along with any blank line or
749 white space at its end. The same will happen if the function
750 returns the nil value. If that function returns the empty
751 string, the type will be ignored, but the blank lines or white
752 spaces will be kept.
754 In addition to element and object types, one function can be
755 associated to the `template' symbol and another one to the
756 `plain-text' symbol.
758 The former returns the final transcoded string, and can be used
759 to add a preamble and a postamble to document's body. It must
760 accept two arguments: the transcoded string and the property list
761 containing export options.
763 The latter, when defined, is to be called on every text not
764 recognized as an element or an object. It must accept two
765 arguments: the text string and the information channel. It is an
766 appropriate place to protect special chars relative to the
767 back-end.
769 BODY can start with pre-defined keyword arguments. The following
770 keywords are understood:
772 :export-block
774 String, or list of strings, representing block names that
775 will not be parsed. This is used to specify blocks that will
776 contain raw code specific to the back-end. These blocks
777 still have to be handled by the relative `export-block' type
778 translator.
780 :filters-alist
782 Alist between filters and function, or list of functions,
783 specific to the back-end. See `org-export-filters-alist' for
784 a list of all allowed filters. Filters defined here
785 shouldn't make a back-end test, as it may prevent back-ends
786 derived from this one to behave properly.
788 :menu-entry
790 Menu entry for the export dispatcher. It should be a list
791 like:
793 \(KEY DESCRIPTION-OR-ORDINAL ACTION-OR-MENU)
795 where :
797 KEY is a free character selecting the back-end.
799 DESCRIPTION-OR-ORDINAL is either a string or a number.
801 If it is a string, is will be used to name the back-end in
802 its menu entry. If it is a number, the following menu will
803 be displayed as a sub-menu of the back-end with the same
804 KEY. Also, the number will be used to determine in which
805 order such sub-menus will appear (lowest first).
807 ACTION-OR-MENU is either a function or an alist.
809 If it is an action, it will be called with three arguments:
810 SUBTREEP, VISIBLE-ONLY and BODY-ONLY. See `org-export-as'
811 for further explanations.
813 If it is an alist, associations should follow the
814 pattern:
816 \(KEY DESCRIPTION ACTION)
818 where KEY, DESCRIPTION and ACTION are described above.
820 Valid values include:
822 \(?m \"My Special Back-end\" my-special-export-function)
826 \(?l \"Export to LaTeX\"
827 \((?b \"TEX (buffer)\" org-e-latex-export-as-latex)
828 \(?l \"TEX (file)\" org-e-latex-export-to-latex)
829 \(?p \"PDF file\" org-e-latex-export-to-pdf)
830 \(?o \"PDF file and open\"
831 \(lambda (subtree visible body-only)
832 \(org-open-file
833 \(org-e-latex-export-to-pdf subtree visible body-only))))))
835 :options-alist
837 Alist between back-end specific properties introduced in
838 communication channel and how their value are acquired. See
839 `org-export-options-alist' for more information about
840 structure of the values."
841 (declare (debug (&define name sexp [&rest [keywordp sexp]] defbody))
842 (indent 1))
843 (let (export-block filters menu-entry options contents)
844 (while (keywordp (car body))
845 (case (pop body)
846 (:export-block (let ((names (pop body)))
847 (setq export-block
848 (if (consp names) (mapcar 'upcase names)
849 (list (upcase names))))))
850 (:filters-alist (setq filters (pop body)))
851 (:menu-entry (setq menu-entry (pop body)))
852 (:options-alist (setq options (pop body)))
853 (t (pop body))))
854 (setq contents (append (list :translate-alist translators)
855 (and filters (list :filters-alist filters))
856 (and options (list :options-alist options))
857 (and menu-entry (list :menu-entry menu-entry))))
858 `(progn
859 ;; Register back-end.
860 (let ((registeredp (assq ',backend org-export-registered-backends)))
861 (if registeredp (setcdr registeredp ',contents)
862 (push (cons ',backend ',contents) org-export-registered-backends)))
863 ;; Tell parser to not parse EXPORT-BLOCK blocks.
864 ,(when export-block
865 `(mapc
866 (lambda (name)
867 (add-to-list 'org-element-block-name-alist
868 `(,name . org-element-export-block-parser)))
869 ',export-block))
870 ;; Splice in the body, if any.
871 ,@body)))
873 (defmacro org-export-define-derived-backend (child parent &rest body)
874 "Create a new back-end as a variant of an existing one.
876 CHILD is the name of the derived back-end. PARENT is the name of
877 the parent back-end.
879 BODY can start with pre-defined keyword arguments. The following
880 keywords are understood:
882 :export-block
884 String, or list of strings, representing block names that
885 will not be parsed. This is used to specify blocks that will
886 contain raw code specific to the back-end. These blocks
887 still have to be handled by the relative `export-block' type
888 translator.
890 :filters-alist
892 Alist of filters that will overwrite or complete filters
893 defined in PARENT back-end. See `org-export-filters-alist'
894 for a list of allowed filters.
896 :menu-entry
898 Menu entry for the export dispatcher. See
899 `org-export-define-backend' for more information about the
900 expected value.
902 :options-alist
904 Alist of back-end specific properties that will overwrite or
905 complete those defined in PARENT back-end. Refer to
906 `org-export-options-alist' for more information about
907 structure of the values.
909 :translate-alist
911 Alist of element and object types and transcoders that will
912 overwrite or complete transcode table from PARENT back-end.
913 Refer to `org-export-define-backend' for detailed information
914 about transcoders.
916 As an example, here is how one could define \"my-latex\" back-end
917 as a variant of `e-latex' back-end with a custom template
918 function:
920 \(org-export-define-derived-backend my-latex e-latex
921 :translate-alist ((template . my-latex-template-fun)))
923 The back-end could then be called with, for example:
925 \(org-export-to-buffer 'my-latex \"*Test my-latex*\")"
926 (declare (debug (&define name sexp [&rest [keywordp sexp]] def-body))
927 (indent 2))
928 (org-export-barf-if-invalid-backend parent)
929 (let (export-block filters menu-entry options translators contents)
930 (while (keywordp (car body))
931 (case (pop body)
932 (:export-block (let ((names (pop body)))
933 (setq export-block
934 (if (consp names) (mapcar 'upcase names)
935 (list (upcase names))))))
936 (:filters-alist (setq filters (pop body)))
937 (:menu-entry (setq menu-entry (pop body)))
938 (:options-alist (setq options (pop body)))
939 (:translate-alist (setq translators (pop body)))
940 (t (pop body))))
941 (setq contents (append
942 (list :parent parent)
943 (let ((p-table (org-export-backend-translate-table parent)))
944 (list :translate-alist (append translators p-table)))
945 (let ((p-filters (org-export-backend-filters parent)))
946 (list :filters-alist (append filters p-filters)))
947 (let ((p-options (org-export-backend-options parent)))
948 (list :options-alist (append options p-options)))
949 (and menu-entry (list :menu-entry menu-entry))))
950 `(progn
951 ;; Register back-end.
952 (let ((registeredp (assq ',child org-export-registered-backends)))
953 (if registeredp (setcdr registeredp ',contents)
954 (push (cons ',child ',contents) org-export-registered-backends)))
955 ;; Tell parser to not parse EXPORT-BLOCK blocks.
956 ,(when export-block
957 `(mapc
958 (lambda (name)
959 (add-to-list 'org-element-block-name-alist
960 `(,name . org-element-export-block-parser)))
961 ',export-block))
962 ;; Splice in the body, if any.
963 ,@body)))
965 (defun org-export-backend-filters (backend)
966 "Return filters for BACKEND."
967 (plist-get (cdr (assq backend org-export-registered-backends))
968 :filters-alist))
970 (defun org-export-backend-menu (backend)
971 "Return menu entry for BACKEND."
972 (plist-get (cdr (assq backend org-export-registered-backends))
973 :menu-entry))
975 (defun org-export-backend-options (backend)
976 "Return export options for BACKEND."
977 (plist-get (cdr (assq backend org-export-registered-backends))
978 :options-alist))
980 (defun org-export-backend-translate-table (backend)
981 "Return translate table for BACKEND."
982 (plist-get (cdr (assq backend org-export-registered-backends))
983 :translate-alist))
985 (defun org-export-barf-if-invalid-backend (backend)
986 "Signal an error if BACKEND isn't defined."
987 (unless (org-export-backend-translate-table backend)
988 (error "Unknown \"%s\" back-end: Aborting export" backend)))
990 (defun org-export-derived-backend-p (backend &rest backends)
991 "Non-nil if BACKEND is derived from one of BACKENDS."
992 (let ((parent backend))
993 (while (and (not (memq parent backends))
994 (setq parent
995 (plist-get (cdr (assq parent
996 org-export-registered-backends))
997 :parent))))
998 parent))
1002 ;;; The Communication Channel
1004 ;; During export process, every function has access to a number of
1005 ;; properties. They are of two types:
1007 ;; 1. Environment options are collected once at the very beginning of
1008 ;; the process, out of the original buffer and configuration.
1009 ;; Collecting them is handled by `org-export-get-environment'
1010 ;; function.
1012 ;; Most environment options are defined through the
1013 ;; `org-export-options-alist' variable.
1015 ;; 2. Tree properties are extracted directly from the parsed tree,
1016 ;; just before export, by `org-export-collect-tree-properties'.
1018 ;; Here is the full list of properties available during transcode
1019 ;; process, with their category and their value type.
1021 ;; + `:author' :: Author's name.
1022 ;; - category :: option
1023 ;; - type :: string
1025 ;; + `:back-end' :: Current back-end used for transcoding.
1026 ;; - category :: tree
1027 ;; - type :: symbol
1029 ;; + `:creator' :: String to write as creation information.
1030 ;; - category :: option
1031 ;; - type :: string
1033 ;; + `:date' :: String to use as date.
1034 ;; - category :: option
1035 ;; - type :: string
1037 ;; + `:description' :: Description text for the current data.
1038 ;; - category :: option
1039 ;; - type :: string
1041 ;; + `:email' :: Author's email.
1042 ;; - category :: option
1043 ;; - type :: string
1045 ;; + `:exclude-tags' :: Tags for exclusion of subtrees from export
1046 ;; process.
1047 ;; - category :: option
1048 ;; - type :: list of strings
1050 ;; + `:exported-data' :: Hash table used for memoizing
1051 ;; `org-export-data'.
1052 ;; - category :: tree
1053 ;; - type :: hash table
1055 ;; + `:filetags' :: List of global tags for buffer. Used by
1056 ;; `org-export-get-tags' to get tags with inheritance.
1057 ;; - category :: option
1058 ;; - type :: list of strings
1060 ;; + `:footnote-definition-alist' :: Alist between footnote labels and
1061 ;; their definition, as parsed data. Only non-inlined footnotes
1062 ;; are represented in this alist. Also, every definition isn't
1063 ;; guaranteed to be referenced in the parse tree. The purpose of
1064 ;; this property is to preserve definitions from oblivion
1065 ;; (i.e. when the parse tree comes from a part of the original
1066 ;; buffer), it isn't meant for direct use in a back-end. To
1067 ;; retrieve a definition relative to a reference, use
1068 ;; `org-export-get-footnote-definition' instead.
1069 ;; - category :: option
1070 ;; - type :: alist (STRING . LIST)
1072 ;; + `:headline-levels' :: Maximum level being exported as an
1073 ;; headline. Comparison is done with the relative level of
1074 ;; headlines in the parse tree, not necessarily with their
1075 ;; actual level.
1076 ;; - category :: option
1077 ;; - type :: integer
1079 ;; + `:headline-offset' :: Difference between relative and real level
1080 ;; of headlines in the parse tree. For example, a value of -1
1081 ;; means a level 2 headline should be considered as level
1082 ;; 1 (cf. `org-export-get-relative-level').
1083 ;; - category :: tree
1084 ;; - type :: integer
1086 ;; + `:headline-numbering' :: Alist between headlines and their
1087 ;; numbering, as a list of numbers
1088 ;; (cf. `org-export-get-headline-number').
1089 ;; - category :: tree
1090 ;; - type :: alist (INTEGER . LIST)
1092 ;; + `:id-alist' :: Alist between ID strings and destination file's
1093 ;; path, relative to current directory. It is used by
1094 ;; `org-export-resolve-id-link' to resolve ID links targeting an
1095 ;; external file.
1096 ;; - category :: option
1097 ;; - type :: alist (STRING . STRING)
1099 ;; + `:ignore-list' :: List of elements and objects that should be
1100 ;; ignored during export.
1101 ;; - category :: tree
1102 ;; - type :: list of elements and objects
1104 ;; + `:input-file' :: Full path to input file, if any.
1105 ;; - category :: option
1106 ;; - type :: string or nil
1108 ;; + `:keywords' :: List of keywords attached to data.
1109 ;; - category :: option
1110 ;; - type :: string
1112 ;; + `:language' :: Default language used for translations.
1113 ;; - category :: option
1114 ;; - type :: string
1116 ;; + `:parse-tree' :: Whole parse tree, available at any time during
1117 ;; transcoding.
1118 ;; - category :: option
1119 ;; - type :: list (as returned by `org-element-parse-buffer')
1121 ;; + `:preserve-breaks' :: Non-nil means transcoding should preserve
1122 ;; all line breaks.
1123 ;; - category :: option
1124 ;; - type :: symbol (nil, t)
1126 ;; + `:section-numbers' :: Non-nil means transcoding should add
1127 ;; section numbers to headlines.
1128 ;; - category :: option
1129 ;; - type :: symbol (nil, t)
1131 ;; + `:select-tags' :: List of tags enforcing inclusion of sub-trees
1132 ;; in transcoding. When such a tag is present, subtrees without
1133 ;; it are de facto excluded from the process. See
1134 ;; `use-select-tags'.
1135 ;; - category :: option
1136 ;; - type :: list of strings
1138 ;; + `:target-list' :: List of targets encountered in the parse tree.
1139 ;; This is used to partly resolve "fuzzy" links
1140 ;; (cf. `org-export-resolve-fuzzy-link').
1141 ;; - category :: tree
1142 ;; - type :: list of strings
1144 ;; + `:time-stamp-file' :: Non-nil means transcoding should insert
1145 ;; a time stamp in the output.
1146 ;; - category :: option
1147 ;; - type :: symbol (nil, t)
1149 ;; + `:translate-alist' :: Alist between element and object types and
1150 ;; transcoding functions relative to the current back-end.
1151 ;; Special keys `template' and `plain-text' are also possible.
1152 ;; - category :: option
1153 ;; - type :: alist (SYMBOL . FUNCTION)
1155 ;; + `:with-archived-trees' :: Non-nil when archived subtrees should
1156 ;; also be transcoded. If it is set to the `headline' symbol,
1157 ;; only the archived headline's name is retained.
1158 ;; - category :: option
1159 ;; - type :: symbol (nil, t, `headline')
1161 ;; + `:with-author' :: Non-nil means author's name should be included
1162 ;; in the output.
1163 ;; - category :: option
1164 ;; - type :: symbol (nil, t)
1166 ;; + `:with-clocks' :: Non-nil means clock keywords should be exported.
1167 ;; - category :: option
1168 ;; - type :: symbol (nil, t)
1170 ;; + `:with-creator' :: Non-nil means a creation sentence should be
1171 ;; inserted at the end of the transcoded string. If the value
1172 ;; is `comment', it should be commented.
1173 ;; - category :: option
1174 ;; - type :: symbol (`comment', nil, t)
1176 ;; + `:with-date' :: Non-nil means output should contain a date.
1177 ;; - category :: option
1178 ;; - type :. symbol (nil, t)
1180 ;; + `:with-drawers' :: Non-nil means drawers should be exported. If
1181 ;; its value is a list of names, only drawers with such names
1182 ;; will be transcoded.
1183 ;; - category :: option
1184 ;; - type :: symbol (nil, t) or list of strings
1186 ;; + `:with-email' :: Non-nil means output should contain author's
1187 ;; email.
1188 ;; - category :: option
1189 ;; - type :: symbol (nil, t)
1191 ;; + `:with-emphasize' :: Non-nil means emphasized text should be
1192 ;; interpreted.
1193 ;; - category :: option
1194 ;; - type :: symbol (nil, t)
1196 ;; + `:with-fixed-width' :: Non-nil if transcoder should interpret
1197 ;; strings starting with a colon as a fixed-with (verbatim) area.
1198 ;; - category :: option
1199 ;; - type :: symbol (nil, t)
1201 ;; + `:with-footnotes' :: Non-nil if transcoder should interpret
1202 ;; footnotes.
1203 ;; - category :: option
1204 ;; - type :: symbol (nil, t)
1206 ;; + `:with-plannings' :: Non-nil means transcoding should include
1207 ;; planning info.
1208 ;; - category :: option
1209 ;; - type :: symbol (nil, t)
1211 ;; + `:with-priority' :: Non-nil means transcoding should include
1212 ;; priority cookies.
1213 ;; - category :: option
1214 ;; - type :: symbol (nil, t)
1216 ;; + `:with-smart-quotes' :: Non-nil means activate smart quotes in
1217 ;; plain text.
1218 ;; - category :: option
1219 ;; - type :: symbol (nil, t)
1221 ;; + `:with-special-strings' :: Non-nil means transcoding should
1222 ;; interpret special strings in plain text.
1223 ;; - category :: option
1224 ;; - type :: symbol (nil, t)
1226 ;; + `:with-sub-superscript' :: Non-nil means transcoding should
1227 ;; interpret subscript and superscript. With a value of "{}",
1228 ;; only interpret those using curly brackets.
1229 ;; - category :: option
1230 ;; - type :: symbol (nil, {}, t)
1232 ;; + `:with-tables' :: Non-nil means transcoding should interpret
1233 ;; tables.
1234 ;; - category :: option
1235 ;; - type :: symbol (nil, t)
1237 ;; + `:with-tags' :: Non-nil means transcoding should keep tags in
1238 ;; headlines. A `not-in-toc' value will remove them from the
1239 ;; table of contents, if any, nonetheless.
1240 ;; - category :: option
1241 ;; - type :: symbol (nil, t, `not-in-toc')
1243 ;; + `:with-tasks' :: Non-nil means transcoding should include
1244 ;; headlines with a TODO keyword. A `todo' value will only
1245 ;; include headlines with a todo type keyword while a `done'
1246 ;; value will do the contrary. If a list of strings is provided,
1247 ;; only tasks with keywords belonging to that list will be kept.
1248 ;; - category :: option
1249 ;; - type :: symbol (t, todo, done, nil) or list of strings
1251 ;; + `:with-timestamps' :: Non-nil means transcoding should include
1252 ;; time stamps. Special value `active' (resp. `inactive') ask to
1253 ;; export only active (resp. inactive) timestamps. Otherwise,
1254 ;; completely remove them.
1255 ;; - category :: option
1256 ;; - type :: symbol: (`active', `inactive', t, nil)
1258 ;; + `:with-toc' :: Non-nil means that a table of contents has to be
1259 ;; added to the output. An integer value limits its depth.
1260 ;; - category :: option
1261 ;; - type :: symbol (nil, t or integer)
1263 ;; + `:with-todo-keywords' :: Non-nil means transcoding should
1264 ;; include TODO keywords.
1265 ;; - category :: option
1266 ;; - type :: symbol (nil, t)
1269 ;;;; Environment Options
1271 ;; Environment options encompass all parameters defined outside the
1272 ;; scope of the parsed data. They come from five sources, in
1273 ;; increasing precedence order:
1275 ;; - Global variables,
1276 ;; - Buffer's attributes,
1277 ;; - Options keyword symbols,
1278 ;; - Buffer keywords,
1279 ;; - Subtree properties.
1281 ;; The central internal function with regards to environment options
1282 ;; is `org-export-get-environment'. It updates global variables with
1283 ;; "#+BIND:" keywords, then retrieve and prioritize properties from
1284 ;; the different sources.
1286 ;; The internal functions doing the retrieval are:
1287 ;; `org-export--get-global-options',
1288 ;; `org-export--get-buffer-attributes',
1289 ;; `org-export--parse-option-keyword',
1290 ;; `org-export--get-subtree-options' and
1291 ;; `org-export--get-inbuffer-options'
1293 ;; Also, `org-export--confirm-letbind' and `org-export--install-letbind'
1294 ;; take care of the part relative to "#+BIND:" keywords.
1296 (defun org-export-get-environment (&optional backend subtreep ext-plist)
1297 "Collect export options from the current buffer.
1299 Optional argument BACKEND is a symbol specifying which back-end
1300 specific options to read, if any.
1302 When optional argument SUBTREEP is non-nil, assume the export is
1303 done against the current sub-tree.
1305 Third optional argument EXT-PLIST is a property list with
1306 external parameters overriding Org default settings, but still
1307 inferior to file-local settings."
1308 ;; First install #+BIND variables.
1309 (org-export--install-letbind-maybe)
1310 ;; Get and prioritize export options...
1311 (org-combine-plists
1312 ;; ... from global variables...
1313 (org-export--get-global-options backend)
1314 ;; ... from an external property list...
1315 ext-plist
1316 ;; ... from in-buffer settings...
1317 (org-export--get-inbuffer-options
1318 backend
1319 (and buffer-file-name (org-remove-double-quotes buffer-file-name)))
1320 ;; ... and from subtree, when appropriate.
1321 (and subtreep (org-export--get-subtree-options backend))
1322 ;; Eventually add misc. properties.
1323 (list
1324 :back-end
1325 backend
1326 :translate-alist
1327 (org-export-backend-translate-table backend)
1328 :footnote-definition-alist
1329 ;; Footnotes definitions must be collected in the original
1330 ;; buffer, as there's no insurance that they will still be in
1331 ;; the parse tree, due to possible narrowing.
1332 (let (alist)
1333 (org-with-wide-buffer
1334 (goto-char (point-min))
1335 (while (re-search-forward org-footnote-definition-re nil t)
1336 (let ((def (save-match-data (org-element-at-point))))
1337 (when (eq (org-element-type def) 'footnote-definition)
1338 (push
1339 (cons (org-element-property :label def)
1340 (let ((cbeg (org-element-property :contents-begin def)))
1341 (when cbeg
1342 (org-element--parse-elements
1343 cbeg (org-element-property :contents-end def)
1344 nil nil nil nil (list 'org-data nil)))))
1345 alist))))
1346 alist))
1347 :id-alist
1348 ;; Collect id references.
1349 (let (alist)
1350 (org-with-wide-buffer
1351 (goto-char (point-min))
1352 (while (re-search-forward "\\[\\[id:\\S-+?\\]" nil t)
1353 (let ((link (org-element-context)))
1354 (when (eq (org-element-type link) 'link)
1355 (let* ((id (org-element-property :path link))
1356 (file (org-id-find-id-file id)))
1357 (when file
1358 (push (cons id (file-relative-name file)) alist)))))))
1359 alist))))
1361 (defun org-export--parse-option-keyword (options &optional backend)
1362 "Parse an OPTIONS line and return values as a plist.
1363 Optional argument BACKEND is a symbol specifying which back-end
1364 specific items to read, if any."
1365 (let* ((all (append org-export-options-alist
1366 (and backend (org-export-backend-options backend))))
1367 ;; Build an alist between #+OPTION: item and property-name.
1368 (alist (delq nil
1369 (mapcar (lambda (e)
1370 (when (nth 2 e) (cons (regexp-quote (nth 2 e))
1371 (car e))))
1372 all)))
1373 plist)
1374 (mapc (lambda (e)
1375 (when (string-match (concat "\\(\\`\\|[ \t]\\)"
1376 (car e)
1377 ":\\(([^)\n]+)\\|[^ \t\n\r;,.]*\\)")
1378 options)
1379 (setq plist (plist-put plist
1380 (cdr e)
1381 (car (read-from-string
1382 (match-string 2 options)))))))
1383 alist)
1384 plist))
1386 (defun org-export--get-subtree-options (&optional backend)
1387 "Get export options in subtree at point.
1388 Optional argument BACKEND is a symbol specifying back-end used
1389 for export. Return options as a plist."
1390 ;; For each buffer keyword, create an headline property setting the
1391 ;; same property in communication channel. The name for the property
1392 ;; is the keyword with "EXPORT_" appended to it.
1393 (org-with-wide-buffer
1394 (let (prop plist)
1395 ;; Make sure point is at an heading.
1396 (unless (org-at-heading-p) (org-back-to-heading t))
1397 ;; Take care of EXPORT_TITLE. If it isn't defined, use headline's
1398 ;; title as its fallback value.
1399 (when (setq prop (or (org-entry-get (point) "EXPORT_TITLE")
1400 (progn (looking-at org-todo-line-regexp)
1401 (org-match-string-no-properties 3))))
1402 (setq plist
1403 (plist-put
1404 plist :title
1405 (org-element-parse-secondary-string
1406 prop (org-element-restriction 'keyword)))))
1407 ;; EXPORT_OPTIONS are parsed in a non-standard way.
1408 (when (setq prop (org-entry-get (point) "EXPORT_OPTIONS"))
1409 (setq plist
1410 (nconc plist (org-export--parse-option-keyword prop backend))))
1411 ;; Handle other keywords. TITLE keyword is excluded as it has
1412 ;; been handled already.
1413 (let ((seen '("TITLE")))
1414 (mapc
1415 (lambda (option)
1416 (let ((property (nth 1 option)))
1417 (when (and property (not (member property seen)))
1418 (let* ((subtree-prop (concat "EXPORT_" property))
1419 ;; Export properties are not case-sensitive.
1420 (value (let ((case-fold-search t))
1421 (org-entry-get (point) subtree-prop))))
1422 (push property seen)
1423 (when value
1424 (setq plist
1425 (plist-put
1426 plist
1427 (car option)
1428 (cond
1429 ;; Parse VALUE if required.
1430 ((member property org-element-document-properties)
1431 (org-element-parse-secondary-string
1432 value (org-element-restriction 'keyword)))
1433 ;; If BEHAVIOUR is `split' expected value is
1434 ;; a list of strings, not a string.
1435 ((eq (nth 4 option) 'split) (org-split-string value))
1436 (t value)))))))))
1437 ;; Also look for both general keywords and back-end specific
1438 ;; options if BACKEND is provided.
1439 (append (and backend (org-export-backend-options backend))
1440 org-export-options-alist)))
1441 ;; Return value.
1442 plist)))
1444 (defun org-export--get-inbuffer-options (&optional backend files)
1445 "Return current buffer export options, as a plist.
1447 Optional argument BACKEND, when non-nil, is a symbol specifying
1448 which back-end specific options should also be read in the
1449 process.
1451 Optional argument FILES is a list of setup files names read so
1452 far, used to avoid circular dependencies.
1454 Assume buffer is in Org mode. Narrowing, if any, is ignored."
1455 (org-with-wide-buffer
1456 (goto-char (point-min))
1457 (let ((case-fold-search t) plist)
1458 ;; 1. Special keywords, as in `org-export-special-keywords'.
1459 (let ((special-re
1460 (format "^[ \t]*#\\+%s:" (regexp-opt org-export-special-keywords))))
1461 (while (re-search-forward special-re nil t)
1462 (let ((element (org-element-at-point)))
1463 (when (eq (org-element-type element) 'keyword)
1464 (let* ((key (org-element-property :key element))
1465 (val (org-element-property :value element))
1466 (prop
1467 (cond
1468 ((equal key "SETUP_FILE")
1469 (let ((file
1470 (expand-file-name
1471 (org-remove-double-quotes (org-trim val)))))
1472 ;; Avoid circular dependencies.
1473 (unless (member file files)
1474 (with-temp-buffer
1475 (insert (org-file-contents file 'noerror))
1476 (org-mode)
1477 (org-export--get-inbuffer-options
1478 backend (cons file files))))))
1479 ((equal key "OPTIONS")
1480 (org-export--parse-option-keyword val backend))
1481 ((equal key "FILETAGS")
1482 (list :filetags
1483 (org-uniquify
1484 (append (org-split-string val ":")
1485 (plist-get plist :filetags))))))))
1486 (setq plist (org-combine-plists plist prop)))))))
1487 ;; 2. Standard options, as in `org-export-options-alist'.
1488 (let* ((all (append org-export-options-alist
1489 ;; Also look for back-end specific options if
1490 ;; BACKEND is defined.
1491 (and backend (org-export-backend-options backend))))
1492 ;; Build ALIST between keyword name and property name.
1493 (alist
1494 (delq nil (mapcar
1495 (lambda (e) (when (nth 1 e) (cons (nth 1 e) (car e))))
1496 all)))
1497 ;; Build regexp matching all keywords associated to export
1498 ;; options. Note: the search is case insensitive.
1499 (opt-re (format "^[ \t]*#\\+%s:"
1500 (regexp-opt
1501 (delq nil (mapcar (lambda (e) (nth 1 e)) all))))))
1502 (goto-char (point-min))
1503 (while (re-search-forward opt-re nil t)
1504 (let ((element (org-element-at-point)))
1505 (when (eq (org-element-type element) 'keyword)
1506 (let* ((key (org-element-property :key element))
1507 (val (org-element-property :value element))
1508 (prop (cdr (assoc key alist)))
1509 (behaviour (nth 4 (assq prop all))))
1510 (setq plist
1511 (plist-put
1512 plist prop
1513 ;; Handle value depending on specified BEHAVIOUR.
1514 (case behaviour
1515 (space
1516 (if (not (plist-get plist prop)) (org-trim val)
1517 (concat (plist-get plist prop) " " (org-trim val))))
1518 (newline
1519 (org-trim
1520 (concat (plist-get plist prop) "\n" (org-trim val))))
1521 (split
1522 `(,@(plist-get plist prop) ,@(org-split-string val)))
1523 ('t val)
1524 (otherwise (if (not (plist-member plist prop)) val
1525 (plist-get plist prop))))))))))
1526 ;; Parse keywords specified in
1527 ;; `org-element-document-properties'.
1528 (mapc
1529 (lambda (key)
1530 (let* ((prop (cdr (assoc key alist)))
1531 (value (and prop (plist-get plist prop))))
1532 (when (stringp value)
1533 (setq plist
1534 (plist-put
1535 plist prop
1536 (org-element-parse-secondary-string
1537 value (org-element-restriction 'keyword)))))))
1538 org-element-document-properties))
1539 ;; 3. Return final value.
1540 plist)))
1542 (defun org-export--get-buffer-attributes ()
1543 "Return properties related to buffer attributes, as a plist."
1544 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
1545 (list
1546 ;; Store full path of input file name, or nil. For internal use.
1547 :input-file visited-file
1548 :title (or (and visited-file
1549 (file-name-sans-extension
1550 (file-name-nondirectory visited-file)))
1551 (buffer-name (buffer-base-buffer))))))
1553 (defun org-export--get-global-options (&optional backend)
1554 "Return global export options as a plist.
1556 Optional argument BACKEND, if non-nil, is a symbol specifying
1557 which back-end specific export options should also be read in the
1558 process."
1559 (let ((all (append org-export-options-alist
1560 (and backend (org-export-backend-options backend))))
1561 ;; Output value.
1562 plist)
1563 (mapc
1564 (lambda (cell)
1565 (setq plist
1566 (plist-put
1567 plist
1568 (car cell)
1569 ;; Eval default value provided. If keyword is a member
1570 ;; of `org-element-document-properties', parse it as
1571 ;; a secondary string before storing it.
1572 (let ((value (eval (nth 3 cell))))
1573 (if (not (stringp value)) value
1574 (let ((keyword (nth 1 cell)))
1575 (if (not (member keyword org-element-document-properties))
1576 value
1577 (org-element-parse-secondary-string
1578 value (org-element-restriction 'keyword)))))))))
1579 all)
1580 ;; Return value.
1581 plist))
1583 (defvar org-export--allow-BIND-local nil)
1584 (defun org-export--confirm-letbind ()
1585 "Can we use #+BIND values during export?
1586 By default this will ask for confirmation by the user, to divert
1587 possible security risks."
1588 (cond
1589 ((not org-export-allow-BIND) nil)
1590 ((eq org-export-allow-BIND t) t)
1591 ((local-variable-p 'org-export--allow-BIND-local)
1592 org-export--allow-BIND-local)
1593 (t (org-set-local 'org-export--allow-BIND-local
1594 (yes-or-no-p "Allow BIND values in this buffer? ")))))
1596 (defun org-export--install-letbind-maybe ()
1597 "Install the values from #+BIND lines as local variables.
1598 Variables must be installed before in-buffer options are
1599 retrieved."
1600 (let ((case-fold-search t) letbind pair)
1601 (org-with-wide-buffer
1602 (goto-char (point-min))
1603 (while (re-search-forward "^[ \t]*#\\+BIND:" nil t)
1604 (let* ((element (org-element-at-point))
1605 (value (org-element-property :value element)))
1606 (when (and (eq (org-element-type element) 'keyword)
1607 (not (equal value ""))
1608 (org-export--confirm-letbind))
1609 (push (read (format "(%s)" value)) letbind)))))
1610 (dolist (pair (nreverse letbind))
1611 (org-set-local (car pair) (nth 1 pair)))))
1614 ;;;; Tree Properties
1616 ;; Tree properties are information extracted from parse tree. They
1617 ;; are initialized at the beginning of the transcoding process by
1618 ;; `org-export-collect-tree-properties'.
1620 ;; Dedicated functions focus on computing the value of specific tree
1621 ;; properties during initialization. Thus,
1622 ;; `org-export--populate-ignore-list' lists elements and objects that
1623 ;; should be skipped during export, `org-export--get-min-level' gets
1624 ;; the minimal exportable level, used as a basis to compute relative
1625 ;; level for headlines. Eventually
1626 ;; `org-export--collect-headline-numbering' builds an alist between
1627 ;; headlines and their numbering.
1629 (defun org-export-collect-tree-properties (data info)
1630 "Extract tree properties from parse tree.
1632 DATA is the parse tree from which information is retrieved. INFO
1633 is a list holding export options.
1635 Following tree properties are set or updated:
1637 `:exported-data' Hash table used to memoize results from
1638 `org-export-data'.
1640 `:footnote-definition-alist' List of footnotes definitions in
1641 original buffer and current parse tree.
1643 `:headline-offset' Offset between true level of headlines and
1644 local level. An offset of -1 means an headline
1645 of level 2 should be considered as a level
1646 1 headline in the context.
1648 `:headline-numbering' Alist of all headlines as key an the
1649 associated numbering as value.
1651 `:ignore-list' List of elements that should be ignored during
1652 export.
1654 `:target-list' List of all targets in the parse tree.
1656 Return updated plist."
1657 ;; Install the parse tree in the communication channel, in order to
1658 ;; use `org-export-get-genealogy' and al.
1659 (setq info (plist-put info :parse-tree data))
1660 ;; Get the list of elements and objects to ignore, and put it into
1661 ;; `:ignore-list'. Do not overwrite any user ignore that might have
1662 ;; been done during parse tree filtering.
1663 (setq info
1664 (plist-put info
1665 :ignore-list
1666 (append (org-export--populate-ignore-list data info)
1667 (plist-get info :ignore-list))))
1668 ;; Compute `:headline-offset' in order to be able to use
1669 ;; `org-export-get-relative-level'.
1670 (setq info
1671 (plist-put info
1672 :headline-offset
1673 (- 1 (org-export--get-min-level data info))))
1674 ;; Update footnotes definitions list with definitions in parse tree.
1675 ;; This is required since buffer expansion might have modified
1676 ;; boundaries of footnote definitions contained in the parse tree.
1677 ;; This way, definitions in `footnote-definition-alist' are bound to
1678 ;; match those in the parse tree.
1679 (let ((defs (plist-get info :footnote-definition-alist)))
1680 (org-element-map
1681 data 'footnote-definition
1682 (lambda (fn)
1683 (push (cons (org-element-property :label fn)
1684 `(org-data nil ,@(org-element-contents fn)))
1685 defs)))
1686 (setq info (plist-put info :footnote-definition-alist defs)))
1687 ;; Properties order doesn't matter: get the rest of the tree
1688 ;; properties.
1689 (nconc
1690 `(:target-list
1691 ,(org-element-map
1692 data '(keyword target)
1693 (lambda (blob)
1694 (when (or (eq (org-element-type blob) 'target)
1695 (string= (org-element-property :key blob) "TARGET"))
1696 blob)) info)
1697 :headline-numbering ,(org-export--collect-headline-numbering data info)
1698 :exported-data ,(make-hash-table :test 'eq :size 4001))
1699 info))
1701 (defun org-export--get-min-level (data options)
1702 "Return minimum exportable headline's level in DATA.
1703 DATA is parsed tree as returned by `org-element-parse-buffer'.
1704 OPTIONS is a plist holding export options."
1705 (catch 'exit
1706 (let ((min-level 10000))
1707 (mapc
1708 (lambda (blob)
1709 (when (and (eq (org-element-type blob) 'headline)
1710 (not (memq blob (plist-get options :ignore-list))))
1711 (setq min-level
1712 (min (org-element-property :level blob) min-level)))
1713 (when (= min-level 1) (throw 'exit 1)))
1714 (org-element-contents data))
1715 ;; If no headline was found, for the sake of consistency, set
1716 ;; minimum level to 1 nonetheless.
1717 (if (= min-level 10000) 1 min-level))))
1719 (defun org-export--collect-headline-numbering (data options)
1720 "Return numbering of all exportable headlines in a parse tree.
1722 DATA is the parse tree. OPTIONS is the plist holding export
1723 options.
1725 Return an alist whose key is an headline and value is its
1726 associated numbering \(in the shape of a list of numbers\)."
1727 (let ((numbering (make-vector org-export-max-depth 0)))
1728 (org-element-map
1729 data
1730 'headline
1731 (lambda (headline)
1732 (let ((relative-level
1733 (1- (org-export-get-relative-level headline options))))
1734 (cons
1735 headline
1736 (loop for n across numbering
1737 for idx from 0 to org-export-max-depth
1738 when (< idx relative-level) collect n
1739 when (= idx relative-level) collect (aset numbering idx (1+ n))
1740 when (> idx relative-level) do (aset numbering idx 0)))))
1741 options)))
1743 (defun org-export--populate-ignore-list (data options)
1744 "Return list of elements and objects to ignore during export.
1745 DATA is the parse tree to traverse. OPTIONS is the plist holding
1746 export options."
1747 (let* (ignore
1748 walk-data
1749 ;; First find trees containing a select tag, if any.
1750 (selected (org-export--selected-trees data options))
1751 (walk-data
1752 (lambda (data)
1753 ;; Collect ignored elements or objects into IGNORE-LIST.
1754 (let ((type (org-element-type data)))
1755 (if (org-export--skip-p data options selected) (push data ignore)
1756 (if (and (eq type 'headline)
1757 (eq (plist-get options :with-archived-trees) 'headline)
1758 (org-element-property :archivedp data))
1759 ;; If headline is archived but tree below has
1760 ;; to be skipped, add it to ignore list.
1761 (mapc (lambda (e) (push e ignore))
1762 (org-element-contents data))
1763 ;; Move into secondary string, if any.
1764 (let ((sec-prop
1765 (cdr (assq type org-element-secondary-value-alist))))
1766 (when sec-prop
1767 (mapc walk-data (org-element-property sec-prop data))))
1768 ;; Move into recursive objects/elements.
1769 (mapc walk-data (org-element-contents data))))))))
1770 ;; Main call.
1771 (funcall walk-data data)
1772 ;; Return value.
1773 ignore))
1775 (defun org-export--selected-trees (data info)
1776 "Return list of headlines containing a select tag in their tree.
1777 DATA is parsed data as returned by `org-element-parse-buffer'.
1778 INFO is a plist holding export options."
1779 (let* (selected-trees
1780 walk-data ; for byte-compiler.
1781 (walk-data
1782 (function
1783 (lambda (data genealogy)
1784 (case (org-element-type data)
1785 (org-data (mapc (lambda (el) (funcall walk-data el genealogy))
1786 (org-element-contents data)))
1787 (headline
1788 (let ((tags (org-element-property :tags data)))
1789 (if (loop for tag in (plist-get info :select-tags)
1790 thereis (member tag tags))
1791 ;; When a select tag is found, mark full
1792 ;; genealogy and every headline within the tree
1793 ;; as acceptable.
1794 (setq selected-trees
1795 (append
1796 genealogy
1797 (org-element-map data 'headline 'identity)
1798 selected-trees))
1799 ;; Else, continue searching in tree, recursively.
1800 (mapc
1801 (lambda (el) (funcall walk-data el (cons data genealogy)))
1802 (org-element-contents data))))))))))
1803 (funcall walk-data data nil) selected-trees))
1805 (defun org-export--skip-p (blob options selected)
1806 "Non-nil when element or object BLOB should be skipped during export.
1807 OPTIONS is the plist holding export options. SELECTED, when
1808 non-nil, is a list of headlines belonging to a tree with a select
1809 tag."
1810 (case (org-element-type blob)
1811 (clock (not (plist-get options :with-clocks)))
1812 (drawer
1813 (or (not (plist-get options :with-drawers))
1814 (and (consp (plist-get options :with-drawers))
1815 (not (member (org-element-property :drawer-name blob)
1816 (plist-get options :with-drawers))))))
1817 (headline
1818 (let ((with-tasks (plist-get options :with-tasks))
1819 (todo (org-element-property :todo-keyword blob))
1820 (todo-type (org-element-property :todo-type blob))
1821 (archived (plist-get options :with-archived-trees))
1822 (tags (org-element-property :tags blob)))
1824 ;; Ignore subtrees with an exclude tag.
1825 (loop for k in (plist-get options :exclude-tags)
1826 thereis (member k tags))
1827 ;; When a select tag is present in the buffer, ignore any tree
1828 ;; without it.
1829 (and selected (not (memq blob selected)))
1830 ;; Ignore commented sub-trees.
1831 (org-element-property :commentedp blob)
1832 ;; Ignore archived subtrees if `:with-archived-trees' is nil.
1833 (and (not archived) (org-element-property :archivedp blob))
1834 ;; Ignore tasks, if specified by `:with-tasks' property.
1835 (and todo
1836 (or (not with-tasks)
1837 (and (memq with-tasks '(todo done))
1838 (not (eq todo-type with-tasks)))
1839 (and (consp with-tasks) (not (member todo with-tasks))))))))
1840 (inlinetask (not (plist-get options :with-inlinetasks)))
1841 (planning (not (plist-get options :with-plannings)))
1842 (statistics-cookie (not (plist-get options :with-statistics-cookies)))
1843 (table-cell
1844 (and (org-export-table-has-special-column-p
1845 (org-export-get-parent-table blob))
1846 (not (org-export-get-previous-element blob options))))
1847 (table-row (org-export-table-row-is-special-p blob options))
1848 (timestamp
1849 (case (plist-get options :with-timestamps)
1850 ;; No timestamp allowed.
1851 ('nil t)
1852 ;; Only active timestamps allowed and the current one isn't
1853 ;; active.
1854 (active
1855 (not (memq (org-element-property :type blob)
1856 '(active active-range))))
1857 ;; Only inactive timestamps allowed and the current one isn't
1858 ;; inactive.
1859 (inactive
1860 (not (memq (org-element-property :type blob)
1861 '(inactive inactive-range))))))))
1865 ;;; The Transcoder
1867 ;; `org-export-data' reads a parse tree (obtained with, i.e.
1868 ;; `org-element-parse-buffer') and transcodes it into a specified
1869 ;; back-end output. It takes care of filtering out elements or
1870 ;; objects according to export options and organizing the output blank
1871 ;; lines and white space are preserved. The function memoizes its
1872 ;; results, so it is cheap to call it within translators.
1874 ;; Internally, three functions handle the filtering of objects and
1875 ;; elements during the export. In particular,
1876 ;; `org-export-ignore-element' marks an element or object so future
1877 ;; parse tree traversals skip it, `org-export--interpret-p' tells which
1878 ;; elements or objects should be seen as real Org syntax and
1879 ;; `org-export-expand' transforms the others back into their original
1880 ;; shape
1882 ;; `org-export-transcoder' is an accessor returning appropriate
1883 ;; translator function for a given element or object.
1885 (defun org-export-transcoder (blob info)
1886 "Return appropriate transcoder for BLOB.
1887 INFO is a plist containing export directives."
1888 (let ((type (org-element-type blob)))
1889 ;; Return contents only for complete parse trees.
1890 (if (eq type 'org-data) (lambda (blob contents info) contents)
1891 (let ((transcoder (cdr (assq type (plist-get info :translate-alist)))))
1892 (and (functionp transcoder) transcoder)))))
1894 (defun org-export-data (data info)
1895 "Convert DATA into current back-end format.
1897 DATA is a parse tree, an element or an object or a secondary
1898 string. INFO is a plist holding export options.
1900 Return transcoded string."
1901 (let ((memo (gethash data (plist-get info :exported-data) 'no-memo)))
1902 (if (not (eq memo 'no-memo)) memo
1903 (let* ((type (org-element-type data))
1904 (results
1905 (cond
1906 ;; Ignored element/object.
1907 ((memq data (plist-get info :ignore-list)) nil)
1908 ;; Plain text. All residual text properties from parse
1909 ;; tree (i.e. `:parent' property) are removed.
1910 ((eq type 'plain-text)
1911 (org-no-properties
1912 (org-export-filter-apply-functions
1913 (plist-get info :filter-plain-text)
1914 (let ((transcoder (org-export-transcoder data info)))
1915 (if transcoder (funcall transcoder data info) data))
1916 info)))
1917 ;; Uninterpreted element/object: change it back to Org
1918 ;; syntax and export again resulting raw string.
1919 ((not (org-export--interpret-p data info))
1920 (org-export-data
1921 (org-export-expand
1922 data
1923 (mapconcat (lambda (blob) (org-export-data blob info))
1924 (org-element-contents data)
1925 ""))
1926 info))
1927 ;; Secondary string.
1928 ((not type)
1929 (mapconcat (lambda (obj) (org-export-data obj info)) data ""))
1930 ;; Element/Object without contents or, as a special case,
1931 ;; headline with archive tag and archived trees restricted
1932 ;; to title only.
1933 ((or (not (org-element-contents data))
1934 (and (eq type 'headline)
1935 (eq (plist-get info :with-archived-trees) 'headline)
1936 (org-element-property :archivedp data)))
1937 (let ((transcoder (org-export-transcoder data info)))
1938 (and (functionp transcoder)
1939 (funcall transcoder data nil info))))
1940 ;; Element/Object with contents.
1942 (let ((transcoder (org-export-transcoder data info)))
1943 (when transcoder
1944 (let* ((greaterp (memq type org-element-greater-elements))
1945 (objectp
1946 (and (not greaterp)
1947 (memq type org-element-recursive-objects)))
1948 (contents
1949 (mapconcat
1950 (lambda (element) (org-export-data element info))
1951 (org-element-contents
1952 (if (or greaterp objectp) data
1953 ;; Elements directly containing objects
1954 ;; must have their indentation normalized
1955 ;; first.
1956 (org-element-normalize-contents
1957 data
1958 ;; When normalizing contents of the first
1959 ;; paragraph in an item or a footnote
1960 ;; definition, ignore first line's
1961 ;; indentation: there is none and it
1962 ;; might be misleading.
1963 (when (eq type 'paragraph)
1964 (let ((parent (org-export-get-parent data)))
1965 (and
1966 (eq (car (org-element-contents parent))
1967 data)
1968 (memq (org-element-type parent)
1969 '(footnote-definition item))))))))
1970 "")))
1971 (funcall transcoder data
1972 (if (not greaterp) contents
1973 (org-element-normalize-string contents))
1974 info))))))))
1975 ;; Final result will be memoized before being returned.
1976 (puthash
1977 data
1978 (cond
1979 ((not results) nil)
1980 ((memq type '(org-data plain-text nil)) results)
1981 ;; Append the same white space between elements or objects as in
1982 ;; the original buffer, and call appropriate filters.
1984 (let ((results
1985 (org-export-filter-apply-functions
1986 (plist-get info (intern (format ":filter-%s" type)))
1987 (let ((post-blank (or (org-element-property :post-blank data)
1988 0)))
1989 (if (memq type org-element-all-elements)
1990 (concat (org-element-normalize-string results)
1991 (make-string post-blank ?\n))
1992 (concat results (make-string post-blank ? ))))
1993 info)))
1994 results)))
1995 (plist-get info :exported-data))))))
1997 (defun org-export--interpret-p (blob info)
1998 "Non-nil if element or object BLOB should be interpreted as Org syntax.
1999 Check is done according to export options INFO, stored as
2000 a plist."
2001 (case (org-element-type blob)
2002 ;; ... entities...
2003 (entity (plist-get info :with-entities))
2004 ;; ... emphasis...
2005 (emphasis (plist-get info :with-emphasize))
2006 ;; ... fixed-width areas.
2007 (fixed-width (plist-get info :with-fixed-width))
2008 ;; ... footnotes...
2009 ((footnote-definition footnote-reference)
2010 (plist-get info :with-footnotes))
2011 ;; ... sub/superscripts...
2012 ((subscript superscript)
2013 (let ((sub/super-p (plist-get info :with-sub-superscript)))
2014 (if (eq sub/super-p '{})
2015 (org-element-property :use-brackets-p blob)
2016 sub/super-p)))
2017 ;; ... tables...
2018 (table (plist-get info :with-tables))
2019 (otherwise t)))
2021 (defun org-export-expand (blob contents)
2022 "Expand a parsed element or object to its original state.
2023 BLOB is either an element or an object. CONTENTS is its
2024 contents, as a string or nil."
2025 (funcall
2026 (intern (format "org-element-%s-interpreter" (org-element-type blob)))
2027 blob contents))
2029 (defun org-export-ignore-element (element info)
2030 "Add ELEMENT to `:ignore-list' in INFO.
2032 Any element in `:ignore-list' will be skipped when using
2033 `org-element-map'. INFO is modified by side effects."
2034 (plist-put info :ignore-list (cons element (plist-get info :ignore-list))))
2038 ;;; The Filter System
2040 ;; Filters allow end-users to tweak easily the transcoded output.
2041 ;; They are the functional counterpart of hooks, as every filter in
2042 ;; a set is applied to the return value of the previous one.
2044 ;; Every set is back-end agnostic. Although, a filter is always
2045 ;; called, in addition to the string it applies to, with the back-end
2046 ;; used as argument, so it's easy for the end-user to add back-end
2047 ;; specific filters in the set. The communication channel, as
2048 ;; a plist, is required as the third argument.
2050 ;; From the developer side, filters sets can be installed in the
2051 ;; process with the help of `org-export-define-backend', which
2052 ;; internally stores filters as an alist. Each association has a key
2053 ;; among the following symbols and a function or a list of functions
2054 ;; as value.
2056 ;; - `:filter-parse-tree' applies directly on the complete parsed
2057 ;; tree. It's the only filters set that doesn't apply to a string.
2058 ;; Users can set it through `org-export-filter-parse-tree-functions'
2059 ;; variable.
2061 ;; - `:filter-final-output' applies to the final transcoded string.
2062 ;; Users can set it with `org-export-filter-final-output-functions'
2063 ;; variable
2065 ;; - `:filter-plain-text' applies to any string not recognized as Org
2066 ;; syntax. `org-export-filter-plain-text-functions' allows users to
2067 ;; configure it.
2069 ;; - `:filter-TYPE' applies on the string returned after an element or
2070 ;; object of type TYPE has been transcoded. An user can modify
2071 ;; `org-export-filter-TYPE-functions'
2073 ;; All filters sets are applied with
2074 ;; `org-export-filter-apply-functions' function. Filters in a set are
2075 ;; applied in a LIFO fashion. It allows developers to be sure that
2076 ;; their filters will be applied first.
2078 ;; Filters properties are installed in communication channel with
2079 ;; `org-export-install-filters' function.
2081 ;; Eventually, two hooks (`org-export-before-processing-hook' and
2082 ;; `org-export-before-parsing-hook') are run at the beginning of the
2083 ;; export process and just before parsing to allow for heavy structure
2084 ;; modifications.
2087 ;;;; Hooks
2089 (defvar org-export-before-processing-hook nil
2090 "Hook run at the beginning of the export process.
2092 This is run before include keywords and macros are expanded and
2093 Babel code blocks executed, on a copy of the original buffer
2094 being exported. Visibility and narrowing are preserved. Point
2095 is at the beginning of the buffer.
2097 Every function in this hook will be called with one argument: the
2098 back-end currently used, as a symbol.")
2100 (defvar org-export-before-parsing-hook nil
2101 "Hook run before parsing an export buffer.
2103 This is run after include keywords and macros have been expanded
2104 and Babel code blocks executed, on a copy of the original buffer
2105 being exported. Visibility and narrowing are preserved. Point
2106 is at the beginning of the buffer.
2108 Every function in this hook will be called with one argument: the
2109 back-end currently used, as a symbol.")
2112 ;;;; Special Filters
2114 (defvar org-export-filter-parse-tree-functions nil
2115 "List of functions applied to the parsed tree.
2116 Each filter is called with three arguments: the parse tree, as
2117 returned by `org-element-parse-buffer', the back-end, as
2118 a symbol, and the communication channel, as a plist. It must
2119 return the modified parse tree to transcode.")
2121 (defvar org-export-filter-final-output-functions nil
2122 "List of functions applied to the transcoded string.
2123 Each filter is called with three arguments: the full transcoded
2124 string, the back-end, as a symbol, and the communication channel,
2125 as a plist. It must return a string that will be used as the
2126 final export output.")
2128 (defvar org-export-filter-plain-text-functions nil
2129 "List of functions applied to plain text.
2130 Each filter is called with three arguments: a string which
2131 contains no Org syntax, the back-end, as a symbol, and the
2132 communication channel, as a plist. It must return a string or
2133 nil.")
2136 ;;;; Elements Filters
2138 (defvar org-export-filter-babel-call-functions nil
2139 "List of functions applied to a transcoded babel-call.
2140 Each filter is called with three arguments: the transcoded data,
2141 as a string, the back-end, as a symbol, and the communication
2142 channel, as a plist. It must return a string or nil.")
2144 (defvar org-export-filter-center-block-functions nil
2145 "List of functions applied to a transcoded center block.
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-clock-functions nil
2151 "List of functions applied to a transcoded clock.
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-comment-functions nil
2157 "List of functions applied to a transcoded comment.
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-block-functions nil
2163 "List of functions applied to a transcoded comment-block.
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-diary-sexp-functions nil
2169 "List of functions applied to a transcoded diary-sexp.
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-drawer-functions nil
2175 "List of functions applied to a transcoded drawer.
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-dynamic-block-functions nil
2181 "List of functions applied to a transcoded dynamic-block.
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-example-block-functions nil
2187 "List of functions applied to a transcoded example-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-export-block-functions nil
2193 "List of functions applied to a transcoded export-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-fixed-width-functions nil
2199 "List of functions applied to a transcoded fixed-width.
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-footnote-definition-functions nil
2205 "List of functions applied to a transcoded footnote-definition.
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-headline-functions nil
2211 "List of functions applied to a transcoded headline.
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-horizontal-rule-functions nil
2217 "List of functions applied to a transcoded horizontal-rule.
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-inlinetask-functions nil
2223 "List of functions applied to a transcoded inlinetask.
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-item-functions nil
2229 "List of functions applied to a transcoded item.
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-keyword-functions nil
2235 "List of functions applied to a transcoded keyword.
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-latex-environment-functions nil
2241 "List of functions applied to a transcoded latex-environment.
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-node-property-functions nil
2247 "List of functions applied to a transcoded node-property.
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-paragraph-functions nil
2253 "List of functions applied to a transcoded paragraph.
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-plain-list-functions nil
2259 "List of functions applied to a transcoded plain-list.
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-planning-functions nil
2265 "List of functions applied to a transcoded planning.
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-property-drawer-functions nil
2271 "List of functions applied to a transcoded property-drawer.
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-quote-block-functions nil
2277 "List of functions applied to a transcoded quote block.
2278 Each filter is called with three arguments: the transcoded quote
2279 data, as a string, the back-end, as a symbol, and the
2280 communication channel, as a plist. It must return a string or
2281 nil.")
2283 (defvar org-export-filter-quote-section-functions nil
2284 "List of functions applied to a transcoded quote-section.
2285 Each filter is called with three arguments: the transcoded data,
2286 as a string, the back-end, as a symbol, and the communication
2287 channel, as a plist. It must return a string or nil.")
2289 (defvar org-export-filter-section-functions nil
2290 "List of functions applied to a transcoded 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-special-block-functions nil
2296 "List of functions applied to a transcoded special block.
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-src-block-functions nil
2302 "List of functions applied to a transcoded src-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-table-functions nil
2308 "List of functions applied to a transcoded table.
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-cell-functions nil
2314 "List of functions applied to a transcoded table-cell.
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-row-functions nil
2320 "List of functions applied to a transcoded table-row.
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-verse-block-functions nil
2326 "List of functions applied to a transcoded verse block.
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.")
2332 ;;;; Objects Filters
2334 (defvar org-export-filter-bold-functions nil
2335 "List of functions applied to transcoded bold text.
2336 Each filter is called with three arguments: the transcoded data,
2337 as a string, the back-end, as a symbol, and the communication
2338 channel, as a plist. It must return a string or nil.")
2340 (defvar org-export-filter-code-functions nil
2341 "List of functions applied to transcoded code 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-entity-functions nil
2347 "List of functions applied to a transcoded entity.
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-export-snippet-functions nil
2353 "List of functions applied to a transcoded export-snippet.
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-footnote-reference-functions nil
2359 "List of functions applied to a transcoded footnote-reference.
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-inline-babel-call-functions nil
2365 "List of functions applied to a transcoded inline-babel-call.
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-src-block-functions nil
2371 "List of functions applied to a transcoded inline-src-block.
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-italic-functions nil
2377 "List of functions applied to transcoded italic text.
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-latex-fragment-functions nil
2383 "List of functions applied to a transcoded latex-fragment.
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-line-break-functions nil
2389 "List of functions applied to a transcoded line-break.
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-link-functions nil
2395 "List of functions applied to a transcoded link.
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-macro-functions nil
2401 "List of functions applied to a transcoded macro.
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-radio-target-functions nil
2407 "List of functions applied to a transcoded radio-target.
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-statistics-cookie-functions nil
2413 "List of functions applied to a transcoded statistics-cookie.
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-strike-through-functions nil
2419 "List of functions applied to transcoded strike-through text.
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-subscript-functions nil
2425 "List of functions applied to a transcoded subscript.
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-superscript-functions nil
2431 "List of functions applied to a transcoded superscript.
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-target-functions nil
2437 "List of functions applied to a transcoded target.
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-timestamp-functions nil
2443 "List of functions applied to a transcoded timestamp.
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-underline-functions nil
2449 "List of functions applied to transcoded underline text.
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-verbatim-functions nil
2455 "List of functions applied to transcoded verbatim 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.")
2461 ;;;; Filters Tools
2463 ;; Internal function `org-export-install-filters' installs filters
2464 ;; hard-coded in back-ends (developer filters) and filters from global
2465 ;; variables (user filters) in the communication channel.
2467 ;; Internal function `org-export-filter-apply-functions' takes care
2468 ;; about applying each filter in order to a given data. It ignores
2469 ;; filters returning a nil value but stops whenever a filter returns
2470 ;; an empty string.
2472 (defun org-export-filter-apply-functions (filters value info)
2473 "Call every function in FILTERS.
2475 Functions are called with arguments VALUE, current export
2476 back-end and INFO. A function returning a nil value will be
2477 skipped. If it returns the empty string, the process ends and
2478 VALUE is ignored.
2480 Call is done in a LIFO fashion, to be sure that developer
2481 specified filters, if any, are called first."
2482 (catch 'exit
2483 (dolist (filter filters value)
2484 (let ((result (funcall filter value (plist-get info :back-end) info)))
2485 (cond ((not result) value)
2486 ((equal value "") (throw 'exit nil))
2487 (t (setq value result)))))))
2489 (defun org-export-install-filters (info)
2490 "Install filters properties in communication channel.
2492 INFO is a plist containing the current communication channel.
2494 Return the updated communication channel."
2495 (let (plist)
2496 ;; Install user defined filters with `org-export-filters-alist'.
2497 (mapc (lambda (p)
2498 (setq plist (plist-put plist (car p) (eval (cdr p)))))
2499 org-export-filters-alist)
2500 ;; Prepend back-end specific filters to that list.
2501 (mapc (lambda (p)
2502 ;; Single values get consed, lists are prepended.
2503 (let ((key (car p)) (value (cdr p)))
2504 (when value
2505 (setq plist
2506 (plist-put
2507 plist key
2508 (if (atom value) (cons value (plist-get plist key))
2509 (append value (plist-get plist key))))))))
2510 (org-export-backend-filters (plist-get info :back-end)))
2511 ;; Return new communication channel.
2512 (org-combine-plists info plist)))
2516 ;;; Core functions
2518 ;; This is the room for the main function, `org-export-as', along with
2519 ;; its derivatives, `org-export-to-buffer' and `org-export-to-file'.
2520 ;; They differ only by the way they output the resulting code.
2522 ;; `org-export-output-file-name' is an auxiliary function meant to be
2523 ;; used with `org-export-to-file'. With a given extension, it tries
2524 ;; to provide a canonical file name to write export output to.
2526 ;; Note that `org-export-as' doesn't really parse the current buffer,
2527 ;; but a copy of it (with the same buffer-local variables and
2528 ;; visibility), where macros and include keywords are expanded and
2529 ;; Babel blocks are executed, if appropriate.
2530 ;; `org-export-with-current-buffer-copy' macro prepares that copy.
2532 ;; File inclusion is taken care of by
2533 ;; `org-export-expand-include-keyword' and
2534 ;; `org-export--prepare-file-contents'. Structure wise, including
2535 ;; a whole Org file in a buffer often makes little sense. For
2536 ;; example, if the file contains an headline and the include keyword
2537 ;; was within an item, the item should contain the headline. That's
2538 ;; why file inclusion should be done before any structure can be
2539 ;; associated to the file, that is before parsing.
2541 (defun org-export-as
2542 (backend &optional subtreep visible-only body-only ext-plist noexpand)
2543 "Transcode current Org buffer into BACKEND code.
2545 If narrowing is active in the current buffer, only transcode its
2546 narrowed part.
2548 If a region is active, transcode that region.
2550 When optional argument SUBTREEP is non-nil, transcode the
2551 sub-tree at point, extracting information from the headline
2552 properties first.
2554 When optional argument VISIBLE-ONLY is non-nil, don't export
2555 contents of hidden elements.
2557 When optional argument BODY-ONLY is non-nil, only return body
2558 code, without preamble nor postamble.
2560 Optional argument EXT-PLIST, when provided, is a property list
2561 with external parameters overriding Org default settings, but
2562 still inferior to file-local settings.
2564 Optional argument NOEXPAND, when non-nil, prevents included files
2565 to be expanded and Babel code to be executed.
2567 Return code as a string."
2568 ;; Barf if BACKEND isn't registered.
2569 (org-export-barf-if-invalid-backend backend)
2570 (save-excursion
2571 (save-restriction
2572 ;; Narrow buffer to an appropriate region or subtree for
2573 ;; parsing. If parsing subtree, be sure to remove main headline
2574 ;; too.
2575 (cond ((org-region-active-p)
2576 (narrow-to-region (region-beginning) (region-end)))
2577 (subtreep
2578 (org-narrow-to-subtree)
2579 (goto-char (point-min))
2580 (forward-line)
2581 (narrow-to-region (point) (point-max))))
2582 ;; Initialize communication channel with original buffer
2583 ;; attributes, unavailable in its copy.
2584 (let ((info (org-export--get-buffer-attributes)) tree)
2585 (org-export-with-current-buffer-copy
2586 ;; Run first hook with current back-end as argument.
2587 (run-hook-with-args 'org-export-before-processing-hook backend)
2588 ;; Update communication channel and get parse tree. Buffer
2589 ;; isn't parsed directly. Instead, a temporary copy is
2590 ;; created, where include keywords, macros are expanded and
2591 ;; code blocks are evaluated.
2592 (unless noexpand
2593 (org-export-expand-include-keyword)
2594 ;; Update macro templates since #+INCLUDE keywords might
2595 ;; have added some new ones.
2596 (org-macro-initialize-templates)
2597 (org-macro-replace-all org-macro-templates)
2598 ;; TODO: Setting `org-current-export-file' is required by
2599 ;; Org Babel to properly resolve noweb references. Once
2600 ;; "org-exp.el" is removed, modify
2601 ;; `org-export-blocks-preprocess' so it accepts the value
2602 ;; as an argument instead.
2603 (let ((org-current-export-file (current-buffer)))
2604 (org-export-blocks-preprocess)))
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))))
2933 ;;; Tools For Back-Ends
2935 ;; A whole set of tools is available to help build new exporters. Any
2936 ;; function general enough to have its use across many back-ends
2937 ;; should be added here.
2939 ;;;; For Affiliated Keywords
2941 ;; `org-export-read-attribute' reads a property from a given element
2942 ;; as a plist. It can be used to normalize affiliated keywords'
2943 ;; syntax.
2945 ;; Since captions can span over multiple lines and accept dual values,
2946 ;; their internal representation is a bit tricky. Therefore,
2947 ;; `org-export-get-caption' transparently returns a given element's
2948 ;; caption as a secondary string.
2950 (defun org-export-read-attribute (attribute element &optional property)
2951 "Turn ATTRIBUTE property from ELEMENT into a plist.
2953 When optional argument PROPERTY is non-nil, return the value of
2954 that property within attributes.
2956 This function assumes attributes are defined as \":keyword
2957 value\" pairs. It is appropriate for `:attr_html' like
2958 properties."
2959 (let ((attributes
2960 (let ((value (org-element-property attribute element)))
2961 (and value
2962 (read (format "(%s)" (mapconcat 'identity value " ")))))))
2963 (if property (plist-get attributes property) attributes)))
2965 (defun org-export-get-caption (element &optional shortp)
2966 "Return caption from ELEMENT as a secondary string.
2968 When optional argument SHORTP is non-nil, return short caption,
2969 as a secondary string, instead.
2971 Caption lines are separated by a white space."
2972 (let ((full-caption (org-element-property :caption element)) caption)
2973 (dolist (line full-caption (cdr caption))
2974 (let ((cap (funcall (if shortp 'cdr 'car) line)))
2975 (when cap
2976 (setq caption (nconc (list " ") (copy-sequence cap) caption)))))))
2979 ;;;; For Derived Back-ends
2981 ;; `org-export-with-backend' is a function allowing to locally use
2982 ;; another back-end to transcode some object or element. In a derived
2983 ;; back-end, it may be used as a fall-back function once all specific
2984 ;; cases have been treated.
2986 (defun org-export-with-backend (back-end data &optional contents info)
2987 "Call a transcoder from BACK-END on DATA.
2988 CONTENTS, when non-nil, is the transcoded contents of DATA
2989 element, as a string. INFO, when non-nil, is the communication
2990 channel used for export, as a plist.."
2991 (org-export-barf-if-invalid-backend back-end)
2992 (let ((type (org-element-type data)))
2993 (if (memq type '(nil org-data)) (error "No foreign transcoder available")
2994 (let ((transcoder
2995 (cdr (assq type (org-export-backend-translate-table back-end)))))
2996 (if (functionp transcoder) (funcall transcoder data contents info)
2997 (error "No foreign transcoder available"))))))
3000 ;;;; For Export Snippets
3002 ;; Every export snippet is transmitted to the back-end. Though, the
3003 ;; latter will only retain one type of export-snippet, ignoring
3004 ;; others, based on the former's target back-end. The function
3005 ;; `org-export-snippet-backend' returns that back-end for a given
3006 ;; export-snippet.
3008 (defun org-export-snippet-backend (export-snippet)
3009 "Return EXPORT-SNIPPET targeted back-end as a symbol.
3010 Translation, with `org-export-snippet-translation-alist', is
3011 applied."
3012 (let ((back-end (org-element-property :back-end export-snippet)))
3013 (intern
3014 (or (cdr (assoc back-end org-export-snippet-translation-alist))
3015 back-end))))
3018 ;;;; For Footnotes
3020 ;; `org-export-collect-footnote-definitions' is a tool to list
3021 ;; actually used footnotes definitions in the whole parse tree, or in
3022 ;; an headline, in order to add footnote listings throughout the
3023 ;; transcoded data.
3025 ;; `org-export-footnote-first-reference-p' is a predicate used by some
3026 ;; back-ends, when they need to attach the footnote definition only to
3027 ;; the first occurrence of the corresponding label.
3029 ;; `org-export-get-footnote-definition' and
3030 ;; `org-export-get-footnote-number' provide easier access to
3031 ;; additional information relative to a footnote reference.
3033 (defun org-export-collect-footnote-definitions (data info)
3034 "Return an alist between footnote numbers, labels and definitions.
3036 DATA is the parse tree from which definitions are collected.
3037 INFO is the plist used as a communication channel.
3039 Definitions are sorted by order of references. They either
3040 appear as Org data or as a secondary string for inlined
3041 footnotes. Unreferenced definitions are ignored."
3042 (let* (num-alist
3043 collect-fn ; for byte-compiler.
3044 (collect-fn
3045 (function
3046 (lambda (data)
3047 ;; Collect footnote number, label and definition in DATA.
3048 (org-element-map
3049 data 'footnote-reference
3050 (lambda (fn)
3051 (when (org-export-footnote-first-reference-p fn info)
3052 (let ((def (org-export-get-footnote-definition fn info)))
3053 (push
3054 (list (org-export-get-footnote-number fn info)
3055 (org-element-property :label fn)
3056 def)
3057 num-alist)
3058 ;; Also search in definition for nested footnotes.
3059 (when (eq (org-element-property :type fn) 'standard)
3060 (funcall collect-fn def)))))
3061 ;; Don't enter footnote definitions since it will happen
3062 ;; when their first reference is found.
3063 info nil 'footnote-definition)))))
3064 (funcall collect-fn (plist-get info :parse-tree))
3065 (reverse num-alist)))
3067 (defun org-export-footnote-first-reference-p (footnote-reference info)
3068 "Non-nil when a footnote reference is the first one for its label.
3070 FOOTNOTE-REFERENCE is the footnote reference being considered.
3071 INFO is the plist used as a communication channel."
3072 (let ((label (org-element-property :label footnote-reference)))
3073 ;; Anonymous footnotes are always a first reference.
3074 (if (not label) t
3075 ;; Otherwise, return the first footnote with the same LABEL and
3076 ;; test if it is equal to FOOTNOTE-REFERENCE.
3077 (let* (search-refs ; for byte-compiler.
3078 (search-refs
3079 (function
3080 (lambda (data)
3081 (org-element-map
3082 data 'footnote-reference
3083 (lambda (fn)
3084 (cond
3085 ((string= (org-element-property :label fn) label)
3086 (throw 'exit fn))
3087 ;; If FN isn't inlined, be sure to traverse its
3088 ;; definition before resuming search. See
3089 ;; comments in `org-export-get-footnote-number'
3090 ;; for more information.
3091 ((eq (org-element-property :type fn) 'standard)
3092 (funcall search-refs
3093 (org-export-get-footnote-definition fn info)))))
3094 ;; Don't enter footnote definitions since it will
3095 ;; happen when their first reference is found.
3096 info 'first-match 'footnote-definition)))))
3097 (eq (catch 'exit (funcall search-refs (plist-get info :parse-tree)))
3098 footnote-reference)))))
3100 (defun org-export-get-footnote-definition (footnote-reference info)
3101 "Return definition of FOOTNOTE-REFERENCE as parsed data.
3102 INFO is the plist used as a communication channel."
3103 (let ((label (org-element-property :label footnote-reference)))
3104 (or (org-element-property :inline-definition footnote-reference)
3105 (cdr (assoc label (plist-get info :footnote-definition-alist))))))
3107 (defun org-export-get-footnote-number (footnote info)
3108 "Return number associated to a footnote.
3110 FOOTNOTE is either a footnote reference or a footnote definition.
3111 INFO is the plist used as a communication channel."
3112 (let* ((label (org-element-property :label footnote))
3113 seen-refs
3114 search-ref ; For byte-compiler.
3115 (search-ref
3116 (function
3117 (lambda (data)
3118 ;; Search footnote references through DATA, filling
3119 ;; SEEN-REFS along the way.
3120 (org-element-map
3121 data 'footnote-reference
3122 (lambda (fn)
3123 (let ((fn-lbl (org-element-property :label fn)))
3124 (cond
3125 ;; Anonymous footnote match: return number.
3126 ((and (not fn-lbl) (eq fn footnote))
3127 (throw 'exit (1+ (length seen-refs))))
3128 ;; Labels match: return number.
3129 ((and label (string= label fn-lbl))
3130 (throw 'exit (1+ (length seen-refs))))
3131 ;; Anonymous footnote: it's always a new one. Also,
3132 ;; be sure to return nil from the `cond' so
3133 ;; `first-match' doesn't get us out of the loop.
3134 ((not fn-lbl) (push 'inline seen-refs) nil)
3135 ;; Label not seen so far: add it so SEEN-REFS.
3137 ;; Also search for subsequent references in
3138 ;; footnote definition so numbering follows reading
3139 ;; logic. Note that we don't have to care about
3140 ;; inline definitions, since `org-element-map'
3141 ;; already traverses them at the right time.
3143 ;; Once again, return nil to stay in the loop.
3144 ((not (member fn-lbl seen-refs))
3145 (push fn-lbl seen-refs)
3146 (funcall search-ref
3147 (org-export-get-footnote-definition fn info))
3148 nil))))
3149 ;; Don't enter footnote definitions since it will happen
3150 ;; when their first reference is found.
3151 info 'first-match 'footnote-definition)))))
3152 (catch 'exit (funcall search-ref (plist-get info :parse-tree)))))
3155 ;;;; For Headlines
3157 ;; `org-export-get-relative-level' is a shortcut to get headline
3158 ;; level, relatively to the lower headline level in the parsed tree.
3160 ;; `org-export-get-headline-number' returns the section number of an
3161 ;; headline, while `org-export-number-to-roman' allows to convert it
3162 ;; to roman numbers.
3164 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
3165 ;; `org-export-last-sibling-p' are three useful predicates when it
3166 ;; comes to fulfill the `:headline-levels' property.
3168 ;; `org-export-get-tags', `org-export-get-category' and
3169 ;; `org-export-get-node-property' extract useful information from an
3170 ;; headline or a parent headline. They all handle inheritance.
3172 (defun org-export-get-relative-level (headline info)
3173 "Return HEADLINE relative level within current parsed tree.
3174 INFO is a plist holding contextual information."
3175 (+ (org-element-property :level headline)
3176 (or (plist-get info :headline-offset) 0)))
3178 (defun org-export-low-level-p (headline info)
3179 "Non-nil when HEADLINE is considered as low level.
3181 INFO is a plist used as a communication channel.
3183 A low level headlines has a relative level greater than
3184 `:headline-levels' property value.
3186 Return value is the difference between HEADLINE relative level
3187 and the last level being considered as high enough, or nil."
3188 (let ((limit (plist-get info :headline-levels)))
3189 (when (wholenump limit)
3190 (let ((level (org-export-get-relative-level headline info)))
3191 (and (> level limit) (- level limit))))))
3193 (defun org-export-get-headline-number (headline info)
3194 "Return HEADLINE numbering as a list of numbers.
3195 INFO is a plist holding contextual information."
3196 (cdr (assoc headline (plist-get info :headline-numbering))))
3198 (defun org-export-numbered-headline-p (headline info)
3199 "Return a non-nil value if HEADLINE element should be numbered.
3200 INFO is a plist used as a communication channel."
3201 (let ((sec-num (plist-get info :section-numbers))
3202 (level (org-export-get-relative-level headline info)))
3203 (if (wholenump sec-num) (<= level sec-num) sec-num)))
3205 (defun org-export-number-to-roman (n)
3206 "Convert integer N into a roman numeral."
3207 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
3208 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
3209 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
3210 ( 1 . "I")))
3211 (res ""))
3212 (if (<= n 0)
3213 (number-to-string n)
3214 (while roman
3215 (if (>= n (caar roman))
3216 (setq n (- n (caar roman))
3217 res (concat res (cdar roman)))
3218 (pop roman)))
3219 res)))
3221 (defun org-export-get-tags (element info &optional tags inherited)
3222 "Return list of tags associated to ELEMENT.
3224 ELEMENT has either an `headline' or an `inlinetask' type. INFO
3225 is a plist used as a communication channel.
3227 Select tags (see `org-export-select-tags') and exclude tags (see
3228 `org-export-exclude-tags') are removed from the list.
3230 When non-nil, optional argument TAGS should be a list of strings.
3231 Any tag belonging to this list will also be removed.
3233 When optional argument INHERITED is non-nil, tags can also be
3234 inherited from parent headlines and FILETAGS keywords."
3235 (org-remove-if
3236 (lambda (tag) (or (member tag (plist-get info :select-tags))
3237 (member tag (plist-get info :exclude-tags))
3238 (member tag tags)))
3239 (if (not inherited) (org-element-property :tags element)
3240 ;; Build complete list of inherited tags.
3241 (let ((current-tag-list (org-element-property :tags element)))
3242 (mapc
3243 (lambda (parent)
3244 (mapc
3245 (lambda (tag)
3246 (when (and (memq (org-element-type parent) '(headline inlinetask))
3247 (not (member tag current-tag-list)))
3248 (push tag current-tag-list)))
3249 (org-element-property :tags parent)))
3250 (org-export-get-genealogy element))
3251 ;; Add FILETAGS keywords and return results.
3252 (org-uniquify (append (plist-get info :filetags) current-tag-list))))))
3254 (defun org-export-get-node-property (property blob &optional inherited)
3255 "Return node PROPERTY value for BLOB.
3257 PROPERTY is normalized symbol (i.e. `:cookie-data'). BLOB is an
3258 element or object.
3260 If optional argument INHERITED is non-nil, the value can be
3261 inherited from a parent headline.
3263 Return value is a string or nil."
3264 (let ((headline (if (eq (org-element-type blob) 'headline) blob
3265 (org-export-get-parent-headline blob))))
3266 (if (not inherited) (org-element-property property blob)
3267 (let ((parent headline) value)
3268 (catch 'found
3269 (while parent
3270 (when (plist-member (nth 1 parent) property)
3271 (throw 'found (org-element-property property parent)))
3272 (setq parent (org-element-property :parent parent))))))))
3274 (defun org-export-get-category (blob info)
3275 "Return category for element or object BLOB.
3277 INFO is a plist used as a communication channel.
3279 CATEGORY is automatically inherited from a parent headline, from
3280 #+CATEGORY: keyword or created out of original file name. If all
3281 fail, the fall-back value is \"???\"."
3282 (or (let ((headline (if (eq (org-element-type blob) 'headline) blob
3283 (org-export-get-parent-headline blob))))
3284 ;; Almost like `org-export-node-property', but we cannot trust
3285 ;; `plist-member' as every headline has a `:category'
3286 ;; property, would it be nil or equal to "???" (which has the
3287 ;; same meaning).
3288 (let ((parent headline) value)
3289 (catch 'found
3290 (while parent
3291 (let ((category (org-element-property :category parent)))
3292 (and category (not (equal "???" category))
3293 (throw 'found category)))
3294 (setq parent (org-element-property :parent parent))))))
3295 (org-element-map
3296 (plist-get info :parse-tree) 'keyword
3297 (lambda (kwd)
3298 (when (equal (org-element-property :key kwd) "CATEGORY")
3299 (org-element-property :value kwd)))
3300 info 'first-match)
3301 (let ((file (plist-get info :input-file)))
3302 (and file (file-name-sans-extension (file-name-nondirectory file))))
3303 "???"))
3305 (defun org-export-first-sibling-p (headline info)
3306 "Non-nil when HEADLINE is the first sibling in its sub-tree.
3307 INFO is a plist used as a communication channel."
3308 (not (eq (org-element-type (org-export-get-previous-element headline info))
3309 'headline)))
3311 (defun org-export-last-sibling-p (headline info)
3312 "Non-nil when HEADLINE is the last sibling in its sub-tree.
3313 INFO is a plist used as a communication channel."
3314 (not (org-export-get-next-element headline info)))
3317 ;;;; For Links
3319 ;; `org-export-solidify-link-text' turns a string into a safer version
3320 ;; for links, replacing most non-standard characters with hyphens.
3322 ;; `org-export-get-coderef-format' returns an appropriate format
3323 ;; string for coderefs.
3325 ;; `org-export-inline-image-p' returns a non-nil value when the link
3326 ;; provided should be considered as an inline image.
3328 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
3329 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
3330 ;; returns an appropriate unique identifier when found, or nil.
3332 ;; `org-export-resolve-id-link' returns the first headline with
3333 ;; specified id or custom-id in parse tree, the path to the external
3334 ;; file with the id or nil when neither was found.
3336 ;; `org-export-resolve-coderef' associates a reference to a line
3337 ;; number in the element it belongs, or returns the reference itself
3338 ;; when the element isn't numbered.
3340 (defun org-export-solidify-link-text (s)
3341 "Take link text S and make a safe target out of it."
3342 (save-match-data
3343 (mapconcat 'identity (org-split-string s "[^a-zA-Z0-9_.-:]+") "-")))
3345 (defun org-export-get-coderef-format (path desc)
3346 "Return format string for code reference link.
3347 PATH is the link path. DESC is its description."
3348 (save-match-data
3349 (cond ((not desc) "%s")
3350 ((string-match (regexp-quote (concat "(" path ")")) desc)
3351 (replace-match "%s" t t desc))
3352 (t desc))))
3354 (defun org-export-inline-image-p (link &optional rules)
3355 "Non-nil if LINK object points to an inline image.
3357 Optional argument is a set of RULES defining inline images. It
3358 is an alist where associations have the following shape:
3360 \(TYPE . REGEXP)
3362 Applying a rule means apply REGEXP against LINK's path when its
3363 type is TYPE. The function will return a non-nil value if any of
3364 the provided rules is non-nil. The default rule is
3365 `org-export-default-inline-image-rule'.
3367 This only applies to links without a description."
3368 (and (not (org-element-contents link))
3369 (let ((case-fold-search t)
3370 (rules (or rules org-export-default-inline-image-rule)))
3371 (catch 'exit
3372 (mapc
3373 (lambda (rule)
3374 (and (string= (org-element-property :type link) (car rule))
3375 (string-match (cdr rule)
3376 (org-element-property :path link))
3377 (throw 'exit t)))
3378 rules)
3379 ;; Return nil if no rule matched.
3380 nil))))
3382 (defun org-export-resolve-coderef (ref info)
3383 "Resolve a code reference REF.
3385 INFO is a plist used as a communication channel.
3387 Return associated line number in source code, or REF itself,
3388 depending on src-block or example element's switches."
3389 (org-element-map
3390 (plist-get info :parse-tree) '(example-block src-block)
3391 (lambda (el)
3392 (with-temp-buffer
3393 (insert (org-trim (org-element-property :value el)))
3394 (let* ((label-fmt (regexp-quote
3395 (or (org-element-property :label-fmt el)
3396 org-coderef-label-format)))
3397 (ref-re
3398 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
3399 (replace-regexp-in-string "%s" ref label-fmt nil t))))
3400 ;; Element containing REF is found. Resolve it to either
3401 ;; a label or a line number, as needed.
3402 (when (re-search-backward ref-re nil t)
3403 (cond
3404 ((org-element-property :use-labels el) ref)
3405 ((eq (org-element-property :number-lines el) 'continued)
3406 (+ (org-export-get-loc el info) (line-number-at-pos)))
3407 (t (line-number-at-pos)))))))
3408 info 'first-match))
3410 (defun org-export-resolve-fuzzy-link (link info)
3411 "Return LINK destination.
3413 INFO is a plist holding contextual information.
3415 Return value can be an object, an element, or nil:
3417 - If LINK path matches a target object (i.e. <<path>>) or
3418 element (i.e. \"#+TARGET: path\"), return it.
3420 - If LINK path exactly matches the name affiliated keyword
3421 \(i.e. #+NAME: path) of an element, return that element.
3423 - If LINK path exactly matches any headline name, return that
3424 element. If more than one headline share that name, priority
3425 will be given to the one with the closest common ancestor, if
3426 any, or the first one in the parse tree otherwise.
3428 - Otherwise, return nil.
3430 Assume LINK type is \"fuzzy\"."
3431 (let* ((path (org-element-property :path link))
3432 (match-title-p (eq (aref path 0) ?*)))
3433 (cond
3434 ;; First try to find a matching "<<path>>" unless user specified
3435 ;; he was looking for an headline (path starts with a *
3436 ;; character).
3437 ((and (not match-title-p)
3438 (loop for target in (plist-get info :target-list)
3439 when (string= (org-element-property :value target) path)
3440 return target)))
3441 ;; Then try to find an element with a matching "#+NAME: path"
3442 ;; affiliated keyword.
3443 ((and (not match-title-p)
3444 (org-element-map
3445 (plist-get info :parse-tree) org-element-all-elements
3446 (lambda (el)
3447 (when (string= (org-element-property :name el) path) el))
3448 info 'first-match)))
3449 ;; Last case: link either points to an headline or to
3450 ;; nothingness. Try to find the source, with priority given to
3451 ;; headlines with the closest common ancestor. If such candidate
3452 ;; is found, return it, otherwise return nil.
3454 (let ((find-headline
3455 (function
3456 ;; Return first headline whose `:raw-value' property
3457 ;; is NAME in parse tree DATA, or nil.
3458 (lambda (name data)
3459 (org-element-map
3460 data 'headline
3461 (lambda (headline)
3462 (when (string=
3463 (org-element-property :raw-value headline)
3464 name)
3465 headline))
3466 info 'first-match)))))
3467 ;; Search among headlines sharing an ancestor with link,
3468 ;; from closest to farthest.
3469 (or (catch 'exit
3470 (mapc
3471 (lambda (parent)
3472 (when (eq (org-element-type parent) 'headline)
3473 (let ((foundp (funcall find-headline path parent)))
3474 (when foundp (throw 'exit foundp)))))
3475 (org-export-get-genealogy link)) nil)
3476 ;; No match with a common ancestor: try the full parse-tree.
3477 (funcall find-headline
3478 (if match-title-p (substring path 1) path)
3479 (plist-get info :parse-tree))))))))
3481 (defun org-export-resolve-id-link (link info)
3482 "Return headline referenced as LINK destination.
3484 INFO is a plist used as a communication channel.
3486 Return value can be the headline element matched in current parse
3487 tree, a file name or nil. Assume LINK type is either \"id\" or
3488 \"custom-id\"."
3489 (let ((id (org-element-property :path link)))
3490 ;; First check if id is within the current parse tree.
3491 (or (org-element-map
3492 (plist-get info :parse-tree) 'headline
3493 (lambda (headline)
3494 (when (or (string= (org-element-property :id headline) id)
3495 (string= (org-element-property :custom-id headline) id))
3496 headline))
3497 info 'first-match)
3498 ;; Otherwise, look for external files.
3499 (cdr (assoc id (plist-get info :id-alist))))))
3501 (defun org-export-resolve-radio-link (link info)
3502 "Return radio-target object referenced as LINK destination.
3504 INFO is a plist used as a communication channel.
3506 Return value can be a radio-target object or nil. Assume LINK
3507 has type \"radio\"."
3508 (let ((path (org-element-property :path link)))
3509 (org-element-map
3510 (plist-get info :parse-tree) 'radio-target
3511 (lambda (radio)
3512 (when (equal (org-element-property :value radio) path) radio))
3513 info 'first-match)))
3516 ;;;; For References
3518 ;; `org-export-get-ordinal' associates a sequence number to any object
3519 ;; or element.
3521 (defun org-export-get-ordinal (element info &optional types predicate)
3522 "Return ordinal number of an element or object.
3524 ELEMENT is the element or object considered. INFO is the plist
3525 used as a communication channel.
3527 Optional argument TYPES, when non-nil, is a list of element or
3528 object types, as symbols, that should also be counted in.
3529 Otherwise, only provided element's type is considered.
3531 Optional argument PREDICATE is a function returning a non-nil
3532 value if the current element or object should be counted in. It
3533 accepts two arguments: the element or object being considered and
3534 the plist used as a communication channel. This allows to count
3535 only a certain type of objects (i.e. inline images).
3537 Return value is a list of numbers if ELEMENT is an headline or an
3538 item. It is nil for keywords. It represents the footnote number
3539 for footnote definitions and footnote references. If ELEMENT is
3540 a target, return the same value as if ELEMENT was the closest
3541 table, item or headline containing the target. In any other
3542 case, return the sequence number of ELEMENT among elements or
3543 objects of the same type."
3544 ;; A target keyword, representing an invisible target, never has
3545 ;; a sequence number.
3546 (unless (eq (org-element-type element) 'keyword)
3547 ;; Ordinal of a target object refer to the ordinal of the closest
3548 ;; table, item, or headline containing the object.
3549 (when (eq (org-element-type element) 'target)
3550 (setq element
3551 (loop for parent in (org-export-get-genealogy element)
3552 when
3553 (memq
3554 (org-element-type parent)
3555 '(footnote-definition footnote-reference headline item
3556 table))
3557 return parent)))
3558 (case (org-element-type element)
3559 ;; Special case 1: An headline returns its number as a list.
3560 (headline (org-export-get-headline-number element info))
3561 ;; Special case 2: An item returns its number as a list.
3562 (item (let ((struct (org-element-property :structure element)))
3563 (org-list-get-item-number
3564 (org-element-property :begin element)
3565 struct
3566 (org-list-prevs-alist struct)
3567 (org-list-parents-alist struct))))
3568 ((footnote-definition footnote-reference)
3569 (org-export-get-footnote-number element info))
3570 (otherwise
3571 (let ((counter 0))
3572 ;; Increment counter until ELEMENT is found again.
3573 (org-element-map
3574 (plist-get info :parse-tree) (or types (org-element-type element))
3575 (lambda (el)
3576 (cond
3577 ((eq element el) (1+ counter))
3578 ((not predicate) (incf counter) nil)
3579 ((funcall predicate el info) (incf counter) nil)))
3580 info 'first-match))))))
3583 ;;;; For Src-Blocks
3585 ;; `org-export-get-loc' counts number of code lines accumulated in
3586 ;; src-block or example-block elements with a "+n" switch until
3587 ;; a given element, excluded. Note: "-n" switches reset that count.
3589 ;; `org-export-unravel-code' extracts source code (along with a code
3590 ;; references alist) from an `element-block' or `src-block' type
3591 ;; element.
3593 ;; `org-export-format-code' applies a formatting function to each line
3594 ;; of code, providing relative line number and code reference when
3595 ;; appropriate. Since it doesn't access the original element from
3596 ;; which the source code is coming, it expects from the code calling
3597 ;; it to know if lines should be numbered and if code references
3598 ;; should appear.
3600 ;; Eventually, `org-export-format-code-default' is a higher-level
3601 ;; function (it makes use of the two previous functions) which handles
3602 ;; line numbering and code references inclusion, and returns source
3603 ;; code in a format suitable for plain text or verbatim output.
3605 (defun org-export-get-loc (element info)
3606 "Return accumulated lines of code up to ELEMENT.
3608 INFO is the plist used as a communication channel.
3610 ELEMENT is excluded from count."
3611 (let ((loc 0))
3612 (org-element-map
3613 (plist-get info :parse-tree)
3614 `(src-block example-block ,(org-element-type element))
3615 (lambda (el)
3616 (cond
3617 ;; ELEMENT is reached: Quit the loop.
3618 ((eq el element))
3619 ;; Only count lines from src-block and example-block elements
3620 ;; with a "+n" or "-n" switch. A "-n" switch resets counter.
3621 ((not (memq (org-element-type el) '(src-block example-block))) nil)
3622 ((let ((linums (org-element-property :number-lines el)))
3623 (when linums
3624 ;; Accumulate locs or reset them.
3625 (let ((lines (org-count-lines
3626 (org-trim (org-element-property :value el)))))
3627 (setq loc (if (eq linums 'new) lines (+ loc lines))))))
3628 ;; Return nil to stay in the loop.
3629 nil)))
3630 info 'first-match)
3631 ;; Return value.
3632 loc))
3634 (defun org-export-unravel-code (element)
3635 "Clean source code and extract references out of it.
3637 ELEMENT has either a `src-block' an `example-block' type.
3639 Return a cons cell whose CAR is the source code, cleaned from any
3640 reference and protective comma and CDR is an alist between
3641 relative line number (integer) and name of code reference on that
3642 line (string)."
3643 (let* ((line 0) refs
3644 ;; Get code and clean it. Remove blank lines at its
3645 ;; beginning and end.
3646 (code (let ((c (replace-regexp-in-string
3647 "\\`\\([ \t]*\n\\)+" ""
3648 (replace-regexp-in-string
3649 "\\(:?[ \t]*\n\\)*[ \t]*\\'" "\n"
3650 (org-element-property :value element)))))
3651 ;; If appropriate, remove global indentation.
3652 (if (or org-src-preserve-indentation
3653 (org-element-property :preserve-indent element))
3655 (org-remove-indentation c))))
3656 ;; Get format used for references.
3657 (label-fmt (regexp-quote
3658 (or (org-element-property :label-fmt element)
3659 org-coderef-label-format)))
3660 ;; Build a regexp matching a loc with a reference.
3661 (with-ref-re
3662 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)[ \t]*\\)$"
3663 (replace-regexp-in-string
3664 "%s" "\\([-a-zA-Z0-9_ ]+\\)" label-fmt nil t))))
3665 ;; Return value.
3666 (cons
3667 ;; Code with references removed.
3668 (org-element-normalize-string
3669 (mapconcat
3670 (lambda (loc)
3671 (incf line)
3672 (if (not (string-match with-ref-re loc)) loc
3673 ;; Ref line: remove ref, and signal its position in REFS.
3674 (push (cons line (match-string 3 loc)) refs)
3675 (replace-match "" nil nil loc 1)))
3676 (org-split-string code "\n") "\n"))
3677 ;; Reference alist.
3678 refs)))
3680 (defun org-export-format-code (code fun &optional num-lines ref-alist)
3681 "Format CODE by applying FUN line-wise and return it.
3683 CODE is a string representing the code to format. FUN is
3684 a function. It must accept three arguments: a line of
3685 code (string), the current line number (integer) or nil and the
3686 reference associated to the current line (string) or nil.
3688 Optional argument NUM-LINES can be an integer representing the
3689 number of code lines accumulated until the current code. Line
3690 numbers passed to FUN will take it into account. If it is nil,
3691 FUN's second argument will always be nil. This number can be
3692 obtained with `org-export-get-loc' function.
3694 Optional argument REF-ALIST can be an alist between relative line
3695 number (i.e. ignoring NUM-LINES) and the name of the code
3696 reference on it. If it is nil, FUN's third argument will always
3697 be nil. It can be obtained through the use of
3698 `org-export-unravel-code' function."
3699 (let ((--locs (org-split-string code "\n"))
3700 (--line 0))
3701 (org-element-normalize-string
3702 (mapconcat
3703 (lambda (--loc)
3704 (incf --line)
3705 (let ((--ref (cdr (assq --line ref-alist))))
3706 (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
3707 --locs "\n"))))
3709 (defun org-export-format-code-default (element info)
3710 "Return source code from ELEMENT, formatted in a standard way.
3712 ELEMENT is either a `src-block' or `example-block' element. INFO
3713 is a plist used as a communication channel.
3715 This function takes care of line numbering and code references
3716 inclusion. Line numbers, when applicable, appear at the
3717 beginning of the line, separated from the code by two white
3718 spaces. Code references, on the other hand, appear flushed to
3719 the right, separated by six white spaces from the widest line of
3720 code."
3721 ;; Extract code and references.
3722 (let* ((code-info (org-export-unravel-code element))
3723 (code (car code-info))
3724 (code-lines (org-split-string code "\n"))
3725 (refs (and (org-element-property :retain-labels element)
3726 (cdr code-info)))
3727 ;; Handle line numbering.
3728 (num-start (case (org-element-property :number-lines element)
3729 (continued (org-export-get-loc element info))
3730 (new 0)))
3731 (num-fmt
3732 (and num-start
3733 (format "%%%ds "
3734 (length (number-to-string
3735 (+ (length code-lines) num-start))))))
3736 ;; Prepare references display, if required. Any reference
3737 ;; should start six columns after the widest line of code,
3738 ;; wrapped with parenthesis.
3739 (max-width
3740 (+ (apply 'max (mapcar 'length code-lines))
3741 (if (not num-start) 0 (length (format num-fmt num-start))))))
3742 (org-export-format-code
3743 code
3744 (lambda (loc line-num ref)
3745 (let ((number-str (and num-fmt (format num-fmt line-num))))
3746 (concat
3747 number-str
3749 (and ref
3750 (concat (make-string
3751 (- (+ 6 max-width)
3752 (+ (length loc) (length number-str))) ? )
3753 (format "(%s)" ref))))))
3754 num-start refs)))
3757 ;;;; For Tables
3759 ;; `org-export-table-has-special-column-p' and and
3760 ;; `org-export-table-row-is-special-p' are predicates used to look for
3761 ;; meta-information about the table structure.
3763 ;; `org-table-has-header-p' tells when the rows before the first rule
3764 ;; should be considered as table's header.
3766 ;; `org-export-table-cell-width', `org-export-table-cell-alignment'
3767 ;; and `org-export-table-cell-borders' extract information from
3768 ;; a table-cell element.
3770 ;; `org-export-table-dimensions' gives the number on rows and columns
3771 ;; in the table, ignoring horizontal rules and special columns.
3772 ;; `org-export-table-cell-address', given a table-cell object, returns
3773 ;; the absolute address of a cell. On the other hand,
3774 ;; `org-export-get-table-cell-at' does the contrary.
3776 ;; `org-export-table-cell-starts-colgroup-p',
3777 ;; `org-export-table-cell-ends-colgroup-p',
3778 ;; `org-export-table-row-starts-rowgroup-p',
3779 ;; `org-export-table-row-ends-rowgroup-p',
3780 ;; `org-export-table-row-starts-header-p' and
3781 ;; `org-export-table-row-ends-header-p' indicate position of current
3782 ;; row or cell within the table.
3784 (defun org-export-table-has-special-column-p (table)
3785 "Non-nil when TABLE has a special column.
3786 All special columns will be ignored during export."
3787 ;; The table has a special column when every first cell of every row
3788 ;; has an empty value or contains a symbol among "/", "#", "!", "$",
3789 ;; "*" "_" and "^". Though, do not consider a first row containing
3790 ;; only empty cells as special.
3791 (let ((special-column-p 'empty))
3792 (catch 'exit
3793 (mapc
3794 (lambda (row)
3795 (when (eq (org-element-property :type row) 'standard)
3796 (let ((value (org-element-contents
3797 (car (org-element-contents row)))))
3798 (cond ((member value '(("/") ("#") ("!") ("$") ("*") ("_") ("^")))
3799 (setq special-column-p 'special))
3800 ((not value))
3801 (t (throw 'exit nil))))))
3802 (org-element-contents table))
3803 (eq special-column-p 'special))))
3805 (defun org-export-table-has-header-p (table info)
3806 "Non-nil when TABLE has an header.
3808 INFO is a plist used as a communication channel.
3810 A table has an header when it contains at least two row groups."
3811 (let ((rowgroup 1) row-flag)
3812 (org-element-map
3813 table 'table-row
3814 (lambda (row)
3815 (cond
3816 ((> rowgroup 1) t)
3817 ((and row-flag (eq (org-element-property :type row) 'rule))
3818 (incf rowgroup) (setq row-flag nil))
3819 ((and (not row-flag) (eq (org-element-property :type row) 'standard))
3820 (setq row-flag t) nil)))
3821 info)))
3823 (defun org-export-table-row-is-special-p (table-row info)
3824 "Non-nil if TABLE-ROW is considered special.
3826 INFO is a plist used as the communication channel.
3828 All special rows will be ignored during export."
3829 (when (eq (org-element-property :type table-row) 'standard)
3830 (let ((first-cell (org-element-contents
3831 (car (org-element-contents table-row)))))
3832 ;; A row is special either when...
3834 ;; ... it starts with a field only containing "/",
3835 (equal first-cell '("/"))
3836 ;; ... the table contains a special column and the row start
3837 ;; with a marking character among, "^", "_", "$" or "!",
3838 (and (org-export-table-has-special-column-p
3839 (org-export-get-parent table-row))
3840 (member first-cell '(("^") ("_") ("$") ("!"))))
3841 ;; ... it contains only alignment cookies and empty cells.
3842 (let ((special-row-p 'empty))
3843 (catch 'exit
3844 (mapc
3845 (lambda (cell)
3846 (let ((value (org-element-contents cell)))
3847 ;; Since VALUE is a secondary string, the following
3848 ;; checks avoid expanding it with `org-export-data'.
3849 (cond ((not value))
3850 ((and (not (cdr value))
3851 (stringp (car value))
3852 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'"
3853 (car value)))
3854 (setq special-row-p 'cookie))
3855 (t (throw 'exit nil)))))
3856 (org-element-contents table-row))
3857 (eq special-row-p 'cookie)))))))
3859 (defun org-export-table-row-group (table-row info)
3860 "Return TABLE-ROW's group.
3862 INFO is a plist used as the communication channel.
3864 Return value is the group number, as an integer, or nil special
3865 rows and table rules. Group 1 is also table's header."
3866 (unless (or (eq (org-element-property :type table-row) 'rule)
3867 (org-export-table-row-is-special-p table-row info))
3868 (let ((group 0) row-flag)
3869 (catch 'found
3870 (mapc
3871 (lambda (row)
3872 (cond
3873 ((and (eq (org-element-property :type row) 'standard)
3874 (not (org-export-table-row-is-special-p row info)))
3875 (unless row-flag (incf group) (setq row-flag t)))
3876 ((eq (org-element-property :type row) 'rule)
3877 (setq row-flag nil)))
3878 (when (eq table-row row) (throw 'found group)))
3879 (org-element-contents (org-export-get-parent table-row)))))))
3881 (defun org-export-table-cell-width (table-cell info)
3882 "Return TABLE-CELL contents width.
3884 INFO is a plist used as the communication channel.
3886 Return value is the width given by the last width cookie in the
3887 same column as TABLE-CELL, or nil."
3888 (let* ((row (org-export-get-parent table-cell))
3889 (column (let ((cells (org-element-contents row)))
3890 (- (length cells) (length (memq table-cell cells)))))
3891 (table (org-export-get-parent-table table-cell))
3892 cookie-width)
3893 (mapc
3894 (lambda (row)
3895 (cond
3896 ;; In a special row, try to find a width cookie at COLUMN.
3897 ((org-export-table-row-is-special-p row info)
3898 (let ((value (org-element-contents
3899 (elt (org-element-contents row) column))))
3900 ;; The following checks avoid expanding unnecessarily the
3901 ;; cell with `org-export-data'
3902 (when (and value
3903 (not (cdr value))
3904 (stringp (car value))
3905 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'" (car value))
3906 (match-string 1 (car value)))
3907 (setq cookie-width
3908 (string-to-number (match-string 1 (car value)))))))
3909 ;; Ignore table rules.
3910 ((eq (org-element-property :type row) 'rule))))
3911 (org-element-contents table))
3912 ;; Return value.
3913 cookie-width))
3915 (defun org-export-table-cell-alignment (table-cell info)
3916 "Return TABLE-CELL contents alignment.
3918 INFO is a plist used as the communication channel.
3920 Return alignment as specified by the last alignment cookie in the
3921 same column as TABLE-CELL. If no such cookie is found, a default
3922 alignment value will be deduced from fraction of numbers in the
3923 column (see `org-table-number-fraction' for more information).
3924 Possible values are `left', `right' and `center'."
3925 (let* ((row (org-export-get-parent table-cell))
3926 (column (let ((cells (org-element-contents row)))
3927 (- (length cells) (length (memq table-cell cells)))))
3928 (table (org-export-get-parent-table table-cell))
3929 (number-cells 0)
3930 (total-cells 0)
3931 cookie-align)
3932 (mapc
3933 (lambda (row)
3934 (cond
3935 ;; In a special row, try to find an alignment cookie at
3936 ;; COLUMN.
3937 ((org-export-table-row-is-special-p row info)
3938 (let ((value (org-element-contents
3939 (elt (org-element-contents row) column))))
3940 ;; Since VALUE is a secondary string, the following checks
3941 ;; avoid useless expansion through `org-export-data'.
3942 (when (and value
3943 (not (cdr value))
3944 (stringp (car value))
3945 (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'"
3946 (car value))
3947 (match-string 1 (car value)))
3948 (setq cookie-align (match-string 1 (car value))))))
3949 ;; Ignore table rules.
3950 ((eq (org-element-property :type row) 'rule))
3951 ;; In a standard row, check if cell's contents are expressing
3952 ;; some kind of number. Increase NUMBER-CELLS accordingly.
3953 ;; Though, don't bother if an alignment cookie has already
3954 ;; defined cell's alignment.
3955 ((not cookie-align)
3956 (let ((value (org-export-data
3957 (org-element-contents
3958 (elt (org-element-contents row) column))
3959 info)))
3960 (incf total-cells)
3961 (when (string-match org-table-number-regexp value)
3962 (incf number-cells))))))
3963 (org-element-contents table))
3964 ;; Return value. Alignment specified by cookies has precedence
3965 ;; over alignment deduced from cells contents.
3966 (cond ((equal cookie-align "l") 'left)
3967 ((equal cookie-align "r") 'right)
3968 ((equal cookie-align "c") 'center)
3969 ((>= (/ (float number-cells) total-cells) org-table-number-fraction)
3970 'right)
3971 (t 'left))))
3973 (defun org-export-table-cell-borders (table-cell info)
3974 "Return TABLE-CELL borders.
3976 INFO is a plist used as a communication channel.
3978 Return value is a list of symbols, or nil. Possible values are:
3979 `top', `bottom', `above', `below', `left' and `right'. Note:
3980 `top' (resp. `bottom') only happen for a cell in the first
3981 row (resp. last row) of the table, ignoring table rules, if any.
3983 Returned borders ignore special rows."
3984 (let* ((row (org-export-get-parent table-cell))
3985 (table (org-export-get-parent-table table-cell))
3986 borders)
3987 ;; Top/above border? TABLE-CELL has a border above when a rule
3988 ;; used to demarcate row groups can be found above. Hence,
3989 ;; finding a rule isn't sufficient to push `above' in BORDERS:
3990 ;; another regular row has to be found above that rule.
3991 (let (rule-flag)
3992 (catch 'exit
3993 (mapc (lambda (row)
3994 (cond ((eq (org-element-property :type row) 'rule)
3995 (setq rule-flag t))
3996 ((not (org-export-table-row-is-special-p row info))
3997 (if rule-flag (throw 'exit (push 'above borders))
3998 (throw 'exit nil)))))
3999 ;; Look at every row before the current one.
4000 (cdr (memq row (reverse (org-element-contents table)))))
4001 ;; No rule above, or rule found starts the table (ignoring any
4002 ;; special row): TABLE-CELL is at the top of the table.
4003 (when rule-flag (push 'above borders))
4004 (push 'top borders)))
4005 ;; Bottom/below border? TABLE-CELL has a border below when next
4006 ;; non-regular row below is a rule.
4007 (let (rule-flag)
4008 (catch 'exit
4009 (mapc (lambda (row)
4010 (cond ((eq (org-element-property :type row) 'rule)
4011 (setq rule-flag t))
4012 ((not (org-export-table-row-is-special-p row info))
4013 (if rule-flag (throw 'exit (push 'below borders))
4014 (throw 'exit nil)))))
4015 ;; Look at every row after the current one.
4016 (cdr (memq row (org-element-contents table))))
4017 ;; No rule below, or rule found ends the table (modulo some
4018 ;; special row): TABLE-CELL is at the bottom of the table.
4019 (when rule-flag (push 'below borders))
4020 (push 'bottom borders)))
4021 ;; Right/left borders? They can only be specified by column
4022 ;; groups. Column groups are defined in a row starting with "/".
4023 ;; Also a column groups row only contains "<", "<>", ">" or blank
4024 ;; cells.
4025 (catch 'exit
4026 (let ((column (let ((cells (org-element-contents row)))
4027 (- (length cells) (length (memq table-cell cells))))))
4028 (mapc
4029 (lambda (row)
4030 (unless (eq (org-element-property :type row) 'rule)
4031 (when (equal (org-element-contents
4032 (car (org-element-contents row)))
4033 '("/"))
4034 (let ((column-groups
4035 (mapcar
4036 (lambda (cell)
4037 (let ((value (org-element-contents cell)))
4038 (when (member value '(("<") ("<>") (">") nil))
4039 (car value))))
4040 (org-element-contents row))))
4041 ;; There's a left border when previous cell, if
4042 ;; any, ends a group, or current one starts one.
4043 (when (or (and (not (zerop column))
4044 (member (elt column-groups (1- column))
4045 '(">" "<>")))
4046 (member (elt column-groups column) '("<" "<>")))
4047 (push 'left borders))
4048 ;; There's a right border when next cell, if any,
4049 ;; starts a group, or current one ends one.
4050 (when (or (and (/= (1+ column) (length column-groups))
4051 (member (elt column-groups (1+ column))
4052 '("<" "<>")))
4053 (member (elt column-groups column) '(">" "<>")))
4054 (push 'right borders))
4055 (throw 'exit nil)))))
4056 ;; Table rows are read in reverse order so last column groups
4057 ;; row has precedence over any previous one.
4058 (reverse (org-element-contents table)))))
4059 ;; Return value.
4060 borders))
4062 (defun org-export-table-cell-starts-colgroup-p (table-cell info)
4063 "Non-nil when TABLE-CELL is at the beginning of a row group.
4064 INFO is a plist used as a communication channel."
4065 ;; A cell starts a column group either when it is at the beginning
4066 ;; of a row (or after the special column, if any) or when it has
4067 ;; a left border.
4068 (or (eq (org-element-map
4069 (org-export-get-parent table-cell)
4070 'table-cell 'identity info 'first-match)
4071 table-cell)
4072 (memq 'left (org-export-table-cell-borders table-cell info))))
4074 (defun org-export-table-cell-ends-colgroup-p (table-cell info)
4075 "Non-nil when TABLE-CELL is at the end of a row group.
4076 INFO is a plist used as a communication channel."
4077 ;; A cell ends a column group either when it is at the end of a row
4078 ;; or when it has a right border.
4079 (or (eq (car (last (org-element-contents
4080 (org-export-get-parent table-cell))))
4081 table-cell)
4082 (memq 'right (org-export-table-cell-borders table-cell info))))
4084 (defun org-export-table-row-starts-rowgroup-p (table-row info)
4085 "Non-nil when TABLE-ROW is at the beginning of a column group.
4086 INFO is a plist used as a communication channel."
4087 (unless (or (eq (org-element-property :type table-row) 'rule)
4088 (org-export-table-row-is-special-p table-row info))
4089 (let ((borders (org-export-table-cell-borders
4090 (car (org-element-contents table-row)) info)))
4091 (or (memq 'top borders) (memq 'above borders)))))
4093 (defun org-export-table-row-ends-rowgroup-p (table-row info)
4094 "Non-nil when TABLE-ROW is at the end of a column group.
4095 INFO is a plist used as a communication channel."
4096 (unless (or (eq (org-element-property :type table-row) 'rule)
4097 (org-export-table-row-is-special-p table-row info))
4098 (let ((borders (org-export-table-cell-borders
4099 (car (org-element-contents table-row)) info)))
4100 (or (memq 'bottom borders) (memq 'below borders)))))
4102 (defun org-export-table-row-starts-header-p (table-row info)
4103 "Non-nil when TABLE-ROW is the first table header's row.
4104 INFO is a plist used as a communication channel."
4105 (and (org-export-table-has-header-p
4106 (org-export-get-parent-table table-row) info)
4107 (org-export-table-row-starts-rowgroup-p table-row info)
4108 (= (org-export-table-row-group table-row info) 1)))
4110 (defun org-export-table-row-ends-header-p (table-row info)
4111 "Non-nil when TABLE-ROW is the last table header's row.
4112 INFO is a plist used as a communication channel."
4113 (and (org-export-table-has-header-p
4114 (org-export-get-parent-table table-row) info)
4115 (org-export-table-row-ends-rowgroup-p table-row info)
4116 (= (org-export-table-row-group table-row info) 1)))
4118 (defun org-export-table-dimensions (table info)
4119 "Return TABLE dimensions.
4121 INFO is a plist used as a communication channel.
4123 Return value is a CONS like (ROWS . COLUMNS) where
4124 ROWS (resp. COLUMNS) is the number of exportable
4125 rows (resp. columns)."
4126 (let (first-row (columns 0) (rows 0))
4127 ;; Set number of rows, and extract first one.
4128 (org-element-map
4129 table 'table-row
4130 (lambda (row)
4131 (when (eq (org-element-property :type row) 'standard)
4132 (incf rows)
4133 (unless first-row (setq first-row row)))) info)
4134 ;; Set number of columns.
4135 (org-element-map first-row 'table-cell (lambda (cell) (incf columns)) info)
4136 ;; Return value.
4137 (cons rows columns)))
4139 (defun org-export-table-cell-address (table-cell info)
4140 "Return address of a regular TABLE-CELL object.
4142 TABLE-CELL is the cell considered. INFO is a plist used as
4143 a communication channel.
4145 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4146 zero-based index. Only exportable cells are considered. The
4147 function returns nil for other cells."
4148 (let* ((table-row (org-export-get-parent table-cell))
4149 (table (org-export-get-parent-table table-cell)))
4150 ;; Ignore cells in special rows or in special column.
4151 (unless (or (org-export-table-row-is-special-p table-row info)
4152 (and (org-export-table-has-special-column-p table)
4153 (eq (car (org-element-contents table-row)) table-cell)))
4154 (cons
4155 ;; Row number.
4156 (let ((row-count 0))
4157 (org-element-map
4158 table 'table-row
4159 (lambda (row)
4160 (cond ((eq (org-element-property :type row) 'rule) nil)
4161 ((eq row table-row) row-count)
4162 (t (incf row-count) nil)))
4163 info 'first-match))
4164 ;; Column number.
4165 (let ((col-count 0))
4166 (org-element-map
4167 table-row 'table-cell
4168 (lambda (cell)
4169 (if (eq cell table-cell) col-count (incf col-count) nil))
4170 info 'first-match))))))
4172 (defun org-export-get-table-cell-at (address table info)
4173 "Return regular table-cell object at ADDRESS in TABLE.
4175 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4176 zero-based index. TABLE is a table type element. INFO is
4177 a plist used as a communication channel.
4179 If no table-cell, among exportable cells, is found at ADDRESS,
4180 return nil."
4181 (let ((column-pos (cdr address)) (column-count 0))
4182 (org-element-map
4183 ;; Row at (car address) or nil.
4184 (let ((row-pos (car address)) (row-count 0))
4185 (org-element-map
4186 table 'table-row
4187 (lambda (row)
4188 (cond ((eq (org-element-property :type row) 'rule) nil)
4189 ((= row-count row-pos) row)
4190 (t (incf row-count) nil)))
4191 info 'first-match))
4192 'table-cell
4193 (lambda (cell)
4194 (if (= column-count column-pos) cell
4195 (incf column-count) nil))
4196 info 'first-match)))
4199 ;;;; For Tables Of Contents
4201 ;; `org-export-collect-headlines' builds a list of all exportable
4202 ;; headline elements, maybe limited to a certain depth. One can then
4203 ;; easily parse it and transcode it.
4205 ;; Building lists of tables, figures or listings is quite similar.
4206 ;; Once the generic function `org-export-collect-elements' is defined,
4207 ;; `org-export-collect-tables', `org-export-collect-figures' and
4208 ;; `org-export-collect-listings' can be derived from it.
4210 (defun org-export-collect-headlines (info &optional n)
4211 "Collect headlines in order to build a table of contents.
4213 INFO is a plist used as a communication channel.
4215 When optional argument N is an integer, it specifies the depth of
4216 the table of contents. Otherwise, it is set to the value of the
4217 last headline level. See `org-export-headline-levels' for more
4218 information.
4220 Return a list of all exportable headlines as parsed elements."
4221 (unless (wholenump n) (setq n (plist-get info :headline-levels)))
4222 (org-element-map
4223 (plist-get info :parse-tree)
4224 'headline
4225 (lambda (headline)
4226 ;; Strip contents from HEADLINE.
4227 (let ((relative-level (org-export-get-relative-level headline info)))
4228 (unless (> relative-level n) headline)))
4229 info))
4231 (defun org-export-collect-elements (type info &optional predicate)
4232 "Collect referenceable elements of a determined type.
4234 TYPE can be a symbol or a list of symbols specifying element
4235 types to search. Only elements with a caption are collected.
4237 INFO is a plist used as a communication channel.
4239 When non-nil, optional argument PREDICATE is a function accepting
4240 one argument, an element of type TYPE. It returns a non-nil
4241 value when that element should be collected.
4243 Return a list of all elements found, in order of appearance."
4244 (org-element-map
4245 (plist-get info :parse-tree) type
4246 (lambda (element)
4247 (and (org-element-property :caption element)
4248 (or (not predicate) (funcall predicate element))
4249 element))
4250 info))
4252 (defun org-export-collect-tables (info)
4253 "Build a list of tables.
4254 INFO is a plist used as a communication channel.
4256 Return a list of table elements with a caption."
4257 (org-export-collect-elements 'table info))
4259 (defun org-export-collect-figures (info predicate)
4260 "Build a list of figures.
4262 INFO is a plist used as a communication channel. PREDICATE is
4263 a function which accepts one argument: a paragraph element and
4264 whose return value is non-nil when that element should be
4265 collected.
4267 A figure is a paragraph type element, with a caption, verifying
4268 PREDICATE. The latter has to be provided since a \"figure\" is
4269 a vague concept that may depend on back-end.
4271 Return a list of elements recognized as figures."
4272 (org-export-collect-elements 'paragraph info predicate))
4274 (defun org-export-collect-listings (info)
4275 "Build a list of src blocks.
4277 INFO is a plist used as a communication channel.
4279 Return a list of src-block elements with a caption."
4280 (org-export-collect-elements 'src-block info))
4283 ;;;; For Timestamps
4285 ;; `org-export-timestamp-has-time-p' is a predicate to know if hours
4286 ;; and minutes are defined in a given timestamp.
4288 ;; `org-export-format-timestamp' allows to format a timestamp object
4289 ;; with an arbitrary format string.
4291 (defun org-export-timestamp-has-time-p (timestamp)
4292 "Non-nil when TIMESTAMP has a time specified."
4293 (org-element-property :hour-start timestamp))
4295 (defun org-export-format-timestamp (timestamp format &optional end utc)
4296 "Format a TIMESTAMP element into a string.
4298 FORMAT is a format specifier to be passed to
4299 `format-time-string'.
4301 When optional argument END is non-nil, use end of date-range or
4302 time-range, if possible.
4304 When optional argument UTC is non-nil, time will be expressed as
4305 Universal Time."
4306 (format-time-string
4307 format
4308 (apply 'encode-time
4309 (cons 0
4310 (mapcar
4311 (lambda (prop) (or (org-element-property prop timestamp) 0))
4312 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
4313 '(:minute-start :hour-start :day-start :month-start
4314 :year-start)))))
4315 utc))
4318 ;;;; Smart Quotes
4320 ;; The main function for the smart quotes sub-system is
4321 ;; `org-export-activate-smart-quotes', which replaces every quote in
4322 ;; a given string from the parse tree with its "smart" counterpart.
4324 ;; Dictionary for smart quotes is stored in
4325 ;; `org-export-smart-quotes-alist'.
4327 ;; Internally, regexps matching potential smart quotes (checks at
4328 ;; string boundaries are also necessary) are defined in
4329 ;; `org-export-smart-quotes-regexps'.
4331 (defconst org-export-smart-quotes-alist
4332 '(("de"
4333 (opening-double-quote :utf-8 "„" :html "&bdquo;" :latex "\"`"
4334 :texinfo "@quotedblbase{}")
4335 (closing-double-quote :utf-8 "“" :html "&ldquo;" :latex "\"'"
4336 :texinfo "@quotedblleft{}")
4337 (opening-single-quote :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}"
4338 :texinfo "@quotesinglbase{}")
4339 (closing-single-quote :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}"
4340 :texinfo "@quoteleft{}")
4341 (apostrophe :utf-8 "’" :html "&rsquo;"))
4342 ("en"
4343 (opening-double-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
4344 (closing-double-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
4345 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
4346 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
4347 (apostrophe :utf-8 "’" :html "&rsquo;"))
4348 ("es"
4349 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
4350 :texinfo "@guillemetleft{}")
4351 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
4352 :texinfo "@guillemetright{}")
4353 (opening-single-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
4354 (closing-single-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
4355 (apostrophe :utf-8 "’" :html "&rsquo;"))
4356 ("fr"
4357 (opening-double-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
4358 :texinfo "@guillemetleft{}@tie{}")
4359 (closing-double-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
4360 :texinfo "@tie{}@guillemetright{}")
4361 (opening-single-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
4362 :texinfo "@guillemetleft{}@tie{}")
4363 (closing-single-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
4364 :texinfo "@tie{}@guillemetright{}")
4365 (apostrophe :utf-8 "’" :html "&rsquo;")))
4366 "Smart quotes translations.
4368 Alist whose CAR is a language string and CDR is an alist with
4369 quote type as key and a plist associating various encodings to
4370 their translation as value.
4372 A quote type can be any symbol among `opening-double-quote',
4373 `closing-double-quote', `opening-single-quote',
4374 `closing-single-quote' and `apostrophe'.
4376 Valid encodings include `:utf-8', `:html', `:latex' and
4377 `:texinfo'.
4379 If no translation is found, the quote character is left as-is.")
4381 (defconst org-export-smart-quotes-regexps
4382 (list
4383 ;; Possible opening quote at beginning of string.
4384 "\\`\\([\"']\\)\\(\\w\\|\\s.\\|\\s_\\)"
4385 ;; Possible closing quote at beginning of string.
4386 "\\`\\([\"']\\)\\(\\s-\\|\\s)\\|\\s.\\)"
4387 ;; Possible apostrophe at beginning of string.
4388 "\\`\\('\\)\\S-"
4389 ;; Opening single and double quotes.
4390 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\(?:\\w\\|\\s.\\|\\s_\\)"
4391 ;; Closing single and double quotes.
4392 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\(?:\\s-\\|\\s)\\|\\s.\\)"
4393 ;; Apostrophe.
4394 "\\S-\\('\\)\\S-"
4395 ;; Possible opening quote at end of string.
4396 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\'"
4397 ;; Possible closing quote at end of string.
4398 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\'"
4399 ;; Possible apostrophe at end of string.
4400 "\\S-\\('\\)\\'")
4401 "List of regexps matching a quote or an apostrophe.
4402 In every regexp, quote or apostrophe matched is put in group 1.")
4404 (defun org-export-activate-smart-quotes (s encoding info &optional original)
4405 "Replace regular quotes with \"smart\" quotes in string S.
4407 ENCODING is a symbol among `:html', `:latex', `:texinfo' and
4408 `:utf-8'. INFO is a plist used as a communication channel.
4410 The function has to retrieve information about string
4411 surroundings in parse tree. It can only happen with an
4412 unmodified string. Thus, if S has already been through another
4413 process, a non-nil ORIGINAL optional argument will provide that
4414 original string.
4416 Return the new string."
4417 (if (equal s "") ""
4418 (let* ((prev (org-export-get-previous-element (or original s) info))
4419 (pre-blank (and prev (org-element-property :post-blank prev)))
4420 (next (org-export-get-next-element (or original s) info))
4421 (get-smart-quote
4422 (lambda (q type)
4423 ;; Return smart quote associated to a give quote Q, as
4424 ;; a string. TYPE is a symbol among `open', `close' and
4425 ;; `apostrophe'.
4426 (let ((key (case type
4427 (apostrophe 'apostrophe)
4428 (open (if (equal "'" q) 'opening-single-quote
4429 'opening-double-quote))
4430 (otherwise (if (equal "'" q) 'closing-single-quote
4431 'closing-double-quote)))))
4432 (or (plist-get
4433 (cdr (assq key
4434 (cdr (assoc (plist-get info :language)
4435 org-export-smart-quotes-alist))))
4436 encoding)
4437 q)))))
4438 (if (or (equal "\"" s) (equal "'" s))
4439 ;; Only a quote: no regexp can match. We have to check both
4440 ;; sides and decide what to do.
4441 (cond ((and (not prev) (not next)) s)
4442 ((not prev) (funcall get-smart-quote s 'open))
4443 ((and (not next) (zerop pre-blank))
4444 (funcall get-smart-quote s 'close))
4445 ((not next) s)
4446 ((zerop pre-blank) (funcall get-smart-quote s 'apostrophe))
4447 (t (funcall get-smart-quote 'open)))
4448 ;; 1. Replace quote character at the beginning of S.
4449 (cond
4450 ;; Apostrophe?
4451 ((and prev (zerop pre-blank)
4452 (string-match (nth 2 org-export-smart-quotes-regexps) s))
4453 (setq s (replace-match
4454 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
4455 nil t s 1)))
4456 ;; Closing quote?
4457 ((and prev (zerop pre-blank)
4458 (string-match (nth 1 org-export-smart-quotes-regexps) s))
4459 (setq s (replace-match
4460 (funcall get-smart-quote (match-string 1 s) 'close)
4461 nil t s 1)))
4462 ;; Opening quote?
4463 ((and (or (not prev) (> pre-blank 0))
4464 (string-match (nth 0 org-export-smart-quotes-regexps) s))
4465 (setq s (replace-match
4466 (funcall get-smart-quote (match-string 1 s) 'open)
4467 nil t s 1))))
4468 ;; 2. Replace quotes in the middle of the string.
4469 (setq s (replace-regexp-in-string
4470 ;; Opening quotes.
4471 (nth 3 org-export-smart-quotes-regexps)
4472 (lambda (text)
4473 (funcall get-smart-quote (match-string 1 text) 'open))
4474 s nil t 1))
4475 (setq s (replace-regexp-in-string
4476 ;; Closing quotes.
4477 (nth 4 org-export-smart-quotes-regexps)
4478 (lambda (text)
4479 (funcall get-smart-quote (match-string 1 text) 'close))
4480 s nil t 1))
4481 (setq s (replace-regexp-in-string
4482 ;; Apostrophes.
4483 (nth 5 org-export-smart-quotes-regexps)
4484 (lambda (text)
4485 (funcall get-smart-quote (match-string 1 text) 'apostrophe))
4486 s nil t 1))
4487 ;; 3. Replace quote character at the end of S.
4488 (cond
4489 ;; Apostrophe?
4490 ((and next (string-match (nth 8 org-export-smart-quotes-regexps) s))
4491 (setq s (replace-match
4492 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
4493 nil t s 1)))
4494 ;; Closing quote?
4495 ((and (not next)
4496 (string-match (nth 7 org-export-smart-quotes-regexps) s))
4497 (setq s (replace-match
4498 (funcall get-smart-quote (match-string 1 s) 'close)
4499 nil t s 1)))
4500 ;; Opening quote?
4501 ((and next (string-match (nth 6 org-export-smart-quotes-regexps) s))
4502 (setq s (replace-match
4503 (funcall get-smart-quote (match-string 1 s) 'open)
4504 nil t s 1))))
4505 ;; Return string with smart quotes.
4506 s))))
4508 ;;;; Topology
4510 ;; Here are various functions to retrieve information about the
4511 ;; neighbourhood of a given element or object. Neighbours of interest
4512 ;; are direct parent (`org-export-get-parent'), parent headline
4513 ;; (`org-export-get-parent-headline'), first element containing an
4514 ;; object, (`org-export-get-parent-element'), parent table
4515 ;; (`org-export-get-parent-table'), previous element or object
4516 ;; (`org-export-get-previous-element') and next element or object
4517 ;; (`org-export-get-next-element').
4519 ;; `org-export-get-genealogy' returns the full genealogy of a given
4520 ;; element or object, from closest parent to full parse tree.
4522 (defun org-export-get-parent (blob)
4523 "Return BLOB parent or nil.
4524 BLOB is the element or object considered."
4525 (org-element-property :parent blob))
4527 (defun org-export-get-genealogy (blob)
4528 "Return full genealogy relative to a given element or object.
4530 BLOB is the element or object being considered.
4532 Ancestors are returned from closest to farthest, the last one
4533 being the full parse tree."
4534 (let (genealogy (parent blob))
4535 (while (setq parent (org-element-property :parent parent))
4536 (push parent genealogy))
4537 (nreverse genealogy)))
4539 (defun org-export-get-parent-headline (blob)
4540 "Return BLOB parent headline or nil.
4541 BLOB is the element or object being considered."
4542 (let ((parent blob))
4543 (while (and (setq parent (org-element-property :parent parent))
4544 (not (eq (org-element-type parent) 'headline))))
4545 parent))
4547 (defun org-export-get-parent-element (object)
4548 "Return first element containing OBJECT or nil.
4549 OBJECT is the object to consider."
4550 (let ((parent object))
4551 (while (and (setq parent (org-element-property :parent parent))
4552 (memq (org-element-type parent) org-element-all-objects)))
4553 parent))
4555 (defun org-export-get-parent-table (object)
4556 "Return OBJECT parent table or nil.
4557 OBJECT is either a `table-cell' or `table-element' type object."
4558 (let ((parent object))
4559 (while (and (setq parent (org-element-property :parent parent))
4560 (not (eq (org-element-type parent) 'table))))
4561 parent))
4563 (defun org-export-get-previous-element (blob info)
4564 "Return previous element or object.
4565 BLOB is an element or object. INFO is a plist used as
4566 a communication channel. Return previous exportable element or
4567 object, a string, or nil."
4568 (let (prev)
4569 (catch 'exit
4570 (mapc (lambda (obj)
4571 (cond ((eq obj blob) (throw 'exit prev))
4572 ((memq obj (plist-get info :ignore-list)))
4573 (t (setq prev obj))))
4574 ;; An object can belong to the contents of its parent or
4575 ;; to a secondary string. We check the latter option
4576 ;; first.
4577 (let ((parent (org-export-get-parent blob)))
4578 (or (and (not (memq (org-element-type blob)
4579 org-element-all-elements))
4580 (let ((sec-value
4581 (org-element-property
4582 (cdr (assq (org-element-type parent)
4583 org-element-secondary-value-alist))
4584 parent)))
4585 (and (memq blob sec-value) sec-value)))
4586 (org-element-contents parent)))))))
4588 (defun org-export-get-next-element (blob info)
4589 "Return next element or object.
4590 BLOB is an element or object. INFO is a plist used as
4591 a communication channel. Return next exportable element or
4592 object, a string, or nil."
4593 (catch 'found
4594 (mapc (lambda (obj)
4595 (unless (memq obj (plist-get info :ignore-list))
4596 (throw 'found obj)))
4597 ;; An object can belong to the contents of its parent or to
4598 ;; a secondary string. We check the latter option first.
4599 (let ((parent (org-export-get-parent blob)))
4600 (or (and (not (memq (org-element-type blob)
4601 org-element-all-objects))
4602 (let ((sec-value
4603 (org-element-property
4604 (cdr (assq (org-element-type parent)
4605 org-element-secondary-value-alist))
4606 parent)))
4607 (cdr (memq blob sec-value))))
4608 (cdr (memq blob (org-element-contents parent))))))
4609 nil))
4612 ;;;; Translation
4614 ;; `org-export-translate' translates a string according to language
4615 ;; specified by LANGUAGE keyword or `org-export-language-setup'
4616 ;; variable and a specified charset. `org-export-dictionary' contains
4617 ;; the dictionary used for the translation.
4619 (defconst org-export-dictionary
4620 '(("Author"
4621 ("ca" :default "Autor")
4622 ("cs" :default "Autor")
4623 ("da" :default "Ophavsmand")
4624 ("de" :default "Autor")
4625 ("eo" :html "A&#365;toro")
4626 ("es" :default "Autor")
4627 ("fi" :html "Tekij&auml;")
4628 ("fr" :default "Auteur")
4629 ("hu" :default "Szerz&otilde;")
4630 ("is" :html "H&ouml;fundur")
4631 ("it" :default "Autore")
4632 ("ja" :html "&#33879;&#32773;" :utf-8 "著者")
4633 ("nl" :default "Auteur")
4634 ("no" :default "Forfatter")
4635 ("nb" :default "Forfatter")
4636 ("nn" :default "Forfattar")
4637 ("pl" :default "Autor")
4638 ("ru" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
4639 ("sv" :html "F&ouml;rfattare")
4640 ("uk" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
4641 ("zh-CN" :html "&#20316;&#32773;" :utf-8 "作者")
4642 ("zh-TW" :html "&#20316;&#32773;" :utf-8 "作者"))
4643 ("Date"
4644 ("ca" :default "Data")
4645 ("cs" :default "Datum")
4646 ("da" :default "Dato")
4647 ("de" :default "Datum")
4648 ("eo" :default "Dato")
4649 ("es" :default "Fecha")
4650 ("fi" :html "P&auml;iv&auml;m&auml;&auml;r&auml;")
4651 ("hu" :html "D&aacute;tum")
4652 ("is" :default "Dagsetning")
4653 ("it" :default "Data")
4654 ("ja" :html "&#26085;&#20184;" :utf-8 "日付")
4655 ("nl" :default "Datum")
4656 ("no" :default "Dato")
4657 ("nb" :default "Dato")
4658 ("nn" :default "Dato")
4659 ("pl" :default "Data")
4660 ("ru" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
4661 ("sv" :default "Datum")
4662 ("uk" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
4663 ("zh-CN" :html "&#26085;&#26399;" :utf-8 "日期")
4664 ("zh-TW" :html "&#26085;&#26399;" :utf-8 "日期"))
4665 ("Equation"
4666 ("fr" :ascii "Equation" :default "Équation"))
4667 ("Figure")
4668 ("Footnotes"
4669 ("ca" :html "Peus de p&agrave;gina")
4670 ("cs" :default "Pozn\xe1mky pod carou")
4671 ("da" :default "Fodnoter")
4672 ("de" :html "Fu&szlig;noten")
4673 ("eo" :default "Piednotoj")
4674 ("es" :html "Pies de p&aacute;gina")
4675 ("fi" :default "Alaviitteet")
4676 ("fr" :default "Notes de bas de page")
4677 ("hu" :html "L&aacute;bjegyzet")
4678 ("is" :html "Aftanm&aacute;lsgreinar")
4679 ("it" :html "Note a pi&egrave; di pagina")
4680 ("ja" :html "&#33050;&#27880;" :utf-8 "脚注")
4681 ("nl" :default "Voetnoten")
4682 ("no" :default "Fotnoter")
4683 ("nb" :default "Fotnoter")
4684 ("nn" :default "Fotnotar")
4685 ("pl" :default "Przypis")
4686 ("ru" :html "&#1057;&#1085;&#1086;&#1089;&#1082;&#1080;" :utf-8 "Сноски")
4687 ("sv" :default "Fotnoter")
4688 ("uk" :html "&#1055;&#1088;&#1080;&#1084;&#1110;&#1090;&#1082;&#1080;"
4689 :utf-8 "Примітки")
4690 ("zh-CN" :html "&#33050;&#27880;" :utf-8 "脚注")
4691 ("zh-TW" :html "&#33139;&#35387;" :utf-8 "腳註"))
4692 ("List of Listings"
4693 ("fr" :default "Liste des programmes"))
4694 ("List of Tables"
4695 ("fr" :default "Liste des tableaux"))
4696 ("Listing %d:"
4697 ("fr"
4698 :ascii "Programme %d :" :default "Programme nº %d :"
4699 :latin1 "Programme %d :"))
4700 ("Listing %d: %s"
4701 ("fr"
4702 :ascii "Programme %d : %s" :default "Programme nº %d : %s"
4703 :latin1 "Programme %d : %s"))
4704 ("See section %s"
4705 ("fr" :default "cf. section %s"))
4706 ("Table %d:"
4707 ("fr"
4708 :ascii "Tableau %d :" :default "Tableau nº %d :" :latin1 "Tableau %d :"))
4709 ("Table %d: %s"
4710 ("fr"
4711 :ascii "Tableau %d : %s" :default "Tableau nº %d : %s"
4712 :latin1 "Tableau %d : %s"))
4713 ("Table of Contents"
4714 ("ca" :html "&Iacute;ndex")
4715 ("cs" :default "Obsah")
4716 ("da" :default "Indhold")
4717 ("de" :default "Inhaltsverzeichnis")
4718 ("eo" :default "Enhavo")
4719 ("es" :html "&Iacute;ndice")
4720 ("fi" :html "Sis&auml;llysluettelo")
4721 ("fr" :ascii "Sommaire" :default "Table des matières")
4722 ("hu" :html "Tartalomjegyz&eacute;k")
4723 ("is" :default "Efnisyfirlit")
4724 ("it" :default "Indice")
4725 ("ja" :html "&#30446;&#27425;" :utf-8 "目次")
4726 ("nl" :default "Inhoudsopgave")
4727 ("no" :default "Innhold")
4728 ("nb" :default "Innhold")
4729 ("nn" :default "Innhald")
4730 ("pl" :html "Spis tre&#x015b;ci")
4731 ("ru" :html "&#1057;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1077;"
4732 :utf-8 "Содержание")
4733 ("sv" :html "Inneh&aring;ll")
4734 ("uk" :html "&#1047;&#1084;&#1110;&#1089;&#1090;" :utf-8 "Зміст")
4735 ("zh-CN" :html "&#30446;&#24405;" :utf-8 "目录")
4736 ("zh-TW" :html "&#30446;&#37636;" :utf-8 "目錄"))
4737 ("Unknown reference"
4738 ("fr" :ascii "Destination inconnue" :default "Référence inconnue")))
4739 "Dictionary for export engine.
4741 Alist whose CAR is the string to translate and CDR is an alist
4742 whose CAR is the language string and CDR is a plist whose
4743 properties are possible charsets and values translated terms.
4745 It is used as a database for `org-export-translate'. Since this
4746 function returns the string as-is if no translation was found,
4747 the variable only needs to record values different from the
4748 entry.")
4750 (defun org-export-translate (s encoding info)
4751 "Translate string S according to language specification.
4753 ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1'
4754 and `:utf-8'. INFO is a plist used as a communication channel.
4756 Translation depends on `:language' property. Return the
4757 translated string. If no translation is found, try to fall back
4758 to `:default' encoding. If it fails, return S."
4759 (let* ((lang (plist-get info :language))
4760 (translations (cdr (assoc lang
4761 (cdr (assoc s org-export-dictionary))))))
4762 (or (plist-get translations encoding)
4763 (plist-get translations :default)
4764 s)))
4768 ;;; The Dispatcher
4770 ;; `org-export-dispatch' is the standard interactive way to start an
4771 ;; export process. It uses `org-export-dispatch-ui' as a subroutine
4772 ;; for its interface, which, in turn, delegates response to key
4773 ;; pressed to `org-export-dispatch-action'.
4775 ;;;###autoload
4776 (defun org-export-dispatch ()
4777 "Export dispatcher for Org mode.
4779 It provides an access to common export related tasks in a buffer.
4780 Its interface comes in two flavours: standard and expert. While
4781 both share the same set of bindings, only the former displays the
4782 valid keys associations. Set `org-export-dispatch-use-expert-ui'
4783 to switch to one or the other."
4784 (interactive)
4785 (let* ((input (save-window-excursion
4786 (unwind-protect
4787 (org-export-dispatch-ui (list org-export-initial-scope)
4789 org-export-dispatch-use-expert-ui)
4790 (and (get-buffer "*Org Export Dispatcher*")
4791 (kill-buffer "*Org Export Dispatcher*")))))
4792 (action (car input))
4793 (optns (cdr input)))
4794 (case action
4795 ;; First handle special hard-coded actions.
4796 (publish-current-file (org-e-publish-current-file (memq 'force optns)))
4797 (publish-current-project
4798 (org-e-publish-current-project (memq 'force optns)))
4799 (publish-choose-project
4800 (org-e-publish (assoc (org-icompleting-read
4801 "Publish project: "
4802 org-e-publish-project-alist nil t)
4803 org-e-publish-project-alist)
4804 (memq 'force optns)))
4805 (publish-all (org-e-publish-all (memq 'force optns)))
4806 (otherwise
4807 (funcall action
4808 (memq 'subtree optns)
4809 (memq 'visible optns)
4810 (memq 'body optns))))))
4812 (defun org-export-dispatch-ui (options first-key expertp)
4813 "Handle interface for `org-export-dispatch'.
4815 OPTIONS is a list containing current interactive options set for
4816 export. It can contain any of the following symbols:
4817 `body' toggles a body-only export
4818 `subtree' restricts export to current subtree
4819 `visible' restricts export to visible part of buffer.
4820 `force' force publishing files.
4822 FIRST-KEY is the key pressed to select the first level menu. It
4823 is nil when this menu hasn't been selected yet.
4825 EXPERTP, when non-nil, triggers expert UI. In that case, no help
4826 buffer is provided, but indications about currently active
4827 options are given in the prompt. Moreover, \[?] allows to switch
4828 back to standard interface."
4829 (let* ((fontify-key
4830 (lambda (key &optional access-key)
4831 ;; Fontify KEY string. Optional argument ACCESS-KEY, when
4832 ;; non-nil is the required first-level key to activate
4833 ;; KEY. When its value is t, activate KEY independently
4834 ;; on the first key, if any. A nil value means KEY will
4835 ;; only be activated at first level.
4836 (if (or (eq access-key t) (eq access-key first-key))
4837 (org-add-props key nil 'face 'org-warning)
4838 (org-no-properties key))))
4839 ;; Prepare menu entries by extracting them from
4840 ;; `org-export-registered-backends', and sorting them by
4841 ;; access key and by ordinal, if any.
4842 (backends (sort
4843 (sort
4844 (delq nil
4845 (mapcar (lambda (b)
4846 (org-export-backend-menu (car b)))
4847 org-export-registered-backends))
4848 (lambda (a b)
4849 (let ((key-a (nth 1 a))
4850 (key-b (nth 1 b)))
4851 (cond ((and (numberp key-a) (numberp key-b))
4852 (< key-a key-b))
4853 ((numberp key-b) t)))))
4854 (lambda (a b) (< (car a) (car b)))))
4855 ;; Compute a list of allowed keys based on the first key
4856 ;; pressed, if any. Some keys (?1, ?2, ?3, ?4 and ?q) are
4857 ;; always available.
4858 (allowed-keys
4859 (nconc (list ?1 ?2 ?3 ?4)
4860 (if (not first-key) (mapcar 'car backends)
4861 (let (sub-menu)
4862 (dolist (backend backends (mapcar 'car sub-menu))
4863 (when (eq (car backend) first-key)
4864 (setq sub-menu (append (nth 2 backend) sub-menu))))))
4865 (cond ((eq first-key ?P) (list ?f ?p ?x ?a))
4866 ((not first-key) (list ?P)))
4867 (when expertp (list ??))
4868 (list ?q)))
4869 ;; Build the help menu for standard UI.
4870 (help
4871 (unless expertp
4872 (concat
4873 ;; Options are hard-coded.
4874 (format "Options
4875 [%s] Body only: %s [%s] Visible only: %s
4876 [%s] Export scope: %s [%s] Force publishing: %s\n"
4877 (funcall fontify-key "1" t)
4878 (if (memq 'body options) "On " "Off")
4879 (funcall fontify-key "2" t)
4880 (if (memq 'visible options) "On " "Off")
4881 (funcall fontify-key "3" t)
4882 (if (memq 'subtree options) "Subtree" "Buffer ")
4883 (funcall fontify-key "4" t)
4884 (if (memq 'force options) "On " "Off"))
4885 ;; Display registered back-end entries. When a key
4886 ;; appears for the second time, do not create another
4887 ;; entry, but append its sub-menu to existing menu.
4888 (let (last-key)
4889 (mapconcat
4890 (lambda (entry)
4891 (let ((top-key (car entry)))
4892 (concat
4893 (unless (eq top-key last-key)
4894 (setq last-key top-key)
4895 (format "\n[%s] %s\n"
4896 (funcall fontify-key (char-to-string top-key))
4897 (nth 1 entry)))
4898 (let ((sub-menu (nth 2 entry)))
4899 (unless (functionp sub-menu)
4900 ;; Split sub-menu into two columns.
4901 (let ((index -1))
4902 (concat
4903 (mapconcat
4904 (lambda (sub-entry)
4905 (incf index)
4906 (format
4907 (if (zerop (mod index 2)) " [%s] %-24s"
4908 "[%s] %s\n")
4909 (funcall fontify-key
4910 (char-to-string (car sub-entry))
4911 top-key)
4912 (nth 1 sub-entry)))
4913 sub-menu "")
4914 (when (zerop (mod index 2)) "\n"))))))))
4915 backends ""))
4916 ;; Publishing menu is hard-coded.
4917 (format "\n[%s] Publish
4918 [%s] Current file [%s] Current project
4919 [%s] Choose project [%s] All projects\n\n"
4920 (funcall fontify-key "P")
4921 (funcall fontify-key "f" ?P)
4922 (funcall fontify-key "p" ?P)
4923 (funcall fontify-key "x" ?P)
4924 (funcall fontify-key "a" ?P))
4925 (format "\[%s] %s"
4926 (funcall fontify-key "q" t)
4927 (if first-key "Main menu" "Exit")))))
4928 ;; Build prompts for both standard and expert UI.
4929 (standard-prompt (unless expertp "Export command: "))
4930 (expert-prompt
4931 (when expertp
4932 (format
4933 "Export command (Options: %s%s%s%s) [%s]: "
4934 (if (memq 'body options) (funcall fontify-key "b" t) "-")
4935 (if (memq 'visible options) (funcall fontify-key "v" t) "-")
4936 (if (memq 'subtree options) (funcall fontify-key "s" t) "-")
4937 (if (memq 'force options) (funcall fontify-key "f" t) "-")
4938 (concat allowed-keys)))))
4939 ;; With expert UI, just read key with a fancy prompt. In standard
4940 ;; UI, display an intrusive help buffer.
4941 (if expertp
4942 (org-export-dispatch-action
4943 expert-prompt allowed-keys backends options first-key expertp)
4944 ;; At first call, create frame layout in order to display menu.
4945 (unless (get-buffer "*Org Export Dispatcher*")
4946 (delete-other-windows)
4947 (org-switch-to-buffer-other-window
4948 (get-buffer-create "*Org Export Dispatcher*"))
4949 (setq cursor-type nil))
4950 ;; At this point, the buffer containing the menu exists and is
4951 ;; visible in the current window. So, refresh it.
4952 (with-current-buffer "*Org Export Dispatcher*"
4953 (erase-buffer)
4954 (insert help))
4955 (org-fit-window-to-buffer)
4956 (org-export-dispatch-action
4957 standard-prompt allowed-keys backends options first-key expertp))))
4959 (defun org-export-dispatch-action
4960 (prompt allowed-keys backends options first-key expertp)
4961 "Read a character from command input and act accordingly.
4963 PROMPT is the displayed prompt, as a string. ALLOWED-KEYS is
4964 a list of characters available at a given step in the process.
4965 BACKENDS is a list of menu entries. OPTIONS, FIRST-KEY and
4966 EXPERTP are the same as defined in `org-export-dispatch-ui',
4967 which see.
4969 Toggle export options when required. Otherwise, return value is
4970 a list with action as CAR and a list of interactive export
4971 options as CDR."
4972 (let ((key (let ((k (read-char-exclusive prompt)))
4973 ;; Translate "C-a", "C-b"... into "a", "b"... Then take action
4974 ;; depending on user's key pressed.
4975 (if (< k 27) (+ k 96) k))))
4976 (cond
4977 ;; Ignore non-standard characters (i.e. "M-a") and
4978 ;; undefined associations.
4979 ((not (memq key allowed-keys))
4980 (ding)
4981 (unless expertp (message "Invalid key") (sit-for 1))
4982 (org-export-dispatch-ui options first-key expertp))
4983 ;; q key at first level aborts export. At second
4984 ;; level, cancel first key instead.
4985 ((eq key ?q) (if (not first-key) (error "Export aborted")
4986 (org-export-dispatch-ui options nil expertp)))
4987 ;; Help key: Switch back to standard interface if
4988 ;; expert UI was active.
4989 ((eq key ??) (org-export-dispatch-ui options first-key nil))
4990 ;; Toggle export options.
4991 ((memq key '(?1 ?2 ?3 ?4))
4992 (org-export-dispatch-ui
4993 (let ((option (case key (?1 'body) (?2 'visible) (?3 'subtree)
4994 (?4 'force))))
4995 (if (memq option options) (remq option options)
4996 (cons option options)))
4997 first-key expertp))
4998 ;; Action selected: Send key and options back to
4999 ;; `org-export-dispatch'.
5000 ((or first-key (functionp (nth 2 (assq key backends))))
5001 (cons (cond
5002 ((not first-key) (nth 2 (assq key backends)))
5003 ;; Publishing actions are hard-coded. Send a special
5004 ;; signal to `org-export-dispatch'.
5005 ((eq first-key ?P)
5006 (case key
5007 (?f 'publish-current-file)
5008 (?p 'publish-current-project)
5009 (?x 'publish-choose-project)
5010 (?a 'publish-all)))
5011 ;; Return first action associated to FIRST-KEY + KEY
5012 ;; path. Indeed, derived backends can share the same
5013 ;; FIRST-KEY.
5014 (t (catch 'found
5015 (mapc (lambda (backend)
5016 (let ((match (assq key (nth 2 backend))))
5017 (when match (throw 'found (nth 2 match)))))
5018 (member (assq first-key backends) backends)))))
5019 options))
5020 ;; Otherwise, enter sub-menu.
5021 (t (org-export-dispatch-ui options key expertp)))))
5024 (provide 'org-export)
5025 ;;; org-export.el ends here