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