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