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