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