Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / ox.el
blob49a9870fe0a14147ecd51b9447dc6c47e708c94a
1 ;;; ox.el --- Export Framework for Org Mode -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2012-2017 Free Software Foundation, Inc.
5 ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
6 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <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-src-coderef-format "org-src" (&optional element))
81 (declare-function org-src-coderef-regexp "org-src" (fmt &optional label))
82 (declare-function org-publish "ox-publish" (project &optional force async))
83 (declare-function org-publish-all "ox-publish" (&optional force async))
84 (declare-function org-publish-current-file "ox-publish" (&optional force async))
85 (declare-function org-publish-current-project "ox-publish" (&optional force async))
87 (defvar org-publish-project-alist)
88 (defvar org-table-number-fraction)
89 (defvar org-table-number-regexp)
92 ;;; Internal Variables
94 ;; Among internal variables, the most important is
95 ;; `org-export-options-alist'. This variable define the global export
96 ;; options, shared between every exporter, and how they are acquired.
98 (defconst org-export-max-depth 19
99 "Maximum nesting depth for headlines, counting from 0.")
101 (defconst org-export-options-alist
102 '((:title "TITLE" nil nil parse)
103 (:date "DATE" nil nil parse)
104 (:author "AUTHOR" nil user-full-name parse)
105 (:email "EMAIL" nil user-mail-address t)
106 (:language "LANGUAGE" nil org-export-default-language t)
107 (:select-tags "SELECT_TAGS" nil org-export-select-tags split)
108 (:exclude-tags "EXCLUDE_TAGS" nil org-export-exclude-tags split)
109 (:creator "CREATOR" nil org-export-creator-string)
110 (:headline-levels nil "H" org-export-headline-levels)
111 (:preserve-breaks nil "\\n" org-export-preserve-breaks)
112 (:section-numbers nil "num" org-export-with-section-numbers)
113 (:time-stamp-file nil "timestamp" org-export-time-stamp-file)
114 (:with-archived-trees nil "arch" org-export-with-archived-trees)
115 (:with-author nil "author" org-export-with-author)
116 (:with-broken-links nil "broken-links" org-export-with-broken-links)
117 (:with-clocks nil "c" org-export-with-clocks)
118 (:with-creator nil "creator" org-export-with-creator)
119 (:with-date nil "date" org-export-with-date)
120 (:with-drawers nil "d" org-export-with-drawers)
121 (:with-email nil "email" org-export-with-email)
122 (:with-emphasize nil "*" org-export-with-emphasize)
123 (:with-entities nil "e" org-export-with-entities)
124 (:with-fixed-width nil ":" org-export-with-fixed-width)
125 (:with-footnotes nil "f" org-export-with-footnotes)
126 (:with-inlinetasks nil "inline" org-export-with-inlinetasks)
127 (:with-latex nil "tex" org-export-with-latex)
128 (:with-planning nil "p" org-export-with-planning)
129 (:with-priority nil "pri" org-export-with-priority)
130 (:with-properties nil "prop" org-export-with-properties)
131 (:with-smart-quotes nil "'" org-export-with-smart-quotes)
132 (:with-special-strings nil "-" org-export-with-special-strings)
133 (:with-statistics-cookies nil "stat" org-export-with-statistics-cookies)
134 (:with-sub-superscript nil "^" org-export-with-sub-superscripts)
135 (:with-toc nil "toc" org-export-with-toc)
136 (:with-tables nil "|" org-export-with-tables)
137 (:with-tags nil "tags" org-export-with-tags)
138 (:with-tasks nil "tasks" org-export-with-tasks)
139 (:with-timestamps nil "<" org-export-with-timestamps)
140 (:with-title nil "title" org-export-with-title)
141 (:with-todo-keywords nil "todo" org-export-with-todo-keywords))
142 "Alist between export properties and ways to set them.
144 The key of the alist is the property name, and the value is a list
145 like (KEYWORD OPTION DEFAULT BEHAVIOR) where:
147 KEYWORD is a string representing a buffer keyword, or nil. Each
148 property defined this way can also be set, during subtree
149 export, through a headline property named after the keyword
150 with the \"EXPORT_\" prefix (i.e. DATE keyword and EXPORT_DATE
151 property).
152 OPTION is a string that could be found in an #+OPTIONS: line.
153 DEFAULT is the default value for the property.
154 BEHAVIOR determines how Org should handle multiple keywords for
155 the same property. It is a symbol among:
156 nil Keep old value and discard the new one.
157 t Replace old value with the new one.
158 `space' Concatenate the values, separating them with a space.
159 `newline' Concatenate the values, separating them with
160 a newline.
161 `split' Split values at white spaces, and cons them to the
162 previous list.
163 `parse' Parse value as a list of strings and Org objects,
164 which can then be transcoded with, e.g.,
165 `org-export-data'. It implies `space' behavior.
167 Values set through KEYWORD and OPTION have precedence over
168 DEFAULT.
170 All these properties should be back-end agnostic. Back-end
171 specific properties are set through `org-export-define-backend'.
172 Properties redefined there have precedence over these.")
174 (defconst org-export-special-keywords '("FILETAGS" "SETUPFILE" "OPTIONS")
175 "List of in-buffer keywords that require special treatment.
176 These keywords are not directly associated to a property. The
177 way they are handled must be hard-coded into
178 `org-export--get-inbuffer-options' function.")
180 (defconst org-export-filters-alist
181 '((:filter-body . org-export-filter-body-functions)
182 (:filter-bold . org-export-filter-bold-functions)
183 (:filter-babel-call . org-export-filter-babel-call-functions)
184 (:filter-center-block . org-export-filter-center-block-functions)
185 (:filter-clock . org-export-filter-clock-functions)
186 (:filter-code . org-export-filter-code-functions)
187 (:filter-diary-sexp . org-export-filter-diary-sexp-functions)
188 (:filter-drawer . org-export-filter-drawer-functions)
189 (:filter-dynamic-block . org-export-filter-dynamic-block-functions)
190 (:filter-entity . org-export-filter-entity-functions)
191 (:filter-example-block . org-export-filter-example-block-functions)
192 (:filter-export-block . org-export-filter-export-block-functions)
193 (:filter-export-snippet . org-export-filter-export-snippet-functions)
194 (:filter-final-output . org-export-filter-final-output-functions)
195 (:filter-fixed-width . org-export-filter-fixed-width-functions)
196 (:filter-footnote-definition . org-export-filter-footnote-definition-functions)
197 (:filter-footnote-reference . org-export-filter-footnote-reference-functions)
198 (:filter-headline . org-export-filter-headline-functions)
199 (:filter-horizontal-rule . org-export-filter-horizontal-rule-functions)
200 (:filter-inline-babel-call . org-export-filter-inline-babel-call-functions)
201 (:filter-inline-src-block . org-export-filter-inline-src-block-functions)
202 (:filter-inlinetask . org-export-filter-inlinetask-functions)
203 (:filter-italic . org-export-filter-italic-functions)
204 (:filter-item . org-export-filter-item-functions)
205 (:filter-keyword . org-export-filter-keyword-functions)
206 (:filter-latex-environment . org-export-filter-latex-environment-functions)
207 (:filter-latex-fragment . org-export-filter-latex-fragment-functions)
208 (:filter-line-break . org-export-filter-line-break-functions)
209 (:filter-link . org-export-filter-link-functions)
210 (:filter-node-property . org-export-filter-node-property-functions)
211 (:filter-options . org-export-filter-options-functions)
212 (:filter-paragraph . org-export-filter-paragraph-functions)
213 (:filter-parse-tree . org-export-filter-parse-tree-functions)
214 (:filter-plain-list . org-export-filter-plain-list-functions)
215 (:filter-plain-text . org-export-filter-plain-text-functions)
216 (:filter-planning . org-export-filter-planning-functions)
217 (:filter-property-drawer . org-export-filter-property-drawer-functions)
218 (:filter-quote-block . org-export-filter-quote-block-functions)
219 (:filter-radio-target . org-export-filter-radio-target-functions)
220 (:filter-section . org-export-filter-section-functions)
221 (:filter-special-block . org-export-filter-special-block-functions)
222 (:filter-src-block . org-export-filter-src-block-functions)
223 (:filter-statistics-cookie . org-export-filter-statistics-cookie-functions)
224 (:filter-strike-through . org-export-filter-strike-through-functions)
225 (:filter-subscript . org-export-filter-subscript-functions)
226 (:filter-superscript . org-export-filter-superscript-functions)
227 (:filter-table . org-export-filter-table-functions)
228 (:filter-table-cell . org-export-filter-table-cell-functions)
229 (:filter-table-row . org-export-filter-table-row-functions)
230 (:filter-target . org-export-filter-target-functions)
231 (:filter-timestamp . org-export-filter-timestamp-functions)
232 (:filter-underline . org-export-filter-underline-functions)
233 (:filter-verbatim . org-export-filter-verbatim-functions)
234 (:filter-verse-block . org-export-filter-verse-block-functions))
235 "Alist between filters properties and initial values.
237 The key of each association is a property name accessible through
238 the communication channel. Its value is a configurable global
239 variable defining initial filters.
241 This list is meant to install user specified filters. Back-end
242 developers may install their own filters using
243 `org-export-define-backend'. Filters defined there will always
244 be prepended to the current list, so they always get applied
245 first.")
247 (defconst org-export-default-inline-image-rule
248 `(("file" .
249 ,(format "\\.%s\\'"
250 (regexp-opt
251 '("png" "jpeg" "jpg" "gif" "tiff" "tif" "xbm"
252 "xpm" "pbm" "pgm" "ppm") t))))
253 "Default rule for link matching an inline image.
254 This rule applies to links with no description. By default, it
255 will be considered as an inline image if it targets a local file
256 whose extension is either \"png\", \"jpeg\", \"jpg\", \"gif\",
257 \"tiff\", \"tif\", \"xbm\", \"xpm\", \"pbm\", \"pgm\" or \"ppm\".
258 See `org-export-inline-image-p' for more information about
259 rules.")
261 (defconst org-export-ignored-local-variables
262 '(org-font-lock-keywords
263 org-element--cache org-element--cache-objects org-element--cache-sync-keys
264 org-element--cache-sync-requests org-element--cache-sync-timer)
265 "List of variables not copied through upon buffer duplication.
266 Export process takes place on a copy of the original buffer.
267 When this copy is created, all Org related local variables not in
268 this list are copied to the new buffer. Variables with an
269 unreadable value are also ignored.")
271 (defvar org-export-async-debug nil
272 "Non-nil means asynchronous export process should leave data behind.
274 This data is found in the appropriate \"*Org Export Process*\"
275 buffer, and in files prefixed with \"org-export-process\" and
276 located in `temporary-file-directory'.
278 When non-nil, it will also set `debug-on-error' to a non-nil
279 value in the external process.")
281 (defvar org-export-stack-contents nil
282 "Record asynchronously generated export results and processes.
283 This is an alist: its CAR is the source of the
284 result (destination file or buffer for a finished process,
285 original buffer for a running one) and its CDR is a list
286 containing the back-end used, as a symbol, and either a process
287 or the time at which it finished. It is used to build the menu
288 from `org-export-stack'.")
290 (defvar org-export-registered-backends nil
291 "List of backends currently available in the exporter.
292 This variable is set with `org-export-define-backend' and
293 `org-export-define-derived-backend' functions.")
295 (defvar org-export-dispatch-last-action nil
296 "Last command called from the dispatcher.
297 The value should be a list. Its CAR is the action, as a symbol,
298 and its CDR is a list of export options.")
300 (defvar org-export-dispatch-last-position (make-marker)
301 "The position where the last export command was created using the dispatcher.
302 This marker will be used with `C-u C-c C-e' to make sure export repetition
303 uses the same subtree if the previous command was restricted to a subtree.")
305 ;; For compatibility with Org < 8
306 (defvar org-export-current-backend nil
307 "Name, if any, of the back-end used during an export process.
309 Its value is a symbol such as `html', `latex', `ascii', or nil if
310 the back-end is anonymous (see `org-export-create-backend') or if
311 there is no export process in progress.
313 It can be used to teach Babel blocks how to act differently
314 according to the back-end used.")
318 ;;; User-configurable Variables
320 ;; Configuration for the masses.
322 ;; They should never be accessed directly, as their value is to be
323 ;; stored in a property list (cf. `org-export-options-alist').
324 ;; Back-ends will read their value from there instead.
326 (defgroup org-export nil
327 "Options for exporting Org mode files."
328 :tag "Org Export"
329 :group 'org)
331 (defgroup org-export-general nil
332 "General options for export engine."
333 :tag "Org Export General"
334 :group 'org-export)
336 (defcustom org-export-with-archived-trees 'headline
337 "Whether sub-trees with the ARCHIVE tag should be exported.
339 This can have three different values:
340 nil Do not export, pretend this tree is not present.
341 t Do export the entire tree.
342 `headline' Only export the headline, but skip the tree below it.
344 This option can also be set with the OPTIONS keyword,
345 e.g. \"arch:nil\"."
346 :group 'org-export-general
347 :type '(choice
348 (const :tag "Not at all" nil)
349 (const :tag "Headline only" headline)
350 (const :tag "Entirely" t))
351 :safe (lambda (x) (memq x '(t nil headline))))
353 (defcustom org-export-with-author t
354 "Non-nil means insert author name into the exported file.
355 This option can also be set with the OPTIONS keyword,
356 e.g. \"author:nil\"."
357 :group 'org-export-general
358 :type 'boolean
359 :safe #'booleanp)
361 (defcustom org-export-with-clocks nil
362 "Non-nil means export CLOCK keywords.
363 This option can also be set with the OPTIONS keyword,
364 e.g. \"c:t\"."
365 :group 'org-export-general
366 :type 'boolean
367 :safe #'booleanp)
369 (defcustom org-export-with-creator nil
370 "Non-nil means the postamble should contain a creator sentence.
372 The sentence can be set in `org-export-creator-string', which
373 see.
375 This option can also be set with the OPTIONS keyword, e.g.,
376 \"creator:t\"."
377 :group 'org-export-general
378 :version "26.1"
379 :package-version '(Org . "8.3")
380 :type 'boolean
381 :safe #'booleanp)
383 (defcustom org-export-with-date t
384 "Non-nil means insert date in the exported document.
385 This option can also be set with the OPTIONS keyword,
386 e.g. \"date:nil\"."
387 :group 'org-export-general
388 :type 'boolean
389 :safe #'booleanp)
391 (defcustom org-export-date-timestamp-format nil
392 "Time-stamp format string to use for DATE keyword.
394 The format string, when specified, only applies if date consists
395 in a single time-stamp. Otherwise its value will be ignored.
397 See `format-time-string' for details on how to build this
398 string."
399 :group 'org-export-general
400 :type '(choice
401 (string :tag "Time-stamp format string")
402 (const :tag "No format string" nil))
403 :safe (lambda (x) (or (null x) (stringp x))))
405 (defcustom org-export-creator-string
406 (format "Emacs %s (Org mode %s)"
407 emacs-version
408 (if (fboundp 'org-version) (org-version) "unknown version"))
409 "Information about the creator of the document.
410 This option can also be set on with the CREATOR keyword."
411 :group 'org-export-general
412 :type '(string :tag "Creator string")
413 :safe #'stringp)
415 (defcustom org-export-with-drawers '(not "LOGBOOK")
416 "Non-nil means export contents of standard drawers.
418 When t, all drawers are exported. This may also be a list of
419 drawer names to export, as strings. If that list starts with
420 `not', only drawers with such names will be ignored.
422 This variable doesn't apply to properties drawers. See
423 `org-export-with-properties' instead.
425 This option can also be set with the OPTIONS keyword,
426 e.g. \"d:nil\"."
427 :group 'org-export-general
428 :version "24.4"
429 :package-version '(Org . "8.0")
430 :type '(choice
431 (const :tag "All drawers" t)
432 (const :tag "None" nil)
433 (repeat :tag "Selected drawers"
434 (string :tag "Drawer name"))
435 (list :tag "Ignored drawers"
436 (const :format "" not)
437 (repeat :tag "Specify names of drawers to ignore during export"
438 :inline t
439 (string :tag "Drawer name"))))
440 :safe (lambda (x) (or (booleanp x)
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 "26.1"
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 "26.1"
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-global-macros nil
887 "Alist between macro names and expansion templates.
889 This variable defines macro expansion templates available
890 globally. Associations follow the pattern
892 (NAME . TEMPLATE)
894 where NAME is a string beginning with a letter and consisting of
895 alphanumeric characters only.
897 TEMPLATE is the string to which the macro is going to be
898 expanded. Inside, \"$1\", \"$2\"... are place-holders for
899 macro's arguments. Moreover, if the template starts with
900 \"(eval\", it will be parsed as an Elisp expression and evaluated
901 accordingly."
902 :group 'org-export-general
903 :version "26.1"
904 :package-version '(Org . "9.1")
905 :type '(repeat
906 (cons (string :tag "Name")
907 (string :tag "Template"))))
909 (defcustom org-export-coding-system nil
910 "Coding system for the exported file."
911 :group 'org-export-general
912 :version "24.4"
913 :package-version '(Org . "8.0")
914 :type 'coding-system)
916 (defcustom org-export-copy-to-kill-ring nil
917 "Non-nil means pushing export output to the kill ring.
918 This variable is ignored during asynchronous export."
919 :group 'org-export-general
920 :version "26.1"
921 :package-version '(Org . "8.3")
922 :type '(choice
923 (const :tag "Always" t)
924 (const :tag "When export is done interactively" if-interactive)
925 (const :tag "Never" nil)))
927 (defcustom org-export-initial-scope 'buffer
928 "The initial scope when exporting with `org-export-dispatch'.
929 This variable can be either set to `buffer' or `subtree'."
930 :group 'org-export-general
931 :type '(choice
932 (const :tag "Export current buffer" buffer)
933 (const :tag "Export current subtree" subtree)))
935 (defcustom org-export-show-temporary-export-buffer t
936 "Non-nil means show buffer after exporting to temp buffer.
937 When Org exports to a file, the buffer visiting that file is never
938 shown, but remains buried. However, when exporting to
939 a temporary buffer, that buffer is popped up in a second window.
940 When this variable is nil, the buffer remains buried also in
941 these cases."
942 :group 'org-export-general
943 :type 'boolean)
945 (defcustom org-export-in-background nil
946 "Non-nil means export and publishing commands will run in background.
947 Results from an asynchronous export are never displayed
948 automatically. But you can retrieve them with `\\[org-export-stack]'."
949 :group 'org-export-general
950 :version "24.4"
951 :package-version '(Org . "8.0")
952 :type 'boolean)
954 (defcustom org-export-async-init-file nil
955 "File used to initialize external export process.
957 Value must be either nil or an absolute file name. When nil, the
958 external process is launched like a regular Emacs session,
959 loading user's initialization file and any site specific
960 configuration. If a file is provided, it, and only it, is loaded
961 at start-up.
963 Therefore, using a specific configuration makes the process to
964 load faster and the export more portable."
965 :group 'org-export-general
966 :version "24.4"
967 :package-version '(Org . "8.0")
968 :type '(choice
969 (const :tag "Regular startup" nil)
970 (file :tag "Specific start-up file" :must-match t)))
972 (defcustom org-export-dispatch-use-expert-ui nil
973 "Non-nil means using a non-intrusive `org-export-dispatch'.
974 In that case, no help buffer is displayed. Though, an indicator
975 for current export scope is added to the prompt (\"b\" when
976 output is restricted to body only, \"s\" when it is restricted to
977 the current subtree, \"v\" when only visible elements are
978 considered for export, \"f\" when publishing functions should be
979 passed the FORCE argument and \"a\" when the export should be
980 asynchronous). Also, [?] allows switching back to standard
981 mode."
982 :group 'org-export-general
983 :version "24.4"
984 :package-version '(Org . "8.0")
985 :type 'boolean)
989 ;;; Defining Back-ends
991 ;; An export back-end is a structure with `org-export-backend' type
992 ;; and `name', `parent', `transcoders', `options', `filters', `blocks'
993 ;; and `menu' slots.
995 ;; At the lowest level, a back-end is created with
996 ;; `org-export-create-backend' function.
998 ;; A named back-end can be registered with
999 ;; `org-export-register-backend' function. A registered back-end can
1000 ;; later be referred to by its name, with `org-export-get-backend'
1001 ;; function. Also, such a back-end can become the parent of a derived
1002 ;; back-end from which slot values will be inherited by default.
1003 ;; `org-export-derived-backend-p' can check if a given back-end is
1004 ;; derived from a list of back-end names.
1006 ;; `org-export-get-all-transcoders', `org-export-get-all-options' and
1007 ;; `org-export-get-all-filters' return the full alist of transcoders,
1008 ;; options and filters, including those inherited from ancestors.
1010 ;; At a higher level, `org-export-define-backend' is the standard way
1011 ;; to define an export back-end. If the new back-end is similar to
1012 ;; a registered back-end, `org-export-define-derived-backend' may be
1013 ;; used instead.
1015 ;; Eventually `org-export-barf-if-invalid-backend' returns an error
1016 ;; when a given back-end hasn't been registered yet.
1018 (cl-defstruct (org-export-backend (:constructor org-export-create-backend)
1019 (:copier nil))
1020 name parent transcoders options filters blocks menu)
1022 ;;;###autoload
1023 (defun org-export-get-backend (name)
1024 "Return export back-end named after NAME.
1025 NAME is a symbol. Return nil if no such back-end is found."
1026 (cl-find-if (lambda (b) (and (eq name (org-export-backend-name b))))
1027 org-export-registered-backends))
1029 (defun org-export-register-backend (backend)
1030 "Register BACKEND as a known export back-end.
1031 BACKEND is a structure with `org-export-backend' type."
1032 ;; Refuse to register an unnamed back-end.
1033 (unless (org-export-backend-name backend)
1034 (error "Cannot register a unnamed export back-end"))
1035 ;; Refuse to register a back-end with an unknown parent.
1036 (let ((parent (org-export-backend-parent backend)))
1037 (when (and parent (not (org-export-get-backend parent)))
1038 (error "Cannot use unknown \"%s\" back-end as a parent" parent)))
1039 ;; If a back-end with the same name as BACKEND is already
1040 ;; registered, replace it with BACKEND. Otherwise, simply add
1041 ;; BACKEND to the list of registered back-ends.
1042 (let ((old (org-export-get-backend (org-export-backend-name backend))))
1043 (if old (setcar (memq old org-export-registered-backends) backend)
1044 (push backend org-export-registered-backends))))
1046 (defun org-export-barf-if-invalid-backend (backend)
1047 "Signal an error if BACKEND isn't defined."
1048 (unless (org-export-backend-p backend)
1049 (error "Unknown \"%s\" back-end: Aborting export" backend)))
1051 (defun org-export-derived-backend-p (backend &rest backends)
1052 "Non-nil if BACKEND is derived from one of BACKENDS.
1053 BACKEND is an export back-end, as returned by, e.g.,
1054 `org-export-create-backend', or a symbol referring to
1055 a registered back-end. BACKENDS is constituted of symbols."
1056 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
1057 (when backend
1058 (catch 'exit
1059 (while (org-export-backend-parent backend)
1060 (when (memq (org-export-backend-name backend) backends)
1061 (throw 'exit t))
1062 (setq backend
1063 (org-export-get-backend (org-export-backend-parent backend))))
1064 (memq (org-export-backend-name backend) backends))))
1066 (defun org-export-get-all-transcoders (backend)
1067 "Return full translation table for BACKEND.
1069 BACKEND is an export back-end, as return by, e.g,,
1070 `org-export-create-backend'. Return value is an alist where
1071 keys are element or object types, as symbols, and values are
1072 transcoders.
1074 Unlike to `org-export-backend-transcoders', this function
1075 also returns transcoders inherited from parent back-ends,
1076 if any."
1077 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
1078 (when backend
1079 (let ((transcoders (org-export-backend-transcoders backend))
1080 parent)
1081 (while (setq parent (org-export-backend-parent backend))
1082 (setq backend (org-export-get-backend parent))
1083 (setq transcoders
1084 (append transcoders (org-export-backend-transcoders backend))))
1085 transcoders)))
1087 (defun org-export-get-all-options (backend)
1088 "Return export options for BACKEND.
1090 BACKEND is an export back-end, as return by, e.g,,
1091 `org-export-create-backend'. See `org-export-options-alist'
1092 for the shape of the return value.
1094 Unlike to `org-export-backend-options', this function also
1095 returns options inherited from parent back-ends, if any."
1096 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
1097 (when backend
1098 (let ((options (org-export-backend-options backend))
1099 parent)
1100 (while (setq parent (org-export-backend-parent backend))
1101 (setq backend (org-export-get-backend parent))
1102 (setq options (append options (org-export-backend-options backend))))
1103 options)))
1105 (defun org-export-get-all-filters (backend)
1106 "Return complete list of filters for BACKEND.
1108 BACKEND is an export back-end, as return by, e.g,,
1109 `org-export-create-backend'. Return value is an alist where
1110 keys are symbols and values lists of functions.
1112 Unlike to `org-export-backend-filters', this function also
1113 returns filters inherited from parent back-ends, if any."
1114 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
1115 (when backend
1116 (let ((filters (org-export-backend-filters backend))
1117 parent)
1118 (while (setq parent (org-export-backend-parent backend))
1119 (setq backend (org-export-get-backend parent))
1120 (setq filters (append filters (org-export-backend-filters backend))))
1121 filters)))
1123 (defun org-export-define-backend (backend transcoders &rest body)
1124 "Define a new back-end BACKEND.
1126 TRANSCODERS is an alist between object or element types and
1127 functions handling them.
1129 These functions should return a string without any trailing
1130 space, or nil. They must accept three arguments: the object or
1131 element itself, its contents or nil when it isn't recursive and
1132 the property list used as a communication channel.
1134 Contents, when not nil, are stripped from any global indentation
1135 \(although the relative one is preserved). They also always end
1136 with a single newline character.
1138 If, for a given type, no function is found, that element or
1139 object type will simply be ignored, along with any blank line or
1140 white space at its end. The same will happen if the function
1141 returns the nil value. If that function returns the empty
1142 string, the type will be ignored, but the blank lines or white
1143 spaces will be kept.
1145 In addition to element and object types, one function can be
1146 associated to the `template' (or `inner-template') symbol and
1147 another one to the `plain-text' symbol.
1149 The former returns the final transcoded string, and can be used
1150 to add a preamble and a postamble to document's body. It must
1151 accept two arguments: the transcoded string and the property list
1152 containing export options. A function associated to `template'
1153 will not be applied if export has option \"body-only\".
1154 A function associated to `inner-template' is always applied.
1156 The latter, when defined, is to be called on every text not
1157 recognized as an element or an object. It must accept two
1158 arguments: the text string and the information channel. It is an
1159 appropriate place to protect special chars relative to the
1160 back-end.
1162 BODY can start with pre-defined keyword arguments. The following
1163 keywords are understood:
1165 :filters-alist
1167 Alist between filters and function, or list of functions,
1168 specific to the back-end. See `org-export-filters-alist' for
1169 a list of all allowed filters. Filters defined here
1170 shouldn't make a back-end test, as it may prevent back-ends
1171 derived from this one to behave properly.
1173 :menu-entry
1175 Menu entry for the export dispatcher. It should be a list
1176 like:
1178 \\='(KEY DESCRIPTION-OR-ORDINAL ACTION-OR-MENU)
1180 where :
1182 KEY is a free character selecting the back-end.
1184 DESCRIPTION-OR-ORDINAL is either a string or a number.
1186 If it is a string, is will be used to name the back-end in
1187 its menu entry. If it is a number, the following menu will
1188 be displayed as a sub-menu of the back-end with the same
1189 KEY. Also, the number will be used to determine in which
1190 order such sub-menus will appear (lowest first).
1192 ACTION-OR-MENU is either a function or an alist.
1194 If it is an action, it will be called with four
1195 arguments (booleans): ASYNC, SUBTREEP, VISIBLE-ONLY and
1196 BODY-ONLY. See `org-export-as' for further explanations on
1197 some of them.
1199 If it is an alist, associations should follow the
1200 pattern:
1202 \\='(KEY DESCRIPTION ACTION)
1204 where KEY, DESCRIPTION and ACTION are described above.
1206 Valid values include:
1208 \\='(?m \"My Special Back-end\" my-special-export-function)
1212 \\='(?l \"Export to LaTeX\"
1213 (?p \"As PDF file\" org-latex-export-to-pdf)
1214 (?o \"As PDF file and open\"
1215 (lambda (a s v b)
1216 (if a (org-latex-export-to-pdf t s v b)
1217 (org-open-file
1218 (org-latex-export-to-pdf nil s v b)))))))
1220 or the following, which will be added to the previous
1221 sub-menu,
1223 \\='(?l 1
1224 ((?B \"As TEX buffer (Beamer)\" org-beamer-export-as-latex)
1225 (?P \"As PDF file (Beamer)\" org-beamer-export-to-pdf)))
1227 :options-alist
1229 Alist between back-end specific properties introduced in
1230 communication channel and how their value are acquired. See
1231 `org-export-options-alist' for more information about
1232 structure of the values."
1233 (declare (indent 1))
1234 (let (filters menu-entry options)
1235 (while (keywordp (car body))
1236 (let ((keyword (pop body)))
1237 (pcase keyword
1238 (:filters-alist (setq filters (pop body)))
1239 (:menu-entry (setq menu-entry (pop body)))
1240 (:options-alist (setq options (pop body)))
1241 (_ (error "Unknown keyword: %s" keyword)))))
1242 (org-export-register-backend
1243 (org-export-create-backend :name backend
1244 :transcoders transcoders
1245 :options options
1246 :filters filters
1247 :menu menu-entry))))
1249 (defun org-export-define-derived-backend (child parent &rest body)
1250 "Create a new back-end as a variant of an existing one.
1252 CHILD is the name of the derived back-end. PARENT is the name of
1253 the parent back-end.
1255 BODY can start with pre-defined keyword arguments. The following
1256 keywords are understood:
1258 :filters-alist
1260 Alist of filters that will overwrite or complete filters
1261 defined in PARENT back-end. See `org-export-filters-alist'
1262 for a list of allowed filters.
1264 :menu-entry
1266 Menu entry for the export dispatcher. See
1267 `org-export-define-backend' for more information about the
1268 expected value.
1270 :options-alist
1272 Alist of back-end specific properties that will overwrite or
1273 complete those defined in PARENT back-end. Refer to
1274 `org-export-options-alist' for more information about
1275 structure of the values.
1277 :translate-alist
1279 Alist of element and object types and transcoders that will
1280 overwrite or complete transcode table from PARENT back-end.
1281 Refer to `org-export-define-backend' for detailed information
1282 about transcoders.
1284 As an example, here is how one could define \"my-latex\" back-end
1285 as a variant of `latex' back-end with a custom template function:
1287 (org-export-define-derived-backend \\='my-latex \\='latex
1288 :translate-alist \\='((template . my-latex-template-fun)))
1290 The back-end could then be called with, for example:
1292 (org-export-to-buffer \\='my-latex \"*Test my-latex*\")"
1293 (declare (indent 2))
1294 (let (filters menu-entry options transcoders)
1295 (while (keywordp (car body))
1296 (let ((keyword (pop body)))
1297 (pcase keyword
1298 (:filters-alist (setq filters (pop body)))
1299 (:menu-entry (setq menu-entry (pop body)))
1300 (:options-alist (setq options (pop body)))
1301 (:translate-alist (setq transcoders (pop body)))
1302 (_ (error "Unknown keyword: %s" keyword)))))
1303 (org-export-register-backend
1304 (org-export-create-backend :name child
1305 :parent parent
1306 :transcoders transcoders
1307 :options options
1308 :filters filters
1309 :menu menu-entry))))
1313 ;;; The Communication Channel
1315 ;; During export process, every function has access to a number of
1316 ;; properties. They are of two types:
1318 ;; 1. Environment options are collected once at the very beginning of
1319 ;; the process, out of the original buffer and configuration.
1320 ;; Collecting them is handled by `org-export-get-environment'
1321 ;; function.
1323 ;; Most environment options are defined through the
1324 ;; `org-export-options-alist' variable.
1326 ;; 2. Tree properties are extracted directly from the parsed tree,
1327 ;; just before export, by `org-export--collect-tree-properties'.
1329 ;;;; Environment Options
1331 ;; Environment options encompass all parameters defined outside the
1332 ;; scope of the parsed data. They come from five sources, in
1333 ;; increasing precedence order:
1335 ;; - Global variables,
1336 ;; - Buffer's attributes,
1337 ;; - Options keyword symbols,
1338 ;; - Buffer keywords,
1339 ;; - Subtree properties.
1341 ;; The central internal function with regards to environment options
1342 ;; is `org-export-get-environment'. It updates global variables with
1343 ;; "#+BIND:" keywords, then retrieve and prioritize properties from
1344 ;; the different sources.
1346 ;; The internal functions doing the retrieval are:
1347 ;; `org-export--get-global-options',
1348 ;; `org-export--get-buffer-attributes',
1349 ;; `org-export--parse-option-keyword',
1350 ;; `org-export--get-subtree-options' and
1351 ;; `org-export--get-inbuffer-options'
1353 ;; Also, `org-export--list-bound-variables' collects bound variables
1354 ;; along with their value in order to set them as buffer local
1355 ;; variables later in the process.
1357 ;;;###autoload
1358 (defun org-export-get-environment (&optional backend subtreep ext-plist)
1359 "Collect export options from the current buffer.
1361 Optional argument BACKEND is an export back-end, as returned by
1362 `org-export-create-backend'.
1364 When optional argument SUBTREEP is non-nil, assume the export is
1365 done against the current sub-tree.
1367 Third optional argument EXT-PLIST is a property list with
1368 external parameters overriding Org default settings, but still
1369 inferior to file-local settings."
1370 ;; First install #+BIND variables since these must be set before
1371 ;; global options are read.
1372 (dolist (pair (org-export--list-bound-variables))
1373 (set (make-local-variable (car pair)) (nth 1 pair)))
1374 ;; Get and prioritize export options...
1375 (org-combine-plists
1376 ;; ... from global variables...
1377 (org-export--get-global-options backend)
1378 ;; ... from an external property list...
1379 ext-plist
1380 ;; ... from in-buffer settings...
1381 (org-export--get-inbuffer-options backend)
1382 ;; ... and from subtree, when appropriate.
1383 (and subtreep (org-export--get-subtree-options backend))))
1385 (defun org-export--parse-option-keyword (options &optional backend)
1386 "Parse an OPTIONS line and return values as a plist.
1387 Optional argument BACKEND is an export back-end, as returned by,
1388 e.g., `org-export-create-backend'. It specifies which back-end
1389 specific items to read, if any."
1390 (let ((line
1391 (let ((s 0) alist)
1392 (while (string-match "\\(.+?\\):\\((.*?)\\|\\S-*\\)[ \t]*" options s)
1393 (setq s (match-end 0))
1394 (push (cons (match-string 1 options)
1395 (read (match-string 2 options)))
1396 alist))
1397 alist))
1398 ;; Priority is given to back-end specific options.
1399 (all (append (and backend (org-export-get-all-options backend))
1400 org-export-options-alist))
1401 (plist))
1402 (when line
1403 (dolist (entry all plist)
1404 (let ((item (nth 2 entry)))
1405 (when item
1406 (let ((v (assoc-string item line t)))
1407 (when v (setq plist (plist-put plist (car entry) (cdr v)))))))))))
1409 (defun org-export--get-subtree-options (&optional backend)
1410 "Get export options in subtree at point.
1411 Optional argument BACKEND is an export back-end, as returned by,
1412 e.g., `org-export-create-backend'. It specifies back-end used
1413 for export. Return options as a plist."
1414 ;; For each buffer keyword, create a headline property setting the
1415 ;; same property in communication channel. The name for the
1416 ;; property is the keyword with "EXPORT_" appended to it.
1417 (org-with-wide-buffer
1418 ;; Make sure point is at a heading.
1419 (if (org-at-heading-p) (org-up-heading-safe) (org-back-to-heading t))
1420 (let ((plist
1421 ;; EXPORT_OPTIONS are parsed in a non-standard way. Take
1422 ;; care of them right from the start.
1423 (let ((o (org-entry-get (point) "EXPORT_OPTIONS" 'selective)))
1424 (and o (org-export--parse-option-keyword o backend))))
1425 ;; Take care of EXPORT_TITLE. If it isn't defined, use
1426 ;; headline's title (with no todo keyword, priority cookie or
1427 ;; tag) as its fallback value.
1428 (cache (list
1429 (cons "TITLE"
1430 (or (org-entry-get (point) "EXPORT_TITLE" 'selective)
1431 (let ((case-fold-search nil))
1432 (looking-at org-complex-heading-regexp)
1433 (match-string-no-properties 4))))))
1434 ;; Look for both general keywords and back-end specific
1435 ;; options, with priority given to the latter.
1436 (options (append (and backend (org-export-get-all-options backend))
1437 org-export-options-alist)))
1438 ;; Handle other keywords. Then return PLIST.
1439 (dolist (option options plist)
1440 (let ((property (car option))
1441 (keyword (nth 1 option)))
1442 (when keyword
1443 (let ((value
1444 (or (cdr (assoc keyword cache))
1445 (let ((v (org-entry-get (point)
1446 (concat "EXPORT_" keyword)
1447 'selective)))
1448 (push (cons keyword v) cache) v))))
1449 (when value
1450 (setq plist
1451 (plist-put plist
1452 property
1453 (cl-case (nth 4 option)
1454 (parse
1455 (org-element-parse-secondary-string
1456 value (org-element-restriction 'keyword)))
1457 (split (org-split-string value))
1458 (t value))))))))))))
1460 (defun org-export--get-inbuffer-options (&optional backend)
1461 "Return current buffer export options, as a plist.
1463 Optional argument BACKEND, when non-nil, is an export back-end,
1464 as returned by, e.g., `org-export-create-backend'. It specifies
1465 which back-end specific options should also be read in the
1466 process.
1468 Assume buffer is in Org mode. Narrowing, if any, is ignored."
1469 (let* ((case-fold-search t)
1470 (options (append
1471 ;; Priority is given to back-end specific options.
1472 (and backend (org-export-get-all-options backend))
1473 org-export-options-alist))
1474 (regexp (format "^[ \t]*#\\+%s:"
1475 (regexp-opt (nconc (delq nil (mapcar #'cadr options))
1476 org-export-special-keywords))))
1477 plist to-parse)
1478 (letrec ((find-properties
1479 (lambda (keyword)
1480 ;; Return all properties associated to KEYWORD.
1481 (let (properties)
1482 (dolist (option options properties)
1483 (when (equal (nth 1 option) keyword)
1484 (cl-pushnew (car option) properties))))))
1485 (get-options
1486 (lambda (&optional files)
1487 ;; Recursively read keywords in buffer. FILES is
1488 ;; a list of files read so far. PLIST is the current
1489 ;; property list obtained.
1490 (org-with-wide-buffer
1491 (goto-char (point-min))
1492 (while (re-search-forward regexp nil t)
1493 (let ((element (org-element-at-point)))
1494 (when (eq (org-element-type element) 'keyword)
1495 (let ((key (org-element-property :key element))
1496 (val (org-element-property :value element)))
1497 (cond
1498 ;; Options in `org-export-special-keywords'.
1499 ((equal key "SETUPFILE")
1500 (let ((file
1501 (expand-file-name
1502 (org-unbracket-string "\"" "\"" (org-trim val)))))
1503 ;; Avoid circular dependencies.
1504 (unless (member file files)
1505 (with-temp-buffer
1506 (setq default-directory
1507 (file-name-directory file))
1508 (insert (org-file-contents file 'noerror))
1509 (let ((org-inhibit-startup t)) (org-mode))
1510 (funcall get-options (cons file files))))))
1511 ((equal key "OPTIONS")
1512 (setq plist
1513 (org-combine-plists
1514 plist
1515 (org-export--parse-option-keyword
1516 val backend))))
1517 ((equal key "FILETAGS")
1518 (setq plist
1519 (org-combine-plists
1520 plist
1521 (list :filetags
1522 (org-uniquify
1523 (append
1524 (org-split-string val ":")
1525 (plist-get plist :filetags)))))))
1527 ;; Options in `org-export-options-alist'.
1528 (dolist (property (funcall find-properties key))
1529 (setq
1530 plist
1531 (plist-put
1532 plist property
1533 ;; Handle value depending on specified
1534 ;; BEHAVIOR.
1535 (cl-case (nth 4 (assq property options))
1536 (parse
1537 (unless (memq property to-parse)
1538 (push property to-parse))
1539 ;; Even if `parse' implies `space'
1540 ;; behavior, we separate line with
1541 ;; "\n" so as to preserve
1542 ;; line-breaks. However, empty
1543 ;; lines are forbidden since `parse'
1544 ;; doesn't allow more than one
1545 ;; paragraph.
1546 (let ((old (plist-get plist property)))
1547 (cond ((not (org-string-nw-p val)) old)
1548 (old (concat old "\n" val))
1549 (t val))))
1550 (space
1551 (if (not (plist-get plist property))
1552 (org-trim val)
1553 (concat (plist-get plist property)
1555 (org-trim val))))
1556 (newline
1557 (org-trim
1558 (concat (plist-get plist property)
1559 "\n"
1560 (org-trim val))))
1561 (split `(,@(plist-get plist property)
1562 ,@(org-split-string val)))
1563 ((t) val)
1564 (otherwise
1565 (if (not (plist-member plist property)) val
1566 (plist-get plist property)))))))))))))))))
1567 ;; Read options in the current buffer and return value.
1568 (funcall get-options (and buffer-file-name (list buffer-file-name)))
1569 ;; Parse properties in TO-PARSE. Remove newline characters not
1570 ;; involved in line breaks to simulate `space' behavior.
1571 ;; Finally return options.
1572 (dolist (p to-parse plist)
1573 (let ((value (org-element-parse-secondary-string
1574 (plist-get plist p)
1575 (org-element-restriction 'keyword))))
1576 (org-element-map value 'plain-text
1577 (lambda (s)
1578 (org-element-set-element
1579 s (replace-regexp-in-string "\n" " " s))))
1580 (setq plist (plist-put plist p value)))))))
1582 (defun org-export--get-export-attributes
1583 (&optional backend subtreep visible-only body-only)
1584 "Return properties related to export process, as a plist.
1585 Optional arguments BACKEND, SUBTREEP, VISIBLE-ONLY and BODY-ONLY
1586 are like the arguments with the same names of function
1587 `org-export-as'."
1588 (list :export-options (delq nil
1589 (list (and subtreep 'subtree)
1590 (and visible-only 'visible-only)
1591 (and body-only 'body-only)))
1592 :back-end backend
1593 :translate-alist (org-export-get-all-transcoders backend)
1594 :exported-data (make-hash-table :test #'eq :size 4001)))
1596 (defun org-export--get-buffer-attributes ()
1597 "Return properties related to buffer attributes, as a plist."
1598 (list :input-buffer (buffer-name (buffer-base-buffer))
1599 :input-file (buffer-file-name (buffer-base-buffer))))
1601 (defun org-export--get-global-options (&optional backend)
1602 "Return global export options as a plist.
1603 Optional argument BACKEND, if non-nil, is an export back-end, as
1604 returned by, e.g., `org-export-create-backend'. It specifies
1605 which back-end specific export options should also be read in the
1606 process."
1607 (let (plist
1608 ;; Priority is given to back-end specific options.
1609 (all (append (and backend (org-export-get-all-options backend))
1610 org-export-options-alist)))
1611 (dolist (cell all plist)
1612 (let ((prop (car cell)))
1613 (unless (plist-member plist prop)
1614 (setq plist
1615 (plist-put
1616 plist
1617 prop
1618 ;; Evaluate default value provided.
1619 (let ((value (eval (nth 3 cell))))
1620 (if (eq (nth 4 cell) 'parse)
1621 (org-element-parse-secondary-string
1622 value (org-element-restriction 'keyword))
1623 value)))))))))
1625 (defun org-export--list-bound-variables ()
1626 "Return variables bound from BIND keywords in current buffer.
1627 Also look for BIND keywords in setup files. The return value is
1628 an alist where associations are (VARIABLE-NAME VALUE)."
1629 (when org-export-allow-bind-keywords
1630 (letrec ((collect-bind
1631 (lambda (files alist)
1632 ;; Return an alist between variable names and their
1633 ;; value. FILES is a list of setup files names read
1634 ;; so far, used to avoid circular dependencies. ALIST
1635 ;; is the alist collected so far.
1636 (let ((case-fold-search t))
1637 (org-with-wide-buffer
1638 (goto-char (point-min))
1639 (while (re-search-forward
1640 "^[ \t]*#\\+\\(BIND\\|SETUPFILE\\):" nil t)
1641 (let ((element (org-element-at-point)))
1642 (when (eq (org-element-type element) 'keyword)
1643 (let ((val (org-element-property :value element)))
1644 (if (equal (org-element-property :key element)
1645 "BIND")
1646 (push (read (format "(%s)" val)) alist)
1647 ;; Enter setup file.
1648 (let ((file (expand-file-name
1649 (org-unbracket-string "\"" "\"" val))))
1650 (unless (member file files)
1651 (with-temp-buffer
1652 (setq default-directory
1653 (file-name-directory file))
1654 (let ((org-inhibit-startup t)) (org-mode))
1655 (insert (org-file-contents file 'noerror))
1656 (setq alist
1657 (funcall collect-bind
1658 (cons file files)
1659 alist))))))))))
1660 alist)))))
1661 ;; Return value in appropriate order of appearance.
1662 (nreverse (funcall collect-bind nil nil)))))
1664 ;; defsubst org-export-get-parent must be defined before first use,
1665 ;; was originally defined in the topology section
1667 (defsubst org-export-get-parent (blob)
1668 "Return BLOB parent or nil.
1669 BLOB is the element or object considered."
1670 (org-element-property :parent blob))
1672 ;;;; Tree Properties
1674 ;; Tree properties are information extracted from parse tree. They
1675 ;; are initialized at the beginning of the transcoding process by
1676 ;; `org-export--collect-tree-properties'.
1678 ;; Dedicated functions focus on computing the value of specific tree
1679 ;; properties during initialization. Thus,
1680 ;; `org-export--populate-ignore-list' lists elements and objects that
1681 ;; should be skipped during export, `org-export--get-min-level' gets
1682 ;; the minimal exportable level, used as a basis to compute relative
1683 ;; level for headlines. Eventually
1684 ;; `org-export--collect-headline-numbering' builds an alist between
1685 ;; headlines and their numbering.
1687 (defun org-export--collect-tree-properties (data info)
1688 "Extract tree properties from parse tree.
1690 DATA is the parse tree from which information is retrieved. INFO
1691 is a list holding export options.
1693 Following tree properties are set or updated:
1695 `:headline-offset' Offset between true level of headlines and
1696 local level. An offset of -1 means a headline
1697 of level 2 should be considered as a level
1698 1 headline in the context.
1700 `:headline-numbering' Alist of all headlines as key and the
1701 associated numbering as value.
1703 `:id-alist' Alist of all ID references as key and associated file
1704 as value.
1706 Return updated plist."
1707 ;; Install the parse tree in the communication channel.
1708 (setq info (plist-put info :parse-tree data))
1709 ;; Compute `:headline-offset' in order to be able to use
1710 ;; `org-export-get-relative-level'.
1711 (setq info
1712 (plist-put info
1713 :headline-offset
1714 (- 1 (org-export--get-min-level data info))))
1715 ;; From now on, properties order doesn't matter: get the rest of the
1716 ;; tree properties.
1717 (org-combine-plists
1718 info
1719 (list :headline-numbering (org-export--collect-headline-numbering data info)
1720 :id-alist
1721 (org-element-map data 'link
1722 (lambda (l)
1723 (and (string= (org-element-property :type l) "id")
1724 (let* ((id (org-element-property :path l))
1725 (file (car (org-id-find id))))
1726 (and file (cons id (file-relative-name file))))))))))
1728 (defun org-export--get-min-level (data options)
1729 "Return minimum exportable headline's level in DATA.
1730 DATA is parsed tree as returned by `org-element-parse-buffer'.
1731 OPTIONS is a plist holding export options."
1732 (catch 'exit
1733 (let ((min-level 10000))
1734 (dolist (datum (org-element-contents data))
1735 (when (and (eq (org-element-type datum) 'headline)
1736 (not (org-element-property :footnote-section-p datum))
1737 (not (memq datum (plist-get options :ignore-list))))
1738 (setq min-level (min (org-element-property :level datum) min-level))
1739 (when (= min-level 1) (throw 'exit 1))))
1740 ;; If no headline was found, for the sake of consistency, set
1741 ;; minimum level to 1 nonetheless.
1742 (if (= min-level 10000) 1 min-level))))
1744 (defun org-export--collect-headline-numbering (data options)
1745 "Return numbering of all exportable, numbered headlines in a parse tree.
1747 DATA is the parse tree. OPTIONS is the plist holding export
1748 options.
1750 Return an alist whose key is a headline and value is its
1751 associated numbering \(in the shape of a list of numbers) or nil
1752 for a footnotes section."
1753 (let ((numbering (make-vector org-export-max-depth 0)))
1754 (org-element-map data 'headline
1755 (lambda (headline)
1756 (when (and (org-export-numbered-headline-p headline options)
1757 (not (org-element-property :footnote-section-p headline)))
1758 (let ((relative-level
1759 (1- (org-export-get-relative-level headline options))))
1760 (cons
1761 headline
1762 (cl-loop
1763 for n across numbering
1764 for idx from 0 to org-export-max-depth
1765 when (< idx relative-level) collect n
1766 when (= idx relative-level) collect (aset numbering idx (1+ n))
1767 when (> idx relative-level) do (aset numbering idx 0))))))
1768 options)))
1770 (defun org-export--selected-trees (data info)
1771 "List headlines and inlinetasks with a select tag in their tree.
1772 DATA is parsed data as returned by `org-element-parse-buffer'.
1773 INFO is a plist holding export options."
1774 (let ((select (plist-get info :select-tags)))
1775 (if (cl-some (lambda (tag) (member tag select)) (plist-get info :filetags))
1776 ;; If FILETAGS contains a select tag, every headline or
1777 ;; inlinetask is returned.
1778 (org-element-map data '(headline inlinetask) #'identity)
1779 (letrec ((selected-trees nil)
1780 (walk-data
1781 (lambda (data genealogy)
1782 (let ((type (org-element-type data)))
1783 (cond
1784 ((memq type '(headline inlinetask))
1785 (let ((tags (org-element-property :tags data)))
1786 (if (cl-some (lambda (tag) (member tag select)) tags)
1787 ;; When a select tag is found, mark full
1788 ;; genealogy and every headline within the
1789 ;; tree as acceptable.
1790 (setq selected-trees
1791 (append
1792 genealogy
1793 (org-element-map data '(headline inlinetask)
1794 #'identity)
1795 selected-trees))
1796 ;; If at a headline, continue searching in
1797 ;; tree, recursively.
1798 (when (eq type 'headline)
1799 (dolist (el (org-element-contents data))
1800 (funcall walk-data el (cons data genealogy)))))))
1801 ((or (eq type 'org-data)
1802 (memq type org-element-greater-elements))
1803 (dolist (el (org-element-contents data))
1804 (funcall walk-data el genealogy))))))))
1805 (funcall walk-data data nil)
1806 selected-trees))))
1808 (defun org-export--skip-p (datum options selected)
1809 "Non-nil when element or object DATUM should be skipped during export.
1810 OPTIONS is the plist holding export options. SELECTED, when
1811 non-nil, is a list of headlines or inlinetasks belonging to
1812 a tree with a select tag."
1813 (cl-case (org-element-type datum)
1814 ((comment comment-block)
1815 ;; Skip all comments and comment blocks. Make to keep maximum
1816 ;; number of blank lines around the comment so as to preserve
1817 ;; local structure of the document upon interpreting it back into
1818 ;; Org syntax.
1819 (let* ((previous (org-export-get-previous-element datum options))
1820 (before (or (org-element-property :post-blank previous) 0))
1821 (after (or (org-element-property :post-blank datum) 0)))
1822 (when previous
1823 (org-element-put-property previous :post-blank (max before after 1))))
1825 (clock (not (plist-get options :with-clocks)))
1826 (drawer
1827 (let ((with-drawers-p (plist-get options :with-drawers)))
1828 (or (not with-drawers-p)
1829 (and (consp with-drawers-p)
1830 ;; If `:with-drawers' value starts with `not', ignore
1831 ;; every drawer whose name belong to that list.
1832 ;; Otherwise, ignore drawers whose name isn't in that
1833 ;; list.
1834 (let ((name (org-element-property :drawer-name datum)))
1835 (if (eq (car with-drawers-p) 'not)
1836 (member-ignore-case name (cdr with-drawers-p))
1837 (not (member-ignore-case name with-drawers-p))))))))
1838 (fixed-width (not (plist-get options :with-fixed-width)))
1839 ((footnote-definition footnote-reference)
1840 (not (plist-get options :with-footnotes)))
1841 ((headline inlinetask)
1842 (let ((with-tasks (plist-get options :with-tasks))
1843 (todo (org-element-property :todo-keyword datum))
1844 (todo-type (org-element-property :todo-type datum))
1845 (archived (plist-get options :with-archived-trees))
1846 (tags (org-export-get-tags datum options nil t)))
1848 (and (eq (org-element-type datum) 'inlinetask)
1849 (not (plist-get options :with-inlinetasks)))
1850 ;; Ignore subtrees with an exclude tag.
1851 (cl-loop for k in (plist-get options :exclude-tags)
1852 thereis (member k tags))
1853 ;; When a select tag is present in the buffer, ignore any tree
1854 ;; without it.
1855 (and selected (not (memq datum selected)))
1856 ;; Ignore commented sub-trees.
1857 (org-element-property :commentedp datum)
1858 ;; Ignore archived subtrees if `:with-archived-trees' is nil.
1859 (and (not archived) (org-element-property :archivedp datum))
1860 ;; Ignore tasks, if specified by `:with-tasks' property.
1861 (and todo
1862 (or (not with-tasks)
1863 (and (memq with-tasks '(todo done))
1864 (not (eq todo-type with-tasks)))
1865 (and (consp with-tasks) (not (member todo with-tasks))))))))
1866 ((latex-environment latex-fragment) (not (plist-get options :with-latex)))
1867 (node-property
1868 (let ((properties-set (plist-get options :with-properties)))
1869 (cond ((null properties-set) t)
1870 ((consp properties-set)
1871 (not (member-ignore-case (org-element-property :key datum)
1872 properties-set))))))
1873 (planning (not (plist-get options :with-planning)))
1874 (property-drawer (not (plist-get options :with-properties)))
1875 (statistics-cookie (not (plist-get options :with-statistics-cookies)))
1876 (table (not (plist-get options :with-tables)))
1877 (table-cell
1878 (and (org-export-table-has-special-column-p
1879 (org-export-get-parent-table datum))
1880 (org-export-first-sibling-p datum options)))
1881 (table-row (org-export-table-row-is-special-p datum options))
1882 (timestamp
1883 ;; `:with-timestamps' only applies to isolated timestamps
1884 ;; objects, i.e. timestamp objects in a paragraph containing only
1885 ;; timestamps and whitespaces.
1886 (when (let ((parent (org-export-get-parent-element datum)))
1887 (and (memq (org-element-type parent) '(paragraph verse-block))
1888 (not (org-element-map parent
1889 (cons 'plain-text
1890 (remq 'timestamp org-element-all-objects))
1891 (lambda (obj)
1892 (or (not (stringp obj)) (org-string-nw-p obj)))
1893 options t))))
1894 (cl-case (plist-get options :with-timestamps)
1895 ((nil) t)
1896 (active
1897 (not (memq (org-element-property :type datum) '(active active-range))))
1898 (inactive
1899 (not (memq (org-element-property :type datum)
1900 '(inactive inactive-range)))))))))
1903 ;;; The Transcoder
1905 ;; `org-export-data' reads a parse tree (obtained with, i.e.
1906 ;; `org-element-parse-buffer') and transcodes it into a specified
1907 ;; back-end output. It takes care of filtering out elements or
1908 ;; objects according to export options and organizing the output blank
1909 ;; lines and white space are preserved. The function memoizes its
1910 ;; results, so it is cheap to call it within transcoders.
1912 ;; It is possible to modify locally the back-end used by
1913 ;; `org-export-data' or even use a temporary back-end by using
1914 ;; `org-export-data-with-backend'.
1916 ;; `org-export-transcoder' is an accessor returning appropriate
1917 ;; translator function for a given element or object.
1919 (defun org-export-transcoder (blob info)
1920 "Return appropriate transcoder for BLOB.
1921 INFO is a plist containing export directives."
1922 (let ((type (org-element-type blob)))
1923 ;; Return contents only for complete parse trees.
1924 (if (eq type 'org-data) (lambda (_datum contents _info) contents)
1925 (let ((transcoder (cdr (assq type (plist-get info :translate-alist)))))
1926 (and (functionp transcoder) transcoder)))))
1928 (defun org-export-data (data info)
1929 "Convert DATA into current back-end format.
1931 DATA is a parse tree, an element or an object or a secondary
1932 string. INFO is a plist holding export options.
1934 Return a string."
1935 (or (gethash data (plist-get info :exported-data))
1936 ;; Handle broken links according to
1937 ;; `org-export-with-broken-links'.
1938 (cl-macrolet
1939 ((broken-link-handler
1940 (&rest body)
1941 `(condition-case err
1942 (progn ,@body)
1943 (org-link-broken
1944 (pcase (plist-get info :with-broken-links)
1945 (`nil (user-error "Unable to resolve link: %S" (nth 1 err)))
1946 (`mark (org-export-data
1947 (format "[BROKEN LINK: %s]" (nth 1 err)) info))
1948 (_ nil))))))
1949 (let* ((type (org-element-type data))
1950 (parent (org-export-get-parent data))
1951 (results
1952 (cond
1953 ;; Ignored element/object.
1954 ((memq data (plist-get info :ignore-list)) nil)
1955 ;; Plain text.
1956 ((eq type 'plain-text)
1957 (org-export-filter-apply-functions
1958 (plist-get info :filter-plain-text)
1959 (let ((transcoder (org-export-transcoder data info)))
1960 (if transcoder (funcall transcoder data info) data))
1961 info))
1962 ;; Secondary string.
1963 ((not type)
1964 (mapconcat (lambda (obj) (org-export-data obj info)) data ""))
1965 ;; Element/Object without contents or, as a special
1966 ;; case, headline with archive tag and archived trees
1967 ;; restricted to title only.
1968 ((or (not (org-element-contents data))
1969 (and (eq type 'headline)
1970 (eq (plist-get info :with-archived-trees) 'headline)
1971 (org-element-property :archivedp data)))
1972 (let ((transcoder (org-export-transcoder data info)))
1973 (or (and (functionp transcoder)
1974 (broken-link-handler
1975 (funcall transcoder data nil info)))
1976 ;; Export snippets never return a nil value so
1977 ;; that white spaces following them are never
1978 ;; ignored.
1979 (and (eq type 'export-snippet) ""))))
1980 ;; Element/Object with contents.
1982 (let ((transcoder (org-export-transcoder data info)))
1983 (when transcoder
1984 (let* ((greaterp (memq type org-element-greater-elements))
1985 (objectp
1986 (and (not greaterp)
1987 (memq type org-element-recursive-objects)))
1988 (contents
1989 (mapconcat
1990 (lambda (element) (org-export-data element info))
1991 (org-element-contents
1992 (if (or greaterp objectp) data
1993 ;; Elements directly containing
1994 ;; objects must have their indentation
1995 ;; normalized first.
1996 (org-element-normalize-contents
1997 data
1998 ;; When normalizing contents of the
1999 ;; first paragraph in an item or
2000 ;; a footnote definition, ignore
2001 ;; first line's indentation: there is
2002 ;; none and it might be misleading.
2003 (when (eq type 'paragraph)
2004 (and
2005 (eq (car (org-element-contents parent))
2006 data)
2007 (memq (org-element-type parent)
2008 '(footnote-definition item)))))))
2009 "")))
2010 (broken-link-handler
2011 (funcall transcoder data
2012 (if (not greaterp) contents
2013 (org-element-normalize-string contents))
2014 info)))))))))
2015 ;; Final result will be memoized before being returned.
2016 (puthash
2017 data
2018 (cond
2019 ((not results) "")
2020 ((memq type '(org-data plain-text nil)) results)
2021 ;; Append the same white space between elements or objects
2022 ;; as in the original buffer, and call appropriate filters.
2024 (org-export-filter-apply-functions
2025 (plist-get info (intern (format ":filter-%s" type)))
2026 (let ((blank (or (org-element-property :post-blank data) 0)))
2027 (if (eq (org-element-class data parent) 'object)
2028 (concat results (make-string blank ?\s))
2029 (concat (org-element-normalize-string results)
2030 (make-string blank ?\n))))
2031 info)))
2032 (plist-get info :exported-data))))))
2034 (defun org-export-data-with-backend (data backend info)
2035 "Convert DATA into BACKEND format.
2037 DATA is an element, an object, a secondary string or a string.
2038 BACKEND is a symbol. INFO is a plist used as a communication
2039 channel.
2041 Unlike to `org-export-with-backend', this function will
2042 recursively convert DATA using BACKEND translation table."
2043 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
2044 ;; Set-up a new communication channel with translations defined in
2045 ;; BACKEND as the translate table and a new hash table for
2046 ;; memoization.
2047 (let ((new-info
2048 (org-combine-plists
2049 info
2050 (list :back-end backend
2051 :translate-alist (org-export-get-all-transcoders backend)
2052 ;; Size of the hash table is reduced since this
2053 ;; function will probably be used on small trees.
2054 :exported-data (make-hash-table :test 'eq :size 401)))))
2055 (prog1 (org-export-data data new-info)
2056 ;; Preserve `:internal-references', as those do not depend on
2057 ;; the back-end used; we need to make sure that any new
2058 ;; reference when the temporary back-end was active gets through
2059 ;; the default one.
2060 (plist-put info :internal-references
2061 (plist-get new-info :internal-references)))))
2063 (defun org-export-expand (blob contents &optional with-affiliated)
2064 "Expand a parsed element or object to its original state.
2066 BLOB is either an element or an object. CONTENTS is its
2067 contents, as a string or nil.
2069 When optional argument WITH-AFFILIATED is non-nil, add affiliated
2070 keywords before output."
2071 (let ((type (org-element-type blob)))
2072 (concat (and with-affiliated
2073 (eq (org-element-class blob) 'element)
2074 (org-element--interpret-affiliated-keywords blob))
2075 (funcall (intern (format "org-element-%s-interpreter" type))
2076 blob contents))))
2080 ;;; The Filter System
2082 ;; Filters allow end-users to tweak easily the transcoded output.
2083 ;; They are the functional counterpart of hooks, as every filter in
2084 ;; a set is applied to the return value of the previous one.
2086 ;; Every set is back-end agnostic. Although, a filter is always
2087 ;; called, in addition to the string it applies to, with the back-end
2088 ;; used as argument, so it's easy for the end-user to add back-end
2089 ;; specific filters in the set. The communication channel, as
2090 ;; a plist, is required as the third argument.
2092 ;; From the developer side, filters sets can be installed in the
2093 ;; process with the help of `org-export-define-backend', which
2094 ;; internally stores filters as an alist. Each association has a key
2095 ;; among the following symbols and a function or a list of functions
2096 ;; as value.
2098 ;; - `:filter-options' applies to the property list containing export
2099 ;; options. Unlike to other filters, functions in this list accept
2100 ;; two arguments instead of three: the property list containing
2101 ;; export options and the back-end. Users can set its value through
2102 ;; `org-export-filter-options-functions' variable.
2104 ;; - `:filter-parse-tree' applies directly to the complete parsed
2105 ;; tree. Users can set it through
2106 ;; `org-export-filter-parse-tree-functions' variable.
2108 ;; - `:filter-body' applies to the body of the output, before template
2109 ;; translator chimes in. Users can set it through
2110 ;; `org-export-filter-body-functions' variable.
2112 ;; - `:filter-final-output' applies to the final transcoded string.
2113 ;; Users can set it with `org-export-filter-final-output-functions'
2114 ;; variable.
2116 ;; - `:filter-plain-text' applies to any string not recognized as Org
2117 ;; syntax. `org-export-filter-plain-text-functions' allows users to
2118 ;; configure it.
2120 ;; - `:filter-TYPE' applies on the string returned after an element or
2121 ;; object of type TYPE has been transcoded. A user can modify
2122 ;; `org-export-filter-TYPE-functions' to install these filters.
2124 ;; All filters sets are applied with
2125 ;; `org-export-filter-apply-functions' function. Filters in a set are
2126 ;; applied in a LIFO fashion. It allows developers to be sure that
2127 ;; their filters will be applied first.
2129 ;; Filters properties are installed in communication channel with
2130 ;; `org-export-install-filters' function.
2132 ;; Eventually, two hooks (`org-export-before-processing-hook' and
2133 ;; `org-export-before-parsing-hook') are run at the beginning of the
2134 ;; export process and just before parsing to allow for heavy structure
2135 ;; modifications.
2138 ;;;; Hooks
2140 (defvar org-export-before-processing-hook nil
2141 "Hook run at the beginning of the export process.
2143 This is run before include keywords and macros are expanded and
2144 Babel code blocks executed, on a copy of the original buffer
2145 being exported. Visibility and narrowing are preserved. Point
2146 is at the beginning of the buffer.
2148 Every function in this hook will be called with one argument: the
2149 back-end currently used, as a symbol.")
2151 (defvar org-export-before-parsing-hook nil
2152 "Hook run before parsing an export buffer.
2154 This is run after include keywords and macros have been expanded
2155 and Babel code blocks executed, on a copy of the original buffer
2156 being exported. Visibility and narrowing are preserved. Point
2157 is at the beginning of the buffer.
2159 Every function in this hook will be called with one argument: the
2160 back-end currently used, as a symbol.")
2163 ;;;; Special Filters
2165 (defvar org-export-filter-options-functions nil
2166 "List of functions applied to the export options.
2167 Each filter is called with two arguments: the export options, as
2168 a plist, and the back-end, as a symbol. It must return
2169 a property list containing export options.")
2171 (defvar org-export-filter-parse-tree-functions nil
2172 "List of functions applied to the parsed tree.
2173 Each filter is called with three arguments: the parse tree, as
2174 returned by `org-element-parse-buffer', the back-end, as
2175 a symbol, and the communication channel, as a plist. It must
2176 return the modified parse tree to transcode.")
2178 (defvar org-export-filter-plain-text-functions nil
2179 "List of functions applied to plain text.
2180 Each filter is called with three arguments: a string which
2181 contains no Org syntax, the back-end, as a symbol, and the
2182 communication channel, as a plist. It must return a string or
2183 nil.")
2185 (defvar org-export-filter-body-functions nil
2186 "List of functions applied to transcoded body.
2187 Each filter is called with three arguments: a string which
2188 contains no Org syntax, the back-end, as a symbol, and the
2189 communication channel, as a plist. It must return a string or
2190 nil.")
2192 (defvar org-export-filter-final-output-functions nil
2193 "List of functions applied to the transcoded string.
2194 Each filter is called with three arguments: the full transcoded
2195 string, the back-end, as a symbol, and the communication channel,
2196 as a plist. It must return a string that will be used as the
2197 final export output.")
2200 ;;;; Elements Filters
2202 (defvar org-export-filter-babel-call-functions nil
2203 "List of functions applied to a transcoded babel-call.
2204 Each filter is called with three arguments: the transcoded data,
2205 as a string, the back-end, as a symbol, and the communication
2206 channel, as a plist. It must return a string or nil.")
2208 (defvar org-export-filter-center-block-functions nil
2209 "List of functions applied to a transcoded center block.
2210 Each filter is called with three arguments: the transcoded data,
2211 as a string, the back-end, as a symbol, and the communication
2212 channel, as a plist. It must return a string or nil.")
2214 (defvar org-export-filter-clock-functions nil
2215 "List of functions applied to a transcoded clock.
2216 Each filter is called with three arguments: the transcoded data,
2217 as a string, the back-end, as a symbol, and the communication
2218 channel, as a plist. It must return a string or nil.")
2220 (defvar org-export-filter-diary-sexp-functions nil
2221 "List of functions applied to a transcoded diary-sexp.
2222 Each filter is called with three arguments: the transcoded data,
2223 as a string, the back-end, as a symbol, and the communication
2224 channel, as a plist. It must return a string or nil.")
2226 (defvar org-export-filter-drawer-functions nil
2227 "List of functions applied to a transcoded drawer.
2228 Each filter is called with three arguments: the transcoded data,
2229 as a string, the back-end, as a symbol, and the communication
2230 channel, as a plist. It must return a string or nil.")
2232 (defvar org-export-filter-dynamic-block-functions nil
2233 "List of functions applied to a transcoded dynamic-block.
2234 Each filter is called with three arguments: the transcoded data,
2235 as a string, the back-end, as a symbol, and the communication
2236 channel, as a plist. It must return a string or nil.")
2238 (defvar org-export-filter-example-block-functions nil
2239 "List of functions applied to a transcoded example-block.
2240 Each filter is called with three arguments: the transcoded data,
2241 as a string, the back-end, as a symbol, and the communication
2242 channel, as a plist. It must return a string or nil.")
2244 (defvar org-export-filter-export-block-functions nil
2245 "List of functions applied to a transcoded export-block.
2246 Each filter is called with three arguments: the transcoded data,
2247 as a string, the back-end, as a symbol, and the communication
2248 channel, as a plist. It must return a string or nil.")
2250 (defvar org-export-filter-fixed-width-functions nil
2251 "List of functions applied to a transcoded fixed-width.
2252 Each filter is called with three arguments: the transcoded data,
2253 as a string, the back-end, as a symbol, and the communication
2254 channel, as a plist. It must return a string or nil.")
2256 (defvar org-export-filter-footnote-definition-functions nil
2257 "List of functions applied to a transcoded footnote-definition.
2258 Each filter is called with three arguments: the transcoded data,
2259 as a string, the back-end, as a symbol, and the communication
2260 channel, as a plist. It must return a string or nil.")
2262 (defvar org-export-filter-headline-functions nil
2263 "List of functions applied to a transcoded headline.
2264 Each filter is called with three arguments: the transcoded data,
2265 as a string, the back-end, as a symbol, and the communication
2266 channel, as a plist. It must return a string or nil.")
2268 (defvar org-export-filter-horizontal-rule-functions nil
2269 "List of functions applied to a transcoded horizontal-rule.
2270 Each filter is called with three arguments: the transcoded data,
2271 as a string, the back-end, as a symbol, and the communication
2272 channel, as a plist. It must return a string or nil.")
2274 (defvar org-export-filter-inlinetask-functions nil
2275 "List of functions applied to a transcoded inlinetask.
2276 Each filter is called with three arguments: the transcoded data,
2277 as a string, the back-end, as a symbol, and the communication
2278 channel, as a plist. It must return a string or nil.")
2280 (defvar org-export-filter-item-functions nil
2281 "List of functions applied to a transcoded item.
2282 Each filter is called with three arguments: the transcoded data,
2283 as a string, the back-end, as a symbol, and the communication
2284 channel, as a plist. It must return a string or nil.")
2286 (defvar org-export-filter-keyword-functions nil
2287 "List of functions applied to a transcoded keyword.
2288 Each filter is called with three arguments: the transcoded data,
2289 as a string, the back-end, as a symbol, and the communication
2290 channel, as a plist. It must return a string or nil.")
2292 (defvar org-export-filter-latex-environment-functions nil
2293 "List of functions applied to a transcoded latex-environment.
2294 Each filter is called with three arguments: the transcoded data,
2295 as a string, the back-end, as a symbol, and the communication
2296 channel, as a plist. It must return a string or nil.")
2298 (defvar org-export-filter-node-property-functions nil
2299 "List of functions applied to a transcoded node-property.
2300 Each filter is called with three arguments: the transcoded data,
2301 as a string, the back-end, as a symbol, and the communication
2302 channel, as a plist. It must return a string or nil.")
2304 (defvar org-export-filter-paragraph-functions nil
2305 "List of functions applied to a transcoded paragraph.
2306 Each filter is called with three arguments: the transcoded data,
2307 as a string, the back-end, as a symbol, and the communication
2308 channel, as a plist. It must return a string or nil.")
2310 (defvar org-export-filter-plain-list-functions nil
2311 "List of functions applied to a transcoded plain-list.
2312 Each filter is called with three arguments: the transcoded data,
2313 as a string, the back-end, as a symbol, and the communication
2314 channel, as a plist. It must return a string or nil.")
2316 (defvar org-export-filter-planning-functions nil
2317 "List of functions applied to a transcoded planning.
2318 Each filter is called with three arguments: the transcoded data,
2319 as a string, the back-end, as a symbol, and the communication
2320 channel, as a plist. It must return a string or nil.")
2322 (defvar org-export-filter-property-drawer-functions nil
2323 "List of functions applied to a transcoded property-drawer.
2324 Each filter is called with three arguments: the transcoded data,
2325 as a string, the back-end, as a symbol, and the communication
2326 channel, as a plist. It must return a string or nil.")
2328 (defvar org-export-filter-quote-block-functions nil
2329 "List of functions applied to a transcoded quote block.
2330 Each filter is called with three arguments: the transcoded quote
2331 data, as a string, the back-end, as a symbol, and the
2332 communication channel, as a plist. It must return a string or
2333 nil.")
2335 (defvar org-export-filter-section-functions nil
2336 "List of functions applied to a transcoded section.
2337 Each filter is called with three arguments: the transcoded data,
2338 as a string, the back-end, as a symbol, and the communication
2339 channel, as a plist. It must return a string or nil.")
2341 (defvar org-export-filter-special-block-functions nil
2342 "List of functions applied to a transcoded special block.
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-src-block-functions nil
2348 "List of functions applied to a transcoded src-block.
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-table-functions nil
2354 "List of functions applied to a transcoded table.
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-table-cell-functions nil
2360 "List of functions applied to a transcoded table-cell.
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-table-row-functions nil
2366 "List of functions applied to a transcoded table-row.
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-verse-block-functions nil
2372 "List of functions applied to a transcoded verse block.
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.")
2378 ;;;; Objects Filters
2380 (defvar org-export-filter-bold-functions nil
2381 "List of functions applied to transcoded bold text.
2382 Each filter is called with three arguments: the transcoded data,
2383 as a string, the back-end, as a symbol, and the communication
2384 channel, as a plist. It must return a string or nil.")
2386 (defvar org-export-filter-code-functions nil
2387 "List of functions applied to transcoded code text.
2388 Each filter is called with three arguments: the transcoded data,
2389 as a string, the back-end, as a symbol, and the communication
2390 channel, as a plist. It must return a string or nil.")
2392 (defvar org-export-filter-entity-functions nil
2393 "List of functions applied to a transcoded entity.
2394 Each filter is called with three arguments: the transcoded data,
2395 as a string, the back-end, as a symbol, and the communication
2396 channel, as a plist. It must return a string or nil.")
2398 (defvar org-export-filter-export-snippet-functions nil
2399 "List of functions applied to a transcoded export-snippet.
2400 Each filter is called with three arguments: the transcoded data,
2401 as a string, the back-end, as a symbol, and the communication
2402 channel, as a plist. It must return a string or nil.")
2404 (defvar org-export-filter-footnote-reference-functions nil
2405 "List of functions applied to a transcoded footnote-reference.
2406 Each filter is called with three arguments: the transcoded data,
2407 as a string, the back-end, as a symbol, and the communication
2408 channel, as a plist. It must return a string or nil.")
2410 (defvar org-export-filter-inline-babel-call-functions nil
2411 "List of functions applied to a transcoded inline-babel-call.
2412 Each filter is called with three arguments: the transcoded data,
2413 as a string, the back-end, as a symbol, and the communication
2414 channel, as a plist. It must return a string or nil.")
2416 (defvar org-export-filter-inline-src-block-functions nil
2417 "List of functions applied to a transcoded inline-src-block.
2418 Each filter is called with three arguments: the transcoded data,
2419 as a string, the back-end, as a symbol, and the communication
2420 channel, as a plist. It must return a string or nil.")
2422 (defvar org-export-filter-italic-functions nil
2423 "List of functions applied to transcoded italic text.
2424 Each filter is called with three arguments: the transcoded data,
2425 as a string, the back-end, as a symbol, and the communication
2426 channel, as a plist. It must return a string or nil.")
2428 (defvar org-export-filter-latex-fragment-functions nil
2429 "List of functions applied to a transcoded latex-fragment.
2430 Each filter is called with three arguments: the transcoded data,
2431 as a string, the back-end, as a symbol, and the communication
2432 channel, as a plist. It must return a string or nil.")
2434 (defvar org-export-filter-line-break-functions nil
2435 "List of functions applied to a transcoded line-break.
2436 Each filter is called with three arguments: the transcoded data,
2437 as a string, the back-end, as a symbol, and the communication
2438 channel, as a plist. It must return a string or nil.")
2440 (defvar org-export-filter-link-functions nil
2441 "List of functions applied to a transcoded link.
2442 Each filter is called with three arguments: the transcoded data,
2443 as a string, the back-end, as a symbol, and the communication
2444 channel, as a plist. It must return a string or nil.")
2446 (defvar org-export-filter-radio-target-functions nil
2447 "List of functions applied to a transcoded radio-target.
2448 Each filter is called with three arguments: the transcoded data,
2449 as a string, the back-end, as a symbol, and the communication
2450 channel, as a plist. It must return a string or nil.")
2452 (defvar org-export-filter-statistics-cookie-functions nil
2453 "List of functions applied to a transcoded statistics-cookie.
2454 Each filter is called with three arguments: the transcoded data,
2455 as a string, the back-end, as a symbol, and the communication
2456 channel, as a plist. It must return a string or nil.")
2458 (defvar org-export-filter-strike-through-functions nil
2459 "List of functions applied to transcoded strike-through text.
2460 Each filter is called with three arguments: the transcoded data,
2461 as a string, the back-end, as a symbol, and the communication
2462 channel, as a plist. It must return a string or nil.")
2464 (defvar org-export-filter-subscript-functions nil
2465 "List of functions applied to a transcoded subscript.
2466 Each filter is called with three arguments: the transcoded data,
2467 as a string, the back-end, as a symbol, and the communication
2468 channel, as a plist. It must return a string or nil.")
2470 (defvar org-export-filter-superscript-functions nil
2471 "List of functions applied to a transcoded superscript.
2472 Each filter is called with three arguments: the transcoded data,
2473 as a string, the back-end, as a symbol, and the communication
2474 channel, as a plist. It must return a string or nil.")
2476 (defvar org-export-filter-target-functions nil
2477 "List of functions applied to a transcoded target.
2478 Each filter is called with three arguments: the transcoded data,
2479 as a string, the back-end, as a symbol, and the communication
2480 channel, as a plist. It must return a string or nil.")
2482 (defvar org-export-filter-timestamp-functions nil
2483 "List of functions applied to a transcoded timestamp.
2484 Each filter is called with three arguments: the transcoded data,
2485 as a string, the back-end, as a symbol, and the communication
2486 channel, as a plist. It must return a string or nil.")
2488 (defvar org-export-filter-underline-functions nil
2489 "List of functions applied to transcoded underline text.
2490 Each filter is called with three arguments: the transcoded data,
2491 as a string, the back-end, as a symbol, and the communication
2492 channel, as a plist. It must return a string or nil.")
2494 (defvar org-export-filter-verbatim-functions nil
2495 "List of functions applied to transcoded verbatim text.
2496 Each filter is called with three arguments: the transcoded data,
2497 as a string, the back-end, as a symbol, and the communication
2498 channel, as a plist. It must return a string or nil.")
2501 ;;;; Filters Tools
2503 ;; Internal function `org-export-install-filters' installs filters
2504 ;; hard-coded in back-ends (developer filters) and filters from global
2505 ;; variables (user filters) in the communication channel.
2507 ;; Internal function `org-export-filter-apply-functions' takes care
2508 ;; about applying each filter in order to a given data. It ignores
2509 ;; filters returning a nil value but stops whenever a filter returns
2510 ;; an empty string.
2512 (defun org-export-filter-apply-functions (filters value info)
2513 "Call every function in FILTERS.
2515 Functions are called with three arguments: a value, the export
2516 back-end name and the communication channel. First function in
2517 FILTERS is called with VALUE as its first argument. Second
2518 function in FILTERS is called with the previous result as its
2519 value, etc.
2521 Functions returning nil are skipped. Any function returning the
2522 empty string ends the process, which returns the empty string.
2524 Call is done in a LIFO fashion, to be sure that developer
2525 specified filters, if any, are called first."
2526 (catch :exit
2527 (let* ((backend (plist-get info :back-end))
2528 (backend-name (and backend (org-export-backend-name backend))))
2529 (dolist (filter filters value)
2530 (let ((result (funcall filter value backend-name info)))
2531 (cond ((not result))
2532 ((equal result "") (throw :exit ""))
2533 (t (setq value result))))))))
2535 (defun org-export-install-filters (info)
2536 "Install filters properties in communication channel.
2537 INFO is a plist containing the current communication channel.
2538 Return the updated communication channel."
2539 (let (plist)
2540 ;; Install user-defined filters with `org-export-filters-alist'
2541 ;; and filters already in INFO (through ext-plist mechanism).
2542 (dolist (p org-export-filters-alist)
2543 (let* ((prop (car p))
2544 (info-value (plist-get info prop))
2545 (default-value (symbol-value (cdr p))))
2546 (setq plist
2547 (plist-put plist prop
2548 ;; Filters in INFO will be called
2549 ;; before those user provided.
2550 (append (if (listp info-value) info-value
2551 (list info-value))
2552 default-value)))))
2553 ;; Prepend back-end specific filters to that list.
2554 (dolist (p (org-export-get-all-filters (plist-get info :back-end)))
2555 ;; Single values get consed, lists are appended.
2556 (let ((key (car p)) (value (cdr p)))
2557 (when value
2558 (setq plist
2559 (plist-put
2560 plist key
2561 (if (atom value) (cons value (plist-get plist key))
2562 (append value (plist-get plist key))))))))
2563 ;; Return new communication channel.
2564 (org-combine-plists info plist)))
2568 ;;; Core functions
2570 ;; This is the room for the main function, `org-export-as', along with
2571 ;; its derivative, `org-export-string-as'.
2572 ;; `org-export--copy-to-kill-ring-p' determines if output of these
2573 ;; function should be added to kill ring.
2575 ;; Note that `org-export-as' doesn't really parse the current buffer,
2576 ;; but a copy of it (with the same buffer-local variables and
2577 ;; visibility), where macros and include keywords are expanded and
2578 ;; Babel blocks are executed, if appropriate.
2579 ;; `org-export-with-buffer-copy' macro prepares that copy.
2581 ;; File inclusion is taken care of by
2582 ;; `org-export-expand-include-keyword' and
2583 ;; `org-export--prepare-file-contents'. Structure wise, including
2584 ;; a whole Org file in a buffer often makes little sense. For
2585 ;; example, if the file contains a headline and the include keyword
2586 ;; was within an item, the item should contain the headline. That's
2587 ;; why file inclusion should be done before any structure can be
2588 ;; associated to the file, that is before parsing.
2590 ;; `org-export-insert-default-template' is a command to insert
2591 ;; a default template (or a back-end specific template) at point or in
2592 ;; current subtree.
2594 (defun org-export-copy-buffer ()
2595 "Return a copy of the current buffer.
2596 The copy preserves Org buffer-local variables, visibility and
2597 narrowing."
2598 (let ((copy-buffer-fun (org-export--generate-copy-script (current-buffer)))
2599 (new-buf (generate-new-buffer (buffer-name))))
2600 (with-current-buffer new-buf
2601 (funcall copy-buffer-fun)
2602 (set-buffer-modified-p nil))
2603 new-buf))
2605 (defmacro org-export-with-buffer-copy (&rest body)
2606 "Apply BODY in a copy of the current buffer.
2607 The copy preserves local variables, visibility and contents of
2608 the original buffer. Point is at the beginning of the buffer
2609 when BODY is applied."
2610 (declare (debug t))
2611 (org-with-gensyms (buf-copy)
2612 `(let ((,buf-copy (org-export-copy-buffer)))
2613 (unwind-protect
2614 (with-current-buffer ,buf-copy
2615 (goto-char (point-min))
2616 (progn ,@body))
2617 (and (buffer-live-p ,buf-copy)
2618 ;; Kill copy without confirmation.
2619 (progn (with-current-buffer ,buf-copy
2620 (restore-buffer-modified-p nil))
2621 (kill-buffer ,buf-copy)))))))
2623 (defun org-export--generate-copy-script (buffer)
2624 "Generate a function duplicating BUFFER.
2626 The copy will preserve local variables, visibility, contents and
2627 narrowing of the original buffer. If a region was active in
2628 BUFFER, contents will be narrowed to that region instead.
2630 The resulting function can be evaluated at a later time, from
2631 another buffer, effectively cloning the original buffer there.
2633 The function assumes BUFFER's major mode is `org-mode'."
2634 (with-current-buffer buffer
2635 `(lambda ()
2636 (let ((inhibit-modification-hooks t))
2637 ;; Set major mode. Ignore `org-mode-hook' as it has been run
2638 ;; already in BUFFER.
2639 (let ((org-mode-hook nil) (org-inhibit-startup t)) (org-mode))
2640 ;; Copy specific buffer local variables and variables set
2641 ;; through BIND keywords.
2642 ,@(let ((bound-variables (org-export--list-bound-variables))
2643 vars)
2644 (dolist (entry (buffer-local-variables (buffer-base-buffer)) vars)
2645 (when (consp entry)
2646 (let ((var (car entry))
2647 (val (cdr entry)))
2648 (and (not (memq var org-export-ignored-local-variables))
2649 (or (memq var
2650 '(default-directory
2651 buffer-file-name
2652 buffer-file-coding-system))
2653 (assq var bound-variables)
2654 (string-match "^\\(org-\\|orgtbl-\\)"
2655 (symbol-name var)))
2656 ;; Skip unreadable values, as they cannot be
2657 ;; sent to external process.
2658 (or (not val) (ignore-errors (read (format "%S" val))))
2659 (push `(set (make-local-variable (quote ,var))
2660 (quote ,val))
2661 vars))))))
2662 ;; Whole buffer contents.
2663 (insert
2664 ,(org-with-wide-buffer
2665 (buffer-substring-no-properties
2666 (point-min) (point-max))))
2667 ;; Narrowing.
2668 ,(if (org-region-active-p)
2669 `(narrow-to-region ,(region-beginning) ,(region-end))
2670 `(narrow-to-region ,(point-min) ,(point-max)))
2671 ;; Current position of point.
2672 (goto-char ,(point))
2673 ;; Overlays with invisible property.
2674 ,@(let (ov-set)
2675 (dolist (ov (overlays-in (point-min) (point-max)) ov-set)
2676 (let ((invis-prop (overlay-get ov 'invisible)))
2677 (when invis-prop
2678 (push `(overlay-put
2679 (make-overlay ,(overlay-start ov)
2680 ,(overlay-end ov))
2681 'invisible (quote ,invis-prop))
2682 ov-set)))))))))
2684 (defun org-export--delete-comment-trees ()
2685 "Delete commented trees and commented inlinetasks in the buffer.
2686 Narrowing, if any, is ignored."
2687 (org-with-wide-buffer
2688 (goto-char (point-min))
2689 (let* ((case-fold-search t)
2690 (regexp (concat org-outline-regexp-bol ".*" org-comment-string)))
2691 (while (re-search-forward regexp nil t)
2692 (let ((element (org-element-at-point)))
2693 (when (org-element-property :commentedp element)
2694 (delete-region (org-element-property :begin element)
2695 (org-element-property :end element))))))))
2697 (defun org-export--prune-tree (data info)
2698 "Prune non exportable elements from DATA.
2699 DATA is the parse tree to traverse. INFO is the plist holding
2700 export info. Also set `:ignore-list' in INFO to a list of
2701 objects which should be ignored during export, but not removed
2702 from tree."
2703 (letrec ((ignore nil)
2704 ;; First find trees containing a select tag, if any.
2705 (selected (org-export--selected-trees data info))
2706 (walk-data
2707 (lambda (data)
2708 ;; Prune non-exportable elements and objects from tree.
2709 ;; As a special case, special rows and cells from tables
2710 ;; are stored in IGNORE, as they still need to be
2711 ;; accessed during export.
2712 (when data
2713 (let ((type (org-element-type data)))
2714 (if (org-export--skip-p data info selected)
2715 (if (memq type '(table-cell table-row)) (push data ignore)
2716 (org-element-extract-element data))
2717 (if (and (eq type 'headline)
2718 (eq (plist-get info :with-archived-trees)
2719 'headline)
2720 (org-element-property :archivedp data))
2721 ;; If headline is archived but tree below has
2722 ;; to be skipped, remove contents.
2723 (org-element-set-contents data)
2724 ;; Move into recursive objects/elements.
2725 (mapc walk-data (org-element-contents data)))
2726 ;; Move into secondary string, if any.
2727 (dolist (p (cdr (assq type
2728 org-element-secondary-value-alist)))
2729 (mapc walk-data (org-element-property p data))))))))
2730 (definitions
2731 ;; Collect definitions before possibly pruning them so as
2732 ;; to avoid parsing them again if they are required.
2733 (org-element-map data '(footnote-definition footnote-reference)
2734 (lambda (f)
2735 (cond
2736 ((eq (org-element-type f) 'footnote-definition) f)
2737 ((eq (org-element-property :type f) 'standard) nil)
2738 (t (let ((label (org-element-property :label f)))
2739 (when label ;Skip anonymous references.
2740 (apply
2741 #'org-element-create
2742 'footnote-definition `(:label ,label :post-blank 1)
2743 (org-element-contents f))))))))))
2744 ;; If a select tag is active, also ignore the section before the
2745 ;; first headline, if any.
2746 (when selected
2747 (let ((first-element (car (org-element-contents data))))
2748 (when (eq (org-element-type first-element) 'section)
2749 (org-element-extract-element first-element))))
2750 ;; Prune tree and communication channel.
2751 (funcall walk-data data)
2752 (dolist (entry (append
2753 ;; Priority is given to back-end specific options.
2754 (org-export-get-all-options (plist-get info :back-end))
2755 org-export-options-alist))
2756 (when (eq (nth 4 entry) 'parse)
2757 (funcall walk-data (plist-get info (car entry)))))
2758 (let ((missing (org-export--missing-definitions data definitions)))
2759 (funcall walk-data missing)
2760 (org-export--install-footnote-definitions missing data))
2761 ;; Eventually set `:ignore-list'.
2762 (plist-put info :ignore-list ignore)))
2764 (defun org-export--missing-definitions (tree definitions)
2765 "List footnote definitions missing from TREE.
2766 Missing definitions are searched within DEFINITIONS, which is
2767 a list of footnote definitions or in the widened buffer."
2768 (let* ((list-labels
2769 (lambda (data)
2770 ;; List all footnote labels encountered in DATA. Inline
2771 ;; footnote references are ignored.
2772 (org-element-map data 'footnote-reference
2773 (lambda (reference)
2774 (and (eq (org-element-property :type reference) 'standard)
2775 (org-element-property :label reference))))))
2776 defined undefined missing-definitions)
2777 ;; Partition DIRECT-REFERENCES between DEFINED and UNDEFINED
2778 ;; references.
2779 (let ((known-definitions
2780 (org-element-map tree '(footnote-reference footnote-definition)
2781 (lambda (f)
2782 (and (or (eq (org-element-type f) 'footnote-definition)
2783 (eq (org-element-property :type f) 'inline))
2784 (org-element-property :label f)))))
2785 seen)
2786 (dolist (l (funcall list-labels tree))
2787 (cond ((member l seen))
2788 ((member l known-definitions) (push l defined))
2789 (t (push l undefined)))))
2790 ;; Complete MISSING-DEFINITIONS by finding the definition of every
2791 ;; undefined label, first by looking into DEFINITIONS, then by
2792 ;; searching the widened buffer. This is a recursive process
2793 ;; since definitions found can themselves contain an undefined
2794 ;; reference.
2795 (while undefined
2796 (let* ((label (pop undefined))
2797 (definition
2798 (cond
2799 ((cl-some
2800 (lambda (d) (and (equal (org-element-property :label d) label)
2802 definitions))
2803 ((pcase (org-footnote-get-definition label)
2804 (`(,_ ,beg . ,_)
2805 (org-with-wide-buffer
2806 (goto-char beg)
2807 (let ((datum (org-element-context)))
2808 (if (eq (org-element-type datum) 'footnote-reference)
2809 datum
2810 ;; Parse definition with contents.
2811 (save-restriction
2812 (narrow-to-region
2813 (org-element-property :begin datum)
2814 (org-element-property :end datum))
2815 (org-element-map (org-element-parse-buffer)
2816 'footnote-definition #'identity nil t))))))
2817 (_ nil)))
2818 (t (user-error "Definition not found for footnote %s" label)))))
2819 (push label defined)
2820 (push definition missing-definitions)
2821 ;; Look for footnote references within DEFINITION, since
2822 ;; we may need to also find their definition.
2823 (dolist (l (funcall list-labels definition))
2824 (unless (or (member l defined) ;Known label
2825 (member l undefined)) ;Processed later
2826 (push l undefined)))))
2827 ;; MISSING-DEFINITIONS may contain footnote references with inline
2828 ;; definitions. Make sure those are changed into real footnote
2829 ;; definitions.
2830 (mapcar (lambda (d)
2831 (if (eq (org-element-type d) 'footnote-definition) d
2832 (let ((label (org-element-property :label d)))
2833 (apply #'org-element-create
2834 'footnote-definition `(:label ,label :post-blank 1)
2835 (org-element-contents d)))))
2836 missing-definitions)))
2838 (defun org-export--install-footnote-definitions (definitions tree)
2839 "Install footnote definitions in tree.
2841 DEFINITIONS is the list of footnote definitions to install. TREE
2842 is the parse tree.
2844 If there is a footnote section in TREE, definitions found are
2845 appended to it. If `org-footnote-section' is non-nil, a new
2846 footnote section containing all definitions is inserted in TREE.
2847 Otherwise, definitions are appended at the end of the section
2848 containing their first reference."
2849 (cond
2850 ((null definitions))
2851 ;; If there is a footnote section, insert definitions there.
2852 ((let ((footnote-section
2853 (org-element-map tree 'headline
2854 (lambda (h) (and (org-element-property :footnote-section-p h) h))
2855 nil t)))
2856 (and footnote-section
2857 (apply #'org-element-adopt-elements
2858 footnote-section
2859 (nreverse definitions)))))
2860 ;; If there should be a footnote section, create one containing all
2861 ;; the definitions at the end of the tree.
2862 (org-footnote-section
2863 (org-element-adopt-elements
2864 tree
2865 (org-element-create 'headline
2866 (list :footnote-section-p t
2867 :level 1
2868 :title org-footnote-section)
2869 (apply #'org-element-create
2870 'section
2872 (nreverse definitions)))))
2873 ;; Otherwise add each definition at the end of the section where it
2874 ;; is first referenced.
2876 (letrec ((seen nil)
2877 (insert-definitions
2878 (lambda (data)
2879 ;; Insert footnote definitions in the same section as
2880 ;; their first reference in DATA.
2881 (org-element-map data 'footnote-reference
2882 (lambda (reference)
2883 (when (eq (org-element-property :type reference) 'standard)
2884 (let ((label (org-element-property :label reference)))
2885 (unless (member label seen)
2886 (push label seen)
2887 (let ((definition
2888 (cl-some
2889 (lambda (d)
2890 (and (equal (org-element-property :label d)
2891 label)
2893 definitions)))
2894 (org-element-adopt-elements
2895 (org-element-lineage reference '(section))
2896 definition)
2897 ;; Also insert definitions for nested
2898 ;; references, if any.
2899 (funcall insert-definitions definition))))))))))
2900 (funcall insert-definitions tree)))))
2902 (defun org-export--remove-uninterpreted-data (data info)
2903 "Change uninterpreted elements back into Org syntax.
2904 DATA is the parse tree. INFO is a plist containing export
2905 options. Each uninterpreted element or object is changed back
2906 into a string. Contents, if any, are not modified. The parse
2907 tree is modified by side effect."
2908 (org-export--remove-uninterpreted-data-1 data info)
2909 (dolist (entry org-export-options-alist)
2910 (when (eq (nth 4 entry) 'parse)
2911 (let ((p (car entry)))
2912 (plist-put info
2914 (org-export--remove-uninterpreted-data-1
2915 (plist-get info p)
2916 info))))))
2918 (defun org-export--remove-uninterpreted-data-1 (data info)
2919 "Change uninterpreted elements back into Org syntax.
2920 DATA is a parse tree or a secondary string. INFO is a plist
2921 containing export options. It is modified by side effect and
2922 returned by the function."
2923 (org-element-map data
2924 '(entity bold italic latex-environment latex-fragment strike-through
2925 subscript superscript underline)
2926 (lambda (blob)
2927 (let ((new
2928 (cl-case (org-element-type blob)
2929 ;; ... entities...
2930 (entity
2931 (and (not (plist-get info :with-entities))
2932 (list (concat
2933 (org-export-expand blob nil)
2934 (make-string
2935 (or (org-element-property :post-blank blob) 0)
2936 ?\s)))))
2937 ;; ... emphasis...
2938 ((bold italic strike-through underline)
2939 (and (not (plist-get info :with-emphasize))
2940 (let ((marker (cl-case (org-element-type blob)
2941 (bold "*")
2942 (italic "/")
2943 (strike-through "+")
2944 (underline "_"))))
2945 (append
2946 (list marker)
2947 (org-element-contents blob)
2948 (list (concat
2949 marker
2950 (make-string
2951 (or (org-element-property :post-blank blob)
2953 ?\s)))))))
2954 ;; ... LaTeX environments and fragments...
2955 ((latex-environment latex-fragment)
2956 (and (eq (plist-get info :with-latex) 'verbatim)
2957 (list (org-export-expand blob nil))))
2958 ;; ... sub/superscripts...
2959 ((subscript superscript)
2960 (let ((sub/super-p (plist-get info :with-sub-superscript))
2961 (bracketp (org-element-property :use-brackets-p blob)))
2962 (and (or (not sub/super-p)
2963 (and (eq sub/super-p '{}) (not bracketp)))
2964 (append
2965 (list (concat
2966 (if (eq (org-element-type blob) 'subscript)
2968 "^")
2969 (and bracketp "{")))
2970 (org-element-contents blob)
2971 (list (concat
2972 (and bracketp "}")
2973 (and (org-element-property :post-blank blob)
2974 (make-string
2975 (org-element-property :post-blank blob)
2976 ?\s)))))))))))
2977 (when new
2978 ;; Splice NEW at BLOB location in parse tree.
2979 (dolist (e new (org-element-extract-element blob))
2980 (unless (equal e "") (org-element-insert-before e blob))))))
2981 info nil nil t)
2982 ;; Return modified parse tree.
2983 data)
2985 ;;;###autoload
2986 (defun org-export-as
2987 (backend &optional subtreep visible-only body-only ext-plist)
2988 "Transcode current Org buffer into BACKEND code.
2990 BACKEND is either an export back-end, as returned by, e.g.,
2991 `org-export-create-backend', or a symbol referring to
2992 a registered back-end.
2994 If narrowing is active in the current buffer, only transcode its
2995 narrowed part.
2997 If a region is active, transcode that region.
2999 When optional argument SUBTREEP is non-nil, transcode the
3000 sub-tree at point, extracting information from the headline
3001 properties first.
3003 When optional argument VISIBLE-ONLY is non-nil, don't export
3004 contents of hidden elements.
3006 When optional argument BODY-ONLY is non-nil, only return body
3007 code, without surrounding template.
3009 Optional argument EXT-PLIST, when provided, is a property list
3010 with external parameters overriding Org default settings, but
3011 still inferior to file-local settings.
3013 Return code as a string."
3014 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
3015 (org-export-barf-if-invalid-backend backend)
3016 (save-excursion
3017 (save-restriction
3018 ;; Narrow buffer to an appropriate region or subtree for
3019 ;; parsing. If parsing subtree, be sure to remove main
3020 ;; headline, planning data and property drawer.
3021 (cond ((org-region-active-p)
3022 (narrow-to-region (region-beginning) (region-end)))
3023 (subtreep
3024 (org-narrow-to-subtree)
3025 (goto-char (point-min))
3026 (org-end-of-meta-data)
3027 (narrow-to-region (point) (point-max))))
3028 ;; Initialize communication channel with original buffer
3029 ;; attributes, unavailable in its copy.
3030 (let* ((org-export-current-backend (org-export-backend-name backend))
3031 (info (org-combine-plists
3032 (org-export--get-export-attributes
3033 backend subtreep visible-only body-only)
3034 (org-export--get-buffer-attributes)))
3035 (parsed-keywords
3036 (delq nil
3037 (mapcar (lambda (o) (and (eq (nth 4 o) 'parse) (nth 1 o)))
3038 (append (org-export-get-all-options backend)
3039 org-export-options-alist))))
3040 tree)
3041 ;; Update communication channel and get parse tree. Buffer
3042 ;; isn't parsed directly. Instead, all buffer modifications
3043 ;; and consequent parsing are undertaken in a temporary copy.
3044 (org-export-with-buffer-copy
3045 ;; Run first hook with current back-end's name as argument.
3046 (run-hook-with-args 'org-export-before-processing-hook
3047 (org-export-backend-name backend))
3048 ;; Include files, delete comments and expand macros.
3049 (org-export-expand-include-keyword)
3050 (org-export--delete-comment-trees)
3051 (org-macro-initialize-templates)
3052 (org-macro-replace-all
3053 (append org-macro-templates org-export-global-macros)
3054 nil parsed-keywords)
3055 ;; Refresh buffer properties and radio targets after
3056 ;; potentially invasive previous changes. Likewise, do it
3057 ;; again after executing Babel code.
3058 (org-set-regexps-and-options)
3059 (org-update-radio-target-regexp)
3060 (when org-export-use-babel
3061 (org-babel-exp-process-buffer)
3062 (org-set-regexps-and-options)
3063 (org-update-radio-target-regexp))
3064 ;; Run last hook with current back-end's name as argument.
3065 ;; Update buffer properties and radio targets one last time
3066 ;; before parsing.
3067 (goto-char (point-min))
3068 (save-excursion
3069 (run-hook-with-args 'org-export-before-parsing-hook
3070 (org-export-backend-name backend)))
3071 (org-set-regexps-and-options)
3072 (org-update-radio-target-regexp)
3073 ;; Update communication channel with environment. Also
3074 ;; install user's and developer's filters.
3075 (setq info
3076 (org-export-install-filters
3077 (org-combine-plists
3078 info (org-export-get-environment backend subtreep ext-plist))))
3079 ;; Call options filters and update export options. We do not
3080 ;; use `org-export-filter-apply-functions' here since the
3081 ;; arity of such filters is different.
3082 (let ((backend-name (org-export-backend-name backend)))
3083 (dolist (filter (plist-get info :filter-options))
3084 (let ((result (funcall filter info backend-name)))
3085 (when result (setq info result)))))
3086 ;; Expand export-specific set of macros: {{{author}}},
3087 ;; {{{date(FORMAT)}}}, {{{email}}} and {{{title}}}. It must
3088 ;; be done once regular macros have been expanded, since
3089 ;; parsed keywords may contain one of them.
3090 (org-macro-replace-all
3091 (list
3092 (cons "author" (org-element-interpret-data (plist-get info :author)))
3093 (cons "date"
3094 (let* ((date (plist-get info :date))
3095 (value (or (org-element-interpret-data date) "")))
3096 (if (and (consp date)
3097 (not (cdr date))
3098 (eq (org-element-type (car date)) 'timestamp))
3099 (format "(eval (if (org-string-nw-p \"$1\") %s %S))"
3100 (format "(org-timestamp-format '%S \"$1\")"
3101 (org-element-copy (car date)))
3102 value)
3103 value)))
3104 (cons "email" (org-element-interpret-data (plist-get info :email)))
3105 (cons "title" (org-element-interpret-data (plist-get info :title)))
3106 (cons "results" "$1"))
3107 'finalize
3108 parsed-keywords)
3109 ;; Parse buffer.
3110 (setq tree (org-element-parse-buffer nil visible-only))
3111 ;; Prune tree from non-exported elements and transform
3112 ;; uninterpreted elements or objects in both parse tree and
3113 ;; communication channel.
3114 (org-export--prune-tree tree info)
3115 (org-export--remove-uninterpreted-data tree info)
3116 ;; Call parse tree filters.
3117 (setq tree
3118 (org-export-filter-apply-functions
3119 (plist-get info :filter-parse-tree) tree info))
3120 ;; Now tree is complete, compute its properties and add them
3121 ;; to communication channel.
3122 (setq info (org-export--collect-tree-properties tree info))
3123 ;; Eventually transcode TREE. Wrap the resulting string into
3124 ;; a template.
3125 (let* ((body (org-element-normalize-string
3126 (or (org-export-data tree info) "")))
3127 (inner-template (cdr (assq 'inner-template
3128 (plist-get info :translate-alist))))
3129 (full-body (org-export-filter-apply-functions
3130 (plist-get info :filter-body)
3131 (if (not (functionp inner-template)) body
3132 (funcall inner-template body info))
3133 info))
3134 (template (cdr (assq 'template
3135 (plist-get info :translate-alist)))))
3136 ;; Remove all text properties since they cannot be
3137 ;; retrieved from an external process. Finally call
3138 ;; final-output filter and return result.
3139 (org-no-properties
3140 (org-export-filter-apply-functions
3141 (plist-get info :filter-final-output)
3142 (if (or (not (functionp template)) body-only) full-body
3143 (funcall template full-body info))
3144 info))))))))
3146 ;;;###autoload
3147 (defun org-export-string-as (string backend &optional body-only ext-plist)
3148 "Transcode STRING into BACKEND code.
3150 BACKEND is either an export back-end, as returned by, e.g.,
3151 `org-export-create-backend', or a symbol referring to
3152 a registered back-end.
3154 When optional argument BODY-ONLY is non-nil, only return body
3155 code, without preamble nor postamble.
3157 Optional argument EXT-PLIST, when provided, is a property list
3158 with external parameters overriding Org default settings, but
3159 still inferior to file-local settings.
3161 Return code as a string."
3162 (with-temp-buffer
3163 (insert string)
3164 (let ((org-inhibit-startup t)) (org-mode))
3165 (org-export-as backend nil nil body-only ext-plist)))
3167 ;;;###autoload
3168 (defun org-export-replace-region-by (backend)
3169 "Replace the active region by its export to BACKEND.
3170 BACKEND is either an export back-end, as returned by, e.g.,
3171 `org-export-create-backend', or a symbol referring to
3172 a registered back-end."
3173 (unless (org-region-active-p) (user-error "No active region to replace"))
3174 (insert
3175 (org-export-string-as
3176 (delete-and-extract-region (region-beginning) (region-end)) backend t)))
3178 ;;;###autoload
3179 (defun org-export-insert-default-template (&optional backend subtreep)
3180 "Insert all export keywords with default values at beginning of line.
3182 BACKEND is a symbol referring to the name of a registered export
3183 back-end, for which specific export options should be added to
3184 the template, or `default' for default template. When it is nil,
3185 the user will be prompted for a category.
3187 If SUBTREEP is non-nil, export configuration will be set up
3188 locally for the subtree through node properties."
3189 (interactive)
3190 (unless (derived-mode-p 'org-mode) (user-error "Not in an Org mode buffer"))
3191 (when (and subtreep (org-before-first-heading-p))
3192 (user-error "No subtree to set export options for"))
3193 (let ((node (and subtreep (save-excursion (org-back-to-heading t) (point))))
3194 (backend
3195 (or backend
3196 (intern
3197 (org-completing-read
3198 "Options category: "
3199 (cons "default"
3200 (mapcar (lambda (b)
3201 (symbol-name (org-export-backend-name b)))
3202 org-export-registered-backends))
3203 nil t))))
3204 options keywords)
3205 ;; Populate OPTIONS and KEYWORDS.
3206 (dolist (entry (cond ((eq backend 'default) org-export-options-alist)
3207 ((org-export-backend-p backend)
3208 (org-export-backend-options backend))
3209 (t (org-export-backend-options
3210 (org-export-get-backend backend)))))
3211 (let ((keyword (nth 1 entry))
3212 (option (nth 2 entry)))
3213 (cond
3214 (keyword (unless (assoc keyword keywords)
3215 (let ((value
3216 (if (eq (nth 4 entry) 'split)
3217 (mapconcat #'identity (eval (nth 3 entry)) " ")
3218 (eval (nth 3 entry)))))
3219 (push (cons keyword value) keywords))))
3220 (option (unless (assoc option options)
3221 (push (cons option (eval (nth 3 entry))) options))))))
3222 ;; Move to an appropriate location in order to insert options.
3223 (unless subtreep (beginning-of-line))
3224 ;; First (multiple) OPTIONS lines. Never go past fill-column.
3225 (when options
3226 (let ((items
3227 (mapcar
3228 #'(lambda (opt) (format "%s:%S" (car opt) (cdr opt)))
3229 (sort options (lambda (k1 k2) (string< (car k1) (car k2)))))))
3230 (if subtreep
3231 (org-entry-put
3232 node "EXPORT_OPTIONS" (mapconcat 'identity items " "))
3233 (while items
3234 (insert "#+OPTIONS:")
3235 (let ((width 10))
3236 (while (and items
3237 (< (+ width (length (car items)) 1) fill-column))
3238 (let ((item (pop items)))
3239 (insert " " item)
3240 (cl-incf width (1+ (length item))))))
3241 (insert "\n")))))
3242 ;; Then the rest of keywords, in the order specified in either
3243 ;; `org-export-options-alist' or respective export back-ends.
3244 (dolist (key (nreverse keywords))
3245 (let ((val (cond ((equal (car key) "DATE")
3246 (or (cdr key)
3247 (with-temp-buffer
3248 (org-insert-time-stamp (current-time)))))
3249 ((equal (car key) "TITLE")
3250 (or (let ((visited-file
3251 (buffer-file-name (buffer-base-buffer))))
3252 (and visited-file
3253 (file-name-sans-extension
3254 (file-name-nondirectory visited-file))))
3255 (buffer-name (buffer-base-buffer))))
3256 (t (cdr key)))))
3257 (if subtreep (org-entry-put node (concat "EXPORT_" (car key)) val)
3258 (insert
3259 (format "#+%s:%s\n"
3260 (car key)
3261 (if (org-string-nw-p val) (format " %s" val) ""))))))))
3263 (defun org-export-expand-include-keyword (&optional included dir footnotes)
3264 "Expand every include keyword in buffer.
3265 Optional argument INCLUDED is a list of included file names along
3266 with their line restriction, when appropriate. It is used to
3267 avoid infinite recursion. Optional argument DIR is the current
3268 working directory. It is used to properly resolve relative
3269 paths. Optional argument FOOTNOTES is a hash-table used for
3270 storing and resolving footnotes. It is created automatically."
3271 (let ((case-fold-search t)
3272 (file-prefix (make-hash-table :test #'equal))
3273 (current-prefix 0)
3274 (footnotes (or footnotes (make-hash-table :test #'equal)))
3275 (include-re "^[ \t]*#\\+INCLUDE:"))
3276 ;; If :minlevel is not set the text-property
3277 ;; `:org-include-induced-level' will be used to determine the
3278 ;; relative level when expanding INCLUDE.
3279 ;; Only affects included Org documents.
3280 (goto-char (point-min))
3281 (while (re-search-forward include-re nil t)
3282 (put-text-property (line-beginning-position) (line-end-position)
3283 :org-include-induced-level
3284 (1+ (org-reduced-level (or (org-current-level) 0)))))
3285 ;; Expand INCLUDE keywords.
3286 (goto-char (point-min))
3287 (while (re-search-forward include-re nil t)
3288 (let ((element (save-match-data (org-element-at-point))))
3289 (when (eq (org-element-type element) 'keyword)
3290 (beginning-of-line)
3291 ;; Extract arguments from keyword's value.
3292 (let* ((value (org-element-property :value element))
3293 (ind (org-get-indentation))
3294 location
3295 (file
3296 (and (string-match
3297 "^\\(\".+?\"\\|\\S-+\\)\\(?:\\s-+\\|$\\)" value)
3298 (prog1
3299 (save-match-data
3300 (let ((matched (match-string 1 value)))
3301 (when (string-match "\\(::\\(.*?\\)\\)\"?\\'"
3302 matched)
3303 (setq location (match-string 2 matched))
3304 (setq matched
3305 (replace-match "" nil nil matched 1)))
3306 (expand-file-name
3307 (org-unbracket-string "\"" "\"" matched)
3308 dir)))
3309 (setq value (replace-match "" nil nil value)))))
3310 (only-contents
3311 (and (string-match ":only-contents *\\([^: \r\t\n]\\S-*\\)?"
3312 value)
3313 (prog1 (org-not-nil (match-string 1 value))
3314 (setq value (replace-match "" nil nil value)))))
3315 (lines
3316 (and (string-match
3317 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\""
3318 value)
3319 (prog1 (match-string 1 value)
3320 (setq value (replace-match "" nil nil value)))))
3321 (env (cond
3322 ((string-match "\\<example\\>" value) 'literal)
3323 ((string-match "\\<export\\(?: +\\(.*\\)\\)?" value)
3324 'literal)
3325 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
3326 'literal)))
3327 ;; Minimal level of included file defaults to the child
3328 ;; level of the current headline, if any, or one. It
3329 ;; only applies is the file is meant to be included as
3330 ;; an Org one.
3331 (minlevel
3332 (and (not env)
3333 (if (string-match ":minlevel +\\([0-9]+\\)" value)
3334 (prog1 (string-to-number (match-string 1 value))
3335 (setq value (replace-match "" nil nil value)))
3336 (get-text-property (point)
3337 :org-include-induced-level))))
3338 (args (and (eq env 'literal) (match-string 1 value)))
3339 (block (and (string-match "\\<\\(\\S-+\\)\\>" value)
3340 (match-string 1 value))))
3341 ;; Remove keyword.
3342 (delete-region (point) (line-beginning-position 2))
3343 (cond
3344 ((not file) nil)
3345 ((not (file-readable-p file))
3346 (error "Cannot include file %s" file))
3347 ;; Check if files has already been parsed. Look after
3348 ;; inclusion lines too, as different parts of the same file
3349 ;; can be included too.
3350 ((member (list file lines) included)
3351 (error "Recursive file inclusion: %s" file))
3353 (cond
3354 ((eq env 'literal)
3355 (insert
3356 (let ((ind-str (make-string ind ?\s))
3357 (arg-str (if (stringp args) (format " %s" args) ""))
3358 (contents
3359 (org-escape-code-in-string
3360 (org-export--prepare-file-contents file lines))))
3361 (format "%s#+BEGIN_%s%s\n%s%s#+END_%s\n"
3362 ind-str block arg-str contents ind-str block))))
3363 ((stringp block)
3364 (insert
3365 (let ((ind-str (make-string ind ?\s))
3366 (contents
3367 (org-export--prepare-file-contents file lines)))
3368 (format "%s#+BEGIN_%s\n%s%s#+END_%s\n"
3369 ind-str block contents ind-str block))))
3371 (insert
3372 (with-temp-buffer
3373 (let ((org-inhibit-startup t)
3374 (lines
3375 (if location
3376 (org-export--inclusion-absolute-lines
3377 file location only-contents lines)
3378 lines)))
3379 (org-mode)
3380 (insert
3381 (org-export--prepare-file-contents
3382 file lines ind minlevel
3383 (or (gethash file file-prefix)
3384 (puthash file (cl-incf current-prefix) file-prefix))
3385 footnotes)))
3386 (org-export-expand-include-keyword
3387 (cons (list file lines) included)
3388 (file-name-directory file)
3389 footnotes)
3390 (buffer-string)))))
3391 ;; Expand footnotes after all files have been included.
3392 ;; Footnotes are stored at end of buffer.
3393 (unless included
3394 (org-with-wide-buffer
3395 (goto-char (point-max))
3396 (maphash (lambda (k v) (insert (format "\n[fn:%s] %s\n" k v)))
3397 footnotes)))))))))))
3399 (defun org-export--inclusion-absolute-lines (file location only-contents lines)
3400 "Resolve absolute lines for an included file with file-link.
3402 FILE is string file-name of the file to include. LOCATION is a
3403 string name within FILE to be included (located via
3404 `org-link-search'). If ONLY-CONTENTS is non-nil only the
3405 contents of the named element will be included, as determined
3406 Org-Element. If LINES is non-nil only those lines are included.
3408 Return a string of lines to be included in the format expected by
3409 `org-export--prepare-file-contents'."
3410 (with-temp-buffer
3411 (insert-file-contents file)
3412 (unless (eq major-mode 'org-mode)
3413 (let ((org-inhibit-startup t)) (org-mode)))
3414 (condition-case err
3415 ;; Enforce consistent search.
3416 (let ((org-link-search-must-match-exact-headline nil))
3417 (org-link-search location))
3418 (error
3419 (error "%s for %s::%s" (error-message-string err) file location)))
3420 (let* ((element (org-element-at-point))
3421 (contents-begin
3422 (and only-contents (org-element-property :contents-begin element))))
3423 (narrow-to-region
3424 (or contents-begin (org-element-property :begin element))
3425 (org-element-property (if contents-begin :contents-end :end) element))
3426 (when (and only-contents
3427 (memq (org-element-type element) '(headline inlinetask)))
3428 ;; Skip planning line and property-drawer.
3429 (goto-char (point-min))
3430 (when (looking-at-p org-planning-line-re) (forward-line))
3431 (when (looking-at org-property-drawer-re) (goto-char (match-end 0)))
3432 (unless (bolp) (forward-line))
3433 (narrow-to-region (point) (point-max))))
3434 (when lines
3435 (org-skip-whitespace)
3436 (beginning-of-line)
3437 (let* ((lines (split-string lines "-"))
3438 (lbeg (string-to-number (car lines)))
3439 (lend (string-to-number (cadr lines)))
3440 (beg (if (zerop lbeg) (point-min)
3441 (goto-char (point-min))
3442 (forward-line (1- lbeg))
3443 (point)))
3444 (end (if (zerop lend) (point-max)
3445 (goto-char beg)
3446 (forward-line (1- lend))
3447 (point))))
3448 (narrow-to-region beg end)))
3449 (let ((end (point-max)))
3450 (goto-char (point-min))
3451 (widen)
3452 (let ((start-line (line-number-at-pos)))
3453 (format "%d-%d"
3454 start-line
3455 (save-excursion
3456 (+ start-line
3457 (let ((counter 0))
3458 (while (< (point) end) (cl-incf counter) (forward-line))
3459 counter))))))))
3461 (defun org-export--prepare-file-contents
3462 (file &optional lines ind minlevel id footnotes)
3463 "Prepare contents of FILE for inclusion and return it as a string.
3465 When optional argument LINES is a string specifying a range of
3466 lines, include only those lines.
3468 Optional argument IND, when non-nil, is an integer specifying the
3469 global indentation of returned contents. Since its purpose is to
3470 allow an included file to stay in the same environment it was
3471 created (e.g., a list item), it doesn't apply past the first
3472 headline encountered.
3474 Optional argument MINLEVEL, when non-nil, is an integer
3475 specifying the level that any top-level headline in the included
3476 file should have.
3478 Optional argument ID is an integer that will be inserted before
3479 each footnote definition and reference if FILE is an Org file.
3480 This is useful to avoid conflicts when more than one Org file
3481 with footnotes is included in a document.
3483 Optional argument FOOTNOTES is a hash-table to store footnotes in
3484 the included document."
3485 (with-temp-buffer
3486 (insert-file-contents file)
3487 (when lines
3488 (let* ((lines (split-string lines "-"))
3489 (lbeg (string-to-number (car lines)))
3490 (lend (string-to-number (cadr lines)))
3491 (beg (if (zerop lbeg) (point-min)
3492 (goto-char (point-min))
3493 (forward-line (1- lbeg))
3494 (point)))
3495 (end (if (zerop lend) (point-max)
3496 (goto-char (point-min))
3497 (forward-line (1- lend))
3498 (point))))
3499 (narrow-to-region beg end)))
3500 ;; Remove blank lines at beginning and end of contents. The logic
3501 ;; behind that removal is that blank lines around include keyword
3502 ;; override blank lines in included file.
3503 (goto-char (point-min))
3504 (org-skip-whitespace)
3505 (beginning-of-line)
3506 (delete-region (point-min) (point))
3507 (goto-char (point-max))
3508 (skip-chars-backward " \r\t\n")
3509 (forward-line)
3510 (delete-region (point) (point-max))
3511 ;; If IND is set, preserve indentation of include keyword until
3512 ;; the first headline encountered.
3513 (when (and ind (> ind 0))
3514 (unless (eq major-mode 'org-mode)
3515 (let ((org-inhibit-startup t)) (org-mode)))
3516 (goto-char (point-min))
3517 (let ((ind-str (make-string ind ?\s)))
3518 (while (not (or (eobp) (looking-at org-outline-regexp-bol)))
3519 ;; Do not move footnote definitions out of column 0.
3520 (unless (and (looking-at org-footnote-definition-re)
3521 (eq (org-element-type (org-element-at-point))
3522 'footnote-definition))
3523 (insert ind-str))
3524 (forward-line))))
3525 ;; When MINLEVEL is specified, compute minimal level for headlines
3526 ;; in the file (CUR-MIN), and remove stars to each headline so
3527 ;; that headlines with minimal level have a level of MINLEVEL.
3528 (when minlevel
3529 (unless (eq major-mode 'org-mode)
3530 (let ((org-inhibit-startup t)) (org-mode)))
3531 (org-with-limited-levels
3532 (let ((levels (org-map-entries
3533 (lambda () (org-reduced-level (org-current-level))))))
3534 (when levels
3535 (let ((offset (- minlevel (apply #'min levels))))
3536 (unless (zerop offset)
3537 (when org-odd-levels-only (setq offset (* offset 2)))
3538 ;; Only change stars, don't bother moving whole
3539 ;; sections.
3540 (org-map-entries
3541 (lambda ()
3542 (if (< offset 0) (delete-char (abs offset))
3543 (insert (make-string offset ?*)))))))))))
3544 ;; Append ID to all footnote references and definitions, so they
3545 ;; become file specific and cannot collide with footnotes in other
3546 ;; included files. Further, collect relevant footnote definitions
3547 ;; outside of LINES, in order to reintroduce them later.
3548 (when id
3549 (let ((marker-min (point-min-marker))
3550 (marker-max (point-max-marker))
3551 (get-new-label
3552 (lambda (label)
3553 ;; Generate new label from LABEL by prefixing it with
3554 ;; "-ID-".
3555 (format "-%d-%s" id label)))
3556 (set-new-label
3557 (lambda (f old new)
3558 ;; Replace OLD label with NEW in footnote F.
3559 (save-excursion
3560 (goto-char (+ (org-element-property :begin f) 4))
3561 (looking-at (regexp-quote old))
3562 (replace-match new))))
3563 (seen-alist))
3564 (goto-char (point-min))
3565 (while (re-search-forward org-footnote-re nil t)
3566 (let ((footnote (save-excursion
3567 (backward-char)
3568 (org-element-context))))
3569 (when (memq (org-element-type footnote)
3570 '(footnote-definition footnote-reference))
3571 (let* ((label (org-element-property :label footnote)))
3572 ;; Update the footnote-reference at point and collect
3573 ;; the new label, which is only used for footnotes
3574 ;; outsides LINES.
3575 (when label
3576 (let ((seen (cdr (assoc label seen-alist))))
3577 (if seen (funcall set-new-label footnote label seen)
3578 (let ((new (funcall get-new-label label)))
3579 (push (cons label new) seen-alist)
3580 (org-with-wide-buffer
3581 (let* ((def (org-footnote-get-definition label))
3582 (beg (nth 1 def)))
3583 (when (and def
3584 (or (< beg marker-min)
3585 (>= beg marker-max)))
3586 ;; Store since footnote-definition is
3587 ;; outside of LINES.
3588 (puthash new
3589 (org-element-normalize-string (nth 3 def))
3590 footnotes))))
3591 (funcall set-new-label footnote label new)))))))))
3592 (set-marker marker-min nil)
3593 (set-marker marker-max nil)))
3594 (org-element-normalize-string (buffer-string))))
3596 (defun org-export--copy-to-kill-ring-p ()
3597 "Return a non-nil value when output should be added to the kill ring.
3598 See also `org-export-copy-to-kill-ring'."
3599 (if (eq org-export-copy-to-kill-ring 'if-interactive)
3600 (not (or executing-kbd-macro noninteractive))
3601 (eq org-export-copy-to-kill-ring t)))
3605 ;;; Tools For Back-Ends
3607 ;; A whole set of tools is available to help build new exporters. Any
3608 ;; function general enough to have its use across many back-ends
3609 ;; should be added here.
3611 ;;;; For Affiliated Keywords
3613 ;; `org-export-read-attribute' reads a property from a given element
3614 ;; as a plist. It can be used to normalize affiliated keywords'
3615 ;; syntax.
3617 ;; Since captions can span over multiple lines and accept dual values,
3618 ;; their internal representation is a bit tricky. Therefore,
3619 ;; `org-export-get-caption' transparently returns a given element's
3620 ;; caption as a secondary string.
3622 (defun org-export-read-attribute (attribute element &optional property)
3623 "Turn ATTRIBUTE property from ELEMENT into a plist.
3625 When optional argument PROPERTY is non-nil, return the value of
3626 that property within attributes.
3628 This function assumes attributes are defined as \":keyword
3629 value\" pairs. It is appropriate for `:attr_html' like
3630 properties.
3632 All values will become strings except the empty string and
3633 \"nil\", which will become nil. Also, values containing only
3634 double quotes will be read as-is, which means that \"\" value
3635 will become the empty string."
3636 (let* ((prepare-value
3637 (lambda (str)
3638 (save-match-data
3639 (cond ((member str '(nil "" "nil")) nil)
3640 ((string-match "^\"\\(\"+\\)?\"$" str)
3641 (or (match-string 1 str) ""))
3642 (t str)))))
3643 (attributes
3644 (let ((value (org-element-property attribute element)))
3645 (when value
3646 (let ((s (mapconcat 'identity value " ")) result)
3647 (while (string-match
3648 "\\(?:^\\|[ \t]+\\)\\(:[-a-zA-Z0-9_]+\\)\\([ \t]+\\|$\\)"
3650 (let ((value (substring s 0 (match-beginning 0))))
3651 (push (funcall prepare-value value) result))
3652 (push (intern (match-string 1 s)) result)
3653 (setq s (substring s (match-end 0))))
3654 ;; Ignore any string before first property with `cdr'.
3655 (cdr (nreverse (cons (funcall prepare-value s) result))))))))
3656 (if property (plist-get attributes property) attributes)))
3658 (defun org-export-get-caption (element &optional shortp)
3659 "Return caption from ELEMENT as a secondary string.
3661 When optional argument SHORTP is non-nil, return short caption,
3662 as a secondary string, instead.
3664 Caption lines are separated by a white space."
3665 (let ((full-caption (org-element-property :caption element)) caption)
3666 (dolist (line full-caption (cdr caption))
3667 (let ((cap (funcall (if shortp 'cdr 'car) line)))
3668 (when cap
3669 (setq caption (nconc (list " ") (copy-sequence cap) caption)))))))
3672 ;;;; For Derived Back-ends
3674 ;; `org-export-with-backend' is a function allowing to locally use
3675 ;; another back-end to transcode some object or element. In a derived
3676 ;; back-end, it may be used as a fall-back function once all specific
3677 ;; cases have been treated.
3679 (defun org-export-with-backend (backend data &optional contents info)
3680 "Call a transcoder from BACKEND on DATA.
3681 BACKEND is an export back-end, as returned by, e.g.,
3682 `org-export-create-backend', or a symbol referring to
3683 a registered back-end. DATA is an Org element, object, secondary
3684 string or string. CONTENTS, when non-nil, is the transcoded
3685 contents of DATA element, as a string. INFO, when non-nil, is
3686 the communication channel used for export, as a plist."
3687 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
3688 (org-export-barf-if-invalid-backend backend)
3689 (let ((type (org-element-type data)))
3690 (when (memq type '(nil org-data)) (error "No foreign transcoder available"))
3691 (let* ((all-transcoders (org-export-get-all-transcoders backend))
3692 (transcoder (cdr (assq type all-transcoders))))
3693 (unless (functionp transcoder) (error "No foreign transcoder available"))
3694 (let ((new-info
3695 (org-combine-plists
3696 info (list
3697 :back-end backend
3698 :translate-alist all-transcoders
3699 :exported-data (make-hash-table :test #'eq :size 401)))))
3700 ;; `:internal-references' are shared across back-ends.
3701 (prog1 (funcall transcoder data contents new-info)
3702 (plist-put info :internal-references
3703 (plist-get new-info :internal-references)))))))
3706 ;;;; For Export Snippets
3708 ;; Every export snippet is transmitted to the back-end. Though, the
3709 ;; latter will only retain one type of export-snippet, ignoring
3710 ;; others, based on the former's target back-end. The function
3711 ;; `org-export-snippet-backend' returns that back-end for a given
3712 ;; export-snippet.
3714 (defun org-export-snippet-backend (export-snippet)
3715 "Return EXPORT-SNIPPET targeted back-end as a symbol.
3716 Translation, with `org-export-snippet-translation-alist', is
3717 applied."
3718 (let ((back-end (org-element-property :back-end export-snippet)))
3719 (intern
3720 (or (cdr (assoc back-end org-export-snippet-translation-alist))
3721 back-end))))
3724 ;;;; For Footnotes
3726 ;; `org-export-collect-footnote-definitions' is a tool to list
3727 ;; actually used footnotes definitions in the whole parse tree, or in
3728 ;; a headline, in order to add footnote listings throughout the
3729 ;; transcoded data.
3731 ;; `org-export-footnote-first-reference-p' is a predicate used by some
3732 ;; back-ends, when they need to attach the footnote definition only to
3733 ;; the first occurrence of the corresponding label.
3735 ;; `org-export-get-footnote-definition' and
3736 ;; `org-export-get-footnote-number' provide easier access to
3737 ;; additional information relative to a footnote reference.
3739 (defun org-export-get-footnote-definition (footnote-reference info)
3740 "Return definition of FOOTNOTE-REFERENCE as parsed data.
3741 INFO is the plist used as a communication channel. If no such
3742 definition can be found, raise an error."
3743 (let ((label (org-element-property :label footnote-reference)))
3744 (if (not label) (org-element-contents footnote-reference)
3745 (let ((cache (or (plist-get info :footnote-definition-cache)
3746 (let ((hash (make-hash-table :test #'equal)))
3747 (plist-put info :footnote-definition-cache hash)
3748 hash))))
3750 (gethash label cache)
3751 (puthash label
3752 (org-element-map (plist-get info :parse-tree)
3753 '(footnote-definition footnote-reference)
3754 (lambda (f)
3755 (cond
3756 ;; Skip any footnote with a different label.
3757 ;; Also skip any standard footnote reference
3758 ;; with the same label since those cannot
3759 ;; contain a definition.
3760 ((not (equal (org-element-property :label f) label)) nil)
3761 ((eq (org-element-property :type f) 'standard) nil)
3762 ((org-element-contents f))
3763 ;; Even if the contents are empty, we can not
3764 ;; return nil since that would eventually raise
3765 ;; the error. Instead, return the equivalent
3766 ;; empty string.
3767 (t "")))
3768 info t)
3769 cache)
3770 (error "Definition not found for footnote %s" label))))))
3772 (defun org-export--footnote-reference-map
3773 (function data info &optional body-first)
3774 "Apply FUNCTION on every footnote reference in DATA.
3775 INFO is a plist containing export state. By default, as soon as
3776 a new footnote reference is encountered, FUNCTION is called onto
3777 its definition. However, if BODY-FIRST is non-nil, this step is
3778 delayed until the end of the process."
3779 (letrec ((definitions nil)
3780 (seen-refs nil)
3781 (search-ref
3782 (lambda (data delayp)
3783 ;; Search footnote references through DATA, filling
3784 ;; SEEN-REFS along the way. When DELAYP is non-nil,
3785 ;; store footnote definitions so they can be entered
3786 ;; later.
3787 (org-element-map data 'footnote-reference
3788 (lambda (f)
3789 (funcall function f)
3790 (let ((--label (org-element-property :label f)))
3791 (unless (and --label (member --label seen-refs))
3792 (when --label (push --label seen-refs))
3793 ;; Search for subsequent references in footnote
3794 ;; definition so numbering follows reading
3795 ;; logic, unless DELAYP in non-nil.
3796 (cond
3797 (delayp
3798 (push (org-export-get-footnote-definition f info)
3799 definitions))
3800 ;; Do not force entering inline definitions,
3801 ;; since `org-element-map' already traverses
3802 ;; them at the right time.
3803 ((eq (org-element-property :type f) 'inline))
3804 (t (funcall search-ref
3805 (org-export-get-footnote-definition f info)
3806 nil))))))
3807 info nil
3808 ;; Don't enter footnote definitions since it will
3809 ;; happen when their first reference is found.
3810 ;; Moreover, if DELAYP is non-nil, make sure we
3811 ;; postpone entering definitions of inline references.
3812 (if delayp '(footnote-definition footnote-reference)
3813 'footnote-definition)))))
3814 (funcall search-ref data body-first)
3815 (funcall search-ref (nreverse definitions) nil)))
3817 (defun org-export-collect-footnote-definitions (info &optional data body-first)
3818 "Return an alist between footnote numbers, labels and definitions.
3820 INFO is the current export state, as a plist.
3822 Definitions are collected throughout the whole parse tree, or
3823 DATA when non-nil.
3825 Sorting is done by order of references. As soon as a new
3826 reference is encountered, other references are searched within
3827 its definition. However, if BODY-FIRST is non-nil, this step is
3828 delayed after the whole tree is checked. This alters results
3829 when references are found in footnote definitions.
3831 Definitions either appear as Org data or as a secondary string
3832 for inlined footnotes. Unreferenced definitions are ignored."
3833 (let ((n 0) labels alist)
3834 (org-export--footnote-reference-map
3835 (lambda (f)
3836 ;; Collect footnote number, label and definition.
3837 (let ((l (org-element-property :label f)))
3838 (unless (and l (member l labels))
3839 (cl-incf n)
3840 (push (list n l (org-export-get-footnote-definition f info)) alist))
3841 (when l (push l labels))))
3842 (or data (plist-get info :parse-tree)) info body-first)
3843 (nreverse alist)))
3845 (defun org-export-footnote-first-reference-p
3846 (footnote-reference info &optional data body-first)
3847 "Non-nil when a footnote reference is the first one for its label.
3849 FOOTNOTE-REFERENCE is the footnote reference being considered.
3850 INFO is a plist containing current export state.
3852 Search is done throughout the whole parse tree, or DATA when
3853 non-nil.
3855 By default, as soon as a new footnote reference is encountered,
3856 other references are searched within its definition. However, if
3857 BODY-FIRST is non-nil, this step is delayed after the whole tree
3858 is checked. This alters results when references are found in
3859 footnote definitions."
3860 (let ((label (org-element-property :label footnote-reference)))
3861 ;; Anonymous footnotes are always a first reference.
3862 (or (not label)
3863 (catch 'exit
3864 (org-export--footnote-reference-map
3865 (lambda (f)
3866 (let ((l (org-element-property :label f)))
3867 (when (and l label (string= label l))
3868 (throw 'exit (eq footnote-reference f)))))
3869 (or data (plist-get info :parse-tree)) info body-first)))))
3871 (defun org-export-get-footnote-number (footnote info &optional data body-first)
3872 "Return number associated to a footnote.
3874 FOOTNOTE is either a footnote reference or a footnote definition.
3875 INFO is the plist containing export state.
3877 Number is unique throughout the whole parse tree, or DATA, when
3878 non-nil.
3880 By default, as soon as a new footnote reference is encountered,
3881 counting process moves into its definition. However, if
3882 BODY-FIRST is non-nil, this step is delayed until the end of the
3883 process, leading to a different order when footnotes are nested."
3884 (let ((count 0)
3885 (seen)
3886 (label (org-element-property :label footnote)))
3887 (catch 'exit
3888 (org-export--footnote-reference-map
3889 (lambda (f)
3890 (let ((l (org-element-property :label f)))
3891 (cond
3892 ;; Anonymous footnote match: return number.
3893 ((and (not l) (not label) (eq footnote f)) (throw 'exit (1+ count)))
3894 ;; Labels match: return number.
3895 ((and label l (string= label l)) (throw 'exit (1+ count)))
3896 ;; Otherwise store label and increase counter if label
3897 ;; wasn't encountered yet.
3898 ((not l) (cl-incf count))
3899 ((not (member l seen)) (push l seen) (cl-incf count)))))
3900 (or data (plist-get info :parse-tree)) info body-first))))
3903 ;;;; For Headlines
3905 ;; `org-export-get-relative-level' is a shortcut to get headline
3906 ;; level, relatively to the lower headline level in the parsed tree.
3908 ;; `org-export-get-headline-number' returns the section number of an
3909 ;; headline, while `org-export-number-to-roman' allows it to be
3910 ;; converted to roman numbers. With an optional argument,
3911 ;; `org-export-get-headline-number' returns a number to unnumbered
3912 ;; headlines (used for internal id).
3914 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
3915 ;; `org-export-last-sibling-p' are three useful predicates when it
3916 ;; comes to fulfill the `:headline-levels' property.
3918 ;; `org-export-get-tags', `org-export-get-category' and
3919 ;; `org-export-get-node-property' extract useful information from an
3920 ;; headline or a parent headline. They all handle inheritance.
3922 ;; `org-export-get-alt-title' tries to retrieve an alternative title,
3923 ;; as a secondary string, suitable for table of contents. It falls
3924 ;; back onto default title.
3926 (defun org-export-get-relative-level (headline info)
3927 "Return HEADLINE relative level within current parsed tree.
3928 INFO is a plist holding contextual information."
3929 (+ (org-element-property :level headline)
3930 (or (plist-get info :headline-offset) 0)))
3932 (defun org-export-low-level-p (headline info)
3933 "Non-nil when HEADLINE is considered as low level.
3935 INFO is a plist used as a communication channel.
3937 A low level headlines has a relative level greater than
3938 `:headline-levels' property value.
3940 Return value is the difference between HEADLINE relative level
3941 and the last level being considered as high enough, or nil."
3942 (let ((limit (plist-get info :headline-levels)))
3943 (when (wholenump limit)
3944 (let ((level (org-export-get-relative-level headline info)))
3945 (and (> level limit) (- level limit))))))
3947 (defun org-export-get-headline-number (headline info)
3948 "Return numbered HEADLINE numbering as a list of numbers.
3949 INFO is a plist holding contextual information."
3950 (and (org-export-numbered-headline-p headline info)
3951 (cdr (assq headline (plist-get info :headline-numbering)))))
3953 (defun org-export-numbered-headline-p (headline info)
3954 "Return a non-nil value if HEADLINE element should be numbered.
3955 INFO is a plist used as a communication channel."
3956 (unless (cl-some
3957 (lambda (head) (org-not-nil (org-element-property :UNNUMBERED head)))
3958 (org-element-lineage headline nil t))
3959 (let ((sec-num (plist-get info :section-numbers))
3960 (level (org-export-get-relative-level headline info)))
3961 (if (wholenump sec-num) (<= level sec-num) sec-num))))
3963 (defun org-export-number-to-roman (n)
3964 "Convert integer N into a roman numeral."
3965 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
3966 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
3967 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
3968 ( 1 . "I")))
3969 (res ""))
3970 (if (<= n 0)
3971 (number-to-string n)
3972 (while roman
3973 (if (>= n (caar roman))
3974 (setq n (- n (caar roman))
3975 res (concat res (cdar roman)))
3976 (pop roman)))
3977 res)))
3979 (defun org-export-get-tags (element info &optional tags inherited)
3980 "Return list of tags associated to ELEMENT.
3982 ELEMENT has either an `headline' or an `inlinetask' type. INFO
3983 is a plist used as a communication channel.
3985 When non-nil, optional argument TAGS should be a list of strings.
3986 Any tag belonging to this list will also be removed.
3988 When optional argument INHERITED is non-nil, tags can also be
3989 inherited from parent headlines and FILETAGS keywords."
3990 (cl-remove-if
3991 (lambda (tag) (member tag tags))
3992 (if (not inherited) (org-element-property :tags element)
3993 ;; Build complete list of inherited tags.
3994 (let ((current-tag-list (org-element-property :tags element)))
3995 (dolist (parent (org-element-lineage element))
3996 (dolist (tag (org-element-property :tags parent))
3997 (when (and (memq (org-element-type parent) '(headline inlinetask))
3998 (not (member tag current-tag-list)))
3999 (push tag current-tag-list))))
4000 ;; Add FILETAGS keywords and return results.
4001 (org-uniquify (append (plist-get info :filetags) current-tag-list))))))
4003 (defun org-export-get-node-property (property blob &optional inherited)
4004 "Return node PROPERTY value for BLOB.
4006 PROPERTY is an upcase symbol (i.e. `:COOKIE_DATA'). BLOB is an
4007 element or object.
4009 If optional argument INHERITED is non-nil, the value can be
4010 inherited from a parent headline.
4012 Return value is a string or nil."
4013 (let ((headline (if (eq (org-element-type blob) 'headline) blob
4014 (org-export-get-parent-headline blob))))
4015 (if (not inherited) (org-element-property property blob)
4016 (let ((parent headline))
4017 (catch 'found
4018 (while parent
4019 (when (plist-member (nth 1 parent) property)
4020 (throw 'found (org-element-property property parent)))
4021 (setq parent (org-element-property :parent parent))))))))
4023 (defun org-export-get-category (blob info)
4024 "Return category for element or object BLOB.
4026 INFO is a plist used as a communication channel.
4028 CATEGORY is automatically inherited from a parent headline, from
4029 #+CATEGORY: keyword or created out of original file name. If all
4030 fail, the fall-back value is \"???\"."
4031 (or (org-export-get-node-property :CATEGORY blob t)
4032 (org-element-map (plist-get info :parse-tree) 'keyword
4033 (lambda (kwd)
4034 (when (equal (org-element-property :key kwd) "CATEGORY")
4035 (org-element-property :value kwd)))
4036 info 'first-match)
4037 (let ((file (plist-get info :input-file)))
4038 (and file (file-name-sans-extension (file-name-nondirectory file))))
4039 "???"))
4041 (defun org-export-get-alt-title (headline _)
4042 "Return alternative title for HEADLINE, as a secondary string.
4043 If no optional title is defined, fall-back to the regular title."
4044 (let ((alt (org-element-property :ALT_TITLE headline)))
4045 (if alt (org-element-parse-secondary-string
4046 alt (org-element-restriction 'headline) headline)
4047 (org-element-property :title headline))))
4049 (defun org-export-first-sibling-p (blob info)
4050 "Non-nil when BLOB is the first sibling in its parent.
4051 BLOB is an element or an object. If BLOB is a headline, non-nil
4052 means it is the first sibling in the sub-tree. INFO is a plist
4053 used as a communication channel."
4054 (memq (org-element-type (org-export-get-previous-element blob info))
4055 '(nil section)))
4057 (defun org-export-last-sibling-p (blob info)
4058 "Non-nil when BLOB is the last sibling in its parent.
4059 BLOB is an element or an object. INFO is a plist used as
4060 a communication channel."
4061 (not (org-export-get-next-element blob info)))
4064 ;;;; For Keywords
4066 ;; `org-export-get-date' returns a date appropriate for the document
4067 ;; to about to be exported. In particular, it takes care of
4068 ;; `org-export-date-timestamp-format'.
4070 (defun org-export-get-date (info &optional fmt)
4071 "Return date value for the current document.
4073 INFO is a plist used as a communication channel. FMT, when
4074 non-nil, is a time format string that will be applied on the date
4075 if it consists in a single timestamp object. It defaults to
4076 `org-export-date-timestamp-format' when nil.
4078 A proper date can be a secondary string, a string or nil. It is
4079 meant to be translated with `org-export-data' or alike."
4080 (let ((date (plist-get info :date))
4081 (fmt (or fmt org-export-date-timestamp-format)))
4082 (cond ((not date) nil)
4083 ((and fmt
4084 (not (cdr date))
4085 (eq (org-element-type (car date)) 'timestamp))
4086 (org-timestamp-format (car date) fmt))
4087 (t date))))
4090 ;;;; For Links
4092 ;; `org-export-custom-protocol-maybe' handles custom protocol defined
4093 ;; in `org-link-parameters'.
4095 ;; `org-export-get-coderef-format' returns an appropriate format
4096 ;; string for coderefs.
4098 ;; `org-export-inline-image-p' returns a non-nil value when the link
4099 ;; provided should be considered as an inline image.
4101 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
4102 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
4103 ;; returns an appropriate unique identifier.
4105 ;; `org-export-resolve-id-link' returns the first headline with
4106 ;; specified id or custom-id in parse tree, the path to the external
4107 ;; file with the id.
4109 ;; `org-export-resolve-coderef' associates a reference to a line
4110 ;; number in the element it belongs, or returns the reference itself
4111 ;; when the element isn't numbered.
4113 ;; `org-export-file-uri' expands a filename as stored in :path value
4114 ;; of a "file" link into a file URI.
4116 ;; Broken links raise a `org-link-broken' error, which is caught by
4117 ;; `org-export-data' for further processing, depending on
4118 ;; `org-export-with-broken-links' value.
4120 (org-define-error 'org-link-broken "Unable to resolve link; aborting")
4122 (defun org-export-custom-protocol-maybe (link desc backend)
4123 "Try exporting LINK with a dedicated function.
4125 DESC is its description, as a string, or nil. BACKEND is the
4126 back-end used for export, as a symbol.
4128 Return output as a string, or nil if no protocol handles LINK.
4130 A custom protocol has precedence over regular back-end export.
4131 The function ignores links with an implicit type (e.g.,
4132 \"custom-id\")."
4133 (let ((type (org-element-property :type link)))
4134 (unless (or (member type '("coderef" "custom-id" "fuzzy" "radio"))
4135 (not backend))
4136 (let ((protocol (org-link-get-parameter type :export)))
4137 (and (functionp protocol)
4138 (funcall protocol
4139 (org-link-unescape (org-element-property :path link))
4140 desc
4141 backend))))))
4143 (defun org-export-get-coderef-format (path desc)
4144 "Return format string for code reference link.
4145 PATH is the link path. DESC is its description."
4146 (save-match-data
4147 (cond ((not desc) "%s")
4148 ((string-match (regexp-quote (concat "(" path ")")) desc)
4149 (replace-match "%s" t t desc))
4150 (t desc))))
4152 (defun org-export-inline-image-p (link &optional rules)
4153 "Non-nil if LINK object points to an inline image.
4155 Optional argument is a set of RULES defining inline images. It
4156 is an alist where associations have the following shape:
4158 (TYPE . REGEXP)
4160 Applying a rule means apply REGEXP against LINK's path when its
4161 type is TYPE. The function will return a non-nil value if any of
4162 the provided rules is non-nil. The default rule is
4163 `org-export-default-inline-image-rule'.
4165 This only applies to links without a description."
4166 (and (not (org-element-contents link))
4167 (let ((case-fold-search t))
4168 (cl-some (lambda (rule)
4169 (and (string= (org-element-property :type link) (car rule))
4170 (string-match-p (cdr rule)
4171 (org-element-property :path link))))
4172 (or rules org-export-default-inline-image-rule)))))
4174 (defun org-export-insert-image-links (data info &optional rules)
4175 "Insert image links in DATA.
4177 Org syntax does not support nested links. Nevertheless, some
4178 export back-ends support images as descriptions of links. Since
4179 images are really links to image files, we need to make an
4180 exception about links nesting.
4182 This function recognizes links whose contents are really images
4183 and turn them into proper nested links. It is meant to be used
4184 as a parse tree filter in back-ends supporting such constructs.
4186 DATA is a parse tree. INFO is the current state of the export
4187 process, as a plist.
4189 A description is a valid images if it matches any rule in RULES,
4190 if non-nil, or `org-export-default-inline-image-rule' otherwise.
4191 See `org-export-inline-image-p' for more information about the
4192 structure of RULES.
4194 Return modified DATA."
4195 (let ((link-re (format "\\`\\(?:%s\\|%s\\)\\'"
4196 org-plain-link-re
4197 org-angle-link-re))
4198 (case-fold-search t))
4199 (org-element-map data 'link
4200 (lambda (l)
4201 (let ((contents (org-element-interpret-data (org-element-contents l))))
4202 (when (and (org-string-nw-p contents)
4203 (string-match link-re contents))
4204 (let ((type (match-string 1 contents))
4205 (path (match-string 2 contents)))
4206 (when (cl-some (lambda (rule)
4207 (and (string= type (car rule))
4208 (string-match-p (cdr rule) path)))
4209 (or rules org-export-default-inline-image-rule))
4210 ;; Replace contents with image link.
4211 (org-element-adopt-elements
4212 (org-element-set-contents l nil)
4213 (with-temp-buffer
4214 (save-excursion (insert contents))
4215 (org-element-link-parser))))))))
4216 info nil nil t))
4217 data)
4219 (defun org-export-resolve-coderef (ref info)
4220 "Resolve a code reference REF.
4222 INFO is a plist used as a communication channel.
4224 Return associated line number in source code, or REF itself,
4225 depending on src-block or example element's switches. Throw an
4226 error if no block contains REF."
4227 (or (org-element-map (plist-get info :parse-tree) '(example-block src-block)
4228 (lambda (el)
4229 (with-temp-buffer
4230 (insert (org-trim (org-element-property :value el)))
4231 (let* ((label-fmt (or (org-element-property :label-fmt el)
4232 org-coderef-label-format))
4233 (ref-re (org-src-coderef-regexp label-fmt ref)))
4234 ;; Element containing REF is found. Resolve it to
4235 ;; either a label or a line number, as needed.
4236 (when (re-search-backward ref-re nil t)
4237 (if (org-element-property :use-labels el) ref
4238 (+ (or (org-export-get-loc el info) 0)
4239 (line-number-at-pos)))))))
4240 info 'first-match)
4241 (signal 'org-link-broken (list ref))))
4243 (defun org-export-search-cells (datum)
4244 "List search cells for element or object DATUM.
4246 A search cell follows the pattern (TYPE . SEARCH) where
4248 TYPE is a symbol among `headline', `custom-id', `target' and
4249 `other'.
4251 SEARCH is the string a link is expected to match. More
4252 accurately, it is
4254 - headline's title, as a list of strings, if TYPE is
4255 `headline'.
4257 - CUSTOM_ID value, as a string, if TYPE is `custom-id'.
4259 - target's or radio-target's name as a list of strings if
4260 TYPE is `target'.
4262 - NAME affiliated keyword is TYPE is `other'.
4264 A search cell is the internal representation of a fuzzy link. It
4265 ignores white spaces and statistics cookies, if applicable."
4266 (pcase (org-element-type datum)
4267 (`headline
4268 (let ((title (split-string
4269 (replace-regexp-in-string
4270 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]" ""
4271 (org-element-property :raw-value datum)))))
4272 (delq nil
4273 (list
4274 (cons 'headline title)
4275 (cons 'other title)
4276 (let ((custom-id (org-element-property :custom-id datum)))
4277 (and custom-id (cons 'custom-id custom-id)))))))
4278 (`target
4279 (list (cons 'target (split-string (org-element-property :value datum)))))
4280 ((and (let name (org-element-property :name datum))
4281 (guard name))
4282 (list (cons 'other (split-string name))))
4283 (_ nil)))
4285 (defun org-export-string-to-search-cell (s)
4286 "Return search cells associated to string S.
4287 S is either the path of a fuzzy link or a search option, i.e., it
4288 tries to match either a headline (through custom ID or title),
4289 a target or a named element."
4290 (pcase (string-to-char s)
4291 (?* (list (cons 'headline (split-string (substring s 1)))))
4292 (?# (list (cons 'custom-id (substring s 1))))
4293 ((let search (split-string s))
4294 (list (cons 'target search) (cons 'other search)))))
4296 (defun org-export-match-search-cell-p (datum cells)
4297 "Non-nil when DATUM matches search cells CELLS.
4298 DATUM is an element or object. CELLS is a list of search cells,
4299 as returned by `org-export-search-cells'."
4300 (let ((targets (org-export-search-cells datum)))
4301 (and targets (cl-some (lambda (cell) (member cell targets)) cells))))
4303 (defun org-export-resolve-fuzzy-link (link info)
4304 "Return LINK destination.
4306 INFO is a plist holding contextual information.
4308 Return value can be an object or an element:
4310 - If LINK path matches a target object (i.e. <<path>>) return it.
4312 - If LINK path exactly matches the name affiliated keyword
4313 (i.e. #+NAME: path) of an element, return that element.
4315 - If LINK path exactly matches any headline name, return that
4316 element.
4318 - Otherwise, throw an error.
4320 Assume LINK type is \"fuzzy\". White spaces are not
4321 significant."
4322 (let* ((search-cells (org-export-string-to-search-cell
4323 (org-link-unescape (org-element-property :path link))))
4324 (link-cache (or (plist-get info :resolve-fuzzy-link-cache)
4325 (let ((table (make-hash-table :test #'eq)))
4326 (plist-put info :resolve-fuzzy-link-cache table)
4327 table)))
4328 (cached (gethash search-cells link-cache 'not-found)))
4329 (if (not (eq cached 'not-found)) cached
4330 (let ((matches
4331 (org-element-map (plist-get info :parse-tree)
4332 (cons 'target org-element-all-elements)
4333 (lambda (datum)
4334 (and (org-export-match-search-cell-p datum search-cells)
4335 datum)))))
4336 (unless matches
4337 (signal 'org-link-broken (list (org-element-property :path link))))
4338 (puthash
4339 search-cells
4340 ;; There can be multiple matches for un-typed searches, i.e.,
4341 ;; for searches not starting with # or *. In this case,
4342 ;; prioritize targets and names over headline titles.
4343 ;; Matching both a name and a target is not valid, and
4344 ;; therefore undefined.
4345 (or (cl-some (lambda (datum)
4346 (and (not (eq (org-element-type datum) 'headline))
4347 datum))
4348 matches)
4349 (car matches))
4350 link-cache)))))
4352 (defun org-export-resolve-id-link (link info)
4353 "Return headline referenced as LINK destination.
4355 INFO is a plist used as a communication channel.
4357 Return value can be the headline element matched in current parse
4358 tree or a file name. Assume LINK type is either \"id\" or
4359 \"custom-id\". Throw an error if no match is found."
4360 (let ((id (org-element-property :path link)))
4361 ;; First check if id is within the current parse tree.
4362 (or (org-element-map (plist-get info :parse-tree) 'headline
4363 (lambda (headline)
4364 (when (or (equal (org-element-property :ID headline) id)
4365 (equal (org-element-property :CUSTOM_ID headline) id))
4366 headline))
4367 info 'first-match)
4368 ;; Otherwise, look for external files.
4369 (cdr (assoc id (plist-get info :id-alist)))
4370 (signal 'org-link-broken (list id)))))
4372 (defun org-export-resolve-radio-link (link info)
4373 "Return radio-target object referenced as LINK destination.
4375 INFO is a plist used as a communication channel.
4377 Return value can be a radio-target object or nil. Assume LINK
4378 has type \"radio\"."
4379 (let ((path (replace-regexp-in-string
4380 "[ \r\t\n]+" " " (org-element-property :path link))))
4381 (org-element-map (plist-get info :parse-tree) 'radio-target
4382 (lambda (radio)
4383 (and (eq (compare-strings
4384 (replace-regexp-in-string
4385 "[ \r\t\n]+" " " (org-element-property :value radio))
4386 nil nil path nil nil t)
4388 radio))
4389 info 'first-match)))
4391 (defun org-export-file-uri (filename)
4392 "Return file URI associated to FILENAME."
4393 (cond ((string-prefix-p "//" filename) (concat "file:" filename))
4394 ((not (file-name-absolute-p filename)) filename)
4395 ((org-file-remote-p filename) (concat "file:/" filename))
4397 (let ((fullname (expand-file-name filename)))
4398 (concat (if (string-prefix-p "/" fullname) "file://" "file:///")
4399 fullname)))))
4401 ;;;; For References
4403 ;; `org-export-get-reference' associate a unique reference for any
4404 ;; object or element. It uses `org-export-new-reference' and
4405 ;; `org-export-format-reference' to, respectively, generate new
4406 ;; internal references and turn them into a string suitable for
4407 ;; output.
4409 ;; `org-export-get-ordinal' associates a sequence number to any object
4410 ;; or element.
4412 (defun org-export-new-reference (references)
4413 "Return a unique reference, among REFERENCES.
4414 REFERENCES is an alist whose values are in-use references, as
4415 numbers. Returns a number, which is the internal representation
4416 of a reference. See also `org-export-format-reference'."
4417 ;; Generate random 7 digits hexadecimal numbers. Collisions
4418 ;; increase exponentially with the numbers of references. However,
4419 ;; the odds for encountering at least one collision with 1000 active
4420 ;; references in the same document are roughly 0.2%, so this
4421 ;; shouldn't be the bottleneck.
4422 (let ((new (random #x10000000)))
4423 (while (rassq new references) (setq new (random #x10000000)))
4424 new))
4426 (defun org-export-format-reference (reference)
4427 "Format REFERENCE into a string.
4428 REFERENCE is a number representing a reference, as returned by
4429 `org-export-new-reference', which see."
4430 (format "org%07x" reference))
4432 (defun org-export-get-reference (datum info)
4433 "Return a unique reference for DATUM, as a string.
4435 DATUM is either an element or an object. INFO is the current
4436 export state, as a plist.
4438 This function checks `:crossrefs' property in INFO for search
4439 cells matching DATUM before creating a new reference. Returned
4440 reference consists of alphanumeric characters only."
4441 (let ((cache (plist-get info :internal-references)))
4442 (or (car (rassq datum cache))
4443 (let* ((crossrefs (plist-get info :crossrefs))
4444 (cells (org-export-search-cells datum))
4445 ;; Preserve any pre-existing association between
4446 ;; a search cell and a reference, i.e., when some
4447 ;; previously published document referenced a location
4448 ;; within current file (see
4449 ;; `org-publish-resolve-external-link').
4451 ;; However, there is no guarantee that search cells are
4452 ;; unique, e.g., there might be duplicate custom ID or
4453 ;; two headings with the same title in the file.
4455 ;; As a consequence, before re-using any reference to
4456 ;; an element or object, we check that it doesn't refer
4457 ;; to a previous element or object.
4458 (new (or (cl-some
4459 (lambda (cell)
4460 (let ((stored (cdr (assoc cell crossrefs))))
4461 (when stored
4462 (let ((old (org-export-format-reference stored)))
4463 (and (not (assoc old cache)) stored)))))
4464 cells)
4465 (org-export-new-reference cache)))
4466 (reference-string (org-export-format-reference new)))
4467 ;; Cache contains both data already associated to
4468 ;; a reference and in-use internal references, so as to make
4469 ;; unique references.
4470 (dolist (cell cells) (push (cons cell new) cache))
4471 ;; Retain a direct association between reference string and
4472 ;; DATUM since (1) not every object or element can be given
4473 ;; a search cell (2) it permits quick lookup.
4474 (push (cons reference-string datum) cache)
4475 (plist-put info :internal-references cache)
4476 reference-string))))
4478 (defun org-export-get-ordinal (element info &optional types predicate)
4479 "Return ordinal number of an element or object.
4481 ELEMENT is the element or object considered. INFO is the plist
4482 used as a communication channel.
4484 Optional argument TYPES, when non-nil, is a list of element or
4485 object types, as symbols, that should also be counted in.
4486 Otherwise, only provided element's type is considered.
4488 Optional argument PREDICATE is a function returning a non-nil
4489 value if the current element or object should be counted in. It
4490 accepts two arguments: the element or object being considered and
4491 the plist used as a communication channel. This allows counting
4492 only a certain type of object (i.e. inline images).
4494 Return value is a list of numbers if ELEMENT is a headline or an
4495 item. It is nil for keywords. It represents the footnote number
4496 for footnote definitions and footnote references. If ELEMENT is
4497 a target, return the same value as if ELEMENT was the closest
4498 table, item or headline containing the target. In any other
4499 case, return the sequence number of ELEMENT among elements or
4500 objects of the same type."
4501 ;; Ordinal of a target object refer to the ordinal of the closest
4502 ;; table, item, or headline containing the object.
4503 (when (eq (org-element-type element) 'target)
4504 (setq element
4505 (org-element-lineage
4506 element
4507 '(footnote-definition footnote-reference headline item table))))
4508 (cl-case (org-element-type element)
4509 ;; Special case 1: A headline returns its number as a list.
4510 (headline (org-export-get-headline-number element info))
4511 ;; Special case 2: An item returns its number as a list.
4512 (item (let ((struct (org-element-property :structure element)))
4513 (org-list-get-item-number
4514 (org-element-property :begin element)
4515 struct
4516 (org-list-prevs-alist struct)
4517 (org-list-parents-alist struct))))
4518 ((footnote-definition footnote-reference)
4519 (org-export-get-footnote-number element info))
4520 (otherwise
4521 (let ((counter 0))
4522 ;; Increment counter until ELEMENT is found again.
4523 (org-element-map (plist-get info :parse-tree)
4524 (or types (org-element-type element))
4525 (lambda (el)
4526 (cond
4527 ((eq element el) (1+ counter))
4528 ((not predicate) (cl-incf counter) nil)
4529 ((funcall predicate el info) (cl-incf counter) nil)))
4530 info 'first-match)))))
4533 ;;;; For Src-Blocks
4535 ;; `org-export-get-loc' counts number of code lines accumulated in
4536 ;; src-block or example-block elements with a "+n" switch until
4537 ;; a given element, excluded. Note: "-n" switches reset that count.
4539 ;; `org-export-unravel-code' extracts source code (along with a code
4540 ;; references alist) from an `element-block' or `src-block' type
4541 ;; element.
4543 ;; `org-export-format-code' applies a formatting function to each line
4544 ;; of code, providing relative line number and code reference when
4545 ;; appropriate. Since it doesn't access the original element from
4546 ;; which the source code is coming, it expects from the code calling
4547 ;; it to know if lines should be numbered and if code references
4548 ;; should appear.
4550 ;; Eventually, `org-export-format-code-default' is a higher-level
4551 ;; function (it makes use of the two previous functions) which handles
4552 ;; line numbering and code references inclusion, and returns source
4553 ;; code in a format suitable for plain text or verbatim output.
4555 (defun org-export-get-loc (element info)
4556 "Return count of lines of code before ELEMENT.
4558 ELEMENT is an example-block or src-block element. INFO is the
4559 plist used as a communication channel.
4561 Count includes every line of code in example-block or src-block
4562 with a \"+n\" or \"-n\" switch before block. Return nil if
4563 ELEMENT doesn't allow line numbering."
4564 (pcase (org-element-property :number-lines element)
4565 (`(new . ,n) n)
4566 (`(continued . ,n)
4567 (let ((loc 0))
4568 (org-element-map (plist-get info :parse-tree) '(src-block example-block)
4569 (lambda (el)
4570 ;; ELEMENT is reached: Quit loop and return locs.
4571 (if (eq el element) (+ loc n)
4572 ;; Only count lines from src-block and example-block
4573 ;; elements with a "+n" or "-n" switch.
4574 (let ((linum (org-element-property :number-lines el)))
4575 (when linum
4576 (let ((lines (org-count-lines
4577 (org-trim (org-element-property :value el)))))
4578 ;; Accumulate locs or reset them.
4579 (pcase linum
4580 (`(new . ,n) (setq loc (+ n lines)))
4581 (`(continued . ,n) (cl-incf loc (+ n lines)))))))
4582 nil)) ;Return nil to stay in the loop.
4583 info 'first-match)))))
4585 (defun org-export-unravel-code (element)
4586 "Clean source code and extract references out of it.
4588 ELEMENT has either a `src-block' an `example-block' type.
4590 Return a cons cell whose CAR is the source code, cleaned from any
4591 reference, protective commas and spurious indentation, and CDR is
4592 an alist between relative line number (integer) and name of code
4593 reference on that line (string)."
4594 (let* ((line 0) refs
4595 (value (org-element-property :value element))
4596 ;; Get code and clean it. Remove blank lines at its
4597 ;; beginning and end.
4598 (code (replace-regexp-in-string
4599 "\\`\\([ \t]*\n\\)+" ""
4600 (replace-regexp-in-string
4601 "\\([ \t]*\n\\)*[ \t]*\\'" "\n"
4602 (if (or org-src-preserve-indentation
4603 (org-element-property :preserve-indent element))
4604 value
4605 (org-remove-indentation value)))))
4606 ;; Build a regexp matching a loc with a reference.
4607 (ref-re (org-src-coderef-regexp (org-src-coderef-format element))))
4608 ;; Return value.
4609 (cons
4610 ;; Code with references removed.
4611 (org-element-normalize-string
4612 (mapconcat
4613 (lambda (loc)
4614 (cl-incf line)
4615 (if (not (string-match ref-re loc)) loc
4616 ;; Ref line: remove ref, and signal its position in REFS.
4617 (push (cons line (match-string 3 loc)) refs)
4618 (replace-match "" nil nil loc 1)))
4619 (org-split-string code "\n") "\n"))
4620 ;; Reference alist.
4621 refs)))
4623 (defun org-export-format-code (code fun &optional num-lines ref-alist)
4624 "Format CODE by applying FUN line-wise and return it.
4626 CODE is a string representing the code to format. FUN is
4627 a function. It must accept three arguments: a line of
4628 code (string), the current line number (integer) or nil and the
4629 reference associated to the current line (string) or nil.
4631 Optional argument NUM-LINES can be an integer representing the
4632 number of code lines accumulated until the current code. Line
4633 numbers passed to FUN will take it into account. If it is nil,
4634 FUN's second argument will always be nil. This number can be
4635 obtained with `org-export-get-loc' function.
4637 Optional argument REF-ALIST can be an alist between relative line
4638 number (i.e. ignoring NUM-LINES) and the name of the code
4639 reference on it. If it is nil, FUN's third argument will always
4640 be nil. It can be obtained through the use of
4641 `org-export-unravel-code' function."
4642 (let ((--locs (org-split-string code "\n"))
4643 (--line 0))
4644 (org-element-normalize-string
4645 (mapconcat
4646 (lambda (--loc)
4647 (cl-incf --line)
4648 (let ((--ref (cdr (assq --line ref-alist))))
4649 (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
4650 --locs "\n"))))
4652 (defun org-export-format-code-default (element info)
4653 "Return source code from ELEMENT, formatted in a standard way.
4655 ELEMENT is either a `src-block' or `example-block' element. INFO
4656 is a plist used as a communication channel.
4658 This function takes care of line numbering and code references
4659 inclusion. Line numbers, when applicable, appear at the
4660 beginning of the line, separated from the code by two white
4661 spaces. Code references, on the other hand, appear flushed to
4662 the right, separated by six white spaces from the widest line of
4663 code."
4664 ;; Extract code and references.
4665 (let* ((code-info (org-export-unravel-code element))
4666 (code (car code-info))
4667 (code-lines (org-split-string code "\n")))
4668 (if (null code-lines) ""
4669 (let* ((refs (and (org-element-property :retain-labels element)
4670 (cdr code-info)))
4671 ;; Handle line numbering.
4672 (num-start (org-export-get-loc element info))
4673 (num-fmt
4674 (and num-start
4675 (format "%%%ds "
4676 (length (number-to-string
4677 (+ (length code-lines) num-start))))))
4678 ;; Prepare references display, if required. Any reference
4679 ;; should start six columns after the widest line of code,
4680 ;; wrapped with parenthesis.
4681 (max-width
4682 (+ (apply 'max (mapcar 'length code-lines))
4683 (if (not num-start) 0 (length (format num-fmt num-start))))))
4684 (org-export-format-code
4685 code
4686 (lambda (loc line-num ref)
4687 (let ((number-str (and num-fmt (format num-fmt line-num))))
4688 (concat
4689 number-str
4691 (and ref
4692 (concat (make-string
4693 (- (+ 6 max-width)
4694 (+ (length loc) (length number-str))) ? )
4695 (format "(%s)" ref))))))
4696 num-start refs)))))
4699 ;;;; For Tables
4701 ;; `org-export-table-has-special-column-p' and and
4702 ;; `org-export-table-row-is-special-p' are predicates used to look for
4703 ;; meta-information about the table structure.
4705 ;; `org-table-has-header-p' tells when the rows before the first rule
4706 ;; should be considered as table's header.
4708 ;; `org-export-table-cell-width', `org-export-table-cell-alignment'
4709 ;; and `org-export-table-cell-borders' extract information from
4710 ;; a table-cell element.
4712 ;; `org-export-table-dimensions' gives the number on rows and columns
4713 ;; in the table, ignoring horizontal rules and special columns.
4714 ;; `org-export-table-cell-address', given a table-cell object, returns
4715 ;; the absolute address of a cell. On the other hand,
4716 ;; `org-export-get-table-cell-at' does the contrary.
4718 ;; `org-export-table-cell-starts-colgroup-p',
4719 ;; `org-export-table-cell-ends-colgroup-p',
4720 ;; `org-export-table-row-starts-rowgroup-p',
4721 ;; `org-export-table-row-ends-rowgroup-p',
4722 ;; `org-export-table-row-starts-header-p',
4723 ;; `org-export-table-row-ends-header-p' and
4724 ;; `org-export-table-row-in-header-p' indicate position of current row
4725 ;; or cell within the table.
4727 (defun org-export-table-has-special-column-p (table)
4728 "Non-nil when TABLE has a special column.
4729 All special columns will be ignored during export."
4730 ;; The table has a special column when every first cell of every row
4731 ;; has an empty value or contains a symbol among "/", "#", "!", "$",
4732 ;; "*" "_" and "^". Though, do not consider a first column
4733 ;; containing only empty cells as special.
4734 (let ((special-column? 'empty))
4735 (catch 'exit
4736 (dolist (row (org-element-contents table))
4737 (when (eq (org-element-property :type row) 'standard)
4738 (let ((value (org-element-contents
4739 (car (org-element-contents row)))))
4740 (cond ((member value
4741 '(("/") ("#") ("!") ("$") ("*") ("_") ("^")))
4742 (setq special-column? 'special))
4743 ((null value))
4744 (t (throw 'exit nil))))))
4745 (eq special-column? 'special))))
4747 (defun org-export-table-has-header-p (table info)
4748 "Non-nil when TABLE has a header.
4750 INFO is a plist used as a communication channel.
4752 A table has a header when it contains at least two row groups."
4753 (let* ((cache (or (plist-get info :table-header-cache)
4754 (let ((table (make-hash-table :test #'eq)))
4755 (plist-put info :table-header-cache table)
4756 table)))
4757 (cached (gethash table cache 'no-cache)))
4758 (if (not (eq cached 'no-cache)) cached
4759 (let ((rowgroup 1) row-flag)
4760 (puthash table
4761 (org-element-map table 'table-row
4762 (lambda (row)
4763 (cond
4764 ((> rowgroup 1) t)
4765 ((and row-flag
4766 (eq (org-element-property :type row) 'rule))
4767 (cl-incf rowgroup)
4768 (setq row-flag nil))
4769 ((and (not row-flag)
4770 (eq (org-element-property :type row) 'standard))
4771 (setq row-flag t)
4772 nil)))
4773 info 'first-match)
4774 cache)))))
4776 (defun org-export-table-row-is-special-p (table-row _)
4777 "Non-nil if TABLE-ROW is considered special.
4778 All special rows will be ignored during export."
4779 (when (eq (org-element-property :type table-row) 'standard)
4780 (let ((first-cell (org-element-contents
4781 (car (org-element-contents table-row)))))
4782 ;; A row is special either when...
4784 ;; ... it starts with a field only containing "/",
4785 (equal first-cell '("/"))
4786 ;; ... the table contains a special column and the row start
4787 ;; with a marking character among, "^", "_", "$" or "!",
4788 (and (org-export-table-has-special-column-p
4789 (org-export-get-parent table-row))
4790 (member first-cell '(("^") ("_") ("$") ("!"))))
4791 ;; ... it contains only alignment cookies and empty cells.
4792 (let ((special-row-p 'empty))
4793 (catch 'exit
4794 (dolist (cell (org-element-contents table-row))
4795 (let ((value (org-element-contents cell)))
4796 ;; Since VALUE is a secondary string, the following
4797 ;; checks avoid expanding it with `org-export-data'.
4798 (cond ((not value))
4799 ((and (not (cdr value))
4800 (stringp (car value))
4801 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'"
4802 (car value)))
4803 (setq special-row-p 'cookie))
4804 (t (throw 'exit nil)))))
4805 (eq special-row-p 'cookie)))))))
4807 (defun org-export-table-row-group (table-row info)
4808 "Return TABLE-ROW's group number, as an integer.
4810 INFO is a plist used as the communication channel.
4812 Return value is the group number, as an integer, or nil for
4813 special rows and rows separators. First group is also table's
4814 header."
4815 (when (eq (org-element-property :type table-row) 'standard)
4816 (let* ((cache (or (plist-get info :table-row-group-cache)
4817 (let ((table (make-hash-table :test #'eq)))
4818 (plist-put info :table-row-group-cache table)
4819 table)))
4820 (cached (gethash table-row cache 'no-cache)))
4821 (if (not (eq cached 'no-cache)) cached
4822 ;; First time a row is queried, populate cache with all the
4823 ;; rows from the table.
4824 (let ((group 0) row-flag)
4825 (org-element-map (org-export-get-parent table-row) 'table-row
4826 (lambda (row)
4827 (if (eq (org-element-property :type row) 'rule)
4828 (setq row-flag nil)
4829 (unless row-flag (cl-incf group) (setq row-flag t))
4830 (puthash row group cache)))
4831 info))
4832 (gethash table-row cache)))))
4834 (defun org-export-table-cell-width (table-cell info)
4835 "Return TABLE-CELL contents width.
4837 INFO is a plist used as the communication channel.
4839 Return value is the width given by the last width cookie in the
4840 same column as TABLE-CELL, or nil."
4841 (let* ((row (org-export-get-parent table-cell))
4842 (table (org-export-get-parent row))
4843 (cells (org-element-contents row))
4844 (columns (length cells))
4845 (column (- columns (length (memq table-cell cells))))
4846 (cache (or (plist-get info :table-cell-width-cache)
4847 (let ((table (make-hash-table :test #'eq)))
4848 (plist-put info :table-cell-width-cache table)
4849 table)))
4850 (width-vector (or (gethash table cache)
4851 (puthash table (make-vector columns 'empty) cache)))
4852 (value (aref width-vector column)))
4853 (if (not (eq value 'empty)) value
4854 (let (cookie-width)
4855 (dolist (row (org-element-contents table)
4856 (aset width-vector column cookie-width))
4857 (when (org-export-table-row-is-special-p row info)
4858 ;; In a special row, try to find a width cookie at COLUMN.
4859 (let* ((value (org-element-contents
4860 (elt (org-element-contents row) column)))
4861 (cookie (car value)))
4862 ;; The following checks avoid expanding unnecessarily
4863 ;; the cell with `org-export-data'.
4864 (when (and value
4865 (not (cdr value))
4866 (stringp cookie)
4867 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'" cookie)
4868 (match-string 1 cookie))
4869 (setq cookie-width
4870 (string-to-number (match-string 1 cookie)))))))))))
4872 (defun org-export-table-cell-alignment (table-cell info)
4873 "Return TABLE-CELL contents alignment.
4875 INFO is a plist used as the communication channel.
4877 Return alignment as specified by the last alignment cookie in the
4878 same column as TABLE-CELL. If no such cookie is found, a default
4879 alignment value will be deduced from fraction of numbers in the
4880 column (see `org-table-number-fraction' for more information).
4881 Possible values are `left', `right' and `center'."
4882 ;; Load `org-table-number-fraction' and `org-table-number-regexp'.
4883 (require 'org-table)
4884 (let* ((row (org-export-get-parent table-cell))
4885 (table (org-export-get-parent row))
4886 (cells (org-element-contents row))
4887 (columns (length cells))
4888 (column (- columns (length (memq table-cell cells))))
4889 (cache (or (plist-get info :table-cell-alignment-cache)
4890 (let ((table (make-hash-table :test #'eq)))
4891 (plist-put info :table-cell-alignment-cache table)
4892 table)))
4893 (align-vector (or (gethash table cache)
4894 (puthash table (make-vector columns nil) cache))))
4895 (or (aref align-vector column)
4896 (let ((number-cells 0)
4897 (total-cells 0)
4898 cookie-align
4899 previous-cell-number-p)
4900 (dolist (row (org-element-contents (org-export-get-parent row)))
4901 (cond
4902 ;; In a special row, try to find an alignment cookie at
4903 ;; COLUMN.
4904 ((org-export-table-row-is-special-p row info)
4905 (let ((value (org-element-contents
4906 (elt (org-element-contents row) column))))
4907 ;; Since VALUE is a secondary string, the following
4908 ;; checks avoid useless expansion through
4909 ;; `org-export-data'.
4910 (when (and value
4911 (not (cdr value))
4912 (stringp (car value))
4913 (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'"
4914 (car value))
4915 (match-string 1 (car value)))
4916 (setq cookie-align (match-string 1 (car value))))))
4917 ;; Ignore table rules.
4918 ((eq (org-element-property :type row) 'rule))
4919 ;; In a standard row, check if cell's contents are
4920 ;; expressing some kind of number. Increase NUMBER-CELLS
4921 ;; accordingly. Though, don't bother if an alignment
4922 ;; cookie has already defined cell's alignment.
4923 ((not cookie-align)
4924 (let ((value (org-export-data
4925 (org-element-contents
4926 (elt (org-element-contents row) column))
4927 info)))
4928 (cl-incf total-cells)
4929 ;; Treat an empty cell as a number if it follows
4930 ;; a number.
4931 (if (not (or (string-match org-table-number-regexp value)
4932 (and (string= value "") previous-cell-number-p)))
4933 (setq previous-cell-number-p nil)
4934 (setq previous-cell-number-p t)
4935 (cl-incf number-cells))))))
4936 ;; Return value. Alignment specified by cookies has
4937 ;; precedence over alignment deduced from cell's contents.
4938 (aset align-vector
4939 column
4940 (cond ((equal cookie-align "l") 'left)
4941 ((equal cookie-align "r") 'right)
4942 ((equal cookie-align "c") 'center)
4943 ((>= (/ (float number-cells) total-cells)
4944 org-table-number-fraction)
4945 'right)
4946 (t 'left)))))))
4948 (defun org-export-table-cell-borders (table-cell info)
4949 "Return TABLE-CELL borders.
4951 INFO is a plist used as a communication channel.
4953 Return value is a list of symbols, or nil. Possible values are:
4954 `top', `bottom', `above', `below', `left' and `right'. Note:
4955 `top' (resp. `bottom') only happen for a cell in the first
4956 row (resp. last row) of the table, ignoring table rules, if any.
4958 Returned borders ignore special rows."
4959 (let* ((row (org-export-get-parent table-cell))
4960 (table (org-export-get-parent-table table-cell))
4961 borders)
4962 ;; Top/above border? TABLE-CELL has a border above when a rule
4963 ;; used to demarcate row groups can be found above. Hence,
4964 ;; finding a rule isn't sufficient to push `above' in BORDERS:
4965 ;; another regular row has to be found above that rule.
4966 (let (rule-flag)
4967 (catch 'exit
4968 ;; Look at every row before the current one.
4969 (dolist (row (cdr (memq row (reverse (org-element-contents table)))))
4970 (cond ((eq (org-element-property :type row) 'rule)
4971 (setq rule-flag t))
4972 ((not (org-export-table-row-is-special-p row info))
4973 (if rule-flag (throw 'exit (push 'above borders))
4974 (throw 'exit nil)))))
4975 ;; No rule above, or rule found starts the table (ignoring any
4976 ;; special row): TABLE-CELL is at the top of the table.
4977 (when rule-flag (push 'above borders))
4978 (push 'top borders)))
4979 ;; Bottom/below border? TABLE-CELL has a border below when next
4980 ;; non-regular row below is a rule.
4981 (let (rule-flag)
4982 (catch 'exit
4983 ;; Look at every row after the current one.
4984 (dolist (row (cdr (memq row (org-element-contents table))))
4985 (cond ((eq (org-element-property :type row) 'rule)
4986 (setq rule-flag t))
4987 ((not (org-export-table-row-is-special-p row info))
4988 (if rule-flag (throw 'exit (push 'below borders))
4989 (throw 'exit nil)))))
4990 ;; No rule below, or rule found ends the table (modulo some
4991 ;; special row): TABLE-CELL is at the bottom of the table.
4992 (when rule-flag (push 'below borders))
4993 (push 'bottom borders)))
4994 ;; Right/left borders? They can only be specified by column
4995 ;; groups. Column groups are defined in a row starting with "/".
4996 ;; Also a column groups row only contains "<", "<>", ">" or blank
4997 ;; cells.
4998 (catch 'exit
4999 (let ((column (let ((cells (org-element-contents row)))
5000 (- (length cells) (length (memq table-cell cells))))))
5001 ;; Table rows are read in reverse order so last column groups
5002 ;; row has precedence over any previous one.
5003 (dolist (row (reverse (org-element-contents table)))
5004 (unless (eq (org-element-property :type row) 'rule)
5005 (when (equal (org-element-contents
5006 (car (org-element-contents row)))
5007 '("/"))
5008 (let ((column-groups
5009 (mapcar
5010 (lambda (cell)
5011 (let ((value (org-element-contents cell)))
5012 (when (member value '(("<") ("<>") (">") nil))
5013 (car value))))
5014 (org-element-contents row))))
5015 ;; There's a left border when previous cell, if
5016 ;; any, ends a group, or current one starts one.
5017 (when (or (and (not (zerop column))
5018 (member (elt column-groups (1- column))
5019 '(">" "<>")))
5020 (member (elt column-groups column) '("<" "<>")))
5021 (push 'left borders))
5022 ;; There's a right border when next cell, if any,
5023 ;; starts a group, or current one ends one.
5024 (when (or (and (/= (1+ column) (length column-groups))
5025 (member (elt column-groups (1+ column))
5026 '("<" "<>")))
5027 (member (elt column-groups column) '(">" "<>")))
5028 (push 'right borders))
5029 (throw 'exit nil)))))))
5030 ;; Return value.
5031 borders))
5033 (defun org-export-table-cell-starts-colgroup-p (table-cell info)
5034 "Non-nil when TABLE-CELL is at the beginning of a column group.
5035 INFO is a plist used as a communication channel."
5036 ;; A cell starts a column group either when it is at the beginning
5037 ;; of a row (or after the special column, if any) or when it has
5038 ;; a left border.
5039 (or (eq (org-element-map (org-export-get-parent table-cell) 'table-cell
5040 'identity info 'first-match)
5041 table-cell)
5042 (memq 'left (org-export-table-cell-borders table-cell info))))
5044 (defun org-export-table-cell-ends-colgroup-p (table-cell info)
5045 "Non-nil when TABLE-CELL is at the end of a column group.
5046 INFO is a plist used as a communication channel."
5047 ;; A cell ends a column group either when it is at the end of a row
5048 ;; or when it has a right border.
5049 (or (eq (car (last (org-element-contents
5050 (org-export-get-parent table-cell))))
5051 table-cell)
5052 (memq 'right (org-export-table-cell-borders table-cell info))))
5054 (defun org-export-table-row-starts-rowgroup-p (table-row info)
5055 "Non-nil when TABLE-ROW is at the beginning of a row group.
5056 INFO is a plist used as a communication channel."
5057 (unless (or (eq (org-element-property :type table-row) 'rule)
5058 (org-export-table-row-is-special-p table-row info))
5059 (let ((borders (org-export-table-cell-borders
5060 (car (org-element-contents table-row)) info)))
5061 (or (memq 'top borders) (memq 'above borders)))))
5063 (defun org-export-table-row-ends-rowgroup-p (table-row info)
5064 "Non-nil when TABLE-ROW is at the end of a row group.
5065 INFO is a plist used as a communication channel."
5066 (unless (or (eq (org-element-property :type table-row) 'rule)
5067 (org-export-table-row-is-special-p table-row info))
5068 (let ((borders (org-export-table-cell-borders
5069 (car (org-element-contents table-row)) info)))
5070 (or (memq 'bottom borders) (memq 'below borders)))))
5072 (defun org-export-table-row-in-header-p (table-row info)
5073 "Non-nil when TABLE-ROW is located within table's header.
5074 INFO is a plist used as a communication channel. Always return
5075 nil for special rows and rows separators."
5076 (and (org-export-table-has-header-p
5077 (org-export-get-parent-table table-row) info)
5078 (eql (org-export-table-row-group table-row info) 1)))
5080 (defun org-export-table-row-starts-header-p (table-row info)
5081 "Non-nil when TABLE-ROW is the first table header's row.
5082 INFO is a plist used as a communication channel."
5083 (and (org-export-table-row-in-header-p table-row info)
5084 (org-export-table-row-starts-rowgroup-p table-row info)))
5086 (defun org-export-table-row-ends-header-p (table-row info)
5087 "Non-nil when TABLE-ROW is the last table header's row.
5088 INFO is a plist used as a communication channel."
5089 (and (org-export-table-row-in-header-p table-row info)
5090 (org-export-table-row-ends-rowgroup-p table-row info)))
5092 (defun org-export-table-row-number (table-row info)
5093 "Return TABLE-ROW number.
5094 INFO is a plist used as a communication channel. Return value is
5095 zero-indexed and ignores separators. The function returns nil
5096 for special rows and separators."
5097 (when (eq (org-element-property :type table-row) 'standard)
5098 (let* ((cache (or (plist-get info :table-row-number-cache)
5099 (let ((table (make-hash-table :test #'eq)))
5100 (plist-put info :table-row-number-cache table)
5101 table)))
5102 (cached (gethash table-row cache 'no-cache)))
5103 (if (not (eq cached 'no-cache)) cached
5104 ;; First time a row is queried, populate cache with all the
5105 ;; rows from the table.
5106 (let ((number -1))
5107 (org-element-map (org-export-get-parent-table table-row) 'table-row
5108 (lambda (row)
5109 (when (eq (org-element-property :type row) 'standard)
5110 (puthash row (cl-incf number) cache)))
5111 info))
5112 (gethash table-row cache)))))
5114 (defun org-export-table-dimensions (table info)
5115 "Return TABLE dimensions.
5117 INFO is a plist used as a communication channel.
5119 Return value is a CONS like (ROWS . COLUMNS) where
5120 ROWS (resp. COLUMNS) is the number of exportable
5121 rows (resp. columns)."
5122 (let (first-row (columns 0) (rows 0))
5123 ;; Set number of rows, and extract first one.
5124 (org-element-map table 'table-row
5125 (lambda (row)
5126 (when (eq (org-element-property :type row) 'standard)
5127 (cl-incf rows)
5128 (unless first-row (setq first-row row)))) info)
5129 ;; Set number of columns.
5130 (org-element-map first-row 'table-cell (lambda (_) (cl-incf columns)) info)
5131 ;; Return value.
5132 (cons rows columns)))
5134 (defun org-export-table-cell-address (table-cell info)
5135 "Return address of a regular TABLE-CELL object.
5137 TABLE-CELL is the cell considered. INFO is a plist used as
5138 a communication channel.
5140 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
5141 zero-based index. Only exportable cells are considered. The
5142 function returns nil for other cells."
5143 (let* ((table-row (org-export-get-parent table-cell))
5144 (row-number (org-export-table-row-number table-row info)))
5145 (when row-number
5146 (cons row-number
5147 (let ((col-count 0))
5148 (org-element-map table-row 'table-cell
5149 (lambda (cell)
5150 (if (eq cell table-cell) col-count (cl-incf col-count) nil))
5151 info 'first-match))))))
5153 (defun org-export-get-table-cell-at (address table info)
5154 "Return regular table-cell object at ADDRESS in TABLE.
5156 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
5157 zero-based index. TABLE is a table type element. INFO is
5158 a plist used as a communication channel.
5160 If no table-cell, among exportable cells, is found at ADDRESS,
5161 return nil."
5162 (let ((column-pos (cdr address)) (column-count 0))
5163 (org-element-map
5164 ;; Row at (car address) or nil.
5165 (let ((row-pos (car address)) (row-count 0))
5166 (org-element-map table 'table-row
5167 (lambda (row)
5168 (cond ((eq (org-element-property :type row) 'rule) nil)
5169 ((= row-count row-pos) row)
5170 (t (cl-incf row-count) nil)))
5171 info 'first-match))
5172 'table-cell
5173 (lambda (cell)
5174 (if (= column-count column-pos) cell
5175 (cl-incf column-count) nil))
5176 info 'first-match)))
5179 ;;;; For Tables Of Contents
5181 ;; `org-export-collect-headlines' builds a list of all exportable
5182 ;; headline elements, maybe limited to a certain depth. One can then
5183 ;; easily parse it and transcode it.
5185 ;; Building lists of tables, figures or listings is quite similar.
5186 ;; Once the generic function `org-export-collect-elements' is defined,
5187 ;; `org-export-collect-tables', `org-export-collect-figures' and
5188 ;; `org-export-collect-listings' can be derived from it.
5190 (defun org-export-collect-headlines (info &optional n scope)
5191 "Collect headlines in order to build a table of contents.
5193 INFO is a plist used as a communication channel.
5195 When optional argument N is an integer, it specifies the depth of
5196 the table of contents. Otherwise, it is set to the value of the
5197 last headline level. See `org-export-headline-levels' for more
5198 information.
5200 Optional argument SCOPE, when non-nil, is an element. If it is
5201 a headline, only children of SCOPE are collected. Otherwise,
5202 collect children of the headline containing provided element. If
5203 there is no such headline, collect all headlines. In any case,
5204 argument N becomes relative to the level of that headline.
5206 Return a list of all exportable headlines as parsed elements.
5207 Footnote sections are ignored."
5208 (let* ((scope (cond ((not scope) (plist-get info :parse-tree))
5209 ((eq (org-element-type scope) 'headline) scope)
5210 ((org-export-get-parent-headline scope))
5211 (t (plist-get info :parse-tree))))
5212 (limit (plist-get info :headline-levels))
5213 (n (if (not (wholenump n)) limit
5214 (min (if (eq (org-element-type scope) 'org-data) n
5215 (+ (org-export-get-relative-level scope info) n))
5216 limit))))
5217 (org-element-map (org-element-contents scope) 'headline
5218 (lambda (headline)
5219 (unless (org-element-property :footnote-section-p headline)
5220 (let ((level (org-export-get-relative-level headline info)))
5221 (and (<= level n) headline))))
5222 info)))
5224 (defun org-export-collect-elements (type info &optional predicate)
5225 "Collect referenceable elements of a determined type.
5227 TYPE can be a symbol or a list of symbols specifying element
5228 types to search. Only elements with a caption are collected.
5230 INFO is a plist used as a communication channel.
5232 When non-nil, optional argument PREDICATE is a function accepting
5233 one argument, an element of type TYPE. It returns a non-nil
5234 value when that element should be collected.
5236 Return a list of all elements found, in order of appearance."
5237 (org-element-map (plist-get info :parse-tree) type
5238 (lambda (element)
5239 (and (org-element-property :caption element)
5240 (or (not predicate) (funcall predicate element))
5241 element))
5242 info))
5244 (defun org-export-collect-tables (info)
5245 "Build a list of tables.
5246 INFO is a plist used as a communication channel.
5248 Return a list of table elements with a caption."
5249 (org-export-collect-elements 'table info))
5251 (defun org-export-collect-figures (info predicate)
5252 "Build a list of figures.
5254 INFO is a plist used as a communication channel. PREDICATE is
5255 a function which accepts one argument: a paragraph element and
5256 whose return value is non-nil when that element should be
5257 collected.
5259 A figure is a paragraph type element, with a caption, verifying
5260 PREDICATE. The latter has to be provided since a \"figure\" is
5261 a vague concept that may depend on back-end.
5263 Return a list of elements recognized as figures."
5264 (org-export-collect-elements 'paragraph info predicate))
5266 (defun org-export-collect-listings (info)
5267 "Build a list of src blocks.
5269 INFO is a plist used as a communication channel.
5271 Return a list of src-block elements with a caption."
5272 (org-export-collect-elements 'src-block info))
5275 ;;;; Smart Quotes
5277 ;; The main function for the smart quotes sub-system is
5278 ;; `org-export-activate-smart-quotes', which replaces every quote in
5279 ;; a given string from the parse tree with its "smart" counterpart.
5281 ;; Dictionary for smart quotes is stored in
5282 ;; `org-export-smart-quotes-alist'.
5284 (defconst org-export-smart-quotes-alist
5285 '(("ar"
5286 (primary-opening
5287 :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5288 :texinfo "@guillemetleft{}")
5289 (primary-closing
5290 :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5291 :texinfo "@guillemetright{}")
5292 (secondary-opening :utf-8 "‹" :html "&lsaquo;" :latex "\\guilsinglleft{}"
5293 :texinfo "@guilsinglleft{}")
5294 (secondary-closing :utf-8 "›" :html "&rsaquo;" :latex "\\guilsinglright{}"
5295 :texinfo "@guilsinglright{}")
5296 (apostrophe :utf-8 "’" :html "&rsquo;"))
5297 ("da"
5298 ;; one may use: »...«, "...", ›...‹, or '...'.
5299 ;; http://sproget.dk/raad-og-regler/retskrivningsregler/retskrivningsregler/a7-40-60/a7-58-anforselstegn/
5300 ;; LaTeX quotes require Babel!
5301 (primary-opening
5302 :utf-8 "»" :html "&raquo;" :latex ">>" :texinfo "@guillemetright{}")
5303 (primary-closing
5304 :utf-8 "«" :html "&laquo;" :latex "<<" :texinfo "@guillemetleft{}")
5305 (secondary-opening
5306 :utf-8 "›" :html "&rsaquo;" :latex "\\frq{}" :texinfo "@guilsinglright{}")
5307 (secondary-closing
5308 :utf-8 "‹" :html "&lsaquo;" :latex "\\flq{}" :texinfo "@guilsingleft{}")
5309 (apostrophe :utf-8 "’" :html "&rsquo;"))
5310 ("de"
5311 (primary-opening
5312 :utf-8 "„" :html "&bdquo;" :latex "\"`" :texinfo "@quotedblbase{}")
5313 (primary-closing
5314 :utf-8 "“" :html "&ldquo;" :latex "\"'" :texinfo "@quotedblleft{}")
5315 (secondary-opening
5316 :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}" :texinfo "@quotesinglbase{}")
5317 (secondary-closing
5318 :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}" :texinfo "@quoteleft{}")
5319 (apostrophe :utf-8 "’" :html "&rsquo;"))
5320 ("en"
5321 (primary-opening :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
5322 (primary-closing :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
5323 (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5324 (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5325 (apostrophe :utf-8 "’" :html "&rsquo;"))
5326 ("es"
5327 (primary-opening
5328 :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5329 :texinfo "@guillemetleft{}")
5330 (primary-closing
5331 :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5332 :texinfo "@guillemetright{}")
5333 (secondary-opening :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
5334 (secondary-closing :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
5335 (apostrophe :utf-8 "’" :html "&rsquo;"))
5336 ("fr"
5337 (primary-opening
5338 :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
5339 :texinfo "@guillemetleft{}@tie{}")
5340 (primary-closing
5341 :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
5342 :texinfo "@tie{}@guillemetright{}")
5343 (secondary-opening
5344 :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
5345 :texinfo "@guillemetleft{}@tie{}")
5346 (secondary-closing :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
5347 :texinfo "@tie{}@guillemetright{}")
5348 (apostrophe :utf-8 "’" :html "&rsquo;"))
5349 ("is"
5350 (primary-opening
5351 :utf-8 "„" :html "&bdquo;" :latex "\"`" :texinfo "@quotedblbase{}")
5352 (primary-closing
5353 :utf-8 "“" :html "&ldquo;" :latex "\"'" :texinfo "@quotedblleft{}")
5354 (secondary-opening
5355 :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}" :texinfo "@quotesinglbase{}")
5356 (secondary-closing
5357 :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}" :texinfo "@quoteleft{}")
5358 (apostrophe :utf-8 "’" :html "&rsquo;"))
5359 ("no"
5360 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5361 (primary-opening
5362 :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5363 :texinfo "@guillemetleft{}")
5364 (primary-closing
5365 :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5366 :texinfo "@guillemetright{}")
5367 (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5368 (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5369 (apostrophe :utf-8 "’" :html "&rsquo;"))
5370 ("nb"
5371 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5372 (primary-opening
5373 :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5374 :texinfo "@guillemetleft{}")
5375 (primary-closing
5376 :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5377 :texinfo "@guillemetright{}")
5378 (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5379 (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5380 (apostrophe :utf-8 "’" :html "&rsquo;"))
5381 ("nn"
5382 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5383 (primary-opening
5384 :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5385 :texinfo "@guillemetleft{}")
5386 (primary-closing
5387 :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5388 :texinfo "@guillemetright{}")
5389 (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5390 (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5391 (apostrophe :utf-8 "’" :html "&rsquo;"))
5392 ("ru"
5393 ;; 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
5394 ;; http://www.artlebedev.ru/kovodstvo/sections/104/
5395 (primary-opening :utf-8 "«" :html "&laquo;" :latex "{}<<"
5396 :texinfo "@guillemetleft{}")
5397 (primary-closing :utf-8 "»" :html "&raquo;" :latex ">>{}"
5398 :texinfo "@guillemetright{}")
5399 (secondary-opening
5400 :utf-8 "„" :html "&bdquo;" :latex "\\glqq{}" :texinfo "@quotedblbase{}")
5401 (secondary-closing
5402 :utf-8 "“" :html "&ldquo;" :latex "\\grqq{}" :texinfo "@quotedblleft{}")
5403 (apostrophe :utf-8 "’" :html: "&#39;"))
5404 ("sl"
5405 ;; Based on https://sl.wikipedia.org/wiki/Narekovaj
5406 (primary-opening :utf-8 "«" :html "&laquo;" :latex "{}<<"
5407 :texinfo "@guillemetleft{}")
5408 (primary-closing :utf-8 "»" :html "&raquo;" :latex ">>{}"
5409 :texinfo "@guillemetright{}")
5410 (secondary-opening
5411 :utf-8 "„" :html "&bdquo;" :latex "\\glqq{}" :texinfo "@quotedblbase{}")
5412 (secondary-closing
5413 :utf-8 "“" :html "&ldquo;" :latex "\\grqq{}" :texinfo "@quotedblleft{}")
5414 (apostrophe :utf-8 "’" :html "&rsquo;"))
5415 ("sv"
5416 ;; Based on https://sv.wikipedia.org/wiki/Citattecken
5417 (primary-opening :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
5418 (primary-closing :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
5419 (secondary-opening :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "`")
5420 (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "'")
5421 (apostrophe :utf-8 "’" :html "&rsquo;")))
5422 "Smart quotes translations.
5424 Alist whose CAR is a language string and CDR is an alist with
5425 quote type as key and a plist associating various encodings to
5426 their translation as value.
5428 A quote type can be any symbol among `primary-opening',
5429 `primary-closing', `secondary-opening', `secondary-closing' and
5430 `apostrophe'.
5432 Valid encodings include `:utf-8', `:html', `:latex' and
5433 `:texinfo'.
5435 If no translation is found, the quote character is left as-is.")
5437 (defun org-export--smart-quote-status (s info)
5438 "Return smart quote status at the beginning of string S.
5439 INFO is the current export state, as a plist."
5440 (let* ((parent (org-element-property :parent s))
5441 (cache (or (plist-get info :smart-quote-cache)
5442 (let ((table (make-hash-table :test #'eq)))
5443 (plist-put info :smart-quote-cache table)
5444 table)))
5445 (value (gethash parent cache 'missing-data)))
5446 (if (not (eq value 'missing-data)) (cdr (assq s value))
5447 (let (level1-open full-status)
5448 (org-element-map
5449 (let ((secondary (org-element-secondary-p s)))
5450 (if secondary (org-element-property secondary parent)
5451 (org-element-contents parent)))
5452 'plain-text
5453 (lambda (text)
5454 (let ((start 0) current-status)
5455 (while (setq start (string-match "['\"]" text start))
5456 (push
5457 (cond
5458 ((equal (match-string 0 text) "\"")
5459 (setf level1-open (not level1-open))
5460 (if level1-open 'primary-opening 'primary-closing))
5461 ;; Not already in a level 1 quote: this is an
5462 ;; apostrophe.
5463 ((not level1-open) 'apostrophe)
5464 ;; Extract previous char and next char. As
5465 ;; a special case, they can also be set to `blank',
5466 ;; `no-blank' or nil. Then determine if current
5467 ;; match is allowed as an opening quote or a closing
5468 ;; quote.
5470 (let* ((previous
5471 (if (> start 0) (substring text (1- start) start)
5472 (let ((p (org-export-get-previous-element
5473 text info)))
5474 (cond ((not p) nil)
5475 ((stringp p) (substring p -1))
5476 ((memq (org-element-property :post-blank p)
5477 '(0 nil))
5478 'no-blank)
5479 (t 'blank)))))
5480 (next
5481 (if (< (1+ start) (length text))
5482 (substring text (1+ start) (+ start 2))
5483 (let ((n (org-export-get-next-element text info)))
5484 (cond ((not n) nil)
5485 ((stringp n) (substring n 0 1))
5486 (t 'no-blank)))))
5487 (allow-open
5488 (and (if (stringp previous)
5489 (string-match "\\s\"\\|\\s-\\|\\s("
5490 previous)
5491 (memq previous '(blank nil)))
5492 (if (stringp next)
5493 (string-match "\\w\\|\\s.\\|\\s_" next)
5494 (eq next 'no-blank))))
5495 (allow-close
5496 (and (if (stringp previous)
5497 (string-match "\\w\\|\\s.\\|\\s_" previous)
5498 (eq previous 'no-blank))
5499 (if (stringp next)
5500 (string-match "\\s-\\|\\s)\\|\\s.\\|\\s\""
5501 next)
5502 (memq next '(blank nil))))))
5503 (cond
5504 ((and allow-open allow-close) (error "Should not happen"))
5505 (allow-open 'secondary-opening)
5506 (allow-close 'secondary-closing)
5507 (t 'apostrophe)))))
5508 current-status)
5509 (cl-incf start))
5510 (when current-status
5511 (push (cons text (nreverse current-status)) full-status))))
5512 info nil org-element-recursive-objects)
5513 (puthash parent full-status cache)
5514 (cdr (assq s full-status))))))
5516 (defun org-export-activate-smart-quotes (s encoding info &optional original)
5517 "Replace regular quotes with \"smart\" quotes in string S.
5519 ENCODING is a symbol among `:html', `:latex', `:texinfo' and
5520 `:utf-8'. INFO is a plist used as a communication channel.
5522 The function has to retrieve information about string
5523 surroundings in parse tree. It can only happen with an
5524 unmodified string. Thus, if S has already been through another
5525 process, a non-nil ORIGINAL optional argument will provide that
5526 original string.
5528 Return the new string."
5529 (let ((quote-status
5530 (copy-sequence (org-export--smart-quote-status (or original s) info))))
5531 (replace-regexp-in-string
5532 "['\"]"
5533 (lambda (match)
5534 (or (plist-get
5535 (cdr (assq (pop quote-status)
5536 (cdr (assoc (plist-get info :language)
5537 org-export-smart-quotes-alist))))
5538 encoding)
5539 match))
5540 s nil t)))
5542 ;;;; Topology
5544 ;; Here are various functions to retrieve information about the
5545 ;; neighborhood of a given element or object. Neighbors of interest
5546 ;; are direct parent (`org-export-get-parent'), parent headline
5547 ;; (`org-export-get-parent-headline'), first element containing an
5548 ;; object, (`org-export-get-parent-element'), parent table
5549 ;; (`org-export-get-parent-table'), previous element or object
5550 ;; (`org-export-get-previous-element') and next element or object
5551 ;; (`org-export-get-next-element').
5553 ;; defsubst org-export-get-parent must be defined before first use
5555 (defun org-export-get-parent-headline (blob)
5556 "Return BLOB parent headline or nil.
5557 BLOB is the element or object being considered."
5558 (org-element-lineage blob '(headline)))
5560 (defun org-export-get-parent-element (object)
5561 "Return first element containing OBJECT or nil.
5562 OBJECT is the object to consider."
5563 (org-element-lineage object org-element-all-elements))
5565 (defun org-export-get-parent-table (object)
5566 "Return OBJECT parent table or nil.
5567 OBJECT is either a `table-cell' or `table-element' type object."
5568 (org-element-lineage object '(table)))
5570 (defun org-export-get-previous-element (blob info &optional n)
5571 "Return previous element or object.
5573 BLOB is an element or object. INFO is a plist used as
5574 a communication channel. Return previous exportable element or
5575 object, a string, or nil.
5577 When optional argument N is a positive integer, return a list
5578 containing up to N siblings before BLOB, from farthest to
5579 closest. With any other non-nil value, return a list containing
5580 all of them."
5581 (let* ((secondary (org-element-secondary-p blob))
5582 (parent (org-export-get-parent blob))
5583 (siblings
5584 (if secondary (org-element-property secondary parent)
5585 (org-element-contents parent)))
5586 prev)
5587 (catch 'exit
5588 (dolist (obj (cdr (memq blob (reverse siblings))) prev)
5589 (cond ((memq obj (plist-get info :ignore-list)))
5590 ((null n) (throw 'exit obj))
5591 ((not (wholenump n)) (push obj prev))
5592 ((zerop n) (throw 'exit prev))
5593 (t (cl-decf n) (push obj prev)))))))
5595 (defun org-export-get-next-element (blob info &optional n)
5596 "Return next element or object.
5598 BLOB is an element or object. INFO is a plist used as
5599 a communication channel. Return next exportable element or
5600 object, a string, or nil.
5602 When optional argument N is a positive integer, return a list
5603 containing up to N siblings after BLOB, from closest to farthest.
5604 With any other non-nil value, return a list containing all of
5605 them."
5606 (let* ((secondary (org-element-secondary-p blob))
5607 (parent (org-export-get-parent blob))
5608 (siblings
5609 (cdr (memq blob
5610 (if secondary (org-element-property secondary parent)
5611 (org-element-contents parent)))))
5612 next)
5613 (catch 'exit
5614 (dolist (obj siblings (nreverse next))
5615 (cond ((memq obj (plist-get info :ignore-list)))
5616 ((null n) (throw 'exit obj))
5617 ((not (wholenump n)) (push obj next))
5618 ((zerop n) (throw 'exit (nreverse next)))
5619 (t (cl-decf n) (push obj next)))))))
5622 ;;;; Translation
5624 ;; `org-export-translate' translates a string according to the language
5625 ;; specified by the LANGUAGE keyword. `org-export-dictionary' contains
5626 ;; the dictionary used for the translation.
5628 (defconst org-export-dictionary
5629 '(("%e %n: %c"
5630 ("fr" :default "%e %n : %c" :html "%e&nbsp;%n&nbsp;: %c"))
5631 ("Author"
5632 ("ar" :default "تأليف")
5633 ("ca" :default "Autor")
5634 ("cs" :default "Autor")
5635 ("da" :default "Forfatter")
5636 ("de" :default "Autor")
5637 ("eo" :html "A&#365;toro")
5638 ("es" :default "Autor")
5639 ("et" :default "Autor")
5640 ("fi" :html "Tekij&auml;")
5641 ("fr" :default "Auteur")
5642 ("hu" :default "Szerz&otilde;")
5643 ("is" :html "H&ouml;fundur")
5644 ("it" :default "Autore")
5645 ("ja" :default "著者" :html "&#33879;&#32773;")
5646 ("nl" :default "Auteur")
5647 ("no" :default "Forfatter")
5648 ("nb" :default "Forfatter")
5649 ("nn" :default "Forfattar")
5650 ("pl" :default "Autor")
5651 ("pt_BR" :default "Autor")
5652 ("ru" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5653 ("sl" :default "Avtor")
5654 ("sv" :html "F&ouml;rfattare")
5655 ("uk" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5656 ("zh-CN" :html "&#20316;&#32773;" :utf-8 "作者")
5657 ("zh-TW" :html "&#20316;&#32773;" :utf-8 "作者"))
5658 ("Continued from previous page"
5659 ("ar" :default "تتمة الصفحة السابقة")
5660 ("de" :default "Fortsetzung von vorheriger Seite")
5661 ("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")
5662 ("fr" :default "Suite de la page précédente")
5663 ("it" :default "Continua da pagina precedente")
5664 ("ja" :default "前ページからの続き")
5665 ("nl" :default "Vervolg van vorige pagina")
5666 ("pt" :default "Continuação da página anterior")
5667 ("ru" :html "(&#1055;&#1088;&#1086;&#1076;&#1086;&#1083;&#1078;&#1077;&#1085;&#1080;&#1077;)"
5668 :utf-8 "(Продолжение)")
5669 ("sl" :default "Nadaljevanje s prejšnje strani"))
5670 ("Continued on next page"
5671 ("ar" :default "التتمة في الصفحة التالية")
5672 ("de" :default "Fortsetzung nächste Seite")
5673 ("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")
5674 ("fr" :default "Suite page suivante")
5675 ("it" :default "Continua alla pagina successiva")
5676 ("ja" :default "次ページに続く")
5677 ("nl" :default "Vervolg op volgende pagina")
5678 ("pt" :default "Continua na página seguinte")
5679 ("ru" :html "(&#1055;&#1088;&#1086;&#1076;&#1086;&#1083;&#1078;&#1077;&#1085;&#1080;&#1077; &#1089;&#1083;&#1077;&#1076;&#1091;&#1077;&#1090;)"
5680 :utf-8 "(Продолжение следует)")
5681 ("sl" :default "Nadaljevanje na naslednji strani"))
5682 ("Created"
5683 ("sl" :default "Ustvarjeno"))
5684 ("Date"
5685 ("ar" :default "بتاريخ")
5686 ("ca" :default "Data")
5687 ("cs" :default "Datum")
5688 ("da" :default "Dato")
5689 ("de" :default "Datum")
5690 ("eo" :default "Dato")
5691 ("es" :default "Fecha")
5692 ("et" :html "Kuup&#228;ev" :utf-8 "Kuupäev")
5693 ("fi" :html "P&auml;iv&auml;m&auml;&auml;r&auml;")
5694 ("hu" :html "D&aacute;tum")
5695 ("is" :default "Dagsetning")
5696 ("it" :default "Data")
5697 ("ja" :default "日付" :html "&#26085;&#20184;")
5698 ("nl" :default "Datum")
5699 ("no" :default "Dato")
5700 ("nb" :default "Dato")
5701 ("nn" :default "Dato")
5702 ("pl" :default "Data")
5703 ("pt_BR" :default "Data")
5704 ("ru" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5705 ("sl" :default "Datum")
5706 ("sv" :default "Datum")
5707 ("uk" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5708 ("zh-CN" :html "&#26085;&#26399;" :utf-8 "日期")
5709 ("zh-TW" :html "&#26085;&#26399;" :utf-8 "日期"))
5710 ("Equation"
5711 ("ar" :default "معادلة")
5712 ("da" :default "Ligning")
5713 ("de" :default "Gleichung")
5714 ("es" :ascii "Ecuacion" :html "Ecuaci&oacute;n" :default "Ecuación")
5715 ("et" :html "V&#245;rrand" :utf-8 "Võrrand")
5716 ("fr" :ascii "Equation" :default "Équation")
5717 ("is" :default "Jafna")
5718 ("ja" :default "方程式")
5719 ("no" :default "Ligning")
5720 ("nb" :default "Ligning")
5721 ("nn" :default "Likning")
5722 ("pt_BR" :html "Equa&ccedil;&atilde;o" :default "Equação" :ascii "Equacao")
5723 ("ru" :html "&#1059;&#1088;&#1072;&#1074;&#1085;&#1077;&#1085;&#1080;&#1077;"
5724 :utf-8 "Уравнение")
5725 ("sl" :default "Enačba")
5726 ("sv" :default "Ekvation")
5727 ("zh-CN" :html "&#26041;&#31243;" :utf-8 "方程"))
5728 ("Figure"
5729 ("ar" :default "شكل")
5730 ("da" :default "Figur")
5731 ("de" :default "Abbildung")
5732 ("es" :default "Figura")
5733 ("et" :default "Joonis")
5734 ("is" :default "Mynd")
5735 ("ja" :default "図" :html "&#22259;")
5736 ("no" :default "Illustrasjon")
5737 ("nb" :default "Illustrasjon")
5738 ("nn" :default "Illustrasjon")
5739 ("pt_BR" :default "Figura")
5740 ("ru" :html "&#1056;&#1080;&#1089;&#1091;&#1085;&#1086;&#1082;" :utf-8 "Рисунок")
5741 ("sv" :default "Illustration")
5742 ("zh-CN" :html "&#22270;" :utf-8 "图"))
5743 ("Figure %d:"
5744 ("ar" :default "شكل %d:")
5745 ("da" :default "Figur %d")
5746 ("de" :default "Abbildung %d:")
5747 ("es" :default "Figura %d:")
5748 ("et" :default "Joonis %d:")
5749 ("fr" :default "Figure %d :" :html "Figure&nbsp;%d&nbsp;:")
5750 ("is" :default "Mynd %d")
5751 ("ja" :default "図%d: " :html "&#22259;%d: ")
5752 ("no" :default "Illustrasjon %d")
5753 ("nb" :default "Illustrasjon %d")
5754 ("nn" :default "Illustrasjon %d")
5755 ("pt_BR" :default "Figura %d:")
5756 ("ru" :html "&#1056;&#1080;&#1089;. %d.:" :utf-8 "Рис. %d.:")
5757 ("sl" :default "Slika %d")
5758 ("sv" :default "Illustration %d")
5759 ("zh-CN" :html "&#22270;%d&nbsp;" :utf-8 "图%d "))
5760 ("Footnotes"
5761 ("ar" :default "الهوامش")
5762 ("ca" :html "Peus de p&agrave;gina")
5763 ("cs" :default "Pozn\xe1mky pod carou")
5764 ("da" :default "Fodnoter")
5765 ("de" :html "Fu&szlig;noten" :default "Fußnoten")
5766 ("eo" :default "Piednotoj")
5767 ("es" :ascii "Nota al pie de pagina" :html "Nota al pie de p&aacute;gina" :default "Nota al pie de página")
5768 ("et" :html "Allm&#228;rkused" :utf-8 "Allmärkused")
5769 ("fi" :default "Alaviitteet")
5770 ("fr" :default "Notes de bas de page")
5771 ("hu" :html "L&aacute;bjegyzet")
5772 ("is" :html "Aftanm&aacute;lsgreinar")
5773 ("it" :html "Note a pi&egrave; di pagina")
5774 ("ja" :default "脚注" :html "&#33050;&#27880;")
5775 ("nl" :default "Voetnoten")
5776 ("no" :default "Fotnoter")
5777 ("nb" :default "Fotnoter")
5778 ("nn" :default "Fotnotar")
5779 ("pl" :default "Przypis")
5780 ("pt_BR" :html "Notas de Rodap&eacute;" :default "Notas de Rodapé" :ascii "Notas de Rodape")
5781 ("ru" :html "&#1057;&#1085;&#1086;&#1089;&#1082;&#1080;" :utf-8 "Сноски")
5782 ("sl" :default "Opombe")
5783 ("sv" :default "Fotnoter")
5784 ("uk" :html "&#1055;&#1088;&#1080;&#1084;&#1110;&#1090;&#1082;&#1080;"
5785 :utf-8 "Примітки")
5786 ("zh-CN" :html "&#33050;&#27880;" :utf-8 "脚注")
5787 ("zh-TW" :html "&#33139;&#35387;" :utf-8 "腳註"))
5788 ("List of Listings"
5789 ("ar" :default "قائمة بالبرامج")
5790 ("da" :default "Programmer")
5791 ("de" :default "Programmauflistungsverzeichnis")
5792 ("es" :ascii "Indice de Listados de programas" :html "&Iacute;ndice de Listados de programas" :default "Índice de Listados de programas")
5793 ("et" :default "Loendite nimekiri")
5794 ("fr" :default "Liste des programmes")
5795 ("ja" :default "ソースコード目次")
5796 ("no" :default "Dataprogrammer")
5797 ("nb" :default "Dataprogrammer")
5798 ("ru" :html "&#1057;&#1087;&#1080;&#1089;&#1086;&#1082; &#1088;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1086;&#1082;"
5799 :utf-8 "Список распечаток")
5800 ("sl" :default "Seznam programskih izpisov")
5801 ("zh-CN" :html "&#20195;&#30721;&#30446;&#24405;" :utf-8 "代码目录"))
5802 ("List of Tables"
5803 ("ar" :default "قائمة بالجداول")
5804 ("da" :default "Tabeller")
5805 ("de" :default "Tabellenverzeichnis")
5806 ("es" :ascii "Indice de tablas" :html "&Iacute;ndice de tablas" :default "Índice de tablas")
5807 ("et" :default "Tabelite nimekiri")
5808 ("fr" :default "Liste des tableaux")
5809 ("is" :default "Töfluskrá" :html "T&ouml;fluskr&aacute;")
5810 ("ja" :default "表目次")
5811 ("no" :default "Tabeller")
5812 ("nb" :default "Tabeller")
5813 ("nn" :default "Tabeller")
5814 ("pt_BR" :default "Índice de Tabelas" :ascii "Indice de Tabelas")
5815 ("ru" :html "&#1057;&#1087;&#1080;&#1089;&#1086;&#1082; &#1090;&#1072;&#1073;&#1083;&#1080;&#1094;"
5816 :utf-8 "Список таблиц")
5817 ("sl" :default "Seznam tabel")
5818 ("sv" :default "Tabeller")
5819 ("zh-CN" :html "&#34920;&#26684;&#30446;&#24405;" :utf-8 "表格目录"))
5820 ("Listing"
5821 ("ar" :default "برنامج")
5822 ("da" :default "Program")
5823 ("de" :default "Programmlisting")
5824 ("es" :default "Listado de programa")
5825 ("et" :default "Loend")
5826 ("fr" :default "Programme" :html "Programme")
5827 ("ja" :default "ソースコード")
5828 ("no" :default "Dataprogram")
5829 ("nb" :default "Dataprogram")
5830 ("pt_BR" :default "Listagem")
5831 ("ru" :html "&#1056;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1082;&#1072;"
5832 :utf-8 "Распечатка")
5833 ("sl" :default "Izpis programa")
5834 ("zh-CN" :html "&#20195;&#30721;" :utf-8 "代码"))
5835 ("Listing %d:"
5836 ("ar" :default "برنامج %d:")
5837 ("da" :default "Program %d")
5838 ("de" :default "Programmlisting %d")
5839 ("es" :default "Listado de programa %d")
5840 ("et" :default "Loend %d")
5841 ("fr" :default "Programme %d :" :html "Programme&nbsp;%d&nbsp;:")
5842 ("ja" :default "ソースコード%d:")
5843 ("no" :default "Dataprogram %d")
5844 ("nb" :default "Dataprogram %d")
5845 ("pt_BR" :default "Listagem %d")
5846 ("ru" :html "&#1056;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1082;&#1072; %d.:"
5847 :utf-8 "Распечатка %d.:")
5848 ("sl" :default "Izpis programa %d")
5849 ("zh-CN" :html "&#20195;&#30721;%d&nbsp;" :utf-8 "代码%d "))
5850 ("References"
5851 ("ar" :default "المراجع")
5852 ("fr" :ascii "References" :default "Références")
5853 ("de" :default "Quellen")
5854 ("es" :default "Referencias")
5855 ("sl" :default "Reference"))
5856 ("See figure %s"
5857 ("fr" :default "cf. figure %s"
5858 :html "cf.&nbsp;figure&nbsp;%s" :latex "cf.~figure~%s")
5859 ("sl" :default "Glej sliko %s"))
5860 ("See listing %s"
5861 ("fr" :default "cf. programme %s"
5862 :html "cf.&nbsp;programme&nbsp;%s" :latex "cf.~programme~%s")
5863 ("sl" :default "Glej izpis programa %s"))
5864 ("See section %s"
5865 ("ar" :default "انظر قسم %s")
5866 ("da" :default "jævnfør afsnit %s")
5867 ("de" :default "siehe Abschnitt %s")
5868 ("es" :ascii "Vea seccion %s" :html "Vea secci&oacute;n %s" :default "Vea sección %s")
5869 ("et" :html "Vaata peat&#252;kki %s" :utf-8 "Vaata peatükki %s")
5870 ("fr" :default "cf. section %s")
5871 ("ja" :default "セクション %s を参照")
5872 ("pt_BR" :html "Veja a se&ccedil;&atilde;o %s" :default "Veja a seção %s"
5873 :ascii "Veja a secao %s")
5874 ("ru" :html "&#1057;&#1084;. &#1088;&#1072;&#1079;&#1076;&#1077;&#1083; %s"
5875 :utf-8 "См. раздел %s")
5876 ("sl" :default "Glej poglavje %d")
5877 ("zh-CN" :html "&#21442;&#35265;&#31532;%s&#33410;" :utf-8 "参见第%s节"))
5878 ("See table %s"
5879 ("fr" :default "cf. tableau %s"
5880 :html "cf.&nbsp;tableau&nbsp;%s" :latex "cf.~tableau~%s")
5881 ("sl" :default "Glej tabelo %s"))
5882 ("Table"
5883 ("ar" :default "جدول")
5884 ("de" :default "Tabelle")
5885 ("es" :default "Tabla")
5886 ("et" :default "Tabel")
5887 ("fr" :default "Tableau")
5888 ("is" :default "Tafla")
5889 ("ja" :default "表" :html "&#34920;")
5890 ("pt_BR" :default "Tabela")
5891 ("ru" :html "&#1058;&#1072;&#1073;&#1083;&#1080;&#1094;&#1072;"
5892 :utf-8 "Таблица")
5893 ("zh-CN" :html "&#34920;" :utf-8 "表"))
5894 ("Table %d:"
5895 ("ar" :default "جدول %d:")
5896 ("da" :default "Tabel %d")
5897 ("de" :default "Tabelle %d")
5898 ("es" :default "Tabla %d")
5899 ("et" :default "Tabel %d")
5900 ("fr" :default "Tableau %d :")
5901 ("is" :default "Tafla %d")
5902 ("ja" :default "表%d:" :html "&#34920;%d:")
5903 ("no" :default "Tabell %d")
5904 ("nb" :default "Tabell %d")
5905 ("nn" :default "Tabell %d")
5906 ("pt_BR" :default "Tabela %d")
5907 ("ru" :html "&#1058;&#1072;&#1073;&#1083;&#1080;&#1094;&#1072; %d.:"
5908 :utf-8 "Таблица %d.:")
5909 ("sl" :default "Tabela %d")
5910 ("sv" :default "Tabell %d")
5911 ("zh-CN" :html "&#34920;%d&nbsp;" :utf-8 "表%d "))
5912 ("Table of Contents"
5913 ("ar" :default "قائمة المحتويات")
5914 ("ca" :html "&Iacute;ndex")
5915 ("cs" :default "Obsah")
5916 ("da" :default "Indhold")
5917 ("de" :default "Inhaltsverzeichnis")
5918 ("eo" :default "Enhavo")
5919 ("es" :ascii "Indice" :html "&Iacute;ndice" :default "Índice")
5920 ("et" :default "Sisukord")
5921 ("fi" :html "Sis&auml;llysluettelo")
5922 ("fr" :ascii "Sommaire" :default "Table des matières")
5923 ("hu" :html "Tartalomjegyz&eacute;k")
5924 ("is" :default "Efnisyfirlit")
5925 ("it" :default "Indice")
5926 ("ja" :default "目次" :html "&#30446;&#27425;")
5927 ("nl" :default "Inhoudsopgave")
5928 ("no" :default "Innhold")
5929 ("nb" :default "Innhold")
5930 ("nn" :default "Innhald")
5931 ("pl" :html "Spis tre&#x015b;ci")
5932 ("pt_BR" :html "&Iacute;ndice" :utf8 "Índice" :ascii "Indice")
5933 ("ru" :html "&#1057;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1077;"
5934 :utf-8 "Содержание")
5935 ("sl" :default "Kazalo")
5936 ("sv" :html "Inneh&aring;ll")
5937 ("uk" :html "&#1047;&#1084;&#1110;&#1089;&#1090;" :utf-8 "Зміст")
5938 ("zh-CN" :html "&#30446;&#24405;" :utf-8 "目录")
5939 ("zh-TW" :html "&#30446;&#37636;" :utf-8 "目錄"))
5940 ("Unknown reference"
5941 ("ar" :default "مرجع غير معرّف")
5942 ("da" :default "ukendt reference")
5943 ("de" :default "Unbekannter Verweis")
5944 ("es" :default "Referencia desconocida")
5945 ("et" :default "Tundmatu viide")
5946 ("fr" :ascii "Destination inconnue" :default "Référence inconnue")
5947 ("ja" :default "不明な参照先")
5948 ("pt_BR" :default "Referência desconhecida"
5949 :ascii "Referencia desconhecida")
5950 ("ru" :html "&#1053;&#1077;&#1080;&#1079;&#1074;&#1077;&#1089;&#1090;&#1085;&#1072;&#1103; &#1089;&#1089;&#1099;&#1083;&#1082;&#1072;"
5951 :utf-8 "Неизвестная ссылка")
5952 ("sl" :default "Neznana referenca")
5953 ("zh-CN" :html "&#26410;&#30693;&#24341;&#29992;" :utf-8 "未知引用")))
5954 "Dictionary for export engine.
5956 Alist whose car is the string to translate and cdr is an alist
5957 whose car is the language string and cdr is a plist whose
5958 properties are possible charsets and values translated terms.
5960 It is used as a database for `org-export-translate'. Since this
5961 function returns the string as-is if no translation was found,
5962 the variable only needs to record values different from the
5963 entry.")
5965 (defun org-export-translate (s encoding info)
5966 "Translate string S according to language specification.
5968 ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1'
5969 and `:utf-8'. INFO is a plist used as a communication channel.
5971 Translation depends on `:language' property. Return the
5972 translated string. If no translation is found, try to fall back
5973 to `:default' encoding. If it fails, return S."
5974 (let* ((lang (plist-get info :language))
5975 (translations (cdr (assoc lang
5976 (cdr (assoc s org-export-dictionary))))))
5977 (or (plist-get translations encoding)
5978 (plist-get translations :default)
5979 s)))
5983 ;;; Asynchronous Export
5985 ;; `org-export-async-start' is the entry point for asynchronous
5986 ;; export. It recreates current buffer (including visibility,
5987 ;; narrowing and visited file) in an external Emacs process, and
5988 ;; evaluates a command there. It then applies a function on the
5989 ;; returned results in the current process.
5991 ;; At a higher level, `org-export-to-buffer' and `org-export-to-file'
5992 ;; allow exporting to a buffer or a file, asynchronously or not.
5994 ;; `org-export-output-file-name' is an auxiliary function meant to be
5995 ;; used with `org-export-to-file'. With a given extension, it tries
5996 ;; to provide a canonical file name to write export output to.
5998 ;; Asynchronously generated results are never displayed directly.
5999 ;; Instead, they are stored in `org-export-stack-contents'. They can
6000 ;; then be retrieved by calling `org-export-stack'.
6002 ;; Export Stack is viewed through a dedicated major mode
6003 ;;`org-export-stack-mode' and tools: `org-export-stack-refresh',
6004 ;;`org-export-stack-delete', `org-export-stack-view' and
6005 ;;`org-export-stack-clear'.
6007 ;; For back-ends, `org-export-add-to-stack' add a new source to stack.
6008 ;; It should be used whenever `org-export-async-start' is called.
6010 (defmacro org-export-async-start (fun &rest body)
6011 "Call function FUN on the results returned by BODY evaluation.
6013 FUN is an anonymous function of one argument. BODY evaluation
6014 happens in an asynchronous process, from a buffer which is an
6015 exact copy of the current one.
6017 Use `org-export-add-to-stack' in FUN in order to register results
6018 in the stack.
6020 This is a low level function. See also `org-export-to-buffer'
6021 and `org-export-to-file' for more specialized functions."
6022 (declare (indent 1) (debug t))
6023 (org-with-gensyms (process temp-file copy-fun proc-buffer coding)
6024 ;; Write the full sexp evaluating BODY in a copy of the current
6025 ;; buffer to a temporary file, as it may be too long for program
6026 ;; args in `start-process'.
6027 `(with-temp-message "Initializing asynchronous export process"
6028 (let ((,copy-fun (org-export--generate-copy-script (current-buffer)))
6029 (,temp-file (make-temp-file "org-export-process"))
6030 (,coding buffer-file-coding-system))
6031 (with-temp-file ,temp-file
6032 (insert
6033 ;; Null characters (from variable values) are inserted
6034 ;; within the file. As a consequence, coding system for
6035 ;; buffer contents will not be recognized properly. So,
6036 ;; we make sure it is the same as the one used to display
6037 ;; the original buffer.
6038 (format ";; -*- coding: %s; -*-\n%S"
6039 ,coding
6040 `(with-temp-buffer
6041 (when org-export-async-debug '(setq debug-on-error t))
6042 ;; Ignore `kill-emacs-hook' and code evaluation
6043 ;; queries from Babel as we need a truly
6044 ;; non-interactive process.
6045 (setq kill-emacs-hook nil
6046 org-babel-confirm-evaluate-answer-no t)
6047 ;; Initialize export framework.
6048 (require 'ox)
6049 ;; Re-create current buffer there.
6050 (funcall ,,copy-fun)
6051 (restore-buffer-modified-p nil)
6052 ;; Sexp to evaluate in the buffer.
6053 (print (progn ,,@body))))))
6054 ;; Start external process.
6055 (let* ((process-connection-type nil)
6056 (,proc-buffer (generate-new-buffer-name "*Org Export Process*"))
6057 (,process
6058 (apply
6059 #'start-process
6060 (append
6061 (list "org-export-process"
6062 ,proc-buffer
6063 (expand-file-name invocation-name invocation-directory)
6064 "--batch")
6065 (if org-export-async-init-file
6066 (list "-Q" "-l" org-export-async-init-file)
6067 (list "-l" user-init-file))
6068 (list "-l" ,temp-file)))))
6069 ;; Register running process in stack.
6070 (org-export-add-to-stack (get-buffer ,proc-buffer) nil ,process)
6071 ;; Set-up sentinel in order to catch results.
6072 (let ((handler ,fun))
6073 (set-process-sentinel
6074 ,process
6075 `(lambda (p status)
6076 (let ((proc-buffer (process-buffer p)))
6077 (when (eq (process-status p) 'exit)
6078 (unwind-protect
6079 (if (zerop (process-exit-status p))
6080 (unwind-protect
6081 (let ((results
6082 (with-current-buffer proc-buffer
6083 (goto-char (point-max))
6084 (backward-sexp)
6085 (read (current-buffer)))))
6086 (funcall ,handler results))
6087 (unless org-export-async-debug
6088 (and (get-buffer proc-buffer)
6089 (kill-buffer proc-buffer))))
6090 (org-export-add-to-stack proc-buffer nil p)
6091 (ding)
6092 (message "Process `%s' exited abnormally" p))
6093 (unless org-export-async-debug
6094 (delete-file ,,temp-file)))))))))))))
6096 ;;;###autoload
6097 (defun org-export-to-buffer
6098 (backend buffer
6099 &optional async subtreep visible-only body-only ext-plist
6100 post-process)
6101 "Call `org-export-as' with output to a specified buffer.
6103 BACKEND is either an export back-end, as returned by, e.g.,
6104 `org-export-create-backend', or a symbol referring to
6105 a registered back-end.
6107 BUFFER is the name of the output buffer. If it already exists,
6108 it will be erased first, otherwise, it will be created.
6110 A non-nil optional argument ASYNC means the process should happen
6111 asynchronously. The resulting buffer should then be accessible
6112 through the `org-export-stack' interface. When ASYNC is nil, the
6113 buffer is displayed if `org-export-show-temporary-export-buffer'
6114 is non-nil.
6116 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
6117 EXT-PLIST are similar to those used in `org-export-as', which
6118 see.
6120 Optional argument POST-PROCESS is a function which should accept
6121 no argument. It is always called within the current process,
6122 from BUFFER, with point at its beginning. Export back-ends can
6123 use it to set a major mode there, e.g,
6125 (defun org-latex-export-as-latex
6126 (&optional async subtreep visible-only body-only ext-plist)
6127 (interactive)
6128 (org-export-to-buffer \\='latex \"*Org LATEX Export*\"
6129 async subtreep visible-only body-only ext-plist (lambda () (LaTeX-mode))))
6131 This function returns BUFFER."
6132 (declare (indent 2))
6133 (if async
6134 (org-export-async-start
6135 `(lambda (output)
6136 (with-current-buffer (get-buffer-create ,buffer)
6137 (erase-buffer)
6138 (setq buffer-file-coding-system ',buffer-file-coding-system)
6139 (insert output)
6140 (goto-char (point-min))
6141 (org-export-add-to-stack (current-buffer) ',backend)
6142 (ignore-errors (funcall ,post-process))))
6143 `(org-export-as
6144 ',backend ,subtreep ,visible-only ,body-only ',ext-plist))
6145 (let ((output
6146 (org-export-as backend subtreep visible-only body-only ext-plist))
6147 (buffer (get-buffer-create buffer))
6148 (encoding buffer-file-coding-system))
6149 (when (and (org-string-nw-p output) (org-export--copy-to-kill-ring-p))
6150 (org-kill-new output))
6151 (with-current-buffer buffer
6152 (erase-buffer)
6153 (setq buffer-file-coding-system encoding)
6154 (insert output)
6155 (goto-char (point-min))
6156 (and (functionp post-process) (funcall post-process)))
6157 (when org-export-show-temporary-export-buffer
6158 (switch-to-buffer-other-window buffer))
6159 buffer)))
6161 ;;;###autoload
6162 (defun org-export-to-file
6163 (backend file &optional async subtreep visible-only body-only ext-plist
6164 post-process)
6165 "Call `org-export-as' with output to a specified file.
6167 BACKEND is either an export back-end, as returned by, e.g.,
6168 `org-export-create-backend', or a symbol referring to
6169 a registered back-end. FILE is the name of the output file, as
6170 a string.
6172 A non-nil optional argument ASYNC means the process should happen
6173 asynchronously. The resulting buffer will then be accessible
6174 through the `org-export-stack' interface.
6176 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
6177 EXT-PLIST are similar to those used in `org-export-as', which
6178 see.
6180 Optional argument POST-PROCESS is called with FILE as its
6181 argument and happens asynchronously when ASYNC is non-nil. It
6182 has to return a file name, or nil. Export back-ends can use this
6183 to send the output file through additional processing, e.g,
6185 (defun org-latex-export-to-latex
6186 (&optional async subtreep visible-only body-only ext-plist)
6187 (interactive)
6188 (let ((outfile (org-export-output-file-name \".tex\" subtreep)))
6189 (org-export-to-file \\='latex outfile
6190 async subtreep visible-only body-only ext-plist
6191 (lambda (file) (org-latex-compile file)))
6193 The function returns either a file name returned by POST-PROCESS,
6194 or FILE."
6195 (declare (indent 2))
6196 (if (not (file-writable-p file)) (error "Output file not writable")
6197 (let ((ext-plist (org-combine-plists `(:output-file ,file) ext-plist))
6198 (encoding (or org-export-coding-system buffer-file-coding-system)))
6199 (if async
6200 (org-export-async-start
6201 `(lambda (file)
6202 (org-export-add-to-stack (expand-file-name file) ',backend))
6203 `(let ((output
6204 (org-export-as
6205 ',backend ,subtreep ,visible-only ,body-only
6206 ',ext-plist)))
6207 (with-temp-buffer
6208 (insert output)
6209 (let ((coding-system-for-write ',encoding))
6210 (write-file ,file)))
6211 (or (ignore-errors (funcall ',post-process ,file)) ,file)))
6212 (let ((output (org-export-as
6213 backend subtreep visible-only body-only ext-plist)))
6214 (with-temp-buffer
6215 (insert output)
6216 (let ((coding-system-for-write encoding))
6217 (write-file file)))
6218 (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p output))
6219 (org-kill-new output))
6220 ;; Get proper return value.
6221 (or (and (functionp post-process) (funcall post-process file))
6222 file))))))
6224 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
6225 "Return output file's name according to buffer specifications.
6227 EXTENSION is a string representing the output file extension,
6228 with the leading dot.
6230 With a non-nil optional argument SUBTREEP, try to determine
6231 output file's name by looking for \"EXPORT_FILE_NAME\" property
6232 of subtree at point.
6234 When optional argument PUB-DIR is set, use it as the publishing
6235 directory.
6237 Return file name as a string."
6238 (let* ((visited-file (buffer-file-name (buffer-base-buffer)))
6239 (base-name
6240 (concat
6241 (file-name-sans-extension
6243 ;; Check EXPORT_FILE_NAME subtree property.
6244 (and subtreep (org-entry-get nil "EXPORT_FILE_NAME" 'selective))
6245 ;; Check #+EXPORT_FILE_NAME keyword.
6246 (org-with-point-at (point-min)
6247 (catch :found
6248 (let ((case-fold-search t))
6249 (while (re-search-forward
6250 "^[ \t]*#\\+EXPORT_FILE_NAME:[ \t]+\\S-" nil t)
6251 (let ((element (org-element-at-point)))
6252 (when (eq 'keyword (org-element-type element))
6253 (throw :found
6254 (org-element-property :value element))))))))
6255 ;; Extract from buffer's associated file, if any.
6256 (and visited-file (file-name-nondirectory visited-file))
6257 ;; Can't determine file name on our own: ask user.
6258 (read-file-name
6259 "Output file: " pub-dir nil nil nil
6260 (lambda (n) (string= extension (file-name-extension n t))))))
6261 extension))
6262 (output-file
6263 ;; Build file name. Enforce EXTENSION over whatever user
6264 ;; may have come up with. PUB-DIR, if defined, always has
6265 ;; precedence over any provided path.
6266 (cond
6267 (pub-dir (concat (file-name-as-directory pub-dir)
6268 (file-name-nondirectory base-name)))
6269 ((file-name-absolute-p base-name) base-name)
6270 (t base-name))))
6271 ;; If writing to OUTPUT-FILE would overwrite original file, append
6272 ;; EXTENSION another time to final name.
6273 (if (and visited-file (file-equal-p visited-file output-file))
6274 (concat output-file extension)
6275 output-file)))
6277 (defun org-export-add-to-stack (source backend &optional process)
6278 "Add a new result to export stack if not present already.
6280 SOURCE is a buffer or a file name containing export results.
6281 BACKEND is a symbol representing export back-end used to generate
6284 Entries already pointing to SOURCE and unavailable entries are
6285 removed beforehand. Return the new stack."
6286 (setq org-export-stack-contents
6287 (cons (list source backend (or process (current-time)))
6288 (org-export-stack-remove source))))
6290 (defun org-export-stack ()
6291 "Menu for asynchronous export results and running processes."
6292 (interactive)
6293 (let ((buffer (get-buffer-create "*Org Export Stack*")))
6294 (with-current-buffer buffer
6295 (org-export-stack-mode)
6296 (tabulated-list-print t))
6297 (pop-to-buffer buffer))
6298 (message "Type \"q\" to quit, \"?\" for help"))
6300 (defun org-export-stack-clear ()
6301 "Remove all entries from export stack."
6302 (interactive)
6303 (setq org-export-stack-contents nil))
6305 (defun org-export-stack-refresh ()
6306 "Refresh the export stack."
6307 (interactive)
6308 (tabulated-list-print t))
6310 (defun org-export-stack-remove (&optional source)
6311 "Remove export results at point from stack.
6312 If optional argument SOURCE is non-nil, remove it instead."
6313 (interactive)
6314 (let ((source (or source (org-export--stack-source-at-point))))
6315 (setq org-export-stack-contents
6316 (cl-remove-if (lambda (el) (equal (car el) source))
6317 org-export-stack-contents))))
6319 (defun org-export-stack-view (&optional in-emacs)
6320 "View export results at point in stack.
6321 With an optional prefix argument IN-EMACS, force viewing files
6322 within Emacs."
6323 (interactive "P")
6324 (let ((source (org-export--stack-source-at-point)))
6325 (cond ((processp source)
6326 (org-switch-to-buffer-other-window (process-buffer source)))
6327 ((bufferp source) (org-switch-to-buffer-other-window source))
6328 (t (org-open-file source in-emacs)))))
6330 (defvar org-export-stack-mode-map
6331 (let ((km (make-sparse-keymap)))
6332 (set-keymap-parent km tabulated-list-mode-map)
6333 (define-key km " " 'next-line)
6334 (define-key km "\C-n" 'next-line)
6335 (define-key km [down] 'next-line)
6336 (define-key km "\C-p" 'previous-line)
6337 (define-key km "\C-?" 'previous-line)
6338 (define-key km [up] 'previous-line)
6339 (define-key km "C" 'org-export-stack-clear)
6340 (define-key km "v" 'org-export-stack-view)
6341 (define-key km (kbd "RET") 'org-export-stack-view)
6342 (define-key km "d" 'org-export-stack-remove)
6344 "Keymap for Org Export Stack.")
6346 (define-derived-mode org-export-stack-mode tabulated-list-mode "Org-Stack"
6347 "Mode for displaying asynchronous export stack.
6349 Type `\\[org-export-stack]' to visualize the asynchronous export
6350 stack.
6352 In an Org Export Stack buffer, use \
6353 \\<org-export-stack-mode-map>`\\[org-export-stack-view]' to view export output
6354 on current line, `\\[org-export-stack-remove]' to remove it from the stack and \
6355 `\\[org-export-stack-clear]' to clear
6356 stack completely.
6358 Removing entries in a stack buffer does not affect files
6359 or buffers, only display.
6361 \\{org-export-stack-mode-map}"
6362 (setq tabulated-list-format
6363 (vector (list "#" 4 #'org-export--stack-num-predicate)
6364 (list "Back-End" 12 t)
6365 (list "Age" 6 nil)
6366 (list "Source" 0 nil)))
6367 (setq tabulated-list-sort-key (cons "#" nil))
6368 (setq tabulated-list-entries #'org-export--stack-generate)
6369 (add-hook 'tabulated-list-revert-hook #'org-export--stack-generate nil t)
6370 (add-hook 'post-command-hook #'org-export-stack-refresh nil t)
6371 (tabulated-list-init-header))
6373 (defun org-export--stack-generate ()
6374 "Generate the asynchronous export stack for display.
6375 Unavailable sources are removed from the list. Return a list
6376 appropriate for `tabulated-list-print'."
6377 ;; Clear stack from exited processes, dead buffers or non-existent
6378 ;; files.
6379 (setq org-export-stack-contents
6380 (cl-remove-if-not
6381 (lambda (el)
6382 (if (processp (nth 2 el))
6383 (buffer-live-p (process-buffer (nth 2 el)))
6384 (let ((source (car el)))
6385 (if (bufferp source) (buffer-live-p source)
6386 (file-exists-p source)))))
6387 org-export-stack-contents))
6388 ;; Update `tabulated-list-entries'.
6389 (let ((counter 0))
6390 (mapcar
6391 (lambda (entry)
6392 (let ((source (car entry)))
6393 (list source
6394 (vector
6395 ;; Counter.
6396 (number-to-string (cl-incf counter))
6397 ;; Back-End.
6398 (if (nth 1 entry) (symbol-name (nth 1 entry)) "")
6399 ;; Age.
6400 (let ((info (nth 2 entry)))
6401 (if (processp info) (symbol-name (process-status info))
6402 (format-seconds "%h:%.2m" (float-time (time-since info)))))
6403 ;; Source.
6404 (if (stringp source) source (buffer-name source))))))
6405 org-export-stack-contents)))
6407 (defun org-export--stack-num-predicate (a b)
6408 (< (string-to-number (aref (nth 1 a) 0))
6409 (string-to-number (aref (nth 1 b) 0))))
6411 (defun org-export--stack-source-at-point ()
6412 "Return source from export results at point in stack."
6413 (let ((source (car (nth (1- (org-current-line)) org-export-stack-contents))))
6414 (if (not source) (error "Source unavailable, please refresh buffer")
6415 (let ((source-name (if (stringp source) source (buffer-name source))))
6416 (if (save-excursion
6417 (beginning-of-line)
6418 (looking-at-p (concat ".* +" (regexp-quote source-name) "$")))
6419 source
6420 ;; SOURCE is not consistent with current line. The stack
6421 ;; view is outdated.
6422 (error (substitute-command-keys
6423 "Source unavailable; type `\\[org-export-stack-refresh]' \
6424 to refresh buffer")))))))
6428 ;;; The Dispatcher
6430 ;; `org-export-dispatch' is the standard interactive way to start an
6431 ;; export process. It uses `org-export--dispatch-ui' as a subroutine
6432 ;; for its interface, which, in turn, delegates response to key
6433 ;; pressed to `org-export--dispatch-action'.
6435 ;;;###autoload
6436 (defun org-export-dispatch (&optional arg)
6437 "Export dispatcher for Org mode.
6439 It provides an access to common export related tasks in a buffer.
6440 Its interface comes in two flavors: standard and expert.
6442 While both share the same set of bindings, only the former
6443 displays the valid keys associations in a dedicated buffer.
6444 Scrolling (resp. line-wise motion) in this buffer is done with
6445 SPC and DEL (resp. C-n and C-p) keys.
6447 Set variable `org-export-dispatch-use-expert-ui' to switch to one
6448 flavor or the other.
6450 When ARG is `\\[universal-argument]', repeat the last export action, with the\
6451 same
6452 set of options used back then, on the current buffer.
6454 When ARG is `\\[universal-argument] \\[universal-argument]', display the \
6455 asynchronous export stack."
6456 (interactive "P")
6457 (let* ((input
6458 (cond ((equal arg '(16)) '(stack))
6459 ((and arg org-export-dispatch-last-action))
6460 (t (save-window-excursion
6461 (unwind-protect
6462 (progn
6463 ;; Remember where we are
6464 (move-marker org-export-dispatch-last-position
6465 (point)
6466 (org-base-buffer (current-buffer)))
6467 ;; Get and store an export command
6468 (setq org-export-dispatch-last-action
6469 (org-export--dispatch-ui
6470 (list org-export-initial-scope
6471 (and org-export-in-background 'async))
6473 org-export-dispatch-use-expert-ui)))
6474 (and (get-buffer "*Org Export Dispatcher*")
6475 (kill-buffer "*Org Export Dispatcher*")))))))
6476 (action (car input))
6477 (optns (cdr input)))
6478 (unless (memq 'subtree optns)
6479 (move-marker org-export-dispatch-last-position nil))
6480 (cl-case action
6481 ;; First handle special hard-coded actions.
6482 (template (org-export-insert-default-template nil optns))
6483 (stack (org-export-stack))
6484 (publish-current-file
6485 (org-publish-current-file (memq 'force optns) (memq 'async optns)))
6486 (publish-current-project
6487 (org-publish-current-project (memq 'force optns) (memq 'async optns)))
6488 (publish-choose-project
6489 (org-publish (assoc (completing-read
6490 "Publish project: "
6491 org-publish-project-alist nil t)
6492 org-publish-project-alist)
6493 (memq 'force optns)
6494 (memq 'async optns)))
6495 (publish-all (org-publish-all (memq 'force optns) (memq 'async optns)))
6496 (otherwise
6497 (save-excursion
6498 (when arg
6499 ;; Repeating command, maybe move cursor to restore subtree
6500 ;; context.
6501 (if (eq (marker-buffer org-export-dispatch-last-position)
6502 (org-base-buffer (current-buffer)))
6503 (goto-char org-export-dispatch-last-position)
6504 ;; We are in a different buffer, forget position.
6505 (move-marker org-export-dispatch-last-position nil)))
6506 (funcall action
6507 ;; Return a symbol instead of a list to ease
6508 ;; asynchronous export macro use.
6509 (and (memq 'async optns) t)
6510 (and (memq 'subtree optns) t)
6511 (and (memq 'visible optns) t)
6512 (and (memq 'body optns) t)))))))
6514 (defun org-export--dispatch-ui (options first-key expertp)
6515 "Handle interface for `org-export-dispatch'.
6517 OPTIONS is a list containing current interactive options set for
6518 export. It can contain any of the following symbols:
6519 `body' toggles a body-only export
6520 `subtree' restricts export to current subtree
6521 `visible' restricts export to visible part of buffer.
6522 `force' force publishing files.
6523 `async' use asynchronous export process
6525 FIRST-KEY is the key pressed to select the first level menu. It
6526 is nil when this menu hasn't been selected yet.
6528 EXPERTP, when non-nil, triggers expert UI. In that case, no help
6529 buffer is provided, but indications about currently active
6530 options are given in the prompt. Moreover, [?] allows switching
6531 back to standard interface."
6532 (let* ((fontify-key
6533 (lambda (key &optional access-key)
6534 ;; Fontify KEY string. Optional argument ACCESS-KEY, when
6535 ;; non-nil is the required first-level key to activate
6536 ;; KEY. When its value is t, activate KEY independently
6537 ;; on the first key, if any. A nil value means KEY will
6538 ;; only be activated at first level.
6539 (if (or (eq access-key t) (eq access-key first-key))
6540 (propertize key 'face 'org-warning)
6541 key)))
6542 (fontify-value
6543 (lambda (value)
6544 ;; Fontify VALUE string.
6545 (propertize value 'face 'font-lock-variable-name-face)))
6546 ;; Prepare menu entries by extracting them from registered
6547 ;; back-ends and sorting them by access key and by ordinal,
6548 ;; if any.
6549 (entries
6550 (sort (sort (delq nil
6551 (mapcar #'org-export-backend-menu
6552 org-export-registered-backends))
6553 (lambda (a b)
6554 (let ((key-a (nth 1 a))
6555 (key-b (nth 1 b)))
6556 (cond ((and (numberp key-a) (numberp key-b))
6557 (< key-a key-b))
6558 ((numberp key-b) t)))))
6559 'car-less-than-car))
6560 ;; Compute a list of allowed keys based on the first key
6561 ;; pressed, if any. Some keys
6562 ;; (?^B, ?^V, ?^S, ?^F, ?^A, ?&, ?# and ?q) are always
6563 ;; available.
6564 (allowed-keys
6565 (nconc (list 2 22 19 6 1)
6566 (if (not first-key) (org-uniquify (mapcar 'car entries))
6567 (let (sub-menu)
6568 (dolist (entry entries (sort (mapcar 'car sub-menu) '<))
6569 (when (eq (car entry) first-key)
6570 (setq sub-menu (append (nth 2 entry) sub-menu))))))
6571 (cond ((eq first-key ?P) (list ?f ?p ?x ?a))
6572 ((not first-key) (list ?P)))
6573 (list ?& ?#)
6574 (when expertp (list ??))
6575 (list ?q)))
6576 ;; Build the help menu for standard UI.
6577 (help
6578 (unless expertp
6579 (concat
6580 ;; Options are hard-coded.
6581 (format "[%s] Body only: %s [%s] Visible only: %s
6582 \[%s] Export scope: %s [%s] Force publishing: %s
6583 \[%s] Async export: %s\n\n"
6584 (funcall fontify-key "C-b" t)
6585 (funcall fontify-value
6586 (if (memq 'body options) "On " "Off"))
6587 (funcall fontify-key "C-v" t)
6588 (funcall fontify-value
6589 (if (memq 'visible options) "On " "Off"))
6590 (funcall fontify-key "C-s" t)
6591 (funcall fontify-value
6592 (if (memq 'subtree options) "Subtree" "Buffer "))
6593 (funcall fontify-key "C-f" t)
6594 (funcall fontify-value
6595 (if (memq 'force options) "On " "Off"))
6596 (funcall fontify-key "C-a" t)
6597 (funcall fontify-value
6598 (if (memq 'async options) "On " "Off")))
6599 ;; Display registered back-end entries. When a key
6600 ;; appears for the second time, do not create another
6601 ;; entry, but append its sub-menu to existing menu.
6602 (let (last-key)
6603 (mapconcat
6604 (lambda (entry)
6605 (let ((top-key (car entry)))
6606 (concat
6607 (unless (eq top-key last-key)
6608 (setq last-key top-key)
6609 (format "\n[%s] %s\n"
6610 (funcall fontify-key (char-to-string top-key))
6611 (nth 1 entry)))
6612 (let ((sub-menu (nth 2 entry)))
6613 (unless (functionp sub-menu)
6614 ;; Split sub-menu into two columns.
6615 (let ((index -1))
6616 (concat
6617 (mapconcat
6618 (lambda (sub-entry)
6619 (cl-incf index)
6620 (format
6621 (if (zerop (mod index 2)) " [%s] %-26s"
6622 "[%s] %s\n")
6623 (funcall fontify-key
6624 (char-to-string (car sub-entry))
6625 top-key)
6626 (nth 1 sub-entry)))
6627 sub-menu "")
6628 (when (zerop (mod index 2)) "\n"))))))))
6629 entries ""))
6630 ;; Publishing menu is hard-coded.
6631 (format "\n[%s] Publish
6632 [%s] Current file [%s] Current project
6633 [%s] Choose project [%s] All projects\n\n\n"
6634 (funcall fontify-key "P")
6635 (funcall fontify-key "f" ?P)
6636 (funcall fontify-key "p" ?P)
6637 (funcall fontify-key "x" ?P)
6638 (funcall fontify-key "a" ?P))
6639 (format "[%s] Export stack [%s] Insert template\n"
6640 (funcall fontify-key "&" t)
6641 (funcall fontify-key "#" t))
6642 (format "[%s] %s"
6643 (funcall fontify-key "q" t)
6644 (if first-key "Main menu" "Exit")))))
6645 ;; Build prompts for both standard and expert UI.
6646 (standard-prompt (unless expertp "Export command: "))
6647 (expert-prompt
6648 (when expertp
6649 (format
6650 "Export command (C-%s%s%s%s%s) [%s]: "
6651 (if (memq 'body options) (funcall fontify-key "b" t) "b")
6652 (if (memq 'visible options) (funcall fontify-key "v" t) "v")
6653 (if (memq 'subtree options) (funcall fontify-key "s" t) "s")
6654 (if (memq 'force options) (funcall fontify-key "f" t) "f")
6655 (if (memq 'async options) (funcall fontify-key "a" t) "a")
6656 (mapconcat (lambda (k)
6657 ;; Strip control characters.
6658 (unless (< k 27) (char-to-string k)))
6659 allowed-keys "")))))
6660 ;; With expert UI, just read key with a fancy prompt. In standard
6661 ;; UI, display an intrusive help buffer.
6662 (if expertp
6663 (org-export--dispatch-action
6664 expert-prompt allowed-keys entries options first-key expertp)
6665 ;; At first call, create frame layout in order to display menu.
6666 (unless (get-buffer "*Org Export Dispatcher*")
6667 (delete-other-windows)
6668 (org-switch-to-buffer-other-window
6669 (get-buffer-create "*Org Export Dispatcher*"))
6670 (setq cursor-type nil
6671 header-line-format "Use SPC, DEL, C-n or C-p to navigate.")
6672 ;; Make sure that invisible cursor will not highlight square
6673 ;; brackets.
6674 (set-syntax-table (copy-syntax-table))
6675 (modify-syntax-entry ?\[ "w"))
6676 ;; At this point, the buffer containing the menu exists and is
6677 ;; visible in the current window. So, refresh it.
6678 (with-current-buffer "*Org Export Dispatcher*"
6679 ;; Refresh help. Maintain display continuity by re-visiting
6680 ;; previous window position.
6681 (let ((pos (window-start)))
6682 (erase-buffer)
6683 (insert help)
6684 (set-window-start nil pos)))
6685 (org-fit-window-to-buffer)
6686 (org-export--dispatch-action
6687 standard-prompt allowed-keys entries options first-key expertp))))
6689 (defun org-export--dispatch-action
6690 (prompt allowed-keys entries options first-key expertp)
6691 "Read a character from command input and act accordingly.
6693 PROMPT is the displayed prompt, as a string. ALLOWED-KEYS is
6694 a list of characters available at a given step in the process.
6695 ENTRIES is a list of menu entries. OPTIONS, FIRST-KEY and
6696 EXPERTP are the same as defined in `org-export--dispatch-ui',
6697 which see.
6699 Toggle export options when required. Otherwise, return value is
6700 a list with action as CAR and a list of interactive export
6701 options as CDR."
6702 (let (key)
6703 ;; Scrolling: when in non-expert mode, act on motion keys (C-n,
6704 ;; C-p, SPC, DEL).
6705 (while (and (setq key (read-char-exclusive prompt))
6706 (not expertp)
6707 (memq key '(14 16 ?\s ?\d)))
6708 (cl-case key
6709 (14 (if (not (pos-visible-in-window-p (point-max)))
6710 (ignore-errors (scroll-up 1))
6711 (message "End of buffer")
6712 (sit-for 1)))
6713 (16 (if (not (pos-visible-in-window-p (point-min)))
6714 (ignore-errors (scroll-down 1))
6715 (message "Beginning of buffer")
6716 (sit-for 1)))
6717 (?\s (if (not (pos-visible-in-window-p (point-max)))
6718 (scroll-up nil)
6719 (message "End of buffer")
6720 (sit-for 1)))
6721 (?\d (if (not (pos-visible-in-window-p (point-min)))
6722 (scroll-down nil)
6723 (message "Beginning of buffer")
6724 (sit-for 1)))))
6725 (cond
6726 ;; Ignore undefined associations.
6727 ((not (memq key allowed-keys))
6728 (ding)
6729 (unless expertp (message "Invalid key") (sit-for 1))
6730 (org-export--dispatch-ui options first-key expertp))
6731 ;; q key at first level aborts export. At second level, cancel
6732 ;; first key instead.
6733 ((eq key ?q) (if (not first-key) (error "Export aborted")
6734 (org-export--dispatch-ui options nil expertp)))
6735 ;; Help key: Switch back to standard interface if expert UI was
6736 ;; active.
6737 ((eq key ??) (org-export--dispatch-ui options first-key nil))
6738 ;; Send request for template insertion along with export scope.
6739 ((eq key ?#) (cons 'template (memq 'subtree options)))
6740 ;; Switch to asynchronous export stack.
6741 ((eq key ?&) '(stack))
6742 ;; Toggle options: C-b (2) C-v (22) C-s (19) C-f (6) C-a (1).
6743 ((memq key '(2 22 19 6 1))
6744 (org-export--dispatch-ui
6745 (let ((option (cl-case key (2 'body) (22 'visible) (19 'subtree)
6746 (6 'force) (1 'async))))
6747 (if (memq option options) (remq option options)
6748 (cons option options)))
6749 first-key expertp))
6750 ;; Action selected: Send key and options back to
6751 ;; `org-export-dispatch'.
6752 ((or first-key (functionp (nth 2 (assq key entries))))
6753 (cons (cond
6754 ((not first-key) (nth 2 (assq key entries)))
6755 ;; Publishing actions are hard-coded. Send a special
6756 ;; signal to `org-export-dispatch'.
6757 ((eq first-key ?P)
6758 (cl-case key
6759 (?f 'publish-current-file)
6760 (?p 'publish-current-project)
6761 (?x 'publish-choose-project)
6762 (?a 'publish-all)))
6763 ;; Return first action associated to FIRST-KEY + KEY
6764 ;; path. Indeed, derived backends can share the same
6765 ;; FIRST-KEY.
6766 (t (catch 'found
6767 (dolist (entry (member (assq first-key entries) entries))
6768 (let ((match (assq key (nth 2 entry))))
6769 (when match (throw 'found (nth 2 match))))))))
6770 options))
6771 ;; Otherwise, enter sub-menu.
6772 (t (org-export--dispatch-ui options key expertp)))))
6776 (provide 'ox)
6778 ;; Local variables:
6779 ;; generated-autoload-file: "org-loaddefs.el"
6780 ;; End:
6782 ;;; ox.el ends here