ox: Fix inline source block evaluation
[org-mode.git] / lisp / ox.el
blob744e94159d2a90ed303b0753e33a128506b4a797
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 (funcall transcoder data contents new-info)
3685 (plist-put info :internal-references
3686 (plist-get new-info :internal-references)))))))
3689 ;;;; For Export Snippets
3691 ;; Every export snippet is transmitted to the back-end. Though, the
3692 ;; latter will only retain one type of export-snippet, ignoring
3693 ;; others, based on the former's target back-end. The function
3694 ;; `org-export-snippet-backend' returns that back-end for a given
3695 ;; export-snippet.
3697 (defun org-export-snippet-backend (export-snippet)
3698 "Return EXPORT-SNIPPET targeted back-end as a symbol.
3699 Translation, with `org-export-snippet-translation-alist', is
3700 applied."
3701 (let ((back-end (org-element-property :back-end export-snippet)))
3702 (intern
3703 (or (cdr (assoc back-end org-export-snippet-translation-alist))
3704 back-end))))
3707 ;;;; For Footnotes
3709 ;; `org-export-collect-footnote-definitions' is a tool to list
3710 ;; actually used footnotes definitions in the whole parse tree, or in
3711 ;; a headline, in order to add footnote listings throughout the
3712 ;; transcoded data.
3714 ;; `org-export-footnote-first-reference-p' is a predicate used by some
3715 ;; back-ends, when they need to attach the footnote definition only to
3716 ;; the first occurrence of the corresponding label.
3718 ;; `org-export-get-footnote-definition' and
3719 ;; `org-export-get-footnote-number' provide easier access to
3720 ;; additional information relative to a footnote reference.
3722 (defun org-export-get-footnote-definition (footnote-reference info)
3723 "Return definition of FOOTNOTE-REFERENCE as parsed data.
3724 INFO is the plist used as a communication channel. If no such
3725 definition can be found, raise an error."
3726 (let ((label (org-element-property :label footnote-reference)))
3727 (if (not label) (org-element-contents footnote-reference)
3728 (let ((cache (or (plist-get info :footnote-definition-cache)
3729 (let ((hash (make-hash-table :test #'equal)))
3730 (plist-put info :footnote-definition-cache hash)
3731 hash))))
3733 (gethash label cache)
3734 (puthash label
3735 (org-element-map (plist-get info :parse-tree)
3736 '(footnote-definition footnote-reference)
3737 (lambda (f)
3738 (cond
3739 ;; Skip any footnote with a different label.
3740 ;; Also skip any standard footnote reference
3741 ;; with the same label since those cannot
3742 ;; contain a definition.
3743 ((not (equal (org-element-property :label f) label)) nil)
3744 ((eq (org-element-property :type f) 'standard) nil)
3745 ((org-element-contents f))
3746 ;; Even if the contents are empty, we can not
3747 ;; return nil since that would eventually raise
3748 ;; the error. Instead, return the equivalent
3749 ;; empty string.
3750 (t "")))
3751 info t)
3752 cache)
3753 (error "Definition not found for footnote %s" label))))))
3755 (defun org-export--footnote-reference-map
3756 (function data info &optional body-first)
3757 "Apply FUNCTION on every footnote reference in DATA.
3758 INFO is a plist containing export state. By default, as soon as
3759 a new footnote reference is encountered, FUNCTION is called onto
3760 its definition. However, if BODY-FIRST is non-nil, this step is
3761 delayed until the end of the process."
3762 (letrec ((definitions nil)
3763 (seen-refs nil)
3764 (search-ref
3765 (lambda (data delayp)
3766 ;; Search footnote references through DATA, filling
3767 ;; SEEN-REFS along the way. When DELAYP is non-nil,
3768 ;; store footnote definitions so they can be entered
3769 ;; later.
3770 (org-element-map data 'footnote-reference
3771 (lambda (f)
3772 (funcall function f)
3773 (let ((--label (org-element-property :label f)))
3774 (unless (and --label (member --label seen-refs))
3775 (when --label (push --label seen-refs))
3776 ;; Search for subsequent references in footnote
3777 ;; definition so numbering follows reading
3778 ;; logic, unless DELAYP in non-nil.
3779 (cond
3780 (delayp
3781 (push (org-export-get-footnote-definition f info)
3782 definitions))
3783 ;; Do not force entering inline definitions,
3784 ;; since `org-element-map' already traverses
3785 ;; them at the right time.
3786 ((eq (org-element-property :type f) 'inline))
3787 (t (funcall search-ref
3788 (org-export-get-footnote-definition f info)
3789 nil))))))
3790 info nil
3791 ;; Don't enter footnote definitions since it will
3792 ;; happen when their first reference is found.
3793 ;; Moreover, if DELAYP is non-nil, make sure we
3794 ;; postpone entering definitions of inline references.
3795 (if delayp '(footnote-definition footnote-reference)
3796 'footnote-definition)))))
3797 (funcall search-ref data body-first)
3798 (funcall search-ref (nreverse definitions) nil)))
3800 (defun org-export-collect-footnote-definitions (info &optional data body-first)
3801 "Return an alist between footnote numbers, labels and definitions.
3803 INFO is the current export state, as a plist.
3805 Definitions are collected throughout the whole parse tree, or
3806 DATA when non-nil.
3808 Sorting is done by order of references. As soon as a new
3809 reference is encountered, other references are searched within
3810 its definition. However, if BODY-FIRST is non-nil, this step is
3811 delayed after the whole tree is checked. This alters results
3812 when references are found in footnote definitions.
3814 Definitions either appear as Org data or as a secondary string
3815 for inlined footnotes. Unreferenced definitions are ignored."
3816 (let ((n 0) labels alist)
3817 (org-export--footnote-reference-map
3818 (lambda (f)
3819 ;; Collect footnote number, label and definition.
3820 (let ((l (org-element-property :label f)))
3821 (unless (and l (member l labels))
3822 (cl-incf n)
3823 (push (list n l (org-export-get-footnote-definition f info)) alist))
3824 (when l (push l labels))))
3825 (or data (plist-get info :parse-tree)) info body-first)
3826 (nreverse alist)))
3828 (defun org-export-footnote-first-reference-p
3829 (footnote-reference info &optional data body-first)
3830 "Non-nil when a footnote reference is the first one for its label.
3832 FOOTNOTE-REFERENCE is the footnote reference being considered.
3833 INFO is a plist containing current export state.
3835 Search is done throughout the whole parse tree, or DATA when
3836 non-nil.
3838 By default, as soon as a new footnote reference is encountered,
3839 other references are searched within its definition. However, if
3840 BODY-FIRST is non-nil, this step is delayed after the whole tree
3841 is checked. This alters results when references are found in
3842 footnote definitions."
3843 (let ((label (org-element-property :label footnote-reference)))
3844 ;; Anonymous footnotes are always a first reference.
3845 (or (not label)
3846 (catch 'exit
3847 (org-export--footnote-reference-map
3848 (lambda (f)
3849 (let ((l (org-element-property :label f)))
3850 (when (and l label (string= label l))
3851 (throw 'exit (eq footnote-reference f)))))
3852 (or data (plist-get info :parse-tree)) info body-first)))))
3854 (defun org-export-get-footnote-number (footnote info &optional data body-first)
3855 "Return number associated to a footnote.
3857 FOOTNOTE is either a footnote reference or a footnote definition.
3858 INFO is the plist containing export state.
3860 Number is unique throughout the whole parse tree, or DATA, when
3861 non-nil.
3863 By default, as soon as a new footnote reference is encountered,
3864 counting process moves into its definition. However, if
3865 BODY-FIRST is non-nil, this step is delayed until the end of the
3866 process, leading to a different order when footnotes are nested."
3867 (let ((count 0)
3868 (seen)
3869 (label (org-element-property :label footnote)))
3870 (catch 'exit
3871 (org-export--footnote-reference-map
3872 (lambda (f)
3873 (let ((l (org-element-property :label f)))
3874 (cond
3875 ;; Anonymous footnote match: return number.
3876 ((and (not l) (not label) (eq footnote f)) (throw 'exit (1+ count)))
3877 ;; Labels match: return number.
3878 ((and label l (string= label l)) (throw 'exit (1+ count)))
3879 ;; Otherwise store label and increase counter if label
3880 ;; wasn't encountered yet.
3881 ((not l) (cl-incf count))
3882 ((not (member l seen)) (push l seen) (cl-incf count)))))
3883 (or data (plist-get info :parse-tree)) info body-first))))
3886 ;;;; For Headlines
3888 ;; `org-export-get-relative-level' is a shortcut to get headline
3889 ;; level, relatively to the lower headline level in the parsed tree.
3891 ;; `org-export-get-headline-number' returns the section number of an
3892 ;; headline, while `org-export-number-to-roman' allows it to be
3893 ;; converted to roman numbers. With an optional argument,
3894 ;; `org-export-get-headline-number' returns a number to unnumbered
3895 ;; headlines (used for internal id).
3897 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
3898 ;; `org-export-last-sibling-p' are three useful predicates when it
3899 ;; comes to fulfill the `:headline-levels' property.
3901 ;; `org-export-get-tags', `org-export-get-category' and
3902 ;; `org-export-get-node-property' extract useful information from an
3903 ;; headline or a parent headline. They all handle inheritance.
3905 ;; `org-export-get-alt-title' tries to retrieve an alternative title,
3906 ;; as a secondary string, suitable for table of contents. It falls
3907 ;; back onto default title.
3909 (defun org-export-get-relative-level (headline info)
3910 "Return HEADLINE relative level within current parsed tree.
3911 INFO is a plist holding contextual information."
3912 (+ (org-element-property :level headline)
3913 (or (plist-get info :headline-offset) 0)))
3915 (defun org-export-low-level-p (headline info)
3916 "Non-nil when HEADLINE is considered as low level.
3918 INFO is a plist used as a communication channel.
3920 A low level headlines has a relative level greater than
3921 `:headline-levels' property value.
3923 Return value is the difference between HEADLINE relative level
3924 and the last level being considered as high enough, or nil."
3925 (let ((limit (plist-get info :headline-levels)))
3926 (when (wholenump limit)
3927 (let ((level (org-export-get-relative-level headline info)))
3928 (and (> level limit) (- level limit))))))
3930 (defun org-export-get-headline-number (headline info)
3931 "Return numbered HEADLINE numbering as a list of numbers.
3932 INFO is a plist holding contextual information."
3933 (and (org-export-numbered-headline-p headline info)
3934 (cdr (assq headline (plist-get info :headline-numbering)))))
3936 (defun org-export-numbered-headline-p (headline info)
3937 "Return a non-nil value if HEADLINE element should be numbered.
3938 INFO is a plist used as a communication channel."
3939 (unless (org-not-nil (org-export-get-node-property :UNNUMBERED headline t))
3940 (let ((sec-num (plist-get info :section-numbers))
3941 (level (org-export-get-relative-level headline info)))
3942 (if (wholenump sec-num) (<= level sec-num) sec-num))))
3944 (defun org-export-number-to-roman (n)
3945 "Convert integer N into a roman numeral."
3946 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
3947 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
3948 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
3949 ( 1 . "I")))
3950 (res ""))
3951 (if (<= n 0)
3952 (number-to-string n)
3953 (while roman
3954 (if (>= n (caar roman))
3955 (setq n (- n (caar roman))
3956 res (concat res (cdar roman)))
3957 (pop roman)))
3958 res)))
3960 (defun org-export-get-tags (element info &optional tags inherited)
3961 "Return list of tags associated to ELEMENT.
3963 ELEMENT has either an `headline' or an `inlinetask' type. INFO
3964 is a plist used as a communication channel.
3966 When non-nil, optional argument TAGS should be a list of strings.
3967 Any tag belonging to this list will also be removed.
3969 When optional argument INHERITED is non-nil, tags can also be
3970 inherited from parent headlines and FILETAGS keywords."
3971 (cl-remove-if
3972 (lambda (tag) (member tag tags))
3973 (if (not inherited) (org-element-property :tags element)
3974 ;; Build complete list of inherited tags.
3975 (let ((current-tag-list (org-element-property :tags element)))
3976 (dolist (parent (org-element-lineage element))
3977 (dolist (tag (org-element-property :tags parent))
3978 (when (and (memq (org-element-type parent) '(headline inlinetask))
3979 (not (member tag current-tag-list)))
3980 (push tag current-tag-list))))
3981 ;; Add FILETAGS keywords and return results.
3982 (org-uniquify (append (plist-get info :filetags) current-tag-list))))))
3984 (defun org-export-get-node-property (property blob &optional inherited)
3985 "Return node PROPERTY value for BLOB.
3987 PROPERTY is an upcase symbol (i.e. `:COOKIE_DATA'). BLOB is an
3988 element or object.
3990 If optional argument INHERITED is non-nil, the value can be
3991 inherited from a parent headline.
3993 Return value is a string or nil."
3994 (let ((headline (if (eq (org-element-type blob) 'headline) blob
3995 (org-export-get-parent-headline blob))))
3996 (if (not inherited) (org-element-property property blob)
3997 (let ((parent headline))
3998 (catch 'found
3999 (while parent
4000 (when (plist-member (nth 1 parent) property)
4001 (throw 'found (org-element-property property parent)))
4002 (setq parent (org-element-property :parent parent))))))))
4004 (defun org-export-get-category (blob info)
4005 "Return category for element or object BLOB.
4007 INFO is a plist used as a communication channel.
4009 CATEGORY is automatically inherited from a parent headline, from
4010 #+CATEGORY: keyword or created out of original file name. If all
4011 fail, the fall-back value is \"???\"."
4012 (or (org-export-get-node-property :CATEGORY blob t)
4013 (org-element-map (plist-get info :parse-tree) 'keyword
4014 (lambda (kwd)
4015 (when (equal (org-element-property :key kwd) "CATEGORY")
4016 (org-element-property :value kwd)))
4017 info 'first-match)
4018 (let ((file (plist-get info :input-file)))
4019 (and file (file-name-sans-extension (file-name-nondirectory file))))
4020 "???"))
4022 (defun org-export-get-alt-title (headline _)
4023 "Return alternative title for HEADLINE, as a secondary string.
4024 If no optional title is defined, fall-back to the regular title."
4025 (let ((alt (org-element-property :ALT_TITLE headline)))
4026 (if alt (org-element-parse-secondary-string
4027 alt (org-element-restriction 'headline) headline)
4028 (org-element-property :title headline))))
4030 (defun org-export-first-sibling-p (blob info)
4031 "Non-nil when BLOB is the first sibling in its parent.
4032 BLOB is an element or an object. If BLOB is a headline, non-nil
4033 means it is the first sibling in the sub-tree. INFO is a plist
4034 used as a communication channel."
4035 (memq (org-element-type (org-export-get-previous-element blob info))
4036 '(nil section)))
4038 (defun org-export-last-sibling-p (datum info)
4039 "Non-nil when DATUM is the last sibling in its parent.
4040 DATUM is an element or an object. INFO is a plist used as
4041 a communication channel."
4042 (let ((next (org-export-get-next-element datum info)))
4043 (or (not next)
4044 (and (eq 'headline (org-element-type datum))
4045 (> (org-element-property :level datum)
4046 (org-element-property :level next))))))
4049 ;;;; For Keywords
4051 ;; `org-export-get-date' returns a date appropriate for the document
4052 ;; to about to be exported. In particular, it takes care of
4053 ;; `org-export-date-timestamp-format'.
4055 (defun org-export-get-date (info &optional fmt)
4056 "Return date value for the current document.
4058 INFO is a plist used as a communication channel. FMT, when
4059 non-nil, is a time format string that will be applied on the date
4060 if it consists in a single timestamp object. It defaults to
4061 `org-export-date-timestamp-format' when nil.
4063 A proper date can be a secondary string, a string or nil. It is
4064 meant to be translated with `org-export-data' or alike."
4065 (let ((date (plist-get info :date))
4066 (fmt (or fmt org-export-date-timestamp-format)))
4067 (cond ((not date) nil)
4068 ((and fmt
4069 (not (cdr date))
4070 (eq (org-element-type (car date)) 'timestamp))
4071 (org-timestamp-format (car date) fmt))
4072 (t date))))
4075 ;;;; For Links
4077 ;; `org-export-custom-protocol-maybe' handles custom protocol defined
4078 ;; in `org-link-parameters'.
4080 ;; `org-export-get-coderef-format' returns an appropriate format
4081 ;; string for coderefs.
4083 ;; `org-export-inline-image-p' returns a non-nil value when the link
4084 ;; provided should be considered as an inline image.
4086 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
4087 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
4088 ;; returns an appropriate unique identifier.
4090 ;; `org-export-resolve-id-link' returns the first headline with
4091 ;; specified id or custom-id in parse tree, the path to the external
4092 ;; file with the id.
4094 ;; `org-export-resolve-coderef' associates a reference to a line
4095 ;; number in the element it belongs, or returns the reference itself
4096 ;; when the element isn't numbered.
4098 ;; `org-export-file-uri' expands a filename as stored in :path value
4099 ;; of a "file" link into a file URI.
4101 ;; Broken links raise a `org-link-broken' error, which is caught by
4102 ;; `org-export-data' for further processing, depending on
4103 ;; `org-export-with-broken-links' value.
4105 (org-define-error 'org-link-broken "Unable to resolve link; aborting")
4107 (defun org-export-custom-protocol-maybe (link desc backend)
4108 "Try exporting LINK with a dedicated function.
4110 DESC is its description, as a string, or nil. BACKEND is the
4111 back-end used for export, as a symbol.
4113 Return output as a string, or nil if no protocol handles LINK.
4115 A custom protocol has precedence over regular back-end export.
4116 The function ignores links with an implicit type (e.g.,
4117 \"custom-id\")."
4118 (let ((type (org-element-property :type link)))
4119 (unless (or (member type '("coderef" "custom-id" "fuzzy" "radio"))
4120 (not backend))
4121 (let ((protocol (org-link-get-parameter type :export)))
4122 (and (functionp protocol)
4123 (funcall protocol
4124 (org-link-unescape (org-element-property :path link))
4125 desc
4126 backend))))))
4128 (defun org-export-get-coderef-format (path desc)
4129 "Return format string for code reference link.
4130 PATH is the link path. DESC is its description."
4131 (save-match-data
4132 (cond ((not desc) "%s")
4133 ((string-match (regexp-quote (concat "(" path ")")) desc)
4134 (replace-match "%s" t t desc))
4135 (t desc))))
4137 (defun org-export-inline-image-p (link &optional rules)
4138 "Non-nil if LINK object points to an inline image.
4140 Optional argument is a set of RULES defining inline images. It
4141 is an alist where associations have the following shape:
4143 (TYPE . REGEXP)
4145 Applying a rule means apply REGEXP against LINK's path when its
4146 type is TYPE. The function will return a non-nil value if any of
4147 the provided rules is non-nil. The default rule is
4148 `org-export-default-inline-image-rule'.
4150 This only applies to links without a description."
4151 (and (not (org-element-contents link))
4152 (let ((case-fold-search t))
4153 (cl-some (lambda (rule)
4154 (and (string= (org-element-property :type link) (car rule))
4155 (string-match-p (cdr rule)
4156 (org-element-property :path link))))
4157 (or rules org-export-default-inline-image-rule)))))
4159 (defun org-export-insert-image-links (data info &optional rules)
4160 "Insert image links in DATA.
4162 Org syntax does not support nested links. Nevertheless, some
4163 export back-ends support images as descriptions of links. Since
4164 images are really links to image files, we need to make an
4165 exception about links nesting.
4167 This function recognizes links whose contents are really images
4168 and turn them into proper nested links. It is meant to be used
4169 as a parse tree filter in back-ends supporting such constructs.
4171 DATA is a parse tree. INFO is the current state of the export
4172 process, as a plist.
4174 A description is a valid images if it matches any rule in RULES,
4175 if non-nil, or `org-export-default-inline-image-rule' otherwise.
4176 See `org-export-inline-image-p' for more information about the
4177 structure of RULES.
4179 Return modified DATA."
4180 (let ((link-re (format "\\`\\(?:%s\\|%s\\)\\'"
4181 org-plain-link-re
4182 org-angle-link-re))
4183 (case-fold-search t))
4184 (org-element-map data 'link
4185 (lambda (l)
4186 (let ((contents (org-element-interpret-data (org-element-contents l))))
4187 (when (and (org-string-nw-p contents)
4188 (string-match link-re contents))
4189 (let ((type (match-string 1 contents))
4190 (path (match-string 2 contents)))
4191 (when (cl-some (lambda (rule)
4192 (and (string= type (car rule))
4193 (string-match-p (cdr rule) path)))
4194 (or rules org-export-default-inline-image-rule))
4195 ;; Replace contents with image link.
4196 (org-element-adopt-elements
4197 (org-element-set-contents l nil)
4198 (with-temp-buffer
4199 (save-excursion (insert contents))
4200 (org-element-link-parser))))))))
4201 info nil nil t))
4202 data)
4204 (defun org-export-resolve-coderef (ref info)
4205 "Resolve a code reference REF.
4207 INFO is a plist used as a communication channel.
4209 Return associated line number in source code, or REF itself,
4210 depending on src-block or example element's switches. Throw an
4211 error if no block contains REF."
4212 (or (org-element-map (plist-get info :parse-tree) '(example-block src-block)
4213 (lambda (el)
4214 (with-temp-buffer
4215 (insert (org-trim (org-element-property :value el)))
4216 (let* ((label-fmt (or (org-element-property :label-fmt el)
4217 org-coderef-label-format))
4218 (ref-re (org-src-coderef-regexp label-fmt ref)))
4219 ;; Element containing REF is found. Resolve it to
4220 ;; either a label or a line number, as needed.
4221 (when (re-search-backward ref-re nil t)
4222 (if (org-element-property :use-labels el) ref
4223 (+ (or (org-export-get-loc el info) 0)
4224 (line-number-at-pos)))))))
4225 info 'first-match)
4226 (signal 'org-link-broken (list ref))))
4228 (defun org-export-search-cells (datum)
4229 "List search cells for element or object DATUM.
4231 A search cell follows the pattern (TYPE . SEARCH) where
4233 TYPE is a symbol among `headline', `custom-id', `target' and
4234 `other'.
4236 SEARCH is the string a link is expected to match. More
4237 accurately, it is
4239 - headline's title, as a list of strings, if TYPE is
4240 `headline'.
4242 - CUSTOM_ID value, as a string, if TYPE is `custom-id'.
4244 - target's or radio-target's name as a list of strings if
4245 TYPE is `target'.
4247 - NAME affiliated keyword is TYPE is `other'.
4249 A search cell is the internal representation of a fuzzy link. It
4250 ignores white spaces and statistics cookies, if applicable."
4251 (pcase (org-element-type datum)
4252 (`headline
4253 (let ((title (split-string
4254 (replace-regexp-in-string
4255 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]" ""
4256 (org-element-property :raw-value datum)))))
4257 (delq nil
4258 (list
4259 (cons 'headline title)
4260 (cons 'other title)
4261 (let ((custom-id (org-element-property :custom-id datum)))
4262 (and custom-id (cons 'custom-id custom-id)))))))
4263 (`target
4264 (list (cons 'target (split-string (org-element-property :value datum)))))
4265 ((and (let name (org-element-property :name datum))
4266 (guard name))
4267 (list (cons 'other (split-string name))))
4268 (_ nil)))
4270 (defun org-export-string-to-search-cell (s)
4271 "Return search cells associated to string S.
4272 S is either the path of a fuzzy link or a search option, i.e., it
4273 tries to match either a headline (through custom ID or title),
4274 a target or a named element."
4275 (pcase (string-to-char s)
4276 (?* (list (cons 'headline (split-string (substring s 1)))))
4277 (?# (list (cons 'custom-id (substring s 1))))
4278 ((let search (split-string s))
4279 (list (cons 'target search) (cons 'other search)))))
4281 (defun org-export-match-search-cell-p (datum cells)
4282 "Non-nil when DATUM matches search cells CELLS.
4283 DATUM is an element or object. CELLS is a list of search cells,
4284 as returned by `org-export-search-cells'."
4285 (let ((targets (org-export-search-cells datum)))
4286 (and targets (cl-some (lambda (cell) (member cell targets)) cells))))
4288 (defun org-export-resolve-fuzzy-link (link info)
4289 "Return LINK destination.
4291 INFO is a plist holding contextual information.
4293 Return value can be an object or an element:
4295 - If LINK path matches a target object (i.e. <<path>>) return it.
4297 - If LINK path exactly matches the name affiliated keyword
4298 (i.e. #+NAME: path) of an element, return that element.
4300 - If LINK path exactly matches any headline name, return that
4301 element.
4303 - Otherwise, throw an error.
4305 Assume LINK type is \"fuzzy\". White spaces are not
4306 significant."
4307 (let* ((search-cells (org-export-string-to-search-cell
4308 (org-link-unescape (org-element-property :path link))))
4309 (link-cache (or (plist-get info :resolve-fuzzy-link-cache)
4310 (let ((table (make-hash-table :test #'eq)))
4311 (plist-put info :resolve-fuzzy-link-cache table)
4312 table)))
4313 (cached (gethash search-cells link-cache 'not-found)))
4314 (if (not (eq cached 'not-found)) cached
4315 (let ((matches
4316 (org-element-map (plist-get info :parse-tree)
4317 (cons 'target org-element-all-elements)
4318 (lambda (datum)
4319 (and (org-export-match-search-cell-p datum search-cells)
4320 datum)))))
4321 (unless matches
4322 (signal 'org-link-broken (list (org-element-property :path link))))
4323 (puthash
4324 search-cells
4325 ;; There can be multiple matches for un-typed searches, i.e.,
4326 ;; for searches not starting with # or *. In this case,
4327 ;; prioritize targets and names over headline titles.
4328 ;; Matching both a name and a target is not valid, and
4329 ;; therefore undefined.
4330 (or (cl-some (lambda (datum)
4331 (and (not (eq (org-element-type datum) 'headline))
4332 datum))
4333 matches)
4334 (car matches))
4335 link-cache)))))
4337 (defun org-export-resolve-id-link (link info)
4338 "Return headline referenced as LINK destination.
4340 INFO is a plist used as a communication channel.
4342 Return value can be the headline element matched in current parse
4343 tree or a file name. Assume LINK type is either \"id\" or
4344 \"custom-id\". Throw an error if no match is found."
4345 (let ((id (org-element-property :path link)))
4346 ;; First check if id is within the current parse tree.
4347 (or (org-element-map (plist-get info :parse-tree) 'headline
4348 (lambda (headline)
4349 (when (or (equal (org-element-property :ID headline) id)
4350 (equal (org-element-property :CUSTOM_ID headline) id))
4351 headline))
4352 info 'first-match)
4353 ;; Otherwise, look for external files.
4354 (cdr (assoc id (plist-get info :id-alist)))
4355 (signal 'org-link-broken (list id)))))
4357 (defun org-export-resolve-radio-link (link info)
4358 "Return radio-target object referenced as LINK destination.
4360 INFO is a plist used as a communication channel.
4362 Return value can be a radio-target object or nil. Assume LINK
4363 has type \"radio\"."
4364 (let ((path (replace-regexp-in-string
4365 "[ \r\t\n]+" " " (org-element-property :path link))))
4366 (org-element-map (plist-get info :parse-tree) 'radio-target
4367 (lambda (radio)
4368 (and (eq (compare-strings
4369 (replace-regexp-in-string
4370 "[ \r\t\n]+" " " (org-element-property :value radio))
4371 nil nil path nil nil t)
4373 radio))
4374 info 'first-match)))
4376 (defun org-export-file-uri (filename)
4377 "Return file URI associated to FILENAME."
4378 (cond ((string-prefix-p "//" filename) (concat "file:" filename))
4379 ((not (file-name-absolute-p filename)) filename)
4380 ((org-file-remote-p filename) (concat "file:/" filename))
4382 (let ((fullname (expand-file-name filename)))
4383 (concat (if (string-prefix-p "/" fullname) "file://" "file:///")
4384 fullname)))))
4386 ;;;; For References
4388 ;; `org-export-get-reference' associate a unique reference for any
4389 ;; object or element. It uses `org-export-new-reference' and
4390 ;; `org-export-format-reference' to, respectively, generate new
4391 ;; internal references and turn them into a string suitable for
4392 ;; output.
4394 ;; `org-export-get-ordinal' associates a sequence number to any object
4395 ;; or element.
4397 (defun org-export-new-reference (references)
4398 "Return a unique reference, among REFERENCES.
4399 REFERENCES is an alist whose values are in-use references, as
4400 numbers. Returns a number, which is the internal representation
4401 of a reference. See also `org-export-format-reference'."
4402 ;; Generate random 7 digits hexadecimal numbers. Collisions
4403 ;; increase exponentially with the numbers of references. However,
4404 ;; the odds for encountering at least one collision with 1000 active
4405 ;; references in the same document are roughly 0.2%, so this
4406 ;; shouldn't be the bottleneck.
4407 (let ((new (random #x10000000)))
4408 (while (rassq new references) (setq new (random #x10000000)))
4409 new))
4411 (defun org-export-format-reference (reference)
4412 "Format REFERENCE into a string.
4413 REFERENCE is a number representing a reference, as returned by
4414 `org-export-new-reference', which see."
4415 (format "org%07x" reference))
4417 (defun org-export-get-reference (datum info)
4418 "Return a unique reference for DATUM, as a string.
4420 DATUM is either an element or an object. INFO is the current
4421 export state, as a plist.
4423 References for the current document are stored in
4424 `:internal-references' property. Its value is an alist with
4425 associations of the following types:
4427 (REFERENCE . DATUM) and (SEARCH-CELL . ID)
4429 REFERENCE is the reference string to be used for object or
4430 element DATUM. SEARCH-CELL is a search cell, as returned by
4431 `org-export-search-cells'. ID is a number or a string uniquely
4432 identifying DATUM within the document.
4434 This function also checks `:crossrefs' property for search cells
4435 matching DATUM before creating a new reference."
4436 (let ((cache (plist-get info :internal-references)))
4437 (or (car (rassq datum cache))
4438 (let* ((crossrefs (plist-get info :crossrefs))
4439 (cells (org-export-search-cells datum))
4440 ;; Preserve any pre-existing association between
4441 ;; a search cell and a reference, i.e., when some
4442 ;; previously published document referenced a location
4443 ;; within current file (see
4444 ;; `org-publish-resolve-external-link').
4446 ;; However, there is no guarantee that search cells are
4447 ;; unique, e.g., there might be duplicate custom ID or
4448 ;; two headings with the same title in the file.
4450 ;; As a consequence, before re-using any reference to
4451 ;; an element or object, we check that it doesn't refer
4452 ;; to a previous element or object.
4453 (new (or (cl-some
4454 (lambda (cell)
4455 (let ((stored (cdr (assoc cell crossrefs))))
4456 (when stored
4457 (let ((old (org-export-format-reference stored)))
4458 (and (not (assoc old cache)) stored)))))
4459 cells)
4460 (org-export-new-reference cache)))
4461 (reference-string (org-export-format-reference new)))
4462 ;; Cache contains both data already associated to
4463 ;; a reference and in-use internal references, so as to make
4464 ;; unique references.
4465 (dolist (cell cells) (push (cons cell new) cache))
4466 ;; Retain a direct association between reference string and
4467 ;; DATUM since (1) not every object or element can be given
4468 ;; a search cell (2) it permits quick lookup.
4469 (push (cons reference-string datum) cache)
4470 (plist-put info :internal-references cache)
4471 reference-string))))
4473 (defun org-export-get-ordinal (element info &optional types predicate)
4474 "Return ordinal number of an element or object.
4476 ELEMENT is the element or object considered. INFO is the plist
4477 used as a communication channel.
4479 Optional argument TYPES, when non-nil, is a list of element or
4480 object types, as symbols, that should also be counted in.
4481 Otherwise, only provided element's type is considered.
4483 Optional argument PREDICATE is a function returning a non-nil
4484 value if the current element or object should be counted in. It
4485 accepts two arguments: the element or object being considered and
4486 the plist used as a communication channel. This allows counting
4487 only a certain type of object (i.e. inline images).
4489 Return value is a list of numbers if ELEMENT is a headline or an
4490 item. It is nil for keywords. It represents the footnote number
4491 for footnote definitions and footnote references. If ELEMENT is
4492 a target, return the same value as if ELEMENT was the closest
4493 table, item or headline containing the target. In any other
4494 case, return the sequence number of ELEMENT among elements or
4495 objects of the same type."
4496 ;; Ordinal of a target object refer to the ordinal of the closest
4497 ;; table, item, or headline containing the object.
4498 (when (eq (org-element-type element) 'target)
4499 (setq element
4500 (org-element-lineage
4501 element
4502 '(footnote-definition footnote-reference headline item table))))
4503 (cl-case (org-element-type element)
4504 ;; Special case 1: A headline returns its number as a list.
4505 (headline (org-export-get-headline-number element info))
4506 ;; Special case 2: An item returns its number as a list.
4507 (item (let ((struct (org-element-property :structure element)))
4508 (org-list-get-item-number
4509 (org-element-property :begin element)
4510 struct
4511 (org-list-prevs-alist struct)
4512 (org-list-parents-alist struct))))
4513 ((footnote-definition footnote-reference)
4514 (org-export-get-footnote-number element info))
4515 (otherwise
4516 (let ((counter 0))
4517 ;; Increment counter until ELEMENT is found again.
4518 (org-element-map (plist-get info :parse-tree)
4519 (or types (org-element-type element))
4520 (lambda (el)
4521 (cond
4522 ((eq element el) (1+ counter))
4523 ((not predicate) (cl-incf counter) nil)
4524 ((funcall predicate el info) (cl-incf counter) nil)))
4525 info 'first-match)))))
4528 ;;;; For Src-Blocks
4530 ;; `org-export-get-loc' counts number of code lines accumulated in
4531 ;; src-block or example-block elements with a "+n" switch until
4532 ;; a given element, excluded. Note: "-n" switches reset that count.
4534 ;; `org-export-unravel-code' extracts source code (along with a code
4535 ;; references alist) from an `element-block' or `src-block' type
4536 ;; element.
4538 ;; `org-export-format-code' applies a formatting function to each line
4539 ;; of code, providing relative line number and code reference when
4540 ;; appropriate. Since it doesn't access the original element from
4541 ;; which the source code is coming, it expects from the code calling
4542 ;; it to know if lines should be numbered and if code references
4543 ;; should appear.
4545 ;; Eventually, `org-export-format-code-default' is a higher-level
4546 ;; function (it makes use of the two previous functions) which handles
4547 ;; line numbering and code references inclusion, and returns source
4548 ;; code in a format suitable for plain text or verbatim output.
4550 (defun org-export-get-loc (element info)
4551 "Return count of lines of code before ELEMENT.
4553 ELEMENT is an example-block or src-block element. INFO is the
4554 plist used as a communication channel.
4556 Count includes every line of code in example-block or src-block
4557 with a \"+n\" or \"-n\" switch before block. Return nil if
4558 ELEMENT doesn't allow line numbering."
4559 (pcase (org-element-property :number-lines element)
4560 (`(new . ,n) n)
4561 (`(continued . ,n)
4562 (let ((loc 0))
4563 (org-element-map (plist-get info :parse-tree) '(src-block example-block)
4564 (lambda (el)
4565 ;; ELEMENT is reached: Quit loop and return locs.
4566 (if (eq el element) (+ loc n)
4567 ;; Only count lines from src-block and example-block
4568 ;; elements with a "+n" or "-n" switch.
4569 (let ((linum (org-element-property :number-lines el)))
4570 (when linum
4571 (let ((lines (org-count-lines
4572 (org-element-property :value el))))
4573 ;; Accumulate locs or reset them.
4574 (pcase linum
4575 (`(new . ,n) (setq loc (+ n lines)))
4576 (`(continued . ,n) (cl-incf loc (+ n lines)))))))
4577 nil)) ;Return nil to stay in the loop.
4578 info 'first-match)))))
4580 (defun org-export-unravel-code (element)
4581 "Clean source code and extract references out of it.
4583 ELEMENT has either a `src-block' an `example-block' type.
4585 Return a cons cell whose CAR is the source code, cleaned from any
4586 reference, protective commas and spurious indentation, and CDR is
4587 an alist between relative line number (integer) and name of code
4588 reference on that line (string)."
4589 (let* ((line 0) refs
4590 (value (org-element-property :value element))
4591 ;; Remove global indentation from code, if necessary. Also
4592 ;; remove final newline character, since it doesn't belongs
4593 ;; to the code proper.
4594 (code (replace-regexp-in-string
4595 "\n\\'" ""
4596 (if (or org-src-preserve-indentation
4597 (org-element-property :preserve-indent element))
4598 value
4599 (org-remove-indentation value))))
4600 ;; Build a regexp matching a loc with a reference.
4601 (ref-re (org-src-coderef-regexp (org-src-coderef-format element))))
4602 ;; Return value.
4603 (cons
4604 ;; Code with references removed.
4605 (mapconcat
4606 (lambda (loc)
4607 (cl-incf line)
4608 (if (not (string-match ref-re loc)) loc
4609 ;; Ref line: remove ref, and add its position in REFS.
4610 (push (cons line (match-string 3 loc)) refs)
4611 (replace-match "" nil nil loc 1)))
4612 (split-string code "\n") "\n")
4613 ;; Reference alist.
4614 refs)))
4616 (defun org-export-format-code (code fun &optional num-lines ref-alist)
4617 "Format CODE by applying FUN line-wise and return it.
4619 CODE is a string representing the code to format. FUN is
4620 a function. It must accept three arguments: a line of
4621 code (string), the current line number (integer) or nil and the
4622 reference associated to the current line (string) or nil.
4624 Optional argument NUM-LINES can be an integer representing the
4625 number of code lines accumulated until the current code. Line
4626 numbers passed to FUN will take it into account. If it is nil,
4627 FUN's second argument will always be nil. This number can be
4628 obtained with `org-export-get-loc' function.
4630 Optional argument REF-ALIST can be an alist between relative line
4631 number (i.e. ignoring NUM-LINES) and the name of the code
4632 reference on it. If it is nil, FUN's third argument will always
4633 be nil. It can be obtained through the use of
4634 `org-export-unravel-code' function."
4635 (let ((--locs (split-string code "\n"))
4636 (--line 0))
4637 (concat
4638 (mapconcat
4639 (lambda (--loc)
4640 (cl-incf --line)
4641 (let ((--ref (cdr (assq --line ref-alist))))
4642 (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
4643 --locs "\n")
4644 "\n")))
4646 (defun org-export-format-code-default (element info)
4647 "Return source code from ELEMENT, formatted in a standard way.
4649 ELEMENT is either a `src-block' or `example-block' element. INFO
4650 is a plist used as a communication channel.
4652 This function takes care of line numbering and code references
4653 inclusion. Line numbers, when applicable, appear at the
4654 beginning of the line, separated from the code by two white
4655 spaces. Code references, on the other hand, appear flushed to
4656 the right, separated by six white spaces from the widest line of
4657 code."
4658 ;; Extract code and references.
4659 (let* ((code-info (org-export-unravel-code element))
4660 (code (car code-info))
4661 (code-lines (split-string code "\n")))
4662 (if (null code-lines) ""
4663 (let* ((refs (and (org-element-property :retain-labels element)
4664 (cdr code-info)))
4665 ;; Handle line numbering.
4666 (num-start (org-export-get-loc element info))
4667 (num-fmt
4668 (and num-start
4669 (format "%%%ds "
4670 (length (number-to-string
4671 (+ (length code-lines) num-start))))))
4672 ;; Prepare references display, if required. Any reference
4673 ;; should start six columns after the widest line of code,
4674 ;; wrapped with parenthesis.
4675 (max-width
4676 (+ (apply 'max (mapcar 'length code-lines))
4677 (if (not num-start) 0 (length (format num-fmt num-start))))))
4678 (org-export-format-code
4679 code
4680 (lambda (loc line-num ref)
4681 (let ((number-str (and num-fmt (format num-fmt line-num))))
4682 (concat
4683 number-str
4685 (and ref
4686 (concat (make-string (- (+ 6 max-width)
4687 (+ (length loc) (length number-str)))
4688 ?\s)
4689 (format "(%s)" ref))))))
4690 num-start refs)))))
4693 ;;;; For Tables
4695 ;; `org-export-table-has-special-column-p' and and
4696 ;; `org-export-table-row-is-special-p' are predicates used to look for
4697 ;; meta-information about the table structure.
4699 ;; `org-table-has-header-p' tells when the rows before the first rule
4700 ;; should be considered as table's header.
4702 ;; `org-export-table-cell-width', `org-export-table-cell-alignment'
4703 ;; and `org-export-table-cell-borders' extract information from
4704 ;; a table-cell element.
4706 ;; `org-export-table-dimensions' gives the number on rows and columns
4707 ;; in the table, ignoring horizontal rules and special columns.
4708 ;; `org-export-table-cell-address', given a table-cell object, returns
4709 ;; the absolute address of a cell. On the other hand,
4710 ;; `org-export-get-table-cell-at' does the contrary.
4712 ;; `org-export-table-cell-starts-colgroup-p',
4713 ;; `org-export-table-cell-ends-colgroup-p',
4714 ;; `org-export-table-row-starts-rowgroup-p',
4715 ;; `org-export-table-row-ends-rowgroup-p',
4716 ;; `org-export-table-row-starts-header-p',
4717 ;; `org-export-table-row-ends-header-p' and
4718 ;; `org-export-table-row-in-header-p' indicate position of current row
4719 ;; or cell within the table.
4721 (defun org-export-table-has-special-column-p (table)
4722 "Non-nil when TABLE has a special column.
4723 All special columns will be ignored during export."
4724 ;; The table has a special column when every first cell of every row
4725 ;; has an empty value or contains a symbol among "/", "#", "!", "$",
4726 ;; "*" "_" and "^". Though, do not consider a first column
4727 ;; containing only empty cells as special.
4728 (let ((special-column? 'empty))
4729 (catch 'exit
4730 (dolist (row (org-element-contents table))
4731 (when (eq (org-element-property :type row) 'standard)
4732 (let ((value (org-element-contents
4733 (car (org-element-contents row)))))
4734 (cond ((member value
4735 '(("/") ("#") ("!") ("$") ("*") ("_") ("^")))
4736 (setq special-column? 'special))
4737 ((null value))
4738 (t (throw 'exit nil))))))
4739 (eq special-column? 'special))))
4741 (defun org-export-table-has-header-p (table info)
4742 "Non-nil when TABLE has a header.
4744 INFO is a plist used as a communication channel.
4746 A table has a header when it contains at least two row groups."
4747 (let* ((cache (or (plist-get info :table-header-cache)
4748 (let ((table (make-hash-table :test #'eq)))
4749 (plist-put info :table-header-cache table)
4750 table)))
4751 (cached (gethash table cache 'no-cache)))
4752 (if (not (eq cached 'no-cache)) cached
4753 (let ((rowgroup 1) row-flag)
4754 (puthash table
4755 (org-element-map table 'table-row
4756 (lambda (row)
4757 (cond
4758 ((> rowgroup 1) t)
4759 ((and row-flag
4760 (eq (org-element-property :type row) 'rule))
4761 (cl-incf rowgroup)
4762 (setq row-flag nil))
4763 ((and (not row-flag)
4764 (eq (org-element-property :type row) 'standard))
4765 (setq row-flag t)
4766 nil)))
4767 info 'first-match)
4768 cache)))))
4770 (defun org-export-table-row-is-special-p (table-row _)
4771 "Non-nil if TABLE-ROW is considered special.
4772 All special rows will be ignored during export."
4773 (when (eq (org-element-property :type table-row) 'standard)
4774 (let ((first-cell (org-element-contents
4775 (car (org-element-contents table-row)))))
4776 ;; A row is special either when...
4778 ;; ... it starts with a field only containing "/",
4779 (equal first-cell '("/"))
4780 ;; ... the table contains a special column and the row start
4781 ;; with a marking character among, "^", "_", "$" or "!",
4782 (and (org-export-table-has-special-column-p
4783 (org-export-get-parent table-row))
4784 (member first-cell '(("^") ("_") ("$") ("!"))))
4785 ;; ... it contains only alignment cookies and empty cells.
4786 (let ((special-row-p 'empty))
4787 (catch 'exit
4788 (dolist (cell (org-element-contents table-row))
4789 (let ((value (org-element-contents cell)))
4790 ;; Since VALUE is a secondary string, the following
4791 ;; checks avoid expanding it with `org-export-data'.
4792 (cond ((not value))
4793 ((and (not (cdr value))
4794 (stringp (car value))
4795 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'"
4796 (car value)))
4797 (setq special-row-p 'cookie))
4798 (t (throw 'exit nil)))))
4799 (eq special-row-p 'cookie)))))))
4801 (defun org-export-table-row-group (table-row info)
4802 "Return TABLE-ROW's group number, as an integer.
4804 INFO is a plist used as the communication channel.
4806 Return value is the group number, as an integer, or nil for
4807 special rows and rows separators. First group is also table's
4808 header."
4809 (when (eq (org-element-property :type table-row) 'standard)
4810 (let* ((cache (or (plist-get info :table-row-group-cache)
4811 (let ((table (make-hash-table :test #'eq)))
4812 (plist-put info :table-row-group-cache table)
4813 table)))
4814 (cached (gethash table-row cache 'no-cache)))
4815 (if (not (eq cached 'no-cache)) cached
4816 ;; First time a row is queried, populate cache with all the
4817 ;; rows from the table.
4818 (let ((group 0) row-flag)
4819 (org-element-map (org-export-get-parent table-row) 'table-row
4820 (lambda (row)
4821 (if (eq (org-element-property :type row) 'rule)
4822 (setq row-flag nil)
4823 (unless row-flag (cl-incf group) (setq row-flag t))
4824 (puthash row group cache)))
4825 info))
4826 (gethash table-row cache)))))
4828 (defun org-export-table-cell-width (table-cell info)
4829 "Return TABLE-CELL contents width.
4831 INFO is a plist used as the communication channel.
4833 Return value is the width given by the last width cookie in the
4834 same column as TABLE-CELL, or nil."
4835 (let* ((row (org-export-get-parent table-cell))
4836 (table (org-export-get-parent row))
4837 (cells (org-element-contents row))
4838 (columns (length cells))
4839 (column (- columns (length (memq table-cell cells))))
4840 (cache (or (plist-get info :table-cell-width-cache)
4841 (let ((table (make-hash-table :test #'eq)))
4842 (plist-put info :table-cell-width-cache table)
4843 table)))
4844 (width-vector (or (gethash table cache)
4845 (puthash table (make-vector columns 'empty) cache)))
4846 (value (aref width-vector column)))
4847 (if (not (eq value 'empty)) value
4848 (let (cookie-width)
4849 (dolist (row (org-element-contents table)
4850 (aset width-vector column cookie-width))
4851 (when (org-export-table-row-is-special-p row info)
4852 ;; In a special row, try to find a width cookie at COLUMN.
4853 (let* ((value (org-element-contents
4854 (elt (org-element-contents row) column)))
4855 (cookie (car value)))
4856 ;; The following checks avoid expanding unnecessarily
4857 ;; the cell with `org-export-data'.
4858 (when (and value
4859 (not (cdr value))
4860 (stringp cookie)
4861 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'" cookie)
4862 (match-string 1 cookie))
4863 (setq cookie-width
4864 (string-to-number (match-string 1 cookie)))))))))))
4866 (defun org-export-table-cell-alignment (table-cell info)
4867 "Return TABLE-CELL contents alignment.
4869 INFO is a plist used as the communication channel.
4871 Return alignment as specified by the last alignment cookie in the
4872 same column as TABLE-CELL. If no such cookie is found, a default
4873 alignment value will be deduced from fraction of numbers in the
4874 column (see `org-table-number-fraction' for more information).
4875 Possible values are `left', `right' and `center'."
4876 ;; Load `org-table-number-fraction' and `org-table-number-regexp'.
4877 (require 'org-table)
4878 (let* ((row (org-export-get-parent table-cell))
4879 (table (org-export-get-parent row))
4880 (cells (org-element-contents row))
4881 (columns (length cells))
4882 (column (- columns (length (memq table-cell cells))))
4883 (cache (or (plist-get info :table-cell-alignment-cache)
4884 (let ((table (make-hash-table :test #'eq)))
4885 (plist-put info :table-cell-alignment-cache table)
4886 table)))
4887 (align-vector (or (gethash table cache)
4888 (puthash table (make-vector columns nil) cache))))
4889 (or (aref align-vector column)
4890 (let ((number-cells 0)
4891 (total-cells 0)
4892 cookie-align
4893 previous-cell-number-p)
4894 (dolist (row (org-element-contents (org-export-get-parent row)))
4895 (cond
4896 ;; In a special row, try to find an alignment cookie at
4897 ;; COLUMN.
4898 ((org-export-table-row-is-special-p row info)
4899 (let ((value (org-element-contents
4900 (elt (org-element-contents row) column))))
4901 ;; Since VALUE is a secondary string, the following
4902 ;; checks avoid useless expansion through
4903 ;; `org-export-data'.
4904 (when (and value
4905 (not (cdr value))
4906 (stringp (car value))
4907 (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'"
4908 (car value))
4909 (match-string 1 (car value)))
4910 (setq cookie-align (match-string 1 (car value))))))
4911 ;; Ignore table rules.
4912 ((eq (org-element-property :type row) 'rule))
4913 ;; In a standard row, check if cell's contents are
4914 ;; expressing some kind of number. Increase NUMBER-CELLS
4915 ;; accordingly. Though, don't bother if an alignment
4916 ;; cookie has already defined cell's alignment.
4917 ((not cookie-align)
4918 (let ((value (org-export-data
4919 (org-element-contents
4920 (elt (org-element-contents row) column))
4921 info)))
4922 (cl-incf total-cells)
4923 ;; Treat an empty cell as a number if it follows
4924 ;; a number.
4925 (if (not (or (string-match org-table-number-regexp value)
4926 (and (string= value "") previous-cell-number-p)))
4927 (setq previous-cell-number-p nil)
4928 (setq previous-cell-number-p t)
4929 (cl-incf number-cells))))))
4930 ;; Return value. Alignment specified by cookies has
4931 ;; precedence over alignment deduced from cell's contents.
4932 (aset align-vector
4933 column
4934 (cond ((equal cookie-align "l") 'left)
4935 ((equal cookie-align "r") 'right)
4936 ((equal cookie-align "c") 'center)
4937 ((>= (/ (float number-cells) total-cells)
4938 org-table-number-fraction)
4939 'right)
4940 (t 'left)))))))
4942 (defun org-export-table-cell-borders (table-cell info)
4943 "Return TABLE-CELL borders.
4945 INFO is a plist used as a communication channel.
4947 Return value is a list of symbols, or nil. Possible values are:
4948 `top', `bottom', `above', `below', `left' and `right'. Note:
4949 `top' (resp. `bottom') only happen for a cell in the first
4950 row (resp. last row) of the table, ignoring table rules, if any.
4952 Returned borders ignore special rows."
4953 (let* ((row (org-export-get-parent table-cell))
4954 (table (org-export-get-parent-table table-cell))
4955 borders)
4956 ;; Top/above border? TABLE-CELL has a border above when a rule
4957 ;; used to demarcate row groups can be found above. Hence,
4958 ;; finding a rule isn't sufficient to push `above' in BORDERS:
4959 ;; another regular row has to be found above that rule.
4960 (let (rule-flag)
4961 (catch 'exit
4962 ;; Look at every row before the current one.
4963 (dolist (row (cdr (memq row (reverse (org-element-contents table)))))
4964 (cond ((eq (org-element-property :type row) 'rule)
4965 (setq rule-flag t))
4966 ((not (org-export-table-row-is-special-p row info))
4967 (if rule-flag (throw 'exit (push 'above borders))
4968 (throw 'exit nil)))))
4969 ;; No rule above, or rule found starts the table (ignoring any
4970 ;; special row): TABLE-CELL is at the top of the table.
4971 (when rule-flag (push 'above borders))
4972 (push 'top borders)))
4973 ;; Bottom/below border? TABLE-CELL has a border below when next
4974 ;; non-regular row below is a rule.
4975 (let (rule-flag)
4976 (catch 'exit
4977 ;; Look at every row after the current one.
4978 (dolist (row (cdr (memq row (org-element-contents table))))
4979 (cond ((eq (org-element-property :type row) 'rule)
4980 (setq rule-flag t))
4981 ((not (org-export-table-row-is-special-p row info))
4982 (if rule-flag (throw 'exit (push 'below borders))
4983 (throw 'exit nil)))))
4984 ;; No rule below, or rule found ends the table (modulo some
4985 ;; special row): TABLE-CELL is at the bottom of the table.
4986 (when rule-flag (push 'below borders))
4987 (push 'bottom borders)))
4988 ;; Right/left borders? They can only be specified by column
4989 ;; groups. Column groups are defined in a row starting with "/".
4990 ;; Also a column groups row only contains "<", "<>", ">" or blank
4991 ;; cells.
4992 (catch 'exit
4993 (let ((column (let ((cells (org-element-contents row)))
4994 (- (length cells) (length (memq table-cell cells))))))
4995 ;; Table rows are read in reverse order so last column groups
4996 ;; row has precedence over any previous one.
4997 (dolist (row (reverse (org-element-contents table)))
4998 (unless (eq (org-element-property :type row) 'rule)
4999 (when (equal (org-element-contents
5000 (car (org-element-contents row)))
5001 '("/"))
5002 (let ((column-groups
5003 (mapcar
5004 (lambda (cell)
5005 (let ((value (org-element-contents cell)))
5006 (when (member value '(("<") ("<>") (">") nil))
5007 (car value))))
5008 (org-element-contents row))))
5009 ;; There's a left border when previous cell, if
5010 ;; any, ends a group, or current one starts one.
5011 (when (or (and (not (zerop column))
5012 (member (elt column-groups (1- column))
5013 '(">" "<>")))
5014 (member (elt column-groups column) '("<" "<>")))
5015 (push 'left borders))
5016 ;; There's a right border when next cell, if any,
5017 ;; starts a group, or current one ends one.
5018 (when (or (and (/= (1+ column) (length column-groups))
5019 (member (elt column-groups (1+ column))
5020 '("<" "<>")))
5021 (member (elt column-groups column) '(">" "<>")))
5022 (push 'right borders))
5023 (throw 'exit nil)))))))
5024 ;; Return value.
5025 borders))
5027 (defun org-export-table-cell-starts-colgroup-p (table-cell info)
5028 "Non-nil when TABLE-CELL is at the beginning of a column group.
5029 INFO is a plist used as a communication channel."
5030 ;; A cell starts a column group either when it is at the beginning
5031 ;; of a row (or after the special column, if any) or when it has
5032 ;; a left border.
5033 (or (eq (org-element-map (org-export-get-parent table-cell) 'table-cell
5034 'identity info 'first-match)
5035 table-cell)
5036 (memq 'left (org-export-table-cell-borders table-cell info))))
5038 (defun org-export-table-cell-ends-colgroup-p (table-cell info)
5039 "Non-nil when TABLE-CELL is at the end of a column group.
5040 INFO is a plist used as a communication channel."
5041 ;; A cell ends a column group either when it is at the end of a row
5042 ;; or when it has a right border.
5043 (or (eq (car (last (org-element-contents
5044 (org-export-get-parent table-cell))))
5045 table-cell)
5046 (memq 'right (org-export-table-cell-borders table-cell info))))
5048 (defun org-export-table-row-starts-rowgroup-p (table-row info)
5049 "Non-nil when TABLE-ROW is at the beginning of a row group.
5050 INFO is a plist used as a communication channel."
5051 (unless (or (eq (org-element-property :type table-row) 'rule)
5052 (org-export-table-row-is-special-p table-row info))
5053 (let ((borders (org-export-table-cell-borders
5054 (car (org-element-contents table-row)) info)))
5055 (or (memq 'top borders) (memq 'above borders)))))
5057 (defun org-export-table-row-ends-rowgroup-p (table-row info)
5058 "Non-nil when TABLE-ROW is at the end of a row group.
5059 INFO is a plist used as a communication channel."
5060 (unless (or (eq (org-element-property :type table-row) 'rule)
5061 (org-export-table-row-is-special-p table-row info))
5062 (let ((borders (org-export-table-cell-borders
5063 (car (org-element-contents table-row)) info)))
5064 (or (memq 'bottom borders) (memq 'below borders)))))
5066 (defun org-export-table-row-in-header-p (table-row info)
5067 "Non-nil when TABLE-ROW is located within table's header.
5068 INFO is a plist used as a communication channel. Always return
5069 nil for special rows and rows separators."
5070 (and (org-export-table-has-header-p
5071 (org-export-get-parent-table table-row) info)
5072 (eql (org-export-table-row-group table-row info) 1)))
5074 (defun org-export-table-row-starts-header-p (table-row info)
5075 "Non-nil when TABLE-ROW is the first table header's row.
5076 INFO is a plist used as a communication channel."
5077 (and (org-export-table-row-in-header-p table-row info)
5078 (org-export-table-row-starts-rowgroup-p table-row info)))
5080 (defun org-export-table-row-ends-header-p (table-row info)
5081 "Non-nil when TABLE-ROW is the last table header's row.
5082 INFO is a plist used as a communication channel."
5083 (and (org-export-table-row-in-header-p table-row info)
5084 (org-export-table-row-ends-rowgroup-p table-row info)))
5086 (defun org-export-table-row-number (table-row info)
5087 "Return TABLE-ROW number.
5088 INFO is a plist used as a communication channel. Return value is
5089 zero-indexed and ignores separators. The function returns nil
5090 for special rows and separators."
5091 (when (eq (org-element-property :type table-row) 'standard)
5092 (let* ((cache (or (plist-get info :table-row-number-cache)
5093 (let ((table (make-hash-table :test #'eq)))
5094 (plist-put info :table-row-number-cache table)
5095 table)))
5096 (cached (gethash table-row cache 'no-cache)))
5097 (if (not (eq cached 'no-cache)) cached
5098 ;; First time a row is queried, populate cache with all the
5099 ;; rows from the table.
5100 (let ((number -1))
5101 (org-element-map (org-export-get-parent-table table-row) 'table-row
5102 (lambda (row)
5103 (when (eq (org-element-property :type row) 'standard)
5104 (puthash row (cl-incf number) cache)))
5105 info))
5106 (gethash table-row cache)))))
5108 (defun org-export-table-dimensions (table info)
5109 "Return TABLE dimensions.
5111 INFO is a plist used as a communication channel.
5113 Return value is a CONS like (ROWS . COLUMNS) where
5114 ROWS (resp. COLUMNS) is the number of exportable
5115 rows (resp. columns)."
5116 (let (first-row (columns 0) (rows 0))
5117 ;; Set number of rows, and extract first one.
5118 (org-element-map table 'table-row
5119 (lambda (row)
5120 (when (eq (org-element-property :type row) 'standard)
5121 (cl-incf rows)
5122 (unless first-row (setq first-row row)))) info)
5123 ;; Set number of columns.
5124 (org-element-map first-row 'table-cell (lambda (_) (cl-incf columns)) info)
5125 ;; Return value.
5126 (cons rows columns)))
5128 (defun org-export-table-cell-address (table-cell info)
5129 "Return address of a regular TABLE-CELL object.
5131 TABLE-CELL is the cell considered. INFO is a plist used as
5132 a communication channel.
5134 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
5135 zero-based index. Only exportable cells are considered. The
5136 function returns nil for other cells."
5137 (let* ((table-row (org-export-get-parent table-cell))
5138 (row-number (org-export-table-row-number table-row info)))
5139 (when row-number
5140 (cons row-number
5141 (let ((col-count 0))
5142 (org-element-map table-row 'table-cell
5143 (lambda (cell)
5144 (if (eq cell table-cell) col-count (cl-incf col-count) nil))
5145 info 'first-match))))))
5147 (defun org-export-get-table-cell-at (address table info)
5148 "Return regular table-cell object at ADDRESS in TABLE.
5150 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
5151 zero-based index. TABLE is a table type element. INFO is
5152 a plist used as a communication channel.
5154 If no table-cell, among exportable cells, is found at ADDRESS,
5155 return nil."
5156 (let ((column-pos (cdr address)) (column-count 0))
5157 (org-element-map
5158 ;; Row at (car address) or nil.
5159 (let ((row-pos (car address)) (row-count 0))
5160 (org-element-map table 'table-row
5161 (lambda (row)
5162 (cond ((eq (org-element-property :type row) 'rule) nil)
5163 ((= row-count row-pos) row)
5164 (t (cl-incf row-count) nil)))
5165 info 'first-match))
5166 'table-cell
5167 (lambda (cell)
5168 (if (= column-count column-pos) cell
5169 (cl-incf column-count) nil))
5170 info 'first-match)))
5173 ;;;; For Tables of Contents
5175 ;; `org-export-collect-headlines' builds a list of all exportable
5176 ;; headline elements, maybe limited to a certain depth. One can then
5177 ;; easily parse it and transcode it.
5179 ;; Building lists of tables, figures or listings is quite similar.
5180 ;; Once the generic function `org-export-collect-elements' is defined,
5181 ;; `org-export-collect-tables', `org-export-collect-figures' and
5182 ;; `org-export-collect-listings' can be derived from it.
5184 ;; `org-export-toc-entry-backend' builds a special anonymous back-end
5185 ;; useful to export table of contents' entries.
5187 (defun org-export-collect-headlines (info &optional n scope)
5188 "Collect headlines in order to build a table of contents.
5190 INFO is a plist used as a communication channel.
5192 When optional argument N is an integer, it specifies the depth of
5193 the table of contents. Otherwise, it is set to the value of the
5194 last headline level. See `org-export-headline-levels' for more
5195 information.
5197 Optional argument SCOPE, when non-nil, is an element. If it is
5198 a headline, only children of SCOPE are collected. Otherwise,
5199 collect children of the headline containing provided element. If
5200 there is no such headline, collect all headlines. In any case,
5201 argument N becomes relative to the level of that headline.
5203 Return a list of all exportable headlines as parsed elements.
5204 Footnote sections are ignored."
5205 (let* ((scope (cond ((not scope) (plist-get info :parse-tree))
5206 ((eq (org-element-type scope) 'headline) scope)
5207 ((org-export-get-parent-headline scope))
5208 (t (plist-get info :parse-tree))))
5209 (limit (plist-get info :headline-levels))
5210 (n (if (not (wholenump n)) limit
5211 (min (if (eq (org-element-type scope) 'org-data) n
5212 (+ (org-export-get-relative-level scope info) n))
5213 limit))))
5214 (org-element-map (org-element-contents scope) 'headline
5215 (lambda (h)
5216 (and (not (org-element-property :footnote-section-p h))
5217 (not (equal "notoc"
5218 (org-export-get-node-property :UNNUMBERED h t)))
5219 (>= n (org-export-get-relative-level h info))
5221 info)))
5223 (defun org-export-collect-elements (type info &optional predicate)
5224 "Collect referenceable elements of a determined type.
5226 TYPE can be a symbol or a list of symbols specifying element
5227 types to search. Only elements with a caption are collected.
5229 INFO is a plist used as a communication channel.
5231 When non-nil, optional argument PREDICATE is a function accepting
5232 one argument, an element of type TYPE. It returns a non-nil
5233 value when that element should be collected.
5235 Return a list of all elements found, in order of appearance."
5236 (org-element-map (plist-get info :parse-tree) type
5237 (lambda (element)
5238 (and (org-element-property :caption element)
5239 (or (not predicate) (funcall predicate element))
5240 element))
5241 info))
5243 (defun org-export-collect-tables (info)
5244 "Build a list of tables.
5245 INFO is a plist used as a communication channel.
5247 Return a list of table elements with a caption."
5248 (org-export-collect-elements 'table info))
5250 (defun org-export-collect-figures (info predicate)
5251 "Build a list of figures.
5253 INFO is a plist used as a communication channel. PREDICATE is
5254 a function which accepts one argument: a paragraph element and
5255 whose return value is non-nil when that element should be
5256 collected.
5258 A figure is a paragraph type element, with a caption, verifying
5259 PREDICATE. The latter has to be provided since a \"figure\" is
5260 a vague concept that may depend on back-end.
5262 Return a list of elements recognized as figures."
5263 (org-export-collect-elements 'paragraph info predicate))
5265 (defun org-export-collect-listings (info)
5266 "Build a list of src blocks.
5268 INFO is a plist used as a communication channel.
5270 Return a list of src-block elements with a caption."
5271 (org-export-collect-elements 'src-block info))
5273 (defun org-export-excluded-from-toc-p (headline info)
5274 "Non-nil if HEADLINE should be excluded from tables of contents.
5276 INFO is a plist used as a communication channel.
5278 Note that such headlines are already excluded from
5279 `org-export-collect-headlines'. Therefore, this function is not
5280 necessary if you only need to list headlines in the table of
5281 contents. However, it is useful if some additional processing is
5282 required on headlines excluded from table of contents."
5283 (or (org-element-property :footnote-section-p headline)
5284 (org-export-low-level-p headline info)
5285 (equal "notoc" (org-export-get-node-property :UNNUMBERED headline t))))
5287 (defun org-export-toc-entry-backend (parent &rest transcoders)
5288 "Return an export back-end appropriate for table of contents entries.
5290 PARENT is an export back-end the returned back-end should inherit
5291 from.
5293 By default, the back-end removes footnote references and targets.
5294 It also changes links and radio targets into regular text.
5295 TRANSCODERS optional argument, when non-nil, specifies additional
5296 transcoders. A transcoder follows the pattern (TYPE . FUNCTION)
5297 where type is an element or object type and FUNCTION the function
5298 transcoding it."
5299 (declare (indent 1))
5300 (org-export-create-backend
5301 :parent parent
5302 :transcoders
5303 (append transcoders
5304 `((footnote-reference . ,#'ignore)
5305 (link . ,(lambda (l c i)
5306 (or c
5307 (org-export-data
5308 (org-element-property :raw-link l)
5309 i))))
5310 (radio-target . ,(lambda (_r c _) c))
5311 (target . ,#'ignore)))))
5314 ;;;; Smart Quotes
5316 ;; The main function for the smart quotes sub-system is
5317 ;; `org-export-activate-smart-quotes', which replaces every quote in
5318 ;; a given string from the parse tree with its "smart" counterpart.
5320 ;; Dictionary for smart quotes is stored in
5321 ;; `org-export-smart-quotes-alist'.
5323 (defconst org-export-smart-quotes-alist
5324 '(("ar"
5325 (primary-opening
5326 :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5327 :texinfo "@guillemetleft{}")
5328 (primary-closing
5329 :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5330 :texinfo "@guillemetright{}")
5331 (secondary-opening :utf-8 "‹" :html "&lsaquo;" :latex "\\guilsinglleft{}"
5332 :texinfo "@guilsinglleft{}")
5333 (secondary-closing :utf-8 "›" :html "&rsaquo;" :latex "\\guilsinglright{}"
5334 :texinfo "@guilsinglright{}")
5335 (apostrophe :utf-8 "’" :html "&rsquo;"))
5336 ("da"
5337 ;; one may use: »...«, "...", ›...‹, or '...'.
5338 ;; http://sproget.dk/raad-og-regler/retskrivningsregler/retskrivningsregler/a7-40-60/a7-58-anforselstegn/
5339 ;; LaTeX quotes require Babel!
5340 (primary-opening
5341 :utf-8 "»" :html "&raquo;" :latex ">>" :texinfo "@guillemetright{}")
5342 (primary-closing
5343 :utf-8 "«" :html "&laquo;" :latex "<<" :texinfo "@guillemetleft{}")
5344 (secondary-opening
5345 :utf-8 "›" :html "&rsaquo;" :latex "\\frq{}" :texinfo "@guilsinglright{}")
5346 (secondary-closing
5347 :utf-8 "‹" :html "&lsaquo;" :latex "\\flq{}" :texinfo "@guilsingleft{}")
5348 (apostrophe :utf-8 "’" :html "&rsquo;"))
5349 ("de"
5350 (primary-opening
5351 :utf-8 "„" :html "&bdquo;" :latex "\"`" :texinfo "@quotedblbase{}")
5352 (primary-closing
5353 :utf-8 "“" :html "&ldquo;" :latex "\"'" :texinfo "@quotedblleft{}")
5354 (secondary-opening
5355 :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}" :texinfo "@quotesinglbase{}")
5356 (secondary-closing
5357 :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}" :texinfo "@quoteleft{}")
5358 (apostrophe :utf-8 "’" :html "&rsquo;"))
5359 ("en"
5360 (primary-opening :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
5361 (primary-closing :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
5362 (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5363 (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5364 (apostrophe :utf-8 "’" :html "&rsquo;"))
5365 ("es"
5366 (primary-opening
5367 :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5368 :texinfo "@guillemetleft{}")
5369 (primary-closing
5370 :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5371 :texinfo "@guillemetright{}")
5372 (secondary-opening :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
5373 (secondary-closing :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
5374 (apostrophe :utf-8 "’" :html "&rsquo;"))
5375 ("fr"
5376 (primary-opening
5377 :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
5378 :texinfo "@guillemetleft{}@tie{}")
5379 (primary-closing
5380 :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
5381 :texinfo "@tie{}@guillemetright{}")
5382 (secondary-opening
5383 :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
5384 :texinfo "@guillemetleft{}@tie{}")
5385 (secondary-closing :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
5386 :texinfo "@tie{}@guillemetright{}")
5387 (apostrophe :utf-8 "’" :html "&rsquo;"))
5388 ("is"
5389 (primary-opening
5390 :utf-8 "„" :html "&bdquo;" :latex "\"`" :texinfo "@quotedblbase{}")
5391 (primary-closing
5392 :utf-8 "“" :html "&ldquo;" :latex "\"'" :texinfo "@quotedblleft{}")
5393 (secondary-opening
5394 :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}" :texinfo "@quotesinglbase{}")
5395 (secondary-closing
5396 :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}" :texinfo "@quoteleft{}")
5397 (apostrophe :utf-8 "’" :html "&rsquo;"))
5398 ("no"
5399 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5400 (primary-opening
5401 :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5402 :texinfo "@guillemetleft{}")
5403 (primary-closing
5404 :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5405 :texinfo "@guillemetright{}")
5406 (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5407 (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5408 (apostrophe :utf-8 "’" :html "&rsquo;"))
5409 ("nb"
5410 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5411 (primary-opening
5412 :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5413 :texinfo "@guillemetleft{}")
5414 (primary-closing
5415 :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5416 :texinfo "@guillemetright{}")
5417 (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5418 (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5419 (apostrophe :utf-8 "’" :html "&rsquo;"))
5420 ("nn"
5421 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5422 (primary-opening
5423 :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5424 :texinfo "@guillemetleft{}")
5425 (primary-closing
5426 :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5427 :texinfo "@guillemetright{}")
5428 (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5429 (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5430 (apostrophe :utf-8 "’" :html "&rsquo;"))
5431 ("ru"
5432 ;; http://ru.wikipedia.org/wiki/%D0%9A%D0%B0%D0%B2%D1%8B%D1%87%D0%BA%D0%B8#.D0.9A.D0.B0.D0.B2.D1.8B.D1.87.D0.BA.D0.B8.2C_.D0.B8.D1.81.D0.BF.D0.BE.D0.BB.D1.8C.D0.B7.D1.83.D0.B5.D0.BC.D1.8B.D0.B5_.D0.B2_.D1.80.D1.83.D1.81.D1.81.D0.BA.D0.BE.D0.BC_.D1.8F.D0.B7.D1.8B.D0.BA.D0.B5
5433 ;; http://www.artlebedev.ru/kovodstvo/sections/104/
5434 (primary-opening :utf-8 "«" :html "&laquo;" :latex "{}<<"
5435 :texinfo "@guillemetleft{}")
5436 (primary-closing :utf-8 "»" :html "&raquo;" :latex ">>{}"
5437 :texinfo "@guillemetright{}")
5438 (secondary-opening
5439 :utf-8 "„" :html "&bdquo;" :latex "\\glqq{}" :texinfo "@quotedblbase{}")
5440 (secondary-closing
5441 :utf-8 "“" :html "&ldquo;" :latex "\\grqq{}" :texinfo "@quotedblleft{}")
5442 (apostrophe :utf-8 "’" :html: "&#39;"))
5443 ("sl"
5444 ;; Based on https://sl.wikipedia.org/wiki/Narekovaj
5445 (primary-opening :utf-8 "«" :html "&laquo;" :latex "{}<<"
5446 :texinfo "@guillemetleft{}")
5447 (primary-closing :utf-8 "»" :html "&raquo;" :latex ">>{}"
5448 :texinfo "@guillemetright{}")
5449 (secondary-opening
5450 :utf-8 "„" :html "&bdquo;" :latex "\\glqq{}" :texinfo "@quotedblbase{}")
5451 (secondary-closing
5452 :utf-8 "“" :html "&ldquo;" :latex "\\grqq{}" :texinfo "@quotedblleft{}")
5453 (apostrophe :utf-8 "’" :html "&rsquo;"))
5454 ("sv"
5455 ;; Based on https://sv.wikipedia.org/wiki/Citattecken
5456 (primary-opening :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
5457 (primary-closing :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
5458 (secondary-opening :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "`")
5459 (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "'")
5460 (apostrophe :utf-8 "’" :html "&rsquo;")))
5461 "Smart quotes translations.
5463 Alist whose CAR is a language string and CDR is an alist with
5464 quote type as key and a plist associating various encodings to
5465 their translation as value.
5467 A quote type can be any symbol among `primary-opening',
5468 `primary-closing', `secondary-opening', `secondary-closing' and
5469 `apostrophe'.
5471 Valid encodings include `:utf-8', `:html', `:latex' and
5472 `:texinfo'.
5474 If no translation is found, the quote character is left as-is.")
5476 (defun org-export--smart-quote-status (s info)
5477 "Return smart quote status at the beginning of string S.
5478 INFO is the current export state, as a plist."
5479 (let* ((parent (org-element-property :parent s))
5480 (cache (or (plist-get info :smart-quote-cache)
5481 (let ((table (make-hash-table :test #'eq)))
5482 (plist-put info :smart-quote-cache table)
5483 table)))
5484 (value (gethash parent cache 'missing-data)))
5485 (if (not (eq value 'missing-data)) (cdr (assq s value))
5486 (let (level1-open full-status)
5487 (org-element-map
5488 (let ((secondary (org-element-secondary-p s)))
5489 (if secondary (org-element-property secondary parent)
5490 (org-element-contents parent)))
5491 'plain-text
5492 (lambda (text)
5493 (let ((start 0) current-status)
5494 (while (setq start (string-match "['\"]" text start))
5495 (push
5496 (cond
5497 ((equal (match-string 0 text) "\"")
5498 (setf level1-open (not level1-open))
5499 (if level1-open 'primary-opening 'primary-closing))
5500 ;; Not already in a level 1 quote: this is an
5501 ;; apostrophe.
5502 ((not level1-open) 'apostrophe)
5503 ;; Extract previous char and next char. As
5504 ;; a special case, they can also be set to `blank',
5505 ;; `no-blank' or nil. Then determine if current
5506 ;; match is allowed as an opening quote or a closing
5507 ;; quote.
5509 (let* ((previous
5510 (if (> start 0) (substring text (1- start) start)
5511 (let ((p (org-export-get-previous-element
5512 text info)))
5513 (cond ((not p) nil)
5514 ((stringp p) (substring p -1))
5515 ((memq (org-element-property :post-blank p)
5516 '(0 nil))
5517 'no-blank)
5518 (t 'blank)))))
5519 (next
5520 (if (< (1+ start) (length text))
5521 (substring text (1+ start) (+ start 2))
5522 (let ((n (org-export-get-next-element text info)))
5523 (cond ((not n) nil)
5524 ((stringp n) (substring n 0 1))
5525 (t 'no-blank)))))
5526 (allow-open
5527 (and (if (stringp previous)
5528 (string-match "\\s\"\\|\\s-\\|\\s("
5529 previous)
5530 (memq previous '(blank nil)))
5531 (if (stringp next)
5532 (string-match "\\w\\|\\s.\\|\\s_" next)
5533 (eq next 'no-blank))))
5534 (allow-close
5535 (and (if (stringp previous)
5536 (string-match "\\w\\|\\s.\\|\\s_" previous)
5537 (eq previous 'no-blank))
5538 (if (stringp next)
5539 (string-match "\\s-\\|\\s)\\|\\s.\\|\\s\""
5540 next)
5541 (memq next '(blank nil))))))
5542 (cond
5543 ((and allow-open allow-close) (error "Should not happen"))
5544 (allow-open 'secondary-opening)
5545 (allow-close 'secondary-closing)
5546 (t 'apostrophe)))))
5547 current-status)
5548 (cl-incf start))
5549 (when current-status
5550 (push (cons text (nreverse current-status)) full-status))))
5551 info nil org-element-recursive-objects)
5552 (puthash parent full-status cache)
5553 (cdr (assq s full-status))))))
5555 (defun org-export-activate-smart-quotes (s encoding info &optional original)
5556 "Replace regular quotes with \"smart\" quotes in string S.
5558 ENCODING is a symbol among `:html', `:latex', `:texinfo' and
5559 `:utf-8'. INFO is a plist used as a communication channel.
5561 The function has to retrieve information about string
5562 surroundings in parse tree. It can only happen with an
5563 unmodified string. Thus, if S has already been through another
5564 process, a non-nil ORIGINAL optional argument will provide that
5565 original string.
5567 Return the new string."
5568 (let ((quote-status
5569 (copy-sequence (org-export--smart-quote-status (or original s) info))))
5570 (replace-regexp-in-string
5571 "['\"]"
5572 (lambda (match)
5573 (or (plist-get
5574 (cdr (assq (pop quote-status)
5575 (cdr (assoc (plist-get info :language)
5576 org-export-smart-quotes-alist))))
5577 encoding)
5578 match))
5579 s nil t)))
5581 ;;;; Topology
5583 ;; Here are various functions to retrieve information about the
5584 ;; neighborhood of a given element or object. Neighbors of interest
5585 ;; are direct parent (`org-export-get-parent'), parent headline
5586 ;; (`org-export-get-parent-headline'), first element containing an
5587 ;; object, (`org-export-get-parent-element'), parent table
5588 ;; (`org-export-get-parent-table'), previous element or object
5589 ;; (`org-export-get-previous-element') and next element or object
5590 ;; (`org-export-get-next-element').
5592 ;; defsubst org-export-get-parent must be defined before first use
5594 (defun org-export-get-parent-headline (blob)
5595 "Return BLOB parent headline or nil.
5596 BLOB is the element or object being considered."
5597 (org-element-lineage blob '(headline)))
5599 (defun org-export-get-parent-element (object)
5600 "Return first element containing OBJECT or nil.
5601 OBJECT is the object to consider."
5602 (org-element-lineage object org-element-all-elements))
5604 (defun org-export-get-parent-table (object)
5605 "Return OBJECT parent table or nil.
5606 OBJECT is either a `table-cell' or `table-element' type object."
5607 (org-element-lineage object '(table)))
5609 (defun org-export-get-previous-element (blob info &optional n)
5610 "Return previous element or object.
5612 BLOB is an element or object. INFO is a plist used as
5613 a communication channel. Return previous exportable element or
5614 object, a string, or nil.
5616 When optional argument N is a positive integer, return a list
5617 containing up to N siblings before BLOB, from farthest to
5618 closest. With any other non-nil value, return a list containing
5619 all of them."
5620 (let* ((secondary (org-element-secondary-p blob))
5621 (parent (org-export-get-parent blob))
5622 (siblings
5623 (if secondary (org-element-property secondary parent)
5624 (org-element-contents parent)))
5625 prev)
5626 (catch 'exit
5627 (dolist (obj (cdr (memq blob (reverse siblings))) prev)
5628 (cond ((memq obj (plist-get info :ignore-list)))
5629 ((null n) (throw 'exit obj))
5630 ((not (wholenump n)) (push obj prev))
5631 ((zerop n) (throw 'exit prev))
5632 (t (cl-decf n) (push obj prev)))))))
5634 (defun org-export-get-next-element (blob info &optional n)
5635 "Return next element or object.
5637 BLOB is an element or object. INFO is a plist used as
5638 a communication channel. Return next exportable element or
5639 object, a string, or nil.
5641 When optional argument N is a positive integer, return a list
5642 containing up to N siblings after BLOB, from closest to farthest.
5643 With any other non-nil value, return a list containing all of
5644 them."
5645 (let* ((secondary (org-element-secondary-p blob))
5646 (parent (org-export-get-parent blob))
5647 (siblings
5648 (cdr (memq blob
5649 (if secondary (org-element-property secondary parent)
5650 (org-element-contents parent)))))
5651 next)
5652 (catch 'exit
5653 (dolist (obj siblings (nreverse next))
5654 (cond ((memq obj (plist-get info :ignore-list)))
5655 ((null n) (throw 'exit obj))
5656 ((not (wholenump n)) (push obj next))
5657 ((zerop n) (throw 'exit (nreverse next)))
5658 (t (cl-decf n) (push obj next)))))))
5661 ;;;; Translation
5663 ;; `org-export-translate' translates a string according to the language
5664 ;; specified by the LANGUAGE keyword. `org-export-dictionary' contains
5665 ;; the dictionary used for the translation.
5667 (defconst org-export-dictionary
5668 '(("%e %n: %c"
5669 ("fr" :default "%e %n : %c" :html "%e&nbsp;%n&nbsp;: %c"))
5670 ("Author"
5671 ("ar" :default "تأليف")
5672 ("ca" :default "Autor")
5673 ("cs" :default "Autor")
5674 ("da" :default "Forfatter")
5675 ("de" :default "Autor")
5676 ("eo" :html "A&#365;toro")
5677 ("es" :default "Autor")
5678 ("et" :default "Autor")
5679 ("fi" :html "Tekij&auml;")
5680 ("fr" :default "Auteur")
5681 ("hu" :default "Szerz&otilde;")
5682 ("is" :html "H&ouml;fundur")
5683 ("it" :default "Autore")
5684 ("ja" :default "著者" :html "&#33879;&#32773;")
5685 ("nl" :default "Auteur")
5686 ("no" :default "Forfatter")
5687 ("nb" :default "Forfatter")
5688 ("nn" :default "Forfattar")
5689 ("pl" :default "Autor")
5690 ("pt_BR" :default "Autor")
5691 ("ru" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5692 ("sl" :default "Avtor")
5693 ("sv" :html "F&ouml;rfattare")
5694 ("uk" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5695 ("zh-CN" :html "&#20316;&#32773;" :utf-8 "作者")
5696 ("zh-TW" :html "&#20316;&#32773;" :utf-8 "作者"))
5697 ("Continued from previous page"
5698 ("ar" :default "تتمة الصفحة السابقة")
5699 ("cs" :default "Pokračování z předchozí strany")
5700 ("de" :default "Fortsetzung von vorheriger Seite")
5701 ("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")
5702 ("fr" :default "Suite de la page précédente")
5703 ("it" :default "Continua da pagina precedente")
5704 ("ja" :default "前ページからの続き")
5705 ("nl" :default "Vervolg van vorige pagina")
5706 ("pt" :default "Continuação da página anterior")
5707 ("ru" :html "(&#1055;&#1088;&#1086;&#1076;&#1086;&#1083;&#1078;&#1077;&#1085;&#1080;&#1077;)"
5708 :utf-8 "(Продолжение)")
5709 ("sl" :default "Nadaljevanje s prejšnje strani"))
5710 ("Continued on next page"
5711 ("ar" :default "التتمة في الصفحة التالية")
5712 ("cs" :default "Pokračuje na další stránce")
5713 ("de" :default "Fortsetzung nächste Seite")
5714 ("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")
5715 ("fr" :default "Suite page suivante")
5716 ("it" :default "Continua alla pagina successiva")
5717 ("ja" :default "次ページに続く")
5718 ("nl" :default "Vervolg op volgende pagina")
5719 ("pt" :default "Continua na página seguinte")
5720 ("ru" :html "(&#1055;&#1088;&#1086;&#1076;&#1086;&#1083;&#1078;&#1077;&#1085;&#1080;&#1077; &#1089;&#1083;&#1077;&#1076;&#1091;&#1077;&#1090;)"
5721 :utf-8 "(Продолжение следует)")
5722 ("sl" :default "Nadaljevanje na naslednji strani"))
5723 ("Created"
5724 ("cs" :default "Vytvořeno")
5725 ("sl" :default "Ustvarjeno"))
5726 ("Date"
5727 ("ar" :default "بتاريخ")
5728 ("ca" :default "Data")
5729 ("cs" :default "Datum")
5730 ("da" :default "Dato")
5731 ("de" :default "Datum")
5732 ("eo" :default "Dato")
5733 ("es" :default "Fecha")
5734 ("et" :html "Kuup&#228;ev" :utf-8 "Kuupäev")
5735 ("fi" :html "P&auml;iv&auml;m&auml;&auml;r&auml;")
5736 ("hu" :html "D&aacute;tum")
5737 ("is" :default "Dagsetning")
5738 ("it" :default "Data")
5739 ("ja" :default "日付" :html "&#26085;&#20184;")
5740 ("nl" :default "Datum")
5741 ("no" :default "Dato")
5742 ("nb" :default "Dato")
5743 ("nn" :default "Dato")
5744 ("pl" :default "Data")
5745 ("pt_BR" :default "Data")
5746 ("ru" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5747 ("sl" :default "Datum")
5748 ("sv" :default "Datum")
5749 ("uk" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5750 ("zh-CN" :html "&#26085;&#26399;" :utf-8 "日期")
5751 ("zh-TW" :html "&#26085;&#26399;" :utf-8 "日期"))
5752 ("Equation"
5753 ("ar" :default "معادلة")
5754 ("cs" :default "Rovnice")
5755 ("da" :default "Ligning")
5756 ("de" :default "Gleichung")
5757 ("es" :ascii "Ecuacion" :html "Ecuaci&oacute;n" :default "Ecuación")
5758 ("et" :html "V&#245;rrand" :utf-8 "Võrrand")
5759 ("fr" :ascii "Equation" :default "Équation")
5760 ("is" :default "Jafna")
5761 ("ja" :default "方程式")
5762 ("no" :default "Ligning")
5763 ("nb" :default "Ligning")
5764 ("nn" :default "Likning")
5765 ("pt_BR" :html "Equa&ccedil;&atilde;o" :default "Equação" :ascii "Equacao")
5766 ("ru" :html "&#1059;&#1088;&#1072;&#1074;&#1085;&#1077;&#1085;&#1080;&#1077;"
5767 :utf-8 "Уравнение")
5768 ("sl" :default "Enačba")
5769 ("sv" :default "Ekvation")
5770 ("zh-CN" :html "&#26041;&#31243;" :utf-8 "方程"))
5771 ("Figure"
5772 ("ar" :default "شكل")
5773 ("cs" :default "Obrázek")
5774 ("da" :default "Figur")
5775 ("de" :default "Abbildung")
5776 ("es" :default "Figura")
5777 ("et" :default "Joonis")
5778 ("is" :default "Mynd")
5779 ("ja" :default "図" :html "&#22259;")
5780 ("no" :default "Illustrasjon")
5781 ("nb" :default "Illustrasjon")
5782 ("nn" :default "Illustrasjon")
5783 ("pt_BR" :default "Figura")
5784 ("ru" :html "&#1056;&#1080;&#1089;&#1091;&#1085;&#1086;&#1082;" :utf-8 "Рисунок")
5785 ("sv" :default "Illustration")
5786 ("zh-CN" :html "&#22270;" :utf-8 "图"))
5787 ("Figure %d:"
5788 ("ar" :default "شكل %d:")
5789 ("cs" :default "Obrázek %d:")
5790 ("da" :default "Figur %d")
5791 ("de" :default "Abbildung %d:")
5792 ("es" :default "Figura %d:")
5793 ("et" :default "Joonis %d:")
5794 ("fr" :default "Figure %d :" :html "Figure&nbsp;%d&nbsp;:")
5795 ("is" :default "Mynd %d")
5796 ("ja" :default "図%d: " :html "&#22259;%d: ")
5797 ("no" :default "Illustrasjon %d")
5798 ("nb" :default "Illustrasjon %d")
5799 ("nn" :default "Illustrasjon %d")
5800 ("pt_BR" :default "Figura %d:")
5801 ("ru" :html "&#1056;&#1080;&#1089;. %d.:" :utf-8 "Рис. %d.:")
5802 ("sl" :default "Slika %d")
5803 ("sv" :default "Illustration %d")
5804 ("zh-CN" :html "&#22270;%d&nbsp;" :utf-8 "图%d "))
5805 ("Footnotes"
5806 ("ar" :default "الهوامش")
5807 ("ca" :html "Peus de p&agrave;gina")
5808 ("cs" :default "Poznámky pod čarou")
5809 ("da" :default "Fodnoter")
5810 ("de" :html "Fu&szlig;noten" :default "Fußnoten")
5811 ("eo" :default "Piednotoj")
5812 ("es" :ascii "Nota al pie de pagina" :html "Nota al pie de p&aacute;gina" :default "Nota al pie de página")
5813 ("et" :html "Allm&#228;rkused" :utf-8 "Allmärkused")
5814 ("fi" :default "Alaviitteet")
5815 ("fr" :default "Notes de bas de page")
5816 ("hu" :html "L&aacute;bjegyzet")
5817 ("is" :html "Aftanm&aacute;lsgreinar")
5818 ("it" :html "Note a pi&egrave; di pagina")
5819 ("ja" :default "脚注" :html "&#33050;&#27880;")
5820 ("nl" :default "Voetnoten")
5821 ("no" :default "Fotnoter")
5822 ("nb" :default "Fotnoter")
5823 ("nn" :default "Fotnotar")
5824 ("pl" :default "Przypis")
5825 ("pt_BR" :html "Notas de Rodap&eacute;" :default "Notas de Rodapé" :ascii "Notas de Rodape")
5826 ("ru" :html "&#1057;&#1085;&#1086;&#1089;&#1082;&#1080;" :utf-8 "Сноски")
5827 ("sl" :default "Opombe")
5828 ("sv" :default "Fotnoter")
5829 ("uk" :html "&#1055;&#1088;&#1080;&#1084;&#1110;&#1090;&#1082;&#1080;"
5830 :utf-8 "Примітки")
5831 ("zh-CN" :html "&#33050;&#27880;" :utf-8 "脚注")
5832 ("zh-TW" :html "&#33139;&#35387;" :utf-8 "腳註"))
5833 ("List of Listings"
5834 ("ar" :default "قائمة بالبرامج")
5835 ("cs" :default "Seznam programů")
5836 ("da" :default "Programmer")
5837 ("de" :default "Programmauflistungsverzeichnis")
5838 ("es" :ascii "Indice de Listados de programas" :html "&Iacute;ndice de Listados de programas" :default "Índice de Listados de programas")
5839 ("et" :default "Loendite nimekiri")
5840 ("fr" :default "Liste des programmes")
5841 ("ja" :default "ソースコード目次")
5842 ("no" :default "Dataprogrammer")
5843 ("nb" :default "Dataprogrammer")
5844 ("ru" :html "&#1057;&#1087;&#1080;&#1089;&#1086;&#1082; &#1088;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1086;&#1082;"
5845 :utf-8 "Список распечаток")
5846 ("sl" :default "Seznam programskih izpisov")
5847 ("zh-CN" :html "&#20195;&#30721;&#30446;&#24405;" :utf-8 "代码目录"))
5848 ("List of Tables"
5849 ("ar" :default "قائمة بالجداول")
5850 ("cs" :default "Seznam tabulek")
5851 ("da" :default "Tabeller")
5852 ("de" :default "Tabellenverzeichnis")
5853 ("es" :ascii "Indice de tablas" :html "&Iacute;ndice de tablas" :default "Índice de tablas")
5854 ("et" :default "Tabelite nimekiri")
5855 ("fr" :default "Liste des tableaux")
5856 ("is" :default "Töfluskrá" :html "T&ouml;fluskr&aacute;")
5857 ("ja" :default "表目次")
5858 ("no" :default "Tabeller")
5859 ("nb" :default "Tabeller")
5860 ("nn" :default "Tabeller")
5861 ("pt_BR" :default "Índice de Tabelas" :ascii "Indice de Tabelas")
5862 ("ru" :html "&#1057;&#1087;&#1080;&#1089;&#1086;&#1082; &#1090;&#1072;&#1073;&#1083;&#1080;&#1094;"
5863 :utf-8 "Список таблиц")
5864 ("sl" :default "Seznam tabel")
5865 ("sv" :default "Tabeller")
5866 ("zh-CN" :html "&#34920;&#26684;&#30446;&#24405;" :utf-8 "表格目录"))
5867 ("Listing"
5868 ("ar" :default "برنامج")
5869 ("cs" :default "Program")
5870 ("da" :default "Program")
5871 ("de" :default "Programmlisting")
5872 ("es" :default "Listado de programa")
5873 ("et" :default "Loend")
5874 ("fr" :default "Programme" :html "Programme")
5875 ("ja" :default "ソースコード")
5876 ("no" :default "Dataprogram")
5877 ("nb" :default "Dataprogram")
5878 ("pt_BR" :default "Listagem")
5879 ("ru" :html "&#1056;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1082;&#1072;"
5880 :utf-8 "Распечатка")
5881 ("sl" :default "Izpis programa")
5882 ("zh-CN" :html "&#20195;&#30721;" :utf-8 "代码"))
5883 ("Listing %d:"
5884 ("ar" :default "برنامج %d:")
5885 ("cs" :default "Program %d:")
5886 ("da" :default "Program %d")
5887 ("de" :default "Programmlisting %d")
5888 ("es" :default "Listado de programa %d")
5889 ("et" :default "Loend %d")
5890 ("fr" :default "Programme %d :" :html "Programme&nbsp;%d&nbsp;:")
5891 ("ja" :default "ソースコード%d:")
5892 ("no" :default "Dataprogram %d")
5893 ("nb" :default "Dataprogram %d")
5894 ("pt_BR" :default "Listagem %d")
5895 ("ru" :html "&#1056;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1082;&#1072; %d.:"
5896 :utf-8 "Распечатка %d.:")
5897 ("sl" :default "Izpis programa %d")
5898 ("zh-CN" :html "&#20195;&#30721;%d&nbsp;" :utf-8 "代码%d "))
5899 ("References"
5900 ("ar" :default "المراجع")
5901 ("cs" :default "Reference")
5902 ("fr" :ascii "References" :default "Références")
5903 ("de" :default "Quellen")
5904 ("es" :default "Referencias")
5905 ("sl" :default "Reference"))
5906 ("See figure %s"
5907 ("cs" :default "Viz obrázek %s")
5908 ("fr" :default "cf. figure %s"
5909 :html "cf.&nbsp;figure&nbsp;%s" :latex "cf.~figure~%s")
5910 ("sl" :default "Glej sliko %s"))
5911 ("See listing %s"
5912 ("cs" :default "Viz program %s")
5913 ("fr" :default "cf. programme %s"
5914 :html "cf.&nbsp;programme&nbsp;%s" :latex "cf.~programme~%s")
5915 ("sl" :default "Glej izpis programa %s"))
5916 ("See section %s"
5917 ("ar" :default "انظر قسم %s")
5918 ("cs" :default "Viz sekce %s")
5919 ("da" :default "jævnfør afsnit %s")
5920 ("de" :default "siehe Abschnitt %s")
5921 ("es" :ascii "Vea seccion %s" :html "Vea secci&oacute;n %s" :default "Vea sección %s")
5922 ("et" :html "Vaata peat&#252;kki %s" :utf-8 "Vaata peatükki %s")
5923 ("fr" :default "cf. section %s")
5924 ("ja" :default "セクション %s を参照")
5925 ("pt_BR" :html "Veja a se&ccedil;&atilde;o %s" :default "Veja a seção %s"
5926 :ascii "Veja a secao %s")
5927 ("ru" :html "&#1057;&#1084;. &#1088;&#1072;&#1079;&#1076;&#1077;&#1083; %s"
5928 :utf-8 "См. раздел %s")
5929 ("sl" :default "Glej poglavje %d")
5930 ("zh-CN" :html "&#21442;&#35265;&#31532;%s&#33410;" :utf-8 "参见第%s节"))
5931 ("See table %s"
5932 ("cs" :default "Viz tabulka %s")
5933 ("fr" :default "cf. tableau %s"
5934 :html "cf.&nbsp;tableau&nbsp;%s" :latex "cf.~tableau~%s")
5935 ("sl" :default "Glej tabelo %s"))
5936 ("Table"
5937 ("ar" :default "جدول")
5938 ("cs" :default "Tabulka")
5939 ("de" :default "Tabelle")
5940 ("es" :default "Tabla")
5941 ("et" :default "Tabel")
5942 ("fr" :default "Tableau")
5943 ("is" :default "Tafla")
5944 ("ja" :default "表" :html "&#34920;")
5945 ("pt_BR" :default "Tabela")
5946 ("ru" :html "&#1058;&#1072;&#1073;&#1083;&#1080;&#1094;&#1072;"
5947 :utf-8 "Таблица")
5948 ("zh-CN" :html "&#34920;" :utf-8 "表"))
5949 ("Table %d:"
5950 ("ar" :default "جدول %d:")
5951 ("cs" :default "Tabulka %d:")
5952 ("da" :default "Tabel %d")
5953 ("de" :default "Tabelle %d")
5954 ("es" :default "Tabla %d")
5955 ("et" :default "Tabel %d")
5956 ("fr" :default "Tableau %d :")
5957 ("is" :default "Tafla %d")
5958 ("ja" :default "表%d:" :html "&#34920;%d:")
5959 ("no" :default "Tabell %d")
5960 ("nb" :default "Tabell %d")
5961 ("nn" :default "Tabell %d")
5962 ("pt_BR" :default "Tabela %d")
5963 ("ru" :html "&#1058;&#1072;&#1073;&#1083;&#1080;&#1094;&#1072; %d.:"
5964 :utf-8 "Таблица %d.:")
5965 ("sl" :default "Tabela %d")
5966 ("sv" :default "Tabell %d")
5967 ("zh-CN" :html "&#34920;%d&nbsp;" :utf-8 "表%d "))
5968 ("Table of Contents"
5969 ("ar" :default "قائمة المحتويات")
5970 ("ca" :html "&Iacute;ndex")
5971 ("cs" :default "Obsah")
5972 ("da" :default "Indhold")
5973 ("de" :default "Inhaltsverzeichnis")
5974 ("eo" :default "Enhavo")
5975 ("es" :ascii "Indice" :html "&Iacute;ndice" :default "Índice")
5976 ("et" :default "Sisukord")
5977 ("fi" :html "Sis&auml;llysluettelo")
5978 ("fr" :ascii "Sommaire" :default "Table des matières")
5979 ("hu" :html "Tartalomjegyz&eacute;k")
5980 ("is" :default "Efnisyfirlit")
5981 ("it" :default "Indice")
5982 ("ja" :default "目次" :html "&#30446;&#27425;")
5983 ("nl" :default "Inhoudsopgave")
5984 ("no" :default "Innhold")
5985 ("nb" :default "Innhold")
5986 ("nn" :default "Innhald")
5987 ("pl" :html "Spis tre&#x015b;ci")
5988 ("pt_BR" :html "&Iacute;ndice" :utf8 "Índice" :ascii "Indice")
5989 ("ru" :html "&#1057;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1077;"
5990 :utf-8 "Содержание")
5991 ("sl" :default "Kazalo")
5992 ("sv" :html "Inneh&aring;ll")
5993 ("uk" :html "&#1047;&#1084;&#1110;&#1089;&#1090;" :utf-8 "Зміст")
5994 ("zh-CN" :html "&#30446;&#24405;" :utf-8 "目录")
5995 ("zh-TW" :html "&#30446;&#37636;" :utf-8 "目錄"))
5996 ("Unknown reference"
5997 ("ar" :default "مرجع غير معرّف")
5998 ("da" :default "ukendt reference")
5999 ("de" :default "Unbekannter Verweis")
6000 ("es" :default "Referencia desconocida")
6001 ("et" :default "Tundmatu viide")
6002 ("fr" :ascii "Destination inconnue" :default "Référence inconnue")
6003 ("ja" :default "不明な参照先")
6004 ("pt_BR" :default "Referência desconhecida"
6005 :ascii "Referencia desconhecida")
6006 ("ru" :html "&#1053;&#1077;&#1080;&#1079;&#1074;&#1077;&#1089;&#1090;&#1085;&#1072;&#1103; &#1089;&#1089;&#1099;&#1083;&#1082;&#1072;"
6007 :utf-8 "Неизвестная ссылка")
6008 ("sl" :default "Neznana referenca")
6009 ("zh-CN" :html "&#26410;&#30693;&#24341;&#29992;" :utf-8 "未知引用")))
6010 "Dictionary for export engine.
6012 Alist whose car is the string to translate and cdr is an alist
6013 whose car is the language string and cdr is a plist whose
6014 properties are possible charsets and values translated terms.
6016 It is used as a database for `org-export-translate'. Since this
6017 function returns the string as-is if no translation was found,
6018 the variable only needs to record values different from the
6019 entry.")
6021 (defun org-export-translate (s encoding info)
6022 "Translate string S according to language specification.
6024 ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1'
6025 and `:utf-8'. INFO is a plist used as a communication channel.
6027 Translation depends on `:language' property. Return the
6028 translated string. If no translation is found, try to fall back
6029 to `:default' encoding. If it fails, return S."
6030 (let* ((lang (plist-get info :language))
6031 (translations (cdr (assoc lang
6032 (cdr (assoc s org-export-dictionary))))))
6033 (or (plist-get translations encoding)
6034 (plist-get translations :default)
6035 s)))
6039 ;;; Asynchronous Export
6041 ;; `org-export-async-start' is the entry point for asynchronous
6042 ;; export. It recreates current buffer (including visibility,
6043 ;; narrowing and visited file) in an external Emacs process, and
6044 ;; evaluates a command there. It then applies a function on the
6045 ;; returned results in the current process.
6047 ;; At a higher level, `org-export-to-buffer' and `org-export-to-file'
6048 ;; allow exporting to a buffer or a file, asynchronously or not.
6050 ;; `org-export-output-file-name' is an auxiliary function meant to be
6051 ;; used with `org-export-to-file'. With a given extension, it tries
6052 ;; to provide a canonical file name to write export output to.
6054 ;; Asynchronously generated results are never displayed directly.
6055 ;; Instead, they are stored in `org-export-stack-contents'. They can
6056 ;; then be retrieved by calling `org-export-stack'.
6058 ;; Export Stack is viewed through a dedicated major mode
6059 ;;`org-export-stack-mode' and tools: `org-export-stack-refresh',
6060 ;;`org-export-stack-delete', `org-export-stack-view' and
6061 ;;`org-export-stack-clear'.
6063 ;; For back-ends, `org-export-add-to-stack' add a new source to stack.
6064 ;; It should be used whenever `org-export-async-start' is called.
6066 (defmacro org-export-async-start (fun &rest body)
6067 "Call function FUN on the results returned by BODY evaluation.
6069 FUN is an anonymous function of one argument. BODY evaluation
6070 happens in an asynchronous process, from a buffer which is an
6071 exact copy of the current one.
6073 Use `org-export-add-to-stack' in FUN in order to register results
6074 in the stack.
6076 This is a low level function. See also `org-export-to-buffer'
6077 and `org-export-to-file' for more specialized functions."
6078 (declare (indent 1) (debug t))
6079 (org-with-gensyms (process temp-file copy-fun proc-buffer coding)
6080 ;; Write the full sexp evaluating BODY in a copy of the current
6081 ;; buffer to a temporary file, as it may be too long for program
6082 ;; args in `start-process'.
6083 `(with-temp-message "Initializing asynchronous export process"
6084 (let ((,copy-fun (org-export--generate-copy-script (current-buffer)))
6085 (,temp-file (make-temp-file "org-export-process"))
6086 (,coding buffer-file-coding-system))
6087 (with-temp-file ,temp-file
6088 (insert
6089 ;; Null characters (from variable values) are inserted
6090 ;; within the file. As a consequence, coding system for
6091 ;; buffer contents will not be recognized properly. So,
6092 ;; we make sure it is the same as the one used to display
6093 ;; the original buffer.
6094 (format ";; -*- coding: %s; -*-\n%S"
6095 ,coding
6096 `(with-temp-buffer
6097 (when org-export-async-debug '(setq debug-on-error t))
6098 ;; Ignore `kill-emacs-hook' and code evaluation
6099 ;; queries from Babel as we need a truly
6100 ;; non-interactive process.
6101 (setq kill-emacs-hook nil
6102 org-babel-confirm-evaluate-answer-no t)
6103 ;; Initialize export framework.
6104 (require 'ox)
6105 ;; Re-create current buffer there.
6106 (funcall ,,copy-fun)
6107 (restore-buffer-modified-p nil)
6108 ;; Sexp to evaluate in the buffer.
6109 (print (progn ,,@body))))))
6110 ;; Start external process.
6111 (let* ((process-connection-type nil)
6112 (,proc-buffer (generate-new-buffer-name "*Org Export Process*"))
6113 (,process
6114 (apply
6115 #'start-process
6116 (append
6117 (list "org-export-process"
6118 ,proc-buffer
6119 (expand-file-name invocation-name invocation-directory)
6120 "--batch")
6121 (if org-export-async-init-file
6122 (list "-Q" "-l" org-export-async-init-file)
6123 (list "-l" user-init-file))
6124 (list "-l" ,temp-file)))))
6125 ;; Register running process in stack.
6126 (org-export-add-to-stack (get-buffer ,proc-buffer) nil ,process)
6127 ;; Set-up sentinel in order to catch results.
6128 (let ((handler ,fun))
6129 (set-process-sentinel
6130 ,process
6131 `(lambda (p status)
6132 (let ((proc-buffer (process-buffer p)))
6133 (when (eq (process-status p) 'exit)
6134 (unwind-protect
6135 (if (zerop (process-exit-status p))
6136 (unwind-protect
6137 (let ((results
6138 (with-current-buffer proc-buffer
6139 (goto-char (point-max))
6140 (backward-sexp)
6141 (read (current-buffer)))))
6142 (funcall ,handler results))
6143 (unless org-export-async-debug
6144 (and (get-buffer proc-buffer)
6145 (kill-buffer proc-buffer))))
6146 (org-export-add-to-stack proc-buffer nil p)
6147 (ding)
6148 (message "Process `%s' exited abnormally" p))
6149 (unless org-export-async-debug
6150 (delete-file ,,temp-file)))))))))))))
6152 ;;;###autoload
6153 (defun org-export-to-buffer
6154 (backend buffer
6155 &optional async subtreep visible-only body-only ext-plist
6156 post-process)
6157 "Call `org-export-as' with output to a specified buffer.
6159 BACKEND is either an export back-end, as returned by, e.g.,
6160 `org-export-create-backend', or a symbol referring to
6161 a registered back-end.
6163 BUFFER is the name of the output buffer. If it already exists,
6164 it will be erased first, otherwise, it will be created.
6166 A non-nil optional argument ASYNC means the process should happen
6167 asynchronously. The resulting buffer should then be accessible
6168 through the `org-export-stack' interface. When ASYNC is nil, the
6169 buffer is displayed if `org-export-show-temporary-export-buffer'
6170 is non-nil.
6172 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
6173 EXT-PLIST are similar to those used in `org-export-as', which
6174 see.
6176 Optional argument POST-PROCESS is a function which should accept
6177 no argument. It is always called within the current process,
6178 from BUFFER, with point at its beginning. Export back-ends can
6179 use it to set a major mode there, e.g,
6181 (defun org-latex-export-as-latex
6182 (&optional async subtreep visible-only body-only ext-plist)
6183 (interactive)
6184 (org-export-to-buffer \\='latex \"*Org LATEX Export*\"
6185 async subtreep visible-only body-only ext-plist (lambda () (LaTeX-mode))))
6187 This function returns BUFFER."
6188 (declare (indent 2))
6189 (if async
6190 (org-export-async-start
6191 `(lambda (output)
6192 (with-current-buffer (get-buffer-create ,buffer)
6193 (erase-buffer)
6194 (setq buffer-file-coding-system ',buffer-file-coding-system)
6195 (insert output)
6196 (goto-char (point-min))
6197 (org-export-add-to-stack (current-buffer) ',backend)
6198 (ignore-errors (funcall ,post-process))))
6199 `(org-export-as
6200 ',backend ,subtreep ,visible-only ,body-only ',ext-plist))
6201 (let ((output
6202 (org-export-as backend subtreep visible-only body-only ext-plist))
6203 (buffer (get-buffer-create buffer))
6204 (encoding buffer-file-coding-system))
6205 (when (and (org-string-nw-p output) (org-export--copy-to-kill-ring-p))
6206 (org-kill-new output))
6207 (with-current-buffer buffer
6208 (erase-buffer)
6209 (setq buffer-file-coding-system encoding)
6210 (insert output)
6211 (goto-char (point-min))
6212 (and (functionp post-process) (funcall post-process)))
6213 (when org-export-show-temporary-export-buffer
6214 (switch-to-buffer-other-window buffer))
6215 buffer)))
6217 ;;;###autoload
6218 (defun org-export-to-file
6219 (backend file &optional async subtreep visible-only body-only ext-plist
6220 post-process)
6221 "Call `org-export-as' with output to a specified file.
6223 BACKEND is either an export back-end, as returned by, e.g.,
6224 `org-export-create-backend', or a symbol referring to
6225 a registered back-end. FILE is the name of the output file, as
6226 a string.
6228 A non-nil optional argument ASYNC means the process should happen
6229 asynchronously. The resulting buffer will then be accessible
6230 through the `org-export-stack' interface.
6232 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
6233 EXT-PLIST are similar to those used in `org-export-as', which
6234 see.
6236 Optional argument POST-PROCESS is called with FILE as its
6237 argument and happens asynchronously when ASYNC is non-nil. It
6238 has to return a file name, or nil. Export back-ends can use this
6239 to send the output file through additional processing, e.g,
6241 (defun org-latex-export-to-latex
6242 (&optional async subtreep visible-only body-only ext-plist)
6243 (interactive)
6244 (let ((outfile (org-export-output-file-name \".tex\" subtreep)))
6245 (org-export-to-file \\='latex outfile
6246 async subtreep visible-only body-only ext-plist
6247 (lambda (file) (org-latex-compile file)))
6249 The function returns either a file name returned by POST-PROCESS,
6250 or FILE."
6251 (declare (indent 2))
6252 (if (not (file-writable-p file)) (error "Output file not writable")
6253 (let ((ext-plist (org-combine-plists `(:output-file ,file) ext-plist))
6254 (encoding (or org-export-coding-system buffer-file-coding-system)))
6255 (if async
6256 (org-export-async-start
6257 `(lambda (file)
6258 (org-export-add-to-stack (expand-file-name file) ',backend))
6259 `(let ((output
6260 (org-export-as
6261 ',backend ,subtreep ,visible-only ,body-only
6262 ',ext-plist)))
6263 (with-temp-buffer
6264 (insert output)
6265 (let ((coding-system-for-write ',encoding))
6266 (write-file ,file)))
6267 (or (ignore-errors (funcall ',post-process ,file)) ,file)))
6268 (let ((output (org-export-as
6269 backend subtreep visible-only body-only ext-plist)))
6270 (with-temp-buffer
6271 (insert output)
6272 (let ((coding-system-for-write encoding))
6273 (write-file file)))
6274 (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p output))
6275 (org-kill-new output))
6276 ;; Get proper return value.
6277 (or (and (functionp post-process) (funcall post-process file))
6278 file))))))
6280 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
6281 "Return output file's name according to buffer specifications.
6283 EXTENSION is a string representing the output file extension,
6284 with the leading dot.
6286 With a non-nil optional argument SUBTREEP, try to determine
6287 output file's name by looking for \"EXPORT_FILE_NAME\" property
6288 of subtree at point.
6290 When optional argument PUB-DIR is set, use it as the publishing
6291 directory.
6293 Return file name as a string."
6294 (let* ((visited-file (buffer-file-name (buffer-base-buffer)))
6295 (base-name
6296 (concat
6297 (file-name-sans-extension
6299 ;; Check EXPORT_FILE_NAME subtree property.
6300 (and subtreep (org-entry-get nil "EXPORT_FILE_NAME" 'selective))
6301 ;; Check #+EXPORT_FILE_NAME keyword.
6302 (org-with-point-at (point-min)
6303 (catch :found
6304 (let ((case-fold-search t))
6305 (while (re-search-forward
6306 "^[ \t]*#\\+EXPORT_FILE_NAME:[ \t]+\\S-" nil t)
6307 (let ((element (org-element-at-point)))
6308 (when (eq 'keyword (org-element-type element))
6309 (throw :found
6310 (org-element-property :value element))))))))
6311 ;; Extract from buffer's associated file, if any.
6312 (and visited-file (file-name-nondirectory visited-file))
6313 ;; Can't determine file name on our own: ask user.
6314 (read-file-name
6315 "Output file: " pub-dir nil nil nil
6316 (lambda (n) (string= extension (file-name-extension n t))))))
6317 extension))
6318 (output-file
6319 ;; Build file name. Enforce EXTENSION over whatever user
6320 ;; may have come up with. PUB-DIR, if defined, always has
6321 ;; precedence over any provided path.
6322 (cond
6323 (pub-dir (concat (file-name-as-directory pub-dir)
6324 (file-name-nondirectory base-name)))
6325 ((file-name-absolute-p base-name) base-name)
6326 (t base-name))))
6327 ;; If writing to OUTPUT-FILE would overwrite original file, append
6328 ;; EXTENSION another time to final name.
6329 (if (and visited-file (file-equal-p visited-file output-file))
6330 (concat output-file extension)
6331 output-file)))
6333 (defun org-export-add-to-stack (source backend &optional process)
6334 "Add a new result to export stack if not present already.
6336 SOURCE is a buffer or a file name containing export results.
6337 BACKEND is a symbol representing export back-end used to generate
6340 Entries already pointing to SOURCE and unavailable entries are
6341 removed beforehand. Return the new stack."
6342 (setq org-export-stack-contents
6343 (cons (list source backend (or process (current-time)))
6344 (org-export-stack-remove source))))
6346 (defun org-export-stack ()
6347 "Menu for asynchronous export results and running processes."
6348 (interactive)
6349 (let ((buffer (get-buffer-create "*Org Export Stack*")))
6350 (with-current-buffer buffer
6351 (org-export-stack-mode)
6352 (tabulated-list-print t))
6353 (pop-to-buffer buffer))
6354 (message "Type \"q\" to quit, \"?\" for help"))
6356 (defun org-export-stack-clear ()
6357 "Remove all entries from export stack."
6358 (interactive)
6359 (setq org-export-stack-contents nil))
6361 (defun org-export-stack-refresh ()
6362 "Refresh the export stack."
6363 (interactive)
6364 (tabulated-list-print t))
6366 (defun org-export-stack-remove (&optional source)
6367 "Remove export results at point from stack.
6368 If optional argument SOURCE is non-nil, remove it instead."
6369 (interactive)
6370 (let ((source (or source (org-export--stack-source-at-point))))
6371 (setq org-export-stack-contents
6372 (cl-remove-if (lambda (el) (equal (car el) source))
6373 org-export-stack-contents))))
6375 (defun org-export-stack-view (&optional in-emacs)
6376 "View export results at point in stack.
6377 With an optional prefix argument IN-EMACS, force viewing files
6378 within Emacs."
6379 (interactive "P")
6380 (let ((source (org-export--stack-source-at-point)))
6381 (cond ((processp source)
6382 (org-switch-to-buffer-other-window (process-buffer source)))
6383 ((bufferp source) (org-switch-to-buffer-other-window source))
6384 (t (org-open-file source in-emacs)))))
6386 (defvar org-export-stack-mode-map
6387 (let ((km (make-sparse-keymap)))
6388 (set-keymap-parent km tabulated-list-mode-map)
6389 (define-key km " " 'next-line)
6390 (define-key km "\C-n" 'next-line)
6391 (define-key km [down] 'next-line)
6392 (define-key km "\C-p" 'previous-line)
6393 (define-key km "\C-?" 'previous-line)
6394 (define-key km [up] 'previous-line)
6395 (define-key km "C" 'org-export-stack-clear)
6396 (define-key km "v" 'org-export-stack-view)
6397 (define-key km (kbd "RET") 'org-export-stack-view)
6398 (define-key km "d" 'org-export-stack-remove)
6400 "Keymap for Org Export Stack.")
6402 (define-derived-mode org-export-stack-mode tabulated-list-mode "Org-Stack"
6403 "Mode for displaying asynchronous export stack.
6405 Type `\\[org-export-stack]' to visualize the asynchronous export
6406 stack.
6408 In an Org Export Stack buffer, use \
6409 \\<org-export-stack-mode-map>`\\[org-export-stack-view]' to view export output
6410 on current line, `\\[org-export-stack-remove]' to remove it from the stack and \
6411 `\\[org-export-stack-clear]' to clear
6412 stack completely.
6414 Removing entries in a stack buffer does not affect files
6415 or buffers, only display.
6417 \\{org-export-stack-mode-map}"
6418 (setq tabulated-list-format
6419 (vector (list "#" 4 #'org-export--stack-num-predicate)
6420 (list "Back-End" 12 t)
6421 (list "Age" 6 nil)
6422 (list "Source" 0 nil)))
6423 (setq tabulated-list-sort-key (cons "#" nil))
6424 (setq tabulated-list-entries #'org-export--stack-generate)
6425 (add-hook 'tabulated-list-revert-hook #'org-export--stack-generate nil t)
6426 (add-hook 'post-command-hook #'org-export-stack-refresh nil t)
6427 (tabulated-list-init-header))
6429 (defun org-export--stack-generate ()
6430 "Generate the asynchronous export stack for display.
6431 Unavailable sources are removed from the list. Return a list
6432 appropriate for `tabulated-list-print'."
6433 ;; Clear stack from exited processes, dead buffers or non-existent
6434 ;; files.
6435 (setq org-export-stack-contents
6436 (cl-remove-if-not
6437 (lambda (el)
6438 (if (processp (nth 2 el))
6439 (buffer-live-p (process-buffer (nth 2 el)))
6440 (let ((source (car el)))
6441 (if (bufferp source) (buffer-live-p source)
6442 (file-exists-p source)))))
6443 org-export-stack-contents))
6444 ;; Update `tabulated-list-entries'.
6445 (let ((counter 0))
6446 (mapcar
6447 (lambda (entry)
6448 (let ((source (car entry)))
6449 (list source
6450 (vector
6451 ;; Counter.
6452 (number-to-string (cl-incf counter))
6453 ;; Back-End.
6454 (if (nth 1 entry) (symbol-name (nth 1 entry)) "")
6455 ;; Age.
6456 (let ((info (nth 2 entry)))
6457 (if (processp info) (symbol-name (process-status info))
6458 (format-seconds "%h:%.2m" (float-time (time-since info)))))
6459 ;; Source.
6460 (if (stringp source) source (buffer-name source))))))
6461 org-export-stack-contents)))
6463 (defun org-export--stack-num-predicate (a b)
6464 (< (string-to-number (aref (nth 1 a) 0))
6465 (string-to-number (aref (nth 1 b) 0))))
6467 (defun org-export--stack-source-at-point ()
6468 "Return source from export results at point in stack."
6469 (let ((source (car (nth (1- (org-current-line)) org-export-stack-contents))))
6470 (if (not source) (error "Source unavailable, please refresh buffer")
6471 (let ((source-name (if (stringp source) source (buffer-name source))))
6472 (if (save-excursion
6473 (beginning-of-line)
6474 (looking-at-p (concat ".* +" (regexp-quote source-name) "$")))
6475 source
6476 ;; SOURCE is not consistent with current line. The stack
6477 ;; view is outdated.
6478 (error (substitute-command-keys
6479 "Source unavailable; type `\\[org-export-stack-refresh]' \
6480 to refresh buffer")))))))
6484 ;;; The Dispatcher
6486 ;; `org-export-dispatch' is the standard interactive way to start an
6487 ;; export process. It uses `org-export--dispatch-ui' as a subroutine
6488 ;; for its interface, which, in turn, delegates response to key
6489 ;; pressed to `org-export--dispatch-action'.
6491 ;;;###autoload
6492 (defun org-export-dispatch (&optional arg)
6493 "Export dispatcher for Org mode.
6495 It provides an access to common export related tasks in a buffer.
6496 Its interface comes in two flavors: standard and expert.
6498 While both share the same set of bindings, only the former
6499 displays the valid keys associations in a dedicated buffer.
6500 Scrolling (resp. line-wise motion) in this buffer is done with
6501 SPC and DEL (resp. C-n and C-p) keys.
6503 Set variable `org-export-dispatch-use-expert-ui' to switch to one
6504 flavor or the other.
6506 When ARG is `\\[universal-argument]', repeat the last export action, with the\
6507 same
6508 set of options used back then, on the current buffer.
6510 When ARG is `\\[universal-argument] \\[universal-argument]', display the \
6511 asynchronous export stack."
6512 (interactive "P")
6513 (let* ((input
6514 (cond ((equal arg '(16)) '(stack))
6515 ((and arg org-export-dispatch-last-action))
6516 (t (save-window-excursion
6517 (unwind-protect
6518 (progn
6519 ;; Remember where we are
6520 (move-marker org-export-dispatch-last-position
6521 (point)
6522 (org-base-buffer (current-buffer)))
6523 ;; Get and store an export command
6524 (setq org-export-dispatch-last-action
6525 (org-export--dispatch-ui
6526 (list org-export-initial-scope
6527 (and org-export-in-background 'async))
6529 org-export-dispatch-use-expert-ui)))
6530 (and (get-buffer "*Org Export Dispatcher*")
6531 (kill-buffer "*Org Export Dispatcher*")))))))
6532 (action (car input))
6533 (optns (cdr input)))
6534 (unless (memq 'subtree optns)
6535 (move-marker org-export-dispatch-last-position nil))
6536 (cl-case action
6537 ;; First handle special hard-coded actions.
6538 (template (org-export-insert-default-template nil optns))
6539 (stack (org-export-stack))
6540 (publish-current-file
6541 (org-publish-current-file (memq 'force optns) (memq 'async optns)))
6542 (publish-current-project
6543 (org-publish-current-project (memq 'force optns) (memq 'async optns)))
6544 (publish-choose-project
6545 (org-publish (assoc (completing-read
6546 "Publish project: "
6547 org-publish-project-alist nil t)
6548 org-publish-project-alist)
6549 (memq 'force optns)
6550 (memq 'async optns)))
6551 (publish-all (org-publish-all (memq 'force optns) (memq 'async optns)))
6552 (otherwise
6553 (save-excursion
6554 (when arg
6555 ;; Repeating command, maybe move cursor to restore subtree
6556 ;; context.
6557 (if (eq (marker-buffer org-export-dispatch-last-position)
6558 (org-base-buffer (current-buffer)))
6559 (goto-char org-export-dispatch-last-position)
6560 ;; We are in a different buffer, forget position.
6561 (move-marker org-export-dispatch-last-position nil)))
6562 (funcall action
6563 ;; Return a symbol instead of a list to ease
6564 ;; asynchronous export macro use.
6565 (and (memq 'async optns) t)
6566 (and (memq 'subtree optns) t)
6567 (and (memq 'visible optns) t)
6568 (and (memq 'body optns) t)))))))
6570 (defun org-export--dispatch-ui (options first-key expertp)
6571 "Handle interface for `org-export-dispatch'.
6573 OPTIONS is a list containing current interactive options set for
6574 export. It can contain any of the following symbols:
6575 `body' toggles a body-only export
6576 `subtree' restricts export to current subtree
6577 `visible' restricts export to visible part of buffer.
6578 `force' force publishing files.
6579 `async' use asynchronous export process
6581 FIRST-KEY is the key pressed to select the first level menu. It
6582 is nil when this menu hasn't been selected yet.
6584 EXPERTP, when non-nil, triggers expert UI. In that case, no help
6585 buffer is provided, but indications about currently active
6586 options are given in the prompt. Moreover, [?] allows switching
6587 back to standard interface."
6588 (let* ((fontify-key
6589 (lambda (key &optional access-key)
6590 ;; Fontify KEY string. Optional argument ACCESS-KEY, when
6591 ;; non-nil is the required first-level key to activate
6592 ;; KEY. When its value is t, activate KEY independently
6593 ;; on the first key, if any. A nil value means KEY will
6594 ;; only be activated at first level.
6595 (if (or (eq access-key t) (eq access-key first-key))
6596 (propertize key 'face 'org-warning)
6597 key)))
6598 (fontify-value
6599 (lambda (value)
6600 ;; Fontify VALUE string.
6601 (propertize value 'face 'font-lock-variable-name-face)))
6602 ;; Prepare menu entries by extracting them from registered
6603 ;; back-ends and sorting them by access key and by ordinal,
6604 ;; if any.
6605 (entries
6606 (sort (sort (delq nil
6607 (mapcar #'org-export-backend-menu
6608 org-export-registered-backends))
6609 (lambda (a b)
6610 (let ((key-a (nth 1 a))
6611 (key-b (nth 1 b)))
6612 (cond ((and (numberp key-a) (numberp key-b))
6613 (< key-a key-b))
6614 ((numberp key-b) t)))))
6615 'car-less-than-car))
6616 ;; Compute a list of allowed keys based on the first key
6617 ;; pressed, if any. Some keys
6618 ;; (?^B, ?^V, ?^S, ?^F, ?^A, ?&, ?# and ?q) are always
6619 ;; available.
6620 (allowed-keys
6621 (nconc (list 2 22 19 6 1)
6622 (if (not first-key) (org-uniquify (mapcar 'car entries))
6623 (let (sub-menu)
6624 (dolist (entry entries (sort (mapcar 'car sub-menu) '<))
6625 (when (eq (car entry) first-key)
6626 (setq sub-menu (append (nth 2 entry) sub-menu))))))
6627 (cond ((eq first-key ?P) (list ?f ?p ?x ?a))
6628 ((not first-key) (list ?P)))
6629 (list ?& ?#)
6630 (when expertp (list ??))
6631 (list ?q)))
6632 ;; Build the help menu for standard UI.
6633 (help
6634 (unless expertp
6635 (concat
6636 ;; Options are hard-coded.
6637 (format "[%s] Body only: %s [%s] Visible only: %s
6638 \[%s] Export scope: %s [%s] Force publishing: %s
6639 \[%s] Async export: %s\n\n"
6640 (funcall fontify-key "C-b" t)
6641 (funcall fontify-value
6642 (if (memq 'body options) "On " "Off"))
6643 (funcall fontify-key "C-v" t)
6644 (funcall fontify-value
6645 (if (memq 'visible options) "On " "Off"))
6646 (funcall fontify-key "C-s" t)
6647 (funcall fontify-value
6648 (if (memq 'subtree options) "Subtree" "Buffer "))
6649 (funcall fontify-key "C-f" t)
6650 (funcall fontify-value
6651 (if (memq 'force options) "On " "Off"))
6652 (funcall fontify-key "C-a" t)
6653 (funcall fontify-value
6654 (if (memq 'async options) "On " "Off")))
6655 ;; Display registered back-end entries. When a key
6656 ;; appears for the second time, do not create another
6657 ;; entry, but append its sub-menu to existing menu.
6658 (let (last-key)
6659 (mapconcat
6660 (lambda (entry)
6661 (let ((top-key (car entry)))
6662 (concat
6663 (unless (eq top-key last-key)
6664 (setq last-key top-key)
6665 (format "\n[%s] %s\n"
6666 (funcall fontify-key (char-to-string top-key))
6667 (nth 1 entry)))
6668 (let ((sub-menu (nth 2 entry)))
6669 (unless (functionp sub-menu)
6670 ;; Split sub-menu into two columns.
6671 (let ((index -1))
6672 (concat
6673 (mapconcat
6674 (lambda (sub-entry)
6675 (cl-incf index)
6676 (format
6677 (if (zerop (mod index 2)) " [%s] %-26s"
6678 "[%s] %s\n")
6679 (funcall fontify-key
6680 (char-to-string (car sub-entry))
6681 top-key)
6682 (nth 1 sub-entry)))
6683 sub-menu "")
6684 (when (zerop (mod index 2)) "\n"))))))))
6685 entries ""))
6686 ;; Publishing menu is hard-coded.
6687 (format "\n[%s] Publish
6688 [%s] Current file [%s] Current project
6689 [%s] Choose project [%s] All projects\n\n\n"
6690 (funcall fontify-key "P")
6691 (funcall fontify-key "f" ?P)
6692 (funcall fontify-key "p" ?P)
6693 (funcall fontify-key "x" ?P)
6694 (funcall fontify-key "a" ?P))
6695 (format "[%s] Export stack [%s] Insert template\n"
6696 (funcall fontify-key "&" t)
6697 (funcall fontify-key "#" t))
6698 (format "[%s] %s"
6699 (funcall fontify-key "q" t)
6700 (if first-key "Main menu" "Exit")))))
6701 ;; Build prompts for both standard and expert UI.
6702 (standard-prompt (unless expertp "Export command: "))
6703 (expert-prompt
6704 (when expertp
6705 (format
6706 "Export command (C-%s%s%s%s%s) [%s]: "
6707 (if (memq 'body options) (funcall fontify-key "b" t) "b")
6708 (if (memq 'visible options) (funcall fontify-key "v" t) "v")
6709 (if (memq 'subtree options) (funcall fontify-key "s" t) "s")
6710 (if (memq 'force options) (funcall fontify-key "f" t) "f")
6711 (if (memq 'async options) (funcall fontify-key "a" t) "a")
6712 (mapconcat (lambda (k)
6713 ;; Strip control characters.
6714 (unless (< k 27) (char-to-string k)))
6715 allowed-keys "")))))
6716 ;; With expert UI, just read key with a fancy prompt. In standard
6717 ;; UI, display an intrusive help buffer.
6718 (if expertp
6719 (org-export--dispatch-action
6720 expert-prompt allowed-keys entries options first-key expertp)
6721 ;; At first call, create frame layout in order to display menu.
6722 (unless (get-buffer "*Org Export Dispatcher*")
6723 (delete-other-windows)
6724 (org-switch-to-buffer-other-window
6725 (get-buffer-create "*Org Export Dispatcher*"))
6726 (setq cursor-type nil
6727 header-line-format "Use SPC, DEL, C-n or C-p to navigate.")
6728 ;; Make sure that invisible cursor will not highlight square
6729 ;; brackets.
6730 (set-syntax-table (copy-syntax-table))
6731 (modify-syntax-entry ?\[ "w"))
6732 ;; At this point, the buffer containing the menu exists and is
6733 ;; visible in the current window. So, refresh it.
6734 (with-current-buffer "*Org Export Dispatcher*"
6735 ;; Refresh help. Maintain display continuity by re-visiting
6736 ;; previous window position.
6737 (let ((pos (window-start)))
6738 (erase-buffer)
6739 (insert help)
6740 (set-window-start nil pos)))
6741 (org-fit-window-to-buffer)
6742 (org-export--dispatch-action
6743 standard-prompt allowed-keys entries options first-key expertp))))
6745 (defun org-export--dispatch-action
6746 (prompt allowed-keys entries options first-key expertp)
6747 "Read a character from command input and act accordingly.
6749 PROMPT is the displayed prompt, as a string. ALLOWED-KEYS is
6750 a list of characters available at a given step in the process.
6751 ENTRIES is a list of menu entries. OPTIONS, FIRST-KEY and
6752 EXPERTP are the same as defined in `org-export--dispatch-ui',
6753 which see.
6755 Toggle export options when required. Otherwise, return value is
6756 a list with action as CAR and a list of interactive export
6757 options as CDR."
6758 (let (key)
6759 ;; Scrolling: when in non-expert mode, act on motion keys (C-n,
6760 ;; C-p, SPC, DEL).
6761 (while (and (setq key (read-char-exclusive prompt))
6762 (not expertp)
6763 (memq key '(14 16 ?\s ?\d)))
6764 (cl-case key
6765 (14 (if (not (pos-visible-in-window-p (point-max)))
6766 (ignore-errors (scroll-up 1))
6767 (message "End of buffer")
6768 (sit-for 1)))
6769 (16 (if (not (pos-visible-in-window-p (point-min)))
6770 (ignore-errors (scroll-down 1))
6771 (message "Beginning of buffer")
6772 (sit-for 1)))
6773 (?\s (if (not (pos-visible-in-window-p (point-max)))
6774 (scroll-up nil)
6775 (message "End of buffer")
6776 (sit-for 1)))
6777 (?\d (if (not (pos-visible-in-window-p (point-min)))
6778 (scroll-down nil)
6779 (message "Beginning of buffer")
6780 (sit-for 1)))))
6781 (cond
6782 ;; Ignore undefined associations.
6783 ((not (memq key allowed-keys))
6784 (ding)
6785 (unless expertp (message "Invalid key") (sit-for 1))
6786 (org-export--dispatch-ui options first-key expertp))
6787 ;; q key at first level aborts export. At second level, cancel
6788 ;; first key instead.
6789 ((eq key ?q) (if (not first-key) (error "Export aborted")
6790 (org-export--dispatch-ui options nil expertp)))
6791 ;; Help key: Switch back to standard interface if expert UI was
6792 ;; active.
6793 ((eq key ??) (org-export--dispatch-ui options first-key nil))
6794 ;; Send request for template insertion along with export scope.
6795 ((eq key ?#) (cons 'template (memq 'subtree options)))
6796 ;; Switch to asynchronous export stack.
6797 ((eq key ?&) '(stack))
6798 ;; Toggle options: C-b (2) C-v (22) C-s (19) C-f (6) C-a (1).
6799 ((memq key '(2 22 19 6 1))
6800 (org-export--dispatch-ui
6801 (let ((option (cl-case key (2 'body) (22 'visible) (19 'subtree)
6802 (6 'force) (1 'async))))
6803 (if (memq option options) (remq option options)
6804 (cons option options)))
6805 first-key expertp))
6806 ;; Action selected: Send key and options back to
6807 ;; `org-export-dispatch'.
6808 ((or first-key (functionp (nth 2 (assq key entries))))
6809 (cons (cond
6810 ((not first-key) (nth 2 (assq key entries)))
6811 ;; Publishing actions are hard-coded. Send a special
6812 ;; signal to `org-export-dispatch'.
6813 ((eq first-key ?P)
6814 (cl-case key
6815 (?f 'publish-current-file)
6816 (?p 'publish-current-project)
6817 (?x 'publish-choose-project)
6818 (?a 'publish-all)))
6819 ;; Return first action associated to FIRST-KEY + KEY
6820 ;; path. Indeed, derived backends can share the same
6821 ;; FIRST-KEY.
6822 (t (catch 'found
6823 (dolist (entry (member (assq first-key entries) entries))
6824 (let ((match (assq key (nth 2 entry))))
6825 (when match (throw 'found (nth 2 match))))))))
6826 options))
6827 ;; Otherwise, enter sub-menu.
6828 (t (org-export--dispatch-ui options key expertp)))))
6832 (provide 'ox)
6834 ;; Local variables:
6835 ;; generated-autoload-file: "org-loaddefs.el"
6836 ;; End:
6838 ;;; ox.el ends here