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