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