Fix file:// uri handling for windows-nt and cygwin
[org-mode/org-tableheadings.git] / lisp / ox.el
blob55ad101c1e7682b79f123215b7fc666f23a7c05c
1 ;;; ox.el --- Export Framework for Org Mode -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2012-2017 Free Software Foundation, Inc.
5 ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
6 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;; This library implements a generic export engine for Org, built on
26 ;; its syntactical parser: Org Elements.
28 ;; Besides that parser, the generic exporter is made of three distinct
29 ;; parts:
31 ;; - The communication channel consists of a property list, which is
32 ;; created and updated during the process. Its use is to offer
33 ;; every piece of information, would it be about initial environment
34 ;; or contextual data, all in a single place.
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 functions is `org-export-as'. It returns the transcoded
48 ;; buffer as a string. Its derivatives are `org-export-to-buffer' and
49 ;; `org-export-to-file'.
51 ;; An export back-end is defined with `org-export-define-backend'.
52 ;; This function can also support specific buffer keywords, OPTION
53 ;; keyword's items and filters. Refer to function's documentation for
54 ;; more information.
56 ;; If the new back-end shares most properties with another one,
57 ;; `org-export-define-derived-backend' can be used to simplify the
58 ;; process.
60 ;; Any back-end can define its own variables. Among them, those
61 ;; customizable should belong to the `org-export-BACKEND' group.
63 ;; Tools for common tasks across back-ends are implemented in the
64 ;; following part of the file.
66 ;; Eventually, a dispatcher (`org-export-dispatch') is provided in the
67 ;; last one.
69 ;; See <http://orgmode.org/worg/dev/org-export-reference.html> for
70 ;; more information.
72 ;;; Code:
74 (require 'cl-lib)
75 (require 'ob-exp)
76 (require 'org-element)
77 (require 'org-macro)
78 (require 'tabulated-list)
80 (declare-function org-src-coderef-format "org-src" (&optional element))
81 (declare-function org-src-coderef-regexp "org-src" (fmt &optional label))
82 (declare-function org-publish "ox-publish" (project &optional force async))
83 (declare-function org-publish-all "ox-publish" (&optional force async))
84 (declare-function org-publish-current-file "ox-publish" (&optional force async))
85 (declare-function org-publish-current-project "ox-publish" (&optional force async))
87 (defvar org-publish-project-alist)
88 (defvar org-table-number-fraction)
89 (defvar org-table-number-regexp)
92 ;;; Internal Variables
94 ;; Among internal variables, the most important is
95 ;; `org-export-options-alist'. This variable define the global export
96 ;; options, shared between every exporter, and how they are acquired.
98 (defconst org-export-max-depth 19
99 "Maximum nesting depth for headlines, counting from 0.")
101 (defconst org-export-options-alist
102 '((:title "TITLE" nil nil parse)
103 (:date "DATE" nil nil parse)
104 (:author "AUTHOR" nil user-full-name parse)
105 (:email "EMAIL" nil user-mail-address t)
106 (:language "LANGUAGE" nil org-export-default-language t)
107 (:select-tags "SELECT_TAGS" nil org-export-select-tags split)
108 (:exclude-tags "EXCLUDE_TAGS" nil org-export-exclude-tags split)
109 (:creator "CREATOR" nil org-export-creator-string)
110 (:headline-levels nil "H" org-export-headline-levels)
111 (:preserve-breaks nil "\\n" org-export-preserve-breaks)
112 (:section-numbers nil "num" org-export-with-section-numbers)
113 (:time-stamp-file nil "timestamp" org-export-time-stamp-file)
114 (:with-archived-trees nil "arch" org-export-with-archived-trees)
115 (:with-author nil "author" org-export-with-author)
116 (:with-broken-links nil "broken-links" org-export-with-broken-links)
117 (:with-clocks nil "c" org-export-with-clocks)
118 (:with-creator nil "creator" org-export-with-creator)
119 (:with-date nil "date" org-export-with-date)
120 (:with-drawers nil "d" org-export-with-drawers)
121 (:with-email nil "email" org-export-with-email)
122 (:with-emphasize nil "*" org-export-with-emphasize)
123 (:with-entities nil "e" org-export-with-entities)
124 (:with-fixed-width nil ":" org-export-with-fixed-width)
125 (:with-footnotes nil "f" org-export-with-footnotes)
126 (:with-inlinetasks nil "inline" org-export-with-inlinetasks)
127 (:with-latex nil "tex" org-export-with-latex)
128 (:with-planning nil "p" org-export-with-planning)
129 (:with-priority nil "pri" org-export-with-priority)
130 (:with-properties nil "prop" org-export-with-properties)
131 (:with-smart-quotes nil "'" org-export-with-smart-quotes)
132 (:with-special-strings nil "-" org-export-with-special-strings)
133 (:with-statistics-cookies nil "stat" org-export-with-statistics-cookies)
134 (:with-sub-superscript nil "^" org-export-with-sub-superscripts)
135 (:with-toc nil "toc" org-export-with-toc)
136 (:with-tables nil "|" org-export-with-tables)
137 (:with-tags nil "tags" org-export-with-tags)
138 (:with-tasks nil "tasks" org-export-with-tasks)
139 (:with-timestamps nil "<" org-export-with-timestamps)
140 (:with-title nil "title" org-export-with-title)
141 (:with-todo-keywords nil "todo" org-export-with-todo-keywords))
142 "Alist between export properties and ways to set them.
144 The key of the alist is the property name, and the value is a list
145 like (KEYWORD OPTION DEFAULT BEHAVIOR) where:
147 KEYWORD is a string representing a buffer keyword, or nil. Each
148 property defined this way can also be set, during subtree
149 export, through a headline property named after the keyword
150 with the \"EXPORT_\" prefix (i.e. DATE keyword and EXPORT_DATE
151 property).
152 OPTION is a string that could be found in an #+OPTIONS: line.
153 DEFAULT is the default value for the property.
154 BEHAVIOR determines how Org should handle multiple keywords for
155 the same property. It is a symbol among:
156 nil Keep old value and discard the new one.
157 t Replace old value with the new one.
158 `space' Concatenate the values, separating them with a space.
159 `newline' Concatenate the values, separating them with
160 a newline.
161 `split' Split values at white spaces, and cons them to the
162 previous list.
163 `parse' Parse value as a list of strings and Org objects,
164 which can then be transcoded with, e.g.,
165 `org-export-data'. It implies `space' behavior.
167 Values set through KEYWORD and OPTION have precedence over
168 DEFAULT.
170 All these properties should be back-end agnostic. Back-end
171 specific properties are set through `org-export-define-backend'.
172 Properties redefined there have precedence over these.")
174 (defconst org-export-special-keywords '("FILETAGS" "SETUPFILE" "OPTIONS")
175 "List of in-buffer keywords that require special treatment.
176 These keywords are not directly associated to a property. The
177 way they are handled must be hard-coded into
178 `org-export--get-inbuffer-options' function.")
180 (defconst org-export-filters-alist
181 '((:filter-body . org-export-filter-body-functions)
182 (:filter-bold . org-export-filter-bold-functions)
183 (:filter-babel-call . org-export-filter-babel-call-functions)
184 (:filter-center-block . org-export-filter-center-block-functions)
185 (:filter-clock . org-export-filter-clock-functions)
186 (:filter-code . org-export-filter-code-functions)
187 (:filter-diary-sexp . org-export-filter-diary-sexp-functions)
188 (:filter-drawer . org-export-filter-drawer-functions)
189 (:filter-dynamic-block . org-export-filter-dynamic-block-functions)
190 (:filter-entity . org-export-filter-entity-functions)
191 (:filter-example-block . org-export-filter-example-block-functions)
192 (:filter-export-block . org-export-filter-export-block-functions)
193 (:filter-export-snippet . org-export-filter-export-snippet-functions)
194 (:filter-final-output . org-export-filter-final-output-functions)
195 (:filter-fixed-width . org-export-filter-fixed-width-functions)
196 (:filter-footnote-definition . org-export-filter-footnote-definition-functions)
197 (:filter-footnote-reference . org-export-filter-footnote-reference-functions)
198 (:filter-headline . org-export-filter-headline-functions)
199 (:filter-horizontal-rule . org-export-filter-horizontal-rule-functions)
200 (:filter-inline-babel-call . org-export-filter-inline-babel-call-functions)
201 (:filter-inline-src-block . org-export-filter-inline-src-block-functions)
202 (:filter-inlinetask . org-export-filter-inlinetask-functions)
203 (:filter-italic . org-export-filter-italic-functions)
204 (:filter-item . org-export-filter-item-functions)
205 (:filter-keyword . org-export-filter-keyword-functions)
206 (:filter-latex-environment . org-export-filter-latex-environment-functions)
207 (:filter-latex-fragment . org-export-filter-latex-fragment-functions)
208 (:filter-line-break . org-export-filter-line-break-functions)
209 (:filter-link . org-export-filter-link-functions)
210 (:filter-node-property . org-export-filter-node-property-functions)
211 (:filter-options . org-export-filter-options-functions)
212 (:filter-paragraph . org-export-filter-paragraph-functions)
213 (:filter-parse-tree . org-export-filter-parse-tree-functions)
214 (:filter-plain-list . org-export-filter-plain-list-functions)
215 (:filter-plain-text . org-export-filter-plain-text-functions)
216 (:filter-planning . org-export-filter-planning-functions)
217 (:filter-property-drawer . org-export-filter-property-drawer-functions)
218 (:filter-quote-block . org-export-filter-quote-block-functions)
219 (:filter-radio-target . org-export-filter-radio-target-functions)
220 (:filter-section . org-export-filter-section-functions)
221 (:filter-special-block . org-export-filter-special-block-functions)
222 (:filter-src-block . org-export-filter-src-block-functions)
223 (:filter-statistics-cookie . org-export-filter-statistics-cookie-functions)
224 (:filter-strike-through . org-export-filter-strike-through-functions)
225 (:filter-subscript . org-export-filter-subscript-functions)
226 (:filter-superscript . org-export-filter-superscript-functions)
227 (:filter-table . org-export-filter-table-functions)
228 (:filter-table-cell . org-export-filter-table-cell-functions)
229 (:filter-table-row . org-export-filter-table-row-functions)
230 (:filter-target . org-export-filter-target-functions)
231 (:filter-timestamp . org-export-filter-timestamp-functions)
232 (:filter-underline . org-export-filter-underline-functions)
233 (:filter-verbatim . org-export-filter-verbatim-functions)
234 (:filter-verse-block . org-export-filter-verse-block-functions))
235 "Alist between filters properties and initial values.
237 The key of each association is a property name accessible through
238 the communication channel. Its value is a configurable global
239 variable defining initial filters.
241 This list is meant to install user specified filters. Back-end
242 developers may install their own filters using
243 `org-export-define-backend'. Filters defined there will always
244 be prepended to the current list, so they always get applied
245 first.")
247 (defconst org-export-default-inline-image-rule
248 `(("file" .
249 ,(format "\\.%s\\'"
250 (regexp-opt
251 '("png" "jpeg" "jpg" "gif" "tiff" "tif" "xbm"
252 "xpm" "pbm" "pgm" "ppm") t))))
253 "Default rule for link matching an inline image.
254 This rule applies to links with no description. By default, it
255 will be considered as an inline image if it targets a local file
256 whose extension is either \"png\", \"jpeg\", \"jpg\", \"gif\",
257 \"tiff\", \"tif\", \"xbm\", \"xpm\", \"pbm\", \"pgm\" or \"ppm\".
258 See `org-export-inline-image-p' for more information about
259 rules.")
261 (defconst org-export-ignored-local-variables
262 '(org-font-lock-keywords
263 org-element--cache org-element--cache-objects org-element--cache-sync-keys
264 org-element--cache-sync-requests org-element--cache-sync-timer)
265 "List of variables not copied through upon buffer duplication.
266 Export process takes place on a copy of the original buffer.
267 When this copy is created, all Org related local variables not in
268 this list are copied to the new buffer. Variables with an
269 unreadable value are also ignored.")
271 (defvar org-export-async-debug nil
272 "Non-nil means asynchronous export process should leave data behind.
274 This data is found in the appropriate \"*Org Export Process*\"
275 buffer, and in files prefixed with \"org-export-process\" and
276 located in `temporary-file-directory'.
278 When non-nil, it will also set `debug-on-error' to a non-nil
279 value in the external process.")
281 (defvar org-export-stack-contents nil
282 "Record asynchronously generated export results and processes.
283 This is an alist: its CAR is the source of the
284 result (destination file or buffer for a finished process,
285 original buffer for a running one) and its CDR is a list
286 containing the back-end used, as a symbol, and either a process
287 or the time at which it finished. It is used to build the menu
288 from `org-export-stack'.")
290 (defvar org-export-registered-backends nil
291 "List of backends currently available in the exporter.
292 This variable is set with `org-export-define-backend' and
293 `org-export-define-derived-backend' functions.")
295 (defvar org-export-dispatch-last-action nil
296 "Last command called from the dispatcher.
297 The value should be a list. Its CAR is the action, as a symbol,
298 and its CDR is a list of export options.")
300 (defvar org-export-dispatch-last-position (make-marker)
301 "The position where the last export command was created using the dispatcher.
302 This marker will be used with `C-u C-c C-e' to make sure export repetition
303 uses the same subtree if the previous command was restricted to a subtree.")
305 ;; For compatibility with Org < 8
306 (defvar org-export-current-backend nil
307 "Name, if any, of the back-end used during an export process.
309 Its value is a symbol such as `html', `latex', `ascii', or nil if
310 the back-end is anonymous (see `org-export-create-backend') or if
311 there is no export process in progress.
313 It can be used to teach Babel blocks how to act differently
314 according to the back-end used.")
318 ;;; User-configurable Variables
320 ;; Configuration for the masses.
322 ;; They should never be accessed directly, as their value is to be
323 ;; stored in a property list (cf. `org-export-options-alist').
324 ;; Back-ends will read their value from there instead.
326 (defgroup org-export nil
327 "Options for exporting Org mode files."
328 :tag "Org Export"
329 :group 'org)
331 (defgroup org-export-general nil
332 "General options for export engine."
333 :tag "Org Export General"
334 :group 'org-export)
336 (defcustom org-export-with-archived-trees 'headline
337 "Whether sub-trees with the ARCHIVE tag should be exported.
339 This can have three different values:
340 nil Do not export, pretend this tree is not present.
341 t Do export the entire tree.
342 `headline' Only export the headline, but skip the tree below it.
344 This option can also be set with the OPTIONS keyword,
345 e.g. \"arch:nil\"."
346 :group 'org-export-general
347 :type '(choice
348 (const :tag "Not at all" nil)
349 (const :tag "Headline only" headline)
350 (const :tag "Entirely" t))
351 :safe (lambda (x) (memq x '(t nil headline))))
353 (defcustom org-export-with-author t
354 "Non-nil means insert author name into the exported file.
355 This option can also be set with the OPTIONS keyword,
356 e.g. \"author:nil\"."
357 :group 'org-export-general
358 :type 'boolean
359 :safe #'booleanp)
361 (defcustom org-export-with-clocks nil
362 "Non-nil means export CLOCK keywords.
363 This option can also be set with the OPTIONS keyword,
364 e.g. \"c:t\"."
365 :group 'org-export-general
366 :type 'boolean
367 :safe #'booleanp)
369 (defcustom org-export-with-creator nil
370 "Non-nil means the postamble should contain a creator sentence.
372 The sentence can be set in `org-export-creator-string', which
373 see.
375 This option can also be set with the OPTIONS keyword, e.g.,
376 \"creator:t\"."
377 :group 'org-export-general
378 :version "26.1"
379 :package-version '(Org . "8.3")
380 :type 'boolean
381 :safe #'booleanp)
383 (defcustom org-export-with-date t
384 "Non-nil means insert date in the exported document.
385 This option can also be set with the OPTIONS keyword,
386 e.g. \"date:nil\"."
387 :group 'org-export-general
388 :type 'boolean
389 :safe #'booleanp)
391 (defcustom org-export-date-timestamp-format nil
392 "Time-stamp format string to use for DATE keyword.
394 The format string, when specified, only applies if date consists
395 in a single time-stamp. Otherwise its value will be ignored.
397 See `format-time-string' for details on how to build this
398 string."
399 :group 'org-export-general
400 :type '(choice
401 (string :tag "Time-stamp format string")
402 (const :tag "No format string" nil))
403 :safe (lambda (x) (or (null x) (stringp x))))
405 (defcustom org-export-creator-string
406 (format "Emacs %s (Org mode %s)"
407 emacs-version
408 (if (fboundp 'org-version) (org-version) "unknown version"))
409 "Information about the creator of the document.
410 This option can also be set on with the CREATOR keyword."
411 :group 'org-export-general
412 :type '(string :tag "Creator string")
413 :safe #'stringp)
415 (defcustom org-export-with-drawers '(not "LOGBOOK")
416 "Non-nil means export contents of standard drawers.
418 When t, all drawers are exported. This may also be a list of
419 drawer names to export, as strings. If that list starts with
420 `not', only drawers with such names will be ignored.
422 This variable doesn't apply to properties drawers. See
423 `org-export-with-properties' instead.
425 This option can also be set with the OPTIONS keyword,
426 e.g. \"d:nil\"."
427 :group 'org-export-general
428 :version "24.4"
429 :package-version '(Org . "8.0")
430 :type '(choice
431 (const :tag "All drawers" t)
432 (const :tag "None" nil)
433 (repeat :tag "Selected drawers"
434 (string :tag "Drawer name"))
435 (list :tag "Ignored drawers"
436 (const :format "" not)
437 (repeat :tag "Specify names of drawers to ignore during export"
438 :inline t
439 (string :tag "Drawer name"))))
440 :safe (lambda (x) (or (booleanp x)
441 (and (listp x)
442 (or (cl-every #'stringp x)
443 (and (eq (nth 0 x) 'not)
444 (cl-every #'stringp (cdr x))))))))
446 (defcustom org-export-with-email nil
447 "Non-nil means insert author email into the exported file.
448 This option can also be set with the OPTIONS keyword,
449 e.g. \"email:t\"."
450 :group 'org-export-general
451 :type 'boolean
452 :safe #'booleanp)
454 (defcustom org-export-with-emphasize t
455 "Non-nil means interpret *word*, /word/, _word_ and +word+.
457 If the export target supports emphasizing text, the word will be
458 typeset in bold, italic, with an underline or strike-through,
459 respectively.
461 This option can also be set with the OPTIONS keyword,
462 e.g. \"*:nil\"."
463 :group 'org-export-general
464 :type 'boolean
465 :safe #'booleanp)
467 (defcustom org-export-exclude-tags '("noexport")
468 "Tags that exclude a tree from export.
470 All trees carrying any of these tags will be excluded from
471 export. This is without condition, so even subtrees inside that
472 carry one of the `org-export-select-tags' will be removed.
474 This option can also be set with the EXCLUDE_TAGS keyword."
475 :group 'org-export-general
476 :type '(repeat (string :tag "Tag"))
477 :safe (lambda (x) (and (listp x) (cl-every #'stringp x))))
479 (defcustom org-export-with-fixed-width t
480 "Non-nil means export lines starting with \":\".
481 This option can also be set with the OPTIONS keyword,
482 e.g. \"::nil\"."
483 :group 'org-export-general
484 :version "24.4"
485 :package-version '(Org . "8.0")
486 :type 'boolean
487 :safe #'booleanp)
489 (defcustom org-export-with-footnotes t
490 "Non-nil means Org footnotes should be exported.
491 This option can also be set with the OPTIONS keyword,
492 e.g. \"f:nil\"."
493 :group 'org-export-general
494 :type 'boolean
495 :safe #'booleanp)
497 (defcustom org-export-with-latex t
498 "Non-nil means process LaTeX environments and fragments.
500 This option can also be set with the OPTIONS line,
501 e.g. \"tex:verbatim\". Allowed values are:
503 nil Ignore math snippets.
504 `verbatim' Keep everything in verbatim.
505 t Allow export of math snippets."
506 :group 'org-export-general
507 :version "24.4"
508 :package-version '(Org . "8.0")
509 :type '(choice
510 (const :tag "Do not process math in any way" nil)
511 (const :tag "Interpret math snippets" t)
512 (const :tag "Leave math verbatim" verbatim))
513 :safe (lambda (x) (memq x '(t nil verbatim))))
515 (defcustom org-export-headline-levels 3
516 "The last level which is still exported as a headline.
518 Inferior levels will usually produce itemize or enumerate lists
519 when exported, but back-end behavior may differ.
521 This option can also be set with the OPTIONS keyword,
522 e.g. \"H:2\"."
523 :group 'org-export-general
524 :type 'integer
525 :safe #'integerp)
527 (defcustom org-export-default-language "en"
528 "The default language for export and clocktable translations, as a string.
529 This may have an association in
530 `org-clock-clocktable-language-setup',
531 `org-export-smart-quotes-alist' and `org-export-dictionary'.
532 This option can also be set with the LANGUAGE keyword."
533 :group 'org-export-general
534 :type '(string :tag "Language")
535 :safe #'stringp)
537 (defcustom org-export-preserve-breaks nil
538 "Non-nil means preserve all line breaks when exporting.
539 This option can also be set with the OPTIONS keyword,
540 e.g. \"\\n:t\"."
541 :group 'org-export-general
542 :type 'boolean
543 :safe #'booleanp)
545 (defcustom org-export-with-entities t
546 "Non-nil means interpret entities when exporting.
548 For example, HTML export converts \\alpha to &alpha; and \\AA to
549 &Aring;.
551 For a list of supported names, see the constant `org-entities'
552 and the user option `org-entities-user'.
554 This option can also be set with the OPTIONS keyword,
555 e.g. \"e:nil\"."
556 :group 'org-export-general
557 :type 'boolean
558 :safe #'booleanp)
560 (defcustom org-export-with-inlinetasks t
561 "Non-nil means inlinetasks should be exported.
562 This option can also be set with the OPTIONS keyword,
563 e.g. \"inline:nil\"."
564 :group 'org-export-general
565 :version "24.4"
566 :package-version '(Org . "8.0")
567 :type 'boolean
568 :safe #'booleanp)
570 (defcustom org-export-with-planning nil
571 "Non-nil means include planning info in export.
573 Planning info is the line containing either SCHEDULED:,
574 DEADLINE:, CLOSED: time-stamps, or a combination of them.
576 This option can also be set with the OPTIONS keyword,
577 e.g. \"p:t\"."
578 :group 'org-export-general
579 :version "24.4"
580 :package-version '(Org . "8.0")
581 :type 'boolean
582 :safe #'booleanp)
584 (defcustom org-export-with-priority nil
585 "Non-nil means include priority cookies in export.
586 This option can also be set with the OPTIONS keyword,
587 e.g. \"pri:t\"."
588 :group 'org-export-general
589 :type 'boolean
590 :safe #'booleanp)
592 (defcustom org-export-with-properties nil
593 "Non-nil means export contents of properties drawers.
595 When t, all properties are exported. This may also be a list of
596 properties to export, as strings.
598 This option can also be set with the OPTIONS keyword,
599 e.g. \"prop:t\"."
600 :group 'org-export-general
601 :version "24.4"
602 :package-version '(Org . "8.3")
603 :type '(choice
604 (const :tag "All properties" t)
605 (const :tag "None" nil)
606 (repeat :tag "Selected properties"
607 (string :tag "Property name")))
608 :safe (lambda (x) (or (booleanp x)
609 (and (listp x) (cl-every #'stringp x)))))
611 (defcustom org-export-with-section-numbers t
612 "Non-nil means add section numbers to headlines when exporting.
614 When set to an integer n, numbering will only happen for
615 headlines whose relative level is higher or equal to n.
617 This option can also be set with the OPTIONS keyword,
618 e.g. \"num:t\"."
619 :group 'org-export-general
620 :type 'boolean
621 :safe #'booleanp)
623 (defcustom org-export-select-tags '("export")
624 "Tags that select a tree for export.
626 If any such tag is found in a buffer, all trees that do not carry
627 one of these tags will be ignored during export. Inside trees
628 that are selected like this, you can still deselect a subtree by
629 tagging it with one of the `org-export-exclude-tags'.
631 This option can also be set with the SELECT_TAGS keyword."
632 :group 'org-export-general
633 :type '(repeat (string :tag "Tag"))
634 :safe (lambda (x) (and (listp x) (cl-every #'stringp x))))
636 (defcustom org-export-with-smart-quotes nil
637 "Non-nil means activate smart quotes during export.
638 This option can also be set with the OPTIONS keyword,
639 e.g., \"':t\".
641 When setting this to non-nil, you need to take care of
642 using the correct Babel package when exporting to LaTeX.
643 E.g., you can load Babel for french like this:
645 #+LATEX_HEADER: \\usepackage[french]{babel}"
646 :group 'org-export-general
647 :version "24.4"
648 :package-version '(Org . "8.0")
649 :type 'boolean
650 :safe #'booleanp)
652 (defcustom org-export-with-special-strings t
653 "Non-nil means interpret \"\\-\", \"--\" and \"---\" for export.
655 When this option is turned on, these strings will be exported as:
657 Org HTML LaTeX UTF-8
658 -----+----------+--------+-------
659 \\- &shy; \\-
660 -- &ndash; -- –
661 --- &mdash; --- —
662 ... &hellip; \\ldots …
664 This option can also be set with the OPTIONS keyword,
665 e.g. \"-:nil\"."
666 :group 'org-export-general
667 :type 'boolean
668 :safe #'booleanp)
670 (defcustom org-export-with-statistics-cookies t
671 "Non-nil means include statistics cookies in export.
672 This option can also be set with the OPTIONS keyword,
673 e.g. \"stat:nil\""
674 :group 'org-export-general
675 :version "24.4"
676 :package-version '(Org . "8.0")
677 :type 'boolean
678 :safe #'booleanp)
680 (defcustom org-export-with-sub-superscripts t
681 "Non-nil means interpret \"_\" and \"^\" for export.
683 If you want to control how Org displays those characters, see
684 `org-use-sub-superscripts'. `org-export-with-sub-superscripts'
685 used to be an alias for `org-use-sub-superscripts' in Org <8.0,
686 it is not anymore.
688 When this option is turned on, you can use TeX-like syntax for
689 sub- and superscripts and see them exported correctly.
691 You can also set the option with #+OPTIONS: ^:t
693 Several characters after \"_\" or \"^\" will be considered as a
694 single item - so grouping with {} is normally not needed. For
695 example, the following things will be parsed as single sub- or
696 superscripts:
698 10^24 or 10^tau several digits will be considered 1 item.
699 10^-12 or 10^-tau a leading sign with digits or a word
700 x^2-y^3 will be read as x^2 - y^3, because items are
701 terminated by almost any nonword/nondigit char.
702 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
704 Still, ambiguity is possible. So when in doubt, use {} to enclose
705 the sub/superscript. If you set this variable to the symbol `{}',
706 the braces are *required* in order to trigger interpretations as
707 sub/superscript. This can be helpful in documents that need \"_\"
708 frequently in plain text."
709 :group 'org-export-general
710 :version "24.4"
711 :package-version '(Org . "8.0")
712 :type '(choice
713 (const :tag "Interpret them" t)
714 (const :tag "Curly brackets only" {})
715 (const :tag "Do not interpret them" nil))
716 :safe (lambda (x) (memq x '(t nil {}))))
718 (defcustom org-export-with-toc t
719 "Non-nil means create a table of contents in exported files.
721 The TOC contains headlines with levels up
722 to`org-export-headline-levels'. When an integer, include levels
723 up to N in the toc, this may then be different from
724 `org-export-headline-levels', but it will not be allowed to be
725 larger than the number of headline levels. When nil, no table of
726 contents is made.
728 This option can also be set with the OPTIONS keyword,
729 e.g. \"toc:nil\" or \"toc:3\"."
730 :group 'org-export-general
731 :type '(choice
732 (const :tag "No Table of Contents" nil)
733 (const :tag "Full Table of Contents" t)
734 (integer :tag "TOC to level"))
735 :safe (lambda (x) (or (booleanp x)
736 (integerp x))))
738 (defcustom org-export-with-tables t
739 "Non-nil means export tables.
740 This option can also be set with the OPTIONS keyword,
741 e.g. \"|:nil\"."
742 :group 'org-export-general
743 :version "24.4"
744 :package-version '(Org . "8.0")
745 :type 'boolean
746 :safe #'booleanp)
748 (defcustom org-export-with-tags t
749 "If nil, do not export tags, just remove them from headlines.
751 If this is the symbol `not-in-toc', tags will be removed from
752 table of contents entries, but still be shown in the headlines of
753 the document.
755 This option can also be set with the OPTIONS keyword,
756 e.g. \"tags:nil\"."
757 :group 'org-export-general
758 :type '(choice
759 (const :tag "Off" nil)
760 (const :tag "Not in TOC" not-in-toc)
761 (const :tag "On" t))
762 :safe (lambda (x) (memq x '(t nil not-in-toc))))
764 (defcustom org-export-with-tasks t
765 "Non-nil means include TODO items for export.
767 This may have the following values:
768 t include tasks independent of state.
769 `todo' include only tasks that are not yet done.
770 `done' include only tasks that are already done.
771 nil ignore all tasks.
772 list of keywords include tasks with these keywords.
774 This option can also be set with the OPTIONS keyword,
775 e.g. \"tasks:nil\"."
776 :group 'org-export-general
777 :type '(choice
778 (const :tag "All tasks" t)
779 (const :tag "No tasks" nil)
780 (const :tag "Not-done tasks" todo)
781 (const :tag "Only done tasks" done)
782 (repeat :tag "Specific TODO keywords"
783 (string :tag "Keyword")))
784 :safe (lambda (x) (or (memq x '(nil t todo done))
785 (and (listp x)
786 (cl-every #'stringp x)))))
788 (defcustom org-export-with-title t
789 "Non-nil means print title into the exported file.
790 This option can also be set with the OPTIONS keyword,
791 e.g. \"title:nil\"."
792 :group 'org-export-general
793 :version "26.1"
794 :package-version '(Org . "8.3")
795 :type 'boolean
796 :safe #'booleanp)
798 (defcustom org-export-time-stamp-file t
799 "Non-nil means insert a time stamp into the exported file.
800 The time stamp shows when the file was created. This option can
801 also be set with the OPTIONS keyword, e.g. \"timestamp:nil\"."
802 :group 'org-export-general
803 :type 'boolean
804 :safe #'booleanp)
806 (defcustom org-export-with-timestamps t
807 "Non nil means allow timestamps in export.
809 It can be set to any of the following values:
810 t export all timestamps.
811 `active' export active timestamps only.
812 `inactive' export inactive timestamps only.
813 nil do not export timestamps
815 This only applies to timestamps isolated in a paragraph
816 containing only timestamps. Other timestamps are always
817 exported.
819 This option can also be set with the OPTIONS keyword, e.g.
820 \"<:nil\"."
821 :group 'org-export-general
822 :type '(choice
823 (const :tag "All timestamps" t)
824 (const :tag "Only active timestamps" active)
825 (const :tag "Only inactive timestamps" inactive)
826 (const :tag "No timestamp" nil))
827 :safe (lambda (x) (memq x '(t nil active inactive))))
829 (defcustom org-export-with-todo-keywords t
830 "Non-nil means include TODO keywords in export.
831 When nil, remove all these keywords from the export. This option
832 can also be set with the OPTIONS keyword, e.g. \"todo:nil\"."
833 :group 'org-export-general
834 :type 'boolean)
836 (defcustom org-export-allow-bind-keywords nil
837 "Non-nil means BIND keywords can define local variable values.
838 This is a potential security risk, which is why the default value
839 is nil. You can also allow them through local buffer variables."
840 :group 'org-export-general
841 :version "24.4"
842 :package-version '(Org . "8.0")
843 :type 'boolean)
845 (defcustom org-export-with-broken-links nil
846 "Non-nil means do not raise an error on broken links.
848 When this variable is non-nil, broken links are ignored, without
849 stopping the export process. If it is set to `mark', broken
850 links are marked as such in the output, with a string like
852 [BROKEN LINK: path]
854 where PATH is the un-resolvable reference.
856 This option can also be set with the OPTIONS keyword, e.g.,
857 \"broken-links:mark\"."
858 :group 'org-export-general
859 :version "26.1"
860 :package-version '(Org . "9.0")
861 :type '(choice
862 (const :tag "Ignore broken links" t)
863 (const :tag "Mark broken links in output" mark)
864 (const :tag "Raise an error" nil)))
866 (defcustom org-export-snippet-translation-alist nil
867 "Alist between export snippets back-ends and exporter back-ends.
869 This variable allows providing shortcuts for export snippets.
871 For example, with a value of \\='((\"h\" . \"html\")), the
872 HTML back-end will recognize the contents of \"@@h:<b>@@\" as
873 HTML code while every other back-end will ignore it."
874 :group 'org-export-general
875 :version "24.4"
876 :package-version '(Org . "8.0")
877 :type '(repeat
878 (cons (string :tag "Shortcut")
879 (string :tag "Back-end")))
880 :safe (lambda (x)
881 (and (listp x)
882 (cl-every #'consp x)
883 (cl-every #'stringp (mapcar #'car x))
884 (cl-every #'stringp (mapcar #'cdr x)))))
886 (defcustom org-export-coding-system nil
887 "Coding system for the exported file."
888 :group 'org-export-general
889 :version "24.4"
890 :package-version '(Org . "8.0")
891 :type 'coding-system)
893 (defcustom org-export-copy-to-kill-ring nil
894 "Non-nil means pushing export output to the kill ring.
895 This variable is ignored during asynchronous export."
896 :group 'org-export-general
897 :version "26.1"
898 :package-version '(Org . "8.3")
899 :type '(choice
900 (const :tag "Always" t)
901 (const :tag "When export is done interactively" if-interactive)
902 (const :tag "Never" nil)))
904 (defcustom org-export-initial-scope 'buffer
905 "The initial scope when exporting with `org-export-dispatch'.
906 This variable can be either set to `buffer' or `subtree'."
907 :group 'org-export-general
908 :type '(choice
909 (const :tag "Export current buffer" buffer)
910 (const :tag "Export current subtree" subtree)))
912 (defcustom org-export-show-temporary-export-buffer t
913 "Non-nil means show buffer after exporting to temp buffer.
914 When Org exports to a file, the buffer visiting that file is never
915 shown, but remains buried. However, when exporting to
916 a temporary buffer, that buffer is popped up in a second window.
917 When this variable is nil, the buffer remains buried also in
918 these cases."
919 :group 'org-export-general
920 :type 'boolean)
922 (defcustom org-export-in-background nil
923 "Non-nil means export and publishing commands will run in background.
924 Results from an asynchronous export are never displayed
925 automatically. But you can retrieve them with `\\[org-export-stack]'."
926 :group 'org-export-general
927 :version "24.4"
928 :package-version '(Org . "8.0")
929 :type 'boolean)
931 (defcustom org-export-async-init-file nil
932 "File used to initialize external export process.
934 Value must be either nil or an absolute file name. When nil, the
935 external process is launched like a regular Emacs session,
936 loading user's initialization file and any site specific
937 configuration. If a file is provided, it, and only it, is loaded
938 at start-up.
940 Therefore, using a specific configuration makes the process to
941 load faster and the export more portable."
942 :group 'org-export-general
943 :version "24.4"
944 :package-version '(Org . "8.0")
945 :type '(choice
946 (const :tag "Regular startup" nil)
947 (file :tag "Specific start-up file" :must-match t)))
949 (defcustom org-export-dispatch-use-expert-ui nil
950 "Non-nil means using a non-intrusive `org-export-dispatch'.
951 In that case, no help buffer is displayed. Though, an indicator
952 for current export scope is added to the prompt (\"b\" when
953 output is restricted to body only, \"s\" when it is restricted to
954 the current subtree, \"v\" when only visible elements are
955 considered for export, \"f\" when publishing functions should be
956 passed the FORCE argument and \"a\" when the export should be
957 asynchronous). Also, [?] allows switching back to standard
958 mode."
959 :group 'org-export-general
960 :version "24.4"
961 :package-version '(Org . "8.0")
962 :type 'boolean)
966 ;;; Defining Back-ends
968 ;; An export back-end is a structure with `org-export-backend' type
969 ;; and `name', `parent', `transcoders', `options', `filters', `blocks'
970 ;; and `menu' slots.
972 ;; At the lowest level, a back-end is created with
973 ;; `org-export-create-backend' function.
975 ;; A named back-end can be registered with
976 ;; `org-export-register-backend' function. A registered back-end can
977 ;; later be referred to by its name, with `org-export-get-backend'
978 ;; function. Also, such a back-end can become the parent of a derived
979 ;; back-end from which slot values will be inherited by default.
980 ;; `org-export-derived-backend-p' can check if a given back-end is
981 ;; derived from a list of back-end names.
983 ;; `org-export-get-all-transcoders', `org-export-get-all-options' and
984 ;; `org-export-get-all-filters' return the full alist of transcoders,
985 ;; options and filters, including those inherited from ancestors.
987 ;; At a higher level, `org-export-define-backend' is the standard way
988 ;; to define an export back-end. If the new back-end is similar to
989 ;; a registered back-end, `org-export-define-derived-backend' may be
990 ;; used instead.
992 ;; Eventually `org-export-barf-if-invalid-backend' returns an error
993 ;; when a given back-end hasn't been registered yet.
995 (cl-defstruct (org-export-backend (:constructor org-export-create-backend)
996 (:copier nil))
997 name parent transcoders options filters blocks menu)
999 ;;;###autoload
1000 (defun org-export-get-backend (name)
1001 "Return export back-end named after NAME.
1002 NAME is a symbol. Return nil if no such back-end is found."
1003 (cl-find-if (lambda (b) (and (eq name (org-export-backend-name b))))
1004 org-export-registered-backends))
1006 (defun org-export-register-backend (backend)
1007 "Register BACKEND as a known export back-end.
1008 BACKEND is a structure with `org-export-backend' type."
1009 ;; Refuse to register an unnamed back-end.
1010 (unless (org-export-backend-name backend)
1011 (error "Cannot register a unnamed export back-end"))
1012 ;; Refuse to register a back-end with an unknown parent.
1013 (let ((parent (org-export-backend-parent backend)))
1014 (when (and parent (not (org-export-get-backend parent)))
1015 (error "Cannot use unknown \"%s\" back-end as a parent" parent)))
1016 ;; If a back-end with the same name as BACKEND is already
1017 ;; registered, replace it with BACKEND. Otherwise, simply add
1018 ;; BACKEND to the list of registered back-ends.
1019 (let ((old (org-export-get-backend (org-export-backend-name backend))))
1020 (if old (setcar (memq old org-export-registered-backends) backend)
1021 (push backend org-export-registered-backends))))
1023 (defun org-export-barf-if-invalid-backend (backend)
1024 "Signal an error if BACKEND isn't defined."
1025 (unless (org-export-backend-p backend)
1026 (error "Unknown \"%s\" back-end: Aborting export" backend)))
1028 (defun org-export-derived-backend-p (backend &rest backends)
1029 "Non-nil if BACKEND is derived from one of BACKENDS.
1030 BACKEND is an export back-end, as returned by, e.g.,
1031 `org-export-create-backend', or a symbol referring to
1032 a registered back-end. BACKENDS is constituted of symbols."
1033 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
1034 (when backend
1035 (catch 'exit
1036 (while (org-export-backend-parent backend)
1037 (when (memq (org-export-backend-name backend) backends)
1038 (throw 'exit t))
1039 (setq backend
1040 (org-export-get-backend (org-export-backend-parent backend))))
1041 (memq (org-export-backend-name backend) backends))))
1043 (defun org-export-get-all-transcoders (backend)
1044 "Return full translation table for BACKEND.
1046 BACKEND is an export back-end, as return by, e.g,,
1047 `org-export-create-backend'. Return value is an alist where
1048 keys are element or object types, as symbols, and values are
1049 transcoders.
1051 Unlike to `org-export-backend-transcoders', this function
1052 also returns transcoders inherited from parent back-ends,
1053 if any."
1054 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
1055 (when backend
1056 (let ((transcoders (org-export-backend-transcoders backend))
1057 parent)
1058 (while (setq parent (org-export-backend-parent backend))
1059 (setq backend (org-export-get-backend parent))
1060 (setq transcoders
1061 (append transcoders (org-export-backend-transcoders backend))))
1062 transcoders)))
1064 (defun org-export-get-all-options (backend)
1065 "Return export options for BACKEND.
1067 BACKEND is an export back-end, as return by, e.g,,
1068 `org-export-create-backend'. See `org-export-options-alist'
1069 for the shape of the return value.
1071 Unlike to `org-export-backend-options', this function also
1072 returns options inherited from parent back-ends, if any."
1073 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
1074 (when backend
1075 (let ((options (org-export-backend-options backend))
1076 parent)
1077 (while (setq parent (org-export-backend-parent backend))
1078 (setq backend (org-export-get-backend parent))
1079 (setq options (append options (org-export-backend-options backend))))
1080 options)))
1082 (defun org-export-get-all-filters (backend)
1083 "Return complete list of filters for BACKEND.
1085 BACKEND is an export back-end, as return by, e.g,,
1086 `org-export-create-backend'. Return value is an alist where
1087 keys are symbols and values lists of functions.
1089 Unlike to `org-export-backend-filters', this function also
1090 returns filters inherited from parent back-ends, if any."
1091 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
1092 (when backend
1093 (let ((filters (org-export-backend-filters backend))
1094 parent)
1095 (while (setq parent (org-export-backend-parent backend))
1096 (setq backend (org-export-get-backend parent))
1097 (setq filters (append filters (org-export-backend-filters backend))))
1098 filters)))
1100 (defun org-export-define-backend (backend transcoders &rest body)
1101 "Define a new back-end BACKEND.
1103 TRANSCODERS is an alist between object or element types and
1104 functions handling them.
1106 These functions should return a string without any trailing
1107 space, or nil. They must accept three arguments: the object or
1108 element itself, its contents or nil when it isn't recursive and
1109 the property list used as a communication channel.
1111 Contents, when not nil, are stripped from any global indentation
1112 \(although the relative one is preserved). They also always end
1113 with a single newline character.
1115 If, for a given type, no function is found, that element or
1116 object type will simply be ignored, along with any blank line or
1117 white space at its end. The same will happen if the function
1118 returns the nil value. If that function returns the empty
1119 string, the type will be ignored, but the blank lines or white
1120 spaces will be kept.
1122 In addition to element and object types, one function can be
1123 associated to the `template' (or `inner-template') symbol and
1124 another one to the `plain-text' symbol.
1126 The former returns the final transcoded string, and can be used
1127 to add a preamble and a postamble to document's body. It must
1128 accept two arguments: the transcoded string and the property list
1129 containing export options. A function associated to `template'
1130 will not be applied if export has option \"body-only\".
1131 A function associated to `inner-template' is always applied.
1133 The latter, when defined, is to be called on every text not
1134 recognized as an element or an object. It must accept two
1135 arguments: the text string and the information channel. It is an
1136 appropriate place to protect special chars relative to the
1137 back-end.
1139 BODY can start with pre-defined keyword arguments. The following
1140 keywords are understood:
1142 :filters-alist
1144 Alist between filters and function, or list of functions,
1145 specific to the back-end. See `org-export-filters-alist' for
1146 a list of all allowed filters. Filters defined here
1147 shouldn't make a back-end test, as it may prevent back-ends
1148 derived from this one to behave properly.
1150 :menu-entry
1152 Menu entry for the export dispatcher. It should be a list
1153 like:
1155 \\='(KEY DESCRIPTION-OR-ORDINAL ACTION-OR-MENU)
1157 where :
1159 KEY is a free character selecting the back-end.
1161 DESCRIPTION-OR-ORDINAL is either a string or a number.
1163 If it is a string, is will be used to name the back-end in
1164 its menu entry. If it is a number, the following menu will
1165 be displayed as a sub-menu of the back-end with the same
1166 KEY. Also, the number will be used to determine in which
1167 order such sub-menus will appear (lowest first).
1169 ACTION-OR-MENU is either a function or an alist.
1171 If it is an action, it will be called with four
1172 arguments (booleans): ASYNC, SUBTREEP, VISIBLE-ONLY and
1173 BODY-ONLY. See `org-export-as' for further explanations on
1174 some of them.
1176 If it is an alist, associations should follow the
1177 pattern:
1179 \\='(KEY DESCRIPTION ACTION)
1181 where KEY, DESCRIPTION and ACTION are described above.
1183 Valid values include:
1185 \\='(?m \"My Special Back-end\" my-special-export-function)
1189 \\='(?l \"Export to LaTeX\"
1190 (?p \"As PDF file\" org-latex-export-to-pdf)
1191 (?o \"As PDF file and open\"
1192 (lambda (a s v b)
1193 (if a (org-latex-export-to-pdf t s v b)
1194 (org-open-file
1195 (org-latex-export-to-pdf nil s v b)))))))
1197 or the following, which will be added to the previous
1198 sub-menu,
1200 \\='(?l 1
1201 ((?B \"As TEX buffer (Beamer)\" org-beamer-export-as-latex)
1202 (?P \"As PDF file (Beamer)\" org-beamer-export-to-pdf)))
1204 :options-alist
1206 Alist between back-end specific properties introduced in
1207 communication channel and how their value are acquired. See
1208 `org-export-options-alist' for more information about
1209 structure of the values."
1210 (declare (indent 1))
1211 (let (filters menu-entry options)
1212 (while (keywordp (car body))
1213 (let ((keyword (pop body)))
1214 (pcase keyword
1215 (:filters-alist (setq filters (pop body)))
1216 (:menu-entry (setq menu-entry (pop body)))
1217 (:options-alist (setq options (pop body)))
1218 (_ (error "Unknown keyword: %s" keyword)))))
1219 (org-export-register-backend
1220 (org-export-create-backend :name backend
1221 :transcoders transcoders
1222 :options options
1223 :filters filters
1224 :menu menu-entry))))
1226 (defun org-export-define-derived-backend (child parent &rest body)
1227 "Create a new back-end as a variant of an existing one.
1229 CHILD is the name of the derived back-end. PARENT is the name of
1230 the parent back-end.
1232 BODY can start with pre-defined keyword arguments. The following
1233 keywords are understood:
1235 :filters-alist
1237 Alist of filters that will overwrite or complete filters
1238 defined in PARENT back-end. See `org-export-filters-alist'
1239 for a list of allowed filters.
1241 :menu-entry
1243 Menu entry for the export dispatcher. See
1244 `org-export-define-backend' for more information about the
1245 expected value.
1247 :options-alist
1249 Alist of back-end specific properties that will overwrite or
1250 complete those defined in PARENT back-end. Refer to
1251 `org-export-options-alist' for more information about
1252 structure of the values.
1254 :translate-alist
1256 Alist of element and object types and transcoders that will
1257 overwrite or complete transcode table from PARENT back-end.
1258 Refer to `org-export-define-backend' for detailed information
1259 about transcoders.
1261 As an example, here is how one could define \"my-latex\" back-end
1262 as a variant of `latex' back-end with a custom template function:
1264 (org-export-define-derived-backend \\='my-latex \\='latex
1265 :translate-alist \\='((template . my-latex-template-fun)))
1267 The back-end could then be called with, for example:
1269 (org-export-to-buffer \\='my-latex \"*Test my-latex*\")"
1270 (declare (indent 2))
1271 (let (filters menu-entry options transcoders)
1272 (while (keywordp (car body))
1273 (let ((keyword (pop body)))
1274 (pcase keyword
1275 (:filters-alist (setq filters (pop body)))
1276 (:menu-entry (setq menu-entry (pop body)))
1277 (:options-alist (setq options (pop body)))
1278 (:translate-alist (setq transcoders (pop body)))
1279 (_ (error "Unknown keyword: %s" keyword)))))
1280 (org-export-register-backend
1281 (org-export-create-backend :name child
1282 :parent parent
1283 :transcoders transcoders
1284 :options options
1285 :filters filters
1286 :menu menu-entry))))
1290 ;;; The Communication Channel
1292 ;; During export process, every function has access to a number of
1293 ;; properties. They are of two types:
1295 ;; 1. Environment options are collected once at the very beginning of
1296 ;; the process, out of the original buffer and configuration.
1297 ;; Collecting them is handled by `org-export-get-environment'
1298 ;; function.
1300 ;; Most environment options are defined through the
1301 ;; `org-export-options-alist' variable.
1303 ;; 2. Tree properties are extracted directly from the parsed tree,
1304 ;; just before export, by `org-export--collect-tree-properties'.
1306 ;;;; Environment Options
1308 ;; Environment options encompass all parameters defined outside the
1309 ;; scope of the parsed data. They come from five sources, in
1310 ;; increasing precedence order:
1312 ;; - Global variables,
1313 ;; - Buffer's attributes,
1314 ;; - Options keyword symbols,
1315 ;; - Buffer keywords,
1316 ;; - Subtree properties.
1318 ;; The central internal function with regards to environment options
1319 ;; is `org-export-get-environment'. It updates global variables with
1320 ;; "#+BIND:" keywords, then retrieve and prioritize properties from
1321 ;; the different sources.
1323 ;; The internal functions doing the retrieval are:
1324 ;; `org-export--get-global-options',
1325 ;; `org-export--get-buffer-attributes',
1326 ;; `org-export--parse-option-keyword',
1327 ;; `org-export--get-subtree-options' and
1328 ;; `org-export--get-inbuffer-options'
1330 ;; Also, `org-export--list-bound-variables' collects bound variables
1331 ;; along with their value in order to set them as buffer local
1332 ;; variables later in the process.
1334 ;;;###autoload
1335 (defun org-export-get-environment (&optional backend subtreep ext-plist)
1336 "Collect export options from the current buffer.
1338 Optional argument BACKEND is an export back-end, as returned by
1339 `org-export-create-backend'.
1341 When optional argument SUBTREEP is non-nil, assume the export is
1342 done against the current sub-tree.
1344 Third optional argument EXT-PLIST is a property list with
1345 external parameters overriding Org default settings, but still
1346 inferior to file-local settings."
1347 ;; First install #+BIND variables since these must be set before
1348 ;; global options are read.
1349 (dolist (pair (org-export--list-bound-variables))
1350 (set (make-local-variable (car pair)) (nth 1 pair)))
1351 ;; Get and prioritize export options...
1352 (org-combine-plists
1353 ;; ... from global variables...
1354 (org-export--get-global-options backend)
1355 ;; ... from an external property list...
1356 ext-plist
1357 ;; ... from in-buffer settings...
1358 (org-export--get-inbuffer-options backend)
1359 ;; ... and from subtree, when appropriate.
1360 (and subtreep (org-export--get-subtree-options backend))))
1362 (defun org-export--parse-option-keyword (options &optional backend)
1363 "Parse an OPTIONS line and return values as a plist.
1364 Optional argument BACKEND is an export back-end, as returned by,
1365 e.g., `org-export-create-backend'. It specifies which back-end
1366 specific items to read, if any."
1367 (let ((line
1368 (let ((s 0) alist)
1369 (while (string-match "\\(.+?\\):\\((.*?)\\|\\S-*\\)[ \t]*" options s)
1370 (setq s (match-end 0))
1371 (push (cons (match-string 1 options)
1372 (read (match-string 2 options)))
1373 alist))
1374 alist))
1375 ;; Priority is given to back-end specific options.
1376 (all (append (and backend (org-export-get-all-options backend))
1377 org-export-options-alist))
1378 (plist))
1379 (when line
1380 (dolist (entry all plist)
1381 (let ((item (nth 2 entry)))
1382 (when item
1383 (let ((v (assoc-string item line t)))
1384 (when v (setq plist (plist-put plist (car entry) (cdr v)))))))))))
1386 (defun org-export--get-subtree-options (&optional backend)
1387 "Get export options in subtree at point.
1388 Optional argument BACKEND is an export back-end, as returned by,
1389 e.g., `org-export-create-backend'. It specifies back-end used
1390 for export. Return options as a plist."
1391 ;; For each buffer keyword, create a headline property setting the
1392 ;; same property in communication channel. The name for the
1393 ;; property is the keyword with "EXPORT_" appended to it.
1394 (org-with-wide-buffer
1395 ;; Make sure point is at a heading.
1396 (if (org-at-heading-p) (org-up-heading-safe) (org-back-to-heading t))
1397 (let ((plist
1398 ;; EXPORT_OPTIONS are parsed in a non-standard way. Take
1399 ;; care of them right from the start.
1400 (let ((o (org-entry-get (point) "EXPORT_OPTIONS" 'selective)))
1401 (and o (org-export--parse-option-keyword o backend))))
1402 ;; Take care of EXPORT_TITLE. If it isn't defined, use
1403 ;; headline's title (with no todo keyword, priority cookie or
1404 ;; tag) as its fallback value.
1405 (cache (list
1406 (cons "TITLE"
1407 (or (org-entry-get (point) "EXPORT_TITLE" 'selective)
1408 (let ((case-fold-search nil))
1409 (looking-at org-complex-heading-regexp)
1410 (match-string-no-properties 4))))))
1411 ;; Look for both general keywords and back-end specific
1412 ;; options, with priority given to the latter.
1413 (options (append (and backend (org-export-get-all-options backend))
1414 org-export-options-alist)))
1415 ;; Handle other keywords. Then return PLIST.
1416 (dolist (option options plist)
1417 (let ((property (car option))
1418 (keyword (nth 1 option)))
1419 (when keyword
1420 (let ((value
1421 (or (cdr (assoc keyword cache))
1422 (let ((v (org-entry-get (point)
1423 (concat "EXPORT_" keyword)
1424 'selective)))
1425 (push (cons keyword v) cache) v))))
1426 (when value
1427 (setq plist
1428 (plist-put plist
1429 property
1430 (cl-case (nth 4 option)
1431 (parse
1432 (org-element-parse-secondary-string
1433 value (org-element-restriction 'keyword)))
1434 (split (org-split-string value))
1435 (t value))))))))))))
1437 (defun org-export--get-inbuffer-options (&optional backend)
1438 "Return current buffer export options, as a plist.
1440 Optional argument BACKEND, when non-nil, is an export back-end,
1441 as returned by, e.g., `org-export-create-backend'. It specifies
1442 which back-end specific options should also be read in the
1443 process.
1445 Assume buffer is in Org mode. Narrowing, if any, is ignored."
1446 (let* ((case-fold-search t)
1447 (options (append
1448 ;; Priority is given to back-end specific options.
1449 (and backend (org-export-get-all-options backend))
1450 org-export-options-alist))
1451 (regexp (format "^[ \t]*#\\+%s:"
1452 (regexp-opt (nconc (delq nil (mapcar #'cadr options))
1453 org-export-special-keywords))))
1454 plist to-parse)
1455 (letrec ((find-properties
1456 (lambda (keyword)
1457 ;; Return all properties associated to KEYWORD.
1458 (let (properties)
1459 (dolist (option options properties)
1460 (when (equal (nth 1 option) keyword)
1461 (cl-pushnew (car option) properties))))))
1462 (get-options
1463 (lambda (&optional files)
1464 ;; Recursively read keywords in buffer. FILES is
1465 ;; a list of files read so far. PLIST is the current
1466 ;; property list obtained.
1467 (org-with-wide-buffer
1468 (goto-char (point-min))
1469 (while (re-search-forward regexp nil t)
1470 (let ((element (org-element-at-point)))
1471 (when (eq (org-element-type element) 'keyword)
1472 (let ((key (org-element-property :key element))
1473 (val (org-element-property :value element)))
1474 (cond
1475 ;; Options in `org-export-special-keywords'.
1476 ((equal key "SETUPFILE")
1477 (let ((file
1478 (expand-file-name
1479 (org-unbracket-string "\"" "\"" (org-trim val)))))
1480 ;; Avoid circular dependencies.
1481 (unless (member file files)
1482 (with-temp-buffer
1483 (setq default-directory
1484 (file-name-directory file))
1485 (insert (org-file-contents file 'noerror))
1486 (let ((org-inhibit-startup t)) (org-mode))
1487 (funcall get-options (cons file files))))))
1488 ((equal key "OPTIONS")
1489 (setq plist
1490 (org-combine-plists
1491 plist
1492 (org-export--parse-option-keyword
1493 val backend))))
1494 ((equal key "FILETAGS")
1495 (setq plist
1496 (org-combine-plists
1497 plist
1498 (list :filetags
1499 (org-uniquify
1500 (append
1501 (org-split-string val ":")
1502 (plist-get plist :filetags)))))))
1504 ;; Options in `org-export-options-alist'.
1505 (dolist (property (funcall find-properties key))
1506 (setq
1507 plist
1508 (plist-put
1509 plist property
1510 ;; Handle value depending on specified
1511 ;; BEHAVIOR.
1512 (cl-case (nth 4 (assq property options))
1513 (parse
1514 (unless (memq property to-parse)
1515 (push property to-parse))
1516 ;; Even if `parse' implies `space'
1517 ;; behavior, we separate line with
1518 ;; "\n" so as to preserve
1519 ;; line-breaks. However, empty
1520 ;; lines are forbidden since `parse'
1521 ;; doesn't allow more than one
1522 ;; paragraph.
1523 (let ((old (plist-get plist property)))
1524 (cond ((not (org-string-nw-p val)) old)
1525 (old (concat old "\n" val))
1526 (t val))))
1527 (space
1528 (if (not (plist-get plist property))
1529 (org-trim val)
1530 (concat (plist-get plist property)
1532 (org-trim val))))
1533 (newline
1534 (org-trim
1535 (concat (plist-get plist property)
1536 "\n"
1537 (org-trim val))))
1538 (split `(,@(plist-get plist property)
1539 ,@(org-split-string val)))
1540 ((t) val)
1541 (otherwise
1542 (if (not (plist-member plist property)) val
1543 (plist-get plist property)))))))))))))))))
1544 ;; Read options in the current buffer and return value.
1545 (funcall get-options (and buffer-file-name (list buffer-file-name)))
1546 ;; Parse properties in TO-PARSE. Remove newline characters not
1547 ;; involved in line breaks to simulate `space' behavior.
1548 ;; Finally return options.
1549 (dolist (p to-parse plist)
1550 (let ((value (org-element-parse-secondary-string
1551 (plist-get plist p)
1552 (org-element-restriction 'keyword))))
1553 (org-element-map value 'plain-text
1554 (lambda (s)
1555 (org-element-set-element
1556 s (replace-regexp-in-string "\n" " " s))))
1557 (setq plist (plist-put plist p value)))))))
1559 (defun org-export--get-export-attributes
1560 (&optional backend subtreep visible-only body-only)
1561 "Return properties related to export process, as a plist.
1562 Optional arguments BACKEND, SUBTREEP, VISIBLE-ONLY and BODY-ONLY
1563 are like the arguments with the same names of function
1564 `org-export-as'."
1565 (list :export-options (delq nil
1566 (list (and subtreep 'subtree)
1567 (and visible-only 'visible-only)
1568 (and body-only 'body-only)))
1569 :back-end backend
1570 :translate-alist (org-export-get-all-transcoders backend)
1571 :exported-data (make-hash-table :test #'eq :size 4001)))
1573 (defun org-export--get-buffer-attributes ()
1574 "Return properties related to buffer attributes, as a plist."
1575 (list :input-buffer (buffer-name (buffer-base-buffer))
1576 :input-file (buffer-file-name (buffer-base-buffer))))
1578 (defun org-export--get-global-options (&optional backend)
1579 "Return global export options as a plist.
1580 Optional argument BACKEND, if non-nil, is an export back-end, as
1581 returned by, e.g., `org-export-create-backend'. It specifies
1582 which back-end specific export options should also be read in the
1583 process."
1584 (let (plist
1585 ;; Priority is given to back-end specific options.
1586 (all (append (and backend (org-export-get-all-options backend))
1587 org-export-options-alist)))
1588 (dolist (cell all plist)
1589 (let ((prop (car cell)))
1590 (unless (plist-member plist prop)
1591 (setq plist
1592 (plist-put
1593 plist
1594 prop
1595 ;; Evaluate default value provided.
1596 (let ((value (eval (nth 3 cell))))
1597 (if (eq (nth 4 cell) 'parse)
1598 (org-element-parse-secondary-string
1599 value (org-element-restriction 'keyword))
1600 value)))))))))
1602 (defun org-export--list-bound-variables ()
1603 "Return variables bound from BIND keywords in current buffer.
1604 Also look for BIND keywords in setup files. The return value is
1605 an alist where associations are (VARIABLE-NAME VALUE)."
1606 (when org-export-allow-bind-keywords
1607 (letrec ((collect-bind
1608 (lambda (files alist)
1609 ;; Return an alist between variable names and their
1610 ;; value. FILES is a list of setup files names read
1611 ;; so far, used to avoid circular dependencies. ALIST
1612 ;; is the alist collected so far.
1613 (let ((case-fold-search t))
1614 (org-with-wide-buffer
1615 (goto-char (point-min))
1616 (while (re-search-forward
1617 "^[ \t]*#\\+\\(BIND\\|SETUPFILE\\):" nil t)
1618 (let ((element (org-element-at-point)))
1619 (when (eq (org-element-type element) 'keyword)
1620 (let ((val (org-element-property :value element)))
1621 (if (equal (org-element-property :key element)
1622 "BIND")
1623 (push (read (format "(%s)" val)) alist)
1624 ;; Enter setup file.
1625 (let ((file (expand-file-name
1626 (org-unbracket-string "\"" "\"" val))))
1627 (unless (member file files)
1628 (with-temp-buffer
1629 (setq default-directory
1630 (file-name-directory file))
1631 (let ((org-inhibit-startup t)) (org-mode))
1632 (insert (org-file-contents file 'noerror))
1633 (setq alist
1634 (funcall collect-bind
1635 (cons file files)
1636 alist))))))))))
1637 alist)))))
1638 ;; Return value in appropriate order of appearance.
1639 (nreverse (funcall collect-bind nil nil)))))
1641 ;; defsubst org-export-get-parent must be defined before first use,
1642 ;; was originally defined in the topology section
1644 (defsubst org-export-get-parent (blob)
1645 "Return BLOB parent or nil.
1646 BLOB is the element or object considered."
1647 (org-element-property :parent blob))
1649 ;;;; Tree Properties
1651 ;; Tree properties are information extracted from parse tree. They
1652 ;; are initialized at the beginning of the transcoding process by
1653 ;; `org-export--collect-tree-properties'.
1655 ;; Dedicated functions focus on computing the value of specific tree
1656 ;; properties during initialization. Thus,
1657 ;; `org-export--populate-ignore-list' lists elements and objects that
1658 ;; should be skipped during export, `org-export--get-min-level' gets
1659 ;; the minimal exportable level, used as a basis to compute relative
1660 ;; level for headlines. Eventually
1661 ;; `org-export--collect-headline-numbering' builds an alist between
1662 ;; headlines and their numbering.
1664 (defun org-export--collect-tree-properties (data info)
1665 "Extract tree properties from parse tree.
1667 DATA is the parse tree from which information is retrieved. INFO
1668 is a list holding export options.
1670 Following tree properties are set or updated:
1672 `:headline-offset' Offset between true level of headlines and
1673 local level. An offset of -1 means a headline
1674 of level 2 should be considered as a level
1675 1 headline in the context.
1677 `:headline-numbering' Alist of all headlines as key and the
1678 associated numbering as value.
1680 `:id-alist' Alist of all ID references as key and associated file
1681 as value.
1683 Return updated plist."
1684 ;; Install the parse tree in the communication channel.
1685 (setq info (plist-put info :parse-tree data))
1686 ;; Compute `:headline-offset' in order to be able to use
1687 ;; `org-export-get-relative-level'.
1688 (setq info
1689 (plist-put info
1690 :headline-offset
1691 (- 1 (org-export--get-min-level data info))))
1692 ;; From now on, properties order doesn't matter: get the rest of the
1693 ;; tree properties.
1694 (org-combine-plists
1695 info
1696 (list :headline-numbering (org-export--collect-headline-numbering data info)
1697 :id-alist
1698 (org-element-map data 'link
1699 (lambda (l)
1700 (and (string= (org-element-property :type l) "id")
1701 (let* ((id (org-element-property :path l))
1702 (file (car (org-id-find id))))
1703 (and file (cons id (file-relative-name file))))))))))
1705 (defun org-export--get-min-level (data options)
1706 "Return minimum exportable headline's level in DATA.
1707 DATA is parsed tree as returned by `org-element-parse-buffer'.
1708 OPTIONS is a plist holding export options."
1709 (catch 'exit
1710 (let ((min-level 10000))
1711 (dolist (datum (org-element-contents data))
1712 (when (and (eq (org-element-type datum) 'headline)
1713 (not (org-element-property :footnote-section-p datum))
1714 (not (memq datum (plist-get options :ignore-list))))
1715 (setq min-level (min (org-element-property :level datum) min-level))
1716 (when (= min-level 1) (throw 'exit 1))))
1717 ;; If no headline was found, for the sake of consistency, set
1718 ;; minimum level to 1 nonetheless.
1719 (if (= min-level 10000) 1 min-level))))
1721 (defun org-export--collect-headline-numbering (data options)
1722 "Return numbering of all exportable, numbered headlines in a parse tree.
1724 DATA is the parse tree. OPTIONS is the plist holding export
1725 options.
1727 Return an alist whose key is a headline and value is its
1728 associated numbering \(in the shape of a list of numbers) or nil
1729 for a footnotes section."
1730 (let ((numbering (make-vector org-export-max-depth 0)))
1731 (org-element-map data 'headline
1732 (lambda (headline)
1733 (when (and (org-export-numbered-headline-p headline options)
1734 (not (org-element-property :footnote-section-p headline)))
1735 (let ((relative-level
1736 (1- (org-export-get-relative-level headline options))))
1737 (cons
1738 headline
1739 (cl-loop
1740 for n across numbering
1741 for idx from 0 to org-export-max-depth
1742 when (< idx relative-level) collect n
1743 when (= idx relative-level) collect (aset numbering idx (1+ n))
1744 when (> idx relative-level) do (aset numbering idx 0))))))
1745 options)))
1747 (defun org-export--selected-trees (data info)
1748 "List headlines and inlinetasks with a select tag in their tree.
1749 DATA is parsed data as returned by `org-element-parse-buffer'.
1750 INFO is a plist holding export options."
1751 (let ((select (plist-get info :select-tags)))
1752 (if (cl-some (lambda (tag) (member tag select)) (plist-get info :filetags))
1753 ;; If FILETAGS contains a select tag, every headline or
1754 ;; inlinetask is returned.
1755 (org-element-map data '(headline inlinetask) #'identity)
1756 (letrec ((selected-trees nil)
1757 (walk-data
1758 (lambda (data genealogy)
1759 (let ((type (org-element-type data)))
1760 (cond
1761 ((memq type '(headline inlinetask))
1762 (let ((tags (org-element-property :tags data)))
1763 (if (cl-some (lambda (tag) (member tag select)) tags)
1764 ;; When a select tag is found, mark full
1765 ;; genealogy and every headline within the
1766 ;; tree as acceptable.
1767 (setq selected-trees
1768 (append
1769 genealogy
1770 (org-element-map data '(headline inlinetask)
1771 #'identity)
1772 selected-trees))
1773 ;; If at a headline, continue searching in
1774 ;; tree, recursively.
1775 (when (eq type 'headline)
1776 (dolist (el (org-element-contents data))
1777 (funcall walk-data el (cons data genealogy)))))))
1778 ((or (eq type 'org-data)
1779 (memq type org-element-greater-elements))
1780 (dolist (el (org-element-contents data))
1781 (funcall walk-data el genealogy))))))))
1782 (funcall walk-data data nil)
1783 selected-trees))))
1785 (defun org-export--skip-p (datum options selected)
1786 "Non-nil when element or object DATUM should be skipped during export.
1787 OPTIONS is the plist holding export options. SELECTED, when
1788 non-nil, is a list of headlines or inlinetasks belonging to
1789 a tree with a select tag."
1790 (cl-case (org-element-type datum)
1791 ((comment comment-block)
1792 ;; Skip all comments and comment blocks. Make to keep maximum
1793 ;; number of blank lines around the comment so as to preserve
1794 ;; local structure of the document upon interpreting it back into
1795 ;; Org syntax.
1796 (let* ((previous (org-export-get-previous-element datum options))
1797 (before (or (org-element-property :post-blank previous) 0))
1798 (after (or (org-element-property :post-blank datum) 0)))
1799 (when previous
1800 (org-element-put-property previous :post-blank (max before after 1))))
1802 (clock (not (plist-get options :with-clocks)))
1803 (drawer
1804 (let ((with-drawers-p (plist-get options :with-drawers)))
1805 (or (not with-drawers-p)
1806 (and (consp with-drawers-p)
1807 ;; If `:with-drawers' value starts with `not', ignore
1808 ;; every drawer whose name belong to that list.
1809 ;; Otherwise, ignore drawers whose name isn't in that
1810 ;; list.
1811 (let ((name (org-element-property :drawer-name datum)))
1812 (if (eq (car with-drawers-p) 'not)
1813 (member-ignore-case name (cdr with-drawers-p))
1814 (not (member-ignore-case name with-drawers-p))))))))
1815 (fixed-width (not (plist-get options :with-fixed-width)))
1816 ((footnote-definition footnote-reference)
1817 (not (plist-get options :with-footnotes)))
1818 ((headline inlinetask)
1819 (let ((with-tasks (plist-get options :with-tasks))
1820 (todo (org-element-property :todo-keyword datum))
1821 (todo-type (org-element-property :todo-type datum))
1822 (archived (plist-get options :with-archived-trees))
1823 (tags (org-export-get-tags datum options nil t)))
1825 (and (eq (org-element-type datum) 'inlinetask)
1826 (not (plist-get options :with-inlinetasks)))
1827 ;; Ignore subtrees with an exclude tag.
1828 (cl-loop for k in (plist-get options :exclude-tags)
1829 thereis (member k tags))
1830 ;; When a select tag is present in the buffer, ignore any tree
1831 ;; without it.
1832 (and selected (not (memq datum selected)))
1833 ;; Ignore commented sub-trees.
1834 (org-element-property :commentedp datum)
1835 ;; Ignore archived subtrees if `:with-archived-trees' is nil.
1836 (and (not archived) (org-element-property :archivedp datum))
1837 ;; Ignore tasks, if specified by `:with-tasks' property.
1838 (and todo
1839 (or (not with-tasks)
1840 (and (memq with-tasks '(todo done))
1841 (not (eq todo-type with-tasks)))
1842 (and (consp with-tasks) (not (member todo with-tasks))))))))
1843 ((latex-environment latex-fragment) (not (plist-get options :with-latex)))
1844 (node-property
1845 (let ((properties-set (plist-get options :with-properties)))
1846 (cond ((null properties-set) t)
1847 ((consp properties-set)
1848 (not (member-ignore-case (org-element-property :key datum)
1849 properties-set))))))
1850 (planning (not (plist-get options :with-planning)))
1851 (property-drawer (not (plist-get options :with-properties)))
1852 (statistics-cookie (not (plist-get options :with-statistics-cookies)))
1853 (table (not (plist-get options :with-tables)))
1854 (table-cell
1855 (and (org-export-table-has-special-column-p
1856 (org-export-get-parent-table datum))
1857 (org-export-first-sibling-p datum options)))
1858 (table-row (org-export-table-row-is-special-p datum options))
1859 (timestamp
1860 ;; `:with-timestamps' only applies to isolated timestamps
1861 ;; objects, i.e. timestamp objects in a paragraph containing only
1862 ;; timestamps and whitespaces.
1863 (when (let ((parent (org-export-get-parent-element datum)))
1864 (and (memq (org-element-type parent) '(paragraph verse-block))
1865 (not (org-element-map parent
1866 (cons 'plain-text
1867 (remq 'timestamp org-element-all-objects))
1868 (lambda (obj)
1869 (or (not (stringp obj)) (org-string-nw-p obj)))
1870 options t))))
1871 (cl-case (plist-get options :with-timestamps)
1872 ((nil) t)
1873 (active
1874 (not (memq (org-element-property :type datum) '(active active-range))))
1875 (inactive
1876 (not (memq (org-element-property :type datum)
1877 '(inactive inactive-range)))))))))
1880 ;;; The Transcoder
1882 ;; `org-export-data' reads a parse tree (obtained with, i.e.
1883 ;; `org-element-parse-buffer') and transcodes it into a specified
1884 ;; back-end output. It takes care of filtering out elements or
1885 ;; objects according to export options and organizing the output blank
1886 ;; lines and white space are preserved. The function memoizes its
1887 ;; results, so it is cheap to call it within transcoders.
1889 ;; It is possible to modify locally the back-end used by
1890 ;; `org-export-data' or even use a temporary back-end by using
1891 ;; `org-export-data-with-backend'.
1893 ;; `org-export-transcoder' is an accessor returning appropriate
1894 ;; translator function for a given element or object.
1896 (defun org-export-transcoder (blob info)
1897 "Return appropriate transcoder for BLOB.
1898 INFO is a plist containing export directives."
1899 (let ((type (org-element-type blob)))
1900 ;; Return contents only for complete parse trees.
1901 (if (eq type 'org-data) (lambda (_datum contents _info) contents)
1902 (let ((transcoder (cdr (assq type (plist-get info :translate-alist)))))
1903 (and (functionp transcoder) transcoder)))))
1905 (defun org-export-data (data info)
1906 "Convert DATA into current back-end format.
1908 DATA is a parse tree, an element or an object or a secondary
1909 string. INFO is a plist holding export options.
1911 Return a string."
1912 (or (gethash data (plist-get info :exported-data))
1913 ;; Handle broken links according to
1914 ;; `org-export-with-broken-links'.
1915 (cl-macrolet
1916 ((broken-link-handler
1917 (&rest body)
1918 `(condition-case err
1919 (progn ,@body)
1920 (org-link-broken
1921 (pcase (plist-get info :with-broken-links)
1922 (`nil (user-error "Unable to resolve link: %S" (nth 1 err)))
1923 (`mark (org-export-data
1924 (format "[BROKEN LINK: %s]" (nth 1 err)) info))
1925 (_ nil))))))
1926 (let* ((type (org-element-type data))
1927 (parent (org-export-get-parent data))
1928 (results
1929 (cond
1930 ;; Ignored element/object.
1931 ((memq data (plist-get info :ignore-list)) nil)
1932 ;; Plain text.
1933 ((eq type 'plain-text)
1934 (org-export-filter-apply-functions
1935 (plist-get info :filter-plain-text)
1936 (let ((transcoder (org-export-transcoder data info)))
1937 (if transcoder (funcall transcoder data info) data))
1938 info))
1939 ;; Secondary string.
1940 ((not type)
1941 (mapconcat (lambda (obj) (org-export-data obj info)) data ""))
1942 ;; Element/Object without contents or, as a special
1943 ;; case, headline with archive tag and archived trees
1944 ;; restricted to title only.
1945 ((or (not (org-element-contents data))
1946 (and (eq type 'headline)
1947 (eq (plist-get info :with-archived-trees) 'headline)
1948 (org-element-property :archivedp data)))
1949 (let ((transcoder (org-export-transcoder data info)))
1950 (or (and (functionp transcoder)
1951 (broken-link-handler
1952 (funcall transcoder data nil info)))
1953 ;; Export snippets never return a nil value so
1954 ;; that white spaces following them are never
1955 ;; ignored.
1956 (and (eq type 'export-snippet) ""))))
1957 ;; Element/Object with contents.
1959 (let ((transcoder (org-export-transcoder data info)))
1960 (when transcoder
1961 (let* ((greaterp (memq type org-element-greater-elements))
1962 (objectp
1963 (and (not greaterp)
1964 (memq type org-element-recursive-objects)))
1965 (contents
1966 (mapconcat
1967 (lambda (element) (org-export-data element info))
1968 (org-element-contents
1969 (if (or greaterp objectp) data
1970 ;; Elements directly containing
1971 ;; objects must have their indentation
1972 ;; normalized first.
1973 (org-element-normalize-contents
1974 data
1975 ;; When normalizing contents of the
1976 ;; first paragraph in an item or
1977 ;; a footnote definition, ignore
1978 ;; first line's indentation: there is
1979 ;; none and it might be misleading.
1980 (when (eq type 'paragraph)
1981 (and
1982 (eq (car (org-element-contents parent))
1983 data)
1984 (memq (org-element-type parent)
1985 '(footnote-definition item)))))))
1986 "")))
1987 (broken-link-handler
1988 (funcall transcoder data
1989 (if (not greaterp) contents
1990 (org-element-normalize-string contents))
1991 info)))))))))
1992 ;; Final result will be memoized before being returned.
1993 (puthash
1994 data
1995 (cond
1996 ((not results) "")
1997 ((memq type '(org-data plain-text nil)) results)
1998 ;; Append the same white space between elements or objects
1999 ;; as in the original buffer, and call appropriate filters.
2001 (org-export-filter-apply-functions
2002 (plist-get info (intern (format ":filter-%s" type)))
2003 (let ((blank (or (org-element-property :post-blank data) 0)))
2004 (if (eq (org-element-class data parent) 'object)
2005 (concat results (make-string blank ?\s))
2006 (concat (org-element-normalize-string results)
2007 (make-string blank ?\n))))
2008 info)))
2009 (plist-get info :exported-data))))))
2011 (defun org-export-data-with-backend (data backend info)
2012 "Convert DATA into BACKEND format.
2014 DATA is an element, an object, a secondary string or a string.
2015 BACKEND is a symbol. INFO is a plist used as a communication
2016 channel.
2018 Unlike to `org-export-with-backend', this function will
2019 recursively convert DATA using BACKEND translation table."
2020 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
2021 ;; Set-up a new communication channel with translations defined in
2022 ;; BACKEND as the translate table and a new hash table for
2023 ;; memoization.
2024 (let ((new-info
2025 (org-combine-plists
2026 info
2027 (list :back-end backend
2028 :translate-alist (org-export-get-all-transcoders backend)
2029 ;; Size of the hash table is reduced since this
2030 ;; function will probably be used on small trees.
2031 :exported-data (make-hash-table :test 'eq :size 401)))))
2032 (prog1 (org-export-data data new-info)
2033 ;; Preserve `:internal-references', as those do not depend on
2034 ;; the back-end used; we need to make sure that any new
2035 ;; reference when the temporary back-end was active gets through
2036 ;; the default one.
2037 (plist-put info :internal-references
2038 (plist-get new-info :internal-references)))))
2040 (defun org-export-expand (blob contents &optional with-affiliated)
2041 "Expand a parsed element or object to its original state.
2043 BLOB is either an element or an object. CONTENTS is its
2044 contents, as a string or nil.
2046 When optional argument WITH-AFFILIATED is non-nil, add affiliated
2047 keywords before output."
2048 (let ((type (org-element-type blob)))
2049 (concat (and with-affiliated
2050 (eq (org-element-class blob) 'element)
2051 (org-element--interpret-affiliated-keywords blob))
2052 (funcall (intern (format "org-element-%s-interpreter" type))
2053 blob contents))))
2057 ;;; The Filter System
2059 ;; Filters allow end-users to tweak easily the transcoded output.
2060 ;; They are the functional counterpart of hooks, as every filter in
2061 ;; a set is applied to the return value of the previous one.
2063 ;; Every set is back-end agnostic. Although, a filter is always
2064 ;; called, in addition to the string it applies to, with the back-end
2065 ;; used as argument, so it's easy for the end-user to add back-end
2066 ;; specific filters in the set. The communication channel, as
2067 ;; a plist, is required as the third argument.
2069 ;; From the developer side, filters sets can be installed in the
2070 ;; process with the help of `org-export-define-backend', which
2071 ;; internally stores filters as an alist. Each association has a key
2072 ;; among the following symbols and a function or a list of functions
2073 ;; as value.
2075 ;; - `:filter-options' applies to the property list containing export
2076 ;; options. Unlike to other filters, functions in this list accept
2077 ;; two arguments instead of three: the property list containing
2078 ;; export options and the back-end. Users can set its value through
2079 ;; `org-export-filter-options-functions' variable.
2081 ;; - `:filter-parse-tree' applies directly to the complete parsed
2082 ;; tree. Users can set it through
2083 ;; `org-export-filter-parse-tree-functions' variable.
2085 ;; - `:filter-body' applies to the body of the output, before template
2086 ;; translator chimes in. Users can set it through
2087 ;; `org-export-filter-body-functions' variable.
2089 ;; - `:filter-final-output' applies to the final transcoded string.
2090 ;; Users can set it with `org-export-filter-final-output-functions'
2091 ;; variable.
2093 ;; - `:filter-plain-text' applies to any string not recognized as Org
2094 ;; syntax. `org-export-filter-plain-text-functions' allows users to
2095 ;; configure it.
2097 ;; - `:filter-TYPE' applies on the string returned after an element or
2098 ;; object of type TYPE has been transcoded. A user can modify
2099 ;; `org-export-filter-TYPE-functions' to install these filters.
2101 ;; All filters sets are applied with
2102 ;; `org-export-filter-apply-functions' function. Filters in a set are
2103 ;; applied in a LIFO fashion. It allows developers to be sure that
2104 ;; their filters will be applied first.
2106 ;; Filters properties are installed in communication channel with
2107 ;; `org-export-install-filters' function.
2109 ;; Eventually, two hooks (`org-export-before-processing-hook' and
2110 ;; `org-export-before-parsing-hook') are run at the beginning of the
2111 ;; export process and just before parsing to allow for heavy structure
2112 ;; modifications.
2115 ;;;; Hooks
2117 (defvar org-export-before-processing-hook nil
2118 "Hook run at the beginning of the export process.
2120 This is run before include keywords and macros are expanded and
2121 Babel code blocks executed, on a copy of the original buffer
2122 being exported. Visibility and narrowing are preserved. Point
2123 is at the beginning of the buffer.
2125 Every function in this hook will be called with one argument: the
2126 back-end currently used, as a symbol.")
2128 (defvar org-export-before-parsing-hook nil
2129 "Hook run before parsing an export buffer.
2131 This is run after include keywords and macros have been expanded
2132 and Babel code blocks executed, on a copy of the original buffer
2133 being exported. Visibility and narrowing are preserved. Point
2134 is at the beginning of the buffer.
2136 Every function in this hook will be called with one argument: the
2137 back-end currently used, as a symbol.")
2140 ;;;; Special Filters
2142 (defvar org-export-filter-options-functions nil
2143 "List of functions applied to the export options.
2144 Each filter is called with two arguments: the export options, as
2145 a plist, and the back-end, as a symbol. It must return
2146 a property list containing export options.")
2148 (defvar org-export-filter-parse-tree-functions nil
2149 "List of functions applied to the parsed tree.
2150 Each filter is called with three arguments: the parse tree, as
2151 returned by `org-element-parse-buffer', the back-end, as
2152 a symbol, and the communication channel, as a plist. It must
2153 return the modified parse tree to transcode.")
2155 (defvar org-export-filter-plain-text-functions nil
2156 "List of functions applied to plain text.
2157 Each filter is called with three arguments: a string which
2158 contains no Org syntax, the back-end, as a symbol, and the
2159 communication channel, as a plist. It must return a string or
2160 nil.")
2162 (defvar org-export-filter-body-functions nil
2163 "List of functions applied to transcoded body.
2164 Each filter is called with three arguments: a string which
2165 contains no Org syntax, the back-end, as a symbol, and the
2166 communication channel, as a plist. It must return a string or
2167 nil.")
2169 (defvar org-export-filter-final-output-functions nil
2170 "List of functions applied to the transcoded string.
2171 Each filter is called with three arguments: the full transcoded
2172 string, the back-end, as a symbol, and the communication channel,
2173 as a plist. It must return a string that will be used as the
2174 final export output.")
2177 ;;;; Elements Filters
2179 (defvar org-export-filter-babel-call-functions nil
2180 "List of functions applied to a transcoded babel-call.
2181 Each filter is called with three arguments: the transcoded data,
2182 as a string, the back-end, as a symbol, and the communication
2183 channel, as a plist. It must return a string or nil.")
2185 (defvar org-export-filter-center-block-functions nil
2186 "List of functions applied to a transcoded center block.
2187 Each filter is called with three arguments: the transcoded data,
2188 as a string, the back-end, as a symbol, and the communication
2189 channel, as a plist. It must return a string or nil.")
2191 (defvar org-export-filter-clock-functions nil
2192 "List of functions applied to a transcoded clock.
2193 Each filter is called with three arguments: the transcoded data,
2194 as a string, the back-end, as a symbol, and the communication
2195 channel, as a plist. It must return a string or nil.")
2197 (defvar org-export-filter-diary-sexp-functions nil
2198 "List of functions applied to a transcoded diary-sexp.
2199 Each filter is called with three arguments: the transcoded data,
2200 as a string, the back-end, as a symbol, and the communication
2201 channel, as a plist. It must return a string or nil.")
2203 (defvar org-export-filter-drawer-functions nil
2204 "List of functions applied to a transcoded drawer.
2205 Each filter is called with three arguments: the transcoded data,
2206 as a string, the back-end, as a symbol, and the communication
2207 channel, as a plist. It must return a string or nil.")
2209 (defvar org-export-filter-dynamic-block-functions nil
2210 "List of functions applied to a transcoded dynamic-block.
2211 Each filter is called with three arguments: the transcoded data,
2212 as a string, the back-end, as a symbol, and the communication
2213 channel, as a plist. It must return a string or nil.")
2215 (defvar org-export-filter-example-block-functions nil
2216 "List of functions applied to a transcoded example-block.
2217 Each filter is called with three arguments: the transcoded data,
2218 as a string, the back-end, as a symbol, and the communication
2219 channel, as a plist. It must return a string or nil.")
2221 (defvar org-export-filter-export-block-functions nil
2222 "List of functions applied to a transcoded export-block.
2223 Each filter is called with three arguments: the transcoded data,
2224 as a string, the back-end, as a symbol, and the communication
2225 channel, as a plist. It must return a string or nil.")
2227 (defvar org-export-filter-fixed-width-functions nil
2228 "List of functions applied to a transcoded fixed-width.
2229 Each filter is called with three arguments: the transcoded data,
2230 as a string, the back-end, as a symbol, and the communication
2231 channel, as a plist. It must return a string or nil.")
2233 (defvar org-export-filter-footnote-definition-functions nil
2234 "List of functions applied to a transcoded footnote-definition.
2235 Each filter is called with three arguments: the transcoded data,
2236 as a string, the back-end, as a symbol, and the communication
2237 channel, as a plist. It must return a string or nil.")
2239 (defvar org-export-filter-headline-functions nil
2240 "List of functions applied to a transcoded headline.
2241 Each filter is called with three arguments: the transcoded data,
2242 as a string, the back-end, as a symbol, and the communication
2243 channel, as a plist. It must return a string or nil.")
2245 (defvar org-export-filter-horizontal-rule-functions nil
2246 "List of functions applied to a transcoded horizontal-rule.
2247 Each filter is called with three arguments: the transcoded data,
2248 as a string, the back-end, as a symbol, and the communication
2249 channel, as a plist. It must return a string or nil.")
2251 (defvar org-export-filter-inlinetask-functions nil
2252 "List of functions applied to a transcoded inlinetask.
2253 Each filter is called with three arguments: the transcoded data,
2254 as a string, the back-end, as a symbol, and the communication
2255 channel, as a plist. It must return a string or nil.")
2257 (defvar org-export-filter-item-functions nil
2258 "List of functions applied to a transcoded item.
2259 Each filter is called with three arguments: the transcoded data,
2260 as a string, the back-end, as a symbol, and the communication
2261 channel, as a plist. It must return a string or nil.")
2263 (defvar org-export-filter-keyword-functions nil
2264 "List of functions applied to a transcoded keyword.
2265 Each filter is called with three arguments: the transcoded data,
2266 as a string, the back-end, as a symbol, and the communication
2267 channel, as a plist. It must return a string or nil.")
2269 (defvar org-export-filter-latex-environment-functions nil
2270 "List of functions applied to a transcoded latex-environment.
2271 Each filter is called with three arguments: the transcoded data,
2272 as a string, the back-end, as a symbol, and the communication
2273 channel, as a plist. It must return a string or nil.")
2275 (defvar org-export-filter-node-property-functions nil
2276 "List of functions applied to a transcoded node-property.
2277 Each filter is called with three arguments: the transcoded data,
2278 as a string, the back-end, as a symbol, and the communication
2279 channel, as a plist. It must return a string or nil.")
2281 (defvar org-export-filter-paragraph-functions nil
2282 "List of functions applied to a transcoded paragraph.
2283 Each filter is called with three arguments: the transcoded data,
2284 as a string, the back-end, as a symbol, and the communication
2285 channel, as a plist. It must return a string or nil.")
2287 (defvar org-export-filter-plain-list-functions nil
2288 "List of functions applied to a transcoded plain-list.
2289 Each filter is called with three arguments: the transcoded data,
2290 as a string, the back-end, as a symbol, and the communication
2291 channel, as a plist. It must return a string or nil.")
2293 (defvar org-export-filter-planning-functions nil
2294 "List of functions applied to a transcoded planning.
2295 Each filter is called with three arguments: the transcoded data,
2296 as a string, the back-end, as a symbol, and the communication
2297 channel, as a plist. It must return a string or nil.")
2299 (defvar org-export-filter-property-drawer-functions nil
2300 "List of functions applied to a transcoded property-drawer.
2301 Each filter is called with three arguments: the transcoded data,
2302 as a string, the back-end, as a symbol, and the communication
2303 channel, as a plist. It must return a string or nil.")
2305 (defvar org-export-filter-quote-block-functions nil
2306 "List of functions applied to a transcoded quote block.
2307 Each filter is called with three arguments: the transcoded quote
2308 data, as a string, the back-end, as a symbol, and the
2309 communication channel, as a plist. It must return a string or
2310 nil.")
2312 (defvar org-export-filter-section-functions nil
2313 "List of functions applied to a transcoded section.
2314 Each filter is called with three arguments: the transcoded data,
2315 as a string, the back-end, as a symbol, and the communication
2316 channel, as a plist. It must return a string or nil.")
2318 (defvar org-export-filter-special-block-functions nil
2319 "List of functions applied to a transcoded special block.
2320 Each filter is called with three arguments: the transcoded data,
2321 as a string, the back-end, as a symbol, and the communication
2322 channel, as a plist. It must return a string or nil.")
2324 (defvar org-export-filter-src-block-functions nil
2325 "List of functions applied to a transcoded src-block.
2326 Each filter is called with three arguments: the transcoded data,
2327 as a string, the back-end, as a symbol, and the communication
2328 channel, as a plist. It must return a string or nil.")
2330 (defvar org-export-filter-table-functions nil
2331 "List of functions applied to a transcoded table.
2332 Each filter is called with three arguments: the transcoded data,
2333 as a string, the back-end, as a symbol, and the communication
2334 channel, as a plist. It must return a string or nil.")
2336 (defvar org-export-filter-table-cell-functions nil
2337 "List of functions applied to a transcoded table-cell.
2338 Each filter is called with three arguments: the transcoded data,
2339 as a string, the back-end, as a symbol, and the communication
2340 channel, as a plist. It must return a string or nil.")
2342 (defvar org-export-filter-table-row-functions nil
2343 "List of functions applied to a transcoded table-row.
2344 Each filter is called with three arguments: the transcoded data,
2345 as a string, the back-end, as a symbol, and the communication
2346 channel, as a plist. It must return a string or nil.")
2348 (defvar org-export-filter-verse-block-functions nil
2349 "List of functions applied to a transcoded verse block.
2350 Each filter is called with three arguments: the transcoded data,
2351 as a string, the back-end, as a symbol, and the communication
2352 channel, as a plist. It must return a string or nil.")
2355 ;;;; Objects Filters
2357 (defvar org-export-filter-bold-functions nil
2358 "List of functions applied to transcoded bold text.
2359 Each filter is called with three arguments: the transcoded data,
2360 as a string, the back-end, as a symbol, and the communication
2361 channel, as a plist. It must return a string or nil.")
2363 (defvar org-export-filter-code-functions nil
2364 "List of functions applied to transcoded code text.
2365 Each filter is called with three arguments: the transcoded data,
2366 as a string, the back-end, as a symbol, and the communication
2367 channel, as a plist. It must return a string or nil.")
2369 (defvar org-export-filter-entity-functions nil
2370 "List of functions applied to a transcoded entity.
2371 Each filter is called with three arguments: the transcoded data,
2372 as a string, the back-end, as a symbol, and the communication
2373 channel, as a plist. It must return a string or nil.")
2375 (defvar org-export-filter-export-snippet-functions nil
2376 "List of functions applied to a transcoded export-snippet.
2377 Each filter is called with three arguments: the transcoded data,
2378 as a string, the back-end, as a symbol, and the communication
2379 channel, as a plist. It must return a string or nil.")
2381 (defvar org-export-filter-footnote-reference-functions nil
2382 "List of functions applied to a transcoded footnote-reference.
2383 Each filter is called with three arguments: the transcoded data,
2384 as a string, the back-end, as a symbol, and the communication
2385 channel, as a plist. It must return a string or nil.")
2387 (defvar org-export-filter-inline-babel-call-functions nil
2388 "List of functions applied to a transcoded inline-babel-call.
2389 Each filter is called with three arguments: the transcoded data,
2390 as a string, the back-end, as a symbol, and the communication
2391 channel, as a plist. It must return a string or nil.")
2393 (defvar org-export-filter-inline-src-block-functions nil
2394 "List of functions applied to a transcoded inline-src-block.
2395 Each filter is called with three arguments: the transcoded data,
2396 as a string, the back-end, as a symbol, and the communication
2397 channel, as a plist. It must return a string or nil.")
2399 (defvar org-export-filter-italic-functions nil
2400 "List of functions applied to transcoded italic text.
2401 Each filter is called with three arguments: the transcoded data,
2402 as a string, the back-end, as a symbol, and the communication
2403 channel, as a plist. It must return a string or nil.")
2405 (defvar org-export-filter-latex-fragment-functions nil
2406 "List of functions applied to a transcoded latex-fragment.
2407 Each filter is called with three arguments: the transcoded data,
2408 as a string, the back-end, as a symbol, and the communication
2409 channel, as a plist. It must return a string or nil.")
2411 (defvar org-export-filter-line-break-functions nil
2412 "List of functions applied to a transcoded line-break.
2413 Each filter is called with three arguments: the transcoded data,
2414 as a string, the back-end, as a symbol, and the communication
2415 channel, as a plist. It must return a string or nil.")
2417 (defvar org-export-filter-link-functions nil
2418 "List of functions applied to a transcoded link.
2419 Each filter is called with three arguments: the transcoded data,
2420 as a string, the back-end, as a symbol, and the communication
2421 channel, as a plist. It must return a string or nil.")
2423 (defvar org-export-filter-radio-target-functions nil
2424 "List of functions applied to a transcoded radio-target.
2425 Each filter is called with three arguments: the transcoded data,
2426 as a string, the back-end, as a symbol, and the communication
2427 channel, as a plist. It must return a string or nil.")
2429 (defvar org-export-filter-statistics-cookie-functions nil
2430 "List of functions applied to a transcoded statistics-cookie.
2431 Each filter is called with three arguments: the transcoded data,
2432 as a string, the back-end, as a symbol, and the communication
2433 channel, as a plist. It must return a string or nil.")
2435 (defvar org-export-filter-strike-through-functions nil
2436 "List of functions applied to transcoded strike-through text.
2437 Each filter is called with three arguments: the transcoded data,
2438 as a string, the back-end, as a symbol, and the communication
2439 channel, as a plist. It must return a string or nil.")
2441 (defvar org-export-filter-subscript-functions nil
2442 "List of functions applied to a transcoded subscript.
2443 Each filter is called with three arguments: the transcoded data,
2444 as a string, the back-end, as a symbol, and the communication
2445 channel, as a plist. It must return a string or nil.")
2447 (defvar org-export-filter-superscript-functions nil
2448 "List of functions applied to a transcoded superscript.
2449 Each filter is called with three arguments: the transcoded data,
2450 as a string, the back-end, as a symbol, and the communication
2451 channel, as a plist. It must return a string or nil.")
2453 (defvar org-export-filter-target-functions nil
2454 "List of functions applied to a transcoded target.
2455 Each filter is called with three arguments: the transcoded data,
2456 as a string, the back-end, as a symbol, and the communication
2457 channel, as a plist. It must return a string or nil.")
2459 (defvar org-export-filter-timestamp-functions nil
2460 "List of functions applied to a transcoded timestamp.
2461 Each filter is called with three arguments: the transcoded data,
2462 as a string, the back-end, as a symbol, and the communication
2463 channel, as a plist. It must return a string or nil.")
2465 (defvar org-export-filter-underline-functions nil
2466 "List of functions applied to transcoded underline text.
2467 Each filter is called with three arguments: the transcoded data,
2468 as a string, the back-end, as a symbol, and the communication
2469 channel, as a plist. It must return a string or nil.")
2471 (defvar org-export-filter-verbatim-functions nil
2472 "List of functions applied to transcoded verbatim text.
2473 Each filter is called with three arguments: the transcoded data,
2474 as a string, the back-end, as a symbol, and the communication
2475 channel, as a plist. It must return a string or nil.")
2478 ;;;; Filters Tools
2480 ;; Internal function `org-export-install-filters' installs filters
2481 ;; hard-coded in back-ends (developer filters) and filters from global
2482 ;; variables (user filters) in the communication channel.
2484 ;; Internal function `org-export-filter-apply-functions' takes care
2485 ;; about applying each filter in order to a given data. It ignores
2486 ;; filters returning a nil value but stops whenever a filter returns
2487 ;; an empty string.
2489 (defun org-export-filter-apply-functions (filters value info)
2490 "Call every function in FILTERS.
2492 Functions are called with three arguments: a value, the export
2493 back-end name and the communication channel. First function in
2494 FILTERS is called with VALUE as its first argument. Second
2495 function in FILTERS is called with the previous result as its
2496 value, etc.
2498 Functions returning nil are skipped. Any function returning the
2499 empty string ends the process, which returns the empty string.
2501 Call is done in a LIFO fashion, to be sure that developer
2502 specified filters, if any, are called first."
2503 (catch :exit
2504 (let* ((backend (plist-get info :back-end))
2505 (backend-name (and backend (org-export-backend-name backend))))
2506 (dolist (filter filters value)
2507 (let ((result (funcall filter value backend-name info)))
2508 (cond ((not result))
2509 ((equal result "") (throw :exit ""))
2510 (t (setq value result))))))))
2512 (defun org-export-install-filters (info)
2513 "Install filters properties in communication channel.
2514 INFO is a plist containing the current communication channel.
2515 Return the updated communication channel."
2516 (let (plist)
2517 ;; Install user-defined filters with `org-export-filters-alist'
2518 ;; and filters already in INFO (through ext-plist mechanism).
2519 (dolist (p org-export-filters-alist)
2520 (let* ((prop (car p))
2521 (info-value (plist-get info prop))
2522 (default-value (symbol-value (cdr p))))
2523 (setq plist
2524 (plist-put plist prop
2525 ;; Filters in INFO will be called
2526 ;; before those user provided.
2527 (append (if (listp info-value) info-value
2528 (list info-value))
2529 default-value)))))
2530 ;; Prepend back-end specific filters to that list.
2531 (dolist (p (org-export-get-all-filters (plist-get info :back-end)))
2532 ;; Single values get consed, lists are appended.
2533 (let ((key (car p)) (value (cdr p)))
2534 (when value
2535 (setq plist
2536 (plist-put
2537 plist key
2538 (if (atom value) (cons value (plist-get plist key))
2539 (append value (plist-get plist key))))))))
2540 ;; Return new communication channel.
2541 (org-combine-plists info plist)))
2545 ;;; Core functions
2547 ;; This is the room for the main function, `org-export-as', along with
2548 ;; its derivative, `org-export-string-as'.
2549 ;; `org-export--copy-to-kill-ring-p' determines if output of these
2550 ;; function should be added to kill ring.
2552 ;; Note that `org-export-as' doesn't really parse the current buffer,
2553 ;; but a copy of it (with the same buffer-local variables and
2554 ;; visibility), where macros and include keywords are expanded and
2555 ;; Babel blocks are executed, if appropriate.
2556 ;; `org-export-with-buffer-copy' macro prepares that copy.
2558 ;; File inclusion is taken care of by
2559 ;; `org-export-expand-include-keyword' and
2560 ;; `org-export--prepare-file-contents'. Structure wise, including
2561 ;; a whole Org file in a buffer often makes little sense. For
2562 ;; example, if the file contains a headline and the include keyword
2563 ;; was within an item, the item should contain the headline. That's
2564 ;; why file inclusion should be done before any structure can be
2565 ;; associated to the file, that is before parsing.
2567 ;; `org-export-insert-default-template' is a command to insert
2568 ;; a default template (or a back-end specific template) at point or in
2569 ;; current subtree.
2571 (defun org-export-copy-buffer ()
2572 "Return a copy of the current buffer.
2573 The copy preserves Org buffer-local variables, visibility and
2574 narrowing."
2575 (let ((copy-buffer-fun (org-export--generate-copy-script (current-buffer)))
2576 (new-buf (generate-new-buffer (buffer-name))))
2577 (with-current-buffer new-buf
2578 (funcall copy-buffer-fun)
2579 (set-buffer-modified-p nil))
2580 new-buf))
2582 (defmacro org-export-with-buffer-copy (&rest body)
2583 "Apply BODY in a copy of the current buffer.
2584 The copy preserves local variables, visibility and contents of
2585 the original buffer. Point is at the beginning of the buffer
2586 when BODY is applied."
2587 (declare (debug t))
2588 (org-with-gensyms (buf-copy)
2589 `(let ((,buf-copy (org-export-copy-buffer)))
2590 (unwind-protect
2591 (with-current-buffer ,buf-copy
2592 (goto-char (point-min))
2593 (progn ,@body))
2594 (and (buffer-live-p ,buf-copy)
2595 ;; Kill copy without confirmation.
2596 (progn (with-current-buffer ,buf-copy
2597 (restore-buffer-modified-p nil))
2598 (kill-buffer ,buf-copy)))))))
2600 (defun org-export--generate-copy-script (buffer)
2601 "Generate a function duplicating BUFFER.
2603 The copy will preserve local variables, visibility, contents and
2604 narrowing of the original buffer. If a region was active in
2605 BUFFER, contents will be narrowed to that region instead.
2607 The resulting function can be evaluated at a later time, from
2608 another buffer, effectively cloning the original buffer there.
2610 The function assumes BUFFER's major mode is `org-mode'."
2611 (with-current-buffer buffer
2612 `(lambda ()
2613 (let ((inhibit-modification-hooks t))
2614 ;; Set major mode. Ignore `org-mode-hook' as it has been run
2615 ;; already in BUFFER.
2616 (let ((org-mode-hook nil) (org-inhibit-startup t)) (org-mode))
2617 ;; Copy specific buffer local variables and variables set
2618 ;; through BIND keywords.
2619 ,@(let ((bound-variables (org-export--list-bound-variables))
2620 vars)
2621 (dolist (entry (buffer-local-variables (buffer-base-buffer)) vars)
2622 (when (consp entry)
2623 (let ((var (car entry))
2624 (val (cdr entry)))
2625 (and (not (memq var org-export-ignored-local-variables))
2626 (or (memq var
2627 '(default-directory
2628 buffer-file-name
2629 buffer-file-coding-system))
2630 (assq var bound-variables)
2631 (string-match "^\\(org-\\|orgtbl-\\)"
2632 (symbol-name var)))
2633 ;; Skip unreadable values, as they cannot be
2634 ;; sent to external process.
2635 (or (not val) (ignore-errors (read (format "%S" val))))
2636 (push `(set (make-local-variable (quote ,var))
2637 (quote ,val))
2638 vars))))))
2639 ;; Whole buffer contents.
2640 (insert
2641 ,(org-with-wide-buffer
2642 (buffer-substring-no-properties
2643 (point-min) (point-max))))
2644 ;; Narrowing.
2645 ,(if (org-region-active-p)
2646 `(narrow-to-region ,(region-beginning) ,(region-end))
2647 `(narrow-to-region ,(point-min) ,(point-max)))
2648 ;; Current position of point.
2649 (goto-char ,(point))
2650 ;; Overlays with invisible property.
2651 ,@(let (ov-set)
2652 (dolist (ov (overlays-in (point-min) (point-max)) ov-set)
2653 (let ((invis-prop (overlay-get ov 'invisible)))
2654 (when invis-prop
2655 (push `(overlay-put
2656 (make-overlay ,(overlay-start ov)
2657 ,(overlay-end ov))
2658 'invisible (quote ,invis-prop))
2659 ov-set)))))))))
2661 (defun org-export--delete-comment-trees ()
2662 "Delete commented trees and commented inlinetasks in the buffer.
2663 Narrowing, if any, is ignored."
2664 (org-with-wide-buffer
2665 (goto-char (point-min))
2666 (let* ((case-fold-search t)
2667 (regexp (concat org-outline-regexp-bol ".*" org-comment-string)))
2668 (while (re-search-forward regexp nil t)
2669 (let ((element (org-element-at-point)))
2670 (when (org-element-property :commentedp element)
2671 (delete-region (org-element-property :begin element)
2672 (org-element-property :end element))))))))
2674 (defun org-export--prune-tree (data info)
2675 "Prune non exportable elements from DATA.
2676 DATA is the parse tree to traverse. INFO is the plist holding
2677 export info. Also set `:ignore-list' in INFO to a list of
2678 objects which should be ignored during export, but not removed
2679 from tree."
2680 (letrec ((ignore nil)
2681 ;; First find trees containing a select tag, if any.
2682 (selected (org-export--selected-trees data info))
2683 (walk-data
2684 (lambda (data)
2685 ;; Prune non-exportable elements and objects from tree.
2686 ;; As a special case, special rows and cells from tables
2687 ;; are stored in IGNORE, as they still need to be
2688 ;; accessed during export.
2689 (when data
2690 (let ((type (org-element-type data)))
2691 (if (org-export--skip-p data info selected)
2692 (if (memq type '(table-cell table-row)) (push data ignore)
2693 (org-element-extract-element data))
2694 (if (and (eq type 'headline)
2695 (eq (plist-get info :with-archived-trees)
2696 'headline)
2697 (org-element-property :archivedp data))
2698 ;; If headline is archived but tree below has
2699 ;; to be skipped, remove contents.
2700 (org-element-set-contents data)
2701 ;; Move into recursive objects/elements.
2702 (mapc walk-data (org-element-contents data)))
2703 ;; Move into secondary string, if any.
2704 (dolist (p (cdr (assq type
2705 org-element-secondary-value-alist)))
2706 (mapc walk-data (org-element-property p data))))))))
2707 (definitions
2708 ;; Collect definitions before possibly pruning them so as
2709 ;; to avoid parsing them again if they are required.
2710 (org-element-map data '(footnote-definition footnote-reference)
2711 (lambda (f)
2712 (cond
2713 ((eq (org-element-type f) 'footnote-definition) f)
2714 ((eq (org-element-property :type f) 'standard) nil)
2715 (t (let ((label (org-element-property :label f)))
2716 (when label ;Skip anonymous references.
2717 (apply
2718 #'org-element-create
2719 'footnote-definition `(:label ,label :post-blank 1)
2720 (org-element-contents f))))))))))
2721 ;; If a select tag is active, also ignore the section before the
2722 ;; first headline, if any.
2723 (when selected
2724 (let ((first-element (car (org-element-contents data))))
2725 (when (eq (org-element-type first-element) 'section)
2726 (org-element-extract-element first-element))))
2727 ;; Prune tree and communication channel.
2728 (funcall walk-data data)
2729 (dolist (entry (append
2730 ;; Priority is given to back-end specific options.
2731 (org-export-get-all-options (plist-get info :back-end))
2732 org-export-options-alist))
2733 (when (eq (nth 4 entry) 'parse)
2734 (funcall walk-data (plist-get info (car entry)))))
2735 (let ((missing (org-export--missing-definitions data definitions)))
2736 (funcall walk-data missing)
2737 (org-export--install-footnote-definitions missing data))
2738 ;; Eventually set `:ignore-list'.
2739 (plist-put info :ignore-list ignore)))
2741 (defun org-export--missing-definitions (tree definitions)
2742 "List footnote definitions missing from TREE.
2743 Missing definitions are searched within DEFINITIONS, which is
2744 a list of footnote definitions or in the widened buffer."
2745 (let* ((list-labels
2746 (lambda (data)
2747 ;; List all footnote labels encountered in DATA. Inline
2748 ;; footnote references are ignored.
2749 (org-element-map data 'footnote-reference
2750 (lambda (reference)
2751 (and (eq (org-element-property :type reference) 'standard)
2752 (org-element-property :label reference))))))
2753 defined undefined missing-definitions)
2754 ;; Partition DIRECT-REFERENCES between DEFINED and UNDEFINED
2755 ;; references.
2756 (let ((known-definitions
2757 (org-element-map tree '(footnote-reference footnote-definition)
2758 (lambda (f)
2759 (and (or (eq (org-element-type f) 'footnote-definition)
2760 (eq (org-element-property :type f) 'inline))
2761 (org-element-property :label f)))))
2762 seen)
2763 (dolist (l (funcall list-labels tree))
2764 (cond ((member l seen))
2765 ((member l known-definitions) (push l defined))
2766 (t (push l undefined)))))
2767 ;; Complete MISSING-DEFINITIONS by finding the definition of every
2768 ;; undefined label, first by looking into DEFINITIONS, then by
2769 ;; searching the widened buffer. This is a recursive process
2770 ;; since definitions found can themselves contain an undefined
2771 ;; reference.
2772 (while undefined
2773 (let* ((label (pop undefined))
2774 (definition
2775 (cond
2776 ((cl-some
2777 (lambda (d) (and (equal (org-element-property :label d) label)
2779 definitions))
2780 ((pcase (org-footnote-get-definition label)
2781 (`(,_ ,beg . ,_)
2782 (org-with-wide-buffer
2783 (goto-char beg)
2784 (let ((datum (org-element-context)))
2785 (if (eq (org-element-type datum) 'footnote-reference)
2786 datum
2787 ;; Parse definition with contents.
2788 (save-restriction
2789 (narrow-to-region
2790 (org-element-property :begin datum)
2791 (org-element-property :end datum))
2792 (org-element-map (org-element-parse-buffer)
2793 'footnote-definition #'identity nil t))))))
2794 (_ nil)))
2795 (t (user-error "Definition not found for footnote %s" label)))))
2796 (push label defined)
2797 (push definition missing-definitions)
2798 ;; Look for footnote references within DEFINITION, since
2799 ;; we may need to also find their definition.
2800 (dolist (l (funcall list-labels definition))
2801 (unless (or (member l defined) ;Known label
2802 (member l undefined)) ;Processed later
2803 (push l undefined)))))
2804 ;; MISSING-DEFINITIONS may contain footnote references with inline
2805 ;; definitions. Make sure those are changed into real footnote
2806 ;; definitions.
2807 (mapcar (lambda (d)
2808 (if (eq (org-element-type d) 'footnote-definition) d
2809 (let ((label (org-element-property :label d)))
2810 (apply #'org-element-create
2811 'footnote-definition `(:label ,label :post-blank 1)
2812 (org-element-contents d)))))
2813 missing-definitions)))
2815 (defun org-export--install-footnote-definitions (definitions tree)
2816 "Install footnote definitions in tree.
2818 DEFINITIONS is the list of footnote definitions to install. TREE
2819 is the parse tree.
2821 If there is a footnote section in TREE, definitions found are
2822 appended to it. If `org-footnote-section' is non-nil, a new
2823 footnote section containing all definitions is inserted in TREE.
2824 Otherwise, definitions are appended at the end of the section
2825 containing their first reference."
2826 (cond
2827 ((null definitions))
2828 ;; If there is a footnote section, insert definitions there.
2829 ((let ((footnote-section
2830 (org-element-map tree 'headline
2831 (lambda (h) (and (org-element-property :footnote-section-p h) h))
2832 nil t)))
2833 (and footnote-section
2834 (apply #'org-element-adopt-elements
2835 footnote-section
2836 (nreverse definitions)))))
2837 ;; If there should be a footnote section, create one containing all
2838 ;; the definitions at the end of the tree.
2839 (org-footnote-section
2840 (org-element-adopt-elements
2841 tree
2842 (org-element-create 'headline
2843 (list :footnote-section-p t
2844 :level 1
2845 :title org-footnote-section)
2846 (apply #'org-element-create
2847 'section
2849 (nreverse definitions)))))
2850 ;; Otherwise add each definition at the end of the section where it
2851 ;; is first referenced.
2853 (letrec ((seen nil)
2854 (insert-definitions
2855 (lambda (data)
2856 ;; Insert footnote definitions in the same section as
2857 ;; their first reference in DATA.
2858 (org-element-map data 'footnote-reference
2859 (lambda (reference)
2860 (when (eq (org-element-property :type reference) 'standard)
2861 (let ((label (org-element-property :label reference)))
2862 (unless (member label seen)
2863 (push label seen)
2864 (let ((definition
2865 (cl-some
2866 (lambda (d)
2867 (and (equal (org-element-property :label d)
2868 label)
2870 definitions)))
2871 (org-element-adopt-elements
2872 (org-element-lineage reference '(section))
2873 definition)
2874 ;; Also insert definitions for nested
2875 ;; references, if any.
2876 (funcall insert-definitions definition))))))))))
2877 (funcall insert-definitions tree)))))
2879 (defun org-export--remove-uninterpreted-data (data info)
2880 "Change uninterpreted elements back into Org syntax.
2881 DATA is the parse tree. INFO is a plist containing export
2882 options. Each uninterpreted element or object is changed back
2883 into a string. Contents, if any, are not modified. The parse
2884 tree is modified by side effect."
2885 (org-export--remove-uninterpreted-data-1 data info)
2886 (dolist (entry org-export-options-alist)
2887 (when (eq (nth 4 entry) 'parse)
2888 (let ((p (car entry)))
2889 (plist-put info
2891 (org-export--remove-uninterpreted-data-1
2892 (plist-get info p)
2893 info))))))
2895 (defun org-export--remove-uninterpreted-data-1 (data info)
2896 "Change uninterpreted elements back into Org syntax.
2897 DATA is a parse tree or a secondary string. INFO is a plist
2898 containing export options. It is modified by side effect and
2899 returned by the function."
2900 (org-element-map data
2901 '(entity bold italic latex-environment latex-fragment strike-through
2902 subscript superscript underline)
2903 (lambda (blob)
2904 (let ((new
2905 (cl-case (org-element-type blob)
2906 ;; ... entities...
2907 (entity
2908 (and (not (plist-get info :with-entities))
2909 (list (concat
2910 (org-export-expand blob nil)
2911 (make-string
2912 (or (org-element-property :post-blank blob) 0)
2913 ?\s)))))
2914 ;; ... emphasis...
2915 ((bold italic strike-through underline)
2916 (and (not (plist-get info :with-emphasize))
2917 (let ((marker (cl-case (org-element-type blob)
2918 (bold "*")
2919 (italic "/")
2920 (strike-through "+")
2921 (underline "_"))))
2922 (append
2923 (list marker)
2924 (org-element-contents blob)
2925 (list (concat
2926 marker
2927 (make-string
2928 (or (org-element-property :post-blank blob)
2930 ?\s)))))))
2931 ;; ... LaTeX environments and fragments...
2932 ((latex-environment latex-fragment)
2933 (and (eq (plist-get info :with-latex) 'verbatim)
2934 (list (org-export-expand blob nil))))
2935 ;; ... sub/superscripts...
2936 ((subscript superscript)
2937 (let ((sub/super-p (plist-get info :with-sub-superscript))
2938 (bracketp (org-element-property :use-brackets-p blob)))
2939 (and (or (not sub/super-p)
2940 (and (eq sub/super-p '{}) (not bracketp)))
2941 (append
2942 (list (concat
2943 (if (eq (org-element-type blob) 'subscript)
2945 "^")
2946 (and bracketp "{")))
2947 (org-element-contents blob)
2948 (list (concat
2949 (and bracketp "}")
2950 (and (org-element-property :post-blank blob)
2951 (make-string
2952 (org-element-property :post-blank blob)
2953 ?\s)))))))))))
2954 (when new
2955 ;; Splice NEW at BLOB location in parse tree.
2956 (dolist (e new (org-element-extract-element blob))
2957 (unless (equal e "") (org-element-insert-before e blob))))))
2958 info nil nil t)
2959 ;; Return modified parse tree.
2960 data)
2962 ;;;###autoload
2963 (defun org-export-as
2964 (backend &optional subtreep visible-only body-only ext-plist)
2965 "Transcode current Org buffer into BACKEND code.
2967 BACKEND is either an export back-end, as returned by, e.g.,
2968 `org-export-create-backend', or a symbol referring to
2969 a registered back-end.
2971 If narrowing is active in the current buffer, only transcode its
2972 narrowed part.
2974 If a region is active, transcode that region.
2976 When optional argument SUBTREEP is non-nil, transcode the
2977 sub-tree at point, extracting information from the headline
2978 properties first.
2980 When optional argument VISIBLE-ONLY is non-nil, don't export
2981 contents of hidden elements.
2983 When optional argument BODY-ONLY is non-nil, only return body
2984 code, without surrounding template.
2986 Optional argument EXT-PLIST, when provided, is a property list
2987 with external parameters overriding Org default settings, but
2988 still inferior to file-local settings.
2990 Return code as a string."
2991 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
2992 (org-export-barf-if-invalid-backend backend)
2993 (save-excursion
2994 (save-restriction
2995 ;; Narrow buffer to an appropriate region or subtree for
2996 ;; parsing. If parsing subtree, be sure to remove main
2997 ;; headline, planning data and property drawer.
2998 (cond ((org-region-active-p)
2999 (narrow-to-region (region-beginning) (region-end)))
3000 (subtreep
3001 (org-narrow-to-subtree)
3002 (goto-char (point-min))
3003 (org-end-of-meta-data)
3004 (narrow-to-region (point) (point-max))))
3005 ;; Initialize communication channel with original buffer
3006 ;; attributes, unavailable in its copy.
3007 (let* ((org-export-current-backend (org-export-backend-name backend))
3008 (info (org-combine-plists
3009 (org-export--get-export-attributes
3010 backend subtreep visible-only body-only)
3011 (org-export--get-buffer-attributes)))
3012 (parsed-keywords
3013 (delq nil
3014 (mapcar (lambda (o) (and (eq (nth 4 o) 'parse) (nth 1 o)))
3015 (append (org-export-get-all-options backend)
3016 org-export-options-alist))))
3017 tree)
3018 ;; Update communication channel and get parse tree. Buffer
3019 ;; isn't parsed directly. Instead, all buffer modifications
3020 ;; and consequent parsing are undertaken in a temporary copy.
3021 (org-export-with-buffer-copy
3022 ;; Run first hook with current back-end's name as argument.
3023 (run-hook-with-args 'org-export-before-processing-hook
3024 (org-export-backend-name backend))
3025 ;; Include files, delete comments and expand macros.
3026 (org-export-expand-include-keyword)
3027 (org-export--delete-comment-trees)
3028 (org-macro-initialize-templates)
3029 (org-macro-replace-all org-macro-templates nil parsed-keywords)
3030 ;; Refresh buffer properties and radio targets after
3031 ;; potentially invasive previous changes. Likewise, do it
3032 ;; again after executing Babel code.
3033 (org-set-regexps-and-options)
3034 (org-update-radio-target-regexp)
3035 (when org-export-babel-evaluate
3036 (org-babel-exp-process-buffer)
3037 (org-set-regexps-and-options)
3038 (org-update-radio-target-regexp))
3039 ;; Run last hook with current back-end's name as argument.
3040 ;; Update buffer properties and radio targets one last time
3041 ;; before parsing.
3042 (goto-char (point-min))
3043 (save-excursion
3044 (run-hook-with-args 'org-export-before-parsing-hook
3045 (org-export-backend-name backend)))
3046 (org-set-regexps-and-options)
3047 (org-update-radio-target-regexp)
3048 ;; Update communication channel with environment. Also
3049 ;; install user's and developer's filters.
3050 (setq info
3051 (org-export-install-filters
3052 (org-combine-plists
3053 info (org-export-get-environment backend subtreep ext-plist))))
3054 ;; Call options filters and update export options. We do not
3055 ;; use `org-export-filter-apply-functions' here since the
3056 ;; arity of such filters is different.
3057 (let ((backend-name (org-export-backend-name backend)))
3058 (dolist (filter (plist-get info :filter-options))
3059 (let ((result (funcall filter info backend-name)))
3060 (when result (setq info result)))))
3061 ;; Expand export-specific set of macros: {{{author}}},
3062 ;; {{{date(FORMAT)}}}, {{{email}}} and {{{title}}}. It must
3063 ;; be done once regular macros have been expanded, since
3064 ;; parsed keywords may contain one of them.
3065 (org-macro-replace-all
3066 (list
3067 (cons "author" (org-element-interpret-data (plist-get info :author)))
3068 (cons "date"
3069 (let* ((date (plist-get info :date))
3070 (value (or (org-element-interpret-data date) "")))
3071 (if (and (consp date)
3072 (not (cdr date))
3073 (eq (org-element-type (car date)) 'timestamp))
3074 (format "(eval (if (org-string-nw-p \"$1\") %s %S))"
3075 (format "(org-timestamp-format '%S \"$1\")"
3076 (org-element-copy (car date)))
3077 value)
3078 value)))
3079 (cons "email" (org-element-interpret-data (plist-get info :email)))
3080 (cons "title" (org-element-interpret-data (plist-get info :title)))
3081 (cons "results" "$1"))
3082 'finalize
3083 parsed-keywords)
3084 ;; Parse buffer.
3085 (setq tree (org-element-parse-buffer nil visible-only))
3086 ;; Prune tree from non-exported elements and transform
3087 ;; uninterpreted elements or objects in both parse tree and
3088 ;; communication channel.
3089 (org-export--prune-tree tree info)
3090 (org-export--remove-uninterpreted-data tree info)
3091 ;; Call parse tree filters.
3092 (setq tree
3093 (org-export-filter-apply-functions
3094 (plist-get info :filter-parse-tree) tree info))
3095 ;; Now tree is complete, compute its properties and add them
3096 ;; to communication channel.
3097 (setq info (org-export--collect-tree-properties tree info))
3098 ;; Eventually transcode TREE. Wrap the resulting string into
3099 ;; a template.
3100 (let* ((body (org-element-normalize-string
3101 (or (org-export-data tree info) "")))
3102 (inner-template (cdr (assq 'inner-template
3103 (plist-get info :translate-alist))))
3104 (full-body (org-export-filter-apply-functions
3105 (plist-get info :filter-body)
3106 (if (not (functionp inner-template)) body
3107 (funcall inner-template body info))
3108 info))
3109 (template (cdr (assq 'template
3110 (plist-get info :translate-alist)))))
3111 ;; Remove all text properties since they cannot be
3112 ;; retrieved from an external process. Finally call
3113 ;; final-output filter and return result.
3114 (org-no-properties
3115 (org-export-filter-apply-functions
3116 (plist-get info :filter-final-output)
3117 (if (or (not (functionp template)) body-only) full-body
3118 (funcall template full-body info))
3119 info))))))))
3121 ;;;###autoload
3122 (defun org-export-string-as (string backend &optional body-only ext-plist)
3123 "Transcode STRING into BACKEND code.
3125 BACKEND is either an export back-end, as returned by, e.g.,
3126 `org-export-create-backend', or a symbol referring to
3127 a registered back-end.
3129 When optional argument BODY-ONLY is non-nil, only return body
3130 code, without preamble nor postamble.
3132 Optional argument EXT-PLIST, when provided, is a property list
3133 with external parameters overriding Org default settings, but
3134 still inferior to file-local settings.
3136 Return code as a string."
3137 (with-temp-buffer
3138 (insert string)
3139 (let ((org-inhibit-startup t)) (org-mode))
3140 (org-export-as backend nil nil body-only ext-plist)))
3142 ;;;###autoload
3143 (defun org-export-replace-region-by (backend)
3144 "Replace the active region by its export to BACKEND.
3145 BACKEND is either an export back-end, as returned by, e.g.,
3146 `org-export-create-backend', or a symbol referring to
3147 a registered back-end."
3148 (unless (org-region-active-p) (user-error "No active region to replace"))
3149 (insert
3150 (org-export-string-as
3151 (delete-and-extract-region (region-beginning) (region-end)) backend t)))
3153 ;;;###autoload
3154 (defun org-export-insert-default-template (&optional backend subtreep)
3155 "Insert all export keywords with default values at beginning of line.
3157 BACKEND is a symbol referring to the name of a registered export
3158 back-end, for which specific export options should be added to
3159 the template, or `default' for default template. When it is nil,
3160 the user will be prompted for a category.
3162 If SUBTREEP is non-nil, export configuration will be set up
3163 locally for the subtree through node properties."
3164 (interactive)
3165 (unless (derived-mode-p 'org-mode) (user-error "Not in an Org mode buffer"))
3166 (when (and subtreep (org-before-first-heading-p))
3167 (user-error "No subtree to set export options for"))
3168 (let ((node (and subtreep (save-excursion (org-back-to-heading t) (point))))
3169 (backend
3170 (or backend
3171 (intern
3172 (org-completing-read
3173 "Options category: "
3174 (cons "default"
3175 (mapcar (lambda (b)
3176 (symbol-name (org-export-backend-name b)))
3177 org-export-registered-backends))
3178 nil t))))
3179 options keywords)
3180 ;; Populate OPTIONS and KEYWORDS.
3181 (dolist (entry (cond ((eq backend 'default) org-export-options-alist)
3182 ((org-export-backend-p backend)
3183 (org-export-backend-options backend))
3184 (t (org-export-backend-options
3185 (org-export-get-backend backend)))))
3186 (let ((keyword (nth 1 entry))
3187 (option (nth 2 entry)))
3188 (cond
3189 (keyword (unless (assoc keyword keywords)
3190 (let ((value
3191 (if (eq (nth 4 entry) 'split)
3192 (mapconcat #'identity (eval (nth 3 entry)) " ")
3193 (eval (nth 3 entry)))))
3194 (push (cons keyword value) keywords))))
3195 (option (unless (assoc option options)
3196 (push (cons option (eval (nth 3 entry))) options))))))
3197 ;; Move to an appropriate location in order to insert options.
3198 (unless subtreep (beginning-of-line))
3199 ;; First (multiple) OPTIONS lines. Never go past fill-column.
3200 (when options
3201 (let ((items
3202 (mapcar
3203 #'(lambda (opt) (format "%s:%S" (car opt) (cdr opt)))
3204 (sort options (lambda (k1 k2) (string< (car k1) (car k2)))))))
3205 (if subtreep
3206 (org-entry-put
3207 node "EXPORT_OPTIONS" (mapconcat 'identity items " "))
3208 (while items
3209 (insert "#+OPTIONS:")
3210 (let ((width 10))
3211 (while (and items
3212 (< (+ width (length (car items)) 1) fill-column))
3213 (let ((item (pop items)))
3214 (insert " " item)
3215 (cl-incf width (1+ (length item))))))
3216 (insert "\n")))))
3217 ;; Then the rest of keywords, in the order specified in either
3218 ;; `org-export-options-alist' or respective export back-ends.
3219 (dolist (key (nreverse keywords))
3220 (let ((val (cond ((equal (car key) "DATE")
3221 (or (cdr key)
3222 (with-temp-buffer
3223 (org-insert-time-stamp (current-time)))))
3224 ((equal (car key) "TITLE")
3225 (or (let ((visited-file
3226 (buffer-file-name (buffer-base-buffer))))
3227 (and visited-file
3228 (file-name-sans-extension
3229 (file-name-nondirectory visited-file))))
3230 (buffer-name (buffer-base-buffer))))
3231 (t (cdr key)))))
3232 (if subtreep (org-entry-put node (concat "EXPORT_" (car key)) val)
3233 (insert
3234 (format "#+%s:%s\n"
3235 (car key)
3236 (if (org-string-nw-p val) (format " %s" val) ""))))))))
3238 (defun org-export-expand-include-keyword (&optional included dir footnotes)
3239 "Expand every include keyword in buffer.
3240 Optional argument INCLUDED is a list of included file names along
3241 with their line restriction, when appropriate. It is used to
3242 avoid infinite recursion. Optional argument DIR is the current
3243 working directory. It is used to properly resolve relative
3244 paths. Optional argument FOOTNOTES is a hash-table used for
3245 storing and resolving footnotes. It is created automatically."
3246 (let ((case-fold-search t)
3247 (file-prefix (make-hash-table :test #'equal))
3248 (current-prefix 0)
3249 (footnotes (or footnotes (make-hash-table :test #'equal)))
3250 (include-re "^[ \t]*#\\+INCLUDE:"))
3251 ;; If :minlevel is not set the text-property
3252 ;; `:org-include-induced-level' will be used to determine the
3253 ;; relative level when expanding INCLUDE.
3254 ;; Only affects included Org documents.
3255 (goto-char (point-min))
3256 (while (re-search-forward include-re nil t)
3257 (put-text-property (line-beginning-position) (line-end-position)
3258 :org-include-induced-level
3259 (1+ (org-reduced-level (or (org-current-level) 0)))))
3260 ;; Expand INCLUDE keywords.
3261 (goto-char (point-min))
3262 (while (re-search-forward include-re nil t)
3263 (let ((element (save-match-data (org-element-at-point))))
3264 (when (eq (org-element-type element) 'keyword)
3265 (beginning-of-line)
3266 ;; Extract arguments from keyword's value.
3267 (let* ((value (org-element-property :value element))
3268 (ind (org-get-indentation))
3269 location
3270 (file
3271 (and (string-match
3272 "^\\(\".+?\"\\|\\S-+\\)\\(?:\\s-+\\|$\\)" value)
3273 (prog1
3274 (save-match-data
3275 (let ((matched (match-string 1 value)))
3276 (when (string-match "\\(::\\(.*?\\)\\)\"?\\'"
3277 matched)
3278 (setq location (match-string 2 matched))
3279 (setq matched
3280 (replace-match "" nil nil matched 1)))
3281 (expand-file-name
3282 (org-unbracket-string "\"" "\"" matched)
3283 dir)))
3284 (setq value (replace-match "" nil nil value)))))
3285 (only-contents
3286 (and (string-match ":only-contents *\\([^: \r\t\n]\\S-*\\)?"
3287 value)
3288 (prog1 (org-not-nil (match-string 1 value))
3289 (setq value (replace-match "" nil nil value)))))
3290 (lines
3291 (and (string-match
3292 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\""
3293 value)
3294 (prog1 (match-string 1 value)
3295 (setq value (replace-match "" nil nil value)))))
3296 (env (cond
3297 ((string-match "\\<example\\>" value) 'literal)
3298 ((string-match "\\<export\\(?: +\\(.*\\)\\)?" value)
3299 'literal)
3300 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
3301 'literal)))
3302 ;; Minimal level of included file defaults to the child
3303 ;; level of the current headline, if any, or one. It
3304 ;; only applies is the file is meant to be included as
3305 ;; an Org one.
3306 (minlevel
3307 (and (not env)
3308 (if (string-match ":minlevel +\\([0-9]+\\)" value)
3309 (prog1 (string-to-number (match-string 1 value))
3310 (setq value (replace-match "" nil nil value)))
3311 (get-text-property (point)
3312 :org-include-induced-level))))
3313 (args (and (eq env 'literal) (match-string 1 value)))
3314 (block (and (string-match "\\<\\(\\S-+\\)\\>" value)
3315 (match-string 1 value))))
3316 ;; Remove keyword.
3317 (delete-region (point) (line-beginning-position 2))
3318 (cond
3319 ((not file) nil)
3320 ((not (file-readable-p file))
3321 (error "Cannot include file %s" file))
3322 ;; Check if files has already been parsed. Look after
3323 ;; inclusion lines too, as different parts of the same file
3324 ;; can be included too.
3325 ((member (list file lines) included)
3326 (error "Recursive file inclusion: %s" file))
3328 (cond
3329 ((eq env 'literal)
3330 (insert
3331 (let ((ind-str (make-string ind ?\s))
3332 (arg-str (if (stringp args) (format " %s" args) ""))
3333 (contents
3334 (org-escape-code-in-string
3335 (org-export--prepare-file-contents file lines))))
3336 (format "%s#+BEGIN_%s%s\n%s%s#+END_%s\n"
3337 ind-str block arg-str contents ind-str block))))
3338 ((stringp block)
3339 (insert
3340 (let ((ind-str (make-string ind ?\s))
3341 (contents
3342 (org-export--prepare-file-contents file lines)))
3343 (format "%s#+BEGIN_%s\n%s%s#+END_%s\n"
3344 ind-str block contents ind-str block))))
3346 (insert
3347 (with-temp-buffer
3348 (let ((org-inhibit-startup t)
3349 (lines
3350 (if location
3351 (org-export--inclusion-absolute-lines
3352 file location only-contents lines)
3353 lines)))
3354 (org-mode)
3355 (insert
3356 (org-export--prepare-file-contents
3357 file lines ind minlevel
3358 (or (gethash file file-prefix)
3359 (puthash file (cl-incf current-prefix) file-prefix))
3360 footnotes)))
3361 (org-export-expand-include-keyword
3362 (cons (list file lines) included)
3363 (file-name-directory file)
3364 footnotes)
3365 (buffer-string)))))
3366 ;; Expand footnotes after all files have been included.
3367 ;; Footnotes are stored at end of buffer.
3368 (unless included
3369 (org-with-wide-buffer
3370 (goto-char (point-max))
3371 (maphash (lambda (k v) (insert (format "\n[fn:%s] %s\n" k v)))
3372 footnotes)))))))))))
3374 (defun org-export--inclusion-absolute-lines (file location only-contents lines)
3375 "Resolve absolute lines for an included file with file-link.
3377 FILE is string file-name of the file to include. LOCATION is a
3378 string name within FILE to be included (located via
3379 `org-link-search'). If ONLY-CONTENTS is non-nil only the
3380 contents of the named element will be included, as determined
3381 Org-Element. If LINES is non-nil only those lines are included.
3383 Return a string of lines to be included in the format expected by
3384 `org-export--prepare-file-contents'."
3385 (with-temp-buffer
3386 (insert-file-contents file)
3387 (unless (eq major-mode 'org-mode)
3388 (let ((org-inhibit-startup t)) (org-mode)))
3389 (condition-case err
3390 ;; Enforce consistent search.
3391 (let ((org-link-search-must-match-exact-headline nil))
3392 (org-link-search location))
3393 (error
3394 (error "%s for %s::%s" (error-message-string err) file location)))
3395 (let* ((element (org-element-at-point))
3396 (contents-begin
3397 (and only-contents (org-element-property :contents-begin element))))
3398 (narrow-to-region
3399 (or contents-begin (org-element-property :begin element))
3400 (org-element-property (if contents-begin :contents-end :end) element))
3401 (when (and only-contents
3402 (memq (org-element-type element) '(headline inlinetask)))
3403 ;; Skip planning line and property-drawer.
3404 (goto-char (point-min))
3405 (when (looking-at-p org-planning-line-re) (forward-line))
3406 (when (looking-at org-property-drawer-re) (goto-char (match-end 0)))
3407 (unless (bolp) (forward-line))
3408 (narrow-to-region (point) (point-max))))
3409 (when lines
3410 (org-skip-whitespace)
3411 (beginning-of-line)
3412 (let* ((lines (split-string lines "-"))
3413 (lbeg (string-to-number (car lines)))
3414 (lend (string-to-number (cadr lines)))
3415 (beg (if (zerop lbeg) (point-min)
3416 (goto-char (point-min))
3417 (forward-line (1- lbeg))
3418 (point)))
3419 (end (if (zerop lend) (point-max)
3420 (goto-char beg)
3421 (forward-line (1- lend))
3422 (point))))
3423 (narrow-to-region beg end)))
3424 (let ((end (point-max)))
3425 (goto-char (point-min))
3426 (widen)
3427 (let ((start-line (line-number-at-pos)))
3428 (format "%d-%d"
3429 start-line
3430 (save-excursion
3431 (+ start-line
3432 (let ((counter 0))
3433 (while (< (point) end) (cl-incf counter) (forward-line))
3434 counter))))))))
3436 (defun org-export--prepare-file-contents
3437 (file &optional lines ind minlevel id footnotes)
3438 "Prepare contents of FILE for inclusion and return it as a string.
3440 When optional argument LINES is a string specifying a range of
3441 lines, include only those lines.
3443 Optional argument IND, when non-nil, is an integer specifying the
3444 global indentation of returned contents. Since its purpose is to
3445 allow an included file to stay in the same environment it was
3446 created (e.g., a list item), it doesn't apply past the first
3447 headline encountered.
3449 Optional argument MINLEVEL, when non-nil, is an integer
3450 specifying the level that any top-level headline in the included
3451 file should have.
3453 Optional argument ID is an integer that will be inserted before
3454 each footnote definition and reference if FILE is an Org file.
3455 This is useful to avoid conflicts when more than one Org file
3456 with footnotes is included in a document.
3458 Optional argument FOOTNOTES is a hash-table to store footnotes in
3459 the included document."
3460 (with-temp-buffer
3461 (insert-file-contents file)
3462 (when lines
3463 (let* ((lines (split-string lines "-"))
3464 (lbeg (string-to-number (car lines)))
3465 (lend (string-to-number (cadr lines)))
3466 (beg (if (zerop lbeg) (point-min)
3467 (goto-char (point-min))
3468 (forward-line (1- lbeg))
3469 (point)))
3470 (end (if (zerop lend) (point-max)
3471 (goto-char (point-min))
3472 (forward-line (1- lend))
3473 (point))))
3474 (narrow-to-region beg end)))
3475 ;; Remove blank lines at beginning and end of contents. The logic
3476 ;; behind that removal is that blank lines around include keyword
3477 ;; override blank lines in included file.
3478 (goto-char (point-min))
3479 (org-skip-whitespace)
3480 (beginning-of-line)
3481 (delete-region (point-min) (point))
3482 (goto-char (point-max))
3483 (skip-chars-backward " \r\t\n")
3484 (forward-line)
3485 (delete-region (point) (point-max))
3486 ;; If IND is set, preserve indentation of include keyword until
3487 ;; the first headline encountered.
3488 (when (and ind (> ind 0))
3489 (unless (eq major-mode 'org-mode)
3490 (let ((org-inhibit-startup t)) (org-mode)))
3491 (goto-char (point-min))
3492 (let ((ind-str (make-string ind ?\s)))
3493 (while (not (or (eobp) (looking-at org-outline-regexp-bol)))
3494 ;; Do not move footnote definitions out of column 0.
3495 (unless (and (looking-at org-footnote-definition-re)
3496 (eq (org-element-type (org-element-at-point))
3497 'footnote-definition))
3498 (insert ind-str))
3499 (forward-line))))
3500 ;; When MINLEVEL is specified, compute minimal level for headlines
3501 ;; in the file (CUR-MIN), and remove stars to each headline so
3502 ;; that headlines with minimal level have a level of MINLEVEL.
3503 (when minlevel
3504 (unless (eq major-mode 'org-mode)
3505 (let ((org-inhibit-startup t)) (org-mode)))
3506 (org-with-limited-levels
3507 (let ((levels (org-map-entries
3508 (lambda () (org-reduced-level (org-current-level))))))
3509 (when levels
3510 (let ((offset (- minlevel (apply #'min levels))))
3511 (unless (zerop offset)
3512 (when org-odd-levels-only (setq offset (* offset 2)))
3513 ;; Only change stars, don't bother moving whole
3514 ;; sections.
3515 (org-map-entries
3516 (lambda ()
3517 (if (< offset 0) (delete-char (abs offset))
3518 (insert (make-string offset ?*)))))))))))
3519 ;; Append ID to all footnote references and definitions, so they
3520 ;; become file specific and cannot collide with footnotes in other
3521 ;; included files. Further, collect relevant footnote definitions
3522 ;; outside of LINES, in order to reintroduce them later.
3523 (when id
3524 (let ((marker-min (point-min-marker))
3525 (marker-max (point-max-marker))
3526 (get-new-label
3527 (lambda (label)
3528 ;; Generate new label from LABEL by prefixing it with
3529 ;; "-ID-".
3530 (format "-%d-%s" id label)))
3531 (set-new-label
3532 (lambda (f old new)
3533 ;; Replace OLD label with NEW in footnote F.
3534 (save-excursion
3535 (goto-char (+ (org-element-property :begin f) 4))
3536 (looking-at (regexp-quote old))
3537 (replace-match new))))
3538 (seen-alist))
3539 (goto-char (point-min))
3540 (while (re-search-forward org-footnote-re nil t)
3541 (let ((footnote (save-excursion
3542 (backward-char)
3543 (org-element-context))))
3544 (when (memq (org-element-type footnote)
3545 '(footnote-definition footnote-reference))
3546 (let* ((label (org-element-property :label footnote)))
3547 ;; Update the footnote-reference at point and collect
3548 ;; the new label, which is only used for footnotes
3549 ;; outsides LINES.
3550 (when label
3551 (let ((seen (cdr (assoc label seen-alist))))
3552 (if seen (funcall set-new-label footnote label seen)
3553 (let ((new (funcall get-new-label label)))
3554 (push (cons label new) seen-alist)
3555 (org-with-wide-buffer
3556 (let* ((def (org-footnote-get-definition label))
3557 (beg (nth 1 def)))
3558 (when (and def
3559 (or (< beg marker-min)
3560 (>= beg marker-max)))
3561 ;; Store since footnote-definition is
3562 ;; outside of LINES.
3563 (puthash new
3564 (org-element-normalize-string (nth 3 def))
3565 footnotes))))
3566 (funcall set-new-label footnote label new)))))))))
3567 (set-marker marker-min nil)
3568 (set-marker marker-max nil)))
3569 (org-element-normalize-string (buffer-string))))
3571 (defun org-export--copy-to-kill-ring-p ()
3572 "Return a non-nil value when output should be added to the kill ring.
3573 See also `org-export-copy-to-kill-ring'."
3574 (if (eq org-export-copy-to-kill-ring 'if-interactive)
3575 (not (or executing-kbd-macro noninteractive))
3576 (eq org-export-copy-to-kill-ring t)))
3580 ;;; Tools For Back-Ends
3582 ;; A whole set of tools is available to help build new exporters. Any
3583 ;; function general enough to have its use across many back-ends
3584 ;; should be added here.
3586 ;;;; For Affiliated Keywords
3588 ;; `org-export-read-attribute' reads a property from a given element
3589 ;; as a plist. It can be used to normalize affiliated keywords'
3590 ;; syntax.
3592 ;; Since captions can span over multiple lines and accept dual values,
3593 ;; their internal representation is a bit tricky. Therefore,
3594 ;; `org-export-get-caption' transparently returns a given element's
3595 ;; caption as a secondary string.
3597 (defun org-export-read-attribute (attribute element &optional property)
3598 "Turn ATTRIBUTE property from ELEMENT into a plist.
3600 When optional argument PROPERTY is non-nil, return the value of
3601 that property within attributes.
3603 This function assumes attributes are defined as \":keyword
3604 value\" pairs. It is appropriate for `:attr_html' like
3605 properties.
3607 All values will become strings except the empty string and
3608 \"nil\", which will become nil. Also, values containing only
3609 double quotes will be read as-is, which means that \"\" value
3610 will become the empty string."
3611 (let* ((prepare-value
3612 (lambda (str)
3613 (save-match-data
3614 (cond ((member str '(nil "" "nil")) nil)
3615 ((string-match "^\"\\(\"+\\)?\"$" str)
3616 (or (match-string 1 str) ""))
3617 (t str)))))
3618 (attributes
3619 (let ((value (org-element-property attribute element)))
3620 (when value
3621 (let ((s (mapconcat 'identity value " ")) result)
3622 (while (string-match
3623 "\\(?:^\\|[ \t]+\\)\\(:[-a-zA-Z0-9_]+\\)\\([ \t]+\\|$\\)"
3625 (let ((value (substring s 0 (match-beginning 0))))
3626 (push (funcall prepare-value value) result))
3627 (push (intern (match-string 1 s)) result)
3628 (setq s (substring s (match-end 0))))
3629 ;; Ignore any string before first property with `cdr'.
3630 (cdr (nreverse (cons (funcall prepare-value s) result))))))))
3631 (if property (plist-get attributes property) attributes)))
3633 (defun org-export-get-caption (element &optional shortp)
3634 "Return caption from ELEMENT as a secondary string.
3636 When optional argument SHORTP is non-nil, return short caption,
3637 as a secondary string, instead.
3639 Caption lines are separated by a white space."
3640 (let ((full-caption (org-element-property :caption element)) caption)
3641 (dolist (line full-caption (cdr caption))
3642 (let ((cap (funcall (if shortp 'cdr 'car) line)))
3643 (when cap
3644 (setq caption (nconc (list " ") (copy-sequence cap) caption)))))))
3647 ;;;; For Derived Back-ends
3649 ;; `org-export-with-backend' is a function allowing to locally use
3650 ;; another back-end to transcode some object or element. In a derived
3651 ;; back-end, it may be used as a fall-back function once all specific
3652 ;; cases have been treated.
3654 (defun org-export-with-backend (backend data &optional contents info)
3655 "Call a transcoder from BACKEND on DATA.
3656 BACKEND is an export back-end, as returned by, e.g.,
3657 `org-export-create-backend', or a symbol referring to
3658 a registered back-end. DATA is an Org element, object, secondary
3659 string or string. CONTENTS, when non-nil, is the transcoded
3660 contents of DATA element, as a string. INFO, when non-nil, is
3661 the communication channel used for export, as a plist."
3662 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
3663 (org-export-barf-if-invalid-backend backend)
3664 (let ((type (org-element-type data)))
3665 (when (memq type '(nil org-data)) (error "No foreign transcoder available"))
3666 (let* ((all-transcoders (org-export-get-all-transcoders backend))
3667 (transcoder (cdr (assq type all-transcoders))))
3668 (unless (functionp transcoder) (error "No foreign transcoder available"))
3669 (let ((new-info
3670 (org-combine-plists
3671 info (list
3672 :back-end backend
3673 :translate-alist all-transcoders
3674 :exported-data (make-hash-table :test #'eq :size 401)))))
3675 ;; `:internal-references' are shared across back-ends.
3676 (prog1 (funcall transcoder data contents new-info)
3677 (plist-put info :internal-references
3678 (plist-get new-info :internal-references)))))))
3681 ;;;; For Export Snippets
3683 ;; Every export snippet is transmitted to the back-end. Though, the
3684 ;; latter will only retain one type of export-snippet, ignoring
3685 ;; others, based on the former's target back-end. The function
3686 ;; `org-export-snippet-backend' returns that back-end for a given
3687 ;; export-snippet.
3689 (defun org-export-snippet-backend (export-snippet)
3690 "Return EXPORT-SNIPPET targeted back-end as a symbol.
3691 Translation, with `org-export-snippet-translation-alist', is
3692 applied."
3693 (let ((back-end (org-element-property :back-end export-snippet)))
3694 (intern
3695 (or (cdr (assoc back-end org-export-snippet-translation-alist))
3696 back-end))))
3699 ;;;; For Footnotes
3701 ;; `org-export-collect-footnote-definitions' is a tool to list
3702 ;; actually used footnotes definitions in the whole parse tree, or in
3703 ;; a headline, in order to add footnote listings throughout the
3704 ;; transcoded data.
3706 ;; `org-export-footnote-first-reference-p' is a predicate used by some
3707 ;; back-ends, when they need to attach the footnote definition only to
3708 ;; the first occurrence of the corresponding label.
3710 ;; `org-export-get-footnote-definition' and
3711 ;; `org-export-get-footnote-number' provide easier access to
3712 ;; additional information relative to a footnote reference.
3714 (defun org-export-get-footnote-definition (footnote-reference info)
3715 "Return definition of FOOTNOTE-REFERENCE as parsed data.
3716 INFO is the plist used as a communication channel. If no such
3717 definition can be found, raise an error."
3718 (let ((label (org-element-property :label footnote-reference)))
3719 (if (not label) (org-element-contents footnote-reference)
3720 (let ((cache (or (plist-get info :footnote-definition-cache)
3721 (let ((hash (make-hash-table :test #'equal)))
3722 (plist-put info :footnote-definition-cache hash)
3723 hash))))
3725 (gethash label cache)
3726 (puthash label
3727 (org-element-map (plist-get info :parse-tree)
3728 '(footnote-definition footnote-reference)
3729 (lambda (f)
3730 (cond
3731 ;; Skip any footnote with a different label.
3732 ;; Also skip any standard footnote reference
3733 ;; with the same label since those cannot
3734 ;; contain a definition.
3735 ((not (equal (org-element-property :label f) label)) nil)
3736 ((eq (org-element-property :type f) 'standard) nil)
3737 ((org-element-contents f))
3738 ;; Even if the contents are empty, we can not
3739 ;; return nil since that would eventually raise
3740 ;; the error. Instead, return the equivalent
3741 ;; empty string.
3742 (t "")))
3743 info t)
3744 cache)
3745 (error "Definition not found for footnote %s" label))))))
3747 (defun org-export--footnote-reference-map
3748 (function data info &optional body-first)
3749 "Apply FUNCTION on every footnote reference in DATA.
3750 INFO is a plist containing export state. By default, as soon as
3751 a new footnote reference is encountered, FUNCTION is called onto
3752 its definition. However, if BODY-FIRST is non-nil, this step is
3753 delayed until the end of the process."
3754 (letrec ((definitions nil)
3755 (seen-refs nil)
3756 (search-ref
3757 (lambda (data delayp)
3758 ;; Search footnote references through DATA, filling
3759 ;; SEEN-REFS along the way. When DELAYP is non-nil,
3760 ;; store footnote definitions so they can be entered
3761 ;; later.
3762 (org-element-map data 'footnote-reference
3763 (lambda (f)
3764 (funcall function f)
3765 (let ((--label (org-element-property :label f)))
3766 (unless (and --label (member --label seen-refs))
3767 (when --label (push --label seen-refs))
3768 ;; Search for subsequent references in footnote
3769 ;; definition so numbering follows reading
3770 ;; logic, unless DELAYP in non-nil.
3771 (cond
3772 (delayp
3773 (push (org-export-get-footnote-definition f info)
3774 definitions))
3775 ;; Do not force entering inline definitions,
3776 ;; since `org-element-map' already traverses
3777 ;; them at the right time.
3778 ((eq (org-element-property :type f) 'inline))
3779 (t (funcall search-ref
3780 (org-export-get-footnote-definition f info)
3781 nil))))))
3782 info nil
3783 ;; Don't enter footnote definitions since it will
3784 ;; happen when their first reference is found.
3785 ;; Moreover, if DELAYP is non-nil, make sure we
3786 ;; postpone entering definitions of inline references.
3787 (if delayp '(footnote-definition footnote-reference)
3788 'footnote-definition)))))
3789 (funcall search-ref data body-first)
3790 (funcall search-ref (nreverse definitions) nil)))
3792 (defun org-export-collect-footnote-definitions (info &optional data body-first)
3793 "Return an alist between footnote numbers, labels and definitions.
3795 INFO is the current export state, as a plist.
3797 Definitions are collected throughout the whole parse tree, or
3798 DATA when non-nil.
3800 Sorting is done by order of references. As soon as a new
3801 reference is encountered, other references are searched within
3802 its definition. However, if BODY-FIRST is non-nil, this step is
3803 delayed after the whole tree is checked. This alters results
3804 when references are found in footnote definitions.
3806 Definitions either appear as Org data or as a secondary string
3807 for inlined footnotes. Unreferenced definitions are ignored."
3808 (let ((n 0) labels alist)
3809 (org-export--footnote-reference-map
3810 (lambda (f)
3811 ;; Collect footnote number, label and definition.
3812 (let ((l (org-element-property :label f)))
3813 (unless (and l (member l labels))
3814 (cl-incf n)
3815 (push (list n l (org-export-get-footnote-definition f info)) alist))
3816 (when l (push l labels))))
3817 (or data (plist-get info :parse-tree)) info body-first)
3818 (nreverse alist)))
3820 (defun org-export-footnote-first-reference-p
3821 (footnote-reference info &optional data body-first)
3822 "Non-nil when a footnote reference is the first one for its label.
3824 FOOTNOTE-REFERENCE is the footnote reference being considered.
3825 INFO is a plist containing current export state.
3827 Search is done throughout the whole parse tree, or DATA when
3828 non-nil.
3830 By default, as soon as a new footnote reference is encountered,
3831 other references are searched within its definition. However, if
3832 BODY-FIRST is non-nil, this step is delayed after the whole tree
3833 is checked. This alters results when references are found in
3834 footnote definitions."
3835 (let ((label (org-element-property :label footnote-reference)))
3836 ;; Anonymous footnotes are always a first reference.
3837 (or (not label)
3838 (catch 'exit
3839 (org-export--footnote-reference-map
3840 (lambda (f)
3841 (let ((l (org-element-property :label f)))
3842 (when (and l label (string= label l))
3843 (throw 'exit (eq footnote-reference f)))))
3844 (or data (plist-get info :parse-tree)) info body-first)))))
3846 (defun org-export-get-footnote-number (footnote info &optional data body-first)
3847 "Return number associated to a footnote.
3849 FOOTNOTE is either a footnote reference or a footnote definition.
3850 INFO is the plist containing export state.
3852 Number is unique throughout the whole parse tree, or DATA, when
3853 non-nil.
3855 By default, as soon as a new footnote reference is encountered,
3856 counting process moves into its definition. However, if
3857 BODY-FIRST is non-nil, this step is delayed until the end of the
3858 process, leading to a different order when footnotes are nested."
3859 (let ((count 0)
3860 (seen)
3861 (label (org-element-property :label footnote)))
3862 (catch 'exit
3863 (org-export--footnote-reference-map
3864 (lambda (f)
3865 (let ((l (org-element-property :label f)))
3866 (cond
3867 ;; Anonymous footnote match: return number.
3868 ((and (not l) (not label) (eq footnote f)) (throw 'exit (1+ count)))
3869 ;; Labels match: return number.
3870 ((and label l (string= label l)) (throw 'exit (1+ count)))
3871 ;; Otherwise store label and increase counter if label
3872 ;; wasn't encountered yet.
3873 ((not l) (cl-incf count))
3874 ((not (member l seen)) (push l seen) (cl-incf count)))))
3875 (or data (plist-get info :parse-tree)) info body-first))))
3878 ;;;; For Headlines
3880 ;; `org-export-get-relative-level' is a shortcut to get headline
3881 ;; level, relatively to the lower headline level in the parsed tree.
3883 ;; `org-export-get-headline-number' returns the section number of an
3884 ;; headline, while `org-export-number-to-roman' allows it to be
3885 ;; converted to roman numbers. With an optional argument,
3886 ;; `org-export-get-headline-number' returns a number to unnumbered
3887 ;; headlines (used for internal id).
3889 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
3890 ;; `org-export-last-sibling-p' are three useful predicates when it
3891 ;; comes to fulfill the `:headline-levels' property.
3893 ;; `org-export-get-tags', `org-export-get-category' and
3894 ;; `org-export-get-node-property' extract useful information from an
3895 ;; headline or a parent headline. They all handle inheritance.
3897 ;; `org-export-get-alt-title' tries to retrieve an alternative title,
3898 ;; as a secondary string, suitable for table of contents. It falls
3899 ;; back onto default title.
3901 (defun org-export-get-relative-level (headline info)
3902 "Return HEADLINE relative level within current parsed tree.
3903 INFO is a plist holding contextual information."
3904 (+ (org-element-property :level headline)
3905 (or (plist-get info :headline-offset) 0)))
3907 (defun org-export-low-level-p (headline info)
3908 "Non-nil when HEADLINE is considered as low level.
3910 INFO is a plist used as a communication channel.
3912 A low level headlines has a relative level greater than
3913 `:headline-levels' property value.
3915 Return value is the difference between HEADLINE relative level
3916 and the last level being considered as high enough, or nil."
3917 (let ((limit (plist-get info :headline-levels)))
3918 (when (wholenump limit)
3919 (let ((level (org-export-get-relative-level headline info)))
3920 (and (> level limit) (- level limit))))))
3922 (defun org-export-get-headline-number (headline info)
3923 "Return numbered HEADLINE numbering as a list of numbers.
3924 INFO is a plist holding contextual information."
3925 (and (org-export-numbered-headline-p headline info)
3926 (cdr (assq headline (plist-get info :headline-numbering)))))
3928 (defun org-export-numbered-headline-p (headline info)
3929 "Return a non-nil value if HEADLINE element should be numbered.
3930 INFO is a plist used as a communication channel."
3931 (unless (cl-some
3932 (lambda (head) (org-not-nil (org-element-property :UNNUMBERED head)))
3933 (org-element-lineage headline nil t))
3934 (let ((sec-num (plist-get info :section-numbers))
3935 (level (org-export-get-relative-level headline info)))
3936 (if (wholenump sec-num) (<= level sec-num) sec-num))))
3938 (defun org-export-number-to-roman (n)
3939 "Convert integer N into a roman numeral."
3940 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
3941 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
3942 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
3943 ( 1 . "I")))
3944 (res ""))
3945 (if (<= n 0)
3946 (number-to-string n)
3947 (while roman
3948 (if (>= n (caar roman))
3949 (setq n (- n (caar roman))
3950 res (concat res (cdar roman)))
3951 (pop roman)))
3952 res)))
3954 (defun org-export-get-tags (element info &optional tags inherited)
3955 "Return list of tags associated to ELEMENT.
3957 ELEMENT has either an `headline' or an `inlinetask' type. INFO
3958 is a plist used as a communication channel.
3960 When non-nil, optional argument TAGS should be a list of strings.
3961 Any tag belonging to this list will also be removed.
3963 When optional argument INHERITED is non-nil, tags can also be
3964 inherited from parent headlines and FILETAGS keywords."
3965 (cl-remove-if
3966 (lambda (tag) (member tag tags))
3967 (if (not inherited) (org-element-property :tags element)
3968 ;; Build complete list of inherited tags.
3969 (let ((current-tag-list (org-element-property :tags element)))
3970 (dolist (parent (org-element-lineage element))
3971 (dolist (tag (org-element-property :tags parent))
3972 (when (and (memq (org-element-type parent) '(headline inlinetask))
3973 (not (member tag current-tag-list)))
3974 (push tag current-tag-list))))
3975 ;; Add FILETAGS keywords and return results.
3976 (org-uniquify (append (plist-get info :filetags) current-tag-list))))))
3978 (defun org-export-get-node-property (property blob &optional inherited)
3979 "Return node PROPERTY value for BLOB.
3981 PROPERTY is an upcase symbol (i.e. `:COOKIE_DATA'). BLOB is an
3982 element or object.
3984 If optional argument INHERITED is non-nil, the value can be
3985 inherited from a parent headline.
3987 Return value is a string or nil."
3988 (let ((headline (if (eq (org-element-type blob) 'headline) blob
3989 (org-export-get-parent-headline blob))))
3990 (if (not inherited) (org-element-property property blob)
3991 (let ((parent headline))
3992 (catch 'found
3993 (while parent
3994 (when (plist-member (nth 1 parent) property)
3995 (throw 'found (org-element-property property parent)))
3996 (setq parent (org-element-property :parent parent))))))))
3998 (defun org-export-get-category (blob info)
3999 "Return category for element or object BLOB.
4001 INFO is a plist used as a communication channel.
4003 CATEGORY is automatically inherited from a parent headline, from
4004 #+CATEGORY: keyword or created out of original file name. If all
4005 fail, the fall-back value is \"???\"."
4006 (or (org-export-get-node-property :CATEGORY blob t)
4007 (org-element-map (plist-get info :parse-tree) 'keyword
4008 (lambda (kwd)
4009 (when (equal (org-element-property :key kwd) "CATEGORY")
4010 (org-element-property :value kwd)))
4011 info 'first-match)
4012 (let ((file (plist-get info :input-file)))
4013 (and file (file-name-sans-extension (file-name-nondirectory file))))
4014 "???"))
4016 (defun org-export-get-alt-title (headline _)
4017 "Return alternative title for HEADLINE, as a secondary string.
4018 If no optional title is defined, fall-back to the regular title."
4019 (let ((alt (org-element-property :ALT_TITLE headline)))
4020 (if alt (org-element-parse-secondary-string
4021 alt (org-element-restriction 'headline) headline)
4022 (org-element-property :title headline))))
4024 (defun org-export-first-sibling-p (blob info)
4025 "Non-nil when BLOB is the first sibling in its parent.
4026 BLOB is an element or an object. If BLOB is a headline, non-nil
4027 means it is the first sibling in the sub-tree. INFO is a plist
4028 used as a communication channel."
4029 (memq (org-element-type (org-export-get-previous-element blob info))
4030 '(nil section)))
4032 (defun org-export-last-sibling-p (blob info)
4033 "Non-nil when BLOB is the last sibling in its parent.
4034 BLOB is an element or an object. INFO is a plist used as
4035 a communication channel."
4036 (not (org-export-get-next-element blob info)))
4039 ;;;; For Keywords
4041 ;; `org-export-get-date' returns a date appropriate for the document
4042 ;; to about to be exported. In particular, it takes care of
4043 ;; `org-export-date-timestamp-format'.
4045 (defun org-export-get-date (info &optional fmt)
4046 "Return date value for the current document.
4048 INFO is a plist used as a communication channel. FMT, when
4049 non-nil, is a time format string that will be applied on the date
4050 if it consists in a single timestamp object. It defaults to
4051 `org-export-date-timestamp-format' when nil.
4053 A proper date can be a secondary string, a string or nil. It is
4054 meant to be translated with `org-export-data' or alike."
4055 (let ((date (plist-get info :date))
4056 (fmt (or fmt org-export-date-timestamp-format)))
4057 (cond ((not date) nil)
4058 ((and fmt
4059 (not (cdr date))
4060 (eq (org-element-type (car date)) 'timestamp))
4061 (org-timestamp-format (car date) fmt))
4062 (t date))))
4065 ;;;; For Links
4067 ;; `org-export-custom-protocol-maybe' handles custom protocol defined
4068 ;; in `org-link-parameters'.
4070 ;; `org-export-get-coderef-format' returns an appropriate format
4071 ;; string for coderefs.
4073 ;; `org-export-inline-image-p' returns a non-nil value when the link
4074 ;; provided should be considered as an inline image.
4076 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
4077 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
4078 ;; returns an appropriate unique identifier.
4080 ;; `org-export-resolve-id-link' returns the first headline with
4081 ;; specified id or custom-id in parse tree, the path to the external
4082 ;; file with the id.
4084 ;; `org-export-resolve-coderef' associates a reference to a line
4085 ;; number in the element it belongs, or returns the reference itself
4086 ;; when the element isn't numbered.
4088 ;; `org-export-file-uri' expands a filename as stored in :path value
4089 ;; of a "file" link into a file URI.
4091 ;; Broken links raise a `org-link-broken' error, which is caught by
4092 ;; `org-export-data' for further processing, depending on
4093 ;; `org-export-with-broken-links' value.
4095 (org-define-error 'org-link-broken "Unable to resolve link; aborting")
4097 (defun org-export-custom-protocol-maybe (link desc backend)
4098 "Try exporting LINK with a dedicated function.
4100 DESC is its description, as a string, or nil. BACKEND is the
4101 back-end used for export, as a symbol.
4103 Return output as a string, or nil if no protocol handles LINK.
4105 A custom protocol has precedence over regular back-end export.
4106 The function ignores links with an implicit type (e.g.,
4107 \"custom-id\")."
4108 (let ((type (org-element-property :type link)))
4109 (unless (or (member type '("coderef" "custom-id" "fuzzy" "radio"))
4110 (not backend))
4111 (let ((protocol (org-link-get-parameter type :export)))
4112 (and (functionp protocol)
4113 (funcall protocol
4114 (org-link-unescape (org-element-property :path link))
4115 desc
4116 backend))))))
4118 (defun org-export-get-coderef-format (path desc)
4119 "Return format string for code reference link.
4120 PATH is the link path. DESC is its description."
4121 (save-match-data
4122 (cond ((not desc) "%s")
4123 ((string-match (regexp-quote (concat "(" path ")")) desc)
4124 (replace-match "%s" t t desc))
4125 (t desc))))
4127 (defun org-export-inline-image-p (link &optional rules)
4128 "Non-nil if LINK object points to an inline image.
4130 Optional argument is a set of RULES defining inline images. It
4131 is an alist where associations have the following shape:
4133 (TYPE . REGEXP)
4135 Applying a rule means apply REGEXP against LINK's path when its
4136 type is TYPE. The function will return a non-nil value if any of
4137 the provided rules is non-nil. The default rule is
4138 `org-export-default-inline-image-rule'.
4140 This only applies to links without a description."
4141 (and (not (org-element-contents link))
4142 (let ((case-fold-search t))
4143 (catch 'exit
4144 (dolist (rule (or rules org-export-default-inline-image-rule))
4145 (and (string= (org-element-property :type link) (car rule))
4146 (string-match-p (cdr rule)
4147 (org-element-property :path link))
4148 (throw 'exit t)))))))
4150 (defun org-export-resolve-coderef (ref info)
4151 "Resolve a code reference REF.
4153 INFO is a plist used as a communication channel.
4155 Return associated line number in source code, or REF itself,
4156 depending on src-block or example element's switches. Throw an
4157 error if no block contains REF."
4158 (or (org-element-map (plist-get info :parse-tree) '(example-block src-block)
4159 (lambda (el)
4160 (with-temp-buffer
4161 (insert (org-trim (org-element-property :value el)))
4162 (let* ((label-fmt (or (org-element-property :label-fmt el)
4163 org-coderef-label-format))
4164 (ref-re (org-src-coderef-regexp label-fmt ref)))
4165 ;; Element containing REF is found. Resolve it to
4166 ;; either a label or a line number, as needed.
4167 (when (re-search-backward ref-re nil t)
4168 (if (org-element-property :use-labels el) ref
4169 (+ (or (org-export-get-loc el info) 0)
4170 (line-number-at-pos)))))))
4171 info 'first-match)
4172 (signal 'org-link-broken (list ref))))
4174 (defun org-export-search-cells (datum)
4175 "List search cells for element or object DATUM.
4177 A search cell follows the pattern (TYPE . SEARCH) where
4179 TYPE is a symbol among `headline', `custom-id', `target' and
4180 `other'.
4182 SEARCH is the string a link is expected to match. More
4183 accurately, it is
4185 - headline's title, as a list of strings, if TYPE is
4186 `headline'.
4188 - CUSTOM_ID value, as a string, if TYPE is `custom-id'.
4190 - target's or radio-target's name as a list of strings if
4191 TYPE is `target'.
4193 - NAME affiliated keyword is TYPE is `other'.
4195 A search cell is the internal representation of a fuzzy link. It
4196 ignores white spaces and statistics cookies, if applicable."
4197 (pcase (org-element-type datum)
4198 (`headline
4199 (let ((title (split-string
4200 (replace-regexp-in-string
4201 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]" ""
4202 (org-element-property :raw-value datum)))))
4203 (delq nil
4204 (list
4205 (cons 'headline title)
4206 (cons 'other title)
4207 (let ((custom-id (org-element-property :custom-id datum)))
4208 (and custom-id (cons 'custom-id custom-id)))))))
4209 (`target
4210 (list (cons 'target (split-string (org-element-property :value datum)))))
4211 ((and (let name (org-element-property :name datum))
4212 (guard name))
4213 (list (cons 'other (split-string name))))
4214 (_ nil)))
4216 (defun org-export-string-to-search-cell (s)
4217 "Return search cells associated to string S.
4218 S is either the path of a fuzzy link or a search option, i.e., it
4219 tries to match either a headline (through custom ID or title),
4220 a target or a named element."
4221 (pcase (string-to-char s)
4222 (?* (list (cons 'headline (split-string (substring s 1)))))
4223 (?# (list (cons 'custom-id (substring s 1))))
4224 ((let search (split-string s))
4225 (list (cons 'target search) (cons 'other search)))))
4227 (defun org-export-match-search-cell-p (datum cells)
4228 "Non-nil when DATUM matches search cells CELLS.
4229 DATUM is an element or object. CELLS is a list of search cells,
4230 as returned by `org-export-search-cells'."
4231 (let ((targets (org-export-search-cells datum)))
4232 (and targets (cl-some (lambda (cell) (member cell targets)) cells))))
4234 (defun org-export-resolve-fuzzy-link (link info)
4235 "Return LINK destination.
4237 INFO is a plist holding contextual information.
4239 Return value can be an object or an element:
4241 - If LINK path matches a target object (i.e. <<path>>) return it.
4243 - If LINK path exactly matches the name affiliated keyword
4244 (i.e. #+NAME: path) of an element, return that element.
4246 - If LINK path exactly matches any headline name, return that
4247 element.
4249 - Otherwise, throw an error.
4251 Assume LINK type is \"fuzzy\". White spaces are not
4252 significant."
4253 (let* ((search-cells (org-export-string-to-search-cell
4254 (org-link-unescape (org-element-property :path link))))
4255 (link-cache
4256 (or (plist-get info :resolve-fuzzy-link-cache)
4257 (plist-get (plist-put info
4258 :resolve-fuzzy-link-cache
4259 (make-hash-table :test #'equal))
4260 :resolve-fuzzy-link-cache)))
4261 (cached (gethash search-cells link-cache 'not-found)))
4262 (if (not (eq cached 'not-found)) cached
4263 (let ((matches
4264 (org-element-map (plist-get info :parse-tree)
4265 (cons 'target org-element-all-elements)
4266 (lambda (datum)
4267 (and (org-export-match-search-cell-p datum search-cells)
4268 datum)))))
4269 (unless matches
4270 (signal 'org-link-broken (list (org-element-property :path link))))
4271 (puthash
4272 search-cells
4273 ;; There can be multiple matches for un-typed searches, i.e.,
4274 ;; for searches not starting with # or *. In this case,
4275 ;; prioritize targets and names over headline titles.
4276 ;; Matching both a name and a target is not valid, and
4277 ;; therefore undefined.
4278 (or (cl-some (lambda (datum)
4279 (and (not (eq (org-element-type datum) 'headline))
4280 datum))
4281 matches)
4282 (car matches))
4283 link-cache)))))
4285 (defun org-export-resolve-id-link (link info)
4286 "Return headline referenced as LINK destination.
4288 INFO is a plist used as a communication channel.
4290 Return value can be the headline element matched in current parse
4291 tree or a file name. Assume LINK type is either \"id\" or
4292 \"custom-id\". Throw an error if no match is found."
4293 (let ((id (org-element-property :path link)))
4294 ;; First check if id is within the current parse tree.
4295 (or (org-element-map (plist-get info :parse-tree) 'headline
4296 (lambda (headline)
4297 (when (or (equal (org-element-property :ID headline) id)
4298 (equal (org-element-property :CUSTOM_ID headline) id))
4299 headline))
4300 info 'first-match)
4301 ;; Otherwise, look for external files.
4302 (cdr (assoc id (plist-get info :id-alist)))
4303 (signal 'org-link-broken (list id)))))
4305 (defun org-export-resolve-radio-link (link info)
4306 "Return radio-target object referenced as LINK destination.
4308 INFO is a plist used as a communication channel.
4310 Return value can be a radio-target object or nil. Assume LINK
4311 has type \"radio\"."
4312 (let ((path (replace-regexp-in-string
4313 "[ \r\t\n]+" " " (org-element-property :path link))))
4314 (org-element-map (plist-get info :parse-tree) 'radio-target
4315 (lambda (radio)
4316 (and (eq (compare-strings
4317 (replace-regexp-in-string
4318 "[ \r\t\n]+" " " (org-element-property :value radio))
4319 nil nil path nil nil t)
4321 radio))
4322 info 'first-match)))
4324 (defun org-export-file-uri (filename)
4325 "Return file URI associated to FILENAME."
4326 (cond ((string-prefix-p "//" filename) (concat "file:" filename))
4327 ((not (file-name-absolute-p filename)) filename)
4328 ((org-file-remote-p filename) (concat "file:/" filename))
4330 (let ((fullname (expand-file-name filename)))
4331 (concat (if (string-prefix-p "/" fullname) "file://" "file:///")
4332 fullname)))))
4334 ;;;; For References
4336 ;; `org-export-get-reference' associate a unique reference for any
4337 ;; object or element. It uses `org-export-new-reference' and
4338 ;; `org-export-format-reference' to, respectively, generate new
4339 ;; internal references and turn them into a string suitable for
4340 ;; output.
4342 ;; `org-export-get-ordinal' associates a sequence number to any object
4343 ;; or element.
4345 (defun org-export-new-reference (references)
4346 "Return a unique reference, among REFERENCES.
4347 REFERENCES is an alist whose values are in-use references, as
4348 numbers. Returns a number, which is the internal representation
4349 of a reference. See also `org-export-format-reference'."
4350 ;; Generate random 7 digits hexadecimal numbers. Collisions
4351 ;; increase exponentially with the numbers of references. However,
4352 ;; the odds for encountering at least one collision with 1000 active
4353 ;; references in the same document are roughly 0.2%, so this
4354 ;; shouldn't be the bottleneck.
4355 (let ((new (random #x10000000)))
4356 (while (rassq new references) (setq new (random #x10000000)))
4357 new))
4359 (defun org-export-format-reference (reference)
4360 "Format REFERENCE into a string.
4361 REFERENCE is a number representing a reference, as returned by
4362 `org-export-new-reference', which see."
4363 (format "org%07x" reference))
4365 (defun org-export-get-reference (datum info)
4366 "Return a unique reference for DATUM, as a string.
4368 DATUM is either an element or an object. INFO is the current
4369 export state, as a plist.
4371 This function checks `:crossrefs' property in INFO for search
4372 cells matching DATUM before creating a new reference. Returned
4373 reference consists of alphanumeric characters only."
4374 (let ((cache (plist-get info :internal-references)))
4375 (or (car (rassq datum cache))
4376 (let* ((crossrefs (plist-get info :crossrefs))
4377 (cells (org-export-search-cells datum))
4378 ;; Preserve any pre-existing association between
4379 ;; a search cell and a reference, i.e., when some
4380 ;; previously published document referenced a location
4381 ;; within current file (see
4382 ;; `org-publish-resolve-external-link').
4384 ;; However, there is no guarantee that search cells are
4385 ;; unique, e.g., there might be duplicate custom ID or
4386 ;; two headings with the same title in the file.
4388 ;; As a consequence, before re-using any reference to
4389 ;; an element or object, we check that it doesn't refer
4390 ;; to a previous element or object.
4391 (new (or (cl-some
4392 (lambda (cell)
4393 (let ((stored (cdr (assoc cell crossrefs))))
4394 (when stored
4395 (let ((old (org-export-format-reference stored)))
4396 (and (not (assoc old cache)) stored)))))
4397 cells)
4398 (org-export-new-reference cache)))
4399 (reference-string (org-export-format-reference new)))
4400 ;; Cache contains both data already associated to
4401 ;; a reference and in-use internal references, so as to make
4402 ;; unique references.
4403 (dolist (cell cells) (push (cons cell new) cache))
4404 ;; Retain a direct association between reference string and
4405 ;; DATUM since (1) not every object or element can be given
4406 ;; a search cell (2) it permits quick lookup.
4407 (push (cons reference-string datum) cache)
4408 (plist-put info :internal-references cache)
4409 reference-string))))
4411 (defun org-export-get-ordinal (element info &optional types predicate)
4412 "Return ordinal number of an element or object.
4414 ELEMENT is the element or object considered. INFO is the plist
4415 used as a communication channel.
4417 Optional argument TYPES, when non-nil, is a list of element or
4418 object types, as symbols, that should also be counted in.
4419 Otherwise, only provided element's type is considered.
4421 Optional argument PREDICATE is a function returning a non-nil
4422 value if the current element or object should be counted in. It
4423 accepts two arguments: the element or object being considered and
4424 the plist used as a communication channel. This allows counting
4425 only a certain type of object (i.e. inline images).
4427 Return value is a list of numbers if ELEMENT is a headline or an
4428 item. It is nil for keywords. It represents the footnote number
4429 for footnote definitions and footnote references. If ELEMENT is
4430 a target, return the same value as if ELEMENT was the closest
4431 table, item or headline containing the target. In any other
4432 case, return the sequence number of ELEMENT among elements or
4433 objects of the same type."
4434 ;; Ordinal of a target object refer to the ordinal of the closest
4435 ;; table, item, or headline containing the object.
4436 (when (eq (org-element-type element) 'target)
4437 (setq element
4438 (org-element-lineage
4439 element
4440 '(footnote-definition footnote-reference headline item table))))
4441 (cl-case (org-element-type element)
4442 ;; Special case 1: A headline returns its number as a list.
4443 (headline (org-export-get-headline-number element info))
4444 ;; Special case 2: An item returns its number as a list.
4445 (item (let ((struct (org-element-property :structure element)))
4446 (org-list-get-item-number
4447 (org-element-property :begin element)
4448 struct
4449 (org-list-prevs-alist struct)
4450 (org-list-parents-alist struct))))
4451 ((footnote-definition footnote-reference)
4452 (org-export-get-footnote-number element info))
4453 (otherwise
4454 (let ((counter 0))
4455 ;; Increment counter until ELEMENT is found again.
4456 (org-element-map (plist-get info :parse-tree)
4457 (or types (org-element-type element))
4458 (lambda (el)
4459 (cond
4460 ((eq element el) (1+ counter))
4461 ((not predicate) (cl-incf counter) nil)
4462 ((funcall predicate el info) (cl-incf counter) nil)))
4463 info 'first-match)))))
4466 ;;;; For Src-Blocks
4468 ;; `org-export-get-loc' counts number of code lines accumulated in
4469 ;; src-block or example-block elements with a "+n" switch until
4470 ;; a given element, excluded. Note: "-n" switches reset that count.
4472 ;; `org-export-unravel-code' extracts source code (along with a code
4473 ;; references alist) from an `element-block' or `src-block' type
4474 ;; element.
4476 ;; `org-export-format-code' applies a formatting function to each line
4477 ;; of code, providing relative line number and code reference when
4478 ;; appropriate. Since it doesn't access the original element from
4479 ;; which the source code is coming, it expects from the code calling
4480 ;; it to know if lines should be numbered and if code references
4481 ;; should appear.
4483 ;; Eventually, `org-export-format-code-default' is a higher-level
4484 ;; function (it makes use of the two previous functions) which handles
4485 ;; line numbering and code references inclusion, and returns source
4486 ;; code in a format suitable for plain text or verbatim output.
4488 (defun org-export-get-loc (element info)
4489 "Return count of lines of code before ELEMENT.
4491 ELEMENT is an example-block or src-block element. INFO is the
4492 plist used as a communication channel.
4494 Count includes every line of code in example-block or src-block
4495 with a \"+n\" or \"-n\" switch before block. Return nil if
4496 ELEMENT doesn't allow line numbering."
4497 (pcase (org-element-property :number-lines element)
4498 (`(new . ,n) n)
4499 (`(continued . ,n)
4500 (let ((loc 0))
4501 (org-element-map (plist-get info :parse-tree) '(src-block example-block)
4502 (lambda (el)
4503 ;; ELEMENT is reached: Quit loop and return locs.
4504 (if (eq el element) (+ loc n)
4505 ;; Only count lines from src-block and example-block
4506 ;; elements with a "+n" or "-n" switch.
4507 (let ((linum (org-element-property :number-lines el)))
4508 (when linum
4509 (let ((lines (org-count-lines
4510 (org-trim (org-element-property :value el)))))
4511 ;; Accumulate locs or reset them.
4512 (pcase linum
4513 (`(new . ,n) (setq loc (+ n lines)))
4514 (`(continued . ,n) (cl-incf loc (+ n lines)))))))
4515 nil)) ;Return nil to stay in the loop.
4516 info 'first-match)))))
4518 (defun org-export-unravel-code (element)
4519 "Clean source code and extract references out of it.
4521 ELEMENT has either a `src-block' an `example-block' type.
4523 Return a cons cell whose CAR is the source code, cleaned from any
4524 reference, protective commas and spurious indentation, and CDR is
4525 an alist between relative line number (integer) and name of code
4526 reference on that line (string)."
4527 (let* ((line 0) refs
4528 (value (org-element-property :value element))
4529 ;; Get code and clean it. Remove blank lines at its
4530 ;; beginning and end.
4531 (code (replace-regexp-in-string
4532 "\\`\\([ \t]*\n\\)+" ""
4533 (replace-regexp-in-string
4534 "\\([ \t]*\n\\)*[ \t]*\\'" "\n"
4535 (if (or org-src-preserve-indentation
4536 (org-element-property :preserve-indent element))
4537 value
4538 (org-remove-indentation value)))))
4539 ;; Build a regexp matching a loc with a reference.
4540 (ref-re (org-src-coderef-regexp (org-src-coderef-format element))))
4541 ;; Return value.
4542 (cons
4543 ;; Code with references removed.
4544 (org-element-normalize-string
4545 (mapconcat
4546 (lambda (loc)
4547 (cl-incf line)
4548 (if (not (string-match ref-re loc)) loc
4549 ;; Ref line: remove ref, and signal its position in REFS.
4550 (push (cons line (match-string 3 loc)) refs)
4551 (replace-match "" nil nil loc 1)))
4552 (org-split-string code "\n") "\n"))
4553 ;; Reference alist.
4554 refs)))
4556 (defun org-export-format-code (code fun &optional num-lines ref-alist)
4557 "Format CODE by applying FUN line-wise and return it.
4559 CODE is a string representing the code to format. FUN is
4560 a function. It must accept three arguments: a line of
4561 code (string), the current line number (integer) or nil and the
4562 reference associated to the current line (string) or nil.
4564 Optional argument NUM-LINES can be an integer representing the
4565 number of code lines accumulated until the current code. Line
4566 numbers passed to FUN will take it into account. If it is nil,
4567 FUN's second argument will always be nil. This number can be
4568 obtained with `org-export-get-loc' function.
4570 Optional argument REF-ALIST can be an alist between relative line
4571 number (i.e. ignoring NUM-LINES) and the name of the code
4572 reference on it. If it is nil, FUN's third argument will always
4573 be nil. It can be obtained through the use of
4574 `org-export-unravel-code' function."
4575 (let ((--locs (org-split-string code "\n"))
4576 (--line 0))
4577 (org-element-normalize-string
4578 (mapconcat
4579 (lambda (--loc)
4580 (cl-incf --line)
4581 (let ((--ref (cdr (assq --line ref-alist))))
4582 (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
4583 --locs "\n"))))
4585 (defun org-export-format-code-default (element info)
4586 "Return source code from ELEMENT, formatted in a standard way.
4588 ELEMENT is either a `src-block' or `example-block' element. INFO
4589 is a plist used as a communication channel.
4591 This function takes care of line numbering and code references
4592 inclusion. Line numbers, when applicable, appear at the
4593 beginning of the line, separated from the code by two white
4594 spaces. Code references, on the other hand, appear flushed to
4595 the right, separated by six white spaces from the widest line of
4596 code."
4597 ;; Extract code and references.
4598 (let* ((code-info (org-export-unravel-code element))
4599 (code (car code-info))
4600 (code-lines (org-split-string code "\n")))
4601 (if (null code-lines) ""
4602 (let* ((refs (and (org-element-property :retain-labels element)
4603 (cdr code-info)))
4604 ;; Handle line numbering.
4605 (num-start (org-export-get-loc element info))
4606 (num-fmt
4607 (and num-start
4608 (format "%%%ds "
4609 (length (number-to-string
4610 (+ (length code-lines) num-start))))))
4611 ;; Prepare references display, if required. Any reference
4612 ;; should start six columns after the widest line of code,
4613 ;; wrapped with parenthesis.
4614 (max-width
4615 (+ (apply 'max (mapcar 'length code-lines))
4616 (if (not num-start) 0 (length (format num-fmt num-start))))))
4617 (org-export-format-code
4618 code
4619 (lambda (loc line-num ref)
4620 (let ((number-str (and num-fmt (format num-fmt line-num))))
4621 (concat
4622 number-str
4624 (and ref
4625 (concat (make-string
4626 (- (+ 6 max-width)
4627 (+ (length loc) (length number-str))) ? )
4628 (format "(%s)" ref))))))
4629 num-start refs)))))
4632 ;;;; For Tables
4634 ;; `org-export-table-has-special-column-p' and and
4635 ;; `org-export-table-row-is-special-p' are predicates used to look for
4636 ;; meta-information about the table structure.
4638 ;; `org-table-has-header-p' tells when the rows before the first rule
4639 ;; should be considered as table's header.
4641 ;; `org-export-table-cell-width', `org-export-table-cell-alignment'
4642 ;; and `org-export-table-cell-borders' extract information from
4643 ;; a table-cell element.
4645 ;; `org-export-table-dimensions' gives the number on rows and columns
4646 ;; in the table, ignoring horizontal rules and special columns.
4647 ;; `org-export-table-cell-address', given a table-cell object, returns
4648 ;; the absolute address of a cell. On the other hand,
4649 ;; `org-export-get-table-cell-at' does the contrary.
4651 ;; `org-export-table-cell-starts-colgroup-p',
4652 ;; `org-export-table-cell-ends-colgroup-p',
4653 ;; `org-export-table-row-starts-rowgroup-p',
4654 ;; `org-export-table-row-ends-rowgroup-p',
4655 ;; `org-export-table-row-starts-header-p',
4656 ;; `org-export-table-row-ends-header-p' and
4657 ;; `org-export-table-row-in-header-p' indicate position of current row
4658 ;; or cell within the table.
4660 (defun org-export-table-has-special-column-p (table)
4661 "Non-nil when TABLE has a special column.
4662 All special columns will be ignored during export."
4663 ;; The table has a special column when every first cell of every row
4664 ;; has an empty value or contains a symbol among "/", "#", "!", "$",
4665 ;; "*" "_" and "^". Though, do not consider a first row containing
4666 ;; only empty cells as special.
4667 (let ((special-column-p 'empty))
4668 (catch 'exit
4669 (dolist (row (org-element-contents table))
4670 (when (eq (org-element-property :type row) 'standard)
4671 (let ((value (org-element-contents
4672 (car (org-element-contents row)))))
4673 (cond ((member value '(("/") ("#") ("!") ("$") ("*") ("_") ("^")))
4674 (setq special-column-p 'special))
4675 ((not value))
4676 (t (throw 'exit nil))))))
4677 (eq special-column-p 'special))))
4679 (defun org-export-table-has-header-p (table info)
4680 "Non-nil when TABLE has a header.
4682 INFO is a plist used as a communication channel.
4684 A table has a header when it contains at least two row groups."
4685 (let ((cache (or (plist-get info :table-header-cache)
4686 (plist-get (setq info
4687 (plist-put info :table-header-cache
4688 (make-hash-table :test 'eq)))
4689 :table-header-cache))))
4690 (or (gethash table cache)
4691 (let ((rowgroup 1) row-flag)
4692 (puthash
4693 table
4694 (org-element-map table 'table-row
4695 (lambda (row)
4696 (cond
4697 ((> rowgroup 1) t)
4698 ((and row-flag (eq (org-element-property :type row) 'rule))
4699 (cl-incf rowgroup) (setq row-flag nil))
4700 ((and (not row-flag) (eq (org-element-property :type row)
4701 'standard))
4702 (setq row-flag t) nil)))
4703 info 'first-match)
4704 cache)))))
4706 (defun org-export-table-row-is-special-p (table-row _)
4707 "Non-nil if TABLE-ROW is considered special.
4708 All special rows will be ignored during export."
4709 (when (eq (org-element-property :type table-row) 'standard)
4710 (let ((first-cell (org-element-contents
4711 (car (org-element-contents table-row)))))
4712 ;; A row is special either when...
4714 ;; ... it starts with a field only containing "/",
4715 (equal first-cell '("/"))
4716 ;; ... the table contains a special column and the row start
4717 ;; with a marking character among, "^", "_", "$" or "!",
4718 (and (org-export-table-has-special-column-p
4719 (org-export-get-parent table-row))
4720 (member first-cell '(("^") ("_") ("$") ("!"))))
4721 ;; ... it contains only alignment cookies and empty cells.
4722 (let ((special-row-p 'empty))
4723 (catch 'exit
4724 (dolist (cell (org-element-contents table-row))
4725 (let ((value (org-element-contents cell)))
4726 ;; Since VALUE is a secondary string, the following
4727 ;; checks avoid expanding it with `org-export-data'.
4728 (cond ((not value))
4729 ((and (not (cdr value))
4730 (stringp (car value))
4731 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'"
4732 (car value)))
4733 (setq special-row-p 'cookie))
4734 (t (throw 'exit nil)))))
4735 (eq special-row-p 'cookie)))))))
4737 (defun org-export-table-row-group (table-row info)
4738 "Return TABLE-ROW's group number, as an integer.
4740 INFO is a plist used as the communication channel.
4742 Return value is the group number, as an integer, or nil for
4743 special rows and rows separators. First group is also table's
4744 header."
4745 (let ((cache (or (plist-get info :table-row-group-cache)
4746 (plist-get (setq info
4747 (plist-put info :table-row-group-cache
4748 (make-hash-table :test 'eq)))
4749 :table-row-group-cache))))
4750 (cond ((gethash table-row cache))
4751 ((eq (org-element-property :type table-row) 'rule) nil)
4752 (t (let ((group 0) row-flag)
4753 (org-element-map (org-export-get-parent table-row) 'table-row
4754 (lambda (row)
4755 (if (eq (org-element-property :type row) 'rule)
4756 (setq row-flag nil)
4757 (unless row-flag (cl-incf group) (setq row-flag t)))
4758 (when (eq table-row row) (puthash table-row group cache)))
4759 info 'first-match))))))
4761 (defun org-export-table-cell-width (table-cell info)
4762 "Return TABLE-CELL contents width.
4764 INFO is a plist used as the communication channel.
4766 Return value is the width given by the last width cookie in the
4767 same column as TABLE-CELL, or nil."
4768 (let* ((row (org-export-get-parent table-cell))
4769 (table (org-export-get-parent row))
4770 (cells (org-element-contents row))
4771 (columns (length cells))
4772 (column (- columns (length (memq table-cell cells))))
4773 (cache (or (plist-get info :table-cell-width-cache)
4774 (plist-get (setq info
4775 (plist-put info :table-cell-width-cache
4776 (make-hash-table :test 'eq)))
4777 :table-cell-width-cache)))
4778 (width-vector (or (gethash table cache)
4779 (puthash table (make-vector columns 'empty) cache)))
4780 (value (aref width-vector column)))
4781 (if (not (eq value 'empty)) value
4782 (let (cookie-width)
4783 (dolist (row (org-element-contents table)
4784 (aset width-vector column cookie-width))
4785 (when (org-export-table-row-is-special-p row info)
4786 ;; In a special row, try to find a width cookie at COLUMN.
4787 (let* ((value (org-element-contents
4788 (elt (org-element-contents row) column)))
4789 (cookie (car value)))
4790 ;; The following checks avoid expanding unnecessarily
4791 ;; the cell with `org-export-data'.
4792 (when (and value
4793 (not (cdr value))
4794 (stringp cookie)
4795 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'" cookie)
4796 (match-string 1 cookie))
4797 (setq cookie-width
4798 (string-to-number (match-string 1 cookie)))))))))))
4800 (defun org-export-table-cell-alignment (table-cell info)
4801 "Return TABLE-CELL contents alignment.
4803 INFO is a plist used as the communication channel.
4805 Return alignment as specified by the last alignment cookie in the
4806 same column as TABLE-CELL. If no such cookie is found, a default
4807 alignment value will be deduced from fraction of numbers in the
4808 column (see `org-table-number-fraction' for more information).
4809 Possible values are `left', `right' and `center'."
4810 ;; Load `org-table-number-fraction' and `org-table-number-regexp'.
4811 (require 'org-table)
4812 (let* ((row (org-export-get-parent table-cell))
4813 (table (org-export-get-parent row))
4814 (cells (org-element-contents row))
4815 (columns (length cells))
4816 (column (- columns (length (memq table-cell cells))))
4817 (cache (or (plist-get info :table-cell-alignment-cache)
4818 (plist-get (setq info
4819 (plist-put info :table-cell-alignment-cache
4820 (make-hash-table :test 'eq)))
4821 :table-cell-alignment-cache)))
4822 (align-vector (or (gethash table cache)
4823 (puthash table (make-vector columns nil) cache))))
4824 (or (aref align-vector column)
4825 (let ((number-cells 0)
4826 (total-cells 0)
4827 cookie-align
4828 previous-cell-number-p)
4829 (dolist (row (org-element-contents (org-export-get-parent row)))
4830 (cond
4831 ;; In a special row, try to find an alignment cookie at
4832 ;; COLUMN.
4833 ((org-export-table-row-is-special-p row info)
4834 (let ((value (org-element-contents
4835 (elt (org-element-contents row) column))))
4836 ;; Since VALUE is a secondary string, the following
4837 ;; checks avoid useless expansion through
4838 ;; `org-export-data'.
4839 (when (and value
4840 (not (cdr value))
4841 (stringp (car value))
4842 (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'"
4843 (car value))
4844 (match-string 1 (car value)))
4845 (setq cookie-align (match-string 1 (car value))))))
4846 ;; Ignore table rules.
4847 ((eq (org-element-property :type row) 'rule))
4848 ;; In a standard row, check if cell's contents are
4849 ;; expressing some kind of number. Increase NUMBER-CELLS
4850 ;; accordingly. Though, don't bother if an alignment
4851 ;; cookie has already defined cell's alignment.
4852 ((not cookie-align)
4853 (let ((value (org-export-data
4854 (org-element-contents
4855 (elt (org-element-contents row) column))
4856 info)))
4857 (cl-incf total-cells)
4858 ;; Treat an empty cell as a number if it follows
4859 ;; a number.
4860 (if (not (or (string-match org-table-number-regexp value)
4861 (and (string= value "") previous-cell-number-p)))
4862 (setq previous-cell-number-p nil)
4863 (setq previous-cell-number-p t)
4864 (cl-incf number-cells))))))
4865 ;; Return value. Alignment specified by cookies has
4866 ;; precedence over alignment deduced from cell's contents.
4867 (aset align-vector
4868 column
4869 (cond ((equal cookie-align "l") 'left)
4870 ((equal cookie-align "r") 'right)
4871 ((equal cookie-align "c") 'center)
4872 ((>= (/ (float number-cells) total-cells)
4873 org-table-number-fraction)
4874 'right)
4875 (t 'left)))))))
4877 (defun org-export-table-cell-borders (table-cell info)
4878 "Return TABLE-CELL borders.
4880 INFO is a plist used as a communication channel.
4882 Return value is a list of symbols, or nil. Possible values are:
4883 `top', `bottom', `above', `below', `left' and `right'. Note:
4884 `top' (resp. `bottom') only happen for a cell in the first
4885 row (resp. last row) of the table, ignoring table rules, if any.
4887 Returned borders ignore special rows."
4888 (let* ((row (org-export-get-parent table-cell))
4889 (table (org-export-get-parent-table table-cell))
4890 borders)
4891 ;; Top/above border? TABLE-CELL has a border above when a rule
4892 ;; used to demarcate row groups can be found above. Hence,
4893 ;; finding a rule isn't sufficient to push `above' in BORDERS:
4894 ;; another regular row has to be found above that rule.
4895 (let (rule-flag)
4896 (catch 'exit
4897 ;; Look at every row before the current one.
4898 (dolist (row (cdr (memq row (reverse (org-element-contents table)))))
4899 (cond ((eq (org-element-property :type row) 'rule)
4900 (setq rule-flag t))
4901 ((not (org-export-table-row-is-special-p row info))
4902 (if rule-flag (throw 'exit (push 'above borders))
4903 (throw 'exit nil)))))
4904 ;; No rule above, or rule found starts the table (ignoring any
4905 ;; special row): TABLE-CELL is at the top of the table.
4906 (when rule-flag (push 'above borders))
4907 (push 'top borders)))
4908 ;; Bottom/below border? TABLE-CELL has a border below when next
4909 ;; non-regular row below is a rule.
4910 (let (rule-flag)
4911 (catch 'exit
4912 ;; Look at every row after the current one.
4913 (dolist (row (cdr (memq row (org-element-contents table))))
4914 (cond ((eq (org-element-property :type row) 'rule)
4915 (setq rule-flag t))
4916 ((not (org-export-table-row-is-special-p row info))
4917 (if rule-flag (throw 'exit (push 'below borders))
4918 (throw 'exit nil)))))
4919 ;; No rule below, or rule found ends the table (modulo some
4920 ;; special row): TABLE-CELL is at the bottom of the table.
4921 (when rule-flag (push 'below borders))
4922 (push 'bottom borders)))
4923 ;; Right/left borders? They can only be specified by column
4924 ;; groups. Column groups are defined in a row starting with "/".
4925 ;; Also a column groups row only contains "<", "<>", ">" or blank
4926 ;; cells.
4927 (catch 'exit
4928 (let ((column (let ((cells (org-element-contents row)))
4929 (- (length cells) (length (memq table-cell cells))))))
4930 ;; Table rows are read in reverse order so last column groups
4931 ;; row has precedence over any previous one.
4932 (dolist (row (reverse (org-element-contents table)))
4933 (unless (eq (org-element-property :type row) 'rule)
4934 (when (equal (org-element-contents
4935 (car (org-element-contents row)))
4936 '("/"))
4937 (let ((column-groups
4938 (mapcar
4939 (lambda (cell)
4940 (let ((value (org-element-contents cell)))
4941 (when (member value '(("<") ("<>") (">") nil))
4942 (car value))))
4943 (org-element-contents row))))
4944 ;; There's a left border when previous cell, if
4945 ;; any, ends a group, or current one starts one.
4946 (when (or (and (not (zerop column))
4947 (member (elt column-groups (1- column))
4948 '(">" "<>")))
4949 (member (elt column-groups column) '("<" "<>")))
4950 (push 'left borders))
4951 ;; There's a right border when next cell, if any,
4952 ;; starts a group, or current one ends one.
4953 (when (or (and (/= (1+ column) (length column-groups))
4954 (member (elt column-groups (1+ column))
4955 '("<" "<>")))
4956 (member (elt column-groups column) '(">" "<>")))
4957 (push 'right borders))
4958 (throw 'exit nil)))))))
4959 ;; Return value.
4960 borders))
4962 (defun org-export-table-cell-starts-colgroup-p (table-cell info)
4963 "Non-nil when TABLE-CELL is at the beginning of a column group.
4964 INFO is a plist used as a communication channel."
4965 ;; A cell starts a column group either when it is at the beginning
4966 ;; of a row (or after the special column, if any) or when it has
4967 ;; a left border.
4968 (or (eq (org-element-map (org-export-get-parent table-cell) 'table-cell
4969 'identity info 'first-match)
4970 table-cell)
4971 (memq 'left (org-export-table-cell-borders table-cell info))))
4973 (defun org-export-table-cell-ends-colgroup-p (table-cell info)
4974 "Non-nil when TABLE-CELL is at the end of a column group.
4975 INFO is a plist used as a communication channel."
4976 ;; A cell ends a column group either when it is at the end of a row
4977 ;; or when it has a right border.
4978 (or (eq (car (last (org-element-contents
4979 (org-export-get-parent table-cell))))
4980 table-cell)
4981 (memq 'right (org-export-table-cell-borders table-cell info))))
4983 (defun org-export-table-row-starts-rowgroup-p (table-row info)
4984 "Non-nil when TABLE-ROW is at the beginning of a row group.
4985 INFO is a plist used as a communication channel."
4986 (unless (or (eq (org-element-property :type table-row) 'rule)
4987 (org-export-table-row-is-special-p table-row info))
4988 (let ((borders (org-export-table-cell-borders
4989 (car (org-element-contents table-row)) info)))
4990 (or (memq 'top borders) (memq 'above borders)))))
4992 (defun org-export-table-row-ends-rowgroup-p (table-row info)
4993 "Non-nil when TABLE-ROW is at the end of a row group.
4994 INFO is a plist used as a communication channel."
4995 (unless (or (eq (org-element-property :type table-row) 'rule)
4996 (org-export-table-row-is-special-p table-row info))
4997 (let ((borders (org-export-table-cell-borders
4998 (car (org-element-contents table-row)) info)))
4999 (or (memq 'bottom borders) (memq 'below borders)))))
5001 (defun org-export-table-row-in-header-p (table-row info)
5002 "Non-nil when TABLE-ROW is located within table's header.
5003 INFO is a plist used as a communication channel. Always return
5004 nil for special rows and rows separators."
5005 (and (org-export-table-has-header-p
5006 (org-export-get-parent-table table-row) info)
5007 (eql (org-export-table-row-group table-row info) 1)))
5009 (defun org-export-table-row-starts-header-p (table-row info)
5010 "Non-nil when TABLE-ROW is the first table header's row.
5011 INFO is a plist used as a communication channel."
5012 (and (org-export-table-row-in-header-p table-row info)
5013 (org-export-table-row-starts-rowgroup-p table-row info)))
5015 (defun org-export-table-row-ends-header-p (table-row info)
5016 "Non-nil when TABLE-ROW is the last table header's row.
5017 INFO is a plist used as a communication channel."
5018 (and (org-export-table-row-in-header-p table-row info)
5019 (org-export-table-row-ends-rowgroup-p table-row info)))
5021 (defun org-export-table-row-number (table-row info)
5022 "Return TABLE-ROW number.
5023 INFO is a plist used as a communication channel. Return value is
5024 zero-based and ignores separators. The function returns nil for
5025 special columns and separators."
5026 (when (and (eq (org-element-property :type table-row) 'standard)
5027 (not (org-export-table-row-is-special-p table-row info)))
5028 (let ((number 0))
5029 (org-element-map (org-export-get-parent-table table-row) 'table-row
5030 (lambda (row)
5031 (cond ((eq row table-row) number)
5032 ((eq (org-element-property :type row) 'standard)
5033 (cl-incf number) nil)))
5034 info 'first-match))))
5036 (defun org-export-table-dimensions (table info)
5037 "Return TABLE dimensions.
5039 INFO is a plist used as a communication channel.
5041 Return value is a CONS like (ROWS . COLUMNS) where
5042 ROWS (resp. COLUMNS) is the number of exportable
5043 rows (resp. columns)."
5044 (let (first-row (columns 0) (rows 0))
5045 ;; Set number of rows, and extract first one.
5046 (org-element-map table 'table-row
5047 (lambda (row)
5048 (when (eq (org-element-property :type row) 'standard)
5049 (cl-incf rows)
5050 (unless first-row (setq first-row row)))) info)
5051 ;; Set number of columns.
5052 (org-element-map first-row 'table-cell (lambda (_) (cl-incf columns)) info)
5053 ;; Return value.
5054 (cons rows columns)))
5056 (defun org-export-table-cell-address (table-cell info)
5057 "Return address of a regular TABLE-CELL object.
5059 TABLE-CELL is the cell considered. INFO is a plist used as
5060 a communication channel.
5062 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
5063 zero-based index. Only exportable cells are considered. The
5064 function returns nil for other cells."
5065 (let* ((table-row (org-export-get-parent table-cell))
5066 (row-number (org-export-table-row-number table-row info)))
5067 (when row-number
5068 (cons row-number
5069 (let ((col-count 0))
5070 (org-element-map table-row 'table-cell
5071 (lambda (cell)
5072 (if (eq cell table-cell) col-count (cl-incf col-count) nil))
5073 info 'first-match))))))
5075 (defun org-export-get-table-cell-at (address table info)
5076 "Return regular table-cell object at ADDRESS in TABLE.
5078 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
5079 zero-based index. TABLE is a table type element. INFO is
5080 a plist used as a communication channel.
5082 If no table-cell, among exportable cells, is found at ADDRESS,
5083 return nil."
5084 (let ((column-pos (cdr address)) (column-count 0))
5085 (org-element-map
5086 ;; Row at (car address) or nil.
5087 (let ((row-pos (car address)) (row-count 0))
5088 (org-element-map table 'table-row
5089 (lambda (row)
5090 (cond ((eq (org-element-property :type row) 'rule) nil)
5091 ((= row-count row-pos) row)
5092 (t (cl-incf row-count) nil)))
5093 info 'first-match))
5094 'table-cell
5095 (lambda (cell)
5096 (if (= column-count column-pos) cell
5097 (cl-incf column-count) nil))
5098 info 'first-match)))
5101 ;;;; For Tables Of Contents
5103 ;; `org-export-collect-headlines' builds a list of all exportable
5104 ;; headline elements, maybe limited to a certain depth. One can then
5105 ;; easily parse it and transcode it.
5107 ;; Building lists of tables, figures or listings is quite similar.
5108 ;; Once the generic function `org-export-collect-elements' is defined,
5109 ;; `org-export-collect-tables', `org-export-collect-figures' and
5110 ;; `org-export-collect-listings' can be derived from it.
5112 (defun org-export-collect-headlines (info &optional n scope)
5113 "Collect headlines in order to build a table of contents.
5115 INFO is a plist used as a communication channel.
5117 When optional argument N is an integer, it specifies the depth of
5118 the table of contents. Otherwise, it is set to the value of the
5119 last headline level. See `org-export-headline-levels' for more
5120 information.
5122 Optional argument SCOPE, when non-nil, is an element. If it is
5123 a headline, only children of SCOPE are collected. Otherwise,
5124 collect children of the headline containing provided element. If
5125 there is no such headline, collect all headlines. In any case,
5126 argument N becomes relative to the level of that headline.
5128 Return a list of all exportable headlines as parsed elements.
5129 Footnote sections are ignored."
5130 (let* ((scope (cond ((not scope) (plist-get info :parse-tree))
5131 ((eq (org-element-type scope) 'headline) scope)
5132 ((org-export-get-parent-headline scope))
5133 (t (plist-get info :parse-tree))))
5134 (limit (plist-get info :headline-levels))
5135 (n (if (not (wholenump n)) limit
5136 (min (if (eq (org-element-type scope) 'org-data) n
5137 (+ (org-export-get-relative-level scope info) n))
5138 limit))))
5139 (org-element-map (org-element-contents scope) 'headline
5140 (lambda (headline)
5141 (unless (org-element-property :footnote-section-p headline)
5142 (let ((level (org-export-get-relative-level headline info)))
5143 (and (<= level n) headline))))
5144 info)))
5146 (defun org-export-collect-elements (type info &optional predicate)
5147 "Collect referenceable elements of a determined type.
5149 TYPE can be a symbol or a list of symbols specifying element
5150 types to search. Only elements with a caption are collected.
5152 INFO is a plist used as a communication channel.
5154 When non-nil, optional argument PREDICATE is a function accepting
5155 one argument, an element of type TYPE. It returns a non-nil
5156 value when that element should be collected.
5158 Return a list of all elements found, in order of appearance."
5159 (org-element-map (plist-get info :parse-tree) type
5160 (lambda (element)
5161 (and (org-element-property :caption element)
5162 (or (not predicate) (funcall predicate element))
5163 element))
5164 info))
5166 (defun org-export-collect-tables (info)
5167 "Build a list of tables.
5168 INFO is a plist used as a communication channel.
5170 Return a list of table elements with a caption."
5171 (org-export-collect-elements 'table info))
5173 (defun org-export-collect-figures (info predicate)
5174 "Build a list of figures.
5176 INFO is a plist used as a communication channel. PREDICATE is
5177 a function which accepts one argument: a paragraph element and
5178 whose return value is non-nil when that element should be
5179 collected.
5181 A figure is a paragraph type element, with a caption, verifying
5182 PREDICATE. The latter has to be provided since a \"figure\" is
5183 a vague concept that may depend on back-end.
5185 Return a list of elements recognized as figures."
5186 (org-export-collect-elements 'paragraph info predicate))
5188 (defun org-export-collect-listings (info)
5189 "Build a list of src blocks.
5191 INFO is a plist used as a communication channel.
5193 Return a list of src-block elements with a caption."
5194 (org-export-collect-elements 'src-block info))
5197 ;;;; Smart Quotes
5199 ;; The main function for the smart quotes sub-system is
5200 ;; `org-export-activate-smart-quotes', which replaces every quote in
5201 ;; a given string from the parse tree with its "smart" counterpart.
5203 ;; Dictionary for smart quotes is stored in
5204 ;; `org-export-smart-quotes-alist'.
5206 (defconst org-export-smart-quotes-alist
5207 '(("da"
5208 ;; one may use: »...«, "...", ›...‹, or '...'.
5209 ;; http://sproget.dk/raad-og-regler/retskrivningsregler/retskrivningsregler/a7-40-60/a7-58-anforselstegn/
5210 ;; LaTeX quotes require Babel!
5211 (primary-opening
5212 :utf-8 "»" :html "&raquo;" :latex ">>" :texinfo "@guillemetright{}")
5213 (primary-closing
5214 :utf-8 "«" :html "&laquo;" :latex "<<" :texinfo "@guillemetleft{}")
5215 (secondary-opening
5216 :utf-8 "›" :html "&rsaquo;" :latex "\\frq{}" :texinfo "@guilsinglright{}")
5217 (secondary-closing
5218 :utf-8 "‹" :html "&lsaquo;" :latex "\\flq{}" :texinfo "@guilsingleft{}")
5219 (apostrophe :utf-8 "’" :html "&rsquo;"))
5220 ("de"
5221 (primary-opening
5222 :utf-8 "„" :html "&bdquo;" :latex "\"`" :texinfo "@quotedblbase{}")
5223 (primary-closing
5224 :utf-8 "“" :html "&ldquo;" :latex "\"'" :texinfo "@quotedblleft{}")
5225 (secondary-opening
5226 :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}" :texinfo "@quotesinglbase{}")
5227 (secondary-closing
5228 :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}" :texinfo "@quoteleft{}")
5229 (apostrophe :utf-8 "’" :html "&rsquo;"))
5230 ("en"
5231 (primary-opening :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
5232 (primary-closing :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
5233 (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5234 (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5235 (apostrophe :utf-8 "’" :html "&rsquo;"))
5236 ("es"
5237 (primary-opening
5238 :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5239 :texinfo "@guillemetleft{}")
5240 (primary-closing
5241 :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5242 :texinfo "@guillemetright{}")
5243 (secondary-opening :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
5244 (secondary-closing :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
5245 (apostrophe :utf-8 "’" :html "&rsquo;"))
5246 ("fr"
5247 (primary-opening
5248 :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
5249 :texinfo "@guillemetleft{}@tie{}")
5250 (primary-closing
5251 :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
5252 :texinfo "@tie{}@guillemetright{}")
5253 (secondary-opening
5254 :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
5255 :texinfo "@guillemetleft{}@tie{}")
5256 (secondary-closing :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
5257 :texinfo "@tie{}@guillemetright{}")
5258 (apostrophe :utf-8 "’" :html "&rsquo;"))
5259 ("is"
5260 (primary-opening
5261 :utf-8 "„" :html "&bdquo;" :latex "\"`" :texinfo "@quotedblbase{}")
5262 (primary-closing
5263 :utf-8 "“" :html "&ldquo;" :latex "\"'" :texinfo "@quotedblleft{}")
5264 (secondary-opening
5265 :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}" :texinfo "@quotesinglbase{}")
5266 (secondary-closing
5267 :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}" :texinfo "@quoteleft{}")
5268 (apostrophe :utf-8 "’" :html "&rsquo;"))
5269 ("no"
5270 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5271 (primary-opening
5272 :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5273 :texinfo "@guillemetleft{}")
5274 (primary-closing
5275 :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5276 :texinfo "@guillemetright{}")
5277 (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5278 (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5279 (apostrophe :utf-8 "’" :html "&rsquo;"))
5280 ("nb"
5281 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5282 (primary-opening
5283 :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5284 :texinfo "@guillemetleft{}")
5285 (primary-closing
5286 :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5287 :texinfo "@guillemetright{}")
5288 (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5289 (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5290 (apostrophe :utf-8 "’" :html "&rsquo;"))
5291 ("nn"
5292 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5293 (primary-opening
5294 :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5295 :texinfo "@guillemetleft{}")
5296 (primary-closing
5297 :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5298 :texinfo "@guillemetright{}")
5299 (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5300 (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5301 (apostrophe :utf-8 "’" :html "&rsquo;"))
5302 ("ru"
5303 ;; http://ru.wikipedia.org/wiki/%D0%9A%D0%B0%D0%B2%D1%8B%D1%87%D0%BA%D0%B8#.D0.9A.D0.B0.D0.B2.D1.8B.D1.87.D0.BA.D0.B8.2C_.D0.B8.D1.81.D0.BF.D0.BE.D0.BB.D1.8C.D0.B7.D1.83.D0.B5.D0.BC.D1.8B.D0.B5_.D0.B2_.D1.80.D1.83.D1.81.D1.81.D0.BA.D0.BE.D0.BC_.D1.8F.D0.B7.D1.8B.D0.BA.D0.B5
5304 ;; http://www.artlebedev.ru/kovodstvo/sections/104/
5305 (primary-opening :utf-8 "«" :html "&laquo;" :latex "{}<<"
5306 :texinfo "@guillemetleft{}")
5307 (primary-closing :utf-8 "»" :html "&raquo;" :latex ">>{}"
5308 :texinfo "@guillemetright{}")
5309 (secondary-opening
5310 :utf-8 "„" :html "&bdquo;" :latex "\\glqq{}" :texinfo "@quotedblbase{}")
5311 (secondary-closing
5312 :utf-8 "“" :html "&ldquo;" :latex "\\grqq{}" :texinfo "@quotedblleft{}")
5313 (apostrophe :utf-8 "’" :html: "&#39;"))
5314 ("sv"
5315 ;; based on https://sv.wikipedia.org/wiki/Citattecken
5316 (primary-opening :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
5317 (primary-closing :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
5318 (secondary-opening :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "`")
5319 (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "'")
5320 (apostrophe :utf-8 "’" :html "&rsquo;")))
5321 "Smart quotes translations.
5323 Alist whose CAR is a language string and CDR is an alist with
5324 quote type as key and a plist associating various encodings to
5325 their translation as value.
5327 A quote type can be any symbol among `primary-opening',
5328 `primary-closing', `secondary-opening', `secondary-closing' and
5329 `apostrophe'.
5331 Valid encodings include `:utf-8', `:html', `:latex' and
5332 `:texinfo'.
5334 If no translation is found, the quote character is left as-is.")
5336 (defun org-export--smart-quote-status (s info)
5337 "Return smart quote status at the beginning of string S.
5338 INFO is the current export state, as a plist."
5339 (let* ((parent (org-element-property :parent s))
5340 (cache (or (plist-get info :smart-quote-cache)
5341 (let ((table (make-hash-table :test #'eq)))
5342 (plist-put info :smart-quote-cache table)
5343 table)))
5344 (value (gethash parent cache 'missing-data)))
5345 (if (not (eq value 'missing-data)) (cdr (assq s value))
5346 (let (level1-open full-status)
5347 (org-element-map
5348 (let ((secondary (org-element-secondary-p s)))
5349 (if secondary (org-element-property secondary parent)
5350 (org-element-contents parent)))
5351 'plain-text
5352 (lambda (text)
5353 (let ((start 0) current-status)
5354 (while (setq start (string-match "['\"]" text start))
5355 (push
5356 (cond
5357 ((equal (match-string 0 text) "\"")
5358 (setf level1-open (not level1-open))
5359 (if level1-open 'primary-opening 'primary-closing))
5360 ;; Not already in a level 1 quote: this is an
5361 ;; apostrophe.
5362 ((not level1-open) 'apostrophe)
5363 ;; Extract previous char and next char. As
5364 ;; a special case, they can also be set to `blank',
5365 ;; `no-blank' or nil. Then determine if current
5366 ;; match is allowed as an opening quote or a closing
5367 ;; quote.
5369 (let* ((previous
5370 (if (> start 0) (substring text (1- start) start)
5371 (let ((p (org-export-get-previous-element
5372 text info)))
5373 (cond ((not p) nil)
5374 ((stringp p) (substring p -1))
5375 ((memq (org-element-property :post-blank p)
5376 '(0 nil))
5377 'no-blank)
5378 (t 'blank)))))
5379 (next
5380 (if (< (1+ start) (length text))
5381 (substring text (1+ start) (+ start 2))
5382 (let ((n (org-export-get-next-element text info)))
5383 (cond ((not n) nil)
5384 ((stringp n) (substring n 0 1))
5385 (t 'no-blank)))))
5386 (allow-open
5387 (and (if (stringp previous)
5388 (string-match "\\s\"\\|\\s-\\|\\s("
5389 previous)
5390 (memq previous '(blank nil)))
5391 (if (stringp next)
5392 (string-match "\\w\\|\\s.\\|\\s_" next)
5393 (eq next 'no-blank))))
5394 (allow-close
5395 (and (if (stringp previous)
5396 (string-match "\\w\\|\\s.\\|\\s_" previous)
5397 (eq previous 'no-blank))
5398 (if (stringp next)
5399 (string-match "\\s-\\|\\s)\\|\\s.\\|\\s\""
5400 next)
5401 (memq next '(blank nil))))))
5402 (cond
5403 ((and allow-open allow-close) (error "Should not happen"))
5404 (allow-open 'secondary-opening)
5405 (allow-close 'secondary-closing)
5406 (t 'apostrophe)))))
5407 current-status)
5408 (cl-incf start))
5409 (when current-status
5410 (push (cons text (nreverse current-status)) full-status))))
5411 info nil org-element-recursive-objects)
5412 (puthash parent full-status cache)
5413 (cdr (assq s full-status))))))
5415 (defun org-export-activate-smart-quotes (s encoding info &optional original)
5416 "Replace regular quotes with \"smart\" quotes in string S.
5418 ENCODING is a symbol among `:html', `:latex', `:texinfo' and
5419 `:utf-8'. INFO is a plist used as a communication channel.
5421 The function has to retrieve information about string
5422 surroundings in parse tree. It can only happen with an
5423 unmodified string. Thus, if S has already been through another
5424 process, a non-nil ORIGINAL optional argument will provide that
5425 original string.
5427 Return the new string."
5428 (let ((quote-status
5429 (copy-sequence (org-export--smart-quote-status (or original s) info))))
5430 (replace-regexp-in-string
5431 "['\"]"
5432 (lambda (match)
5433 (or (plist-get
5434 (cdr (assq (pop quote-status)
5435 (cdr (assoc (plist-get info :language)
5436 org-export-smart-quotes-alist))))
5437 encoding)
5438 match))
5439 s nil t)))
5441 ;;;; Topology
5443 ;; Here are various functions to retrieve information about the
5444 ;; neighborhood of a given element or object. Neighbors of interest
5445 ;; are direct parent (`org-export-get-parent'), parent headline
5446 ;; (`org-export-get-parent-headline'), first element containing an
5447 ;; object, (`org-export-get-parent-element'), parent table
5448 ;; (`org-export-get-parent-table'), previous element or object
5449 ;; (`org-export-get-previous-element') and next element or object
5450 ;; (`org-export-get-next-element').
5452 ;; defsubst org-export-get-parent must be defined before first use
5454 (defun org-export-get-parent-headline (blob)
5455 "Return BLOB parent headline or nil.
5456 BLOB is the element or object being considered."
5457 (org-element-lineage blob '(headline)))
5459 (defun org-export-get-parent-element (object)
5460 "Return first element containing OBJECT or nil.
5461 OBJECT is the object to consider."
5462 (org-element-lineage object org-element-all-elements))
5464 (defun org-export-get-parent-table (object)
5465 "Return OBJECT parent table or nil.
5466 OBJECT is either a `table-cell' or `table-element' type object."
5467 (org-element-lineage object '(table)))
5469 (defun org-export-get-previous-element (blob info &optional n)
5470 "Return previous element or object.
5472 BLOB is an element or object. INFO is a plist used as
5473 a communication channel. Return previous exportable element or
5474 object, a string, or nil.
5476 When optional argument N is a positive integer, return a list
5477 containing up to N siblings before BLOB, from farthest to
5478 closest. With any other non-nil value, return a list containing
5479 all of them."
5480 (let* ((secondary (org-element-secondary-p blob))
5481 (parent (org-export-get-parent blob))
5482 (siblings
5483 (if secondary (org-element-property secondary parent)
5484 (org-element-contents parent)))
5485 prev)
5486 (catch 'exit
5487 (dolist (obj (cdr (memq blob (reverse siblings))) prev)
5488 (cond ((memq obj (plist-get info :ignore-list)))
5489 ((null n) (throw 'exit obj))
5490 ((not (wholenump n)) (push obj prev))
5491 ((zerop n) (throw 'exit prev))
5492 (t (cl-decf n) (push obj prev)))))))
5494 (defun org-export-get-next-element (blob info &optional n)
5495 "Return next element or object.
5497 BLOB is an element or object. INFO is a plist used as
5498 a communication channel. Return next exportable element or
5499 object, a string, or nil.
5501 When optional argument N is a positive integer, return a list
5502 containing up to N siblings after BLOB, from closest to farthest.
5503 With any other non-nil value, return a list containing all of
5504 them."
5505 (let* ((secondary (org-element-secondary-p blob))
5506 (parent (org-export-get-parent blob))
5507 (siblings
5508 (cdr (memq blob
5509 (if secondary (org-element-property secondary parent)
5510 (org-element-contents parent)))))
5511 next)
5512 (catch 'exit
5513 (dolist (obj siblings (nreverse next))
5514 (cond ((memq obj (plist-get info :ignore-list)))
5515 ((null n) (throw 'exit obj))
5516 ((not (wholenump n)) (push obj next))
5517 ((zerop n) (throw 'exit (nreverse next)))
5518 (t (cl-decf n) (push obj next)))))))
5521 ;;;; Translation
5523 ;; `org-export-translate' translates a string according to the language
5524 ;; specified by the LANGUAGE keyword. `org-export-dictionary' contains
5525 ;; the dictionary used for the translation.
5527 (defconst org-export-dictionary
5528 '(("%e %n: %c"
5529 ("fr" :default "%e %n : %c" :html "%e&nbsp;%n&nbsp;: %c"))
5530 ("Author"
5531 ("ca" :default "Autor")
5532 ("cs" :default "Autor")
5533 ("da" :default "Forfatter")
5534 ("de" :default "Autor")
5535 ("eo" :html "A&#365;toro")
5536 ("es" :default "Autor")
5537 ("et" :default "Autor")
5538 ("fi" :html "Tekij&auml;")
5539 ("fr" :default "Auteur")
5540 ("hu" :default "Szerz&otilde;")
5541 ("is" :html "H&ouml;fundur")
5542 ("it" :default "Autore")
5543 ("ja" :default "著者" :html "&#33879;&#32773;")
5544 ("nl" :default "Auteur")
5545 ("no" :default "Forfatter")
5546 ("nb" :default "Forfatter")
5547 ("nn" :default "Forfattar")
5548 ("pl" :default "Autor")
5549 ("pt_BR" :default "Autor")
5550 ("ru" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5551 ("sv" :html "F&ouml;rfattare")
5552 ("uk" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5553 ("zh-CN" :html "&#20316;&#32773;" :utf-8 "作者")
5554 ("zh-TW" :html "&#20316;&#32773;" :utf-8 "作者"))
5555 ("Continued from previous page"
5556 ("de" :default "Fortsetzung von vorheriger Seite")
5557 ("es" :html "Contin&uacute;a de la p&aacute;gina anterior" :ascii "Continua de la pagina anterior" :default "Continúa de la página anterior")
5558 ("fr" :default "Suite de la page précédente")
5559 ("it" :default "Continua da pagina precedente")
5560 ("ja" :default "前ページからの続き")
5561 ("nl" :default "Vervolg van vorige pagina")
5562 ("pt" :default "Continuação da página anterior")
5563 ("ru" :html "(&#1055;&#1088;&#1086;&#1076;&#1086;&#1083;&#1078;&#1077;&#1085;&#1080;&#1077;)"
5564 :utf-8 "(Продолжение)"))
5565 ("Continued on next page"
5566 ("de" :default "Fortsetzung nächste Seite")
5567 ("es" :html "Contin&uacute;a en la siguiente p&aacute;gina" :ascii "Continua en la siguiente pagina" :default "Continúa en la siguiente página")
5568 ("fr" :default "Suite page suivante")
5569 ("it" :default "Continua alla pagina successiva")
5570 ("ja" :default "次ページに続く")
5571 ("nl" :default "Vervolg op volgende pagina")
5572 ("pt" :default "Continua na página seguinte")
5573 ("ru" :html "(&#1055;&#1088;&#1086;&#1076;&#1086;&#1083;&#1078;&#1077;&#1085;&#1080;&#1077; &#1089;&#1083;&#1077;&#1076;&#1091;&#1077;&#1090;)"
5574 :utf-8 "(Продолжение следует)"))
5575 ("Date"
5576 ("ca" :default "Data")
5577 ("cs" :default "Datum")
5578 ("da" :default "Dato")
5579 ("de" :default "Datum")
5580 ("eo" :default "Dato")
5581 ("es" :default "Fecha")
5582 ("et" :html "Kuup&#228;ev" :utf-8 "Kuupäev")
5583 ("fi" :html "P&auml;iv&auml;m&auml;&auml;r&auml;")
5584 ("hu" :html "D&aacute;tum")
5585 ("is" :default "Dagsetning")
5586 ("it" :default "Data")
5587 ("ja" :default "日付" :html "&#26085;&#20184;")
5588 ("nl" :default "Datum")
5589 ("no" :default "Dato")
5590 ("nb" :default "Dato")
5591 ("nn" :default "Dato")
5592 ("pl" :default "Data")
5593 ("pt_BR" :default "Data")
5594 ("ru" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5595 ("sv" :default "Datum")
5596 ("uk" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5597 ("zh-CN" :html "&#26085;&#26399;" :utf-8 "日期")
5598 ("zh-TW" :html "&#26085;&#26399;" :utf-8 "日期"))
5599 ("Equation"
5600 ("da" :default "Ligning")
5601 ("de" :default "Gleichung")
5602 ("es" :ascii "Ecuacion" :html "Ecuaci&oacute;n" :default "Ecuación")
5603 ("et" :html "V&#245;rrand" :utf-8 "Võrrand")
5604 ("fr" :ascii "Equation" :default "Équation")
5605 ("is" :default "Jafna")
5606 ("ja" :default "方程式")
5607 ("no" :default "Ligning")
5608 ("nb" :default "Ligning")
5609 ("nn" :default "Likning")
5610 ("pt_BR" :html "Equa&ccedil;&atilde;o" :default "Equação" :ascii "Equacao")
5611 ("ru" :html "&#1059;&#1088;&#1072;&#1074;&#1085;&#1077;&#1085;&#1080;&#1077;"
5612 :utf-8 "Уравнение")
5613 ("sv" :default "Ekvation")
5614 ("zh-CN" :html "&#26041;&#31243;" :utf-8 "方程"))
5615 ("Figure"
5616 ("da" :default "Figur")
5617 ("de" :default "Abbildung")
5618 ("es" :default "Figura")
5619 ("et" :default "Joonis")
5620 ("is" :default "Mynd")
5621 ("ja" :default "図" :html "&#22259;")
5622 ("no" :default "Illustrasjon")
5623 ("nb" :default "Illustrasjon")
5624 ("nn" :default "Illustrasjon")
5625 ("pt_BR" :default "Figura")
5626 ("ru" :html "&#1056;&#1080;&#1089;&#1091;&#1085;&#1086;&#1082;" :utf-8 "Рисунок")
5627 ("sv" :default "Illustration")
5628 ("zh-CN" :html "&#22270;" :utf-8 "图"))
5629 ("Figure %d:"
5630 ("da" :default "Figur %d")
5631 ("de" :default "Abbildung %d:")
5632 ("es" :default "Figura %d:")
5633 ("et" :default "Joonis %d:")
5634 ("fr" :default "Figure %d :" :html "Figure&nbsp;%d&nbsp;:")
5635 ("is" :default "Mynd %d")
5636 ("ja" :default "図%d: " :html "&#22259;%d: ")
5637 ("no" :default "Illustrasjon %d")
5638 ("nb" :default "Illustrasjon %d")
5639 ("nn" :default "Illustrasjon %d")
5640 ("pt_BR" :default "Figura %d:")
5641 ("ru" :html "&#1056;&#1080;&#1089;. %d.:" :utf-8 "Рис. %d.:")
5642 ("sv" :default "Illustration %d")
5643 ("zh-CN" :html "&#22270;%d&nbsp;" :utf-8 "图%d "))
5644 ("Footnotes"
5645 ("ca" :html "Peus de p&agrave;gina")
5646 ("cs" :default "Pozn\xe1mky pod carou")
5647 ("da" :default "Fodnoter")
5648 ("de" :html "Fu&szlig;noten" :default "Fußnoten")
5649 ("eo" :default "Piednotoj")
5650 ("es" :ascii "Nota al pie de pagina" :html "Nota al pie de p&aacute;gina" :default "Nota al pie de página")
5651 ("et" :html "Allm&#228;rkused" :utf-8 "Allmärkused")
5652 ("fi" :default "Alaviitteet")
5653 ("fr" :default "Notes de bas de page")
5654 ("hu" :html "L&aacute;bjegyzet")
5655 ("is" :html "Aftanm&aacute;lsgreinar")
5656 ("it" :html "Note a pi&egrave; di pagina")
5657 ("ja" :default "脚注" :html "&#33050;&#27880;")
5658 ("nl" :default "Voetnoten")
5659 ("no" :default "Fotnoter")
5660 ("nb" :default "Fotnoter")
5661 ("nn" :default "Fotnotar")
5662 ("pl" :default "Przypis")
5663 ("pt_BR" :html "Notas de Rodap&eacute;" :default "Notas de Rodapé" :ascii "Notas de Rodape")
5664 ("ru" :html "&#1057;&#1085;&#1086;&#1089;&#1082;&#1080;" :utf-8 "Сноски")
5665 ("sv" :default "Fotnoter")
5666 ("uk" :html "&#1055;&#1088;&#1080;&#1084;&#1110;&#1090;&#1082;&#1080;"
5667 :utf-8 "Примітки")
5668 ("zh-CN" :html "&#33050;&#27880;" :utf-8 "脚注")
5669 ("zh-TW" :html "&#33139;&#35387;" :utf-8 "腳註"))
5670 ("List of Listings"
5671 ("da" :default "Programmer")
5672 ("de" :default "Programmauflistungsverzeichnis")
5673 ("es" :ascii "Indice de Listados de programas" :html "&Iacute;ndice de Listados de programas" :default "Índice de Listados de programas")
5674 ("et" :default "Loendite nimekiri")
5675 ("fr" :default "Liste des programmes")
5676 ("ja" :default "ソースコード目次")
5677 ("no" :default "Dataprogrammer")
5678 ("nb" :default "Dataprogrammer")
5679 ("ru" :html "&#1057;&#1087;&#1080;&#1089;&#1086;&#1082; &#1088;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1086;&#1082;"
5680 :utf-8 "Список распечаток")
5681 ("zh-CN" :html "&#20195;&#30721;&#30446;&#24405;" :utf-8 "代码目录"))
5682 ("List of Tables"
5683 ("da" :default "Tabeller")
5684 ("de" :default "Tabellenverzeichnis")
5685 ("es" :ascii "Indice de tablas" :html "&Iacute;ndice de tablas" :default "Índice de tablas")
5686 ("et" :default "Tabelite nimekiri")
5687 ("fr" :default "Liste des tableaux")
5688 ("is" :default "Töfluskrá" :html "T&ouml;fluskr&aacute;")
5689 ("ja" :default "表目次")
5690 ("no" :default "Tabeller")
5691 ("nb" :default "Tabeller")
5692 ("nn" :default "Tabeller")
5693 ("pt_BR" :default "Índice de Tabelas" :ascii "Indice de Tabelas")
5694 ("ru" :html "&#1057;&#1087;&#1080;&#1089;&#1086;&#1082; &#1090;&#1072;&#1073;&#1083;&#1080;&#1094;"
5695 :utf-8 "Список таблиц")
5696 ("sv" :default "Tabeller")
5697 ("zh-CN" :html "&#34920;&#26684;&#30446;&#24405;" :utf-8 "表格目录"))
5698 ("Listing"
5699 ("da" :default "Program")
5700 ("de" :default "Programmlisting")
5701 ("es" :default "Listado de programa")
5702 ("et" :default "Loend")
5703 ("fr" :default "Programme" :html "Programme")
5704 ("ja" :default "ソースコード")
5705 ("no" :default "Dataprogram")
5706 ("nb" :default "Dataprogram")
5707 ("pt_BR" :default "Listagem")
5708 ("ru" :html "&#1056;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1082;&#1072;"
5709 :utf-8 "Распечатка")
5710 ("zh-CN" :html "&#20195;&#30721;" :utf-8 "代码"))
5711 ("Listing %d:"
5712 ("da" :default "Program %d")
5713 ("de" :default "Programmlisting %d")
5714 ("es" :default "Listado de programa %d")
5715 ("et" :default "Loend %d")
5716 ("fr" :default "Programme %d :" :html "Programme&nbsp;%d&nbsp;:")
5717 ("ja" :default "ソースコード%d:")
5718 ("no" :default "Dataprogram %d")
5719 ("nb" :default "Dataprogram %d")
5720 ("pt_BR" :default "Listagem %d")
5721 ("ru" :html "&#1056;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1082;&#1072; %d.:"
5722 :utf-8 "Распечатка %d.:")
5723 ("zh-CN" :html "&#20195;&#30721;%d&nbsp;" :utf-8 "代码%d "))
5724 ("References"
5725 ("fr" :ascii "References" :default "Références")
5726 ("de" :default "Quellen")
5727 ("es" :default "Referencias"))
5728 ("See figure %s"
5729 ("fr" :default "cf. figure %s"
5730 :html "cf.&nbsp;figure&nbsp;%s" :latex "cf.~figure~%s"))
5731 ("See listing %s"
5732 ("fr" :default "cf. programme %s"
5733 :html "cf.&nbsp;programme&nbsp;%s" :latex "cf.~programme~%s"))
5734 ("See section %s"
5735 ("da" :default "jævnfør afsnit %s")
5736 ("de" :default "siehe Abschnitt %s")
5737 ("es" :ascii "Vea seccion %s" :html "Vea secci&oacute;n %s" :default "Vea sección %s")
5738 ("et" :html "Vaata peat&#252;kki %s" :utf-8 "Vaata peatükki %s")
5739 ("fr" :default "cf. section %s")
5740 ("ja" :default "セクション %s を参照")
5741 ("pt_BR" :html "Veja a se&ccedil;&atilde;o %s" :default "Veja a seção %s"
5742 :ascii "Veja a secao %s")
5743 ("ru" :html "&#1057;&#1084;. &#1088;&#1072;&#1079;&#1076;&#1077;&#1083; %s"
5744 :utf-8 "См. раздел %s")
5745 ("zh-CN" :html "&#21442;&#35265;&#31532;%s&#33410;" :utf-8 "参见第%s节"))
5746 ("See table %s"
5747 ("fr" :default "cf. tableau %s"
5748 :html "cf.&nbsp;tableau&nbsp;%s" :latex "cf.~tableau~%s"))
5749 ("Table"
5750 ("de" :default "Tabelle")
5751 ("es" :default "Tabla")
5752 ("et" :default "Tabel")
5753 ("fr" :default "Tableau")
5754 ("is" :default "Tafla")
5755 ("ja" :default "表" :html "&#34920;")
5756 ("pt_BR" :default "Tabela")
5757 ("ru" :html "&#1058;&#1072;&#1073;&#1083;&#1080;&#1094;&#1072;"
5758 :utf-8 "Таблица")
5759 ("zh-CN" :html "&#34920;" :utf-8 "表"))
5760 ("Table %d:"
5761 ("da" :default "Tabel %d")
5762 ("de" :default "Tabelle %d")
5763 ("es" :default "Tabla %d")
5764 ("et" :default "Tabel %d")
5765 ("fr" :default "Tableau %d :")
5766 ("is" :default "Tafla %d")
5767 ("ja" :default "表%d:" :html "&#34920;%d:")
5768 ("no" :default "Tabell %d")
5769 ("nb" :default "Tabell %d")
5770 ("nn" :default "Tabell %d")
5771 ("pt_BR" :default "Tabela %d")
5772 ("ru" :html "&#1058;&#1072;&#1073;&#1083;&#1080;&#1094;&#1072; %d.:"
5773 :utf-8 "Таблица %d.:")
5774 ("sv" :default "Tabell %d")
5775 ("zh-CN" :html "&#34920;%d&nbsp;" :utf-8 "表%d "))
5776 ("Table of Contents"
5777 ("ca" :html "&Iacute;ndex")
5778 ("cs" :default "Obsah")
5779 ("da" :default "Indhold")
5780 ("de" :default "Inhaltsverzeichnis")
5781 ("eo" :default "Enhavo")
5782 ("es" :ascii "Indice" :html "&Iacute;ndice" :default "Índice")
5783 ("et" :default "Sisukord")
5784 ("fi" :html "Sis&auml;llysluettelo")
5785 ("fr" :ascii "Sommaire" :default "Table des matières")
5786 ("hu" :html "Tartalomjegyz&eacute;k")
5787 ("is" :default "Efnisyfirlit")
5788 ("it" :default "Indice")
5789 ("ja" :default "目次" :html "&#30446;&#27425;")
5790 ("nl" :default "Inhoudsopgave")
5791 ("no" :default "Innhold")
5792 ("nb" :default "Innhold")
5793 ("nn" :default "Innhald")
5794 ("pl" :html "Spis tre&#x015b;ci")
5795 ("pt_BR" :html "&Iacute;ndice" :utf8 "Índice" :ascii "Indice")
5796 ("ru" :html "&#1057;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1077;"
5797 :utf-8 "Содержание")
5798 ("sv" :html "Inneh&aring;ll")
5799 ("uk" :html "&#1047;&#1084;&#1110;&#1089;&#1090;" :utf-8 "Зміст")
5800 ("zh-CN" :html "&#30446;&#24405;" :utf-8 "目录")
5801 ("zh-TW" :html "&#30446;&#37636;" :utf-8 "目錄"))
5802 ("Unknown reference"
5803 ("da" :default "ukendt reference")
5804 ("de" :default "Unbekannter Verweis")
5805 ("es" :default "Referencia desconocida")
5806 ("et" :default "Tundmatu viide")
5807 ("fr" :ascii "Destination inconnue" :default "Référence inconnue")
5808 ("ja" :default "不明な参照先")
5809 ("pt_BR" :default "Referência desconhecida"
5810 :ascii "Referencia desconhecida")
5811 ("ru" :html "&#1053;&#1077;&#1080;&#1079;&#1074;&#1077;&#1089;&#1090;&#1085;&#1072;&#1103; &#1089;&#1089;&#1099;&#1083;&#1082;&#1072;"
5812 :utf-8 "Неизвестная ссылка")
5813 ("zh-CN" :html "&#26410;&#30693;&#24341;&#29992;" :utf-8 "未知引用")))
5814 "Dictionary for export engine.
5816 Alist whose car is the string to translate and cdr is an alist
5817 whose car is the language string and cdr is a plist whose
5818 properties are possible charsets and values translated terms.
5820 It is used as a database for `org-export-translate'. Since this
5821 function returns the string as-is if no translation was found,
5822 the variable only needs to record values different from the
5823 entry.")
5825 (defun org-export-translate (s encoding info)
5826 "Translate string S according to language specification.
5828 ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1'
5829 and `:utf-8'. INFO is a plist used as a communication channel.
5831 Translation depends on `:language' property. Return the
5832 translated string. If no translation is found, try to fall back
5833 to `:default' encoding. If it fails, return S."
5834 (let* ((lang (plist-get info :language))
5835 (translations (cdr (assoc lang
5836 (cdr (assoc s org-export-dictionary))))))
5837 (or (plist-get translations encoding)
5838 (plist-get translations :default)
5839 s)))
5843 ;;; Asynchronous Export
5845 ;; `org-export-async-start' is the entry point for asynchronous
5846 ;; export. It recreates current buffer (including visibility,
5847 ;; narrowing and visited file) in an external Emacs process, and
5848 ;; evaluates a command there. It then applies a function on the
5849 ;; returned results in the current process.
5851 ;; At a higher level, `org-export-to-buffer' and `org-export-to-file'
5852 ;; allow exporting to a buffer or a file, asynchronously or not.
5854 ;; `org-export-output-file-name' is an auxiliary function meant to be
5855 ;; used with `org-export-to-file'. With a given extension, it tries
5856 ;; to provide a canonical file name to write export output to.
5858 ;; Asynchronously generated results are never displayed directly.
5859 ;; Instead, they are stored in `org-export-stack-contents'. They can
5860 ;; then be retrieved by calling `org-export-stack'.
5862 ;; Export Stack is viewed through a dedicated major mode
5863 ;;`org-export-stack-mode' and tools: `org-export-stack-refresh',
5864 ;;`org-export-stack-delete', `org-export-stack-view' and
5865 ;;`org-export-stack-clear'.
5867 ;; For back-ends, `org-export-add-to-stack' add a new source to stack.
5868 ;; It should be used whenever `org-export-async-start' is called.
5870 (defmacro org-export-async-start (fun &rest body)
5871 "Call function FUN on the results returned by BODY evaluation.
5873 FUN is an anonymous function of one argument. BODY evaluation
5874 happens in an asynchronous process, from a buffer which is an
5875 exact copy of the current one.
5877 Use `org-export-add-to-stack' in FUN in order to register results
5878 in the stack.
5880 This is a low level function. See also `org-export-to-buffer'
5881 and `org-export-to-file' for more specialized functions."
5882 (declare (indent 1) (debug t))
5883 (org-with-gensyms (process temp-file copy-fun proc-buffer coding)
5884 ;; Write the full sexp evaluating BODY in a copy of the current
5885 ;; buffer to a temporary file, as it may be too long for program
5886 ;; args in `start-process'.
5887 `(with-temp-message "Initializing asynchronous export process"
5888 (let ((,copy-fun (org-export--generate-copy-script (current-buffer)))
5889 (,temp-file (make-temp-file "org-export-process"))
5890 (,coding buffer-file-coding-system))
5891 (with-temp-file ,temp-file
5892 (insert
5893 ;; Null characters (from variable values) are inserted
5894 ;; within the file. As a consequence, coding system for
5895 ;; buffer contents will not be recognized properly. So,
5896 ;; we make sure it is the same as the one used to display
5897 ;; the original buffer.
5898 (format ";; -*- coding: %s; -*-\n%S"
5899 ,coding
5900 `(with-temp-buffer
5901 (when org-export-async-debug '(setq debug-on-error t))
5902 ;; Ignore `kill-emacs-hook' and code evaluation
5903 ;; queries from Babel as we need a truly
5904 ;; non-interactive process.
5905 (setq kill-emacs-hook nil
5906 org-babel-confirm-evaluate-answer-no t)
5907 ;; Initialize export framework.
5908 (require 'ox)
5909 ;; Re-create current buffer there.
5910 (funcall ,,copy-fun)
5911 (restore-buffer-modified-p nil)
5912 ;; Sexp to evaluate in the buffer.
5913 (print (progn ,,@body))))))
5914 ;; Start external process.
5915 (let* ((process-connection-type nil)
5916 (,proc-buffer (generate-new-buffer-name "*Org Export Process*"))
5917 (,process
5918 (apply
5919 #'start-process
5920 (append
5921 (list "org-export-process"
5922 ,proc-buffer
5923 (expand-file-name invocation-name invocation-directory)
5924 "--batch")
5925 (if org-export-async-init-file
5926 (list "-Q" "-l" org-export-async-init-file)
5927 (list "-l" user-init-file))
5928 (list "-l" ,temp-file)))))
5929 ;; Register running process in stack.
5930 (org-export-add-to-stack (get-buffer ,proc-buffer) nil ,process)
5931 ;; Set-up sentinel in order to catch results.
5932 (let ((handler ,fun))
5933 (set-process-sentinel
5934 ,process
5935 `(lambda (p status)
5936 (let ((proc-buffer (process-buffer p)))
5937 (when (eq (process-status p) 'exit)
5938 (unwind-protect
5939 (if (zerop (process-exit-status p))
5940 (unwind-protect
5941 (let ((results
5942 (with-current-buffer proc-buffer
5943 (goto-char (point-max))
5944 (backward-sexp)
5945 (read (current-buffer)))))
5946 (funcall ,handler results))
5947 (unless org-export-async-debug
5948 (and (get-buffer proc-buffer)
5949 (kill-buffer proc-buffer))))
5950 (org-export-add-to-stack proc-buffer nil p)
5951 (ding)
5952 (message "Process `%s' exited abnormally" p))
5953 (unless org-export-async-debug
5954 (delete-file ,,temp-file)))))))))))))
5956 ;;;###autoload
5957 (defun org-export-to-buffer
5958 (backend buffer
5959 &optional async subtreep visible-only body-only ext-plist
5960 post-process)
5961 "Call `org-export-as' with output to a specified buffer.
5963 BACKEND is either an export back-end, as returned by, e.g.,
5964 `org-export-create-backend', or a symbol referring to
5965 a registered back-end.
5967 BUFFER is the name of the output buffer. If it already exists,
5968 it will be erased first, otherwise, it will be created.
5970 A non-nil optional argument ASYNC means the process should happen
5971 asynchronously. The resulting buffer should then be accessible
5972 through the `org-export-stack' interface. When ASYNC is nil, the
5973 buffer is displayed if `org-export-show-temporary-export-buffer'
5974 is non-nil.
5976 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
5977 EXT-PLIST are similar to those used in `org-export-as', which
5978 see.
5980 Optional argument POST-PROCESS is a function which should accept
5981 no argument. It is always called within the current process,
5982 from BUFFER, with point at its beginning. Export back-ends can
5983 use it to set a major mode there, e.g,
5985 (defun org-latex-export-as-latex
5986 (&optional async subtreep visible-only body-only ext-plist)
5987 (interactive)
5988 (org-export-to-buffer \\='latex \"*Org LATEX Export*\"
5989 async subtreep visible-only body-only ext-plist (lambda () (LaTeX-mode))))
5991 This function returns BUFFER."
5992 (declare (indent 2))
5993 (if async
5994 (org-export-async-start
5995 `(lambda (output)
5996 (with-current-buffer (get-buffer-create ,buffer)
5997 (erase-buffer)
5998 (setq buffer-file-coding-system ',buffer-file-coding-system)
5999 (insert output)
6000 (goto-char (point-min))
6001 (org-export-add-to-stack (current-buffer) ',backend)
6002 (ignore-errors (funcall ,post-process))))
6003 `(org-export-as
6004 ',backend ,subtreep ,visible-only ,body-only ',ext-plist))
6005 (let ((output
6006 (org-export-as backend subtreep visible-only body-only ext-plist))
6007 (buffer (get-buffer-create buffer))
6008 (encoding buffer-file-coding-system))
6009 (when (and (org-string-nw-p output) (org-export--copy-to-kill-ring-p))
6010 (org-kill-new output))
6011 (with-current-buffer buffer
6012 (erase-buffer)
6013 (setq buffer-file-coding-system encoding)
6014 (insert output)
6015 (goto-char (point-min))
6016 (and (functionp post-process) (funcall post-process)))
6017 (when org-export-show-temporary-export-buffer
6018 (switch-to-buffer-other-window buffer))
6019 buffer)))
6021 ;;;###autoload
6022 (defun org-export-to-file
6023 (backend file &optional async subtreep visible-only body-only ext-plist
6024 post-process)
6025 "Call `org-export-as' with output to a specified file.
6027 BACKEND is either an export back-end, as returned by, e.g.,
6028 `org-export-create-backend', or a symbol referring to
6029 a registered back-end. FILE is the name of the output file, as
6030 a string.
6032 A non-nil optional argument ASYNC means the process should happen
6033 asynchronously. The resulting buffer will then be accessible
6034 through the `org-export-stack' interface.
6036 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
6037 EXT-PLIST are similar to those used in `org-export-as', which
6038 see.
6040 Optional argument POST-PROCESS is called with FILE as its
6041 argument and happens asynchronously when ASYNC is non-nil. It
6042 has to return a file name, or nil. Export back-ends can use this
6043 to send the output file through additional processing, e.g,
6045 (defun org-latex-export-to-latex
6046 (&optional async subtreep visible-only body-only ext-plist)
6047 (interactive)
6048 (let ((outfile (org-export-output-file-name \".tex\" subtreep)))
6049 (org-export-to-file \\='latex outfile
6050 async subtreep visible-only body-only ext-plist
6051 (lambda (file) (org-latex-compile file)))
6053 The function returns either a file name returned by POST-PROCESS,
6054 or FILE."
6055 (declare (indent 2))
6056 (if (not (file-writable-p file)) (error "Output file not writable")
6057 (let ((ext-plist (org-combine-plists `(:output-file ,file) ext-plist))
6058 (encoding (or org-export-coding-system buffer-file-coding-system)))
6059 (if async
6060 (org-export-async-start
6061 `(lambda (file)
6062 (org-export-add-to-stack (expand-file-name file) ',backend))
6063 `(let ((output
6064 (org-export-as
6065 ',backend ,subtreep ,visible-only ,body-only
6066 ',ext-plist)))
6067 (with-temp-buffer
6068 (insert output)
6069 (let ((coding-system-for-write ',encoding))
6070 (write-file ,file)))
6071 (or (ignore-errors (funcall ',post-process ,file)) ,file)))
6072 (let ((output (org-export-as
6073 backend subtreep visible-only body-only ext-plist)))
6074 (with-temp-buffer
6075 (insert output)
6076 (let ((coding-system-for-write encoding))
6077 (write-file file)))
6078 (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p output))
6079 (org-kill-new output))
6080 ;; Get proper return value.
6081 (or (and (functionp post-process) (funcall post-process file))
6082 file))))))
6084 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
6085 "Return output file's name according to buffer specifications.
6087 EXTENSION is a string representing the output file extension,
6088 with the leading dot.
6090 With a non-nil optional argument SUBTREEP, try to determine
6091 output file's name by looking for \"EXPORT_FILE_NAME\" property
6092 of subtree at point.
6094 When optional argument PUB-DIR is set, use it as the publishing
6095 directory.
6097 Return file name as a string."
6098 (let* ((visited-file (buffer-file-name (buffer-base-buffer)))
6099 (base-name
6100 ;; File name may come from EXPORT_FILE_NAME subtree
6101 ;; property.
6102 (file-name-sans-extension
6103 (or (and subtreep (org-entry-get nil "EXPORT_FILE_NAME" 'selective))
6104 ;; File name may be extracted from buffer's associated
6105 ;; file, if any.
6106 (and visited-file (file-name-nondirectory visited-file))
6107 ;; Can't determine file name on our own: Ask user.
6108 (read-file-name
6109 "Output file: " pub-dir nil nil nil
6110 (lambda (name)
6111 (string= (file-name-extension name t) extension))))))
6112 (output-file
6113 ;; Build file name. Enforce EXTENSION over whatever user
6114 ;; may have come up with. PUB-DIR, if defined, always has
6115 ;; precedence over any provided path.
6116 (cond
6117 (pub-dir
6118 (concat (file-name-as-directory pub-dir)
6119 (file-name-nondirectory base-name)
6120 extension))
6121 ((file-name-absolute-p base-name) (concat base-name extension))
6122 (t (concat (file-name-as-directory ".") base-name extension)))))
6123 ;; If writing to OUTPUT-FILE would overwrite original file, append
6124 ;; EXTENSION another time to final name.
6125 (if (and visited-file (file-equal-p visited-file output-file))
6126 (concat output-file extension)
6127 output-file)))
6129 (defun org-export-add-to-stack (source backend &optional process)
6130 "Add a new result to export stack if not present already.
6132 SOURCE is a buffer or a file name containing export results.
6133 BACKEND is a symbol representing export back-end used to generate
6136 Entries already pointing to SOURCE and unavailable entries are
6137 removed beforehand. Return the new stack."
6138 (setq org-export-stack-contents
6139 (cons (list source backend (or process (current-time)))
6140 (org-export-stack-remove source))))
6142 (defun org-export-stack ()
6143 "Menu for asynchronous export results and running processes."
6144 (interactive)
6145 (let ((buffer (get-buffer-create "*Org Export Stack*")))
6146 (with-current-buffer buffer
6147 (org-export-stack-mode)
6148 (tabulated-list-print t))
6149 (pop-to-buffer buffer))
6150 (message "Type \"q\" to quit, \"?\" for help"))
6152 (defun org-export-stack-clear ()
6153 "Remove all entries from export stack."
6154 (interactive)
6155 (setq org-export-stack-contents nil))
6157 (defun org-export-stack-refresh ()
6158 "Refresh the export stack."
6159 (interactive)
6160 (tabulated-list-print t))
6162 (defun org-export-stack-remove (&optional source)
6163 "Remove export results at point from stack.
6164 If optional argument SOURCE is non-nil, remove it instead."
6165 (interactive)
6166 (let ((source (or source (org-export--stack-source-at-point))))
6167 (setq org-export-stack-contents
6168 (cl-remove-if (lambda (el) (equal (car el) source))
6169 org-export-stack-contents))))
6171 (defun org-export-stack-view (&optional in-emacs)
6172 "View export results at point in stack.
6173 With an optional prefix argument IN-EMACS, force viewing files
6174 within Emacs."
6175 (interactive "P")
6176 (let ((source (org-export--stack-source-at-point)))
6177 (cond ((processp source)
6178 (org-switch-to-buffer-other-window (process-buffer source)))
6179 ((bufferp source) (org-switch-to-buffer-other-window source))
6180 (t (org-open-file source in-emacs)))))
6182 (defvar org-export-stack-mode-map
6183 (let ((km (make-sparse-keymap)))
6184 (set-keymap-parent km tabulated-list-mode-map)
6185 (define-key km " " 'next-line)
6186 (define-key km "\C-n" 'next-line)
6187 (define-key km [down] 'next-line)
6188 (define-key km "\C-p" 'previous-line)
6189 (define-key km "\C-?" 'previous-line)
6190 (define-key km [up] 'previous-line)
6191 (define-key km "C" 'org-export-stack-clear)
6192 (define-key km "v" 'org-export-stack-view)
6193 (define-key km (kbd "RET") 'org-export-stack-view)
6194 (define-key km "d" 'org-export-stack-remove)
6196 "Keymap for Org Export Stack.")
6198 (define-derived-mode org-export-stack-mode tabulated-list-mode "Org-Stack"
6199 "Mode for displaying asynchronous export stack.
6201 Type `\\[org-export-stack]' to visualize the asynchronous export
6202 stack.
6204 In an Org Export Stack buffer, use \
6205 \\<org-export-stack-mode-map>`\\[org-export-stack-view]' to view export output
6206 on current line, `\\[org-export-stack-remove]' to remove it from the stack and \
6207 `\\[org-export-stack-clear]' to clear
6208 stack completely.
6210 Removing entries in a stack buffer does not affect files
6211 or buffers, only display.
6213 \\{org-export-stack-mode-map}"
6214 (setq tabulated-list-format
6215 (vector (list "#" 4 #'org-export--stack-num-predicate)
6216 (list "Back-End" 12 t)
6217 (list "Age" 6 nil)
6218 (list "Source" 0 nil)))
6219 (setq tabulated-list-sort-key (cons "#" nil))
6220 (setq tabulated-list-entries #'org-export--stack-generate)
6221 (add-hook 'tabulated-list-revert-hook #'org-export--stack-generate nil t)
6222 (add-hook 'post-command-hook #'org-export-stack-refresh nil t)
6223 (tabulated-list-init-header))
6225 (defun org-export--stack-generate ()
6226 "Generate the asynchronous export stack for display.
6227 Unavailable sources are removed from the list. Return a list
6228 appropriate for `tabulated-list-print'."
6229 ;; Clear stack from exited processes, dead buffers or non-existent
6230 ;; files.
6231 (setq org-export-stack-contents
6232 (cl-remove-if-not
6233 (lambda (el)
6234 (if (processp (nth 2 el))
6235 (buffer-live-p (process-buffer (nth 2 el)))
6236 (let ((source (car el)))
6237 (if (bufferp source) (buffer-live-p source)
6238 (file-exists-p source)))))
6239 org-export-stack-contents))
6240 ;; Update `tabulated-list-entries'.
6241 (let ((counter 0))
6242 (mapcar
6243 (lambda (entry)
6244 (let ((source (car entry)))
6245 (list source
6246 (vector
6247 ;; Counter.
6248 (number-to-string (cl-incf counter))
6249 ;; Back-End.
6250 (if (nth 1 entry) (symbol-name (nth 1 entry)) "")
6251 ;; Age.
6252 (let ((info (nth 2 entry)))
6253 (if (processp info) (symbol-name (process-status info))
6254 (format-seconds "%h:%.2m" (float-time (time-since info)))))
6255 ;; Source.
6256 (if (stringp source) source (buffer-name source))))))
6257 org-export-stack-contents)))
6259 (defun org-export--stack-num-predicate (a b)
6260 (< (string-to-number (aref (nth 1 a) 0))
6261 (string-to-number (aref (nth 1 b) 0))))
6263 (defun org-export--stack-source-at-point ()
6264 "Return source from export results at point in stack."
6265 (let ((source (car (nth (1- (org-current-line)) org-export-stack-contents))))
6266 (if (not source) (error "Source unavailable, please refresh buffer")
6267 (let ((source-name (if (stringp source) source (buffer-name source))))
6268 (if (save-excursion
6269 (beginning-of-line)
6270 (looking-at-p (concat ".* +" (regexp-quote source-name) "$")))
6271 source
6272 ;; SOURCE is not consistent with current line. The stack
6273 ;; view is outdated.
6274 (error (substitute-command-keys
6275 "Source unavailable; type `\\[org-export-stack-refresh]' \
6276 to refresh buffer")))))))
6280 ;;; The Dispatcher
6282 ;; `org-export-dispatch' is the standard interactive way to start an
6283 ;; export process. It uses `org-export--dispatch-ui' as a subroutine
6284 ;; for its interface, which, in turn, delegates response to key
6285 ;; pressed to `org-export--dispatch-action'.
6287 ;;;###autoload
6288 (defun org-export-dispatch (&optional arg)
6289 "Export dispatcher for Org mode.
6291 It provides an access to common export related tasks in a buffer.
6292 Its interface comes in two flavors: standard and expert.
6294 While both share the same set of bindings, only the former
6295 displays the valid keys associations in a dedicated buffer.
6296 Scrolling (resp. line-wise motion) in this buffer is done with
6297 SPC and DEL (resp. C-n and C-p) keys.
6299 Set variable `org-export-dispatch-use-expert-ui' to switch to one
6300 flavor or the other.
6302 When ARG is `\\[universal-argument]', repeat the last export action, with the\
6303 same
6304 set of options used back then, on the current buffer.
6306 When ARG is `\\[universal-argument] \\[universal-argument]', display the \
6307 asynchronous export stack."
6308 (interactive "P")
6309 (let* ((input
6310 (cond ((equal arg '(16)) '(stack))
6311 ((and arg org-export-dispatch-last-action))
6312 (t (save-window-excursion
6313 (unwind-protect
6314 (progn
6315 ;; Remember where we are
6316 (move-marker org-export-dispatch-last-position
6317 (point)
6318 (org-base-buffer (current-buffer)))
6319 ;; Get and store an export command
6320 (setq org-export-dispatch-last-action
6321 (org-export--dispatch-ui
6322 (list org-export-initial-scope
6323 (and org-export-in-background 'async))
6325 org-export-dispatch-use-expert-ui)))
6326 (and (get-buffer "*Org Export Dispatcher*")
6327 (kill-buffer "*Org Export Dispatcher*")))))))
6328 (action (car input))
6329 (optns (cdr input)))
6330 (unless (memq 'subtree optns)
6331 (move-marker org-export-dispatch-last-position nil))
6332 (cl-case action
6333 ;; First handle special hard-coded actions.
6334 (template (org-export-insert-default-template nil optns))
6335 (stack (org-export-stack))
6336 (publish-current-file
6337 (org-publish-current-file (memq 'force optns) (memq 'async optns)))
6338 (publish-current-project
6339 (org-publish-current-project (memq 'force optns) (memq 'async optns)))
6340 (publish-choose-project
6341 (org-publish (assoc (completing-read
6342 "Publish project: "
6343 org-publish-project-alist nil t)
6344 org-publish-project-alist)
6345 (memq 'force optns)
6346 (memq 'async optns)))
6347 (publish-all (org-publish-all (memq 'force optns) (memq 'async optns)))
6348 (otherwise
6349 (save-excursion
6350 (when arg
6351 ;; Repeating command, maybe move cursor to restore subtree
6352 ;; context.
6353 (if (eq (marker-buffer org-export-dispatch-last-position)
6354 (org-base-buffer (current-buffer)))
6355 (goto-char org-export-dispatch-last-position)
6356 ;; We are in a different buffer, forget position.
6357 (move-marker org-export-dispatch-last-position nil)))
6358 (funcall action
6359 ;; Return a symbol instead of a list to ease
6360 ;; asynchronous export macro use.
6361 (and (memq 'async optns) t)
6362 (and (memq 'subtree optns) t)
6363 (and (memq 'visible optns) t)
6364 (and (memq 'body optns) t)))))))
6366 (defun org-export--dispatch-ui (options first-key expertp)
6367 "Handle interface for `org-export-dispatch'.
6369 OPTIONS is a list containing current interactive options set for
6370 export. It can contain any of the following symbols:
6371 `body' toggles a body-only export
6372 `subtree' restricts export to current subtree
6373 `visible' restricts export to visible part of buffer.
6374 `force' force publishing files.
6375 `async' use asynchronous export process
6377 FIRST-KEY is the key pressed to select the first level menu. It
6378 is nil when this menu hasn't been selected yet.
6380 EXPERTP, when non-nil, triggers expert UI. In that case, no help
6381 buffer is provided, but indications about currently active
6382 options are given in the prompt. Moreover, [?] allows switching
6383 back to standard interface."
6384 (let* ((fontify-key
6385 (lambda (key &optional access-key)
6386 ;; Fontify KEY string. Optional argument ACCESS-KEY, when
6387 ;; non-nil is the required first-level key to activate
6388 ;; KEY. When its value is t, activate KEY independently
6389 ;; on the first key, if any. A nil value means KEY will
6390 ;; only be activated at first level.
6391 (if (or (eq access-key t) (eq access-key first-key))
6392 (propertize key 'face 'org-warning)
6393 key)))
6394 (fontify-value
6395 (lambda (value)
6396 ;; Fontify VALUE string.
6397 (propertize value 'face 'font-lock-variable-name-face)))
6398 ;; Prepare menu entries by extracting them from registered
6399 ;; back-ends and sorting them by access key and by ordinal,
6400 ;; if any.
6401 (entries
6402 (sort (sort (delq nil
6403 (mapcar #'org-export-backend-menu
6404 org-export-registered-backends))
6405 (lambda (a b)
6406 (let ((key-a (nth 1 a))
6407 (key-b (nth 1 b)))
6408 (cond ((and (numberp key-a) (numberp key-b))
6409 (< key-a key-b))
6410 ((numberp key-b) t)))))
6411 'car-less-than-car))
6412 ;; Compute a list of allowed keys based on the first key
6413 ;; pressed, if any. Some keys
6414 ;; (?^B, ?^V, ?^S, ?^F, ?^A, ?&, ?# and ?q) are always
6415 ;; available.
6416 (allowed-keys
6417 (nconc (list 2 22 19 6 1)
6418 (if (not first-key) (org-uniquify (mapcar 'car entries))
6419 (let (sub-menu)
6420 (dolist (entry entries (sort (mapcar 'car sub-menu) '<))
6421 (when (eq (car entry) first-key)
6422 (setq sub-menu (append (nth 2 entry) sub-menu))))))
6423 (cond ((eq first-key ?P) (list ?f ?p ?x ?a))
6424 ((not first-key) (list ?P)))
6425 (list ?& ?#)
6426 (when expertp (list ??))
6427 (list ?q)))
6428 ;; Build the help menu for standard UI.
6429 (help
6430 (unless expertp
6431 (concat
6432 ;; Options are hard-coded.
6433 (format "[%s] Body only: %s [%s] Visible only: %s
6434 \[%s] Export scope: %s [%s] Force publishing: %s
6435 \[%s] Async export: %s\n\n"
6436 (funcall fontify-key "C-b" t)
6437 (funcall fontify-value
6438 (if (memq 'body options) "On " "Off"))
6439 (funcall fontify-key "C-v" t)
6440 (funcall fontify-value
6441 (if (memq 'visible options) "On " "Off"))
6442 (funcall fontify-key "C-s" t)
6443 (funcall fontify-value
6444 (if (memq 'subtree options) "Subtree" "Buffer "))
6445 (funcall fontify-key "C-f" t)
6446 (funcall fontify-value
6447 (if (memq 'force options) "On " "Off"))
6448 (funcall fontify-key "C-a" t)
6449 (funcall fontify-value
6450 (if (memq 'async options) "On " "Off")))
6451 ;; Display registered back-end entries. When a key
6452 ;; appears for the second time, do not create another
6453 ;; entry, but append its sub-menu to existing menu.
6454 (let (last-key)
6455 (mapconcat
6456 (lambda (entry)
6457 (let ((top-key (car entry)))
6458 (concat
6459 (unless (eq top-key last-key)
6460 (setq last-key top-key)
6461 (format "\n[%s] %s\n"
6462 (funcall fontify-key (char-to-string top-key))
6463 (nth 1 entry)))
6464 (let ((sub-menu (nth 2 entry)))
6465 (unless (functionp sub-menu)
6466 ;; Split sub-menu into two columns.
6467 (let ((index -1))
6468 (concat
6469 (mapconcat
6470 (lambda (sub-entry)
6471 (cl-incf index)
6472 (format
6473 (if (zerop (mod index 2)) " [%s] %-26s"
6474 "[%s] %s\n")
6475 (funcall fontify-key
6476 (char-to-string (car sub-entry))
6477 top-key)
6478 (nth 1 sub-entry)))
6479 sub-menu "")
6480 (when (zerop (mod index 2)) "\n"))))))))
6481 entries ""))
6482 ;; Publishing menu is hard-coded.
6483 (format "\n[%s] Publish
6484 [%s] Current file [%s] Current project
6485 [%s] Choose project [%s] All projects\n\n\n"
6486 (funcall fontify-key "P")
6487 (funcall fontify-key "f" ?P)
6488 (funcall fontify-key "p" ?P)
6489 (funcall fontify-key "x" ?P)
6490 (funcall fontify-key "a" ?P))
6491 (format "[%s] Export stack [%s] Insert template\n"
6492 (funcall fontify-key "&" t)
6493 (funcall fontify-key "#" t))
6494 (format "[%s] %s"
6495 (funcall fontify-key "q" t)
6496 (if first-key "Main menu" "Exit")))))
6497 ;; Build prompts for both standard and expert UI.
6498 (standard-prompt (unless expertp "Export command: "))
6499 (expert-prompt
6500 (when expertp
6501 (format
6502 "Export command (C-%s%s%s%s%s) [%s]: "
6503 (if (memq 'body options) (funcall fontify-key "b" t) "b")
6504 (if (memq 'visible options) (funcall fontify-key "v" t) "v")
6505 (if (memq 'subtree options) (funcall fontify-key "s" t) "s")
6506 (if (memq 'force options) (funcall fontify-key "f" t) "f")
6507 (if (memq 'async options) (funcall fontify-key "a" t) "a")
6508 (mapconcat (lambda (k)
6509 ;; Strip control characters.
6510 (unless (< k 27) (char-to-string k)))
6511 allowed-keys "")))))
6512 ;; With expert UI, just read key with a fancy prompt. In standard
6513 ;; UI, display an intrusive help buffer.
6514 (if expertp
6515 (org-export--dispatch-action
6516 expert-prompt allowed-keys entries options first-key expertp)
6517 ;; At first call, create frame layout in order to display menu.
6518 (unless (get-buffer "*Org Export Dispatcher*")
6519 (delete-other-windows)
6520 (org-switch-to-buffer-other-window
6521 (get-buffer-create "*Org Export Dispatcher*"))
6522 (setq cursor-type nil
6523 header-line-format "Use SPC, DEL, C-n or C-p to navigate.")
6524 ;; Make sure that invisible cursor will not highlight square
6525 ;; brackets.
6526 (set-syntax-table (copy-syntax-table))
6527 (modify-syntax-entry ?\[ "w"))
6528 ;; At this point, the buffer containing the menu exists and is
6529 ;; visible in the current window. So, refresh it.
6530 (with-current-buffer "*Org Export Dispatcher*"
6531 ;; Refresh help. Maintain display continuity by re-visiting
6532 ;; previous window position.
6533 (let ((pos (window-start)))
6534 (erase-buffer)
6535 (insert help)
6536 (set-window-start nil pos)))
6537 (org-fit-window-to-buffer)
6538 (org-export--dispatch-action
6539 standard-prompt allowed-keys entries options first-key expertp))))
6541 (defun org-export--dispatch-action
6542 (prompt allowed-keys entries options first-key expertp)
6543 "Read a character from command input and act accordingly.
6545 PROMPT is the displayed prompt, as a string. ALLOWED-KEYS is
6546 a list of characters available at a given step in the process.
6547 ENTRIES is a list of menu entries. OPTIONS, FIRST-KEY and
6548 EXPERTP are the same as defined in `org-export--dispatch-ui',
6549 which see.
6551 Toggle export options when required. Otherwise, return value is
6552 a list with action as CAR and a list of interactive export
6553 options as CDR."
6554 (let (key)
6555 ;; Scrolling: when in non-expert mode, act on motion keys (C-n,
6556 ;; C-p, SPC, DEL).
6557 (while (and (setq key (read-char-exclusive prompt))
6558 (not expertp)
6559 (memq key '(14 16 ?\s ?\d)))
6560 (cl-case key
6561 (14 (if (not (pos-visible-in-window-p (point-max)))
6562 (ignore-errors (scroll-up 1))
6563 (message "End of buffer")
6564 (sit-for 1)))
6565 (16 (if (not (pos-visible-in-window-p (point-min)))
6566 (ignore-errors (scroll-down 1))
6567 (message "Beginning of buffer")
6568 (sit-for 1)))
6569 (?\s (if (not (pos-visible-in-window-p (point-max)))
6570 (scroll-up nil)
6571 (message "End of buffer")
6572 (sit-for 1)))
6573 (?\d (if (not (pos-visible-in-window-p (point-min)))
6574 (scroll-down nil)
6575 (message "Beginning of buffer")
6576 (sit-for 1)))))
6577 (cond
6578 ;; Ignore undefined associations.
6579 ((not (memq key allowed-keys))
6580 (ding)
6581 (unless expertp (message "Invalid key") (sit-for 1))
6582 (org-export--dispatch-ui options first-key expertp))
6583 ;; q key at first level aborts export. At second level, cancel
6584 ;; first key instead.
6585 ((eq key ?q) (if (not first-key) (error "Export aborted")
6586 (org-export--dispatch-ui options nil expertp)))
6587 ;; Help key: Switch back to standard interface if expert UI was
6588 ;; active.
6589 ((eq key ??) (org-export--dispatch-ui options first-key nil))
6590 ;; Send request for template insertion along with export scope.
6591 ((eq key ?#) (cons 'template (memq 'subtree options)))
6592 ;; Switch to asynchronous export stack.
6593 ((eq key ?&) '(stack))
6594 ;; Toggle options: C-b (2) C-v (22) C-s (19) C-f (6) C-a (1).
6595 ((memq key '(2 22 19 6 1))
6596 (org-export--dispatch-ui
6597 (let ((option (cl-case key (2 'body) (22 'visible) (19 'subtree)
6598 (6 'force) (1 'async))))
6599 (if (memq option options) (remq option options)
6600 (cons option options)))
6601 first-key expertp))
6602 ;; Action selected: Send key and options back to
6603 ;; `org-export-dispatch'.
6604 ((or first-key (functionp (nth 2 (assq key entries))))
6605 (cons (cond
6606 ((not first-key) (nth 2 (assq key entries)))
6607 ;; Publishing actions are hard-coded. Send a special
6608 ;; signal to `org-export-dispatch'.
6609 ((eq first-key ?P)
6610 (cl-case key
6611 (?f 'publish-current-file)
6612 (?p 'publish-current-project)
6613 (?x 'publish-choose-project)
6614 (?a 'publish-all)))
6615 ;; Return first action associated to FIRST-KEY + KEY
6616 ;; path. Indeed, derived backends can share the same
6617 ;; FIRST-KEY.
6618 (t (catch 'found
6619 (dolist (entry (member (assq first-key entries) entries))
6620 (let ((match (assq key (nth 2 entry))))
6621 (when match (throw 'found (nth 2 match))))))))
6622 options))
6623 ;; Otherwise, enter sub-menu.
6624 (t (org-export--dispatch-ui options key expertp)))))
6628 (provide 'ox)
6630 ;; Local variables:
6631 ;; generated-autoload-file: "org-loaddefs.el"
6632 ;; End:
6634 ;;; ox.el ends here