Merge branch 'maint'
[org-mode.git] / lisp / ox.el
blob11ab4c1bdb714db5f3d7697b46e467a03cbd38eb
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 first paragraph
2005 ;; of an item or
2006 ;; a footnote-definition, ignore
2007 ;; first line's indentation.
2008 (and
2009 (eq type 'paragraph)
2010 (memq (org-element-type parent)
2011 '(footnote-definition item))
2012 (eq (car (org-element-contents parent))
2013 data)
2014 (eq (org-element-property :pre-blank parent)
2015 0)))))
2016 "")))
2017 (broken-link-handler
2018 (funcall transcoder data
2019 (if (not greaterp) contents
2020 (org-element-normalize-string contents))
2021 info)))))))))
2022 ;; Final result will be memoized before being returned.
2023 (puthash
2024 data
2025 (cond
2026 ((not results) "")
2027 ((memq type '(org-data plain-text nil)) results)
2028 ;; Append the same white space between elements or objects
2029 ;; as in the original buffer, and call appropriate filters.
2031 (org-export-filter-apply-functions
2032 (plist-get info (intern (format ":filter-%s" type)))
2033 (let ((blank (or (org-element-property :post-blank data) 0)))
2034 (if (eq (org-element-class data parent) 'object)
2035 (concat results (make-string blank ?\s))
2036 (concat (org-element-normalize-string results)
2037 (make-string blank ?\n))))
2038 info)))
2039 (plist-get info :exported-data))))))
2041 (defun org-export-data-with-backend (data backend info)
2042 "Convert DATA into BACKEND format.
2044 DATA is an element, an object, a secondary string or a string.
2045 BACKEND is a symbol. INFO is a plist used as a communication
2046 channel.
2048 Unlike to `org-export-with-backend', this function will
2049 recursively convert DATA using BACKEND translation table."
2050 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
2051 ;; Set-up a new communication channel with translations defined in
2052 ;; BACKEND as the translate table and a new hash table for
2053 ;; memoization.
2054 (let ((new-info
2055 (org-combine-plists
2056 info
2057 (list :back-end backend
2058 :translate-alist (org-export-get-all-transcoders backend)
2059 ;; Size of the hash table is reduced since this
2060 ;; function will probably be used on small trees.
2061 :exported-data (make-hash-table :test 'eq :size 401)))))
2062 (prog1 (org-export-data data new-info)
2063 ;; Preserve `:internal-references', as those do not depend on
2064 ;; the back-end used; we need to make sure that any new
2065 ;; reference when the temporary back-end was active gets through
2066 ;; the default one.
2067 (plist-put info :internal-references
2068 (plist-get new-info :internal-references)))))
2070 (defun org-export-expand (blob contents &optional with-affiliated)
2071 "Expand a parsed element or object to its original state.
2073 BLOB is either an element or an object. CONTENTS is its
2074 contents, as a string or nil.
2076 When optional argument WITH-AFFILIATED is non-nil, add affiliated
2077 keywords before output."
2078 (let ((type (org-element-type blob)))
2079 (concat (and with-affiliated
2080 (eq (org-element-class blob) 'element)
2081 (org-element--interpret-affiliated-keywords blob))
2082 (funcall (intern (format "org-element-%s-interpreter" type))
2083 blob contents))))
2087 ;;; The Filter System
2089 ;; Filters allow end-users to tweak easily the transcoded output.
2090 ;; They are the functional counterpart of hooks, as every filter in
2091 ;; a set is applied to the return value of the previous one.
2093 ;; Every set is back-end agnostic. Although, a filter is always
2094 ;; called, in addition to the string it applies to, with the back-end
2095 ;; used as argument, so it's easy for the end-user to add back-end
2096 ;; specific filters in the set. The communication channel, as
2097 ;; a plist, is required as the third argument.
2099 ;; From the developer side, filters sets can be installed in the
2100 ;; process with the help of `org-export-define-backend', which
2101 ;; internally stores filters as an alist. Each association has a key
2102 ;; among the following symbols and a function or a list of functions
2103 ;; as value.
2105 ;; - `:filter-options' applies to the property list containing export
2106 ;; options. Unlike to other filters, functions in this list accept
2107 ;; two arguments instead of three: the property list containing
2108 ;; export options and the back-end. Users can set its value through
2109 ;; `org-export-filter-options-functions' variable.
2111 ;; - `:filter-parse-tree' applies directly to the complete parsed
2112 ;; tree. Users can set it through
2113 ;; `org-export-filter-parse-tree-functions' variable.
2115 ;; - `:filter-body' applies to the body of the output, before template
2116 ;; translator chimes in. Users can set it through
2117 ;; `org-export-filter-body-functions' variable.
2119 ;; - `:filter-final-output' applies to the final transcoded string.
2120 ;; Users can set it with `org-export-filter-final-output-functions'
2121 ;; variable.
2123 ;; - `:filter-plain-text' applies to any string not recognized as Org
2124 ;; syntax. `org-export-filter-plain-text-functions' allows users to
2125 ;; configure it.
2127 ;; - `:filter-TYPE' applies on the string returned after an element or
2128 ;; object of type TYPE has been transcoded. A user can modify
2129 ;; `org-export-filter-TYPE-functions' to install these filters.
2131 ;; All filters sets are applied with
2132 ;; `org-export-filter-apply-functions' function. Filters in a set are
2133 ;; applied in a LIFO fashion. It allows developers to be sure that
2134 ;; their filters will be applied first.
2136 ;; Filters properties are installed in communication channel with
2137 ;; `org-export-install-filters' function.
2139 ;; Eventually, two hooks (`org-export-before-processing-hook' and
2140 ;; `org-export-before-parsing-hook') are run at the beginning of the
2141 ;; export process and just before parsing to allow for heavy structure
2142 ;; modifications.
2145 ;;;; Hooks
2147 (defvar org-export-before-processing-hook nil
2148 "Hook run at the beginning of the export process.
2150 This is run before include keywords and macros are expanded and
2151 Babel code blocks executed, on a copy of the original buffer
2152 being exported. Visibility and narrowing are preserved. Point
2153 is at the beginning of the buffer.
2155 Every function in this hook will be called with one argument: the
2156 back-end currently used, as a symbol.")
2158 (defvar org-export-before-parsing-hook nil
2159 "Hook run before parsing an export buffer.
2161 This is run after include keywords and macros have been expanded
2162 and Babel code blocks executed, on a copy of the original buffer
2163 being exported. Visibility and narrowing are preserved. Point
2164 is at the beginning of the buffer.
2166 Every function in this hook will be called with one argument: the
2167 back-end currently used, as a symbol.")
2170 ;;;; Special Filters
2172 (defvar org-export-filter-options-functions nil
2173 "List of functions applied to the export options.
2174 Each filter is called with two arguments: the export options, as
2175 a plist, and the back-end, as a symbol. It must return
2176 a property list containing export options.")
2178 (defvar org-export-filter-parse-tree-functions nil
2179 "List of functions applied to the parsed tree.
2180 Each filter is called with three arguments: the parse tree, as
2181 returned by `org-element-parse-buffer', the back-end, as
2182 a symbol, and the communication channel, as a plist. It must
2183 return the modified parse tree to transcode.")
2185 (defvar org-export-filter-plain-text-functions nil
2186 "List of functions applied to plain text.
2187 Each filter is called with three arguments: a string which
2188 contains no Org syntax, the back-end, as a symbol, and the
2189 communication channel, as a plist. It must return a string or
2190 nil.")
2192 (defvar org-export-filter-body-functions nil
2193 "List of functions applied to transcoded body.
2194 Each filter is called with three arguments: a string which
2195 contains no Org syntax, the back-end, as a symbol, and the
2196 communication channel, as a plist. It must return a string or
2197 nil.")
2199 (defvar org-export-filter-final-output-functions nil
2200 "List of functions applied to the transcoded string.
2201 Each filter is called with three arguments: the full transcoded
2202 string, the back-end, as a symbol, and the communication channel,
2203 as a plist. It must return a string that will be used as the
2204 final export output.")
2207 ;;;; Elements Filters
2209 (defvar org-export-filter-babel-call-functions nil
2210 "List of functions applied to a transcoded babel-call.
2211 Each filter is called with three arguments: the transcoded data,
2212 as a string, the back-end, as a symbol, and the communication
2213 channel, as a plist. It must return a string or nil.")
2215 (defvar org-export-filter-center-block-functions nil
2216 "List of functions applied to a transcoded center block.
2217 Each filter is called with three arguments: the transcoded data,
2218 as a string, the back-end, as a symbol, and the communication
2219 channel, as a plist. It must return a string or nil.")
2221 (defvar org-export-filter-clock-functions nil
2222 "List of functions applied to a transcoded clock.
2223 Each filter is called with three arguments: the transcoded data,
2224 as a string, the back-end, as a symbol, and the communication
2225 channel, as a plist. It must return a string or nil.")
2227 (defvar org-export-filter-diary-sexp-functions nil
2228 "List of functions applied to a transcoded diary-sexp.
2229 Each filter is called with three arguments: the transcoded data,
2230 as a string, the back-end, as a symbol, and the communication
2231 channel, as a plist. It must return a string or nil.")
2233 (defvar org-export-filter-drawer-functions nil
2234 "List of functions applied to a transcoded drawer.
2235 Each filter is called with three arguments: the transcoded data,
2236 as a string, the back-end, as a symbol, and the communication
2237 channel, as a plist. It must return a string or nil.")
2239 (defvar org-export-filter-dynamic-block-functions nil
2240 "List of functions applied to a transcoded dynamic-block.
2241 Each filter is called with three arguments: the transcoded data,
2242 as a string, the back-end, as a symbol, and the communication
2243 channel, as a plist. It must return a string or nil.")
2245 (defvar org-export-filter-example-block-functions nil
2246 "List of functions applied to a transcoded example-block.
2247 Each filter is called with three arguments: the transcoded data,
2248 as a string, the back-end, as a symbol, and the communication
2249 channel, as a plist. It must return a string or nil.")
2251 (defvar org-export-filter-export-block-functions nil
2252 "List of functions applied to a transcoded export-block.
2253 Each filter is called with three arguments: the transcoded data,
2254 as a string, the back-end, as a symbol, and the communication
2255 channel, as a plist. It must return a string or nil.")
2257 (defvar org-export-filter-fixed-width-functions nil
2258 "List of functions applied to a transcoded fixed-width.
2259 Each filter is called with three arguments: the transcoded data,
2260 as a string, the back-end, as a symbol, and the communication
2261 channel, as a plist. It must return a string or nil.")
2263 (defvar org-export-filter-footnote-definition-functions nil
2264 "List of functions applied to a transcoded footnote-definition.
2265 Each filter is called with three arguments: the transcoded data,
2266 as a string, the back-end, as a symbol, and the communication
2267 channel, as a plist. It must return a string or nil.")
2269 (defvar org-export-filter-headline-functions nil
2270 "List of functions applied to a transcoded headline.
2271 Each filter is called with three arguments: the transcoded data,
2272 as a string, the back-end, as a symbol, and the communication
2273 channel, as a plist. It must return a string or nil.")
2275 (defvar org-export-filter-horizontal-rule-functions nil
2276 "List of functions applied to a transcoded horizontal-rule.
2277 Each filter is called with three arguments: the transcoded data,
2278 as a string, the back-end, as a symbol, and the communication
2279 channel, as a plist. It must return a string or nil.")
2281 (defvar org-export-filter-inlinetask-functions nil
2282 "List of functions applied to a transcoded inlinetask.
2283 Each filter is called with three arguments: the transcoded data,
2284 as a string, the back-end, as a symbol, and the communication
2285 channel, as a plist. It must return a string or nil.")
2287 (defvar org-export-filter-item-functions nil
2288 "List of functions applied to a transcoded item.
2289 Each filter is called with three arguments: the transcoded data,
2290 as a string, the back-end, as a symbol, and the communication
2291 channel, as a plist. It must return a string or nil.")
2293 (defvar org-export-filter-keyword-functions nil
2294 "List of functions applied to a transcoded keyword.
2295 Each filter is called with three arguments: the transcoded data,
2296 as a string, the back-end, as a symbol, and the communication
2297 channel, as a plist. It must return a string or nil.")
2299 (defvar org-export-filter-latex-environment-functions nil
2300 "List of functions applied to a transcoded latex-environment.
2301 Each filter is called with three arguments: the transcoded data,
2302 as a string, the back-end, as a symbol, and the communication
2303 channel, as a plist. It must return a string or nil.")
2305 (defvar org-export-filter-node-property-functions nil
2306 "List of functions applied to a transcoded node-property.
2307 Each filter is called with three arguments: the transcoded data,
2308 as a string, the back-end, as a symbol, and the communication
2309 channel, as a plist. It must return a string or nil.")
2311 (defvar org-export-filter-paragraph-functions nil
2312 "List of functions applied to a transcoded paragraph.
2313 Each filter is called with three arguments: the transcoded data,
2314 as a string, the back-end, as a symbol, and the communication
2315 channel, as a plist. It must return a string or nil.")
2317 (defvar org-export-filter-plain-list-functions nil
2318 "List of functions applied to a transcoded plain-list.
2319 Each filter is called with three arguments: the transcoded data,
2320 as a string, the back-end, as a symbol, and the communication
2321 channel, as a plist. It must return a string or nil.")
2323 (defvar org-export-filter-planning-functions nil
2324 "List of functions applied to a transcoded planning.
2325 Each filter is called with three arguments: the transcoded data,
2326 as a string, the back-end, as a symbol, and the communication
2327 channel, as a plist. It must return a string or nil.")
2329 (defvar org-export-filter-property-drawer-functions nil
2330 "List of functions applied to a transcoded property-drawer.
2331 Each filter is called with three arguments: the transcoded data,
2332 as a string, the back-end, as a symbol, and the communication
2333 channel, as a plist. It must return a string or nil.")
2335 (defvar org-export-filter-quote-block-functions nil
2336 "List of functions applied to a transcoded quote block.
2337 Each filter is called with three arguments: the transcoded quote
2338 data, as a string, the back-end, as a symbol, and the
2339 communication channel, as a plist. It must return a string or
2340 nil.")
2342 (defvar org-export-filter-section-functions nil
2343 "List of functions applied to a transcoded section.
2344 Each filter is called with three arguments: the transcoded data,
2345 as a string, the back-end, as a symbol, and the communication
2346 channel, as a plist. It must return a string or nil.")
2348 (defvar org-export-filter-special-block-functions nil
2349 "List of functions applied to a transcoded special block.
2350 Each filter is called with three arguments: the transcoded data,
2351 as a string, the back-end, as a symbol, and the communication
2352 channel, as a plist. It must return a string or nil.")
2354 (defvar org-export-filter-src-block-functions nil
2355 "List of functions applied to a transcoded src-block.
2356 Each filter is called with three arguments: the transcoded data,
2357 as a string, the back-end, as a symbol, and the communication
2358 channel, as a plist. It must return a string or nil.")
2360 (defvar org-export-filter-table-functions nil
2361 "List of functions applied to a transcoded table.
2362 Each filter is called with three arguments: the transcoded data,
2363 as a string, the back-end, as a symbol, and the communication
2364 channel, as a plist. It must return a string or nil.")
2366 (defvar org-export-filter-table-cell-functions nil
2367 "List of functions applied to a transcoded table-cell.
2368 Each filter is called with three arguments: the transcoded data,
2369 as a string, the back-end, as a symbol, and the communication
2370 channel, as a plist. It must return a string or nil.")
2372 (defvar org-export-filter-table-row-functions nil
2373 "List of functions applied to a transcoded table-row.
2374 Each filter is called with three arguments: the transcoded data,
2375 as a string, the back-end, as a symbol, and the communication
2376 channel, as a plist. It must return a string or nil.")
2378 (defvar org-export-filter-verse-block-functions nil
2379 "List of functions applied to a transcoded verse block.
2380 Each filter is called with three arguments: the transcoded data,
2381 as a string, the back-end, as a symbol, and the communication
2382 channel, as a plist. It must return a string or nil.")
2385 ;;;; Objects Filters
2387 (defvar org-export-filter-bold-functions nil
2388 "List of functions applied to transcoded bold text.
2389 Each filter is called with three arguments: the transcoded data,
2390 as a string, the back-end, as a symbol, and the communication
2391 channel, as a plist. It must return a string or nil.")
2393 (defvar org-export-filter-code-functions nil
2394 "List of functions applied to transcoded code text.
2395 Each filter is called with three arguments: the transcoded data,
2396 as a string, the back-end, as a symbol, and the communication
2397 channel, as a plist. It must return a string or nil.")
2399 (defvar org-export-filter-entity-functions nil
2400 "List of functions applied to a transcoded entity.
2401 Each filter is called with three arguments: the transcoded data,
2402 as a string, the back-end, as a symbol, and the communication
2403 channel, as a plist. It must return a string or nil.")
2405 (defvar org-export-filter-export-snippet-functions nil
2406 "List of functions applied to a transcoded export-snippet.
2407 Each filter is called with three arguments: the transcoded data,
2408 as a string, the back-end, as a symbol, and the communication
2409 channel, as a plist. It must return a string or nil.")
2411 (defvar org-export-filter-footnote-reference-functions nil
2412 "List of functions applied to a transcoded footnote-reference.
2413 Each filter is called with three arguments: the transcoded data,
2414 as a string, the back-end, as a symbol, and the communication
2415 channel, as a plist. It must return a string or nil.")
2417 (defvar org-export-filter-inline-babel-call-functions nil
2418 "List of functions applied to a transcoded inline-babel-call.
2419 Each filter is called with three arguments: the transcoded data,
2420 as a string, the back-end, as a symbol, and the communication
2421 channel, as a plist. It must return a string or nil.")
2423 (defvar org-export-filter-inline-src-block-functions nil
2424 "List of functions applied to a transcoded inline-src-block.
2425 Each filter is called with three arguments: the transcoded data,
2426 as a string, the back-end, as a symbol, and the communication
2427 channel, as a plist. It must return a string or nil.")
2429 (defvar org-export-filter-italic-functions nil
2430 "List of functions applied to transcoded italic text.
2431 Each filter is called with three arguments: the transcoded data,
2432 as a string, the back-end, as a symbol, and the communication
2433 channel, as a plist. It must return a string or nil.")
2435 (defvar org-export-filter-latex-fragment-functions nil
2436 "List of functions applied to a transcoded latex-fragment.
2437 Each filter is called with three arguments: the transcoded data,
2438 as a string, the back-end, as a symbol, and the communication
2439 channel, as a plist. It must return a string or nil.")
2441 (defvar org-export-filter-line-break-functions nil
2442 "List of functions applied to a transcoded line-break.
2443 Each filter is called with three arguments: the transcoded data,
2444 as a string, the back-end, as a symbol, and the communication
2445 channel, as a plist. It must return a string or nil.")
2447 (defvar org-export-filter-link-functions nil
2448 "List of functions applied to a transcoded link.
2449 Each filter is called with three arguments: the transcoded data,
2450 as a string, the back-end, as a symbol, and the communication
2451 channel, as a plist. It must return a string or nil.")
2453 (defvar org-export-filter-radio-target-functions nil
2454 "List of functions applied to a transcoded radio-target.
2455 Each filter is called with three arguments: the transcoded data,
2456 as a string, the back-end, as a symbol, and the communication
2457 channel, as a plist. It must return a string or nil.")
2459 (defvar org-export-filter-statistics-cookie-functions nil
2460 "List of functions applied to a transcoded statistics-cookie.
2461 Each filter is called with three arguments: the transcoded data,
2462 as a string, the back-end, as a symbol, and the communication
2463 channel, as a plist. It must return a string or nil.")
2465 (defvar org-export-filter-strike-through-functions nil
2466 "List of functions applied to transcoded strike-through text.
2467 Each filter is called with three arguments: the transcoded data,
2468 as a string, the back-end, as a symbol, and the communication
2469 channel, as a plist. It must return a string or nil.")
2471 (defvar org-export-filter-subscript-functions nil
2472 "List of functions applied to a transcoded subscript.
2473 Each filter is called with three arguments: the transcoded data,
2474 as a string, the back-end, as a symbol, and the communication
2475 channel, as a plist. It must return a string or nil.")
2477 (defvar org-export-filter-superscript-functions nil
2478 "List of functions applied to a transcoded superscript.
2479 Each filter is called with three arguments: the transcoded data,
2480 as a string, the back-end, as a symbol, and the communication
2481 channel, as a plist. It must return a string or nil.")
2483 (defvar org-export-filter-target-functions nil
2484 "List of functions applied to a transcoded target.
2485 Each filter is called with three arguments: the transcoded data,
2486 as a string, the back-end, as a symbol, and the communication
2487 channel, as a plist. It must return a string or nil.")
2489 (defvar org-export-filter-timestamp-functions nil
2490 "List of functions applied to a transcoded timestamp.
2491 Each filter is called with three arguments: the transcoded data,
2492 as a string, the back-end, as a symbol, and the communication
2493 channel, as a plist. It must return a string or nil.")
2495 (defvar org-export-filter-underline-functions nil
2496 "List of functions applied to transcoded underline text.
2497 Each filter is called with three arguments: the transcoded data,
2498 as a string, the back-end, as a symbol, and the communication
2499 channel, as a plist. It must return a string or nil.")
2501 (defvar org-export-filter-verbatim-functions nil
2502 "List of functions applied to transcoded verbatim text.
2503 Each filter is called with three arguments: the transcoded data,
2504 as a string, the back-end, as a symbol, and the communication
2505 channel, as a plist. It must return a string or nil.")
2508 ;;;; Filters Tools
2510 ;; Internal function `org-export-install-filters' installs filters
2511 ;; hard-coded in back-ends (developer filters) and filters from global
2512 ;; variables (user filters) in the communication channel.
2514 ;; Internal function `org-export-filter-apply-functions' takes care
2515 ;; about applying each filter in order to a given data. It ignores
2516 ;; filters returning a nil value but stops whenever a filter returns
2517 ;; an empty string.
2519 (defun org-export-filter-apply-functions (filters value info)
2520 "Call every function in FILTERS.
2522 Functions are called with three arguments: a value, the export
2523 back-end name and the communication channel. First function in
2524 FILTERS is called with VALUE as its first argument. Second
2525 function in FILTERS is called with the previous result as its
2526 value, etc.
2528 Functions returning nil are skipped. Any function returning the
2529 empty string ends the process, which returns the empty string.
2531 Call is done in a LIFO fashion, to be sure that developer
2532 specified filters, if any, are called first."
2533 (catch :exit
2534 (let* ((backend (plist-get info :back-end))
2535 (backend-name (and backend (org-export-backend-name backend))))
2536 (dolist (filter filters value)
2537 (let ((result (funcall filter value backend-name info)))
2538 (cond ((not result))
2539 ((equal result "") (throw :exit ""))
2540 (t (setq value result))))))))
2542 (defun org-export-install-filters (info)
2543 "Install filters properties in communication channel.
2544 INFO is a plist containing the current communication channel.
2545 Return the updated communication channel."
2546 (let (plist)
2547 ;; Install user-defined filters with `org-export-filters-alist'
2548 ;; and filters already in INFO (through ext-plist mechanism).
2549 (dolist (p org-export-filters-alist)
2550 (let* ((prop (car p))
2551 (info-value (plist-get info prop))
2552 (default-value (symbol-value (cdr p))))
2553 (setq plist
2554 (plist-put plist prop
2555 ;; Filters in INFO will be called
2556 ;; before those user provided.
2557 (append (if (listp info-value) info-value
2558 (list info-value))
2559 default-value)))))
2560 ;; Prepend back-end specific filters to that list.
2561 (dolist (p (org-export-get-all-filters (plist-get info :back-end)))
2562 ;; Single values get consed, lists are appended.
2563 (let ((key (car p)) (value (cdr p)))
2564 (when value
2565 (setq plist
2566 (plist-put
2567 plist key
2568 (if (atom value) (cons value (plist-get plist key))
2569 (append value (plist-get plist key))))))))
2570 ;; Return new communication channel.
2571 (org-combine-plists info plist)))
2575 ;;; Core functions
2577 ;; This is the room for the main function, `org-export-as', along with
2578 ;; its derivative, `org-export-string-as'.
2579 ;; `org-export--copy-to-kill-ring-p' determines if output of these
2580 ;; function should be added to kill ring.
2582 ;; Note that `org-export-as' doesn't really parse the current buffer,
2583 ;; but a copy of it (with the same buffer-local variables and
2584 ;; visibility), where macros and include keywords are expanded and
2585 ;; Babel blocks are executed, if appropriate.
2586 ;; `org-export-with-buffer-copy' macro prepares that copy.
2588 ;; File inclusion is taken care of by
2589 ;; `org-export-expand-include-keyword' and
2590 ;; `org-export--prepare-file-contents'. Structure wise, including
2591 ;; a whole Org file in a buffer often makes little sense. For
2592 ;; example, if the file contains a headline and the include keyword
2593 ;; was within an item, the item should contain the headline. That's
2594 ;; why file inclusion should be done before any structure can be
2595 ;; associated to the file, that is before parsing.
2597 ;; `org-export-insert-default-template' is a command to insert
2598 ;; a default template (or a back-end specific template) at point or in
2599 ;; current subtree.
2601 (defun org-export-copy-buffer ()
2602 "Return a copy of the current buffer.
2603 The copy preserves Org buffer-local variables, visibility and
2604 narrowing."
2605 (let ((copy-buffer-fun (org-export--generate-copy-script (current-buffer)))
2606 (new-buf (generate-new-buffer (buffer-name))))
2607 (with-current-buffer new-buf
2608 (funcall copy-buffer-fun)
2609 (set-buffer-modified-p nil))
2610 new-buf))
2612 (defmacro org-export-with-buffer-copy (&rest body)
2613 "Apply BODY in a copy of the current buffer.
2614 The copy preserves local variables, visibility and contents of
2615 the original buffer. Point is at the beginning of the buffer
2616 when BODY is applied."
2617 (declare (debug t))
2618 (org-with-gensyms (buf-copy)
2619 `(let ((,buf-copy (org-export-copy-buffer)))
2620 (unwind-protect
2621 (with-current-buffer ,buf-copy
2622 (goto-char (point-min))
2623 (progn ,@body))
2624 (and (buffer-live-p ,buf-copy)
2625 ;; Kill copy without confirmation.
2626 (progn (with-current-buffer ,buf-copy
2627 (restore-buffer-modified-p nil))
2628 (kill-buffer ,buf-copy)))))))
2630 (defun org-export--generate-copy-script (buffer)
2631 "Generate a function duplicating BUFFER.
2633 The copy will preserve local variables, visibility, contents and
2634 narrowing of the original buffer. If a region was active in
2635 BUFFER, contents will be narrowed to that region instead.
2637 The resulting function can be evaluated at a later time, from
2638 another buffer, effectively cloning the original buffer there.
2640 The function assumes BUFFER's major mode is `org-mode'."
2641 (with-current-buffer buffer
2642 `(lambda ()
2643 (let ((inhibit-modification-hooks t))
2644 ;; Set major mode. Ignore `org-mode-hook' as it has been run
2645 ;; already in BUFFER.
2646 (let ((org-mode-hook nil) (org-inhibit-startup t)) (org-mode))
2647 ;; Copy specific buffer local variables and variables set
2648 ;; through BIND keywords.
2649 ,@(let ((bound-variables (org-export--list-bound-variables))
2650 vars)
2651 (dolist (entry (buffer-local-variables (buffer-base-buffer)) vars)
2652 (when (consp entry)
2653 (let ((var (car entry))
2654 (val (cdr entry)))
2655 (and (not (memq var org-export-ignored-local-variables))
2656 (or (memq var
2657 '(default-directory
2658 buffer-file-name
2659 buffer-file-coding-system))
2660 (assq var bound-variables)
2661 (string-match "^\\(org-\\|orgtbl-\\)"
2662 (symbol-name var)))
2663 ;; Skip unreadable values, as they cannot be
2664 ;; sent to external process.
2665 (or (not val) (ignore-errors (read (format "%S" val))))
2666 (push `(set (make-local-variable (quote ,var))
2667 (quote ,val))
2668 vars))))))
2669 ;; Whole buffer contents.
2670 (insert
2671 ,(org-with-wide-buffer
2672 (buffer-substring-no-properties
2673 (point-min) (point-max))))
2674 ;; Narrowing.
2675 ,(if (org-region-active-p)
2676 `(narrow-to-region ,(region-beginning) ,(region-end))
2677 `(narrow-to-region ,(point-min) ,(point-max)))
2678 ;; Current position of point.
2679 (goto-char ,(point))
2680 ;; Overlays with invisible property.
2681 ,@(let (ov-set)
2682 (dolist (ov (overlays-in (point-min) (point-max)) ov-set)
2683 (let ((invis-prop (overlay-get ov 'invisible)))
2684 (when invis-prop
2685 (push `(overlay-put
2686 (make-overlay ,(overlay-start ov)
2687 ,(overlay-end ov))
2688 'invisible (quote ,invis-prop))
2689 ov-set)))))))))
2691 (defun org-export--delete-comment-trees ()
2692 "Delete commented trees and commented inlinetasks in the buffer.
2693 Narrowing, if any, is ignored."
2694 (org-with-wide-buffer
2695 (goto-char (point-min))
2696 (let* ((case-fold-search t)
2697 (regexp (concat org-outline-regexp-bol ".*" org-comment-string)))
2698 (while (re-search-forward regexp nil t)
2699 (let ((element (org-element-at-point)))
2700 (when (org-element-property :commentedp element)
2701 (delete-region (org-element-property :begin element)
2702 (org-element-property :end element))))))))
2704 (defun org-export--prune-tree (data info)
2705 "Prune non exportable elements from DATA.
2706 DATA is the parse tree to traverse. INFO is the plist holding
2707 export info. Also set `:ignore-list' in INFO to a list of
2708 objects which should be ignored during export, but not removed
2709 from tree."
2710 (letrec ((ignore nil)
2711 ;; First find trees containing a select tag, if any.
2712 (selected (org-export--selected-trees data info))
2713 (walk-data
2714 (lambda (data)
2715 ;; Prune non-exportable elements and objects from tree.
2716 ;; As a special case, special rows and cells from tables
2717 ;; are stored in IGNORE, as they still need to be
2718 ;; accessed during export.
2719 (when data
2720 (let ((type (org-element-type data)))
2721 (if (org-export--skip-p data info selected)
2722 (if (memq type '(table-cell table-row)) (push data ignore)
2723 (org-element-extract-element data))
2724 (if (and (eq type 'headline)
2725 (eq (plist-get info :with-archived-trees)
2726 'headline)
2727 (org-element-property :archivedp data))
2728 ;; If headline is archived but tree below has
2729 ;; to be skipped, remove contents.
2730 (org-element-set-contents data)
2731 ;; Move into recursive objects/elements.
2732 (mapc walk-data (org-element-contents data)))
2733 ;; Move into secondary string, if any.
2734 (dolist (p (cdr (assq type
2735 org-element-secondary-value-alist)))
2736 (mapc walk-data (org-element-property p data))))))))
2737 (definitions
2738 ;; Collect definitions before possibly pruning them so as
2739 ;; to avoid parsing them again if they are required.
2740 (org-element-map data '(footnote-definition footnote-reference)
2741 (lambda (f)
2742 (cond
2743 ((eq 'footnote-definition (org-element-type f)) f)
2744 ((and (eq 'inline (org-element-property :type f))
2745 (org-element-property :label f))
2747 (t nil))))))
2748 ;; If a select tag is active, also ignore the section before the
2749 ;; first headline, if any.
2750 (when selected
2751 (let ((first-element (car (org-element-contents data))))
2752 (when (eq (org-element-type first-element) 'section)
2753 (org-element-extract-element first-element))))
2754 ;; Prune tree and communication channel.
2755 (funcall walk-data data)
2756 (dolist (entry (append
2757 ;; Priority is given to back-end specific options.
2758 (org-export-get-all-options (plist-get info :back-end))
2759 org-export-options-alist))
2760 (when (eq (nth 4 entry) 'parse)
2761 (funcall walk-data (plist-get info (car entry)))))
2762 (let ((missing (org-export--missing-definitions data definitions)))
2763 (funcall walk-data missing)
2764 (org-export--install-footnote-definitions missing data))
2765 ;; Eventually set `:ignore-list'.
2766 (plist-put info :ignore-list ignore)))
2768 (defun org-export--missing-definitions (tree definitions)
2769 "List footnote definitions missing from TREE.
2770 Missing definitions are searched within DEFINITIONS, which is
2771 a list of footnote definitions or in the widened buffer."
2772 (let* ((list-labels
2773 (lambda (data)
2774 ;; List all footnote labels encountered in DATA. Inline
2775 ;; footnote references are ignored.
2776 (org-element-map data 'footnote-reference
2777 (lambda (reference)
2778 (and (eq (org-element-property :type reference) 'standard)
2779 (org-element-property :label reference))))))
2780 defined undefined missing-definitions)
2781 ;; Partition DIRECT-REFERENCES between DEFINED and UNDEFINED
2782 ;; references.
2783 (let ((known-definitions
2784 (org-element-map tree '(footnote-reference footnote-definition)
2785 (lambda (f)
2786 (and (or (eq (org-element-type f) 'footnote-definition)
2787 (eq (org-element-property :type f) 'inline))
2788 (org-element-property :label f)))))
2789 seen)
2790 (dolist (l (funcall list-labels tree))
2791 (cond ((member l seen))
2792 ((member l known-definitions) (push l defined))
2793 (t (push l undefined)))))
2794 ;; Complete MISSING-DEFINITIONS by finding the definition of every
2795 ;; undefined label, first by looking into DEFINITIONS, then by
2796 ;; searching the widened buffer. This is a recursive process
2797 ;; since definitions found can themselves contain an undefined
2798 ;; reference.
2799 (while undefined
2800 (let* ((label (pop undefined))
2801 (definition
2802 (cond
2803 ((cl-some
2804 (lambda (d) (and (equal (org-element-property :label d) label)
2806 definitions))
2807 ((pcase (org-footnote-get-definition label)
2808 (`(,_ ,beg . ,_)
2809 (org-with-wide-buffer
2810 (goto-char beg)
2811 (let ((datum (org-element-context)))
2812 (if (eq (org-element-type datum) 'footnote-reference)
2813 datum
2814 ;; Parse definition with contents.
2815 (save-restriction
2816 (narrow-to-region
2817 (org-element-property :begin datum)
2818 (org-element-property :end datum))
2819 (org-element-map (org-element-parse-buffer)
2820 'footnote-definition #'identity nil t))))))
2821 (_ nil)))
2822 (t (user-error "Definition not found for footnote %s" label)))))
2823 (push label defined)
2824 (push definition missing-definitions)
2825 ;; Look for footnote references within DEFINITION, since
2826 ;; we may need to also find their definition.
2827 (dolist (l (funcall list-labels definition))
2828 (unless (or (member l defined) ;Known label
2829 (member l undefined)) ;Processed later
2830 (push l undefined)))))
2831 ;; MISSING-DEFINITIONS may contain footnote references with inline
2832 ;; definitions. Make sure those are changed into real footnote
2833 ;; definitions.
2834 (mapcar (lambda (d)
2835 (if (eq (org-element-type d) 'footnote-definition) d
2836 (let ((label (org-element-property :label d)))
2837 (apply #'org-element-create
2838 'footnote-definition `(:label ,label :post-blank 1)
2839 (org-element-contents d)))))
2840 missing-definitions)))
2842 (defun org-export--install-footnote-definitions (definitions tree)
2843 "Install footnote definitions in tree.
2845 DEFINITIONS is the list of footnote definitions to install. TREE
2846 is the parse tree.
2848 If there is a footnote section in TREE, definitions found are
2849 appended to it. If `org-footnote-section' is non-nil, a new
2850 footnote section containing all definitions is inserted in TREE.
2851 Otherwise, definitions are appended at the end of the section
2852 containing their first reference."
2853 (cond
2854 ((null definitions))
2855 ;; If there is a footnote section, insert definitions there.
2856 ((let ((footnote-section
2857 (org-element-map tree 'headline
2858 (lambda (h) (and (org-element-property :footnote-section-p h) h))
2859 nil t)))
2860 (and footnote-section
2861 (apply #'org-element-adopt-elements
2862 footnote-section
2863 (nreverse definitions)))))
2864 ;; If there should be a footnote section, create one containing all
2865 ;; the definitions at the end of the tree.
2866 (org-footnote-section
2867 (org-element-adopt-elements
2868 tree
2869 (org-element-create 'headline
2870 (list :footnote-section-p t
2871 :level 1
2872 :title org-footnote-section
2873 :raw-value org-footnote-section)
2874 (apply #'org-element-create
2875 'section
2877 (nreverse definitions)))))
2878 ;; Otherwise add each definition at the end of the section where it
2879 ;; is first referenced.
2881 (letrec ((seen nil)
2882 (insert-definitions
2883 (lambda (data)
2884 ;; Insert footnote definitions in the same section as
2885 ;; their first reference in DATA.
2886 (org-element-map data 'footnote-reference
2887 (lambda (reference)
2888 (when (eq (org-element-property :type reference) 'standard)
2889 (let ((label (org-element-property :label reference)))
2890 (unless (member label seen)
2891 (push label seen)
2892 (let ((definition
2893 (cl-some
2894 (lambda (d)
2895 (and (equal (org-element-property :label d)
2896 label)
2898 definitions)))
2899 (org-element-adopt-elements
2900 (org-element-lineage reference '(section))
2901 definition)
2902 ;; Also insert definitions for nested
2903 ;; references, if any.
2904 (funcall insert-definitions definition))))))))))
2905 (funcall insert-definitions tree)))))
2907 (defun org-export--remove-uninterpreted-data (data info)
2908 "Change uninterpreted elements back into Org syntax.
2909 DATA is a parse tree or a secondary string. INFO is a plist
2910 containing export options. It is modified by side effect and
2911 returned by the function."
2912 (org-element-map data
2913 '(entity bold italic latex-environment latex-fragment strike-through
2914 subscript superscript underline)
2915 (lambda (datum)
2916 (let ((new
2917 (cl-case (org-element-type datum)
2918 ;; ... entities...
2919 (entity
2920 (and (not (plist-get info :with-entities))
2921 (list (concat
2922 (org-export-expand datum nil)
2923 (make-string
2924 (or (org-element-property :post-blank datum) 0)
2925 ?\s)))))
2926 ;; ... emphasis...
2927 ((bold italic strike-through underline)
2928 (and (not (plist-get info :with-emphasize))
2929 (let ((marker (cl-case (org-element-type datum)
2930 (bold "*")
2931 (italic "/")
2932 (strike-through "+")
2933 (underline "_"))))
2934 (append
2935 (list marker)
2936 (org-element-contents datum)
2937 (list (concat
2938 marker
2939 (make-string
2940 (or (org-element-property :post-blank datum)
2942 ?\s)))))))
2943 ;; ... LaTeX environments and fragments...
2944 ((latex-environment latex-fragment)
2945 (and (eq (plist-get info :with-latex) 'verbatim)
2946 (list (org-export-expand datum nil))))
2947 ;; ... sub/superscripts...
2948 ((subscript superscript)
2949 (let ((sub/super-p (plist-get info :with-sub-superscript))
2950 (bracketp (org-element-property :use-brackets-p datum)))
2951 (and (or (not sub/super-p)
2952 (and (eq sub/super-p '{}) (not bracketp)))
2953 (append
2954 (list (concat
2955 (if (eq (org-element-type datum) 'subscript)
2957 "^")
2958 (and bracketp "{")))
2959 (org-element-contents datum)
2960 (list (concat
2961 (and bracketp "}")
2962 (and (org-element-property :post-blank datum)
2963 (make-string
2964 (org-element-property :post-blank datum)
2965 ?\s)))))))))))
2966 (when new
2967 ;; Splice NEW at DATUM location in parse tree.
2968 (dolist (e new (org-element-extract-element datum))
2969 (unless (equal e "") (org-element-insert-before e datum))))))
2970 info nil nil t)
2971 ;; Return modified parse tree.
2972 data)
2974 ;;;###autoload
2975 (defun org-export-as
2976 (backend &optional subtreep visible-only body-only ext-plist)
2977 "Transcode current Org buffer into BACKEND code.
2979 BACKEND is either an export back-end, as returned by, e.g.,
2980 `org-export-create-backend', or a symbol referring to
2981 a registered back-end.
2983 If narrowing is active in the current buffer, only transcode its
2984 narrowed part.
2986 If a region is active, transcode that region.
2988 When optional argument SUBTREEP is non-nil, transcode the
2989 sub-tree at point, extracting information from the headline
2990 properties first.
2992 When optional argument VISIBLE-ONLY is non-nil, don't export
2993 contents of hidden elements.
2995 When optional argument BODY-ONLY is non-nil, only return body
2996 code, without surrounding template.
2998 Optional argument EXT-PLIST, when provided, is a property list
2999 with external parameters overriding Org default settings, but
3000 still inferior to file-local settings.
3002 Return code as a string."
3003 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
3004 (org-export-barf-if-invalid-backend backend)
3005 (save-excursion
3006 (save-restriction
3007 ;; Narrow buffer to an appropriate region or subtree for
3008 ;; parsing. If parsing subtree, be sure to remove main
3009 ;; headline, planning data and property drawer.
3010 (cond ((org-region-active-p)
3011 (narrow-to-region (region-beginning) (region-end)))
3012 (subtreep
3013 (org-narrow-to-subtree)
3014 (goto-char (point-min))
3015 (org-end-of-meta-data)
3016 (narrow-to-region (point) (point-max))))
3017 ;; Initialize communication channel with original buffer
3018 ;; attributes, unavailable in its copy.
3019 (let* ((org-export-current-backend (org-export-backend-name backend))
3020 (info (org-combine-plists
3021 (org-export--get-export-attributes
3022 backend subtreep visible-only body-only)
3023 (org-export--get-buffer-attributes)))
3024 (parsed-keywords
3025 (delq nil
3026 (mapcar (lambda (o) (and (eq (nth 4 o) 'parse) (nth 1 o)))
3027 (append (org-export-get-all-options backend)
3028 org-export-options-alist))))
3029 tree)
3030 ;; Update communication channel and get parse tree. Buffer
3031 ;; isn't parsed directly. Instead, all buffer modifications
3032 ;; and consequent parsing are undertaken in a temporary copy.
3033 (org-export-with-buffer-copy
3034 ;; Run first hook with current back-end's name as argument.
3035 (run-hook-with-args 'org-export-before-processing-hook
3036 (org-export-backend-name backend))
3037 ;; Include files, delete comments and expand macros. Refresh
3038 ;; buffer properties and radio targets after these
3039 ;; potentially invasive changes.
3040 (org-export-expand-include-keyword)
3041 (org-export--delete-comment-trees)
3042 (org-macro-initialize-templates)
3043 (org-macro-replace-all (append org-macro-templates
3044 org-export-global-macros)
3045 parsed-keywords)
3046 (org-set-regexps-and-options)
3047 (org-update-radio-target-regexp)
3048 ;; Possibly execute Babel code. Re-run a macro expansion
3049 ;; specifically for {{{results}}} since inline source blocks
3050 ;; may have generated some more. Refresh buffer properties
3051 ;; and radio targets another time.
3052 (when org-export-use-babel
3053 (org-babel-exp-process-buffer)
3054 (org-macro-replace-all '(("results" . "$1")) parsed-keywords)
3055 (org-set-regexps-and-options)
3056 (org-update-radio-target-regexp))
3057 ;; Run last hook with current back-end's name as argument.
3058 ;; Update buffer properties and radio targets one last time
3059 ;; before parsing.
3060 (goto-char (point-min))
3061 (save-excursion
3062 (run-hook-with-args 'org-export-before-parsing-hook
3063 (org-export-backend-name backend)))
3064 (org-set-regexps-and-options)
3065 (org-update-radio-target-regexp)
3066 ;; Update communication channel with environment.
3067 (setq info
3068 (org-combine-plists
3069 info (org-export-get-environment backend subtreep ext-plist)))
3070 ;; De-activate uninterpreted data from parsed keywords.
3071 (dolist (entry (append (org-export-get-all-options backend)
3072 org-export-options-alist))
3073 (pcase entry
3074 (`(,p ,_ ,_ ,_ parse)
3075 (let ((value (plist-get info p)))
3076 (plist-put info
3078 (org-export--remove-uninterpreted-data value info))))
3079 (_ nil)))
3080 ;; Install user's and developer's filters.
3081 (setq info (org-export-install-filters info))
3082 ;; Call options filters and update export options. We do not
3083 ;; use `org-export-filter-apply-functions' here since the
3084 ;; arity of such filters is different.
3085 (let ((backend-name (org-export-backend-name backend)))
3086 (dolist (filter (plist-get info :filter-options))
3087 (let ((result (funcall filter info backend-name)))
3088 (when result (setq info result)))))
3089 ;; Parse buffer.
3090 (setq tree (org-element-parse-buffer nil visible-only))
3091 ;; Prune tree from non-exported elements and transform
3092 ;; uninterpreted elements or objects in both parse tree and
3093 ;; communication channel.
3094 (org-export--prune-tree tree info)
3095 (org-export--remove-uninterpreted-data tree info)
3096 ;; Call parse tree filters.
3097 (setq tree
3098 (org-export-filter-apply-functions
3099 (plist-get info :filter-parse-tree) tree info))
3100 ;; Now tree is complete, compute its properties and add them
3101 ;; to communication channel.
3102 (setq info (org-export--collect-tree-properties tree info))
3103 ;; Eventually transcode TREE. Wrap the resulting string into
3104 ;; a template.
3105 (let* ((body (org-element-normalize-string
3106 (or (org-export-data tree info) "")))
3107 (inner-template (cdr (assq 'inner-template
3108 (plist-get info :translate-alist))))
3109 (full-body (org-export-filter-apply-functions
3110 (plist-get info :filter-body)
3111 (if (not (functionp inner-template)) body
3112 (funcall inner-template body info))
3113 info))
3114 (template (cdr (assq 'template
3115 (plist-get info :translate-alist)))))
3116 ;; Remove all text properties since they cannot be
3117 ;; retrieved from an external process. Finally call
3118 ;; final-output filter and return result.
3119 (org-no-properties
3120 (org-export-filter-apply-functions
3121 (plist-get info :filter-final-output)
3122 (if (or (not (functionp template)) body-only) full-body
3123 (funcall template full-body info))
3124 info))))))))
3126 ;;;###autoload
3127 (defun org-export-string-as (string backend &optional body-only ext-plist)
3128 "Transcode STRING into BACKEND code.
3130 BACKEND is either an export back-end, as returned by, e.g.,
3131 `org-export-create-backend', or a symbol referring to
3132 a registered back-end.
3134 When optional argument BODY-ONLY is non-nil, only return body
3135 code, without preamble nor postamble.
3137 Optional argument EXT-PLIST, when provided, is a property list
3138 with external parameters overriding Org default settings, but
3139 still inferior to file-local settings.
3141 Return code as a string."
3142 (with-temp-buffer
3143 (insert string)
3144 (let ((org-inhibit-startup t)) (org-mode))
3145 (org-export-as backend nil nil body-only ext-plist)))
3147 ;;;###autoload
3148 (defun org-export-replace-region-by (backend)
3149 "Replace the active region by its export to BACKEND.
3150 BACKEND is either an export back-end, as returned by, e.g.,
3151 `org-export-create-backend', or a symbol referring to
3152 a registered back-end."
3153 (unless (org-region-active-p) (user-error "No active region to replace"))
3154 (insert
3155 (org-export-string-as
3156 (delete-and-extract-region (region-beginning) (region-end)) backend t)))
3158 ;;;###autoload
3159 (defun org-export-insert-default-template (&optional backend subtreep)
3160 "Insert all export keywords with default values at beginning of line.
3162 BACKEND is a symbol referring to the name of a registered export
3163 back-end, for which specific export options should be added to
3164 the template, or `default' for default template. When it is nil,
3165 the user will be prompted for a category.
3167 If SUBTREEP is non-nil, export configuration will be set up
3168 locally for the subtree through node properties."
3169 (interactive)
3170 (unless (derived-mode-p 'org-mode) (user-error "Not in an Org mode buffer"))
3171 (when (and subtreep (org-before-first-heading-p))
3172 (user-error "No subtree to set export options for"))
3173 (let ((node (and subtreep (save-excursion (org-back-to-heading t) (point))))
3174 (backend
3175 (or backend
3176 (intern
3177 (org-completing-read
3178 "Options category: "
3179 (cons "default"
3180 (mapcar (lambda (b)
3181 (symbol-name (org-export-backend-name b)))
3182 org-export-registered-backends))
3183 nil t))))
3184 options keywords)
3185 ;; Populate OPTIONS and KEYWORDS.
3186 (dolist (entry (cond ((eq backend 'default) org-export-options-alist)
3187 ((org-export-backend-p backend)
3188 (org-export-backend-options backend))
3189 (t (org-export-backend-options
3190 (org-export-get-backend backend)))))
3191 (let ((keyword (nth 1 entry))
3192 (option (nth 2 entry)))
3193 (cond
3194 (keyword (unless (assoc keyword keywords)
3195 (let ((value
3196 (if (eq (nth 4 entry) 'split)
3197 (mapconcat #'identity (eval (nth 3 entry)) " ")
3198 (eval (nth 3 entry)))))
3199 (push (cons keyword value) keywords))))
3200 (option (unless (assoc option options)
3201 (push (cons option (eval (nth 3 entry))) options))))))
3202 ;; Move to an appropriate location in order to insert options.
3203 (unless subtreep (beginning-of-line))
3204 ;; First (multiple) OPTIONS lines. Never go past fill-column.
3205 (when options
3206 (let ((items
3207 (mapcar
3208 #'(lambda (opt) (format "%s:%S" (car opt) (cdr opt)))
3209 (sort options (lambda (k1 k2) (string< (car k1) (car k2)))))))
3210 (if subtreep
3211 (org-entry-put
3212 node "EXPORT_OPTIONS" (mapconcat 'identity items " "))
3213 (while items
3214 (insert "#+OPTIONS:")
3215 (let ((width 10))
3216 (while (and items
3217 (< (+ width (length (car items)) 1) fill-column))
3218 (let ((item (pop items)))
3219 (insert " " item)
3220 (cl-incf width (1+ (length item))))))
3221 (insert "\n")))))
3222 ;; Then the rest of keywords, in the order specified in either
3223 ;; `org-export-options-alist' or respective export back-ends.
3224 (dolist (key (nreverse keywords))
3225 (let ((val (cond ((equal (car key) "DATE")
3226 (or (cdr key)
3227 (with-temp-buffer
3228 (org-insert-time-stamp (current-time)))))
3229 ((equal (car key) "TITLE")
3230 (or (let ((visited-file
3231 (buffer-file-name (buffer-base-buffer))))
3232 (and visited-file
3233 (file-name-sans-extension
3234 (file-name-nondirectory visited-file))))
3235 (buffer-name (buffer-base-buffer))))
3236 (t (cdr key)))))
3237 (if subtreep (org-entry-put node (concat "EXPORT_" (car key)) val)
3238 (insert
3239 (format "#+%s:%s\n"
3240 (car key)
3241 (if (org-string-nw-p val) (format " %s" val) ""))))))))
3243 (defun org-export-expand-include-keyword (&optional included dir footnotes)
3244 "Expand every include keyword in buffer.
3245 Optional argument INCLUDED is a list of included file names along
3246 with their line restriction, when appropriate. It is used to
3247 avoid infinite recursion. Optional argument DIR is the current
3248 working directory. It is used to properly resolve relative
3249 paths. Optional argument FOOTNOTES is a hash-table used for
3250 storing and resolving footnotes. It is created automatically."
3251 (let ((case-fold-search t)
3252 (file-prefix (make-hash-table :test #'equal))
3253 (current-prefix 0)
3254 (footnotes (or footnotes (make-hash-table :test #'equal)))
3255 (include-re "^[ \t]*#\\+INCLUDE:"))
3256 ;; If :minlevel is not set the text-property
3257 ;; `:org-include-induced-level' will be used to determine the
3258 ;; relative level when expanding INCLUDE.
3259 ;; Only affects included Org documents.
3260 (goto-char (point-min))
3261 (while (re-search-forward include-re nil t)
3262 (put-text-property (line-beginning-position) (line-end-position)
3263 :org-include-induced-level
3264 (1+ (org-reduced-level (or (org-current-level) 0)))))
3265 ;; Expand INCLUDE keywords.
3266 (goto-char (point-min))
3267 (while (re-search-forward include-re nil t)
3268 (unless (org-in-commented-heading-p)
3269 (let ((element (save-match-data (org-element-at-point))))
3270 (when (eq (org-element-type element) 'keyword)
3271 (beginning-of-line)
3272 ;; Extract arguments from keyword's value.
3273 (let* ((value (org-element-property :value element))
3274 (ind (org-get-indentation))
3275 location
3276 (file
3277 (and (string-match
3278 "^\\(\".+?\"\\|\\S-+\\)\\(?:\\s-+\\|$\\)" value)
3279 (prog1
3280 (save-match-data
3281 (let ((matched (match-string 1 value)))
3282 (when (string-match "\\(::\\(.*?\\)\\)\"?\\'"
3283 matched)
3284 (setq location (match-string 2 matched))
3285 (setq matched
3286 (replace-match "" nil nil matched 1)))
3287 (expand-file-name
3288 (org-unbracket-string "\"" "\"" matched)
3289 dir)))
3290 (setq value (replace-match "" nil nil value)))))
3291 (only-contents
3292 (and (string-match ":only-contents *\\([^: \r\t\n]\\S-*\\)?"
3293 value)
3294 (prog1 (org-not-nil (match-string 1 value))
3295 (setq value (replace-match "" nil nil value)))))
3296 (lines
3297 (and (string-match
3298 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\""
3299 value)
3300 (prog1 (match-string 1 value)
3301 (setq value (replace-match "" nil nil value)))))
3302 (env (cond
3303 ((string-match "\\<example\\>" value) 'literal)
3304 ((string-match "\\<export\\(?: +\\(.*\\)\\)?" value)
3305 'literal)
3306 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
3307 'literal)))
3308 ;; Minimal level of included file defaults to the
3309 ;; child level of the current headline, if any, or
3310 ;; one. It only applies is the file is meant to be
3311 ;; included as an Org one.
3312 (minlevel
3313 (and (not env)
3314 (if (string-match ":minlevel +\\([0-9]+\\)" value)
3315 (prog1 (string-to-number (match-string 1 value))
3316 (setq value (replace-match "" nil nil value)))
3317 (get-text-property (point)
3318 :org-include-induced-level))))
3319 (args (and (eq env 'literal) (match-string 1 value)))
3320 (block (and (string-match "\\<\\(\\S-+\\)\\>" value)
3321 (match-string 1 value))))
3322 ;; Remove keyword.
3323 (delete-region (point) (line-beginning-position 2))
3324 (cond
3325 ((not file) nil)
3326 ((not (file-readable-p file))
3327 (error "Cannot include file %s" file))
3328 ;; Check if files has already been parsed. Look after
3329 ;; inclusion lines too, as different parts of the same
3330 ;; file can be included too.
3331 ((member (list file lines) included)
3332 (error "Recursive file inclusion: %s" file))
3334 (cond
3335 ((eq env 'literal)
3336 (insert
3337 (let ((ind-str (make-string ind ?\s))
3338 (arg-str (if (stringp args) (format " %s" args) ""))
3339 (contents
3340 (org-escape-code-in-string
3341 (org-export--prepare-file-contents file lines))))
3342 (format "%s#+BEGIN_%s%s\n%s%s#+END_%s\n"
3343 ind-str block arg-str contents ind-str block))))
3344 ((stringp block)
3345 (insert
3346 (let ((ind-str (make-string ind ?\s))
3347 (contents
3348 (org-export--prepare-file-contents file lines)))
3349 (format "%s#+BEGIN_%s\n%s%s#+END_%s\n"
3350 ind-str block contents ind-str block))))
3352 (insert
3353 (with-temp-buffer
3354 (let ((org-inhibit-startup t)
3355 (lines
3356 (if location
3357 (org-export--inclusion-absolute-lines
3358 file location only-contents lines)
3359 lines)))
3360 (org-mode)
3361 (insert
3362 (org-export--prepare-file-contents
3363 file lines ind minlevel
3365 (gethash file file-prefix)
3366 (puthash file (cl-incf current-prefix) file-prefix))
3367 footnotes)))
3368 (org-export-expand-include-keyword
3369 (cons (list file lines) included)
3370 (file-name-directory file)
3371 footnotes)
3372 (buffer-string)))))
3373 ;; Expand footnotes after all files have been
3374 ;; included. Footnotes are stored at end of buffer.
3375 (unless included
3376 (org-with-wide-buffer
3377 (goto-char (point-max))
3378 (maphash (lambda (k v)
3379 (insert (format "\n[fn:%s] %s\n" k v)))
3380 footnotes))))))))))))
3382 (defun org-export--inclusion-absolute-lines (file location only-contents lines)
3383 "Resolve absolute lines for an included file with file-link.
3385 FILE is string file-name of the file to include. LOCATION is a
3386 string name within FILE to be included (located via
3387 `org-link-search'). If ONLY-CONTENTS is non-nil only the
3388 contents of the named element will be included, as determined
3389 Org-Element. If LINES is non-nil only those lines are included.
3391 Return a string of lines to be included in the format expected by
3392 `org-export--prepare-file-contents'."
3393 (with-temp-buffer
3394 (insert-file-contents file)
3395 (unless (eq major-mode 'org-mode)
3396 (let ((org-inhibit-startup t)) (org-mode)))
3397 (condition-case err
3398 ;; Enforce consistent search.
3399 (let ((org-link-search-must-match-exact-headline nil))
3400 (org-link-search location))
3401 (error
3402 (error "%s for %s::%s" (error-message-string err) file location)))
3403 (let* ((element (org-element-at-point))
3404 (contents-begin
3405 (and only-contents (org-element-property :contents-begin element))))
3406 (narrow-to-region
3407 (or contents-begin (org-element-property :begin element))
3408 (org-element-property (if contents-begin :contents-end :end) element))
3409 (when (and only-contents
3410 (memq (org-element-type element) '(headline inlinetask)))
3411 ;; Skip planning line and property-drawer.
3412 (goto-char (point-min))
3413 (when (looking-at-p org-planning-line-re) (forward-line))
3414 (when (looking-at org-property-drawer-re) (goto-char (match-end 0)))
3415 (unless (bolp) (forward-line))
3416 (narrow-to-region (point) (point-max))))
3417 (when lines
3418 (org-skip-whitespace)
3419 (beginning-of-line)
3420 (let* ((lines (split-string lines "-"))
3421 (lbeg (string-to-number (car lines)))
3422 (lend (string-to-number (cadr lines)))
3423 (beg (if (zerop lbeg) (point-min)
3424 (goto-char (point-min))
3425 (forward-line (1- lbeg))
3426 (point)))
3427 (end (if (zerop lend) (point-max)
3428 (goto-char beg)
3429 (forward-line (1- lend))
3430 (point))))
3431 (narrow-to-region beg end)))
3432 (let ((end (point-max)))
3433 (goto-char (point-min))
3434 (widen)
3435 (let ((start-line (line-number-at-pos)))
3436 (format "%d-%d"
3437 start-line
3438 (save-excursion
3439 (+ start-line
3440 (let ((counter 0))
3441 (while (< (point) end) (cl-incf counter) (forward-line))
3442 counter))))))))
3444 (defun org-export--prepare-file-contents
3445 (file &optional lines ind minlevel id footnotes)
3446 "Prepare contents of FILE for inclusion and return it as a string.
3448 When optional argument LINES is a string specifying a range of
3449 lines, include only those lines.
3451 Optional argument IND, when non-nil, is an integer specifying the
3452 global indentation of returned contents. Since its purpose is to
3453 allow an included file to stay in the same environment it was
3454 created (e.g., a list item), it doesn't apply past the first
3455 headline encountered.
3457 Optional argument MINLEVEL, when non-nil, is an integer
3458 specifying the level that any top-level headline in the included
3459 file should have.
3461 Optional argument ID is an integer that will be inserted before
3462 each footnote definition and reference if FILE is an Org file.
3463 This is useful to avoid conflicts when more than one Org file
3464 with footnotes is included in a document.
3466 Optional argument FOOTNOTES is a hash-table to store footnotes in
3467 the included document."
3468 (with-temp-buffer
3469 (insert-file-contents file)
3470 (when lines
3471 (let* ((lines (split-string lines "-"))
3472 (lbeg (string-to-number (car lines)))
3473 (lend (string-to-number (cadr lines)))
3474 (beg (if (zerop lbeg) (point-min)
3475 (goto-char (point-min))
3476 (forward-line (1- lbeg))
3477 (point)))
3478 (end (if (zerop lend) (point-max)
3479 (goto-char (point-min))
3480 (forward-line (1- lend))
3481 (point))))
3482 (narrow-to-region beg end)))
3483 ;; Remove blank lines at beginning and end of contents. The logic
3484 ;; behind that removal is that blank lines around include keyword
3485 ;; override blank lines in included file.
3486 (goto-char (point-min))
3487 (org-skip-whitespace)
3488 (beginning-of-line)
3489 (delete-region (point-min) (point))
3490 (goto-char (point-max))
3491 (skip-chars-backward " \r\t\n")
3492 (forward-line)
3493 (delete-region (point) (point-max))
3494 ;; If IND is set, preserve indentation of include keyword until
3495 ;; the first headline encountered.
3496 (when (and ind (> ind 0))
3497 (unless (eq major-mode 'org-mode)
3498 (let ((org-inhibit-startup t)) (org-mode)))
3499 (goto-char (point-min))
3500 (let ((ind-str (make-string ind ?\s)))
3501 (while (not (or (eobp) (looking-at org-outline-regexp-bol)))
3502 ;; Do not move footnote definitions out of column 0.
3503 (unless (and (looking-at org-footnote-definition-re)
3504 (eq (org-element-type (org-element-at-point))
3505 'footnote-definition))
3506 (insert ind-str))
3507 (forward-line))))
3508 ;; When MINLEVEL is specified, compute minimal level for headlines
3509 ;; in the file (CUR-MIN), and remove stars to each headline so
3510 ;; that headlines with minimal level have a level of MINLEVEL.
3511 (when minlevel
3512 (unless (eq major-mode 'org-mode)
3513 (let ((org-inhibit-startup t)) (org-mode)))
3514 (org-with-limited-levels
3515 (let ((levels (org-map-entries
3516 (lambda () (org-reduced-level (org-current-level))))))
3517 (when levels
3518 (let ((offset (- minlevel (apply #'min levels))))
3519 (unless (zerop offset)
3520 (when org-odd-levels-only (setq offset (* offset 2)))
3521 ;; Only change stars, don't bother moving whole
3522 ;; sections.
3523 (org-map-entries
3524 (lambda ()
3525 (if (< offset 0) (delete-char (abs offset))
3526 (insert (make-string offset ?*)))))))))))
3527 ;; Append ID to all footnote references and definitions, so they
3528 ;; become file specific and cannot collide with footnotes in other
3529 ;; included files. Further, collect relevant footnote definitions
3530 ;; outside of LINES, in order to reintroduce them later.
3531 (when id
3532 (let ((marker-min (point-min-marker))
3533 (marker-max (point-max-marker))
3534 (get-new-label
3535 (lambda (label)
3536 ;; Generate new label from LABEL by prefixing it with
3537 ;; "-ID-".
3538 (format "-%d-%s" id label)))
3539 (set-new-label
3540 (lambda (f old new)
3541 ;; Replace OLD label with NEW in footnote F.
3542 (save-excursion
3543 (goto-char (+ (org-element-property :begin f) 4))
3544 (looking-at (regexp-quote old))
3545 (replace-match new))))
3546 (seen-alist))
3547 (goto-char (point-min))
3548 (while (re-search-forward org-footnote-re nil t)
3549 (let ((footnote (save-excursion
3550 (backward-char)
3551 (org-element-context))))
3552 (when (memq (org-element-type footnote)
3553 '(footnote-definition footnote-reference))
3554 (let* ((label (org-element-property :label footnote)))
3555 ;; Update the footnote-reference at point and collect
3556 ;; the new label, which is only used for footnotes
3557 ;; outsides LINES.
3558 (when label
3559 (let ((seen (cdr (assoc label seen-alist))))
3560 (if seen (funcall set-new-label footnote label seen)
3561 (let ((new (funcall get-new-label label)))
3562 (push (cons label new) seen-alist)
3563 (org-with-wide-buffer
3564 (let* ((def (org-footnote-get-definition label))
3565 (beg (nth 1 def)))
3566 (when (and def
3567 (or (< beg marker-min)
3568 (>= beg marker-max)))
3569 ;; Store since footnote-definition is
3570 ;; outside of LINES.
3571 (puthash new
3572 (org-element-normalize-string (nth 3 def))
3573 footnotes))))
3574 (funcall set-new-label footnote label new)))))))))
3575 (set-marker marker-min nil)
3576 (set-marker marker-max nil)))
3577 (org-element-normalize-string (buffer-string))))
3579 (defun org-export--copy-to-kill-ring-p ()
3580 "Return a non-nil value when output should be added to the kill ring.
3581 See also `org-export-copy-to-kill-ring'."
3582 (if (eq org-export-copy-to-kill-ring 'if-interactive)
3583 (not (or executing-kbd-macro noninteractive))
3584 (eq org-export-copy-to-kill-ring t)))
3588 ;;; Tools For Back-Ends
3590 ;; A whole set of tools is available to help build new exporters. Any
3591 ;; function general enough to have its use across many back-ends
3592 ;; should be added here.
3594 ;;;; For Affiliated Keywords
3596 ;; `org-export-read-attribute' reads a property from a given element
3597 ;; as a plist. It can be used to normalize affiliated keywords'
3598 ;; syntax.
3600 ;; Since captions can span over multiple lines and accept dual values,
3601 ;; their internal representation is a bit tricky. Therefore,
3602 ;; `org-export-get-caption' transparently returns a given element's
3603 ;; caption as a secondary string.
3605 (defun org-export-read-attribute (attribute element &optional property)
3606 "Turn ATTRIBUTE property from ELEMENT into a plist.
3608 When optional argument PROPERTY is non-nil, return the value of
3609 that property within attributes.
3611 This function assumes attributes are defined as \":keyword
3612 value\" pairs. It is appropriate for `:attr_html' like
3613 properties.
3615 All values will become strings except the empty string and
3616 \"nil\", which will become nil. Also, values containing only
3617 double quotes will be read as-is, which means that \"\" value
3618 will become the empty string."
3619 (let* ((prepare-value
3620 (lambda (str)
3621 (save-match-data
3622 (cond ((member str '(nil "" "nil")) nil)
3623 ((string-match "^\"\\(\"+\\)?\"$" str)
3624 (or (match-string 1 str) ""))
3625 (t str)))))
3626 (attributes
3627 (let ((value (org-element-property attribute element)))
3628 (when value
3629 (let ((s (mapconcat 'identity value " ")) result)
3630 (while (string-match
3631 "\\(?:^\\|[ \t]+\\)\\(:[-a-zA-Z0-9_]+\\)\\([ \t]+\\|$\\)"
3633 (let ((value (substring s 0 (match-beginning 0))))
3634 (push (funcall prepare-value value) result))
3635 (push (intern (match-string 1 s)) result)
3636 (setq s (substring s (match-end 0))))
3637 ;; Ignore any string before first property with `cdr'.
3638 (cdr (nreverse (cons (funcall prepare-value s) result))))))))
3639 (if property (plist-get attributes property) attributes)))
3641 (defun org-export-get-caption (element &optional shortp)
3642 "Return caption from ELEMENT as a secondary string.
3644 When optional argument SHORTP is non-nil, return short caption,
3645 as a secondary string, instead.
3647 Caption lines are separated by a white space."
3648 (let ((full-caption (org-element-property :caption element)) caption)
3649 (dolist (line full-caption (cdr caption))
3650 (let ((cap (funcall (if shortp 'cdr 'car) line)))
3651 (when cap
3652 (setq caption (nconc (list " ") (copy-sequence cap) caption)))))))
3655 ;;;; For Derived Back-ends
3657 ;; `org-export-with-backend' is a function allowing to locally use
3658 ;; another back-end to transcode some object or element. In a derived
3659 ;; back-end, it may be used as a fall-back function once all specific
3660 ;; cases have been treated.
3662 (defun org-export-with-backend (backend data &optional contents info)
3663 "Call a transcoder from BACKEND on DATA.
3664 BACKEND is an export back-end, as returned by, e.g.,
3665 `org-export-create-backend', or a symbol referring to
3666 a registered back-end. DATA is an Org element, object, secondary
3667 string or string. CONTENTS, when non-nil, is the transcoded
3668 contents of DATA element, as a string. INFO, when non-nil, is
3669 the communication channel used for export, as a plist."
3670 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
3671 (org-export-barf-if-invalid-backend backend)
3672 (let ((type (org-element-type data)))
3673 (when (memq type '(nil org-data)) (error "No foreign transcoder available"))
3674 (let* ((all-transcoders (org-export-get-all-transcoders backend))
3675 (transcoder (cdr (assq type all-transcoders))))
3676 (unless (functionp transcoder) (error "No foreign transcoder available"))
3677 (let ((new-info
3678 (org-combine-plists
3679 info (list
3680 :back-end backend
3681 :translate-alist all-transcoders
3682 :exported-data (make-hash-table :test #'eq :size 401)))))
3683 ;; `:internal-references' are shared across back-ends.
3684 (prog1 (if (eq type 'plain-text)
3685 (funcall transcoder data new-info)
3686 (funcall transcoder data contents new-info))
3687 (plist-put info :internal-references
3688 (plist-get new-info :internal-references)))))))
3691 ;;;; For Export Snippets
3693 ;; Every export snippet is transmitted to the back-end. Though, the
3694 ;; latter will only retain one type of export-snippet, ignoring
3695 ;; others, based on the former's target back-end. The function
3696 ;; `org-export-snippet-backend' returns that back-end for a given
3697 ;; export-snippet.
3699 (defun org-export-snippet-backend (export-snippet)
3700 "Return EXPORT-SNIPPET targeted back-end as a symbol.
3701 Translation, with `org-export-snippet-translation-alist', is
3702 applied."
3703 (let ((back-end (org-element-property :back-end export-snippet)))
3704 (intern
3705 (or (cdr (assoc back-end org-export-snippet-translation-alist))
3706 back-end))))
3709 ;;;; For Footnotes
3711 ;; `org-export-collect-footnote-definitions' is a tool to list
3712 ;; actually used footnotes definitions in the whole parse tree, or in
3713 ;; a headline, in order to add footnote listings throughout the
3714 ;; transcoded data.
3716 ;; `org-export-footnote-first-reference-p' is a predicate used by some
3717 ;; back-ends, when they need to attach the footnote definition only to
3718 ;; the first occurrence of the corresponding label.
3720 ;; `org-export-get-footnote-definition' and
3721 ;; `org-export-get-footnote-number' provide easier access to
3722 ;; additional information relative to a footnote reference.
3724 (defun org-export-get-footnote-definition (footnote-reference info)
3725 "Return definition of FOOTNOTE-REFERENCE as parsed data.
3726 INFO is the plist used as a communication channel. If no such
3727 definition can be found, raise an error."
3728 (let ((label (org-element-property :label footnote-reference)))
3729 (if (not label) (org-element-contents footnote-reference)
3730 (let ((cache (or (plist-get info :footnote-definition-cache)
3731 (let ((hash (make-hash-table :test #'equal)))
3732 (plist-put info :footnote-definition-cache hash)
3733 hash))))
3735 (gethash label cache)
3736 (puthash label
3737 (org-element-map (plist-get info :parse-tree)
3738 '(footnote-definition footnote-reference)
3739 (lambda (f)
3740 (cond
3741 ;; Skip any footnote with a different label.
3742 ;; Also skip any standard footnote reference
3743 ;; with the same label since those cannot
3744 ;; contain a definition.
3745 ((not (equal (org-element-property :label f) label)) nil)
3746 ((eq (org-element-property :type f) 'standard) nil)
3747 ((org-element-contents f))
3748 ;; Even if the contents are empty, we can not
3749 ;; return nil since that would eventually raise
3750 ;; the error. Instead, return the equivalent
3751 ;; empty string.
3752 (t "")))
3753 info t)
3754 cache)
3755 (error "Definition not found for footnote %s" label))))))
3757 (defun org-export--footnote-reference-map
3758 (function data info &optional body-first)
3759 "Apply FUNCTION on every footnote reference in DATA.
3760 INFO is a plist containing export state. By default, as soon as
3761 a new footnote reference is encountered, FUNCTION is called onto
3762 its definition. However, if BODY-FIRST is non-nil, this step is
3763 delayed until the end of the process."
3764 (letrec ((definitions nil)
3765 (seen-refs nil)
3766 (search-ref
3767 (lambda (data delayp)
3768 ;; Search footnote references through DATA, filling
3769 ;; SEEN-REFS along the way. When DELAYP is non-nil,
3770 ;; store footnote definitions so they can be entered
3771 ;; later.
3772 (org-element-map data 'footnote-reference
3773 (lambda (f)
3774 (funcall function f)
3775 (let ((--label (org-element-property :label f)))
3776 (unless (and --label (member --label seen-refs))
3777 (when --label (push --label seen-refs))
3778 ;; Search for subsequent references in footnote
3779 ;; definition so numbering follows reading
3780 ;; logic, unless DELAYP in non-nil.
3781 (cond
3782 (delayp
3783 (push (org-export-get-footnote-definition f info)
3784 definitions))
3785 ;; Do not force entering inline definitions,
3786 ;; since `org-element-map' already traverses
3787 ;; them at the right time.
3788 ((eq (org-element-property :type f) 'inline))
3789 (t (funcall search-ref
3790 (org-export-get-footnote-definition f info)
3791 nil))))))
3792 info nil
3793 ;; Don't enter footnote definitions since it will
3794 ;; happen when their first reference is found.
3795 ;; Moreover, if DELAYP is non-nil, make sure we
3796 ;; postpone entering definitions of inline references.
3797 (if delayp '(footnote-definition footnote-reference)
3798 'footnote-definition)))))
3799 (funcall search-ref data body-first)
3800 (funcall search-ref (nreverse definitions) nil)))
3802 (defun org-export-collect-footnote-definitions (info &optional data body-first)
3803 "Return an alist between footnote numbers, labels and definitions.
3805 INFO is the current export state, as a plist.
3807 Definitions are collected throughout the whole parse tree, or
3808 DATA when non-nil.
3810 Sorting is done by order of references. As soon as a new
3811 reference is encountered, other references are searched within
3812 its definition. However, if BODY-FIRST is non-nil, this step is
3813 delayed after the whole tree is checked. This alters results
3814 when references are found in footnote definitions.
3816 Definitions either appear as Org data or as a secondary string
3817 for inlined footnotes. Unreferenced definitions are ignored."
3818 (let ((n 0) labels alist)
3819 (org-export--footnote-reference-map
3820 (lambda (f)
3821 ;; Collect footnote number, label and definition.
3822 (let ((l (org-element-property :label f)))
3823 (unless (and l (member l labels))
3824 (cl-incf n)
3825 (push (list n l (org-export-get-footnote-definition f info)) alist))
3826 (when l (push l labels))))
3827 (or data (plist-get info :parse-tree)) info body-first)
3828 (nreverse alist)))
3830 (defun org-export-footnote-first-reference-p
3831 (footnote-reference info &optional data body-first)
3832 "Non-nil when a footnote reference is the first one for its label.
3834 FOOTNOTE-REFERENCE is the footnote reference being considered.
3835 INFO is a plist containing current export state.
3837 Search is done throughout the whole parse tree, or DATA when
3838 non-nil.
3840 By default, as soon as a new footnote reference is encountered,
3841 other references are searched within its definition. However, if
3842 BODY-FIRST is non-nil, this step is delayed after the whole tree
3843 is checked. This alters results when references are found in
3844 footnote definitions."
3845 (let ((label (org-element-property :label footnote-reference)))
3846 ;; Anonymous footnotes are always a first reference.
3847 (or (not label)
3848 (catch 'exit
3849 (org-export--footnote-reference-map
3850 (lambda (f)
3851 (let ((l (org-element-property :label f)))
3852 (when (and l label (string= label l))
3853 (throw 'exit (eq footnote-reference f)))))
3854 (or data (plist-get info :parse-tree)) info body-first)))))
3856 (defun org-export-get-footnote-number (footnote info &optional data body-first)
3857 "Return number associated to a footnote.
3859 FOOTNOTE is either a footnote reference or a footnote definition.
3860 INFO is the plist containing export state.
3862 Number is unique throughout the whole parse tree, or DATA, when
3863 non-nil.
3865 By default, as soon as a new footnote reference is encountered,
3866 counting process moves into its definition. However, if
3867 BODY-FIRST is non-nil, this step is delayed until the end of the
3868 process, leading to a different order when footnotes are nested."
3869 (let ((count 0)
3870 (seen)
3871 (label (org-element-property :label footnote)))
3872 (catch 'exit
3873 (org-export--footnote-reference-map
3874 (lambda (f)
3875 (let ((l (org-element-property :label f)))
3876 (cond
3877 ;; Anonymous footnote match: return number.
3878 ((and (not l) (not label) (eq footnote f)) (throw 'exit (1+ count)))
3879 ;; Labels match: return number.
3880 ((and label l (string= label l)) (throw 'exit (1+ count)))
3881 ;; Otherwise store label and increase counter if label
3882 ;; wasn't encountered yet.
3883 ((not l) (cl-incf count))
3884 ((not (member l seen)) (push l seen) (cl-incf count)))))
3885 (or data (plist-get info :parse-tree)) info body-first))))
3888 ;;;; For Headlines
3890 ;; `org-export-get-relative-level' is a shortcut to get headline
3891 ;; level, relatively to the lower headline level in the parsed tree.
3893 ;; `org-export-get-headline-number' returns the section number of an
3894 ;; headline, while `org-export-number-to-roman' allows it to be
3895 ;; converted to roman numbers. With an optional argument,
3896 ;; `org-export-get-headline-number' returns a number to unnumbered
3897 ;; headlines (used for internal id).
3899 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
3900 ;; `org-export-last-sibling-p' are three useful predicates when it
3901 ;; comes to fulfill the `:headline-levels' property.
3903 ;; `org-export-get-tags', `org-export-get-category' and
3904 ;; `org-export-get-node-property' extract useful information from an
3905 ;; headline or a parent headline. They all handle inheritance.
3907 ;; `org-export-get-alt-title' tries to retrieve an alternative title,
3908 ;; as a secondary string, suitable for table of contents. It falls
3909 ;; back onto default title.
3911 (defun org-export-get-relative-level (headline info)
3912 "Return HEADLINE relative level within current parsed tree.
3913 INFO is a plist holding contextual information."
3914 (+ (org-element-property :level headline)
3915 (or (plist-get info :headline-offset) 0)))
3917 (defun org-export-low-level-p (headline info)
3918 "Non-nil when HEADLINE is considered as low level.
3920 INFO is a plist used as a communication channel.
3922 A low level headlines has a relative level greater than
3923 `:headline-levels' property value.
3925 Return value is the difference between HEADLINE relative level
3926 and the last level being considered as high enough, or nil."
3927 (let ((limit (plist-get info :headline-levels)))
3928 (when (wholenump limit)
3929 (let ((level (org-export-get-relative-level headline info)))
3930 (and (> level limit) (- level limit))))))
3932 (defun org-export-get-headline-number (headline info)
3933 "Return numbered HEADLINE numbering as a list of numbers.
3934 INFO is a plist holding contextual information."
3935 (and (org-export-numbered-headline-p headline info)
3936 (cdr (assq headline (plist-get info :headline-numbering)))))
3938 (defun org-export-numbered-headline-p (headline info)
3939 "Return a non-nil value if HEADLINE element should be numbered.
3940 INFO is a plist used as a communication channel."
3941 (unless (org-not-nil (org-export-get-node-property :UNNUMBERED headline t))
3942 (let ((sec-num (plist-get info :section-numbers))
3943 (level (org-export-get-relative-level headline info)))
3944 (if (wholenump sec-num) (<= level sec-num) sec-num))))
3946 (defun org-export-number-to-roman (n)
3947 "Convert integer N into a roman numeral."
3948 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
3949 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
3950 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
3951 ( 1 . "I")))
3952 (res ""))
3953 (if (<= n 0)
3954 (number-to-string n)
3955 (while roman
3956 (if (>= n (caar roman))
3957 (setq n (- n (caar roman))
3958 res (concat res (cdar roman)))
3959 (pop roman)))
3960 res)))
3962 (defun org-export-get-tags (element info &optional tags inherited)
3963 "Return list of tags associated to ELEMENT.
3965 ELEMENT has either an `headline' or an `inlinetask' type. INFO
3966 is a plist used as a communication channel.
3968 When non-nil, optional argument TAGS should be a list of strings.
3969 Any tag belonging to this list will also be removed.
3971 When optional argument INHERITED is non-nil, tags can also be
3972 inherited from parent headlines and FILETAGS keywords."
3973 (cl-remove-if
3974 (lambda (tag) (member tag tags))
3975 (if (not inherited) (org-element-property :tags element)
3976 ;; Build complete list of inherited tags.
3977 (let ((current-tag-list (org-element-property :tags element)))
3978 (dolist (parent (org-element-lineage element))
3979 (dolist (tag (org-element-property :tags parent))
3980 (when (and (memq (org-element-type parent) '(headline inlinetask))
3981 (not (member tag current-tag-list)))
3982 (push tag current-tag-list))))
3983 ;; Add FILETAGS keywords and return results.
3984 (org-uniquify (append (plist-get info :filetags) current-tag-list))))))
3986 (defun org-export-get-node-property (property blob &optional inherited)
3987 "Return node PROPERTY value for BLOB.
3989 PROPERTY is an upcase symbol (i.e. `:COOKIE_DATA'). BLOB is an
3990 element or object.
3992 If optional argument INHERITED is non-nil, the value can be
3993 inherited from a parent headline.
3995 Return value is a string or nil."
3996 (let ((headline (if (eq (org-element-type blob) 'headline) blob
3997 (org-export-get-parent-headline blob))))
3998 (if (not inherited) (org-element-property property blob)
3999 (let ((parent headline))
4000 (catch 'found
4001 (while parent
4002 (when (plist-member (nth 1 parent) property)
4003 (throw 'found (org-element-property property parent)))
4004 (setq parent (org-element-property :parent parent))))))))
4006 (defun org-export-get-category (blob info)
4007 "Return category for element or object BLOB.
4009 INFO is a plist used as a communication channel.
4011 CATEGORY is automatically inherited from a parent headline, from
4012 #+CATEGORY: keyword or created out of original file name. If all
4013 fail, the fall-back value is \"???\"."
4014 (or (org-export-get-node-property :CATEGORY blob t)
4015 (org-element-map (plist-get info :parse-tree) 'keyword
4016 (lambda (kwd)
4017 (when (equal (org-element-property :key kwd) "CATEGORY")
4018 (org-element-property :value kwd)))
4019 info 'first-match)
4020 (let ((file (plist-get info :input-file)))
4021 (and file (file-name-sans-extension (file-name-nondirectory file))))
4022 "???"))
4024 (defun org-export-get-alt-title (headline _)
4025 "Return alternative title for HEADLINE, as a secondary string.
4026 If no optional title is defined, fall-back to the regular title."
4027 (let ((alt (org-element-property :ALT_TITLE headline)))
4028 (if alt (org-element-parse-secondary-string
4029 alt (org-element-restriction 'headline) headline)
4030 (org-element-property :title headline))))
4032 (defun org-export-first-sibling-p (blob info)
4033 "Non-nil when BLOB is the first sibling in its parent.
4034 BLOB is an element or an object. If BLOB is a headline, non-nil
4035 means it is the first sibling in the sub-tree. INFO is a plist
4036 used as a communication channel."
4037 (memq (org-element-type (org-export-get-previous-element blob info))
4038 '(nil section)))
4040 (defun org-export-last-sibling-p (datum info)
4041 "Non-nil when DATUM is the last sibling in its parent.
4042 DATUM is an element or an object. INFO is a plist used as
4043 a communication channel."
4044 (let ((next (org-export-get-next-element datum info)))
4045 (or (not next)
4046 (and (eq 'headline (org-element-type datum))
4047 (> (org-element-property :level datum)
4048 (org-element-property :level next))))))
4051 ;;;; For Keywords
4053 ;; `org-export-get-date' returns a date appropriate for the document
4054 ;; to about to be exported. In particular, it takes care of
4055 ;; `org-export-date-timestamp-format'.
4057 (defun org-export-get-date (info &optional fmt)
4058 "Return date value for the current document.
4060 INFO is a plist used as a communication channel. FMT, when
4061 non-nil, is a time format string that will be applied on the date
4062 if it consists in a single timestamp object. It defaults to
4063 `org-export-date-timestamp-format' when nil.
4065 A proper date can be a secondary string, a string or nil. It is
4066 meant to be translated with `org-export-data' or alike."
4067 (let ((date (plist-get info :date))
4068 (fmt (or fmt org-export-date-timestamp-format)))
4069 (cond ((not date) nil)
4070 ((and fmt
4071 (not (cdr date))
4072 (eq (org-element-type (car date)) 'timestamp))
4073 (org-timestamp-format (car date) fmt))
4074 (t date))))
4077 ;;;; For Links
4079 ;; `org-export-custom-protocol-maybe' handles custom protocol defined
4080 ;; in `org-link-parameters'.
4082 ;; `org-export-get-coderef-format' returns an appropriate format
4083 ;; string for coderefs.
4085 ;; `org-export-inline-image-p' returns a non-nil value when the link
4086 ;; provided should be considered as an inline image.
4088 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
4089 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
4090 ;; returns an appropriate unique identifier.
4092 ;; `org-export-resolve-id-link' returns the first headline with
4093 ;; specified id or custom-id in parse tree, the path to the external
4094 ;; file with the id.
4096 ;; `org-export-resolve-coderef' associates a reference to a line
4097 ;; number in the element it belongs, or returns the reference itself
4098 ;; when the element isn't numbered.
4100 ;; `org-export-file-uri' expands a filename as stored in :path value
4101 ;; of a "file" link into a file URI.
4103 ;; Broken links raise a `org-link-broken' error, which is caught by
4104 ;; `org-export-data' for further processing, depending on
4105 ;; `org-export-with-broken-links' value.
4107 (org-define-error 'org-link-broken "Unable to resolve link; aborting")
4109 (defun org-export-custom-protocol-maybe (link desc backend)
4110 "Try exporting LINK with a dedicated function.
4112 DESC is its description, as a string, or nil. BACKEND is the
4113 back-end used for export, as a symbol.
4115 Return output as a string, or nil if no protocol handles LINK.
4117 A custom protocol has precedence over regular back-end export.
4118 The function ignores links with an implicit type (e.g.,
4119 \"custom-id\")."
4120 (let ((type (org-element-property :type link)))
4121 (unless (or (member type '("coderef" "custom-id" "fuzzy" "radio"))
4122 (not backend))
4123 (let ((protocol (org-link-get-parameter type :export)))
4124 (and (functionp protocol)
4125 (funcall protocol
4126 (org-link-unescape (org-element-property :path link))
4127 desc
4128 backend))))))
4130 (defun org-export-get-coderef-format (path desc)
4131 "Return format string for code reference link.
4132 PATH is the link path. DESC is its description."
4133 (save-match-data
4134 (cond ((not desc) "%s")
4135 ((string-match (regexp-quote (concat "(" path ")")) desc)
4136 (replace-match "%s" t t desc))
4137 (t desc))))
4139 (defun org-export-inline-image-p (link &optional rules)
4140 "Non-nil if LINK object points to an inline image.
4142 Optional argument is a set of RULES defining inline images. It
4143 is an alist where associations have the following shape:
4145 (TYPE . REGEXP)
4147 Applying a rule means apply REGEXP against LINK's path when its
4148 type is TYPE. The function will return a non-nil value if any of
4149 the provided rules is non-nil. The default rule is
4150 `org-export-default-inline-image-rule'.
4152 This only applies to links without a description."
4153 (and (not (org-element-contents link))
4154 (let ((case-fold-search t))
4155 (cl-some (lambda (rule)
4156 (and (string= (org-element-property :type link) (car rule))
4157 (string-match-p (cdr rule)
4158 (org-element-property :path link))))
4159 (or rules org-export-default-inline-image-rule)))))
4161 (defun org-export-insert-image-links (data info &optional rules)
4162 "Insert image links in DATA.
4164 Org syntax does not support nested links. Nevertheless, some
4165 export back-ends support images as descriptions of links. Since
4166 images are really links to image files, we need to make an
4167 exception about links nesting.
4169 This function recognizes links whose contents are really images
4170 and turn them into proper nested links. It is meant to be used
4171 as a parse tree filter in back-ends supporting such constructs.
4173 DATA is a parse tree. INFO is the current state of the export
4174 process, as a plist.
4176 A description is a valid images if it matches any rule in RULES,
4177 if non-nil, or `org-export-default-inline-image-rule' otherwise.
4178 See `org-export-inline-image-p' for more information about the
4179 structure of RULES.
4181 Return modified DATA."
4182 (let ((link-re (format "\\`\\(?:%s\\|%s\\)\\'"
4183 org-plain-link-re
4184 org-angle-link-re))
4185 (case-fold-search t))
4186 (org-element-map data 'link
4187 (lambda (l)
4188 (let ((contents (org-element-interpret-data (org-element-contents l))))
4189 (when (and (org-string-nw-p contents)
4190 (string-match link-re contents))
4191 (let ((type (match-string 1 contents))
4192 (path (match-string 2 contents)))
4193 (when (cl-some (lambda (rule)
4194 (and (string= type (car rule))
4195 (string-match-p (cdr rule) path)))
4196 (or rules org-export-default-inline-image-rule))
4197 ;; Replace contents with image link.
4198 (org-element-adopt-elements
4199 (org-element-set-contents l nil)
4200 (with-temp-buffer
4201 (save-excursion (insert contents))
4202 (org-element-link-parser))))))))
4203 info nil nil t))
4204 data)
4206 (defun org-export-resolve-coderef (ref info)
4207 "Resolve a code reference REF.
4209 INFO is a plist used as a communication channel.
4211 Return associated line number in source code, or REF itself,
4212 depending on src-block or example element's switches. Throw an
4213 error if no block contains REF."
4214 (or (org-element-map (plist-get info :parse-tree) '(example-block src-block)
4215 (lambda (el)
4216 (with-temp-buffer
4217 (insert (org-trim (org-element-property :value el)))
4218 (let* ((label-fmt (or (org-element-property :label-fmt el)
4219 org-coderef-label-format))
4220 (ref-re (org-src-coderef-regexp label-fmt ref)))
4221 ;; Element containing REF is found. Resolve it to
4222 ;; either a label or a line number, as needed.
4223 (when (re-search-backward ref-re nil t)
4224 (if (org-element-property :use-labels el) ref
4225 (+ (or (org-export-get-loc el info) 0)
4226 (line-number-at-pos)))))))
4227 info 'first-match)
4228 (signal 'org-link-broken (list ref))))
4230 (defun org-export-search-cells (datum)
4231 "List search cells for element or object DATUM.
4233 A search cell follows the pattern (TYPE . SEARCH) where
4235 TYPE is a symbol among `headline', `custom-id', `target' and
4236 `other'.
4238 SEARCH is the string a link is expected to match. More
4239 accurately, it is
4241 - headline's title, as a list of strings, if TYPE is
4242 `headline'.
4244 - CUSTOM_ID value, as a string, if TYPE is `custom-id'.
4246 - target's or radio-target's name as a list of strings if
4247 TYPE is `target'.
4249 - NAME affiliated keyword is TYPE is `other'.
4251 A search cell is the internal representation of a fuzzy link. It
4252 ignores white spaces and statistics cookies, if applicable."
4253 (pcase (org-element-type datum)
4254 (`headline
4255 (let ((title (split-string
4256 (replace-regexp-in-string
4257 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]" ""
4258 (org-element-property :raw-value datum)))))
4259 (delq nil
4260 (list
4261 (cons 'headline title)
4262 (cons 'other title)
4263 (let ((custom-id (org-element-property :custom-id datum)))
4264 (and custom-id (cons 'custom-id custom-id)))))))
4265 (`target
4266 (list (cons 'target (split-string (org-element-property :value datum)))))
4267 ((and (let name (org-element-property :name datum))
4268 (guard name))
4269 (list (cons 'other (split-string name))))
4270 (_ nil)))
4272 (defun org-export-string-to-search-cell (s)
4273 "Return search cells associated to string S.
4274 S is either the path of a fuzzy link or a search option, i.e., it
4275 tries to match either a headline (through custom ID or title),
4276 a target or a named element."
4277 (pcase (string-to-char s)
4278 (?* (list (cons 'headline (split-string (substring s 1)))))
4279 (?# (list (cons 'custom-id (substring s 1))))
4280 ((let search (split-string s))
4281 (list (cons 'target search) (cons 'other search)))))
4283 (defun org-export-match-search-cell-p (datum cells)
4284 "Non-nil when DATUM matches search cells CELLS.
4285 DATUM is an element or object. CELLS is a list of search cells,
4286 as returned by `org-export-search-cells'."
4287 (let ((targets (org-export-search-cells datum)))
4288 (and targets (cl-some (lambda (cell) (member cell targets)) cells))))
4290 (defun org-export-resolve-fuzzy-link (link info)
4291 "Return LINK destination.
4293 INFO is a plist holding contextual information.
4295 Return value can be an object or an element:
4297 - If LINK path matches a target object (i.e. <<path>>) return it.
4299 - If LINK path exactly matches the name affiliated keyword
4300 (i.e. #+NAME: path) of an element, return that element.
4302 - If LINK path exactly matches any headline name, return that
4303 element.
4305 - Otherwise, throw an error.
4307 Assume LINK type is \"fuzzy\". White spaces are not
4308 significant."
4309 (let* ((search-cells (org-export-string-to-search-cell
4310 (org-link-unescape (org-element-property :path link))))
4311 (link-cache (or (plist-get info :resolve-fuzzy-link-cache)
4312 (let ((table (make-hash-table :test #'eq)))
4313 (plist-put info :resolve-fuzzy-link-cache table)
4314 table)))
4315 (cached (gethash search-cells link-cache 'not-found)))
4316 (if (not (eq cached 'not-found)) cached
4317 (let ((matches
4318 (org-element-map (plist-get info :parse-tree)
4319 (cons 'target org-element-all-elements)
4320 (lambda (datum)
4321 (and (org-export-match-search-cell-p datum search-cells)
4322 datum)))))
4323 (unless matches
4324 (signal 'org-link-broken (list (org-element-property :path link))))
4325 (puthash
4326 search-cells
4327 ;; There can be multiple matches for un-typed searches, i.e.,
4328 ;; for searches not starting with # or *. In this case,
4329 ;; prioritize targets and names over headline titles.
4330 ;; Matching both a name and a target is not valid, and
4331 ;; therefore undefined.
4332 (or (cl-some (lambda (datum)
4333 (and (not (eq (org-element-type datum) 'headline))
4334 datum))
4335 matches)
4336 (car matches))
4337 link-cache)))))
4339 (defun org-export-resolve-id-link (link info)
4340 "Return headline referenced as LINK destination.
4342 INFO is a plist used as a communication channel.
4344 Return value can be the headline element matched in current parse
4345 tree or a file name. Assume LINK type is either \"id\" or
4346 \"custom-id\". Throw an error if no match is found."
4347 (let ((id (org-element-property :path link)))
4348 ;; First check if id is within the current parse tree.
4349 (or (org-element-map (plist-get info :parse-tree) 'headline
4350 (lambda (headline)
4351 (when (or (equal (org-element-property :ID headline) id)
4352 (equal (org-element-property :CUSTOM_ID headline) id))
4353 headline))
4354 info 'first-match)
4355 ;; Otherwise, look for external files.
4356 (cdr (assoc id (plist-get info :id-alist)))
4357 (signal 'org-link-broken (list id)))))
4359 (defun org-export-resolve-radio-link (link info)
4360 "Return radio-target object referenced as LINK destination.
4362 INFO is a plist used as a communication channel.
4364 Return value can be a radio-target object or nil. Assume LINK
4365 has type \"radio\"."
4366 (let ((path (replace-regexp-in-string
4367 "[ \r\t\n]+" " " (org-element-property :path link))))
4368 (org-element-map (plist-get info :parse-tree) 'radio-target
4369 (lambda (radio)
4370 (and (eq (compare-strings
4371 (replace-regexp-in-string
4372 "[ \r\t\n]+" " " (org-element-property :value radio))
4373 nil nil path nil nil t)
4375 radio))
4376 info 'first-match)))
4378 (defun org-export-file-uri (filename)
4379 "Return file URI associated to FILENAME."
4380 (cond ((string-prefix-p "//" filename) (concat "file:" filename))
4381 ((not (file-name-absolute-p filename)) filename)
4382 ((org-file-remote-p filename) (concat "file:/" filename))
4384 (let ((fullname (expand-file-name filename)))
4385 (concat (if (string-prefix-p "/" fullname) "file://" "file:///")
4386 fullname)))))
4388 ;;;; For References
4390 ;; `org-export-get-reference' associate a unique reference for any
4391 ;; object or element. It uses `org-export-new-reference' and
4392 ;; `org-export-format-reference' to, respectively, generate new
4393 ;; internal references and turn them into a string suitable for
4394 ;; output.
4396 ;; `org-export-get-ordinal' associates a sequence number to any object
4397 ;; or element.
4399 (defun org-export-new-reference (references)
4400 "Return a unique reference, among REFERENCES.
4401 REFERENCES is an alist whose values are in-use references, as
4402 numbers. Returns a number, which is the internal representation
4403 of a reference. See also `org-export-format-reference'."
4404 ;; Generate random 7 digits hexadecimal numbers. Collisions
4405 ;; increase exponentially with the numbers of references. However,
4406 ;; the odds for encountering at least one collision with 1000 active
4407 ;; references in the same document are roughly 0.2%, so this
4408 ;; shouldn't be the bottleneck.
4409 (let ((new (random #x10000000)))
4410 (while (rassq new references) (setq new (random #x10000000)))
4411 new))
4413 (defun org-export-format-reference (reference)
4414 "Format REFERENCE into a string.
4415 REFERENCE is a number representing a reference, as returned by
4416 `org-export-new-reference', which see."
4417 (format "org%07x" reference))
4419 (defun org-export-get-reference (datum info)
4420 "Return a unique reference for DATUM, as a string.
4422 DATUM is either an element or an object. INFO is the current
4423 export state, as a plist.
4425 References for the current document are stored in
4426 `:internal-references' property. Its value is an alist with
4427 associations of the following types:
4429 (REFERENCE . DATUM) and (SEARCH-CELL . ID)
4431 REFERENCE is the reference string to be used for object or
4432 element DATUM. SEARCH-CELL is a search cell, as returned by
4433 `org-export-search-cells'. ID is a number or a string uniquely
4434 identifying DATUM within the document.
4436 This function also checks `:crossrefs' property for search cells
4437 matching DATUM before creating a new reference."
4438 (let ((cache (plist-get info :internal-references)))
4439 (or (car (rassq datum cache))
4440 (let* ((crossrefs (plist-get info :crossrefs))
4441 (cells (org-export-search-cells datum))
4442 ;; Preserve any pre-existing association between
4443 ;; a search cell and a reference, i.e., when some
4444 ;; previously published document referenced a location
4445 ;; within current file (see
4446 ;; `org-publish-resolve-external-link').
4448 ;; However, there is no guarantee that search cells are
4449 ;; unique, e.g., there might be duplicate custom ID or
4450 ;; two headings with the same title in the file.
4452 ;; As a consequence, before re-using any reference to
4453 ;; an element or object, we check that it doesn't refer
4454 ;; to a previous element or object.
4455 (new (or (cl-some
4456 (lambda (cell)
4457 (let ((stored (cdr (assoc cell crossrefs))))
4458 (when stored
4459 (let ((old (org-export-format-reference stored)))
4460 (and (not (assoc old cache)) stored)))))
4461 cells)
4462 (org-export-new-reference cache)))
4463 (reference-string (org-export-format-reference new)))
4464 ;; Cache contains both data already associated to
4465 ;; a reference and in-use internal references, so as to make
4466 ;; unique references.
4467 (dolist (cell cells) (push (cons cell new) cache))
4468 ;; Retain a direct association between reference string and
4469 ;; DATUM since (1) not every object or element can be given
4470 ;; a search cell (2) it permits quick lookup.
4471 (push (cons reference-string datum) cache)
4472 (plist-put info :internal-references cache)
4473 reference-string))))
4475 (defun org-export-get-ordinal (element info &optional types predicate)
4476 "Return ordinal number of an element or object.
4478 ELEMENT is the element or object considered. INFO is the plist
4479 used as a communication channel.
4481 Optional argument TYPES, when non-nil, is a list of element or
4482 object types, as symbols, that should also be counted in.
4483 Otherwise, only provided element's type is considered.
4485 Optional argument PREDICATE is a function returning a non-nil
4486 value if the current element or object should be counted in. It
4487 accepts two arguments: the element or object being considered and
4488 the plist used as a communication channel. This allows counting
4489 only a certain type of object (i.e. inline images).
4491 Return value is a list of numbers if ELEMENT is a headline or an
4492 item. It is nil for keywords. It represents the footnote number
4493 for footnote definitions and footnote references. If ELEMENT is
4494 a target, return the same value as if ELEMENT was the closest
4495 table, item or headline containing the target. In any other
4496 case, return the sequence number of ELEMENT among elements or
4497 objects of the same type."
4498 ;; Ordinal of a target object refer to the ordinal of the closest
4499 ;; table, item, or headline containing the object.
4500 (when (eq (org-element-type element) 'target)
4501 (setq element
4502 (org-element-lineage
4503 element
4504 '(footnote-definition footnote-reference headline item table))))
4505 (cl-case (org-element-type element)
4506 ;; Special case 1: A headline returns its number as a list.
4507 (headline (org-export-get-headline-number element info))
4508 ;; Special case 2: An item returns its number as a list.
4509 (item (let ((struct (org-element-property :structure element)))
4510 (org-list-get-item-number
4511 (org-element-property :begin element)
4512 struct
4513 (org-list-prevs-alist struct)
4514 (org-list-parents-alist struct))))
4515 ((footnote-definition footnote-reference)
4516 (org-export-get-footnote-number element info))
4517 (otherwise
4518 (let ((counter 0))
4519 ;; Increment counter until ELEMENT is found again.
4520 (org-element-map (plist-get info :parse-tree)
4521 (or types (org-element-type element))
4522 (lambda (el)
4523 (cond
4524 ((eq element el) (1+ counter))
4525 ((not predicate) (cl-incf counter) nil)
4526 ((funcall predicate el info) (cl-incf counter) nil)))
4527 info 'first-match)))))
4530 ;;;; For Src-Blocks
4532 ;; `org-export-get-loc' counts number of code lines accumulated in
4533 ;; src-block or example-block elements with a "+n" switch until
4534 ;; a given element, excluded. Note: "-n" switches reset that count.
4536 ;; `org-export-unravel-code' extracts source code (along with a code
4537 ;; references alist) from an `element-block' or `src-block' type
4538 ;; element.
4540 ;; `org-export-format-code' applies a formatting function to each line
4541 ;; of code, providing relative line number and code reference when
4542 ;; appropriate. Since it doesn't access the original element from
4543 ;; which the source code is coming, it expects from the code calling
4544 ;; it to know if lines should be numbered and if code references
4545 ;; should appear.
4547 ;; Eventually, `org-export-format-code-default' is a higher-level
4548 ;; function (it makes use of the two previous functions) which handles
4549 ;; line numbering and code references inclusion, and returns source
4550 ;; code in a format suitable for plain text or verbatim output.
4552 (defun org-export-get-loc (element info)
4553 "Return count of lines of code before ELEMENT.
4555 ELEMENT is an example-block or src-block element. INFO is the
4556 plist used as a communication channel.
4558 Count includes every line of code in example-block or src-block
4559 with a \"+n\" or \"-n\" switch before block. Return nil if
4560 ELEMENT doesn't allow line numbering."
4561 (pcase (org-element-property :number-lines element)
4562 (`(new . ,n) n)
4563 (`(continued . ,n)
4564 (let ((loc 0))
4565 (org-element-map (plist-get info :parse-tree) '(src-block example-block)
4566 (lambda (el)
4567 ;; ELEMENT is reached: Quit loop and return locs.
4568 (if (eq el element) (+ loc n)
4569 ;; Only count lines from src-block and example-block
4570 ;; elements with a "+n" or "-n" switch.
4571 (let ((linum (org-element-property :number-lines el)))
4572 (when linum
4573 (let ((lines (org-count-lines
4574 (org-element-property :value el))))
4575 ;; Accumulate locs or reset them.
4576 (pcase linum
4577 (`(new . ,n) (setq loc (+ n lines)))
4578 (`(continued . ,n) (cl-incf loc (+ n lines)))))))
4579 nil)) ;Return nil to stay in the loop.
4580 info 'first-match)))))
4582 (defun org-export-unravel-code (element)
4583 "Clean source code and extract references out of it.
4585 ELEMENT has either a `src-block' an `example-block' type.
4587 Return a cons cell whose CAR is the source code, cleaned from any
4588 reference, protective commas and spurious indentation, and CDR is
4589 an alist between relative line number (integer) and name of code
4590 reference on that line (string)."
4591 (let* ((line 0) refs
4592 (value (org-element-property :value element))
4593 ;; Remove global indentation from code, if necessary. Also
4594 ;; remove final newline character, since it doesn't belongs
4595 ;; to the code proper.
4596 (code (replace-regexp-in-string
4597 "\n\\'" ""
4598 (if (or org-src-preserve-indentation
4599 (org-element-property :preserve-indent element))
4600 value
4601 (org-remove-indentation value))))
4602 ;; Build a regexp matching a loc with a reference.
4603 (ref-re (org-src-coderef-regexp (org-src-coderef-format element))))
4604 ;; Return value.
4605 (cons
4606 ;; Code with references removed.
4607 (mapconcat
4608 (lambda (loc)
4609 (cl-incf line)
4610 (if (not (string-match ref-re loc)) loc
4611 ;; Ref line: remove ref, and add its position in REFS.
4612 (push (cons line (match-string 3 loc)) refs)
4613 (replace-match "" nil nil loc 1)))
4614 (split-string code "\n") "\n")
4615 ;; Reference alist.
4616 refs)))
4618 (defun org-export-format-code (code fun &optional num-lines ref-alist)
4619 "Format CODE by applying FUN line-wise and return it.
4621 CODE is a string representing the code to format. FUN is
4622 a function. It must accept three arguments: a line of
4623 code (string), the current line number (integer) or nil and the
4624 reference associated to the current line (string) or nil.
4626 Optional argument NUM-LINES can be an integer representing the
4627 number of code lines accumulated until the current code. Line
4628 numbers passed to FUN will take it into account. If it is nil,
4629 FUN's second argument will always be nil. This number can be
4630 obtained with `org-export-get-loc' function.
4632 Optional argument REF-ALIST can be an alist between relative line
4633 number (i.e. ignoring NUM-LINES) and the name of the code
4634 reference on it. If it is nil, FUN's third argument will always
4635 be nil. It can be obtained through the use of
4636 `org-export-unravel-code' function."
4637 (let ((--locs (split-string code "\n"))
4638 (--line 0))
4639 (concat
4640 (mapconcat
4641 (lambda (--loc)
4642 (cl-incf --line)
4643 (let ((--ref (cdr (assq --line ref-alist))))
4644 (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
4645 --locs "\n")
4646 "\n")))
4648 (defun org-export-format-code-default (element info)
4649 "Return source code from ELEMENT, formatted in a standard way.
4651 ELEMENT is either a `src-block' or `example-block' element. INFO
4652 is a plist used as a communication channel.
4654 This function takes care of line numbering and code references
4655 inclusion. Line numbers, when applicable, appear at the
4656 beginning of the line, separated from the code by two white
4657 spaces. Code references, on the other hand, appear flushed to
4658 the right, separated by six white spaces from the widest line of
4659 code."
4660 ;; Extract code and references.
4661 (let* ((code-info (org-export-unravel-code element))
4662 (code (car code-info))
4663 (code-lines (split-string code "\n")))
4664 (if (null code-lines) ""
4665 (let* ((refs (and (org-element-property :retain-labels element)
4666 (cdr code-info)))
4667 ;; Handle line numbering.
4668 (num-start (org-export-get-loc element info))
4669 (num-fmt
4670 (and num-start
4671 (format "%%%ds "
4672 (length (number-to-string
4673 (+ (length code-lines) num-start))))))
4674 ;; Prepare references display, if required. Any reference
4675 ;; should start six columns after the widest line of code,
4676 ;; wrapped with parenthesis.
4677 (max-width
4678 (+ (apply 'max (mapcar 'length code-lines))
4679 (if (not num-start) 0 (length (format num-fmt num-start))))))
4680 (org-export-format-code
4681 code
4682 (lambda (loc line-num ref)
4683 (let ((number-str (and num-fmt (format num-fmt line-num))))
4684 (concat
4685 number-str
4687 (and ref
4688 (concat (make-string (- (+ 6 max-width)
4689 (+ (length loc) (length number-str)))
4690 ?\s)
4691 (format "(%s)" ref))))))
4692 num-start refs)))))
4695 ;;;; For Tables
4697 ;; `org-export-table-has-special-column-p' and and
4698 ;; `org-export-table-row-is-special-p' are predicates used to look for
4699 ;; meta-information about the table structure.
4701 ;; `org-table-has-header-p' tells when the rows before the first rule
4702 ;; should be considered as table's header.
4704 ;; `org-export-table-cell-width', `org-export-table-cell-alignment'
4705 ;; and `org-export-table-cell-borders' extract information from
4706 ;; a table-cell element.
4708 ;; `org-export-table-dimensions' gives the number on rows and columns
4709 ;; in the table, ignoring horizontal rules and special columns.
4710 ;; `org-export-table-cell-address', given a table-cell object, returns
4711 ;; the absolute address of a cell. On the other hand,
4712 ;; `org-export-get-table-cell-at' does the contrary.
4714 ;; `org-export-table-cell-starts-colgroup-p',
4715 ;; `org-export-table-cell-ends-colgroup-p',
4716 ;; `org-export-table-row-starts-rowgroup-p',
4717 ;; `org-export-table-row-ends-rowgroup-p',
4718 ;; `org-export-table-row-starts-header-p',
4719 ;; `org-export-table-row-ends-header-p' and
4720 ;; `org-export-table-row-in-header-p' indicate position of current row
4721 ;; or cell within the table.
4723 (defun org-export-table-has-special-column-p (table)
4724 "Non-nil when TABLE has a special column.
4725 All special columns will be ignored during export."
4726 ;; The table has a special column when every first cell of every row
4727 ;; has an empty value or contains a symbol among "/", "#", "!", "$",
4728 ;; "*" "_" and "^". Though, do not consider a first column
4729 ;; containing only empty cells as special.
4730 (let ((special-column? 'empty))
4731 (catch 'exit
4732 (dolist (row (org-element-contents table))
4733 (when (eq (org-element-property :type row) 'standard)
4734 (let ((value (org-element-contents
4735 (car (org-element-contents row)))))
4736 (cond ((member value
4737 '(("/") ("#") ("!") ("$") ("*") ("_") ("^")))
4738 (setq special-column? 'special))
4739 ((null value))
4740 (t (throw 'exit nil))))))
4741 (eq special-column? 'special))))
4743 (defun org-export-table-has-header-p (table info)
4744 "Non-nil when TABLE has a header.
4746 INFO is a plist used as a communication channel.
4748 A table has a header when it contains at least two row groups."
4749 (let* ((cache (or (plist-get info :table-header-cache)
4750 (let ((table (make-hash-table :test #'eq)))
4751 (plist-put info :table-header-cache table)
4752 table)))
4753 (cached (gethash table cache 'no-cache)))
4754 (if (not (eq cached 'no-cache)) cached
4755 (let ((rowgroup 1) row-flag)
4756 (puthash table
4757 (org-element-map table 'table-row
4758 (lambda (row)
4759 (cond
4760 ((> rowgroup 1) t)
4761 ((and row-flag
4762 (eq (org-element-property :type row) 'rule))
4763 (cl-incf rowgroup)
4764 (setq row-flag nil))
4765 ((and (not row-flag)
4766 (eq (org-element-property :type row) 'standard))
4767 (setq row-flag t)
4768 nil)))
4769 info 'first-match)
4770 cache)))))
4772 (defun org-export-table-row-is-special-p (table-row _)
4773 "Non-nil if TABLE-ROW is considered special.
4774 All special rows will be ignored during export."
4775 (when (eq (org-element-property :type table-row) 'standard)
4776 (let ((first-cell (org-element-contents
4777 (car (org-element-contents table-row)))))
4778 ;; A row is special either when...
4780 ;; ... it starts with a field only containing "/",
4781 (equal first-cell '("/"))
4782 ;; ... the table contains a special column and the row start
4783 ;; with a marking character among, "^", "_", "$" or "!",
4784 (and (org-export-table-has-special-column-p
4785 (org-export-get-parent table-row))
4786 (member first-cell '(("^") ("_") ("$") ("!"))))
4787 ;; ... it contains only alignment cookies and empty cells.
4788 (let ((special-row-p 'empty))
4789 (catch 'exit
4790 (dolist (cell (org-element-contents table-row))
4791 (let ((value (org-element-contents cell)))
4792 ;; Since VALUE is a secondary string, the following
4793 ;; checks avoid expanding it with `org-export-data'.
4794 (cond ((not value))
4795 ((and (not (cdr value))
4796 (stringp (car value))
4797 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'"
4798 (car value)))
4799 (setq special-row-p 'cookie))
4800 (t (throw 'exit nil)))))
4801 (eq special-row-p 'cookie)))))))
4803 (defun org-export-table-row-group (table-row info)
4804 "Return TABLE-ROW's group number, as an integer.
4806 INFO is a plist used as the communication channel.
4808 Return value is the group number, as an integer, or nil for
4809 special rows and rows separators. First group is also table's
4810 header."
4811 (when (eq (org-element-property :type table-row) 'standard)
4812 (let* ((cache (or (plist-get info :table-row-group-cache)
4813 (let ((table (make-hash-table :test #'eq)))
4814 (plist-put info :table-row-group-cache table)
4815 table)))
4816 (cached (gethash table-row cache 'no-cache)))
4817 (if (not (eq cached 'no-cache)) cached
4818 ;; First time a row is queried, populate cache with all the
4819 ;; rows from the table.
4820 (let ((group 0) row-flag)
4821 (org-element-map (org-export-get-parent table-row) 'table-row
4822 (lambda (row)
4823 (if (eq (org-element-property :type row) 'rule)
4824 (setq row-flag nil)
4825 (unless row-flag (cl-incf group) (setq row-flag t))
4826 (puthash row group cache)))
4827 info))
4828 (gethash table-row cache)))))
4830 (defun org-export-table-cell-width (table-cell info)
4831 "Return TABLE-CELL contents width.
4833 INFO is a plist used as the communication channel.
4835 Return value is the width given by the last width cookie in the
4836 same column as TABLE-CELL, or nil."
4837 (let* ((row (org-export-get-parent table-cell))
4838 (table (org-export-get-parent row))
4839 (cells (org-element-contents row))
4840 (columns (length cells))
4841 (column (- columns (length (memq table-cell cells))))
4842 (cache (or (plist-get info :table-cell-width-cache)
4843 (let ((table (make-hash-table :test #'eq)))
4844 (plist-put info :table-cell-width-cache table)
4845 table)))
4846 (width-vector (or (gethash table cache)
4847 (puthash table (make-vector columns 'empty) cache)))
4848 (value (aref width-vector column)))
4849 (if (not (eq value 'empty)) value
4850 (let (cookie-width)
4851 (dolist (row (org-element-contents table)
4852 (aset width-vector column cookie-width))
4853 (when (org-export-table-row-is-special-p row info)
4854 ;; In a special row, try to find a width cookie at COLUMN.
4855 (let* ((value (org-element-contents
4856 (elt (org-element-contents row) column)))
4857 (cookie (car value)))
4858 ;; The following checks avoid expanding unnecessarily
4859 ;; the cell with `org-export-data'.
4860 (when (and value
4861 (not (cdr value))
4862 (stringp cookie)
4863 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'" cookie)
4864 (match-string 1 cookie))
4865 (setq cookie-width
4866 (string-to-number (match-string 1 cookie)))))))))))
4868 (defun org-export-table-cell-alignment (table-cell info)
4869 "Return TABLE-CELL contents alignment.
4871 INFO is a plist used as the communication channel.
4873 Return alignment as specified by the last alignment cookie in the
4874 same column as TABLE-CELL. If no such cookie is found, a default
4875 alignment value will be deduced from fraction of numbers in the
4876 column (see `org-table-number-fraction' for more information).
4877 Possible values are `left', `right' and `center'."
4878 ;; Load `org-table-number-fraction' and `org-table-number-regexp'.
4879 (require 'org-table)
4880 (let* ((row (org-export-get-parent table-cell))
4881 (table (org-export-get-parent row))
4882 (cells (org-element-contents row))
4883 (columns (length cells))
4884 (column (- columns (length (memq table-cell cells))))
4885 (cache (or (plist-get info :table-cell-alignment-cache)
4886 (let ((table (make-hash-table :test #'eq)))
4887 (plist-put info :table-cell-alignment-cache table)
4888 table)))
4889 (align-vector (or (gethash table cache)
4890 (puthash table (make-vector columns nil) cache))))
4891 (or (aref align-vector column)
4892 (let ((number-cells 0)
4893 (total-cells 0)
4894 cookie-align
4895 previous-cell-number-p)
4896 (dolist (row (org-element-contents (org-export-get-parent row)))
4897 (cond
4898 ;; In a special row, try to find an alignment cookie at
4899 ;; COLUMN.
4900 ((org-export-table-row-is-special-p row info)
4901 (let ((value (org-element-contents
4902 (elt (org-element-contents row) column))))
4903 ;; Since VALUE is a secondary string, the following
4904 ;; checks avoid useless expansion through
4905 ;; `org-export-data'.
4906 (when (and value
4907 (not (cdr value))
4908 (stringp (car value))
4909 (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'"
4910 (car value))
4911 (match-string 1 (car value)))
4912 (setq cookie-align (match-string 1 (car value))))))
4913 ;; Ignore table rules.
4914 ((eq (org-element-property :type row) 'rule))
4915 ;; In a standard row, check if cell's contents are
4916 ;; expressing some kind of number. Increase NUMBER-CELLS
4917 ;; accordingly. Though, don't bother if an alignment
4918 ;; cookie has already defined cell's alignment.
4919 ((not cookie-align)
4920 (let ((value (org-export-data
4921 (org-element-contents
4922 (elt (org-element-contents row) column))
4923 info)))
4924 (cl-incf total-cells)
4925 ;; Treat an empty cell as a number if it follows
4926 ;; a number.
4927 (if (not (or (string-match org-table-number-regexp value)
4928 (and (string= value "") previous-cell-number-p)))
4929 (setq previous-cell-number-p nil)
4930 (setq previous-cell-number-p t)
4931 (cl-incf number-cells))))))
4932 ;; Return value. Alignment specified by cookies has
4933 ;; precedence over alignment deduced from cell's contents.
4934 (aset align-vector
4935 column
4936 (cond ((equal cookie-align "l") 'left)
4937 ((equal cookie-align "r") 'right)
4938 ((equal cookie-align "c") 'center)
4939 ((>= (/ (float number-cells) total-cells)
4940 org-table-number-fraction)
4941 'right)
4942 (t 'left)))))))
4944 (defun org-export-table-cell-borders (table-cell info)
4945 "Return TABLE-CELL borders.
4947 INFO is a plist used as a communication channel.
4949 Return value is a list of symbols, or nil. Possible values are:
4950 `top', `bottom', `above', `below', `left' and `right'. Note:
4951 `top' (resp. `bottom') only happen for a cell in the first
4952 row (resp. last row) of the table, ignoring table rules, if any.
4954 Returned borders ignore special rows."
4955 (let* ((row (org-export-get-parent table-cell))
4956 (table (org-export-get-parent-table table-cell))
4957 borders)
4958 ;; Top/above border? TABLE-CELL has a border above when a rule
4959 ;; used to demarcate row groups can be found above. Hence,
4960 ;; finding a rule isn't sufficient to push `above' in BORDERS:
4961 ;; another regular row has to be found above that rule.
4962 (let (rule-flag)
4963 (catch 'exit
4964 ;; Look at every row before the current one.
4965 (dolist (row (cdr (memq row (reverse (org-element-contents table)))))
4966 (cond ((eq (org-element-property :type row) 'rule)
4967 (setq rule-flag t))
4968 ((not (org-export-table-row-is-special-p row info))
4969 (if rule-flag (throw 'exit (push 'above borders))
4970 (throw 'exit nil)))))
4971 ;; No rule above, or rule found starts the table (ignoring any
4972 ;; special row): TABLE-CELL is at the top of the table.
4973 (when rule-flag (push 'above borders))
4974 (push 'top borders)))
4975 ;; Bottom/below border? TABLE-CELL has a border below when next
4976 ;; non-regular row below is a rule.
4977 (let (rule-flag)
4978 (catch 'exit
4979 ;; Look at every row after the current one.
4980 (dolist (row (cdr (memq row (org-element-contents table))))
4981 (cond ((eq (org-element-property :type row) 'rule)
4982 (setq rule-flag t))
4983 ((not (org-export-table-row-is-special-p row info))
4984 (if rule-flag (throw 'exit (push 'below borders))
4985 (throw 'exit nil)))))
4986 ;; No rule below, or rule found ends the table (modulo some
4987 ;; special row): TABLE-CELL is at the bottom of the table.
4988 (when rule-flag (push 'below borders))
4989 (push 'bottom borders)))
4990 ;; Right/left borders? They can only be specified by column
4991 ;; groups. Column groups are defined in a row starting with "/".
4992 ;; Also a column groups row only contains "<", "<>", ">" or blank
4993 ;; cells.
4994 (catch 'exit
4995 (let ((column (let ((cells (org-element-contents row)))
4996 (- (length cells) (length (memq table-cell cells))))))
4997 ;; Table rows are read in reverse order so last column groups
4998 ;; row has precedence over any previous one.
4999 (dolist (row (reverse (org-element-contents table)))
5000 (unless (eq (org-element-property :type row) 'rule)
5001 (when (equal (org-element-contents
5002 (car (org-element-contents row)))
5003 '("/"))
5004 (let ((column-groups
5005 (mapcar
5006 (lambda (cell)
5007 (let ((value (org-element-contents cell)))
5008 (when (member value '(("<") ("<>") (">") nil))
5009 (car value))))
5010 (org-element-contents row))))
5011 ;; There's a left border when previous cell, if
5012 ;; any, ends a group, or current one starts one.
5013 (when (or (and (not (zerop column))
5014 (member (elt column-groups (1- column))
5015 '(">" "<>")))
5016 (member (elt column-groups column) '("<" "<>")))
5017 (push 'left borders))
5018 ;; There's a right border when next cell, if any,
5019 ;; starts a group, or current one ends one.
5020 (when (or (and (/= (1+ column) (length column-groups))
5021 (member (elt column-groups (1+ column))
5022 '("<" "<>")))
5023 (member (elt column-groups column) '(">" "<>")))
5024 (push 'right borders))
5025 (throw 'exit nil)))))))
5026 ;; Return value.
5027 borders))
5029 (defun org-export-table-cell-starts-colgroup-p (table-cell info)
5030 "Non-nil when TABLE-CELL is at the beginning of a column group.
5031 INFO is a plist used as a communication channel."
5032 ;; A cell starts a column group either when it is at the beginning
5033 ;; of a row (or after the special column, if any) or when it has
5034 ;; a left border.
5035 (or (eq (org-element-map (org-export-get-parent table-cell) 'table-cell
5036 'identity info 'first-match)
5037 table-cell)
5038 (memq 'left (org-export-table-cell-borders table-cell info))))
5040 (defun org-export-table-cell-ends-colgroup-p (table-cell info)
5041 "Non-nil when TABLE-CELL is at the end of a column group.
5042 INFO is a plist used as a communication channel."
5043 ;; A cell ends a column group either when it is at the end of a row
5044 ;; or when it has a right border.
5045 (or (eq (car (last (org-element-contents
5046 (org-export-get-parent table-cell))))
5047 table-cell)
5048 (memq 'right (org-export-table-cell-borders table-cell info))))
5050 (defun org-export-table-row-starts-rowgroup-p (table-row info)
5051 "Non-nil when TABLE-ROW is at the beginning of a row group.
5052 INFO is a plist used as a communication channel."
5053 (unless (or (eq (org-element-property :type table-row) 'rule)
5054 (org-export-table-row-is-special-p table-row info))
5055 (let ((borders (org-export-table-cell-borders
5056 (car (org-element-contents table-row)) info)))
5057 (or (memq 'top borders) (memq 'above borders)))))
5059 (defun org-export-table-row-ends-rowgroup-p (table-row info)
5060 "Non-nil when TABLE-ROW is at the end of a row group.
5061 INFO is a plist used as a communication channel."
5062 (unless (or (eq (org-element-property :type table-row) 'rule)
5063 (org-export-table-row-is-special-p table-row info))
5064 (let ((borders (org-export-table-cell-borders
5065 (car (org-element-contents table-row)) info)))
5066 (or (memq 'bottom borders) (memq 'below borders)))))
5068 (defun org-export-table-row-in-header-p (table-row info)
5069 "Non-nil when TABLE-ROW is located within table's header.
5070 INFO is a plist used as a communication channel. Always return
5071 nil for special rows and rows separators."
5072 (and (org-export-table-has-header-p
5073 (org-export-get-parent-table table-row) info)
5074 (eql (org-export-table-row-group table-row info) 1)))
5076 (defun org-export-table-row-starts-header-p (table-row info)
5077 "Non-nil when TABLE-ROW is the first table header's row.
5078 INFO is a plist used as a communication channel."
5079 (and (org-export-table-row-in-header-p table-row info)
5080 (org-export-table-row-starts-rowgroup-p table-row info)))
5082 (defun org-export-table-row-ends-header-p (table-row info)
5083 "Non-nil when TABLE-ROW is the last table header's row.
5084 INFO is a plist used as a communication channel."
5085 (and (org-export-table-row-in-header-p table-row info)
5086 (org-export-table-row-ends-rowgroup-p table-row info)))
5088 (defun org-export-table-row-number (table-row info)
5089 "Return TABLE-ROW number.
5090 INFO is a plist used as a communication channel. Return value is
5091 zero-indexed and ignores separators. The function returns nil
5092 for special rows and separators."
5093 (when (eq (org-element-property :type table-row) 'standard)
5094 (let* ((cache (or (plist-get info :table-row-number-cache)
5095 (let ((table (make-hash-table :test #'eq)))
5096 (plist-put info :table-row-number-cache table)
5097 table)))
5098 (cached (gethash table-row cache 'no-cache)))
5099 (if (not (eq cached 'no-cache)) cached
5100 ;; First time a row is queried, populate cache with all the
5101 ;; rows from the table.
5102 (let ((number -1))
5103 (org-element-map (org-export-get-parent-table table-row) 'table-row
5104 (lambda (row)
5105 (when (eq (org-element-property :type row) 'standard)
5106 (puthash row (cl-incf number) cache)))
5107 info))
5108 (gethash table-row cache)))))
5110 (defun org-export-table-dimensions (table info)
5111 "Return TABLE dimensions.
5113 INFO is a plist used as a communication channel.
5115 Return value is a CONS like (ROWS . COLUMNS) where
5116 ROWS (resp. COLUMNS) is the number of exportable
5117 rows (resp. columns)."
5118 (let (first-row (columns 0) (rows 0))
5119 ;; Set number of rows, and extract first one.
5120 (org-element-map table 'table-row
5121 (lambda (row)
5122 (when (eq (org-element-property :type row) 'standard)
5123 (cl-incf rows)
5124 (unless first-row (setq first-row row)))) info)
5125 ;; Set number of columns.
5126 (org-element-map first-row 'table-cell (lambda (_) (cl-incf columns)) info)
5127 ;; Return value.
5128 (cons rows columns)))
5130 (defun org-export-table-cell-address (table-cell info)
5131 "Return address of a regular TABLE-CELL object.
5133 TABLE-CELL is the cell considered. INFO is a plist used as
5134 a communication channel.
5136 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
5137 zero-based index. Only exportable cells are considered. The
5138 function returns nil for other cells."
5139 (let* ((table-row (org-export-get-parent table-cell))
5140 (row-number (org-export-table-row-number table-row info)))
5141 (when row-number
5142 (cons row-number
5143 (let ((col-count 0))
5144 (org-element-map table-row 'table-cell
5145 (lambda (cell)
5146 (if (eq cell table-cell) col-count (cl-incf col-count) nil))
5147 info 'first-match))))))
5149 (defun org-export-get-table-cell-at (address table info)
5150 "Return regular table-cell object at ADDRESS in TABLE.
5152 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
5153 zero-based index. TABLE is a table type element. INFO is
5154 a plist used as a communication channel.
5156 If no table-cell, among exportable cells, is found at ADDRESS,
5157 return nil."
5158 (let ((column-pos (cdr address)) (column-count 0))
5159 (org-element-map
5160 ;; Row at (car address) or nil.
5161 (let ((row-pos (car address)) (row-count 0))
5162 (org-element-map table 'table-row
5163 (lambda (row)
5164 (cond ((eq (org-element-property :type row) 'rule) nil)
5165 ((= row-count row-pos) row)
5166 (t (cl-incf row-count) nil)))
5167 info 'first-match))
5168 'table-cell
5169 (lambda (cell)
5170 (if (= column-count column-pos) cell
5171 (cl-incf column-count) nil))
5172 info 'first-match)))
5175 ;;;; For Tables of Contents
5177 ;; `org-export-collect-headlines' builds a list of all exportable
5178 ;; headline elements, maybe limited to a certain depth. One can then
5179 ;; easily parse it and transcode it.
5181 ;; Building lists of tables, figures or listings is quite similar.
5182 ;; Once the generic function `org-export-collect-elements' is defined,
5183 ;; `org-export-collect-tables', `org-export-collect-figures' and
5184 ;; `org-export-collect-listings' can be derived from it.
5186 ;; `org-export-toc-entry-backend' builds a special anonymous back-end
5187 ;; useful to export table of contents' entries.
5189 (defun org-export-collect-headlines (info &optional n scope)
5190 "Collect headlines in order to build a table of contents.
5192 INFO is a plist used as a communication channel.
5194 When optional argument N is an integer, it specifies the depth of
5195 the table of contents. Otherwise, it is set to the value of the
5196 last headline level. See `org-export-headline-levels' for more
5197 information.
5199 Optional argument SCOPE, when non-nil, is an element. If it is
5200 a headline, only children of SCOPE are collected. Otherwise,
5201 collect children of the headline containing provided element. If
5202 there is no such headline, collect all headlines. In any case,
5203 argument N becomes relative to the level of that headline.
5205 Return a list of all exportable headlines as parsed elements.
5206 Footnote sections are ignored."
5207 (let* ((scope (cond ((not scope) (plist-get info :parse-tree))
5208 ((eq (org-element-type scope) 'headline) scope)
5209 ((org-export-get-parent-headline scope))
5210 (t (plist-get info :parse-tree))))
5211 (limit (plist-get info :headline-levels))
5212 (n (if (not (wholenump n)) limit
5213 (min (if (eq (org-element-type scope) 'org-data) n
5214 (+ (org-export-get-relative-level scope info) n))
5215 limit))))
5216 (org-element-map (org-element-contents scope) 'headline
5217 (lambda (h)
5218 (and (not (org-element-property :footnote-section-p h))
5219 (not (equal "notoc"
5220 (org-export-get-node-property :UNNUMBERED h t)))
5221 (>= n (org-export-get-relative-level h info))
5223 info)))
5225 (defun org-export-collect-elements (type info &optional predicate)
5226 "Collect referenceable elements of a determined type.
5228 TYPE can be a symbol or a list of symbols specifying element
5229 types to search. Only elements with a caption are collected.
5231 INFO is a plist used as a communication channel.
5233 When non-nil, optional argument PREDICATE is a function accepting
5234 one argument, an element of type TYPE. It returns a non-nil
5235 value when that element should be collected.
5237 Return a list of all elements found, in order of appearance."
5238 (org-element-map (plist-get info :parse-tree) type
5239 (lambda (element)
5240 (and (org-element-property :caption element)
5241 (or (not predicate) (funcall predicate element))
5242 element))
5243 info))
5245 (defun org-export-collect-tables (info)
5246 "Build a list of tables.
5247 INFO is a plist used as a communication channel.
5249 Return a list of table elements with a caption."
5250 (org-export-collect-elements 'table info))
5252 (defun org-export-collect-figures (info predicate)
5253 "Build a list of figures.
5255 INFO is a plist used as a communication channel. PREDICATE is
5256 a function which accepts one argument: a paragraph element and
5257 whose return value is non-nil when that element should be
5258 collected.
5260 A figure is a paragraph type element, with a caption, verifying
5261 PREDICATE. The latter has to be provided since a \"figure\" is
5262 a vague concept that may depend on back-end.
5264 Return a list of elements recognized as figures."
5265 (org-export-collect-elements 'paragraph info predicate))
5267 (defun org-export-collect-listings (info)
5268 "Build a list of src blocks.
5270 INFO is a plist used as a communication channel.
5272 Return a list of src-block elements with a caption."
5273 (org-export-collect-elements 'src-block info))
5275 (defun org-export-excluded-from-toc-p (headline info)
5276 "Non-nil if HEADLINE should be excluded from tables of contents.
5278 INFO is a plist used as a communication channel.
5280 Note that such headlines are already excluded from
5281 `org-export-collect-headlines'. Therefore, this function is not
5282 necessary if you only need to list headlines in the table of
5283 contents. However, it is useful if some additional processing is
5284 required on headlines excluded from table of contents."
5285 (or (org-element-property :footnote-section-p headline)
5286 (org-export-low-level-p headline info)
5287 (equal "notoc" (org-export-get-node-property :UNNUMBERED headline t))))
5289 (defun org-export-toc-entry-backend (parent &rest transcoders)
5290 "Return an export back-end appropriate for table of contents entries.
5292 PARENT is an export back-end the returned back-end should inherit
5293 from.
5295 By default, the back-end removes footnote references and targets.
5296 It also changes links and radio targets into regular text.
5297 TRANSCODERS optional argument, when non-nil, specifies additional
5298 transcoders. A transcoder follows the pattern (TYPE . FUNCTION)
5299 where type is an element or object type and FUNCTION the function
5300 transcoding it."
5301 (declare (indent 1))
5302 (org-export-create-backend
5303 :parent parent
5304 :transcoders
5305 (append transcoders
5306 `((footnote-reference . ,#'ignore)
5307 (link . ,(lambda (l c i)
5308 (or c
5309 (org-export-data
5310 (org-element-property :raw-link l)
5311 i))))
5312 (radio-target . ,(lambda (_r c _) c))
5313 (target . ,#'ignore)))))
5316 ;;;; Smart Quotes
5318 ;; The main function for the smart quotes sub-system is
5319 ;; `org-export-activate-smart-quotes', which replaces every quote in
5320 ;; a given string from the parse tree with its "smart" counterpart.
5322 ;; Dictionary for smart quotes is stored in
5323 ;; `org-export-smart-quotes-alist'.
5325 (defconst org-export-smart-quotes-alist
5326 '(("ar"
5327 (primary-opening
5328 :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5329 :texinfo "@guillemetleft{}")
5330 (primary-closing
5331 :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5332 :texinfo "@guillemetright{}")
5333 (secondary-opening :utf-8 "‹" :html "&lsaquo;" :latex "\\guilsinglleft{}"
5334 :texinfo "@guilsinglleft{}")
5335 (secondary-closing :utf-8 "›" :html "&rsaquo;" :latex "\\guilsinglright{}"
5336 :texinfo "@guilsinglright{}")
5337 (apostrophe :utf-8 "’" :html "&rsquo;"))
5338 ("da"
5339 ;; one may use: »...«, "...", ›...‹, or '...'.
5340 ;; http://sproget.dk/raad-og-regler/retskrivningsregler/retskrivningsregler/a7-40-60/a7-58-anforselstegn/
5341 ;; LaTeX quotes require Babel!
5342 (primary-opening
5343 :utf-8 "»" :html "&raquo;" :latex ">>" :texinfo "@guillemetright{}")
5344 (primary-closing
5345 :utf-8 "«" :html "&laquo;" :latex "<<" :texinfo "@guillemetleft{}")
5346 (secondary-opening
5347 :utf-8 "›" :html "&rsaquo;" :latex "\\frq{}" :texinfo "@guilsinglright{}")
5348 (secondary-closing
5349 :utf-8 "‹" :html "&lsaquo;" :latex "\\flq{}" :texinfo "@guilsingleft{}")
5350 (apostrophe :utf-8 "’" :html "&rsquo;"))
5351 ("de"
5352 (primary-opening
5353 :utf-8 "„" :html "&bdquo;" :latex "\"`" :texinfo "@quotedblbase{}")
5354 (primary-closing
5355 :utf-8 "“" :html "&ldquo;" :latex "\"'" :texinfo "@quotedblleft{}")
5356 (secondary-opening
5357 :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}" :texinfo "@quotesinglbase{}")
5358 (secondary-closing
5359 :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}" :texinfo "@quoteleft{}")
5360 (apostrophe :utf-8 "’" :html "&rsquo;"))
5361 ("en"
5362 (primary-opening :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
5363 (primary-closing :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
5364 (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5365 (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5366 (apostrophe :utf-8 "’" :html "&rsquo;"))
5367 ("es"
5368 (primary-opening
5369 :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5370 :texinfo "@guillemetleft{}")
5371 (primary-closing
5372 :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5373 :texinfo "@guillemetright{}")
5374 (secondary-opening :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
5375 (secondary-closing :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
5376 (apostrophe :utf-8 "’" :html "&rsquo;"))
5377 ("fr"
5378 (primary-opening
5379 :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
5380 :texinfo "@guillemetleft{}@tie{}")
5381 (primary-closing
5382 :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
5383 :texinfo "@tie{}@guillemetright{}")
5384 (secondary-opening
5385 :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
5386 :texinfo "@guillemetleft{}@tie{}")
5387 (secondary-closing :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
5388 :texinfo "@tie{}@guillemetright{}")
5389 (apostrophe :utf-8 "’" :html "&rsquo;"))
5390 ("is"
5391 (primary-opening
5392 :utf-8 "„" :html "&bdquo;" :latex "\"`" :texinfo "@quotedblbase{}")
5393 (primary-closing
5394 :utf-8 "“" :html "&ldquo;" :latex "\"'" :texinfo "@quotedblleft{}")
5395 (secondary-opening
5396 :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}" :texinfo "@quotesinglbase{}")
5397 (secondary-closing
5398 :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}" :texinfo "@quoteleft{}")
5399 (apostrophe :utf-8 "’" :html "&rsquo;"))
5400 ("no"
5401 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5402 (primary-opening
5403 :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5404 :texinfo "@guillemetleft{}")
5405 (primary-closing
5406 :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5407 :texinfo "@guillemetright{}")
5408 (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5409 (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5410 (apostrophe :utf-8 "’" :html "&rsquo;"))
5411 ("nb"
5412 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5413 (primary-opening
5414 :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5415 :texinfo "@guillemetleft{}")
5416 (primary-closing
5417 :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5418 :texinfo "@guillemetright{}")
5419 (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5420 (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5421 (apostrophe :utf-8 "’" :html "&rsquo;"))
5422 ("nn"
5423 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5424 (primary-opening
5425 :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5426 :texinfo "@guillemetleft{}")
5427 (primary-closing
5428 :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5429 :texinfo "@guillemetright{}")
5430 (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5431 (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5432 (apostrophe :utf-8 "’" :html "&rsquo;"))
5433 ("ru"
5434 ;; 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
5435 ;; http://www.artlebedev.ru/kovodstvo/sections/104/
5436 (primary-opening :utf-8 "«" :html "&laquo;" :latex "{}<<"
5437 :texinfo "@guillemetleft{}")
5438 (primary-closing :utf-8 "»" :html "&raquo;" :latex ">>{}"
5439 :texinfo "@guillemetright{}")
5440 (secondary-opening
5441 :utf-8 "„" :html "&bdquo;" :latex "\\glqq{}" :texinfo "@quotedblbase{}")
5442 (secondary-closing
5443 :utf-8 "“" :html "&ldquo;" :latex "\\grqq{}" :texinfo "@quotedblleft{}")
5444 (apostrophe :utf-8 "’" :html: "&#39;"))
5445 ("sl"
5446 ;; Based on https://sl.wikipedia.org/wiki/Narekovaj
5447 (primary-opening :utf-8 "«" :html "&laquo;" :latex "{}<<"
5448 :texinfo "@guillemetleft{}")
5449 (primary-closing :utf-8 "»" :html "&raquo;" :latex ">>{}"
5450 :texinfo "@guillemetright{}")
5451 (secondary-opening
5452 :utf-8 "„" :html "&bdquo;" :latex "\\glqq{}" :texinfo "@quotedblbase{}")
5453 (secondary-closing
5454 :utf-8 "“" :html "&ldquo;" :latex "\\grqq{}" :texinfo "@quotedblleft{}")
5455 (apostrophe :utf-8 "’" :html "&rsquo;"))
5456 ("sv"
5457 ;; Based on https://sv.wikipedia.org/wiki/Citattecken
5458 (primary-opening :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
5459 (primary-closing :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
5460 (secondary-opening :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "`")
5461 (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "'")
5462 (apostrophe :utf-8 "’" :html "&rsquo;")))
5463 "Smart quotes translations.
5465 Alist whose CAR is a language string and CDR is an alist with
5466 quote type as key and a plist associating various encodings to
5467 their translation as value.
5469 A quote type can be any symbol among `primary-opening',
5470 `primary-closing', `secondary-opening', `secondary-closing' and
5471 `apostrophe'.
5473 Valid encodings include `:utf-8', `:html', `:latex' and
5474 `:texinfo'.
5476 If no translation is found, the quote character is left as-is.")
5478 (defun org-export--smart-quote-status (s info)
5479 "Return smart quote status at the beginning of string S.
5480 INFO is the current export state, as a plist."
5481 (let* ((parent (org-element-property :parent s))
5482 (cache (or (plist-get info :smart-quote-cache)
5483 (let ((table (make-hash-table :test #'eq)))
5484 (plist-put info :smart-quote-cache table)
5485 table)))
5486 (value (gethash parent cache 'missing-data)))
5487 (if (not (eq value 'missing-data)) (cdr (assq s value))
5488 (let (level1-open full-status)
5489 (org-element-map
5490 (let ((secondary (org-element-secondary-p s)))
5491 (if secondary (org-element-property secondary parent)
5492 (org-element-contents parent)))
5493 'plain-text
5494 (lambda (text)
5495 (let ((start 0) current-status)
5496 (while (setq start (string-match "['\"]" text start))
5497 (push
5498 (cond
5499 ((equal (match-string 0 text) "\"")
5500 (setf level1-open (not level1-open))
5501 (if level1-open 'primary-opening 'primary-closing))
5502 ;; Not already in a level 1 quote: this is an
5503 ;; apostrophe.
5504 ((not level1-open) 'apostrophe)
5505 ;; Extract previous char and next char. As
5506 ;; a special case, they can also be set to `blank',
5507 ;; `no-blank' or nil. Then determine if current
5508 ;; match is allowed as an opening quote or a closing
5509 ;; quote.
5511 (let* ((previous
5512 (if (> start 0) (substring text (1- start) start)
5513 (let ((p (org-export-get-previous-element
5514 text info)))
5515 (cond ((not p) nil)
5516 ((stringp p) (substring p -1))
5517 ((memq (org-element-property :post-blank p)
5518 '(0 nil))
5519 'no-blank)
5520 (t 'blank)))))
5521 (next
5522 (if (< (1+ start) (length text))
5523 (substring text (1+ start) (+ start 2))
5524 (let ((n (org-export-get-next-element text info)))
5525 (cond ((not n) nil)
5526 ((stringp n) (substring n 0 1))
5527 (t 'no-blank)))))
5528 (allow-open
5529 (and (if (stringp previous)
5530 (string-match "\\s\"\\|\\s-\\|\\s("
5531 previous)
5532 (memq previous '(blank nil)))
5533 (if (stringp next)
5534 (string-match "\\w\\|\\s.\\|\\s_" next)
5535 (eq next 'no-blank))))
5536 (allow-close
5537 (and (if (stringp previous)
5538 (string-match "\\w\\|\\s.\\|\\s_" previous)
5539 (eq previous 'no-blank))
5540 (if (stringp next)
5541 (string-match "\\s-\\|\\s)\\|\\s.\\|\\s\""
5542 next)
5543 (memq next '(blank nil))))))
5544 (cond
5545 ((and allow-open allow-close) (error "Should not happen"))
5546 (allow-open 'secondary-opening)
5547 (allow-close 'secondary-closing)
5548 (t 'apostrophe)))))
5549 current-status)
5550 (cl-incf start))
5551 (when current-status
5552 (push (cons text (nreverse current-status)) full-status))))
5553 info nil org-element-recursive-objects)
5554 (puthash parent full-status cache)
5555 (cdr (assq s full-status))))))
5557 (defun org-export-activate-smart-quotes (s encoding info &optional original)
5558 "Replace regular quotes with \"smart\" quotes in string S.
5560 ENCODING is a symbol among `:html', `:latex', `:texinfo' and
5561 `:utf-8'. INFO is a plist used as a communication channel.
5563 The function has to retrieve information about string
5564 surroundings in parse tree. It can only happen with an
5565 unmodified string. Thus, if S has already been through another
5566 process, a non-nil ORIGINAL optional argument will provide that
5567 original string.
5569 Return the new string."
5570 (let ((quote-status
5571 (copy-sequence (org-export--smart-quote-status (or original s) info))))
5572 (replace-regexp-in-string
5573 "['\"]"
5574 (lambda (match)
5575 (or (plist-get
5576 (cdr (assq (pop quote-status)
5577 (cdr (assoc (plist-get info :language)
5578 org-export-smart-quotes-alist))))
5579 encoding)
5580 match))
5581 s nil t)))
5583 ;;;; Topology
5585 ;; Here are various functions to retrieve information about the
5586 ;; neighborhood of a given element or object. Neighbors of interest
5587 ;; are direct parent (`org-export-get-parent'), parent headline
5588 ;; (`org-export-get-parent-headline'), first element containing an
5589 ;; object, (`org-export-get-parent-element'), parent table
5590 ;; (`org-export-get-parent-table'), previous element or object
5591 ;; (`org-export-get-previous-element') and next element or object
5592 ;; (`org-export-get-next-element').
5594 ;; defsubst org-export-get-parent must be defined before first use
5596 (defun org-export-get-parent-headline (blob)
5597 "Return BLOB parent headline or nil.
5598 BLOB is the element or object being considered."
5599 (org-element-lineage blob '(headline)))
5601 (defun org-export-get-parent-element (object)
5602 "Return first element containing OBJECT or nil.
5603 OBJECT is the object to consider."
5604 (org-element-lineage object org-element-all-elements))
5606 (defun org-export-get-parent-table (object)
5607 "Return OBJECT parent table or nil.
5608 OBJECT is either a `table-cell' or `table-element' type object."
5609 (org-element-lineage object '(table)))
5611 (defun org-export-get-previous-element (blob info &optional n)
5612 "Return previous element or object.
5614 BLOB is an element or object. INFO is a plist used as
5615 a communication channel. Return previous exportable element or
5616 object, a string, or nil.
5618 When optional argument N is a positive integer, return a list
5619 containing up to N siblings before BLOB, from farthest to
5620 closest. With any other non-nil value, return a list containing
5621 all of them."
5622 (let* ((secondary (org-element-secondary-p blob))
5623 (parent (org-export-get-parent blob))
5624 (siblings
5625 (if secondary (org-element-property secondary parent)
5626 (org-element-contents parent)))
5627 prev)
5628 (catch 'exit
5629 (dolist (obj (cdr (memq blob (reverse siblings))) prev)
5630 (cond ((memq obj (plist-get info :ignore-list)))
5631 ((null n) (throw 'exit obj))
5632 ((not (wholenump n)) (push obj prev))
5633 ((zerop n) (throw 'exit prev))
5634 (t (cl-decf n) (push obj prev)))))))
5636 (defun org-export-get-next-element (blob info &optional n)
5637 "Return next element or object.
5639 BLOB is an element or object. INFO is a plist used as
5640 a communication channel. Return next exportable element or
5641 object, a string, or nil.
5643 When optional argument N is a positive integer, return a list
5644 containing up to N siblings after BLOB, from closest to farthest.
5645 With any other non-nil value, return a list containing all of
5646 them."
5647 (let* ((secondary (org-element-secondary-p blob))
5648 (parent (org-export-get-parent blob))
5649 (siblings
5650 (cdr (memq blob
5651 (if secondary (org-element-property secondary parent)
5652 (org-element-contents parent)))))
5653 next)
5654 (catch 'exit
5655 (dolist (obj siblings (nreverse next))
5656 (cond ((memq obj (plist-get info :ignore-list)))
5657 ((null n) (throw 'exit obj))
5658 ((not (wholenump n)) (push obj next))
5659 ((zerop n) (throw 'exit (nreverse next)))
5660 (t (cl-decf n) (push obj next)))))))
5663 ;;;; Translation
5665 ;; `org-export-translate' translates a string according to the language
5666 ;; specified by the LANGUAGE keyword. `org-export-dictionary' contains
5667 ;; the dictionary used for the translation.
5669 (defconst org-export-dictionary
5670 '(("%e %n: %c"
5671 ("fr" :default "%e %n : %c" :html "%e&nbsp;%n&nbsp;: %c"))
5672 ("Author"
5673 ("ar" :default "تأليف")
5674 ("ca" :default "Autor")
5675 ("cs" :default "Autor")
5676 ("da" :default "Forfatter")
5677 ("de" :default "Autor")
5678 ("eo" :html "A&#365;toro")
5679 ("es" :default "Autor")
5680 ("et" :default "Autor")
5681 ("fi" :html "Tekij&auml;")
5682 ("fr" :default "Auteur")
5683 ("hu" :default "Szerz&otilde;")
5684 ("is" :html "H&ouml;fundur")
5685 ("it" :default "Autore")
5686 ("ja" :default "著者" :html "&#33879;&#32773;")
5687 ("nl" :default "Auteur")
5688 ("no" :default "Forfatter")
5689 ("nb" :default "Forfatter")
5690 ("nn" :default "Forfattar")
5691 ("pl" :default "Autor")
5692 ("pt_BR" :default "Autor")
5693 ("ru" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5694 ("sl" :default "Avtor")
5695 ("sv" :html "F&ouml;rfattare")
5696 ("uk" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5697 ("zh-CN" :html "&#20316;&#32773;" :utf-8 "作者")
5698 ("zh-TW" :html "&#20316;&#32773;" :utf-8 "作者"))
5699 ("Continued from previous page"
5700 ("ar" :default "تتمة الصفحة السابقة")
5701 ("cs" :default "Pokračování z předchozí strany")
5702 ("de" :default "Fortsetzung von vorheriger Seite")
5703 ("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")
5704 ("fr" :default "Suite de la page précédente")
5705 ("it" :default "Continua da pagina precedente")
5706 ("ja" :default "前ページからの続き")
5707 ("nl" :default "Vervolg van vorige pagina")
5708 ("pt" :default "Continuação da página anterior")
5709 ("ru" :html "(&#1055;&#1088;&#1086;&#1076;&#1086;&#1083;&#1078;&#1077;&#1085;&#1080;&#1077;)"
5710 :utf-8 "(Продолжение)")
5711 ("sl" :default "Nadaljevanje s prejšnje strani"))
5712 ("Continued on next page"
5713 ("ar" :default "التتمة في الصفحة التالية")
5714 ("cs" :default "Pokračuje na další stránce")
5715 ("de" :default "Fortsetzung nächste Seite")
5716 ("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")
5717 ("fr" :default "Suite page suivante")
5718 ("it" :default "Continua alla pagina successiva")
5719 ("ja" :default "次ページに続く")
5720 ("nl" :default "Vervolg op volgende pagina")
5721 ("pt" :default "Continua na página seguinte")
5722 ("ru" :html "(&#1055;&#1088;&#1086;&#1076;&#1086;&#1083;&#1078;&#1077;&#1085;&#1080;&#1077; &#1089;&#1083;&#1077;&#1076;&#1091;&#1077;&#1090;)"
5723 :utf-8 "(Продолжение следует)")
5724 ("sl" :default "Nadaljevanje na naslednji strani"))
5725 ("Created"
5726 ("cs" :default "Vytvořeno")
5727 ("sl" :default "Ustvarjeno"))
5728 ("Date"
5729 ("ar" :default "بتاريخ")
5730 ("ca" :default "Data")
5731 ("cs" :default "Datum")
5732 ("da" :default "Dato")
5733 ("de" :default "Datum")
5734 ("eo" :default "Dato")
5735 ("es" :default "Fecha")
5736 ("et" :html "Kuup&#228;ev" :utf-8 "Kuupäev")
5737 ("fi" :html "P&auml;iv&auml;m&auml;&auml;r&auml;")
5738 ("hu" :html "D&aacute;tum")
5739 ("is" :default "Dagsetning")
5740 ("it" :default "Data")
5741 ("ja" :default "日付" :html "&#26085;&#20184;")
5742 ("nl" :default "Datum")
5743 ("no" :default "Dato")
5744 ("nb" :default "Dato")
5745 ("nn" :default "Dato")
5746 ("pl" :default "Data")
5747 ("pt_BR" :default "Data")
5748 ("ru" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5749 ("sl" :default "Datum")
5750 ("sv" :default "Datum")
5751 ("uk" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5752 ("zh-CN" :html "&#26085;&#26399;" :utf-8 "日期")
5753 ("zh-TW" :html "&#26085;&#26399;" :utf-8 "日期"))
5754 ("Equation"
5755 ("ar" :default "معادلة")
5756 ("cs" :default "Rovnice")
5757 ("da" :default "Ligning")
5758 ("de" :default "Gleichung")
5759 ("es" :ascii "Ecuacion" :html "Ecuaci&oacute;n" :default "Ecuación")
5760 ("et" :html "V&#245;rrand" :utf-8 "Võrrand")
5761 ("fr" :ascii "Equation" :default "Équation")
5762 ("is" :default "Jafna")
5763 ("ja" :default "方程式")
5764 ("no" :default "Ligning")
5765 ("nb" :default "Ligning")
5766 ("nn" :default "Likning")
5767 ("pt_BR" :html "Equa&ccedil;&atilde;o" :default "Equação" :ascii "Equacao")
5768 ("ru" :html "&#1059;&#1088;&#1072;&#1074;&#1085;&#1077;&#1085;&#1080;&#1077;"
5769 :utf-8 "Уравнение")
5770 ("sl" :default "Enačba")
5771 ("sv" :default "Ekvation")
5772 ("zh-CN" :html "&#26041;&#31243;" :utf-8 "方程"))
5773 ("Figure"
5774 ("ar" :default "شكل")
5775 ("cs" :default "Obrázek")
5776 ("da" :default "Figur")
5777 ("de" :default "Abbildung")
5778 ("es" :default "Figura")
5779 ("et" :default "Joonis")
5780 ("is" :default "Mynd")
5781 ("ja" :default "図" :html "&#22259;")
5782 ("no" :default "Illustrasjon")
5783 ("nb" :default "Illustrasjon")
5784 ("nn" :default "Illustrasjon")
5785 ("pt_BR" :default "Figura")
5786 ("ru" :html "&#1056;&#1080;&#1089;&#1091;&#1085;&#1086;&#1082;" :utf-8 "Рисунок")
5787 ("sv" :default "Illustration")
5788 ("zh-CN" :html "&#22270;" :utf-8 "图"))
5789 ("Figure %d:"
5790 ("ar" :default "شكل %d:")
5791 ("cs" :default "Obrázek %d:")
5792 ("da" :default "Figur %d")
5793 ("de" :default "Abbildung %d:")
5794 ("es" :default "Figura %d:")
5795 ("et" :default "Joonis %d:")
5796 ("fr" :default "Figure %d :" :html "Figure&nbsp;%d&nbsp;:")
5797 ("is" :default "Mynd %d")
5798 ("ja" :default "図%d: " :html "&#22259;%d: ")
5799 ("no" :default "Illustrasjon %d")
5800 ("nb" :default "Illustrasjon %d")
5801 ("nn" :default "Illustrasjon %d")
5802 ("pt_BR" :default "Figura %d:")
5803 ("ru" :html "&#1056;&#1080;&#1089;. %d.:" :utf-8 "Рис. %d.:")
5804 ("sl" :default "Slika %d")
5805 ("sv" :default "Illustration %d")
5806 ("zh-CN" :html "&#22270;%d&nbsp;" :utf-8 "图%d "))
5807 ("Footnotes"
5808 ("ar" :default "الهوامش")
5809 ("ca" :html "Peus de p&agrave;gina")
5810 ("cs" :default "Poznámky pod čarou")
5811 ("da" :default "Fodnoter")
5812 ("de" :html "Fu&szlig;noten" :default "Fußnoten")
5813 ("eo" :default "Piednotoj")
5814 ("es" :ascii "Nota al pie de pagina" :html "Nota al pie de p&aacute;gina" :default "Nota al pie de página")
5815 ("et" :html "Allm&#228;rkused" :utf-8 "Allmärkused")
5816 ("fi" :default "Alaviitteet")
5817 ("fr" :default "Notes de bas de page")
5818 ("hu" :html "L&aacute;bjegyzet")
5819 ("is" :html "Aftanm&aacute;lsgreinar")
5820 ("it" :html "Note a pi&egrave; di pagina")
5821 ("ja" :default "脚注" :html "&#33050;&#27880;")
5822 ("nl" :default "Voetnoten")
5823 ("no" :default "Fotnoter")
5824 ("nb" :default "Fotnoter")
5825 ("nn" :default "Fotnotar")
5826 ("pl" :default "Przypis")
5827 ("pt_BR" :html "Notas de Rodap&eacute;" :default "Notas de Rodapé" :ascii "Notas de Rodape")
5828 ("ru" :html "&#1057;&#1085;&#1086;&#1089;&#1082;&#1080;" :utf-8 "Сноски")
5829 ("sl" :default "Opombe")
5830 ("sv" :default "Fotnoter")
5831 ("uk" :html "&#1055;&#1088;&#1080;&#1084;&#1110;&#1090;&#1082;&#1080;"
5832 :utf-8 "Примітки")
5833 ("zh-CN" :html "&#33050;&#27880;" :utf-8 "脚注")
5834 ("zh-TW" :html "&#33139;&#35387;" :utf-8 "腳註"))
5835 ("List of Listings"
5836 ("ar" :default "قائمة بالبرامج")
5837 ("cs" :default "Seznam programů")
5838 ("da" :default "Programmer")
5839 ("de" :default "Programmauflistungsverzeichnis")
5840 ("es" :ascii "Indice de Listados de programas" :html "&Iacute;ndice de Listados de programas" :default "Índice de Listados de programas")
5841 ("et" :default "Loendite nimekiri")
5842 ("fr" :default "Liste des programmes")
5843 ("ja" :default "ソースコード目次")
5844 ("no" :default "Dataprogrammer")
5845 ("nb" :default "Dataprogrammer")
5846 ("ru" :html "&#1057;&#1087;&#1080;&#1089;&#1086;&#1082; &#1088;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1086;&#1082;"
5847 :utf-8 "Список распечаток")
5848 ("sl" :default "Seznam programskih izpisov")
5849 ("zh-CN" :html "&#20195;&#30721;&#30446;&#24405;" :utf-8 "代码目录"))
5850 ("List of Tables"
5851 ("ar" :default "قائمة بالجداول")
5852 ("cs" :default "Seznam tabulek")
5853 ("da" :default "Tabeller")
5854 ("de" :default "Tabellenverzeichnis")
5855 ("es" :ascii "Indice de tablas" :html "&Iacute;ndice de tablas" :default "Índice de tablas")
5856 ("et" :default "Tabelite nimekiri")
5857 ("fr" :default "Liste des tableaux")
5858 ("is" :default "Töfluskrá" :html "T&ouml;fluskr&aacute;")
5859 ("ja" :default "表目次")
5860 ("no" :default "Tabeller")
5861 ("nb" :default "Tabeller")
5862 ("nn" :default "Tabeller")
5863 ("pt_BR" :default "Índice de Tabelas" :ascii "Indice de Tabelas")
5864 ("ru" :html "&#1057;&#1087;&#1080;&#1089;&#1086;&#1082; &#1090;&#1072;&#1073;&#1083;&#1080;&#1094;"
5865 :utf-8 "Список таблиц")
5866 ("sl" :default "Seznam tabel")
5867 ("sv" :default "Tabeller")
5868 ("zh-CN" :html "&#34920;&#26684;&#30446;&#24405;" :utf-8 "表格目录"))
5869 ("Listing"
5870 ("ar" :default "برنامج")
5871 ("cs" :default "Program")
5872 ("da" :default "Program")
5873 ("de" :default "Programmlisting")
5874 ("es" :default "Listado de programa")
5875 ("et" :default "Loend")
5876 ("fr" :default "Programme" :html "Programme")
5877 ("ja" :default "ソースコード")
5878 ("no" :default "Dataprogram")
5879 ("nb" :default "Dataprogram")
5880 ("pt_BR" :default "Listagem")
5881 ("ru" :html "&#1056;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1082;&#1072;"
5882 :utf-8 "Распечатка")
5883 ("sl" :default "Izpis programa")
5884 ("zh-CN" :html "&#20195;&#30721;" :utf-8 "代码"))
5885 ("Listing %d:"
5886 ("ar" :default "برنامج %d:")
5887 ("cs" :default "Program %d:")
5888 ("da" :default "Program %d")
5889 ("de" :default "Programmlisting %d")
5890 ("es" :default "Listado de programa %d")
5891 ("et" :default "Loend %d")
5892 ("fr" :default "Programme %d :" :html "Programme&nbsp;%d&nbsp;:")
5893 ("ja" :default "ソースコード%d:")
5894 ("no" :default "Dataprogram %d")
5895 ("nb" :default "Dataprogram %d")
5896 ("pt_BR" :default "Listagem %d")
5897 ("ru" :html "&#1056;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1082;&#1072; %d.:"
5898 :utf-8 "Распечатка %d.:")
5899 ("sl" :default "Izpis programa %d")
5900 ("zh-CN" :html "&#20195;&#30721;%d&nbsp;" :utf-8 "代码%d "))
5901 ("References"
5902 ("ar" :default "المراجع")
5903 ("cs" :default "Reference")
5904 ("fr" :ascii "References" :default "Références")
5905 ("de" :default "Quellen")
5906 ("es" :default "Referencias")
5907 ("sl" :default "Reference"))
5908 ("See figure %s"
5909 ("cs" :default "Viz obrázek %s")
5910 ("fr" :default "cf. figure %s"
5911 :html "cf.&nbsp;figure&nbsp;%s" :latex "cf.~figure~%s")
5912 ("sl" :default "Glej sliko %s"))
5913 ("See listing %s"
5914 ("cs" :default "Viz program %s")
5915 ("fr" :default "cf. programme %s"
5916 :html "cf.&nbsp;programme&nbsp;%s" :latex "cf.~programme~%s")
5917 ("sl" :default "Glej izpis programa %s"))
5918 ("See section %s"
5919 ("ar" :default "انظر قسم %s")
5920 ("cs" :default "Viz sekce %s")
5921 ("da" :default "jævnfør afsnit %s")
5922 ("de" :default "siehe Abschnitt %s")
5923 ("es" :ascii "Vea seccion %s" :html "Vea secci&oacute;n %s" :default "Vea sección %s")
5924 ("et" :html "Vaata peat&#252;kki %s" :utf-8 "Vaata peatükki %s")
5925 ("fr" :default "cf. section %s")
5926 ("ja" :default "セクション %s を参照")
5927 ("pt_BR" :html "Veja a se&ccedil;&atilde;o %s" :default "Veja a seção %s"
5928 :ascii "Veja a secao %s")
5929 ("ru" :html "&#1057;&#1084;. &#1088;&#1072;&#1079;&#1076;&#1077;&#1083; %s"
5930 :utf-8 "См. раздел %s")
5931 ("sl" :default "Glej poglavje %d")
5932 ("zh-CN" :html "&#21442;&#35265;&#31532;%s&#33410;" :utf-8 "参见第%s节"))
5933 ("See table %s"
5934 ("cs" :default "Viz tabulka %s")
5935 ("fr" :default "cf. tableau %s"
5936 :html "cf.&nbsp;tableau&nbsp;%s" :latex "cf.~tableau~%s")
5937 ("sl" :default "Glej tabelo %s"))
5938 ("Table"
5939 ("ar" :default "جدول")
5940 ("cs" :default "Tabulka")
5941 ("de" :default "Tabelle")
5942 ("es" :default "Tabla")
5943 ("et" :default "Tabel")
5944 ("fr" :default "Tableau")
5945 ("is" :default "Tafla")
5946 ("ja" :default "表" :html "&#34920;")
5947 ("pt_BR" :default "Tabela")
5948 ("ru" :html "&#1058;&#1072;&#1073;&#1083;&#1080;&#1094;&#1072;"
5949 :utf-8 "Таблица")
5950 ("zh-CN" :html "&#34920;" :utf-8 "表"))
5951 ("Table %d:"
5952 ("ar" :default "جدول %d:")
5953 ("cs" :default "Tabulka %d:")
5954 ("da" :default "Tabel %d")
5955 ("de" :default "Tabelle %d")
5956 ("es" :default "Tabla %d")
5957 ("et" :default "Tabel %d")
5958 ("fr" :default "Tableau %d :")
5959 ("is" :default "Tafla %d")
5960 ("ja" :default "表%d:" :html "&#34920;%d:")
5961 ("no" :default "Tabell %d")
5962 ("nb" :default "Tabell %d")
5963 ("nn" :default "Tabell %d")
5964 ("pt_BR" :default "Tabela %d")
5965 ("ru" :html "&#1058;&#1072;&#1073;&#1083;&#1080;&#1094;&#1072; %d.:"
5966 :utf-8 "Таблица %d.:")
5967 ("sl" :default "Tabela %d")
5968 ("sv" :default "Tabell %d")
5969 ("zh-CN" :html "&#34920;%d&nbsp;" :utf-8 "表%d "))
5970 ("Table of Contents"
5971 ("ar" :default "قائمة المحتويات")
5972 ("ca" :html "&Iacute;ndex")
5973 ("cs" :default "Obsah")
5974 ("da" :default "Indhold")
5975 ("de" :default "Inhaltsverzeichnis")
5976 ("eo" :default "Enhavo")
5977 ("es" :ascii "Indice" :html "&Iacute;ndice" :default "Índice")
5978 ("et" :default "Sisukord")
5979 ("fi" :html "Sis&auml;llysluettelo")
5980 ("fr" :ascii "Sommaire" :default "Table des matières")
5981 ("hu" :html "Tartalomjegyz&eacute;k")
5982 ("is" :default "Efnisyfirlit")
5983 ("it" :default "Indice")
5984 ("ja" :default "目次" :html "&#30446;&#27425;")
5985 ("nl" :default "Inhoudsopgave")
5986 ("no" :default "Innhold")
5987 ("nb" :default "Innhold")
5988 ("nn" :default "Innhald")
5989 ("pl" :html "Spis tre&#x015b;ci")
5990 ("pt_BR" :html "&Iacute;ndice" :utf8 "Índice" :ascii "Indice")
5991 ("ru" :html "&#1057;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1077;"
5992 :utf-8 "Содержание")
5993 ("sl" :default "Kazalo")
5994 ("sv" :html "Inneh&aring;ll")
5995 ("uk" :html "&#1047;&#1084;&#1110;&#1089;&#1090;" :utf-8 "Зміст")
5996 ("zh-CN" :html "&#30446;&#24405;" :utf-8 "目录")
5997 ("zh-TW" :html "&#30446;&#37636;" :utf-8 "目錄"))
5998 ("Unknown reference"
5999 ("ar" :default "مرجع غير معرّف")
6000 ("da" :default "ukendt reference")
6001 ("de" :default "Unbekannter Verweis")
6002 ("es" :default "Referencia desconocida")
6003 ("et" :default "Tundmatu viide")
6004 ("fr" :ascii "Destination inconnue" :default "Référence inconnue")
6005 ("ja" :default "不明な参照先")
6006 ("pt_BR" :default "Referência desconhecida"
6007 :ascii "Referencia desconhecida")
6008 ("ru" :html "&#1053;&#1077;&#1080;&#1079;&#1074;&#1077;&#1089;&#1090;&#1085;&#1072;&#1103; &#1089;&#1089;&#1099;&#1083;&#1082;&#1072;"
6009 :utf-8 "Неизвестная ссылка")
6010 ("sl" :default "Neznana referenca")
6011 ("zh-CN" :html "&#26410;&#30693;&#24341;&#29992;" :utf-8 "未知引用")))
6012 "Dictionary for export engine.
6014 Alist whose car is the string to translate and cdr is an alist
6015 whose car is the language string and cdr is a plist whose
6016 properties are possible charsets and values translated terms.
6018 It is used as a database for `org-export-translate'. Since this
6019 function returns the string as-is if no translation was found,
6020 the variable only needs to record values different from the
6021 entry.")
6023 (defun org-export-translate (s encoding info)
6024 "Translate string S according to language specification.
6026 ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1'
6027 and `:utf-8'. INFO is a plist used as a communication channel.
6029 Translation depends on `:language' property. Return the
6030 translated string. If no translation is found, try to fall back
6031 to `:default' encoding. If it fails, return S."
6032 (let* ((lang (plist-get info :language))
6033 (translations (cdr (assoc lang
6034 (cdr (assoc s org-export-dictionary))))))
6035 (or (plist-get translations encoding)
6036 (plist-get translations :default)
6037 s)))
6041 ;;; Asynchronous Export
6043 ;; `org-export-async-start' is the entry point for asynchronous
6044 ;; export. It recreates current buffer (including visibility,
6045 ;; narrowing and visited file) in an external Emacs process, and
6046 ;; evaluates a command there. It then applies a function on the
6047 ;; returned results in the current process.
6049 ;; At a higher level, `org-export-to-buffer' and `org-export-to-file'
6050 ;; allow exporting to a buffer or a file, asynchronously or not.
6052 ;; `org-export-output-file-name' is an auxiliary function meant to be
6053 ;; used with `org-export-to-file'. With a given extension, it tries
6054 ;; to provide a canonical file name to write export output to.
6056 ;; Asynchronously generated results are never displayed directly.
6057 ;; Instead, they are stored in `org-export-stack-contents'. They can
6058 ;; then be retrieved by calling `org-export-stack'.
6060 ;; Export Stack is viewed through a dedicated major mode
6061 ;;`org-export-stack-mode' and tools: `org-export-stack-refresh',
6062 ;;`org-export-stack-delete', `org-export-stack-view' and
6063 ;;`org-export-stack-clear'.
6065 ;; For back-ends, `org-export-add-to-stack' add a new source to stack.
6066 ;; It should be used whenever `org-export-async-start' is called.
6068 (defmacro org-export-async-start (fun &rest body)
6069 "Call function FUN on the results returned by BODY evaluation.
6071 FUN is an anonymous function of one argument. BODY evaluation
6072 happens in an asynchronous process, from a buffer which is an
6073 exact copy of the current one.
6075 Use `org-export-add-to-stack' in FUN in order to register results
6076 in the stack.
6078 This is a low level function. See also `org-export-to-buffer'
6079 and `org-export-to-file' for more specialized functions."
6080 (declare (indent 1) (debug t))
6081 (org-with-gensyms (process temp-file copy-fun proc-buffer coding)
6082 ;; Write the full sexp evaluating BODY in a copy of the current
6083 ;; buffer to a temporary file, as it may be too long for program
6084 ;; args in `start-process'.
6085 `(with-temp-message "Initializing asynchronous export process"
6086 (let ((,copy-fun (org-export--generate-copy-script (current-buffer)))
6087 (,temp-file (make-temp-file "org-export-process"))
6088 (,coding buffer-file-coding-system))
6089 (with-temp-file ,temp-file
6090 (insert
6091 ;; Null characters (from variable values) are inserted
6092 ;; within the file. As a consequence, coding system for
6093 ;; buffer contents will not be recognized properly. So,
6094 ;; we make sure it is the same as the one used to display
6095 ;; the original buffer.
6096 (format ";; -*- coding: %s; -*-\n%S"
6097 ,coding
6098 `(with-temp-buffer
6099 (when org-export-async-debug '(setq debug-on-error t))
6100 ;; Ignore `kill-emacs-hook' and code evaluation
6101 ;; queries from Babel as we need a truly
6102 ;; non-interactive process.
6103 (setq kill-emacs-hook nil
6104 org-babel-confirm-evaluate-answer-no t)
6105 ;; Initialize export framework.
6106 (require 'ox)
6107 ;; Re-create current buffer there.
6108 (funcall ,,copy-fun)
6109 (restore-buffer-modified-p nil)
6110 ;; Sexp to evaluate in the buffer.
6111 (print (progn ,,@body))))))
6112 ;; Start external process.
6113 (let* ((process-connection-type nil)
6114 (,proc-buffer (generate-new-buffer-name "*Org Export Process*"))
6115 (,process
6116 (apply
6117 #'start-process
6118 (append
6119 (list "org-export-process"
6120 ,proc-buffer
6121 (expand-file-name invocation-name invocation-directory)
6122 "--batch")
6123 (if org-export-async-init-file
6124 (list "-Q" "-l" org-export-async-init-file)
6125 (list "-l" user-init-file))
6126 (list "-l" ,temp-file)))))
6127 ;; Register running process in stack.
6128 (org-export-add-to-stack (get-buffer ,proc-buffer) nil ,process)
6129 ;; Set-up sentinel in order to catch results.
6130 (let ((handler ,fun))
6131 (set-process-sentinel
6132 ,process
6133 `(lambda (p status)
6134 (let ((proc-buffer (process-buffer p)))
6135 (when (eq (process-status p) 'exit)
6136 (unwind-protect
6137 (if (zerop (process-exit-status p))
6138 (unwind-protect
6139 (let ((results
6140 (with-current-buffer proc-buffer
6141 (goto-char (point-max))
6142 (backward-sexp)
6143 (read (current-buffer)))))
6144 (funcall ,handler results))
6145 (unless org-export-async-debug
6146 (and (get-buffer proc-buffer)
6147 (kill-buffer proc-buffer))))
6148 (org-export-add-to-stack proc-buffer nil p)
6149 (ding)
6150 (message "Process `%s' exited abnormally" p))
6151 (unless org-export-async-debug
6152 (delete-file ,,temp-file)))))))))))))
6154 ;;;###autoload
6155 (defun org-export-to-buffer
6156 (backend buffer
6157 &optional async subtreep visible-only body-only ext-plist
6158 post-process)
6159 "Call `org-export-as' with output to a specified buffer.
6161 BACKEND is either an export back-end, as returned by, e.g.,
6162 `org-export-create-backend', or a symbol referring to
6163 a registered back-end.
6165 BUFFER is the name of the output buffer. If it already exists,
6166 it will be erased first, otherwise, it will be created.
6168 A non-nil optional argument ASYNC means the process should happen
6169 asynchronously. The resulting buffer should then be accessible
6170 through the `org-export-stack' interface. When ASYNC is nil, the
6171 buffer is displayed if `org-export-show-temporary-export-buffer'
6172 is non-nil.
6174 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
6175 EXT-PLIST are similar to those used in `org-export-as', which
6176 see.
6178 Optional argument POST-PROCESS is a function which should accept
6179 no argument. It is always called within the current process,
6180 from BUFFER, with point at its beginning. Export back-ends can
6181 use it to set a major mode there, e.g,
6183 (defun org-latex-export-as-latex
6184 (&optional async subtreep visible-only body-only ext-plist)
6185 (interactive)
6186 (org-export-to-buffer \\='latex \"*Org LATEX Export*\"
6187 async subtreep visible-only body-only ext-plist (lambda () (LaTeX-mode))))
6189 This function returns BUFFER."
6190 (declare (indent 2))
6191 (if async
6192 (org-export-async-start
6193 `(lambda (output)
6194 (with-current-buffer (get-buffer-create ,buffer)
6195 (erase-buffer)
6196 (setq buffer-file-coding-system ',buffer-file-coding-system)
6197 (insert output)
6198 (goto-char (point-min))
6199 (org-export-add-to-stack (current-buffer) ',backend)
6200 (ignore-errors (funcall ,post-process))))
6201 `(org-export-as
6202 ',backend ,subtreep ,visible-only ,body-only ',ext-plist))
6203 (let ((output
6204 (org-export-as backend subtreep visible-only body-only ext-plist))
6205 (buffer (get-buffer-create buffer))
6206 (encoding buffer-file-coding-system))
6207 (when (and (org-string-nw-p output) (org-export--copy-to-kill-ring-p))
6208 (org-kill-new output))
6209 (with-current-buffer buffer
6210 (erase-buffer)
6211 (setq buffer-file-coding-system encoding)
6212 (insert output)
6213 (goto-char (point-min))
6214 (and (functionp post-process) (funcall post-process)))
6215 (when org-export-show-temporary-export-buffer
6216 (switch-to-buffer-other-window buffer))
6217 buffer)))
6219 ;;;###autoload
6220 (defun org-export-to-file
6221 (backend file &optional async subtreep visible-only body-only ext-plist
6222 post-process)
6223 "Call `org-export-as' with output to a specified file.
6225 BACKEND is either an export back-end, as returned by, e.g.,
6226 `org-export-create-backend', or a symbol referring to
6227 a registered back-end. FILE is the name of the output file, as
6228 a string.
6230 A non-nil optional argument ASYNC means the process should happen
6231 asynchronously. The resulting buffer will then be accessible
6232 through the `org-export-stack' interface.
6234 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
6235 EXT-PLIST are similar to those used in `org-export-as', which
6236 see.
6238 Optional argument POST-PROCESS is called with FILE as its
6239 argument and happens asynchronously when ASYNC is non-nil. It
6240 has to return a file name, or nil. Export back-ends can use this
6241 to send the output file through additional processing, e.g,
6243 (defun org-latex-export-to-latex
6244 (&optional async subtreep visible-only body-only ext-plist)
6245 (interactive)
6246 (let ((outfile (org-export-output-file-name \".tex\" subtreep)))
6247 (org-export-to-file \\='latex outfile
6248 async subtreep visible-only body-only ext-plist
6249 (lambda (file) (org-latex-compile file)))
6251 The function returns either a file name returned by POST-PROCESS,
6252 or FILE."
6253 (declare (indent 2))
6254 (if (not (file-writable-p file)) (error "Output file not writable")
6255 (let ((ext-plist (org-combine-plists `(:output-file ,file) ext-plist))
6256 (encoding (or org-export-coding-system buffer-file-coding-system)))
6257 (if async
6258 (org-export-async-start
6259 `(lambda (file)
6260 (org-export-add-to-stack (expand-file-name file) ',backend))
6261 `(let ((output
6262 (org-export-as
6263 ',backend ,subtreep ,visible-only ,body-only
6264 ',ext-plist)))
6265 (with-temp-buffer
6266 (insert output)
6267 (let ((coding-system-for-write ',encoding))
6268 (write-file ,file)))
6269 (or (ignore-errors (funcall ',post-process ,file)) ,file)))
6270 (let ((output (org-export-as
6271 backend subtreep visible-only body-only ext-plist)))
6272 (with-temp-buffer
6273 (insert output)
6274 (let ((coding-system-for-write encoding))
6275 (write-file file)))
6276 (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p output))
6277 (org-kill-new output))
6278 ;; Get proper return value.
6279 (or (and (functionp post-process) (funcall post-process file))
6280 file))))))
6282 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
6283 "Return output file's name according to buffer specifications.
6285 EXTENSION is a string representing the output file extension,
6286 with the leading dot.
6288 With a non-nil optional argument SUBTREEP, try to determine
6289 output file's name by looking for \"EXPORT_FILE_NAME\" property
6290 of subtree at point.
6292 When optional argument PUB-DIR is set, use it as the publishing
6293 directory.
6295 Return file name as a string."
6296 (let* ((visited-file (buffer-file-name (buffer-base-buffer)))
6297 (base-name
6298 (concat
6299 (file-name-sans-extension
6301 ;; Check EXPORT_FILE_NAME subtree property.
6302 (and subtreep (org-entry-get nil "EXPORT_FILE_NAME" 'selective))
6303 ;; Check #+EXPORT_FILE_NAME keyword.
6304 (org-with-point-at (point-min)
6305 (catch :found
6306 (let ((case-fold-search t))
6307 (while (re-search-forward
6308 "^[ \t]*#\\+EXPORT_FILE_NAME:[ \t]+\\S-" nil t)
6309 (let ((element (org-element-at-point)))
6310 (when (eq 'keyword (org-element-type element))
6311 (throw :found
6312 (org-element-property :value element))))))))
6313 ;; Extract from buffer's associated file, if any.
6314 (and visited-file (file-name-nondirectory visited-file))
6315 ;; Can't determine file name on our own: ask user.
6316 (read-file-name
6317 "Output file: " pub-dir nil nil nil
6318 (lambda (n) (string= extension (file-name-extension n t))))))
6319 extension))
6320 (output-file
6321 ;; Build file name. Enforce EXTENSION over whatever user
6322 ;; may have come up with. PUB-DIR, if defined, always has
6323 ;; precedence over any provided path.
6324 (cond
6325 (pub-dir (concat (file-name-as-directory pub-dir)
6326 (file-name-nondirectory base-name)))
6327 ((file-name-absolute-p base-name) base-name)
6328 (t base-name))))
6329 ;; If writing to OUTPUT-FILE would overwrite original file, append
6330 ;; EXTENSION another time to final name.
6331 (if (and visited-file (file-equal-p visited-file output-file))
6332 (concat output-file extension)
6333 output-file)))
6335 (defun org-export-add-to-stack (source backend &optional process)
6336 "Add a new result to export stack if not present already.
6338 SOURCE is a buffer or a file name containing export results.
6339 BACKEND is a symbol representing export back-end used to generate
6342 Entries already pointing to SOURCE and unavailable entries are
6343 removed beforehand. Return the new stack."
6344 (setq org-export-stack-contents
6345 (cons (list source backend (or process (current-time)))
6346 (org-export-stack-remove source))))
6348 (defun org-export-stack ()
6349 "Menu for asynchronous export results and running processes."
6350 (interactive)
6351 (let ((buffer (get-buffer-create "*Org Export Stack*")))
6352 (with-current-buffer buffer
6353 (org-export-stack-mode)
6354 (tabulated-list-print t))
6355 (pop-to-buffer buffer))
6356 (message "Type \"q\" to quit, \"?\" for help"))
6358 (defun org-export-stack-clear ()
6359 "Remove all entries from export stack."
6360 (interactive)
6361 (setq org-export-stack-contents nil))
6363 (defun org-export-stack-refresh ()
6364 "Refresh the export stack."
6365 (interactive)
6366 (tabulated-list-print t))
6368 (defun org-export-stack-remove (&optional source)
6369 "Remove export results at point from stack.
6370 If optional argument SOURCE is non-nil, remove it instead."
6371 (interactive)
6372 (let ((source (or source (org-export--stack-source-at-point))))
6373 (setq org-export-stack-contents
6374 (cl-remove-if (lambda (el) (equal (car el) source))
6375 org-export-stack-contents))))
6377 (defun org-export-stack-view (&optional in-emacs)
6378 "View export results at point in stack.
6379 With an optional prefix argument IN-EMACS, force viewing files
6380 within Emacs."
6381 (interactive "P")
6382 (let ((source (org-export--stack-source-at-point)))
6383 (cond ((processp source)
6384 (org-switch-to-buffer-other-window (process-buffer source)))
6385 ((bufferp source) (org-switch-to-buffer-other-window source))
6386 (t (org-open-file source in-emacs)))))
6388 (defvar org-export-stack-mode-map
6389 (let ((km (make-sparse-keymap)))
6390 (set-keymap-parent km tabulated-list-mode-map)
6391 (define-key km " " 'next-line)
6392 (define-key km "\C-n" 'next-line)
6393 (define-key km [down] 'next-line)
6394 (define-key km "\C-p" 'previous-line)
6395 (define-key km "\C-?" 'previous-line)
6396 (define-key km [up] 'previous-line)
6397 (define-key km "C" 'org-export-stack-clear)
6398 (define-key km "v" 'org-export-stack-view)
6399 (define-key km (kbd "RET") 'org-export-stack-view)
6400 (define-key km "d" 'org-export-stack-remove)
6402 "Keymap for Org Export Stack.")
6404 (define-derived-mode org-export-stack-mode tabulated-list-mode "Org-Stack"
6405 "Mode for displaying asynchronous export stack.
6407 Type `\\[org-export-stack]' to visualize the asynchronous export
6408 stack.
6410 In an Org Export Stack buffer, use \
6411 \\<org-export-stack-mode-map>`\\[org-export-stack-view]' to view export output
6412 on current line, `\\[org-export-stack-remove]' to remove it from the stack and \
6413 `\\[org-export-stack-clear]' to clear
6414 stack completely.
6416 Removing entries in a stack buffer does not affect files
6417 or buffers, only display.
6419 \\{org-export-stack-mode-map}"
6420 (setq tabulated-list-format
6421 (vector (list "#" 4 #'org-export--stack-num-predicate)
6422 (list "Back-End" 12 t)
6423 (list "Age" 6 nil)
6424 (list "Source" 0 nil)))
6425 (setq tabulated-list-sort-key (cons "#" nil))
6426 (setq tabulated-list-entries #'org-export--stack-generate)
6427 (add-hook 'tabulated-list-revert-hook #'org-export--stack-generate nil t)
6428 (add-hook 'post-command-hook #'org-export-stack-refresh nil t)
6429 (tabulated-list-init-header))
6431 (defun org-export--stack-generate ()
6432 "Generate the asynchronous export stack for display.
6433 Unavailable sources are removed from the list. Return a list
6434 appropriate for `tabulated-list-print'."
6435 ;; Clear stack from exited processes, dead buffers or non-existent
6436 ;; files.
6437 (setq org-export-stack-contents
6438 (cl-remove-if-not
6439 (lambda (el)
6440 (if (processp (nth 2 el))
6441 (buffer-live-p (process-buffer (nth 2 el)))
6442 (let ((source (car el)))
6443 (if (bufferp source) (buffer-live-p source)
6444 (file-exists-p source)))))
6445 org-export-stack-contents))
6446 ;; Update `tabulated-list-entries'.
6447 (let ((counter 0))
6448 (mapcar
6449 (lambda (entry)
6450 (let ((source (car entry)))
6451 (list source
6452 (vector
6453 ;; Counter.
6454 (number-to-string (cl-incf counter))
6455 ;; Back-End.
6456 (if (nth 1 entry) (symbol-name (nth 1 entry)) "")
6457 ;; Age.
6458 (let ((info (nth 2 entry)))
6459 (if (processp info) (symbol-name (process-status info))
6460 (format-seconds "%h:%.2m" (float-time (time-since info)))))
6461 ;; Source.
6462 (if (stringp source) source (buffer-name source))))))
6463 org-export-stack-contents)))
6465 (defun org-export--stack-num-predicate (a b)
6466 (< (string-to-number (aref (nth 1 a) 0))
6467 (string-to-number (aref (nth 1 b) 0))))
6469 (defun org-export--stack-source-at-point ()
6470 "Return source from export results at point in stack."
6471 (let ((source (car (nth (1- (org-current-line)) org-export-stack-contents))))
6472 (if (not source) (error "Source unavailable, please refresh buffer")
6473 (let ((source-name (if (stringp source) source (buffer-name source))))
6474 (if (save-excursion
6475 (beginning-of-line)
6476 (looking-at-p (concat ".* +" (regexp-quote source-name) "$")))
6477 source
6478 ;; SOURCE is not consistent with current line. The stack
6479 ;; view is outdated.
6480 (error (substitute-command-keys
6481 "Source unavailable; type `\\[org-export-stack-refresh]' \
6482 to refresh buffer")))))))
6486 ;;; The Dispatcher
6488 ;; `org-export-dispatch' is the standard interactive way to start an
6489 ;; export process. It uses `org-export--dispatch-ui' as a subroutine
6490 ;; for its interface, which, in turn, delegates response to key
6491 ;; pressed to `org-export--dispatch-action'.
6493 ;;;###autoload
6494 (defun org-export-dispatch (&optional arg)
6495 "Export dispatcher for Org mode.
6497 It provides an access to common export related tasks in a buffer.
6498 Its interface comes in two flavors: standard and expert.
6500 While both share the same set of bindings, only the former
6501 displays the valid keys associations in a dedicated buffer.
6502 Scrolling (resp. line-wise motion) in this buffer is done with
6503 SPC and DEL (resp. C-n and C-p) keys.
6505 Set variable `org-export-dispatch-use-expert-ui' to switch to one
6506 flavor or the other.
6508 When ARG is `\\[universal-argument]', repeat the last export action, with the\
6509 same
6510 set of options used back then, on the current buffer.
6512 When ARG is `\\[universal-argument] \\[universal-argument]', display the \
6513 asynchronous export stack."
6514 (interactive "P")
6515 (let* ((input
6516 (cond ((equal arg '(16)) '(stack))
6517 ((and arg org-export-dispatch-last-action))
6518 (t (save-window-excursion
6519 (unwind-protect
6520 (progn
6521 ;; Remember where we are
6522 (move-marker org-export-dispatch-last-position
6523 (point)
6524 (org-base-buffer (current-buffer)))
6525 ;; Get and store an export command
6526 (setq org-export-dispatch-last-action
6527 (org-export--dispatch-ui
6528 (list org-export-initial-scope
6529 (and org-export-in-background 'async))
6531 org-export-dispatch-use-expert-ui)))
6532 (and (get-buffer "*Org Export Dispatcher*")
6533 (kill-buffer "*Org Export Dispatcher*")))))))
6534 (action (car input))
6535 (optns (cdr input)))
6536 (unless (memq 'subtree optns)
6537 (move-marker org-export-dispatch-last-position nil))
6538 (cl-case action
6539 ;; First handle special hard-coded actions.
6540 (template (org-export-insert-default-template nil optns))
6541 (stack (org-export-stack))
6542 (publish-current-file
6543 (org-publish-current-file (memq 'force optns) (memq 'async optns)))
6544 (publish-current-project
6545 (org-publish-current-project (memq 'force optns) (memq 'async optns)))
6546 (publish-choose-project
6547 (org-publish (assoc (completing-read
6548 "Publish project: "
6549 org-publish-project-alist nil t)
6550 org-publish-project-alist)
6551 (memq 'force optns)
6552 (memq 'async optns)))
6553 (publish-all (org-publish-all (memq 'force optns) (memq 'async optns)))
6554 (otherwise
6555 (save-excursion
6556 (when arg
6557 ;; Repeating command, maybe move cursor to restore subtree
6558 ;; context.
6559 (if (eq (marker-buffer org-export-dispatch-last-position)
6560 (org-base-buffer (current-buffer)))
6561 (goto-char org-export-dispatch-last-position)
6562 ;; We are in a different buffer, forget position.
6563 (move-marker org-export-dispatch-last-position nil)))
6564 (funcall action
6565 ;; Return a symbol instead of a list to ease
6566 ;; asynchronous export macro use.
6567 (and (memq 'async optns) t)
6568 (and (memq 'subtree optns) t)
6569 (and (memq 'visible optns) t)
6570 (and (memq 'body optns) t)))))))
6572 (defun org-export--dispatch-ui (options first-key expertp)
6573 "Handle interface for `org-export-dispatch'.
6575 OPTIONS is a list containing current interactive options set for
6576 export. It can contain any of the following symbols:
6577 `body' toggles a body-only export
6578 `subtree' restricts export to current subtree
6579 `visible' restricts export to visible part of buffer.
6580 `force' force publishing files.
6581 `async' use asynchronous export process
6583 FIRST-KEY is the key pressed to select the first level menu. It
6584 is nil when this menu hasn't been selected yet.
6586 EXPERTP, when non-nil, triggers expert UI. In that case, no help
6587 buffer is provided, but indications about currently active
6588 options are given in the prompt. Moreover, [?] allows switching
6589 back to standard interface."
6590 (let* ((fontify-key
6591 (lambda (key &optional access-key)
6592 ;; Fontify KEY string. Optional argument ACCESS-KEY, when
6593 ;; non-nil is the required first-level key to activate
6594 ;; KEY. When its value is t, activate KEY independently
6595 ;; on the first key, if any. A nil value means KEY will
6596 ;; only be activated at first level.
6597 (if (or (eq access-key t) (eq access-key first-key))
6598 (propertize key 'face 'org-warning)
6599 key)))
6600 (fontify-value
6601 (lambda (value)
6602 ;; Fontify VALUE string.
6603 (propertize value 'face 'font-lock-variable-name-face)))
6604 ;; Prepare menu entries by extracting them from registered
6605 ;; back-ends and sorting them by access key and by ordinal,
6606 ;; if any.
6607 (entries
6608 (sort (sort (delq nil
6609 (mapcar #'org-export-backend-menu
6610 org-export-registered-backends))
6611 (lambda (a b)
6612 (let ((key-a (nth 1 a))
6613 (key-b (nth 1 b)))
6614 (cond ((and (numberp key-a) (numberp key-b))
6615 (< key-a key-b))
6616 ((numberp key-b) t)))))
6617 'car-less-than-car))
6618 ;; Compute a list of allowed keys based on the first key
6619 ;; pressed, if any. Some keys
6620 ;; (?^B, ?^V, ?^S, ?^F, ?^A, ?&, ?# and ?q) are always
6621 ;; available.
6622 (allowed-keys
6623 (nconc (list 2 22 19 6 1)
6624 (if (not first-key) (org-uniquify (mapcar 'car entries))
6625 (let (sub-menu)
6626 (dolist (entry entries (sort (mapcar 'car sub-menu) '<))
6627 (when (eq (car entry) first-key)
6628 (setq sub-menu (append (nth 2 entry) sub-menu))))))
6629 (cond ((eq first-key ?P) (list ?f ?p ?x ?a))
6630 ((not first-key) (list ?P)))
6631 (list ?& ?#)
6632 (when expertp (list ??))
6633 (list ?q)))
6634 ;; Build the help menu for standard UI.
6635 (help
6636 (unless expertp
6637 (concat
6638 ;; Options are hard-coded.
6639 (format "[%s] Body only: %s [%s] Visible only: %s
6640 \[%s] Export scope: %s [%s] Force publishing: %s
6641 \[%s] Async export: %s\n\n"
6642 (funcall fontify-key "C-b" t)
6643 (funcall fontify-value
6644 (if (memq 'body options) "On " "Off"))
6645 (funcall fontify-key "C-v" t)
6646 (funcall fontify-value
6647 (if (memq 'visible options) "On " "Off"))
6648 (funcall fontify-key "C-s" t)
6649 (funcall fontify-value
6650 (if (memq 'subtree options) "Subtree" "Buffer "))
6651 (funcall fontify-key "C-f" t)
6652 (funcall fontify-value
6653 (if (memq 'force options) "On " "Off"))
6654 (funcall fontify-key "C-a" t)
6655 (funcall fontify-value
6656 (if (memq 'async options) "On " "Off")))
6657 ;; Display registered back-end entries. When a key
6658 ;; appears for the second time, do not create another
6659 ;; entry, but append its sub-menu to existing menu.
6660 (let (last-key)
6661 (mapconcat
6662 (lambda (entry)
6663 (let ((top-key (car entry)))
6664 (concat
6665 (unless (eq top-key last-key)
6666 (setq last-key top-key)
6667 (format "\n[%s] %s\n"
6668 (funcall fontify-key (char-to-string top-key))
6669 (nth 1 entry)))
6670 (let ((sub-menu (nth 2 entry)))
6671 (unless (functionp sub-menu)
6672 ;; Split sub-menu into two columns.
6673 (let ((index -1))
6674 (concat
6675 (mapconcat
6676 (lambda (sub-entry)
6677 (cl-incf index)
6678 (format
6679 (if (zerop (mod index 2)) " [%s] %-26s"
6680 "[%s] %s\n")
6681 (funcall fontify-key
6682 (char-to-string (car sub-entry))
6683 top-key)
6684 (nth 1 sub-entry)))
6685 sub-menu "")
6686 (when (zerop (mod index 2)) "\n"))))))))
6687 entries ""))
6688 ;; Publishing menu is hard-coded.
6689 (format "\n[%s] Publish
6690 [%s] Current file [%s] Current project
6691 [%s] Choose project [%s] All projects\n\n\n"
6692 (funcall fontify-key "P")
6693 (funcall fontify-key "f" ?P)
6694 (funcall fontify-key "p" ?P)
6695 (funcall fontify-key "x" ?P)
6696 (funcall fontify-key "a" ?P))
6697 (format "[%s] Export stack [%s] Insert template\n"
6698 (funcall fontify-key "&" t)
6699 (funcall fontify-key "#" t))
6700 (format "[%s] %s"
6701 (funcall fontify-key "q" t)
6702 (if first-key "Main menu" "Exit")))))
6703 ;; Build prompts for both standard and expert UI.
6704 (standard-prompt (unless expertp "Export command: "))
6705 (expert-prompt
6706 (when expertp
6707 (format
6708 "Export command (C-%s%s%s%s%s) [%s]: "
6709 (if (memq 'body options) (funcall fontify-key "b" t) "b")
6710 (if (memq 'visible options) (funcall fontify-key "v" t) "v")
6711 (if (memq 'subtree options) (funcall fontify-key "s" t) "s")
6712 (if (memq 'force options) (funcall fontify-key "f" t) "f")
6713 (if (memq 'async options) (funcall fontify-key "a" t) "a")
6714 (mapconcat (lambda (k)
6715 ;; Strip control characters.
6716 (unless (< k 27) (char-to-string k)))
6717 allowed-keys "")))))
6718 ;; With expert UI, just read key with a fancy prompt. In standard
6719 ;; UI, display an intrusive help buffer.
6720 (if expertp
6721 (org-export--dispatch-action
6722 expert-prompt allowed-keys entries options first-key expertp)
6723 ;; At first call, create frame layout in order to display menu.
6724 (unless (get-buffer "*Org Export Dispatcher*")
6725 (delete-other-windows)
6726 (org-switch-to-buffer-other-window
6727 (get-buffer-create "*Org Export Dispatcher*"))
6728 (setq cursor-type nil
6729 header-line-format "Use SPC, DEL, C-n or C-p to navigate.")
6730 ;; Make sure that invisible cursor will not highlight square
6731 ;; brackets.
6732 (set-syntax-table (copy-syntax-table))
6733 (modify-syntax-entry ?\[ "w"))
6734 ;; At this point, the buffer containing the menu exists and is
6735 ;; visible in the current window. So, refresh it.
6736 (with-current-buffer "*Org Export Dispatcher*"
6737 ;; Refresh help. Maintain display continuity by re-visiting
6738 ;; previous window position.
6739 (let ((pos (window-start)))
6740 (erase-buffer)
6741 (insert help)
6742 (set-window-start nil pos)))
6743 (org-fit-window-to-buffer)
6744 (org-export--dispatch-action
6745 standard-prompt allowed-keys entries options first-key expertp))))
6747 (defun org-export--dispatch-action
6748 (prompt allowed-keys entries options first-key expertp)
6749 "Read a character from command input and act accordingly.
6751 PROMPT is the displayed prompt, as a string. ALLOWED-KEYS is
6752 a list of characters available at a given step in the process.
6753 ENTRIES is a list of menu entries. OPTIONS, FIRST-KEY and
6754 EXPERTP are the same as defined in `org-export--dispatch-ui',
6755 which see.
6757 Toggle export options when required. Otherwise, return value is
6758 a list with action as CAR and a list of interactive export
6759 options as CDR."
6760 (let (key)
6761 ;; Scrolling: when in non-expert mode, act on motion keys (C-n,
6762 ;; C-p, SPC, DEL).
6763 (while (and (setq key (read-char-exclusive prompt))
6764 (not expertp)
6765 (memq key '(14 16 ?\s ?\d)))
6766 (cl-case key
6767 (14 (if (not (pos-visible-in-window-p (point-max)))
6768 (ignore-errors (scroll-up 1))
6769 (message "End of buffer")
6770 (sit-for 1)))
6771 (16 (if (not (pos-visible-in-window-p (point-min)))
6772 (ignore-errors (scroll-down 1))
6773 (message "Beginning of buffer")
6774 (sit-for 1)))
6775 (?\s (if (not (pos-visible-in-window-p (point-max)))
6776 (scroll-up nil)
6777 (message "End of buffer")
6778 (sit-for 1)))
6779 (?\d (if (not (pos-visible-in-window-p (point-min)))
6780 (scroll-down nil)
6781 (message "Beginning of buffer")
6782 (sit-for 1)))))
6783 (cond
6784 ;; Ignore undefined associations.
6785 ((not (memq key allowed-keys))
6786 (ding)
6787 (unless expertp (message "Invalid key") (sit-for 1))
6788 (org-export--dispatch-ui options first-key expertp))
6789 ;; q key at first level aborts export. At second level, cancel
6790 ;; first key instead.
6791 ((eq key ?q) (if (not first-key) (error "Export aborted")
6792 (org-export--dispatch-ui options nil expertp)))
6793 ;; Help key: Switch back to standard interface if expert UI was
6794 ;; active.
6795 ((eq key ??) (org-export--dispatch-ui options first-key nil))
6796 ;; Send request for template insertion along with export scope.
6797 ((eq key ?#) (cons 'template (memq 'subtree options)))
6798 ;; Switch to asynchronous export stack.
6799 ((eq key ?&) '(stack))
6800 ;; Toggle options: C-b (2) C-v (22) C-s (19) C-f (6) C-a (1).
6801 ((memq key '(2 22 19 6 1))
6802 (org-export--dispatch-ui
6803 (let ((option (cl-case key (2 'body) (22 'visible) (19 'subtree)
6804 (6 'force) (1 'async))))
6805 (if (memq option options) (remq option options)
6806 (cons option options)))
6807 first-key expertp))
6808 ;; Action selected: Send key and options back to
6809 ;; `org-export-dispatch'.
6810 ((or first-key (functionp (nth 2 (assq key entries))))
6811 (cons (cond
6812 ((not first-key) (nth 2 (assq key entries)))
6813 ;; Publishing actions are hard-coded. Send a special
6814 ;; signal to `org-export-dispatch'.
6815 ((eq first-key ?P)
6816 (cl-case key
6817 (?f 'publish-current-file)
6818 (?p 'publish-current-project)
6819 (?x 'publish-choose-project)
6820 (?a 'publish-all)))
6821 ;; Return first action associated to FIRST-KEY + KEY
6822 ;; path. Indeed, derived backends can share the same
6823 ;; FIRST-KEY.
6824 (t (catch 'found
6825 (dolist (entry (member (assq first-key entries) entries))
6826 (let ((match (assq key (nth 2 entry))))
6827 (when match (throw 'found (nth 2 match))))))))
6828 options))
6829 ;; Otherwise, enter sub-menu.
6830 (t (org-export--dispatch-ui options key expertp)))))
6834 (provide 'ox)
6836 ;; Local variables:
6837 ;; generated-autoload-file: "org-loaddefs.el"
6838 ;; End:
6840 ;;; ox.el ends here