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