org-clone-subtree-with-time-shift: Fix SHIFT check
[org-mode.git] / lisp / ox.el
blobf07116e2ff3d06144b52674048a703ba6649dc5c
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-publish "ox-publish" (project &optional force async))
81 (declare-function org-publish-all "ox-publish" (&optional force async))
82 (declare-function org-publish-current-file "ox-publish" (&optional force async))
83 (declare-function org-publish-current-project "ox-publish" (&optional force async))
84 (declare-function org-src-coderef-format "org-src" (&optional element))
85 (declare-function org-src-coderef-regexp "org-src" (fmt &optional label))
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 "25.2"
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 "25.2"
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 "25.2"
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 "25.2"
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 (defun org-export-get-backend (name)
1000 "Return export back-end named after NAME.
1001 NAME is a symbol. Return nil if no such back-end is found."
1002 (catch 'found
1003 (dolist (b org-export-registered-backends)
1004 (when (eq (org-export-backend-name b) name)
1005 (throw 'found b)))))
1007 (defun org-export-register-backend (backend)
1008 "Register BACKEND as a known export back-end.
1009 BACKEND is a structure with `org-export-backend' type."
1010 ;; Refuse to register an unnamed back-end.
1011 (unless (org-export-backend-name backend)
1012 (error "Cannot register a unnamed export back-end"))
1013 ;; Refuse to register a back-end with an unknown parent.
1014 (let ((parent (org-export-backend-parent backend)))
1015 (when (and parent (not (org-export-get-backend parent)))
1016 (error "Cannot use unknown \"%s\" back-end as a parent" parent)))
1017 ;; If a back-end with the same name as BACKEND is already
1018 ;; registered, replace it with BACKEND. Otherwise, simply add
1019 ;; BACKEND to the list of registered back-ends.
1020 (let ((old (org-export-get-backend (org-export-backend-name backend))))
1021 (if old (setcar (memq old org-export-registered-backends) backend)
1022 (push backend org-export-registered-backends))))
1024 (defun org-export-barf-if-invalid-backend (backend)
1025 "Signal an error if BACKEND isn't defined."
1026 (unless (org-export-backend-p backend)
1027 (error "Unknown \"%s\" back-end: Aborting export" backend)))
1029 (defun org-export-derived-backend-p (backend &rest backends)
1030 "Non-nil if BACKEND is derived from one of BACKENDS.
1031 BACKEND is an export back-end, as returned by, e.g.,
1032 `org-export-create-backend', or a symbol referring to
1033 a registered back-end. BACKENDS is constituted of symbols."
1034 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
1035 (when backend
1036 (catch 'exit
1037 (while (org-export-backend-parent backend)
1038 (when (memq (org-export-backend-name backend) backends)
1039 (throw 'exit t))
1040 (setq backend
1041 (org-export-get-backend (org-export-backend-parent backend))))
1042 (memq (org-export-backend-name backend) backends))))
1044 (defun org-export-get-all-transcoders (backend)
1045 "Return full translation table for BACKEND.
1047 BACKEND is an export back-end, as return by, e.g,,
1048 `org-export-create-backend'. Return value is an alist where
1049 keys are element or object types, as symbols, and values are
1050 transcoders.
1052 Unlike to `org-export-backend-transcoders', this function
1053 also returns transcoders inherited from parent back-ends,
1054 if any."
1055 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
1056 (when backend
1057 (let ((transcoders (org-export-backend-transcoders backend))
1058 parent)
1059 (while (setq parent (org-export-backend-parent backend))
1060 (setq backend (org-export-get-backend parent))
1061 (setq transcoders
1062 (append transcoders (org-export-backend-transcoders backend))))
1063 transcoders)))
1065 (defun org-export-get-all-options (backend)
1066 "Return export options for BACKEND.
1068 BACKEND is an export back-end, as return by, e.g,,
1069 `org-export-create-backend'. See `org-export-options-alist'
1070 for the shape of the return value.
1072 Unlike to `org-export-backend-options', this function also
1073 returns options inherited from parent back-ends, if any."
1074 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
1075 (when backend
1076 (let ((options (org-export-backend-options backend))
1077 parent)
1078 (while (setq parent (org-export-backend-parent backend))
1079 (setq backend (org-export-get-backend parent))
1080 (setq options (append options (org-export-backend-options backend))))
1081 options)))
1083 (defun org-export-get-all-filters (backend)
1084 "Return complete list of filters for BACKEND.
1086 BACKEND is an export back-end, as return by, e.g,,
1087 `org-export-create-backend'. Return value is an alist where
1088 keys are symbols and values lists of functions.
1090 Unlike to `org-export-backend-filters', this function also
1091 returns filters inherited from parent back-ends, if any."
1092 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
1093 (when backend
1094 (let ((filters (org-export-backend-filters backend))
1095 parent)
1096 (while (setq parent (org-export-backend-parent backend))
1097 (setq backend (org-export-get-backend parent))
1098 (setq filters (append filters (org-export-backend-filters backend))))
1099 filters)))
1101 (defun org-export-define-backend (backend transcoders &rest body)
1102 "Define a new back-end BACKEND.
1104 TRANSCODERS is an alist between object or element types and
1105 functions handling them.
1107 These functions should return a string without any trailing
1108 space, or nil. They must accept three arguments: the object or
1109 element itself, its contents or nil when it isn't recursive and
1110 the property list used as a communication channel.
1112 Contents, when not nil, are stripped from any global indentation
1113 \(although the relative one is preserved). They also always end
1114 with a single newline character.
1116 If, for a given type, no function is found, that element or
1117 object type will simply be ignored, along with any blank line or
1118 white space at its end. The same will happen if the function
1119 returns the nil value. If that function returns the empty
1120 string, the type will be ignored, but the blank lines or white
1121 spaces will be kept.
1123 In addition to element and object types, one function can be
1124 associated to the `template' (or `inner-template') symbol and
1125 another one to the `plain-text' symbol.
1127 The former returns the final transcoded string, and can be used
1128 to add a preamble and a postamble to document's body. It must
1129 accept two arguments: the transcoded string and the property list
1130 containing export options. A function associated to `template'
1131 will not be applied if export has option \"body-only\".
1132 A function associated to `inner-template' is always applied.
1134 The latter, when defined, is to be called on every text not
1135 recognized as an element or an object. It must accept two
1136 arguments: the text string and the information channel. It is an
1137 appropriate place to protect special chars relative to the
1138 back-end.
1140 BODY can start with pre-defined keyword arguments. The following
1141 keywords are understood:
1143 :filters-alist
1145 Alist between filters and function, or list of functions,
1146 specific to the back-end. See `org-export-filters-alist' for
1147 a list of all allowed filters. Filters defined here
1148 shouldn't make a back-end test, as it may prevent back-ends
1149 derived from this one to behave properly.
1151 :menu-entry
1153 Menu entry for the export dispatcher. It should be a list
1154 like:
1156 \\='(KEY DESCRIPTION-OR-ORDINAL ACTION-OR-MENU)
1158 where :
1160 KEY is a free character selecting the back-end.
1162 DESCRIPTION-OR-ORDINAL is either a string or a number.
1164 If it is a string, is will be used to name the back-end in
1165 its menu entry. If it is a number, the following menu will
1166 be displayed as a sub-menu of the back-end with the same
1167 KEY. Also, the number will be used to determine in which
1168 order such sub-menus will appear (lowest first).
1170 ACTION-OR-MENU is either a function or an alist.
1172 If it is an action, it will be called with four
1173 arguments (booleans): ASYNC, SUBTREEP, VISIBLE-ONLY and
1174 BODY-ONLY. See `org-export-as' for further explanations on
1175 some of them.
1177 If it is an alist, associations should follow the
1178 pattern:
1180 \\='(KEY DESCRIPTION ACTION)
1182 where KEY, DESCRIPTION and ACTION are described above.
1184 Valid values include:
1186 \\='(?m \"My Special Back-end\" my-special-export-function)
1190 \\='(?l \"Export to LaTeX\"
1191 (?p \"As PDF file\" org-latex-export-to-pdf)
1192 (?o \"As PDF file and open\"
1193 (lambda (a s v b)
1194 (if a (org-latex-export-to-pdf t s v b)
1195 (org-open-file
1196 (org-latex-export-to-pdf nil s v b)))))))
1198 or the following, which will be added to the previous
1199 sub-menu,
1201 \\='(?l 1
1202 ((?B \"As TEX buffer (Beamer)\" org-beamer-export-as-latex)
1203 (?P \"As PDF file (Beamer)\" org-beamer-export-to-pdf)))
1205 :options-alist
1207 Alist between back-end specific properties introduced in
1208 communication channel and how their value are acquired. See
1209 `org-export-options-alist' for more information about
1210 structure of the values."
1211 (declare (indent 1))
1212 (let (filters menu-entry options)
1213 (while (keywordp (car body))
1214 (let ((keyword (pop body)))
1215 (pcase keyword
1216 (:filters-alist (setq filters (pop body)))
1217 (:menu-entry (setq menu-entry (pop body)))
1218 (:options-alist (setq options (pop body)))
1219 (_ (error "Unknown keyword: %s" keyword)))))
1220 (org-export-register-backend
1221 (org-export-create-backend :name backend
1222 :transcoders transcoders
1223 :options options
1224 :filters filters
1225 :menu menu-entry))))
1227 (defun org-export-define-derived-backend (child parent &rest body)
1228 "Create a new back-end as a variant of an existing one.
1230 CHILD is the name of the derived back-end. PARENT is the name of
1231 the parent back-end.
1233 BODY can start with pre-defined keyword arguments. The following
1234 keywords are understood:
1236 :filters-alist
1238 Alist of filters that will overwrite or complete filters
1239 defined in PARENT back-end. See `org-export-filters-alist'
1240 for a list of allowed filters.
1242 :menu-entry
1244 Menu entry for the export dispatcher. See
1245 `org-export-define-backend' for more information about the
1246 expected value.
1248 :options-alist
1250 Alist of back-end specific properties that will overwrite or
1251 complete those defined in PARENT back-end. Refer to
1252 `org-export-options-alist' for more information about
1253 structure of the values.
1255 :translate-alist
1257 Alist of element and object types and transcoders that will
1258 overwrite or complete transcode table from PARENT back-end.
1259 Refer to `org-export-define-backend' for detailed information
1260 about transcoders.
1262 As an example, here is how one could define \"my-latex\" back-end
1263 as a variant of `latex' back-end with a custom template function:
1265 (org-export-define-derived-backend \\='my-latex \\='latex
1266 :translate-alist \\='((template . my-latex-template-fun)))
1268 The back-end could then be called with, for example:
1270 (org-export-to-buffer \\='my-latex \"*Test my-latex*\")"
1271 (declare (indent 2))
1272 (let (filters menu-entry options transcoders)
1273 (while (keywordp (car body))
1274 (let ((keyword (pop body)))
1275 (pcase keyword
1276 (:filters-alist (setq filters (pop body)))
1277 (:menu-entry (setq menu-entry (pop body)))
1278 (:options-alist (setq options (pop body)))
1279 (:translate-alist (setq transcoders (pop body)))
1280 (_ (error "Unknown keyword: %s" keyword)))))
1281 (org-export-register-backend
1282 (org-export-create-backend :name child
1283 :parent parent
1284 :transcoders transcoders
1285 :options options
1286 :filters filters
1287 :menu menu-entry))))
1291 ;;; The Communication Channel
1293 ;; During export process, every function has access to a number of
1294 ;; properties. They are of two types:
1296 ;; 1. Environment options are collected once at the very beginning of
1297 ;; the process, out of the original buffer and configuration.
1298 ;; Collecting them is handled by `org-export-get-environment'
1299 ;; function.
1301 ;; Most environment options are defined through the
1302 ;; `org-export-options-alist' variable.
1304 ;; 2. Tree properties are extracted directly from the parsed tree,
1305 ;; just before export, by `org-export--collect-tree-properties'.
1307 ;;;; Environment Options
1309 ;; Environment options encompass all parameters defined outside the
1310 ;; scope of the parsed data. They come from five sources, in
1311 ;; increasing precedence order:
1313 ;; - Global variables,
1314 ;; - Buffer's attributes,
1315 ;; - Options keyword symbols,
1316 ;; - Buffer keywords,
1317 ;; - Subtree properties.
1319 ;; The central internal function with regards to environment options
1320 ;; is `org-export-get-environment'. It updates global variables with
1321 ;; "#+BIND:" keywords, then retrieve and prioritize properties from
1322 ;; the different sources.
1324 ;; The internal functions doing the retrieval are:
1325 ;; `org-export--get-global-options',
1326 ;; `org-export--get-buffer-attributes',
1327 ;; `org-export--parse-option-keyword',
1328 ;; `org-export--get-subtree-options' and
1329 ;; `org-export--get-inbuffer-options'
1331 ;; Also, `org-export--list-bound-variables' collects bound variables
1332 ;; along with their value in order to set them as buffer local
1333 ;; variables later in the process.
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-match-p "\\`//" filename) (concat "file:" filename))
4327 ((not (file-name-absolute-p filename)) filename)
4328 ((org-file-remote-p filename) (concat "file:/" filename))
4329 (t (concat "file://" (expand-file-name filename)))))
4332 ;;;; For References
4334 ;; `org-export-get-reference' associate a unique reference for any
4335 ;; object or element. It uses `org-export-new-reference' and
4336 ;; `org-export-format-reference' to, respectively, generate new
4337 ;; internal references and turn them into a string suitable for
4338 ;; output.
4340 ;; `org-export-get-ordinal' associates a sequence number to any object
4341 ;; or element.
4343 (defun org-export-new-reference (references)
4344 "Return a unique reference, among REFERENCES.
4345 REFERENCES is an alist whose values are in-use references, as
4346 numbers. Returns a number, which is the internal representation
4347 of a reference. See also `org-export-format-reference'."
4348 ;; Generate random 7 digits hexadecimal numbers. Collisions
4349 ;; increase exponentially with the numbers of references. However,
4350 ;; the odds for encountering at least one collision with 1000 active
4351 ;; references in the same document are roughly 0.2%, so this
4352 ;; shouldn't be the bottleneck.
4353 (let ((new (random #x10000000)))
4354 (while (rassq new references) (setq new (random #x10000000)))
4355 new))
4357 (defun org-export-format-reference (reference)
4358 "Format REFERENCE into a string.
4359 REFERENCE is a number representing a reference, as returned by
4360 `org-export-new-reference', which see."
4361 (format "org%07x" reference))
4363 (defun org-export-get-reference (datum info)
4364 "Return a unique reference for DATUM, as a string.
4366 DATUM is either an element or an object. INFO is the current
4367 export state, as a plist.
4369 This function checks `:crossrefs' property in INFO for search
4370 cells matching DATUM before creating a new reference. Returned
4371 reference consists of alphanumeric characters only."
4372 (let ((cache (plist-get info :internal-references)))
4373 (or (car (rassq datum cache))
4374 (let* ((crossrefs (plist-get info :crossrefs))
4375 (cells (org-export-search-cells datum))
4376 ;; Preserve any pre-existing association between
4377 ;; a search cell and a reference, i.e., when some
4378 ;; previously published document referenced a location
4379 ;; within current file (see
4380 ;; `org-publish-resolve-external-link').
4382 ;; However, there is no guarantee that search cells are
4383 ;; unique, e.g., there might be duplicate custom ID or
4384 ;; two headings with the same title in the file.
4386 ;; As a consequence, before re-using any reference to
4387 ;; an element or object, we check that it doesn't refer
4388 ;; to a previous element or object.
4389 (new (or (cl-some
4390 (lambda (cell)
4391 (let ((stored (cdr (assoc cell crossrefs))))
4392 (when stored
4393 (let ((old (org-export-format-reference stored)))
4394 (and (not (assoc old cache)) stored)))))
4395 cells)
4396 (org-export-new-reference cache)))
4397 (reference-string (org-export-format-reference new)))
4398 ;; Cache contains both data already associated to
4399 ;; a reference and in-use internal references, so as to make
4400 ;; unique references.
4401 (dolist (cell cells) (push (cons cell new) cache))
4402 ;; Retain a direct association between reference string and
4403 ;; DATUM since (1) not every object or element can be given
4404 ;; a search cell (2) it permits quick lookup.
4405 (push (cons reference-string datum) cache)
4406 (plist-put info :internal-references cache)
4407 reference-string))))
4409 (defun org-export-get-ordinal (element info &optional types predicate)
4410 "Return ordinal number of an element or object.
4412 ELEMENT is the element or object considered. INFO is the plist
4413 used as a communication channel.
4415 Optional argument TYPES, when non-nil, is a list of element or
4416 object types, as symbols, that should also be counted in.
4417 Otherwise, only provided element's type is considered.
4419 Optional argument PREDICATE is a function returning a non-nil
4420 value if the current element or object should be counted in. It
4421 accepts two arguments: the element or object being considered and
4422 the plist used as a communication channel. This allows counting
4423 only a certain type of object (i.e. inline images).
4425 Return value is a list of numbers if ELEMENT is a headline or an
4426 item. It is nil for keywords. It represents the footnote number
4427 for footnote definitions and footnote references. If ELEMENT is
4428 a target, return the same value as if ELEMENT was the closest
4429 table, item or headline containing the target. In any other
4430 case, return the sequence number of ELEMENT among elements or
4431 objects of the same type."
4432 ;; Ordinal of a target object refer to the ordinal of the closest
4433 ;; table, item, or headline containing the object.
4434 (when (eq (org-element-type element) 'target)
4435 (setq element
4436 (org-element-lineage
4437 element
4438 '(footnote-definition footnote-reference headline item table))))
4439 (cl-case (org-element-type element)
4440 ;; Special case 1: A headline returns its number as a list.
4441 (headline (org-export-get-headline-number element info))
4442 ;; Special case 2: An item returns its number as a list.
4443 (item (let ((struct (org-element-property :structure element)))
4444 (org-list-get-item-number
4445 (org-element-property :begin element)
4446 struct
4447 (org-list-prevs-alist struct)
4448 (org-list-parents-alist struct))))
4449 ((footnote-definition footnote-reference)
4450 (org-export-get-footnote-number element info))
4451 (otherwise
4452 (let ((counter 0))
4453 ;; Increment counter until ELEMENT is found again.
4454 (org-element-map (plist-get info :parse-tree)
4455 (or types (org-element-type element))
4456 (lambda (el)
4457 (cond
4458 ((eq element el) (1+ counter))
4459 ((not predicate) (cl-incf counter) nil)
4460 ((funcall predicate el info) (cl-incf counter) nil)))
4461 info 'first-match)))))
4464 ;;;; For Src-Blocks
4466 ;; `org-export-get-loc' counts number of code lines accumulated in
4467 ;; src-block or example-block elements with a "+n" switch until
4468 ;; a given element, excluded. Note: "-n" switches reset that count.
4470 ;; `org-export-unravel-code' extracts source code (along with a code
4471 ;; references alist) from an `element-block' or `src-block' type
4472 ;; element.
4474 ;; `org-export-format-code' applies a formatting function to each line
4475 ;; of code, providing relative line number and code reference when
4476 ;; appropriate. Since it doesn't access the original element from
4477 ;; which the source code is coming, it expects from the code calling
4478 ;; it to know if lines should be numbered and if code references
4479 ;; should appear.
4481 ;; Eventually, `org-export-format-code-default' is a higher-level
4482 ;; function (it makes use of the two previous functions) which handles
4483 ;; line numbering and code references inclusion, and returns source
4484 ;; code in a format suitable for plain text or verbatim output.
4486 (defun org-export-get-loc (element info)
4487 "Return count of lines of code before ELEMENT.
4489 ELEMENT is an example-block or src-block element. INFO is the
4490 plist used as a communication channel.
4492 Count includes every line of code in example-block or src-block
4493 with a \"+n\" or \"-n\" switch before block. Return nil if
4494 ELEMENT doesn't allow line numbering."
4495 (pcase (org-element-property :number-lines element)
4496 (`(new . ,n) n)
4497 (`(continued . ,n)
4498 (let ((loc 0))
4499 (org-element-map (plist-get info :parse-tree) '(src-block example-block)
4500 (lambda (el)
4501 ;; ELEMENT is reached: Quit loop and return locs.
4502 (if (eq el element) (+ loc n)
4503 ;; Only count lines from src-block and example-block
4504 ;; elements with a "+n" or "-n" switch.
4505 (let ((linum (org-element-property :number-lines el)))
4506 (when linum
4507 (let ((lines (org-count-lines
4508 (org-trim (org-element-property :value el)))))
4509 ;; Accumulate locs or reset them.
4510 (pcase linum
4511 (`(new . ,n) (setq loc (+ n lines)))
4512 (`(continued . ,n) (cl-incf loc (+ n lines)))))))
4513 nil)) ;Return nil to stay in the loop.
4514 info 'first-match)))))
4516 (defun org-export-unravel-code (element)
4517 "Clean source code and extract references out of it.
4519 ELEMENT has either a `src-block' an `example-block' type.
4521 Return a cons cell whose CAR is the source code, cleaned from any
4522 reference, protective commas and spurious indentation, and CDR is
4523 an alist between relative line number (integer) and name of code
4524 reference on that line (string)."
4525 (let* ((line 0) refs
4526 (value (org-element-property :value element))
4527 ;; Get code and clean it. Remove blank lines at its
4528 ;; beginning and end.
4529 (code (replace-regexp-in-string
4530 "\\`\\([ \t]*\n\\)+" ""
4531 (replace-regexp-in-string
4532 "\\([ \t]*\n\\)*[ \t]*\\'" "\n"
4533 (if (or org-src-preserve-indentation
4534 (org-element-property :preserve-indent element))
4535 value
4536 (org-remove-indentation value)))))
4537 ;; Build a regexp matching a loc with a reference.
4538 (ref-re (org-src-coderef-regexp (org-src-coderef-format element))))
4539 ;; Return value.
4540 (cons
4541 ;; Code with references removed.
4542 (org-element-normalize-string
4543 (mapconcat
4544 (lambda (loc)
4545 (cl-incf line)
4546 (if (not (string-match ref-re loc)) loc
4547 ;; Ref line: remove ref, and signal its position in REFS.
4548 (push (cons line (match-string 3 loc)) refs)
4549 (replace-match "" nil nil loc 1)))
4550 (org-split-string code "\n") "\n"))
4551 ;; Reference alist.
4552 refs)))
4554 (defun org-export-format-code (code fun &optional num-lines ref-alist)
4555 "Format CODE by applying FUN line-wise and return it.
4557 CODE is a string representing the code to format. FUN is
4558 a function. It must accept three arguments: a line of
4559 code (string), the current line number (integer) or nil and the
4560 reference associated to the current line (string) or nil.
4562 Optional argument NUM-LINES can be an integer representing the
4563 number of code lines accumulated until the current code. Line
4564 numbers passed to FUN will take it into account. If it is nil,
4565 FUN's second argument will always be nil. This number can be
4566 obtained with `org-export-get-loc' function.
4568 Optional argument REF-ALIST can be an alist between relative line
4569 number (i.e. ignoring NUM-LINES) and the name of the code
4570 reference on it. If it is nil, FUN's third argument will always
4571 be nil. It can be obtained through the use of
4572 `org-export-unravel-code' function."
4573 (let ((--locs (org-split-string code "\n"))
4574 (--line 0))
4575 (org-element-normalize-string
4576 (mapconcat
4577 (lambda (--loc)
4578 (cl-incf --line)
4579 (let ((--ref (cdr (assq --line ref-alist))))
4580 (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
4581 --locs "\n"))))
4583 (defun org-export-format-code-default (element info)
4584 "Return source code from ELEMENT, formatted in a standard way.
4586 ELEMENT is either a `src-block' or `example-block' element. INFO
4587 is a plist used as a communication channel.
4589 This function takes care of line numbering and code references
4590 inclusion. Line numbers, when applicable, appear at the
4591 beginning of the line, separated from the code by two white
4592 spaces. Code references, on the other hand, appear flushed to
4593 the right, separated by six white spaces from the widest line of
4594 code."
4595 ;; Extract code and references.
4596 (let* ((code-info (org-export-unravel-code element))
4597 (code (car code-info))
4598 (code-lines (org-split-string code "\n")))
4599 (if (null code-lines) ""
4600 (let* ((refs (and (org-element-property :retain-labels element)
4601 (cdr code-info)))
4602 ;; Handle line numbering.
4603 (num-start (org-export-get-loc element info))
4604 (num-fmt
4605 (and num-start
4606 (format "%%%ds "
4607 (length (number-to-string
4608 (+ (length code-lines) num-start))))))
4609 ;; Prepare references display, if required. Any reference
4610 ;; should start six columns after the widest line of code,
4611 ;; wrapped with parenthesis.
4612 (max-width
4613 (+ (apply 'max (mapcar 'length code-lines))
4614 (if (not num-start) 0 (length (format num-fmt num-start))))))
4615 (org-export-format-code
4616 code
4617 (lambda (loc line-num ref)
4618 (let ((number-str (and num-fmt (format num-fmt line-num))))
4619 (concat
4620 number-str
4622 (and ref
4623 (concat (make-string
4624 (- (+ 6 max-width)
4625 (+ (length loc) (length number-str))) ? )
4626 (format "(%s)" ref))))))
4627 num-start refs)))))
4630 ;;;; For Tables
4632 ;; `org-export-table-has-special-column-p' and and
4633 ;; `org-export-table-row-is-special-p' are predicates used to look for
4634 ;; meta-information about the table structure.
4636 ;; `org-table-has-header-p' tells when the rows before the first rule
4637 ;; should be considered as table's header.
4639 ;; `org-export-table-cell-width', `org-export-table-cell-alignment'
4640 ;; and `org-export-table-cell-borders' extract information from
4641 ;; a table-cell element.
4643 ;; `org-export-table-dimensions' gives the number on rows and columns
4644 ;; in the table, ignoring horizontal rules and special columns.
4645 ;; `org-export-table-cell-address', given a table-cell object, returns
4646 ;; the absolute address of a cell. On the other hand,
4647 ;; `org-export-get-table-cell-at' does the contrary.
4649 ;; `org-export-table-cell-starts-colgroup-p',
4650 ;; `org-export-table-cell-ends-colgroup-p',
4651 ;; `org-export-table-row-starts-rowgroup-p',
4652 ;; `org-export-table-row-ends-rowgroup-p',
4653 ;; `org-export-table-row-starts-header-p',
4654 ;; `org-export-table-row-ends-header-p' and
4655 ;; `org-export-table-row-in-header-p' indicate position of current row
4656 ;; or cell within the table.
4658 (defun org-export-table-has-special-column-p (table)
4659 "Non-nil when TABLE has a special column.
4660 All special columns will be ignored during export."
4661 ;; The table has a special column when every first cell of every row
4662 ;; has an empty value or contains a symbol among "/", "#", "!", "$",
4663 ;; "*" "_" and "^". Though, do not consider a first row containing
4664 ;; only empty cells as special.
4665 (let ((special-column-p 'empty))
4666 (catch 'exit
4667 (dolist (row (org-element-contents table))
4668 (when (eq (org-element-property :type row) 'standard)
4669 (let ((value (org-element-contents
4670 (car (org-element-contents row)))))
4671 (cond ((member value '(("/") ("#") ("!") ("$") ("*") ("_") ("^")))
4672 (setq special-column-p 'special))
4673 ((not value))
4674 (t (throw 'exit nil))))))
4675 (eq special-column-p 'special))))
4677 (defun org-export-table-has-header-p (table info)
4678 "Non-nil when TABLE has a header.
4680 INFO is a plist used as a communication channel.
4682 A table has a header when it contains at least two row groups."
4683 (let ((cache (or (plist-get info :table-header-cache)
4684 (plist-get (setq info
4685 (plist-put info :table-header-cache
4686 (make-hash-table :test 'eq)))
4687 :table-header-cache))))
4688 (or (gethash table cache)
4689 (let ((rowgroup 1) row-flag)
4690 (puthash
4691 table
4692 (org-element-map table 'table-row
4693 (lambda (row)
4694 (cond
4695 ((> rowgroup 1) t)
4696 ((and row-flag (eq (org-element-property :type row) 'rule))
4697 (cl-incf rowgroup) (setq row-flag nil))
4698 ((and (not row-flag) (eq (org-element-property :type row)
4699 'standard))
4700 (setq row-flag t) nil)))
4701 info 'first-match)
4702 cache)))))
4704 (defun org-export-table-row-is-special-p (table-row _)
4705 "Non-nil if TABLE-ROW is considered special.
4706 All special rows will be ignored during export."
4707 (when (eq (org-element-property :type table-row) 'standard)
4708 (let ((first-cell (org-element-contents
4709 (car (org-element-contents table-row)))))
4710 ;; A row is special either when...
4712 ;; ... it starts with a field only containing "/",
4713 (equal first-cell '("/"))
4714 ;; ... the table contains a special column and the row start
4715 ;; with a marking character among, "^", "_", "$" or "!",
4716 (and (org-export-table-has-special-column-p
4717 (org-export-get-parent table-row))
4718 (member first-cell '(("^") ("_") ("$") ("!"))))
4719 ;; ... it contains only alignment cookies and empty cells.
4720 (let ((special-row-p 'empty))
4721 (catch 'exit
4722 (dolist (cell (org-element-contents table-row))
4723 (let ((value (org-element-contents cell)))
4724 ;; Since VALUE is a secondary string, the following
4725 ;; checks avoid expanding it with `org-export-data'.
4726 (cond ((not value))
4727 ((and (not (cdr value))
4728 (stringp (car value))
4729 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'"
4730 (car value)))
4731 (setq special-row-p 'cookie))
4732 (t (throw 'exit nil)))))
4733 (eq special-row-p 'cookie)))))))
4735 (defun org-export-table-row-group (table-row info)
4736 "Return TABLE-ROW's group number, as an integer.
4738 INFO is a plist used as the communication channel.
4740 Return value is the group number, as an integer, or nil for
4741 special rows and rows separators. First group is also table's
4742 header."
4743 (let ((cache (or (plist-get info :table-row-group-cache)
4744 (plist-get (setq info
4745 (plist-put info :table-row-group-cache
4746 (make-hash-table :test 'eq)))
4747 :table-row-group-cache))))
4748 (cond ((gethash table-row cache))
4749 ((eq (org-element-property :type table-row) 'rule) nil)
4750 (t (let ((group 0) row-flag)
4751 (org-element-map (org-export-get-parent table-row) 'table-row
4752 (lambda (row)
4753 (if (eq (org-element-property :type row) 'rule)
4754 (setq row-flag nil)
4755 (unless row-flag (cl-incf group) (setq row-flag t)))
4756 (when (eq table-row row) (puthash table-row group cache)))
4757 info 'first-match))))))
4759 (defun org-export-table-cell-width (table-cell info)
4760 "Return TABLE-CELL contents width.
4762 INFO is a plist used as the communication channel.
4764 Return value is the width given by the last width cookie in the
4765 same column as TABLE-CELL, or nil."
4766 (let* ((row (org-export-get-parent table-cell))
4767 (table (org-export-get-parent row))
4768 (cells (org-element-contents row))
4769 (columns (length cells))
4770 (column (- columns (length (memq table-cell cells))))
4771 (cache (or (plist-get info :table-cell-width-cache)
4772 (plist-get (setq info
4773 (plist-put info :table-cell-width-cache
4774 (make-hash-table :test 'eq)))
4775 :table-cell-width-cache)))
4776 (width-vector (or (gethash table cache)
4777 (puthash table (make-vector columns 'empty) cache)))
4778 (value (aref width-vector column)))
4779 (if (not (eq value 'empty)) value
4780 (let (cookie-width)
4781 (dolist (row (org-element-contents table)
4782 (aset width-vector column cookie-width))
4783 (when (org-export-table-row-is-special-p row info)
4784 ;; In a special row, try to find a width cookie at COLUMN.
4785 (let* ((value (org-element-contents
4786 (elt (org-element-contents row) column)))
4787 (cookie (car value)))
4788 ;; The following checks avoid expanding unnecessarily
4789 ;; the cell with `org-export-data'.
4790 (when (and value
4791 (not (cdr value))
4792 (stringp cookie)
4793 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'" cookie)
4794 (match-string 1 cookie))
4795 (setq cookie-width
4796 (string-to-number (match-string 1 cookie)))))))))))
4798 (defun org-export-table-cell-alignment (table-cell info)
4799 "Return TABLE-CELL contents alignment.
4801 INFO is a plist used as the communication channel.
4803 Return alignment as specified by the last alignment cookie in the
4804 same column as TABLE-CELL. If no such cookie is found, a default
4805 alignment value will be deduced from fraction of numbers in the
4806 column (see `org-table-number-fraction' for more information).
4807 Possible values are `left', `right' and `center'."
4808 ;; Load `org-table-number-fraction' and `org-table-number-regexp'.
4809 (require 'org-table)
4810 (let* ((row (org-export-get-parent table-cell))
4811 (table (org-export-get-parent row))
4812 (cells (org-element-contents row))
4813 (columns (length cells))
4814 (column (- columns (length (memq table-cell cells))))
4815 (cache (or (plist-get info :table-cell-alignment-cache)
4816 (plist-get (setq info
4817 (plist-put info :table-cell-alignment-cache
4818 (make-hash-table :test 'eq)))
4819 :table-cell-alignment-cache)))
4820 (align-vector (or (gethash table cache)
4821 (puthash table (make-vector columns nil) cache))))
4822 (or (aref align-vector column)
4823 (let ((number-cells 0)
4824 (total-cells 0)
4825 cookie-align
4826 previous-cell-number-p)
4827 (dolist (row (org-element-contents (org-export-get-parent row)))
4828 (cond
4829 ;; In a special row, try to find an alignment cookie at
4830 ;; COLUMN.
4831 ((org-export-table-row-is-special-p row info)
4832 (let ((value (org-element-contents
4833 (elt (org-element-contents row) column))))
4834 ;; Since VALUE is a secondary string, the following
4835 ;; checks avoid useless expansion through
4836 ;; `org-export-data'.
4837 (when (and value
4838 (not (cdr value))
4839 (stringp (car value))
4840 (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'"
4841 (car value))
4842 (match-string 1 (car value)))
4843 (setq cookie-align (match-string 1 (car value))))))
4844 ;; Ignore table rules.
4845 ((eq (org-element-property :type row) 'rule))
4846 ;; In a standard row, check if cell's contents are
4847 ;; expressing some kind of number. Increase NUMBER-CELLS
4848 ;; accordingly. Though, don't bother if an alignment
4849 ;; cookie has already defined cell's alignment.
4850 ((not cookie-align)
4851 (let ((value (org-export-data
4852 (org-element-contents
4853 (elt (org-element-contents row) column))
4854 info)))
4855 (cl-incf total-cells)
4856 ;; Treat an empty cell as a number if it follows
4857 ;; a number.
4858 (if (not (or (string-match org-table-number-regexp value)
4859 (and (string= value "") previous-cell-number-p)))
4860 (setq previous-cell-number-p nil)
4861 (setq previous-cell-number-p t)
4862 (cl-incf number-cells))))))
4863 ;; Return value. Alignment specified by cookies has
4864 ;; precedence over alignment deduced from cell's contents.
4865 (aset align-vector
4866 column
4867 (cond ((equal cookie-align "l") 'left)
4868 ((equal cookie-align "r") 'right)
4869 ((equal cookie-align "c") 'center)
4870 ((>= (/ (float number-cells) total-cells)
4871 org-table-number-fraction)
4872 'right)
4873 (t 'left)))))))
4875 (defun org-export-table-cell-borders (table-cell info)
4876 "Return TABLE-CELL borders.
4878 INFO is a plist used as a communication channel.
4880 Return value is a list of symbols, or nil. Possible values are:
4881 `top', `bottom', `above', `below', `left' and `right'. Note:
4882 `top' (resp. `bottom') only happen for a cell in the first
4883 row (resp. last row) of the table, ignoring table rules, if any.
4885 Returned borders ignore special rows."
4886 (let* ((row (org-export-get-parent table-cell))
4887 (table (org-export-get-parent-table table-cell))
4888 borders)
4889 ;; Top/above border? TABLE-CELL has a border above when a rule
4890 ;; used to demarcate row groups can be found above. Hence,
4891 ;; finding a rule isn't sufficient to push `above' in BORDERS:
4892 ;; another regular row has to be found above that rule.
4893 (let (rule-flag)
4894 (catch 'exit
4895 ;; Look at every row before the current one.
4896 (dolist (row (cdr (memq row (reverse (org-element-contents table)))))
4897 (cond ((eq (org-element-property :type row) 'rule)
4898 (setq rule-flag t))
4899 ((not (org-export-table-row-is-special-p row info))
4900 (if rule-flag (throw 'exit (push 'above borders))
4901 (throw 'exit nil)))))
4902 ;; No rule above, or rule found starts the table (ignoring any
4903 ;; special row): TABLE-CELL is at the top of the table.
4904 (when rule-flag (push 'above borders))
4905 (push 'top borders)))
4906 ;; Bottom/below border? TABLE-CELL has a border below when next
4907 ;; non-regular row below is a rule.
4908 (let (rule-flag)
4909 (catch 'exit
4910 ;; Look at every row after the current one.
4911 (dolist (row (cdr (memq row (org-element-contents table))))
4912 (cond ((eq (org-element-property :type row) 'rule)
4913 (setq rule-flag t))
4914 ((not (org-export-table-row-is-special-p row info))
4915 (if rule-flag (throw 'exit (push 'below borders))
4916 (throw 'exit nil)))))
4917 ;; No rule below, or rule found ends the table (modulo some
4918 ;; special row): TABLE-CELL is at the bottom of the table.
4919 (when rule-flag (push 'below borders))
4920 (push 'bottom borders)))
4921 ;; Right/left borders? They can only be specified by column
4922 ;; groups. Column groups are defined in a row starting with "/".
4923 ;; Also a column groups row only contains "<", "<>", ">" or blank
4924 ;; cells.
4925 (catch 'exit
4926 (let ((column (let ((cells (org-element-contents row)))
4927 (- (length cells) (length (memq table-cell cells))))))
4928 ;; Table rows are read in reverse order so last column groups
4929 ;; row has precedence over any previous one.
4930 (dolist (row (reverse (org-element-contents table)))
4931 (unless (eq (org-element-property :type row) 'rule)
4932 (when (equal (org-element-contents
4933 (car (org-element-contents row)))
4934 '("/"))
4935 (let ((column-groups
4936 (mapcar
4937 (lambda (cell)
4938 (let ((value (org-element-contents cell)))
4939 (when (member value '(("<") ("<>") (">") nil))
4940 (car value))))
4941 (org-element-contents row))))
4942 ;; There's a left border when previous cell, if
4943 ;; any, ends a group, or current one starts one.
4944 (when (or (and (not (zerop column))
4945 (member (elt column-groups (1- column))
4946 '(">" "<>")))
4947 (member (elt column-groups column) '("<" "<>")))
4948 (push 'left borders))
4949 ;; There's a right border when next cell, if any,
4950 ;; starts a group, or current one ends one.
4951 (when (or (and (/= (1+ column) (length column-groups))
4952 (member (elt column-groups (1+ column))
4953 '("<" "<>")))
4954 (member (elt column-groups column) '(">" "<>")))
4955 (push 'right borders))
4956 (throw 'exit nil)))))))
4957 ;; Return value.
4958 borders))
4960 (defun org-export-table-cell-starts-colgroup-p (table-cell info)
4961 "Non-nil when TABLE-CELL is at the beginning of a column group.
4962 INFO is a plist used as a communication channel."
4963 ;; A cell starts a column group either when it is at the beginning
4964 ;; of a row (or after the special column, if any) or when it has
4965 ;; a left border.
4966 (or (eq (org-element-map (org-export-get-parent table-cell) 'table-cell
4967 'identity info 'first-match)
4968 table-cell)
4969 (memq 'left (org-export-table-cell-borders table-cell info))))
4971 (defun org-export-table-cell-ends-colgroup-p (table-cell info)
4972 "Non-nil when TABLE-CELL is at the end of a column group.
4973 INFO is a plist used as a communication channel."
4974 ;; A cell ends a column group either when it is at the end of a row
4975 ;; or when it has a right border.
4976 (or (eq (car (last (org-element-contents
4977 (org-export-get-parent table-cell))))
4978 table-cell)
4979 (memq 'right (org-export-table-cell-borders table-cell info))))
4981 (defun org-export-table-row-starts-rowgroup-p (table-row info)
4982 "Non-nil when TABLE-ROW is at the beginning of a row group.
4983 INFO is a plist used as a communication channel."
4984 (unless (or (eq (org-element-property :type table-row) 'rule)
4985 (org-export-table-row-is-special-p table-row info))
4986 (let ((borders (org-export-table-cell-borders
4987 (car (org-element-contents table-row)) info)))
4988 (or (memq 'top borders) (memq 'above borders)))))
4990 (defun org-export-table-row-ends-rowgroup-p (table-row info)
4991 "Non-nil when TABLE-ROW is at the end of a row group.
4992 INFO is a plist used as a communication channel."
4993 (unless (or (eq (org-element-property :type table-row) 'rule)
4994 (org-export-table-row-is-special-p table-row info))
4995 (let ((borders (org-export-table-cell-borders
4996 (car (org-element-contents table-row)) info)))
4997 (or (memq 'bottom borders) (memq 'below borders)))))
4999 (defun org-export-table-row-in-header-p (table-row info)
5000 "Non-nil when TABLE-ROW is located within table's header.
5001 INFO is a plist used as a communication channel. Always return
5002 nil for special rows and rows separators."
5003 (and (org-export-table-has-header-p
5004 (org-export-get-parent-table table-row) info)
5005 (eql (org-export-table-row-group table-row info) 1)))
5007 (defun org-export-table-row-starts-header-p (table-row info)
5008 "Non-nil when TABLE-ROW is the first table header's row.
5009 INFO is a plist used as a communication channel."
5010 (and (org-export-table-row-in-header-p table-row info)
5011 (org-export-table-row-starts-rowgroup-p table-row info)))
5013 (defun org-export-table-row-ends-header-p (table-row info)
5014 "Non-nil when TABLE-ROW is the last table header's row.
5015 INFO is a plist used as a communication channel."
5016 (and (org-export-table-row-in-header-p table-row info)
5017 (org-export-table-row-ends-rowgroup-p table-row info)))
5019 (defun org-export-table-row-number (table-row info)
5020 "Return TABLE-ROW number.
5021 INFO is a plist used as a communication channel. Return value is
5022 zero-based and ignores separators. The function returns nil for
5023 special columns and separators."
5024 (when (and (eq (org-element-property :type table-row) 'standard)
5025 (not (org-export-table-row-is-special-p table-row info)))
5026 (let ((number 0))
5027 (org-element-map (org-export-get-parent-table table-row) 'table-row
5028 (lambda (row)
5029 (cond ((eq row table-row) number)
5030 ((eq (org-element-property :type row) 'standard)
5031 (cl-incf number) nil)))
5032 info 'first-match))))
5034 (defun org-export-table-dimensions (table info)
5035 "Return TABLE dimensions.
5037 INFO is a plist used as a communication channel.
5039 Return value is a CONS like (ROWS . COLUMNS) where
5040 ROWS (resp. COLUMNS) is the number of exportable
5041 rows (resp. columns)."
5042 (let (first-row (columns 0) (rows 0))
5043 ;; Set number of rows, and extract first one.
5044 (org-element-map table 'table-row
5045 (lambda (row)
5046 (when (eq (org-element-property :type row) 'standard)
5047 (cl-incf rows)
5048 (unless first-row (setq first-row row)))) info)
5049 ;; Set number of columns.
5050 (org-element-map first-row 'table-cell (lambda (_) (cl-incf columns)) info)
5051 ;; Return value.
5052 (cons rows columns)))
5054 (defun org-export-table-cell-address (table-cell info)
5055 "Return address of a regular TABLE-CELL object.
5057 TABLE-CELL is the cell considered. INFO is a plist used as
5058 a communication channel.
5060 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
5061 zero-based index. Only exportable cells are considered. The
5062 function returns nil for other cells."
5063 (let* ((table-row (org-export-get-parent table-cell))
5064 (row-number (org-export-table-row-number table-row info)))
5065 (when row-number
5066 (cons row-number
5067 (let ((col-count 0))
5068 (org-element-map table-row 'table-cell
5069 (lambda (cell)
5070 (if (eq cell table-cell) col-count (cl-incf col-count) nil))
5071 info 'first-match))))))
5073 (defun org-export-get-table-cell-at (address table info)
5074 "Return regular table-cell object at ADDRESS in TABLE.
5076 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
5077 zero-based index. TABLE is a table type element. INFO is
5078 a plist used as a communication channel.
5080 If no table-cell, among exportable cells, is found at ADDRESS,
5081 return nil."
5082 (let ((column-pos (cdr address)) (column-count 0))
5083 (org-element-map
5084 ;; Row at (car address) or nil.
5085 (let ((row-pos (car address)) (row-count 0))
5086 (org-element-map table 'table-row
5087 (lambda (row)
5088 (cond ((eq (org-element-property :type row) 'rule) nil)
5089 ((= row-count row-pos) row)
5090 (t (cl-incf row-count) nil)))
5091 info 'first-match))
5092 'table-cell
5093 (lambda (cell)
5094 (if (= column-count column-pos) cell
5095 (cl-incf column-count) nil))
5096 info 'first-match)))
5099 ;;;; For Tables Of Contents
5101 ;; `org-export-collect-headlines' builds a list of all exportable
5102 ;; headline elements, maybe limited to a certain depth. One can then
5103 ;; easily parse it and transcode it.
5105 ;; Building lists of tables, figures or listings is quite similar.
5106 ;; Once the generic function `org-export-collect-elements' is defined,
5107 ;; `org-export-collect-tables', `org-export-collect-figures' and
5108 ;; `org-export-collect-listings' can be derived from it.
5110 (defun org-export-collect-headlines (info &optional n scope)
5111 "Collect headlines in order to build a table of contents.
5113 INFO is a plist used as a communication channel.
5115 When optional argument N is an integer, it specifies the depth of
5116 the table of contents. Otherwise, it is set to the value of the
5117 last headline level. See `org-export-headline-levels' for more
5118 information.
5120 Optional argument SCOPE, when non-nil, is an element. If it is
5121 a headline, only children of SCOPE are collected. Otherwise,
5122 collect children of the headline containing provided element. If
5123 there is no such headline, collect all headlines. In any case,
5124 argument N becomes relative to the level of that headline.
5126 Return a list of all exportable headlines as parsed elements.
5127 Footnote sections are ignored."
5128 (let* ((scope (cond ((not scope) (plist-get info :parse-tree))
5129 ((eq (org-element-type scope) 'headline) scope)
5130 ((org-export-get-parent-headline scope))
5131 (t (plist-get info :parse-tree))))
5132 (limit (plist-get info :headline-levels))
5133 (n (if (not (wholenump n)) limit
5134 (min (if (eq (org-element-type scope) 'org-data) n
5135 (+ (org-export-get-relative-level scope info) n))
5136 limit))))
5137 (org-element-map (org-element-contents scope) 'headline
5138 (lambda (headline)
5139 (unless (org-element-property :footnote-section-p headline)
5140 (let ((level (org-export-get-relative-level headline info)))
5141 (and (<= level n) headline))))
5142 info)))
5144 (defun org-export-collect-elements (type info &optional predicate)
5145 "Collect referenceable elements of a determined type.
5147 TYPE can be a symbol or a list of symbols specifying element
5148 types to search. Only elements with a caption are collected.
5150 INFO is a plist used as a communication channel.
5152 When non-nil, optional argument PREDICATE is a function accepting
5153 one argument, an element of type TYPE. It returns a non-nil
5154 value when that element should be collected.
5156 Return a list of all elements found, in order of appearance."
5157 (org-element-map (plist-get info :parse-tree) type
5158 (lambda (element)
5159 (and (org-element-property :caption element)
5160 (or (not predicate) (funcall predicate element))
5161 element))
5162 info))
5164 (defun org-export-collect-tables (info)
5165 "Build a list of tables.
5166 INFO is a plist used as a communication channel.
5168 Return a list of table elements with a caption."
5169 (org-export-collect-elements 'table info))
5171 (defun org-export-collect-figures (info predicate)
5172 "Build a list of figures.
5174 INFO is a plist used as a communication channel. PREDICATE is
5175 a function which accepts one argument: a paragraph element and
5176 whose return value is non-nil when that element should be
5177 collected.
5179 A figure is a paragraph type element, with a caption, verifying
5180 PREDICATE. The latter has to be provided since a \"figure\" is
5181 a vague concept that may depend on back-end.
5183 Return a list of elements recognized as figures."
5184 (org-export-collect-elements 'paragraph info predicate))
5186 (defun org-export-collect-listings (info)
5187 "Build a list of src blocks.
5189 INFO is a plist used as a communication channel.
5191 Return a list of src-block elements with a caption."
5192 (org-export-collect-elements 'src-block info))
5195 ;;;; Smart Quotes
5197 ;; The main function for the smart quotes sub-system is
5198 ;; `org-export-activate-smart-quotes', which replaces every quote in
5199 ;; a given string from the parse tree with its "smart" counterpart.
5201 ;; Dictionary for smart quotes is stored in
5202 ;; `org-export-smart-quotes-alist'.
5204 (defconst org-export-smart-quotes-alist
5205 '(("da"
5206 ;; one may use: »...«, "...", ›...‹, or '...'.
5207 ;; http://sproget.dk/raad-og-regler/retskrivningsregler/retskrivningsregler/a7-40-60/a7-58-anforselstegn/
5208 ;; LaTeX quotes require Babel!
5209 (primary-opening
5210 :utf-8 "»" :html "&raquo;" :latex ">>" :texinfo "@guillemetright{}")
5211 (primary-closing
5212 :utf-8 "«" :html "&laquo;" :latex "<<" :texinfo "@guillemetleft{}")
5213 (secondary-opening
5214 :utf-8 "›" :html "&rsaquo;" :latex "\\frq{}" :texinfo "@guilsinglright{}")
5215 (secondary-closing
5216 :utf-8 "‹" :html "&lsaquo;" :latex "\\flq{}" :texinfo "@guilsingleft{}")
5217 (apostrophe :utf-8 "’" :html "&rsquo;"))
5218 ("de"
5219 (primary-opening
5220 :utf-8 "„" :html "&bdquo;" :latex "\"`" :texinfo "@quotedblbase{}")
5221 (primary-closing
5222 :utf-8 "“" :html "&ldquo;" :latex "\"'" :texinfo "@quotedblleft{}")
5223 (secondary-opening
5224 :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}" :texinfo "@quotesinglbase{}")
5225 (secondary-closing
5226 :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}" :texinfo "@quoteleft{}")
5227 (apostrophe :utf-8 "’" :html "&rsquo;"))
5228 ("en"
5229 (primary-opening :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
5230 (primary-closing :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
5231 (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5232 (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5233 (apostrophe :utf-8 "’" :html "&rsquo;"))
5234 ("es"
5235 (primary-opening
5236 :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5237 :texinfo "@guillemetleft{}")
5238 (primary-closing
5239 :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5240 :texinfo "@guillemetright{}")
5241 (secondary-opening :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
5242 (secondary-closing :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
5243 (apostrophe :utf-8 "’" :html "&rsquo;"))
5244 ("fr"
5245 (primary-opening
5246 :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
5247 :texinfo "@guillemetleft{}@tie{}")
5248 (primary-closing
5249 :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
5250 :texinfo "@tie{}@guillemetright{}")
5251 (secondary-opening
5252 :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
5253 :texinfo "@guillemetleft{}@tie{}")
5254 (secondary-closing :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
5255 :texinfo "@tie{}@guillemetright{}")
5256 (apostrophe :utf-8 "’" :html "&rsquo;"))
5257 ("is"
5258 (primary-opening
5259 :utf-8 "„" :html "&bdquo;" :latex "\"`" :texinfo "@quotedblbase{}")
5260 (primary-closing
5261 :utf-8 "“" :html "&ldquo;" :latex "\"'" :texinfo "@quotedblleft{}")
5262 (secondary-opening
5263 :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}" :texinfo "@quotesinglbase{}")
5264 (secondary-closing
5265 :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}" :texinfo "@quoteleft{}")
5266 (apostrophe :utf-8 "’" :html "&rsquo;"))
5267 ("no"
5268 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5269 (primary-opening
5270 :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5271 :texinfo "@guillemetleft{}")
5272 (primary-closing
5273 :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5274 :texinfo "@guillemetright{}")
5275 (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5276 (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5277 (apostrophe :utf-8 "’" :html "&rsquo;"))
5278 ("nb"
5279 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5280 (primary-opening
5281 :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5282 :texinfo "@guillemetleft{}")
5283 (primary-closing
5284 :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5285 :texinfo "@guillemetright{}")
5286 (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5287 (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5288 (apostrophe :utf-8 "’" :html "&rsquo;"))
5289 ("nn"
5290 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5291 (primary-opening
5292 :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5293 :texinfo "@guillemetleft{}")
5294 (primary-closing
5295 :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5296 :texinfo "@guillemetright{}")
5297 (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5298 (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5299 (apostrophe :utf-8 "’" :html "&rsquo;"))
5300 ("ru"
5301 ;; 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
5302 ;; http://www.artlebedev.ru/kovodstvo/sections/104/
5303 (primary-opening :utf-8 "«" :html "&laquo;" :latex "{}<<"
5304 :texinfo "@guillemetleft{}")
5305 (primary-closing :utf-8 "»" :html "&raquo;" :latex ">>{}"
5306 :texinfo "@guillemetright{}")
5307 (secondary-opening
5308 :utf-8 "„" :html "&bdquo;" :latex "\\glqq{}" :texinfo "@quotedblbase{}")
5309 (secondary-closing
5310 :utf-8 "“" :html "&ldquo;" :latex "\\grqq{}" :texinfo "@quotedblleft{}")
5311 (apostrophe :utf-8 "’" :html: "&#39;"))
5312 ("sv"
5313 ;; based on https://sv.wikipedia.org/wiki/Citattecken
5314 (primary-opening :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
5315 (primary-closing :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
5316 (secondary-opening :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "`")
5317 (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "'")
5318 (apostrophe :utf-8 "’" :html "&rsquo;")))
5319 "Smart quotes translations.
5321 Alist whose CAR is a language string and CDR is an alist with
5322 quote type as key and a plist associating various encodings to
5323 their translation as value.
5325 A quote type can be any symbol among `primary-opening',
5326 `primary-closing', `secondary-opening', `secondary-closing' and
5327 `apostrophe'.
5329 Valid encodings include `:utf-8', `:html', `:latex' and
5330 `:texinfo'.
5332 If no translation is found, the quote character is left as-is.")
5334 (defun org-export--smart-quote-status (s info)
5335 "Return smart quote status at the beginning of string S.
5336 INFO is the current export state, as a plist."
5337 (let* ((parent (org-element-property :parent s))
5338 (cache (or (plist-get info :smart-quote-cache)
5339 (let ((table (make-hash-table :test #'eq)))
5340 (plist-put info :smart-quote-cache table)
5341 table)))
5342 (value (gethash parent cache 'missing-data)))
5343 (if (not (eq value 'missing-data)) (cdr (assq s value))
5344 (let (level1-open full-status)
5345 (org-element-map
5346 (let ((secondary (org-element-secondary-p s)))
5347 (if secondary (org-element-property secondary parent)
5348 (org-element-contents parent)))
5349 'plain-text
5350 (lambda (text)
5351 (let ((start 0) current-status)
5352 (while (setq start (string-match "['\"]" text start))
5353 (push
5354 (cond
5355 ((equal (match-string 0 text) "\"")
5356 (setf level1-open (not level1-open))
5357 (if level1-open 'primary-opening 'primary-closing))
5358 ;; Not already in a level 1 quote: this is an
5359 ;; apostrophe.
5360 ((not level1-open) 'apostrophe)
5361 ;; Extract previous char and next char. As
5362 ;; a special case, they can also be set to `blank',
5363 ;; `no-blank' or nil. Then determine if current
5364 ;; match is allowed as an opening quote or a closing
5365 ;; quote.
5367 (let* ((previous
5368 (if (> start 0) (substring text (1- start) start)
5369 (let ((p (org-export-get-previous-element
5370 text info)))
5371 (cond ((not p) nil)
5372 ((stringp p) (substring p -1))
5373 ((memq (org-element-property :post-blank p)
5374 '(0 nil))
5375 'no-blank)
5376 (t 'blank)))))
5377 (next
5378 (if (< (1+ start) (length text))
5379 (substring text (1+ start) (+ start 2))
5380 (let ((n (org-export-get-next-element text info)))
5381 (cond ((not n) nil)
5382 ((stringp n) (substring n 0 1))
5383 (t 'no-blank)))))
5384 (allow-open
5385 (and (if (stringp previous)
5386 (string-match "\\s\"\\|\\s-\\|\\s("
5387 previous)
5388 (memq previous '(blank nil)))
5389 (if (stringp next)
5390 (string-match "\\w\\|\\s.\\|\\s_" next)
5391 (eq next 'no-blank))))
5392 (allow-close
5393 (and (if (stringp previous)
5394 (string-match "\\w\\|\\s.\\|\\s_" previous)
5395 (eq previous 'no-blank))
5396 (if (stringp next)
5397 (string-match "\\s-\\|\\s)\\|\\s.\\|\\s\""
5398 next)
5399 (memq next '(blank nil))))))
5400 (cond
5401 ((and allow-open allow-close) (error "Should not happen"))
5402 (allow-open 'secondary-opening)
5403 (allow-close 'secondary-closing)
5404 (t 'apostrophe)))))
5405 current-status)
5406 (cl-incf start))
5407 (when current-status
5408 (push (cons text (nreverse current-status)) full-status))))
5409 info nil org-element-recursive-objects)
5410 (puthash parent full-status cache)
5411 (cdr (assq s full-status))))))
5413 (defun org-export-activate-smart-quotes (s encoding info &optional original)
5414 "Replace regular quotes with \"smart\" quotes in string S.
5416 ENCODING is a symbol among `:html', `:latex', `:texinfo' and
5417 `:utf-8'. INFO is a plist used as a communication channel.
5419 The function has to retrieve information about string
5420 surroundings in parse tree. It can only happen with an
5421 unmodified string. Thus, if S has already been through another
5422 process, a non-nil ORIGINAL optional argument will provide that
5423 original string.
5425 Return the new string."
5426 (let ((quote-status
5427 (copy-sequence (org-export--smart-quote-status (or original s) info))))
5428 (replace-regexp-in-string
5429 "['\"]"
5430 (lambda (match)
5431 (or (plist-get
5432 (cdr (assq (pop quote-status)
5433 (cdr (assoc (plist-get info :language)
5434 org-export-smart-quotes-alist))))
5435 encoding)
5436 match))
5437 s nil t)))
5439 ;;;; Topology
5441 ;; Here are various functions to retrieve information about the
5442 ;; neighborhood of a given element or object. Neighbors of interest
5443 ;; are direct parent (`org-export-get-parent'), parent headline
5444 ;; (`org-export-get-parent-headline'), first element containing an
5445 ;; object, (`org-export-get-parent-element'), parent table
5446 ;; (`org-export-get-parent-table'), previous element or object
5447 ;; (`org-export-get-previous-element') and next element or object
5448 ;; (`org-export-get-next-element').
5450 ;; defsubst org-export-get-parent must be defined before first use
5452 (defun org-export-get-parent-headline (blob)
5453 "Return BLOB parent headline or nil.
5454 BLOB is the element or object being considered."
5455 (org-element-lineage blob '(headline)))
5457 (defun org-export-get-parent-element (object)
5458 "Return first element containing OBJECT or nil.
5459 OBJECT is the object to consider."
5460 (org-element-lineage object org-element-all-elements))
5462 (defun org-export-get-parent-table (object)
5463 "Return OBJECT parent table or nil.
5464 OBJECT is either a `table-cell' or `table-element' type object."
5465 (org-element-lineage object '(table)))
5467 (defun org-export-get-previous-element (blob info &optional n)
5468 "Return previous element or object.
5470 BLOB is an element or object. INFO is a plist used as
5471 a communication channel. Return previous exportable element or
5472 object, a string, or nil.
5474 When optional argument N is a positive integer, return a list
5475 containing up to N siblings before BLOB, from farthest to
5476 closest. With any other non-nil value, return a list containing
5477 all of them."
5478 (let* ((secondary (org-element-secondary-p blob))
5479 (parent (org-export-get-parent blob))
5480 (siblings
5481 (if secondary (org-element-property secondary parent)
5482 (org-element-contents parent)))
5483 prev)
5484 (catch 'exit
5485 (dolist (obj (cdr (memq blob (reverse siblings))) prev)
5486 (cond ((memq obj (plist-get info :ignore-list)))
5487 ((null n) (throw 'exit obj))
5488 ((not (wholenump n)) (push obj prev))
5489 ((zerop n) (throw 'exit prev))
5490 (t (cl-decf n) (push obj prev)))))))
5492 (defun org-export-get-next-element (blob info &optional n)
5493 "Return next element or object.
5495 BLOB is an element or object. INFO is a plist used as
5496 a communication channel. Return next exportable element or
5497 object, a string, or nil.
5499 When optional argument N is a positive integer, return a list
5500 containing up to N siblings after BLOB, from closest to farthest.
5501 With any other non-nil value, return a list containing all of
5502 them."
5503 (let* ((secondary (org-element-secondary-p blob))
5504 (parent (org-export-get-parent blob))
5505 (siblings
5506 (cdr (memq blob
5507 (if secondary (org-element-property secondary parent)
5508 (org-element-contents parent)))))
5509 next)
5510 (catch 'exit
5511 (dolist (obj siblings (nreverse next))
5512 (cond ((memq obj (plist-get info :ignore-list)))
5513 ((null n) (throw 'exit obj))
5514 ((not (wholenump n)) (push obj next))
5515 ((zerop n) (throw 'exit (nreverse next)))
5516 (t (cl-decf n) (push obj next)))))))
5519 ;;;; Translation
5521 ;; `org-export-translate' translates a string according to the language
5522 ;; specified by the LANGUAGE keyword. `org-export-dictionary' contains
5523 ;; the dictionary used for the translation.
5525 (defconst org-export-dictionary
5526 '(("%e %n: %c"
5527 ("fr" :default "%e %n : %c" :html "%e&nbsp;%n&nbsp;: %c"))
5528 ("Author"
5529 ("ca" :default "Autor")
5530 ("cs" :default "Autor")
5531 ("da" :default "Forfatter")
5532 ("de" :default "Autor")
5533 ("eo" :html "A&#365;toro")
5534 ("es" :default "Autor")
5535 ("et" :default "Autor")
5536 ("fi" :html "Tekij&auml;")
5537 ("fr" :default "Auteur")
5538 ("hu" :default "Szerz&otilde;")
5539 ("is" :html "H&ouml;fundur")
5540 ("it" :default "Autore")
5541 ("ja" :default "著者" :html "&#33879;&#32773;")
5542 ("nl" :default "Auteur")
5543 ("no" :default "Forfatter")
5544 ("nb" :default "Forfatter")
5545 ("nn" :default "Forfattar")
5546 ("pl" :default "Autor")
5547 ("pt_BR" :default "Autor")
5548 ("ru" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5549 ("sv" :html "F&ouml;rfattare")
5550 ("uk" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5551 ("zh-CN" :html "&#20316;&#32773;" :utf-8 "作者")
5552 ("zh-TW" :html "&#20316;&#32773;" :utf-8 "作者"))
5553 ("Continued from previous page"
5554 ("de" :default "Fortsetzung von vorheriger Seite")
5555 ("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")
5556 ("fr" :default "Suite de la page précédente")
5557 ("it" :default "Continua da pagina precedente")
5558 ("ja" :default "前ページからの続き")
5559 ("nl" :default "Vervolg van vorige pagina")
5560 ("pt" :default "Continuação da página anterior")
5561 ("ru" :html "(&#1055;&#1088;&#1086;&#1076;&#1086;&#1083;&#1078;&#1077;&#1085;&#1080;&#1077;)"
5562 :utf-8 "(Продолжение)"))
5563 ("Continued on next page"
5564 ("de" :default "Fortsetzung nächste Seite")
5565 ("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")
5566 ("fr" :default "Suite page suivante")
5567 ("it" :default "Continua alla pagina successiva")
5568 ("ja" :default "次ページに続く")
5569 ("nl" :default "Vervolg op volgende pagina")
5570 ("pt" :default "Continua na página seguinte")
5571 ("ru" :html "(&#1055;&#1088;&#1086;&#1076;&#1086;&#1083;&#1078;&#1077;&#1085;&#1080;&#1077; &#1089;&#1083;&#1077;&#1076;&#1091;&#1077;&#1090;)"
5572 :utf-8 "(Продолжение следует)"))
5573 ("Date"
5574 ("ca" :default "Data")
5575 ("cs" :default "Datum")
5576 ("da" :default "Dato")
5577 ("de" :default "Datum")
5578 ("eo" :default "Dato")
5579 ("es" :default "Fecha")
5580 ("et" :html "Kuup&#228;ev" :utf-8 "Kuupäev")
5581 ("fi" :html "P&auml;iv&auml;m&auml;&auml;r&auml;")
5582 ("hu" :html "D&aacute;tum")
5583 ("is" :default "Dagsetning")
5584 ("it" :default "Data")
5585 ("ja" :default "日付" :html "&#26085;&#20184;")
5586 ("nl" :default "Datum")
5587 ("no" :default "Dato")
5588 ("nb" :default "Dato")
5589 ("nn" :default "Dato")
5590 ("pl" :default "Data")
5591 ("pt_BR" :default "Data")
5592 ("ru" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5593 ("sv" :default "Datum")
5594 ("uk" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5595 ("zh-CN" :html "&#26085;&#26399;" :utf-8 "日期")
5596 ("zh-TW" :html "&#26085;&#26399;" :utf-8 "日期"))
5597 ("Equation"
5598 ("da" :default "Ligning")
5599 ("de" :default "Gleichung")
5600 ("es" :ascii "Ecuacion" :html "Ecuaci&oacute;n" :default "Ecuación")
5601 ("et" :html "V&#245;rrand" :utf-8 "Võrrand")
5602 ("fr" :ascii "Equation" :default "Équation")
5603 ("is" :default "Jafna")
5604 ("ja" :default "方程式")
5605 ("no" :default "Ligning")
5606 ("nb" :default "Ligning")
5607 ("nn" :default "Likning")
5608 ("pt_BR" :html "Equa&ccedil;&atilde;o" :default "Equação" :ascii "Equacao")
5609 ("ru" :html "&#1059;&#1088;&#1072;&#1074;&#1085;&#1077;&#1085;&#1080;&#1077;"
5610 :utf-8 "Уравнение")
5611 ("sv" :default "Ekvation")
5612 ("zh-CN" :html "&#26041;&#31243;" :utf-8 "方程"))
5613 ("Figure"
5614 ("da" :default "Figur")
5615 ("de" :default "Abbildung")
5616 ("es" :default "Figura")
5617 ("et" :default "Joonis")
5618 ("is" :default "Mynd")
5619 ("ja" :default "図" :html "&#22259;")
5620 ("no" :default "Illustrasjon")
5621 ("nb" :default "Illustrasjon")
5622 ("nn" :default "Illustrasjon")
5623 ("pt_BR" :default "Figura")
5624 ("ru" :html "&#1056;&#1080;&#1089;&#1091;&#1085;&#1086;&#1082;" :utf-8 "Рисунок")
5625 ("sv" :default "Illustration")
5626 ("zh-CN" :html "&#22270;" :utf-8 "图"))
5627 ("Figure %d:"
5628 ("da" :default "Figur %d")
5629 ("de" :default "Abbildung %d:")
5630 ("es" :default "Figura %d:")
5631 ("et" :default "Joonis %d:")
5632 ("fr" :default "Figure %d :" :html "Figure&nbsp;%d&nbsp;:")
5633 ("is" :default "Mynd %d")
5634 ("ja" :default "図%d: " :html "&#22259;%d: ")
5635 ("no" :default "Illustrasjon %d")
5636 ("nb" :default "Illustrasjon %d")
5637 ("nn" :default "Illustrasjon %d")
5638 ("pt_BR" :default "Figura %d:")
5639 ("ru" :html "&#1056;&#1080;&#1089;. %d.:" :utf-8 "Рис. %d.:")
5640 ("sv" :default "Illustration %d")
5641 ("zh-CN" :html "&#22270;%d&nbsp;" :utf-8 "图%d "))
5642 ("Footnotes"
5643 ("ca" :html "Peus de p&agrave;gina")
5644 ("cs" :default "Pozn\xe1mky pod carou")
5645 ("da" :default "Fodnoter")
5646 ("de" :html "Fu&szlig;noten" :default "Fußnoten")
5647 ("eo" :default "Piednotoj")
5648 ("es" :ascii "Nota al pie de pagina" :html "Nota al pie de p&aacute;gina" :default "Nota al pie de página")
5649 ("et" :html "Allm&#228;rkused" :utf-8 "Allmärkused")
5650 ("fi" :default "Alaviitteet")
5651 ("fr" :default "Notes de bas de page")
5652 ("hu" :html "L&aacute;bjegyzet")
5653 ("is" :html "Aftanm&aacute;lsgreinar")
5654 ("it" :html "Note a pi&egrave; di pagina")
5655 ("ja" :default "脚注" :html "&#33050;&#27880;")
5656 ("nl" :default "Voetnoten")
5657 ("no" :default "Fotnoter")
5658 ("nb" :default "Fotnoter")
5659 ("nn" :default "Fotnotar")
5660 ("pl" :default "Przypis")
5661 ("pt_BR" :html "Notas de Rodap&eacute;" :default "Notas de Rodapé" :ascii "Notas de Rodape")
5662 ("ru" :html "&#1057;&#1085;&#1086;&#1089;&#1082;&#1080;" :utf-8 "Сноски")
5663 ("sv" :default "Fotnoter")
5664 ("uk" :html "&#1055;&#1088;&#1080;&#1084;&#1110;&#1090;&#1082;&#1080;"
5665 :utf-8 "Примітки")
5666 ("zh-CN" :html "&#33050;&#27880;" :utf-8 "脚注")
5667 ("zh-TW" :html "&#33139;&#35387;" :utf-8 "腳註"))
5668 ("List of Listings"
5669 ("da" :default "Programmer")
5670 ("de" :default "Programmauflistungsverzeichnis")
5671 ("es" :ascii "Indice de Listados de programas" :html "&Iacute;ndice de Listados de programas" :default "Índice de Listados de programas")
5672 ("et" :default "Loendite nimekiri")
5673 ("fr" :default "Liste des programmes")
5674 ("ja" :default "ソースコード目次")
5675 ("no" :default "Dataprogrammer")
5676 ("nb" :default "Dataprogrammer")
5677 ("ru" :html "&#1057;&#1087;&#1080;&#1089;&#1086;&#1082; &#1088;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1086;&#1082;"
5678 :utf-8 "Список распечаток")
5679 ("zh-CN" :html "&#20195;&#30721;&#30446;&#24405;" :utf-8 "代码目录"))
5680 ("List of Tables"
5681 ("da" :default "Tabeller")
5682 ("de" :default "Tabellenverzeichnis")
5683 ("es" :ascii "Indice de tablas" :html "&Iacute;ndice de tablas" :default "Índice de tablas")
5684 ("et" :default "Tabelite nimekiri")
5685 ("fr" :default "Liste des tableaux")
5686 ("is" :default "Töfluskrá" :html "T&ouml;fluskr&aacute;")
5687 ("ja" :default "表目次")
5688 ("no" :default "Tabeller")
5689 ("nb" :default "Tabeller")
5690 ("nn" :default "Tabeller")
5691 ("pt_BR" :default "Índice de Tabelas" :ascii "Indice de Tabelas")
5692 ("ru" :html "&#1057;&#1087;&#1080;&#1089;&#1086;&#1082; &#1090;&#1072;&#1073;&#1083;&#1080;&#1094;"
5693 :utf-8 "Список таблиц")
5694 ("sv" :default "Tabeller")
5695 ("zh-CN" :html "&#34920;&#26684;&#30446;&#24405;" :utf-8 "表格目录"))
5696 ("Listing"
5697 ("da" :default "Program")
5698 ("de" :default "Programmlisting")
5699 ("es" :default "Listado de programa")
5700 ("et" :default "Loend")
5701 ("fr" :default "Programme" :html "Programme")
5702 ("ja" :default "ソースコード")
5703 ("no" :default "Dataprogram")
5704 ("nb" :default "Dataprogram")
5705 ("pt_BR" :default "Listagem")
5706 ("ru" :html "&#1056;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1082;&#1072;"
5707 :utf-8 "Распечатка")
5708 ("zh-CN" :html "&#20195;&#30721;" :utf-8 "代码"))
5709 ("Listing %d:"
5710 ("da" :default "Program %d")
5711 ("de" :default "Programmlisting %d")
5712 ("es" :default "Listado de programa %d")
5713 ("et" :default "Loend %d")
5714 ("fr" :default "Programme %d :" :html "Programme&nbsp;%d&nbsp;:")
5715 ("ja" :default "ソースコード%d:")
5716 ("no" :default "Dataprogram %d")
5717 ("nb" :default "Dataprogram %d")
5718 ("pt_BR" :default "Listagem %d")
5719 ("ru" :html "&#1056;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1082;&#1072; %d.:"
5720 :utf-8 "Распечатка %d.:")
5721 ("zh-CN" :html "&#20195;&#30721;%d&nbsp;" :utf-8 "代码%d "))
5722 ("References"
5723 ("fr" :ascii "References" :default "Références")
5724 ("de" :default "Quellen")
5725 ("es" :default "Referencias"))
5726 ("See figure %s"
5727 ("fr" :default "cf. figure %s"
5728 :html "cf.&nbsp;figure&nbsp;%s" :latex "cf.~figure~%s"))
5729 ("See listing %s"
5730 ("fr" :default "cf. programme %s"
5731 :html "cf.&nbsp;programme&nbsp;%s" :latex "cf.~programme~%s"))
5732 ("See section %s"
5733 ("da" :default "jævnfør afsnit %s")
5734 ("de" :default "siehe Abschnitt %s")
5735 ("es" :ascii "Vea seccion %s" :html "Vea secci&oacute;n %s" :default "Vea sección %s")
5736 ("et" :html "Vaata peat&#252;kki %s" :utf-8 "Vaata peatükki %s")
5737 ("fr" :default "cf. section %s")
5738 ("ja" :default "セクション %s を参照")
5739 ("pt_BR" :html "Veja a se&ccedil;&atilde;o %s" :default "Veja a seção %s"
5740 :ascii "Veja a secao %s")
5741 ("ru" :html "&#1057;&#1084;. &#1088;&#1072;&#1079;&#1076;&#1077;&#1083; %s"
5742 :utf-8 "См. раздел %s")
5743 ("zh-CN" :html "&#21442;&#35265;&#31532;%s&#33410;" :utf-8 "参见第%s节"))
5744 ("See table %s"
5745 ("fr" :default "cf. tableau %s"
5746 :html "cf.&nbsp;tableau&nbsp;%s" :latex "cf.~tableau~%s"))
5747 ("Table"
5748 ("de" :default "Tabelle")
5749 ("es" :default "Tabla")
5750 ("et" :default "Tabel")
5751 ("fr" :default "Tableau")
5752 ("is" :default "Tafla")
5753 ("ja" :default "表" :html "&#34920;")
5754 ("pt_BR" :default "Tabela")
5755 ("ru" :html "&#1058;&#1072;&#1073;&#1083;&#1080;&#1094;&#1072;"
5756 :utf-8 "Таблица")
5757 ("zh-CN" :html "&#34920;" :utf-8 "表"))
5758 ("Table %d:"
5759 ("da" :default "Tabel %d")
5760 ("de" :default "Tabelle %d")
5761 ("es" :default "Tabla %d")
5762 ("et" :default "Tabel %d")
5763 ("fr" :default "Tableau %d :")
5764 ("is" :default "Tafla %d")
5765 ("ja" :default "表%d:" :html "&#34920;%d:")
5766 ("no" :default "Tabell %d")
5767 ("nb" :default "Tabell %d")
5768 ("nn" :default "Tabell %d")
5769 ("pt_BR" :default "Tabela %d")
5770 ("ru" :html "&#1058;&#1072;&#1073;&#1083;&#1080;&#1094;&#1072; %d.:"
5771 :utf-8 "Таблица %d.:")
5772 ("sv" :default "Tabell %d")
5773 ("zh-CN" :html "&#34920;%d&nbsp;" :utf-8 "表%d "))
5774 ("Table of Contents"
5775 ("ca" :html "&Iacute;ndex")
5776 ("cs" :default "Obsah")
5777 ("da" :default "Indhold")
5778 ("de" :default "Inhaltsverzeichnis")
5779 ("eo" :default "Enhavo")
5780 ("es" :ascii "Indice" :html "&Iacute;ndice" :default "Índice")
5781 ("et" :default "Sisukord")
5782 ("fi" :html "Sis&auml;llysluettelo")
5783 ("fr" :ascii "Sommaire" :default "Table des matières")
5784 ("hu" :html "Tartalomjegyz&eacute;k")
5785 ("is" :default "Efnisyfirlit")
5786 ("it" :default "Indice")
5787 ("ja" :default "目次" :html "&#30446;&#27425;")
5788 ("nl" :default "Inhoudsopgave")
5789 ("no" :default "Innhold")
5790 ("nb" :default "Innhold")
5791 ("nn" :default "Innhald")
5792 ("pl" :html "Spis tre&#x015b;ci")
5793 ("pt_BR" :html "&Iacute;ndice" :utf8 "Índice" :ascii "Indice")
5794 ("ru" :html "&#1057;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1077;"
5795 :utf-8 "Содержание")
5796 ("sv" :html "Inneh&aring;ll")
5797 ("uk" :html "&#1047;&#1084;&#1110;&#1089;&#1090;" :utf-8 "Зміст")
5798 ("zh-CN" :html "&#30446;&#24405;" :utf-8 "目录")
5799 ("zh-TW" :html "&#30446;&#37636;" :utf-8 "目錄"))
5800 ("Unknown reference"
5801 ("da" :default "ukendt reference")
5802 ("de" :default "Unbekannter Verweis")
5803 ("es" :default "Referencia desconocida")
5804 ("et" :default "Tundmatu viide")
5805 ("fr" :ascii "Destination inconnue" :default "Référence inconnue")
5806 ("ja" :default "不明な参照先")
5807 ("pt_BR" :default "Referência desconhecida"
5808 :ascii "Referencia desconhecida")
5809 ("ru" :html "&#1053;&#1077;&#1080;&#1079;&#1074;&#1077;&#1089;&#1090;&#1085;&#1072;&#1103; &#1089;&#1089;&#1099;&#1083;&#1082;&#1072;"
5810 :utf-8 "Неизвестная ссылка")
5811 ("zh-CN" :html "&#26410;&#30693;&#24341;&#29992;" :utf-8 "未知引用")))
5812 "Dictionary for export engine.
5814 Alist whose car is the string to translate and cdr is an alist
5815 whose car is the language string and cdr is a plist whose
5816 properties are possible charsets and values translated terms.
5818 It is used as a database for `org-export-translate'. Since this
5819 function returns the string as-is if no translation was found,
5820 the variable only needs to record values different from the
5821 entry.")
5823 (defun org-export-translate (s encoding info)
5824 "Translate string S according to language specification.
5826 ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1'
5827 and `:utf-8'. INFO is a plist used as a communication channel.
5829 Translation depends on `:language' property. Return the
5830 translated string. If no translation is found, try to fall back
5831 to `:default' encoding. If it fails, return S."
5832 (let* ((lang (plist-get info :language))
5833 (translations (cdr (assoc lang
5834 (cdr (assoc s org-export-dictionary))))))
5835 (or (plist-get translations encoding)
5836 (plist-get translations :default)
5837 s)))
5841 ;;; Asynchronous Export
5843 ;; `org-export-async-start' is the entry point for asynchronous
5844 ;; export. It recreates current buffer (including visibility,
5845 ;; narrowing and visited file) in an external Emacs process, and
5846 ;; evaluates a command there. It then applies a function on the
5847 ;; returned results in the current process.
5849 ;; At a higher level, `org-export-to-buffer' and `org-export-to-file'
5850 ;; allow exporting to a buffer or a file, asynchronously or not.
5852 ;; `org-export-output-file-name' is an auxiliary function meant to be
5853 ;; used with `org-export-to-file'. With a given extension, it tries
5854 ;; to provide a canonical file name to write export output to.
5856 ;; Asynchronously generated results are never displayed directly.
5857 ;; Instead, they are stored in `org-export-stack-contents'. They can
5858 ;; then be retrieved by calling `org-export-stack'.
5860 ;; Export Stack is viewed through a dedicated major mode
5861 ;;`org-export-stack-mode' and tools: `org-export-stack-refresh',
5862 ;;`org-export-stack-delete', `org-export-stack-view' and
5863 ;;`org-export-stack-clear'.
5865 ;; For back-ends, `org-export-add-to-stack' add a new source to stack.
5866 ;; It should be used whenever `org-export-async-start' is called.
5868 (defmacro org-export-async-start (fun &rest body)
5869 "Call function FUN on the results returned by BODY evaluation.
5871 FUN is an anonymous function of one argument. BODY evaluation
5872 happens in an asynchronous process, from a buffer which is an
5873 exact copy of the current one.
5875 Use `org-export-add-to-stack' in FUN in order to register results
5876 in the stack.
5878 This is a low level function. See also `org-export-to-buffer'
5879 and `org-export-to-file' for more specialized functions."
5880 (declare (indent 1) (debug t))
5881 (org-with-gensyms (process temp-file copy-fun proc-buffer coding)
5882 ;; Write the full sexp evaluating BODY in a copy of the current
5883 ;; buffer to a temporary file, as it may be too long for program
5884 ;; args in `start-process'.
5885 `(with-temp-message "Initializing asynchronous export process"
5886 (let ((,copy-fun (org-export--generate-copy-script (current-buffer)))
5887 (,temp-file (make-temp-file "org-export-process"))
5888 (,coding buffer-file-coding-system))
5889 (with-temp-file ,temp-file
5890 (insert
5891 ;; Null characters (from variable values) are inserted
5892 ;; within the file. As a consequence, coding system for
5893 ;; buffer contents will not be recognized properly. So,
5894 ;; we make sure it is the same as the one used to display
5895 ;; the original buffer.
5896 (format ";; -*- coding: %s; -*-\n%S"
5897 ,coding
5898 `(with-temp-buffer
5899 (when org-export-async-debug '(setq debug-on-error t))
5900 ;; Ignore `kill-emacs-hook' and code evaluation
5901 ;; queries from Babel as we need a truly
5902 ;; non-interactive process.
5903 (setq kill-emacs-hook nil
5904 org-babel-confirm-evaluate-answer-no t)
5905 ;; Initialize export framework.
5906 (require 'ox)
5907 ;; Re-create current buffer there.
5908 (funcall ,,copy-fun)
5909 (restore-buffer-modified-p nil)
5910 ;; Sexp to evaluate in the buffer.
5911 (print (progn ,,@body))))))
5912 ;; Start external process.
5913 (let* ((process-connection-type nil)
5914 (,proc-buffer (generate-new-buffer-name "*Org Export Process*"))
5915 (,process
5916 (apply
5917 #'start-process
5918 (append
5919 (list "org-export-process"
5920 ,proc-buffer
5921 (expand-file-name invocation-name invocation-directory)
5922 "--batch")
5923 (if org-export-async-init-file
5924 (list "-Q" "-l" org-export-async-init-file)
5925 (list "-l" user-init-file))
5926 (list "-l" ,temp-file)))))
5927 ;; Register running process in stack.
5928 (org-export-add-to-stack (get-buffer ,proc-buffer) nil ,process)
5929 ;; Set-up sentinel in order to catch results.
5930 (let ((handler ,fun))
5931 (set-process-sentinel
5932 ,process
5933 `(lambda (p status)
5934 (let ((proc-buffer (process-buffer p)))
5935 (when (eq (process-status p) 'exit)
5936 (unwind-protect
5937 (if (zerop (process-exit-status p))
5938 (unwind-protect
5939 (let ((results
5940 (with-current-buffer proc-buffer
5941 (goto-char (point-max))
5942 (backward-sexp)
5943 (read (current-buffer)))))
5944 (funcall ,handler results))
5945 (unless org-export-async-debug
5946 (and (get-buffer proc-buffer)
5947 (kill-buffer proc-buffer))))
5948 (org-export-add-to-stack proc-buffer nil p)
5949 (ding)
5950 (message "Process `%s' exited abnormally" p))
5951 (unless org-export-async-debug
5952 (delete-file ,,temp-file)))))))))))))
5954 ;;;###autoload
5955 (defun org-export-to-buffer
5956 (backend buffer
5957 &optional async subtreep visible-only body-only ext-plist
5958 post-process)
5959 "Call `org-export-as' with output to a specified buffer.
5961 BACKEND is either an export back-end, as returned by, e.g.,
5962 `org-export-create-backend', or a symbol referring to
5963 a registered back-end.
5965 BUFFER is the name of the output buffer. If it already exists,
5966 it will be erased first, otherwise, it will be created.
5968 A non-nil optional argument ASYNC means the process should happen
5969 asynchronously. The resulting buffer should then be accessible
5970 through the `org-export-stack' interface. When ASYNC is nil, the
5971 buffer is displayed if `org-export-show-temporary-export-buffer'
5972 is non-nil.
5974 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
5975 EXT-PLIST are similar to those used in `org-export-as', which
5976 see.
5978 Optional argument POST-PROCESS is a function which should accept
5979 no argument. It is always called within the current process,
5980 from BUFFER, with point at its beginning. Export back-ends can
5981 use it to set a major mode there, e.g,
5983 (defun org-latex-export-as-latex
5984 (&optional async subtreep visible-only body-only ext-plist)
5985 (interactive)
5986 (org-export-to-buffer \\='latex \"*Org LATEX Export*\"
5987 async subtreep visible-only body-only ext-plist (lambda () (LaTeX-mode))))
5989 This function returns BUFFER."
5990 (declare (indent 2))
5991 (if async
5992 (org-export-async-start
5993 `(lambda (output)
5994 (with-current-buffer (get-buffer-create ,buffer)
5995 (erase-buffer)
5996 (setq buffer-file-coding-system ',buffer-file-coding-system)
5997 (insert output)
5998 (goto-char (point-min))
5999 (org-export-add-to-stack (current-buffer) ',backend)
6000 (ignore-errors (funcall ,post-process))))
6001 `(org-export-as
6002 ',backend ,subtreep ,visible-only ,body-only ',ext-plist))
6003 (let ((output
6004 (org-export-as backend subtreep visible-only body-only ext-plist))
6005 (buffer (get-buffer-create buffer))
6006 (encoding buffer-file-coding-system))
6007 (when (and (org-string-nw-p output) (org-export--copy-to-kill-ring-p))
6008 (org-kill-new output))
6009 (with-current-buffer buffer
6010 (erase-buffer)
6011 (setq buffer-file-coding-system encoding)
6012 (insert output)
6013 (goto-char (point-min))
6014 (and (functionp post-process) (funcall post-process)))
6015 (when org-export-show-temporary-export-buffer
6016 (switch-to-buffer-other-window buffer))
6017 buffer)))
6019 ;;;###autoload
6020 (defun org-export-to-file
6021 (backend file &optional async subtreep visible-only body-only ext-plist
6022 post-process)
6023 "Call `org-export-as' with output to a specified file.
6025 BACKEND is either an export back-end, as returned by, e.g.,
6026 `org-export-create-backend', or a symbol referring to
6027 a registered back-end. FILE is the name of the output file, as
6028 a string.
6030 A non-nil optional argument ASYNC means the process should happen
6031 asynchronously. The resulting buffer will then be accessible
6032 through the `org-export-stack' interface.
6034 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
6035 EXT-PLIST are similar to those used in `org-export-as', which
6036 see.
6038 Optional argument POST-PROCESS is called with FILE as its
6039 argument and happens asynchronously when ASYNC is non-nil. It
6040 has to return a file name, or nil. Export back-ends can use this
6041 to send the output file through additional processing, e.g,
6043 (defun org-latex-export-to-latex
6044 (&optional async subtreep visible-only body-only ext-plist)
6045 (interactive)
6046 (let ((outfile (org-export-output-file-name \".tex\" subtreep)))
6047 (org-export-to-file \\='latex outfile
6048 async subtreep visible-only body-only ext-plist
6049 (lambda (file) (org-latex-compile file)))
6051 The function returns either a file name returned by POST-PROCESS,
6052 or FILE."
6053 (declare (indent 2))
6054 (if (not (file-writable-p file)) (error "Output file not writable")
6055 (let ((ext-plist (org-combine-plists `(:output-file ,file) ext-plist))
6056 (encoding (or org-export-coding-system buffer-file-coding-system)))
6057 (if async
6058 (org-export-async-start
6059 `(lambda (file)
6060 (org-export-add-to-stack (expand-file-name file) ',backend))
6061 `(let ((output
6062 (org-export-as
6063 ',backend ,subtreep ,visible-only ,body-only
6064 ',ext-plist)))
6065 (with-temp-buffer
6066 (insert output)
6067 (let ((coding-system-for-write ',encoding))
6068 (write-file ,file)))
6069 (or (ignore-errors (funcall ',post-process ,file)) ,file)))
6070 (let ((output (org-export-as
6071 backend subtreep visible-only body-only ext-plist)))
6072 (with-temp-buffer
6073 (insert output)
6074 (let ((coding-system-for-write encoding))
6075 (write-file file)))
6076 (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p output))
6077 (org-kill-new output))
6078 ;; Get proper return value.
6079 (or (and (functionp post-process) (funcall post-process file))
6080 file))))))
6082 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
6083 "Return output file's name according to buffer specifications.
6085 EXTENSION is a string representing the output file extension,
6086 with the leading dot.
6088 With a non-nil optional argument SUBTREEP, try to determine
6089 output file's name by looking for \"EXPORT_FILE_NAME\" property
6090 of subtree at point.
6092 When optional argument PUB-DIR is set, use it as the publishing
6093 directory.
6095 Return file name as a string."
6096 (let* ((visited-file (buffer-file-name (buffer-base-buffer)))
6097 (base-name
6098 ;; File name may come from EXPORT_FILE_NAME subtree
6099 ;; property.
6100 (file-name-sans-extension
6101 (or (and subtreep (org-entry-get nil "EXPORT_FILE_NAME" 'selective))
6102 ;; File name may be extracted from buffer's associated
6103 ;; file, if any.
6104 (and visited-file (file-name-nondirectory visited-file))
6105 ;; Can't determine file name on our own: Ask user.
6106 (read-file-name
6107 "Output file: " pub-dir nil nil nil
6108 (lambda (name)
6109 (string= (file-name-extension name t) extension))))))
6110 (output-file
6111 ;; Build file name. Enforce EXTENSION over whatever user
6112 ;; may have come up with. PUB-DIR, if defined, always has
6113 ;; precedence over any provided path.
6114 (cond
6115 (pub-dir
6116 (concat (file-name-as-directory pub-dir)
6117 (file-name-nondirectory base-name)
6118 extension))
6119 ((file-name-absolute-p base-name) (concat base-name extension))
6120 (t (concat (file-name-as-directory ".") base-name extension)))))
6121 ;; If writing to OUTPUT-FILE would overwrite original file, append
6122 ;; EXTENSION another time to final name.
6123 (if (and visited-file (file-equal-p visited-file output-file))
6124 (concat output-file extension)
6125 output-file)))
6127 (defun org-export-add-to-stack (source backend &optional process)
6128 "Add a new result to export stack if not present already.
6130 SOURCE is a buffer or a file name containing export results.
6131 BACKEND is a symbol representing export back-end used to generate
6134 Entries already pointing to SOURCE and unavailable entries are
6135 removed beforehand. Return the new stack."
6136 (setq org-export-stack-contents
6137 (cons (list source backend (or process (current-time)))
6138 (org-export-stack-remove source))))
6140 (defun org-export-stack ()
6141 "Menu for asynchronous export results and running processes."
6142 (interactive)
6143 (let ((buffer (get-buffer-create "*Org Export Stack*")))
6144 (with-current-buffer buffer
6145 (org-export-stack-mode)
6146 (tabulated-list-print t))
6147 (pop-to-buffer buffer))
6148 (message "Type \"q\" to quit, \"?\" for help"))
6150 (defun org-export-stack-clear ()
6151 "Remove all entries from export stack."
6152 (interactive)
6153 (setq org-export-stack-contents nil))
6155 (defun org-export-stack-refresh ()
6156 "Refresh the export stack."
6157 (interactive)
6158 (tabulated-list-print t))
6160 (defun org-export-stack-remove (&optional source)
6161 "Remove export results at point from stack.
6162 If optional argument SOURCE is non-nil, remove it instead."
6163 (interactive)
6164 (let ((source (or source (org-export--stack-source-at-point))))
6165 (setq org-export-stack-contents
6166 (cl-remove-if (lambda (el) (equal (car el) source))
6167 org-export-stack-contents))))
6169 (defun org-export-stack-view (&optional in-emacs)
6170 "View export results at point in stack.
6171 With an optional prefix argument IN-EMACS, force viewing files
6172 within Emacs."
6173 (interactive "P")
6174 (let ((source (org-export--stack-source-at-point)))
6175 (cond ((processp source)
6176 (org-switch-to-buffer-other-window (process-buffer source)))
6177 ((bufferp source) (org-switch-to-buffer-other-window source))
6178 (t (org-open-file source in-emacs)))))
6180 (defvar org-export-stack-mode-map
6181 (let ((km (make-sparse-keymap)))
6182 (set-keymap-parent km tabulated-list-mode-map)
6183 (define-key km " " 'next-line)
6184 (define-key km "\C-n" 'next-line)
6185 (define-key km [down] 'next-line)
6186 (define-key km "\C-p" 'previous-line)
6187 (define-key km "\C-?" 'previous-line)
6188 (define-key km [up] 'previous-line)
6189 (define-key km "C" 'org-export-stack-clear)
6190 (define-key km "v" 'org-export-stack-view)
6191 (define-key km (kbd "RET") 'org-export-stack-view)
6192 (define-key km "d" 'org-export-stack-remove)
6194 "Keymap for Org Export Stack.")
6196 (define-derived-mode org-export-stack-mode tabulated-list-mode "Org-Stack"
6197 "Mode for displaying asynchronous export stack.
6199 Type `\\[org-export-stack]' to visualize the asynchronous export
6200 stack.
6202 In an Org Export Stack buffer, use \
6203 \\<org-export-stack-mode-map>`\\[org-export-stack-view]' to view export output
6204 on current line, `\\[org-export-stack-remove]' to remove it from the stack and \
6205 `\\[org-export-stack-clear]' to clear
6206 stack completely.
6208 Removing entries in a stack buffer does not affect files
6209 or buffers, only display.
6211 \\{org-export-stack-mode-map}"
6212 (setq tabulated-list-format
6213 (vector (list "#" 4 #'org-export--stack-num-predicate)
6214 (list "Back-End" 12 t)
6215 (list "Age" 6 nil)
6216 (list "Source" 0 nil)))
6217 (setq tabulated-list-sort-key (cons "#" nil))
6218 (setq tabulated-list-entries #'org-export--stack-generate)
6219 (add-hook 'tabulated-list-revert-hook #'org-export--stack-generate nil t)
6220 (add-hook 'post-command-hook #'org-export-stack-refresh nil t)
6221 (tabulated-list-init-header))
6223 (defun org-export--stack-generate ()
6224 "Generate the asynchronous export stack for display.
6225 Unavailable sources are removed from the list. Return a list
6226 appropriate for `tabulated-list-print'."
6227 ;; Clear stack from exited processes, dead buffers or non-existent
6228 ;; files.
6229 (setq org-export-stack-contents
6230 (cl-remove-if-not
6231 (lambda (el)
6232 (if (processp (nth 2 el))
6233 (buffer-live-p (process-buffer (nth 2 el)))
6234 (let ((source (car el)))
6235 (if (bufferp source) (buffer-live-p source)
6236 (file-exists-p source)))))
6237 org-export-stack-contents))
6238 ;; Update `tabulated-list-entries'.
6239 (let ((counter 0))
6240 (mapcar
6241 (lambda (entry)
6242 (let ((source (car entry)))
6243 (list source
6244 (vector
6245 ;; Counter.
6246 (number-to-string (cl-incf counter))
6247 ;; Back-End.
6248 (if (nth 1 entry) (symbol-name (nth 1 entry)) "")
6249 ;; Age.
6250 (let ((info (nth 2 entry)))
6251 (if (processp info) (symbol-name (process-status info))
6252 (format-seconds "%h:%.2m" (float-time (time-since info)))))
6253 ;; Source.
6254 (if (stringp source) source (buffer-name source))))))
6255 org-export-stack-contents)))
6257 (defun org-export--stack-num-predicate (a b)
6258 (< (string-to-number (aref (nth 1 a) 0))
6259 (string-to-number (aref (nth 1 b) 0))))
6261 (defun org-export--stack-source-at-point ()
6262 "Return source from export results at point in stack."
6263 (let ((source (car (nth (1- (org-current-line)) org-export-stack-contents))))
6264 (if (not source) (error "Source unavailable, please refresh buffer")
6265 (let ((source-name (if (stringp source) source (buffer-name source))))
6266 (if (save-excursion
6267 (beginning-of-line)
6268 (looking-at-p (concat ".* +" (regexp-quote source-name) "$")))
6269 source
6270 ;; SOURCE is not consistent with current line. The stack
6271 ;; view is outdated.
6272 (error (substitute-command-keys
6273 "Source unavailable; type `\\[org-export-stack-refresh]' \
6274 to refresh buffer")))))))
6278 ;;; The Dispatcher
6280 ;; `org-export-dispatch' is the standard interactive way to start an
6281 ;; export process. It uses `org-export--dispatch-ui' as a subroutine
6282 ;; for its interface, which, in turn, delegates response to key
6283 ;; pressed to `org-export--dispatch-action'.
6285 ;;;###autoload
6286 (defun org-export-dispatch (&optional arg)
6287 "Export dispatcher for Org mode.
6289 It provides an access to common export related tasks in a buffer.
6290 Its interface comes in two flavors: standard and expert.
6292 While both share the same set of bindings, only the former
6293 displays the valid keys associations in a dedicated buffer.
6294 Scrolling (resp. line-wise motion) in this buffer is done with
6295 SPC and DEL (resp. C-n and C-p) keys.
6297 Set variable `org-export-dispatch-use-expert-ui' to switch to one
6298 flavor or the other.
6300 When ARG is `\\[universal-argument]', repeat the last export action, with the\
6301 same
6302 set of options used back then, on the current buffer.
6304 When ARG is `\\[universal-argument] \\[universal-argument]', display the \
6305 asynchronous export stack."
6306 (interactive "P")
6307 (let* ((input
6308 (cond ((equal arg '(16)) '(stack))
6309 ((and arg org-export-dispatch-last-action))
6310 (t (save-window-excursion
6311 (unwind-protect
6312 (progn
6313 ;; Remember where we are
6314 (move-marker org-export-dispatch-last-position
6315 (point)
6316 (org-base-buffer (current-buffer)))
6317 ;; Get and store an export command
6318 (setq org-export-dispatch-last-action
6319 (org-export--dispatch-ui
6320 (list org-export-initial-scope
6321 (and org-export-in-background 'async))
6323 org-export-dispatch-use-expert-ui)))
6324 (and (get-buffer "*Org Export Dispatcher*")
6325 (kill-buffer "*Org Export Dispatcher*")))))))
6326 (action (car input))
6327 (optns (cdr input)))
6328 (unless (memq 'subtree optns)
6329 (move-marker org-export-dispatch-last-position nil))
6330 (cl-case action
6331 ;; First handle special hard-coded actions.
6332 (template (org-export-insert-default-template nil optns))
6333 (stack (org-export-stack))
6334 (publish-current-file
6335 (org-publish-current-file (memq 'force optns) (memq 'async optns)))
6336 (publish-current-project
6337 (org-publish-current-project (memq 'force optns) (memq 'async optns)))
6338 (publish-choose-project
6339 (org-publish (assoc (completing-read
6340 "Publish project: "
6341 org-publish-project-alist nil t)
6342 org-publish-project-alist)
6343 (memq 'force optns)
6344 (memq 'async optns)))
6345 (publish-all (org-publish-all (memq 'force optns) (memq 'async optns)))
6346 (otherwise
6347 (save-excursion
6348 (when arg
6349 ;; Repeating command, maybe move cursor to restore subtree
6350 ;; context.
6351 (if (eq (marker-buffer org-export-dispatch-last-position)
6352 (org-base-buffer (current-buffer)))
6353 (goto-char org-export-dispatch-last-position)
6354 ;; We are in a different buffer, forget position.
6355 (move-marker org-export-dispatch-last-position nil)))
6356 (funcall action
6357 ;; Return a symbol instead of a list to ease
6358 ;; asynchronous export macro use.
6359 (and (memq 'async optns) t)
6360 (and (memq 'subtree optns) t)
6361 (and (memq 'visible optns) t)
6362 (and (memq 'body optns) t)))))))
6364 (defun org-export--dispatch-ui (options first-key expertp)
6365 "Handle interface for `org-export-dispatch'.
6367 OPTIONS is a list containing current interactive options set for
6368 export. It can contain any of the following symbols:
6369 `body' toggles a body-only export
6370 `subtree' restricts export to current subtree
6371 `visible' restricts export to visible part of buffer.
6372 `force' force publishing files.
6373 `async' use asynchronous export process
6375 FIRST-KEY is the key pressed to select the first level menu. It
6376 is nil when this menu hasn't been selected yet.
6378 EXPERTP, when non-nil, triggers expert UI. In that case, no help
6379 buffer is provided, but indications about currently active
6380 options are given in the prompt. Moreover, [?] allows switching
6381 back to standard interface."
6382 (let* ((fontify-key
6383 (lambda (key &optional access-key)
6384 ;; Fontify KEY string. Optional argument ACCESS-KEY, when
6385 ;; non-nil is the required first-level key to activate
6386 ;; KEY. When its value is t, activate KEY independently
6387 ;; on the first key, if any. A nil value means KEY will
6388 ;; only be activated at first level.
6389 (if (or (eq access-key t) (eq access-key first-key))
6390 (propertize key 'face 'org-warning)
6391 key)))
6392 (fontify-value
6393 (lambda (value)
6394 ;; Fontify VALUE string.
6395 (propertize value 'face 'font-lock-variable-name-face)))
6396 ;; Prepare menu entries by extracting them from registered
6397 ;; back-ends and sorting them by access key and by ordinal,
6398 ;; if any.
6399 (entries
6400 (sort (sort (delq nil
6401 (mapcar #'org-export-backend-menu
6402 org-export-registered-backends))
6403 (lambda (a b)
6404 (let ((key-a (nth 1 a))
6405 (key-b (nth 1 b)))
6406 (cond ((and (numberp key-a) (numberp key-b))
6407 (< key-a key-b))
6408 ((numberp key-b) t)))))
6409 'car-less-than-car))
6410 ;; Compute a list of allowed keys based on the first key
6411 ;; pressed, if any. Some keys
6412 ;; (?^B, ?^V, ?^S, ?^F, ?^A, ?&, ?# and ?q) are always
6413 ;; available.
6414 (allowed-keys
6415 (nconc (list 2 22 19 6 1)
6416 (if (not first-key) (org-uniquify (mapcar 'car entries))
6417 (let (sub-menu)
6418 (dolist (entry entries (sort (mapcar 'car sub-menu) '<))
6419 (when (eq (car entry) first-key)
6420 (setq sub-menu (append (nth 2 entry) sub-menu))))))
6421 (cond ((eq first-key ?P) (list ?f ?p ?x ?a))
6422 ((not first-key) (list ?P)))
6423 (list ?& ?#)
6424 (when expertp (list ??))
6425 (list ?q)))
6426 ;; Build the help menu for standard UI.
6427 (help
6428 (unless expertp
6429 (concat
6430 ;; Options are hard-coded.
6431 (format "[%s] Body only: %s [%s] Visible only: %s
6432 \[%s] Export scope: %s [%s] Force publishing: %s
6433 \[%s] Async export: %s\n\n"
6434 (funcall fontify-key "C-b" t)
6435 (funcall fontify-value
6436 (if (memq 'body options) "On " "Off"))
6437 (funcall fontify-key "C-v" t)
6438 (funcall fontify-value
6439 (if (memq 'visible options) "On " "Off"))
6440 (funcall fontify-key "C-s" t)
6441 (funcall fontify-value
6442 (if (memq 'subtree options) "Subtree" "Buffer "))
6443 (funcall fontify-key "C-f" t)
6444 (funcall fontify-value
6445 (if (memq 'force options) "On " "Off"))
6446 (funcall fontify-key "C-a" t)
6447 (funcall fontify-value
6448 (if (memq 'async options) "On " "Off")))
6449 ;; Display registered back-end entries. When a key
6450 ;; appears for the second time, do not create another
6451 ;; entry, but append its sub-menu to existing menu.
6452 (let (last-key)
6453 (mapconcat
6454 (lambda (entry)
6455 (let ((top-key (car entry)))
6456 (concat
6457 (unless (eq top-key last-key)
6458 (setq last-key top-key)
6459 (format "\n[%s] %s\n"
6460 (funcall fontify-key (char-to-string top-key))
6461 (nth 1 entry)))
6462 (let ((sub-menu (nth 2 entry)))
6463 (unless (functionp sub-menu)
6464 ;; Split sub-menu into two columns.
6465 (let ((index -1))
6466 (concat
6467 (mapconcat
6468 (lambda (sub-entry)
6469 (cl-incf index)
6470 (format
6471 (if (zerop (mod index 2)) " [%s] %-26s"
6472 "[%s] %s\n")
6473 (funcall fontify-key
6474 (char-to-string (car sub-entry))
6475 top-key)
6476 (nth 1 sub-entry)))
6477 sub-menu "")
6478 (when (zerop (mod index 2)) "\n"))))))))
6479 entries ""))
6480 ;; Publishing menu is hard-coded.
6481 (format "\n[%s] Publish
6482 [%s] Current file [%s] Current project
6483 [%s] Choose project [%s] All projects\n\n\n"
6484 (funcall fontify-key "P")
6485 (funcall fontify-key "f" ?P)
6486 (funcall fontify-key "p" ?P)
6487 (funcall fontify-key "x" ?P)
6488 (funcall fontify-key "a" ?P))
6489 (format "[%s] Export stack [%s] Insert template\n"
6490 (funcall fontify-key "&" t)
6491 (funcall fontify-key "#" t))
6492 (format "[%s] %s"
6493 (funcall fontify-key "q" t)
6494 (if first-key "Main menu" "Exit")))))
6495 ;; Build prompts for both standard and expert UI.
6496 (standard-prompt (unless expertp "Export command: "))
6497 (expert-prompt
6498 (when expertp
6499 (format
6500 "Export command (C-%s%s%s%s%s) [%s]: "
6501 (if (memq 'body options) (funcall fontify-key "b" t) "b")
6502 (if (memq 'visible options) (funcall fontify-key "v" t) "v")
6503 (if (memq 'subtree options) (funcall fontify-key "s" t) "s")
6504 (if (memq 'force options) (funcall fontify-key "f" t) "f")
6505 (if (memq 'async options) (funcall fontify-key "a" t) "a")
6506 (mapconcat (lambda (k)
6507 ;; Strip control characters.
6508 (unless (< k 27) (char-to-string k)))
6509 allowed-keys "")))))
6510 ;; With expert UI, just read key with a fancy prompt. In standard
6511 ;; UI, display an intrusive help buffer.
6512 (if expertp
6513 (org-export--dispatch-action
6514 expert-prompt allowed-keys entries options first-key expertp)
6515 ;; At first call, create frame layout in order to display menu.
6516 (unless (get-buffer "*Org Export Dispatcher*")
6517 (delete-other-windows)
6518 (org-switch-to-buffer-other-window
6519 (get-buffer-create "*Org Export Dispatcher*"))
6520 (setq cursor-type nil
6521 header-line-format "Use SPC, DEL, C-n or C-p to navigate.")
6522 ;; Make sure that invisible cursor will not highlight square
6523 ;; brackets.
6524 (set-syntax-table (copy-syntax-table))
6525 (modify-syntax-entry ?\[ "w"))
6526 ;; At this point, the buffer containing the menu exists and is
6527 ;; visible in the current window. So, refresh it.
6528 (with-current-buffer "*Org Export Dispatcher*"
6529 ;; Refresh help. Maintain display continuity by re-visiting
6530 ;; previous window position.
6531 (let ((pos (window-start)))
6532 (erase-buffer)
6533 (insert help)
6534 (set-window-start nil pos)))
6535 (org-fit-window-to-buffer)
6536 (org-export--dispatch-action
6537 standard-prompt allowed-keys entries options first-key expertp))))
6539 (defun org-export--dispatch-action
6540 (prompt allowed-keys entries options first-key expertp)
6541 "Read a character from command input and act accordingly.
6543 PROMPT is the displayed prompt, as a string. ALLOWED-KEYS is
6544 a list of characters available at a given step in the process.
6545 ENTRIES is a list of menu entries. OPTIONS, FIRST-KEY and
6546 EXPERTP are the same as defined in `org-export--dispatch-ui',
6547 which see.
6549 Toggle export options when required. Otherwise, return value is
6550 a list with action as CAR and a list of interactive export
6551 options as CDR."
6552 (let (key)
6553 ;; Scrolling: when in non-expert mode, act on motion keys (C-n,
6554 ;; C-p, SPC, DEL).
6555 (while (and (setq key (read-char-exclusive prompt))
6556 (not expertp)
6557 (memq key '(14 16 ?\s ?\d)))
6558 (cl-case key
6559 (14 (if (not (pos-visible-in-window-p (point-max)))
6560 (ignore-errors (scroll-up 1))
6561 (message "End of buffer")
6562 (sit-for 1)))
6563 (16 (if (not (pos-visible-in-window-p (point-min)))
6564 (ignore-errors (scroll-down 1))
6565 (message "Beginning of buffer")
6566 (sit-for 1)))
6567 (?\s (if (not (pos-visible-in-window-p (point-max)))
6568 (scroll-up nil)
6569 (message "End of buffer")
6570 (sit-for 1)))
6571 (?\d (if (not (pos-visible-in-window-p (point-min)))
6572 (scroll-down nil)
6573 (message "Beginning of buffer")
6574 (sit-for 1)))))
6575 (cond
6576 ;; Ignore undefined associations.
6577 ((not (memq key allowed-keys))
6578 (ding)
6579 (unless expertp (message "Invalid key") (sit-for 1))
6580 (org-export--dispatch-ui options first-key expertp))
6581 ;; q key at first level aborts export. At second level, cancel
6582 ;; first key instead.
6583 ((eq key ?q) (if (not first-key) (error "Export aborted")
6584 (org-export--dispatch-ui options nil expertp)))
6585 ;; Help key: Switch back to standard interface if expert UI was
6586 ;; active.
6587 ((eq key ??) (org-export--dispatch-ui options first-key nil))
6588 ;; Send request for template insertion along with export scope.
6589 ((eq key ?#) (cons 'template (memq 'subtree options)))
6590 ;; Switch to asynchronous export stack.
6591 ((eq key ?&) '(stack))
6592 ;; Toggle options: C-b (2) C-v (22) C-s (19) C-f (6) C-a (1).
6593 ((memq key '(2 22 19 6 1))
6594 (org-export--dispatch-ui
6595 (let ((option (cl-case key (2 'body) (22 'visible) (19 'subtree)
6596 (6 'force) (1 'async))))
6597 (if (memq option options) (remq option options)
6598 (cons option options)))
6599 first-key expertp))
6600 ;; Action selected: Send key and options back to
6601 ;; `org-export-dispatch'.
6602 ((or first-key (functionp (nth 2 (assq key entries))))
6603 (cons (cond
6604 ((not first-key) (nth 2 (assq key entries)))
6605 ;; Publishing actions are hard-coded. Send a special
6606 ;; signal to `org-export-dispatch'.
6607 ((eq first-key ?P)
6608 (cl-case key
6609 (?f 'publish-current-file)
6610 (?p 'publish-current-project)
6611 (?x 'publish-choose-project)
6612 (?a 'publish-all)))
6613 ;; Return first action associated to FIRST-KEY + KEY
6614 ;; path. Indeed, derived backends can share the same
6615 ;; FIRST-KEY.
6616 (t (catch 'found
6617 (dolist (entry (member (assq first-key entries) entries))
6618 (let ((match (assq key (nth 2 entry))))
6619 (when match (throw 'found (nth 2 match))))))))
6620 options))
6621 ;; Otherwise, enter sub-menu.
6622 (t (org-export--dispatch-ui options key expertp)))))
6626 (provide 'ox)
6628 ;; Local variables:
6629 ;; generated-autoload-file: "org-loaddefs.el"
6630 ;; End:
6632 ;;; ox.el ends here