ox: Speed-up some tools on tables
[org-mode/org-tableheadings.git] / lisp / ox.el
blobf4b046e9682d14aecd4bdd99e234cd5d4a2e47bb
1 ;;; ox.el --- Export Framework for Org Mode -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2012-2016 Free Software Foundation, Inc.
5 ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
6 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;; This library implements a generic export engine for Org, built on
26 ;; its syntactical parser: Org Elements.
28 ;; Besides that parser, the generic exporter is made of three distinct
29 ;; parts:
31 ;; - The communication channel consists of a property list, which is
32 ;; created and updated during the process. Its use is to offer
33 ;; every piece of information, would it be about initial environment
34 ;; or contextual data, all in a single place.
36 ;; - The transcoder walks the parse tree, ignores or treat as plain
37 ;; text elements and objects according to export options, and
38 ;; eventually calls back-end specific functions to do the real
39 ;; transcoding, concatenating their return value along the way.
41 ;; - The filter system is activated at the very beginning and the very
42 ;; end of the export process, and each time an element or an object
43 ;; has been converted. It is the entry point to fine-tune standard
44 ;; output from back-end transcoders. See "The Filter System"
45 ;; section for more information.
47 ;; The core functions is `org-export-as'. It returns the transcoded
48 ;; buffer as a string. Its derivatives are `org-export-to-buffer' and
49 ;; `org-export-to-file'.
51 ;; An export back-end is defined with `org-export-define-backend'.
52 ;; This function can also support specific buffer keywords, OPTION
53 ;; keyword's items and filters. Refer to function's documentation for
54 ;; more information.
56 ;; If the new back-end shares most properties with another one,
57 ;; `org-export-define-derived-backend' can be used to simplify the
58 ;; process.
60 ;; Any back-end can define its own variables. Among them, those
61 ;; customizable should belong to the `org-export-BACKEND' group.
63 ;; Tools for common tasks across back-ends are implemented in the
64 ;; following part of the file.
66 ;; Eventually, a dispatcher (`org-export-dispatch') is provided in the
67 ;; last one.
69 ;; See <http://orgmode.org/worg/dev/org-export-reference.html> for
70 ;; more information.
72 ;;; Code:
74 (require 'cl-lib)
75 (require 'ob-exp)
76 (require 'org-element)
77 (require 'org-macro)
78 (require 'tabulated-list)
80 (declare-function org-publish "ox-publish" (project &optional force async))
81 (declare-function org-publish-all "ox-publish" (&optional force async))
82 (declare-function org-publish-current-file "ox-publish" (&optional force async))
83 (declare-function org-publish-current-project "ox-publish" (&optional force async))
84 (declare-function org-src-coderef-format "org-src" (&optional element))
85 (declare-function org-src-coderef-regexp "org-src" (fmt &optional label))
87 (defvar org-publish-project-alist)
88 (defvar org-table-number-fraction)
89 (defvar org-table-number-regexp)
92 ;;; Internal Variables
94 ;; Among internal variables, the most important is
95 ;; `org-export-options-alist'. This variable define the global export
96 ;; options, shared between every exporter, and how they are acquired.
98 (defconst org-export-max-depth 19
99 "Maximum nesting depth for headlines, counting from 0.")
101 (defconst org-export-options-alist
102 '((:title "TITLE" nil nil parse)
103 (:date "DATE" nil nil parse)
104 (:author "AUTHOR" nil user-full-name parse)
105 (:email "EMAIL" nil user-mail-address t)
106 (:language "LANGUAGE" nil org-export-default-language t)
107 (:select-tags "SELECT_TAGS" nil org-export-select-tags split)
108 (:exclude-tags "EXCLUDE_TAGS" nil org-export-exclude-tags split)
109 (:creator "CREATOR" nil org-export-creator-string)
110 (:headline-levels nil "H" org-export-headline-levels)
111 (:preserve-breaks nil "\\n" org-export-preserve-breaks)
112 (:section-numbers nil "num" org-export-with-section-numbers)
113 (:time-stamp-file nil "timestamp" org-export-time-stamp-file)
114 (:with-archived-trees nil "arch" org-export-with-archived-trees)
115 (:with-author nil "author" org-export-with-author)
116 (:with-broken-links nil "broken-links" org-export-with-broken-links)
117 (:with-clocks nil "c" org-export-with-clocks)
118 (:with-creator nil "creator" org-export-with-creator)
119 (:with-date nil "date" org-export-with-date)
120 (:with-drawers nil "d" org-export-with-drawers)
121 (:with-email nil "email" org-export-with-email)
122 (:with-emphasize nil "*" org-export-with-emphasize)
123 (:with-entities nil "e" org-export-with-entities)
124 (:with-fixed-width nil ":" org-export-with-fixed-width)
125 (:with-footnotes nil "f" org-export-with-footnotes)
126 (:with-inlinetasks nil "inline" org-export-with-inlinetasks)
127 (:with-latex nil "tex" org-export-with-latex)
128 (:with-planning nil "p" org-export-with-planning)
129 (:with-priority nil "pri" org-export-with-priority)
130 (:with-properties nil "prop" org-export-with-properties)
131 (:with-smart-quotes nil "'" org-export-with-smart-quotes)
132 (:with-special-strings nil "-" org-export-with-special-strings)
133 (:with-statistics-cookies nil "stat" org-export-with-statistics-cookies)
134 (:with-sub-superscript nil "^" org-export-with-sub-superscripts)
135 (:with-toc nil "toc" org-export-with-toc)
136 (:with-tables nil "|" org-export-with-tables)
137 (:with-tags nil "tags" org-export-with-tags)
138 (:with-tasks nil "tasks" org-export-with-tasks)
139 (:with-timestamps nil "<" org-export-with-timestamps)
140 (:with-title nil "title" org-export-with-title)
141 (:with-todo-keywords nil "todo" org-export-with-todo-keywords))
142 "Alist between export properties and ways to set them.
144 The key of the alist is the property name, and the value is a list
145 like (KEYWORD OPTION DEFAULT BEHAVIOR) where:
147 KEYWORD is a string representing a buffer keyword, or nil. Each
148 property defined this way can also be set, during subtree
149 export, through a headline property named after the keyword
150 with the \"EXPORT_\" prefix (i.e. DATE keyword and EXPORT_DATE
151 property).
152 OPTION is a string that could be found in an #+OPTIONS: line.
153 DEFAULT is the default value for the property.
154 BEHAVIOR determines how Org should handle multiple keywords for
155 the same property. It is a symbol among:
156 nil Keep old value and discard the new one.
157 t Replace old value with the new one.
158 `space' Concatenate the values, separating them with a space.
159 `newline' Concatenate the values, separating them with
160 a newline.
161 `split' Split values at white spaces, and cons them to the
162 previous list.
163 `parse' Parse value as a list of strings and Org objects,
164 which can then be transcoded with, e.g.,
165 `org-export-data'. It implies `space' behavior.
167 Values set through KEYWORD and OPTION have precedence over
168 DEFAULT.
170 All these properties should be back-end agnostic. Back-end
171 specific properties are set through `org-export-define-backend'.
172 Properties redefined there have precedence over these.")
174 (defconst org-export-special-keywords '("FILETAGS" "SETUPFILE" "OPTIONS")
175 "List of in-buffer keywords that require special treatment.
176 These keywords are not directly associated to a property. The
177 way they are handled must be hard-coded into
178 `org-export--get-inbuffer-options' function.")
180 (defconst org-export-filters-alist
181 '((:filter-body . org-export-filter-body-functions)
182 (:filter-bold . org-export-filter-bold-functions)
183 (:filter-babel-call . org-export-filter-babel-call-functions)
184 (:filter-center-block . org-export-filter-center-block-functions)
185 (:filter-clock . org-export-filter-clock-functions)
186 (:filter-code . org-export-filter-code-functions)
187 (:filter-diary-sexp . org-export-filter-diary-sexp-functions)
188 (:filter-drawer . org-export-filter-drawer-functions)
189 (:filter-dynamic-block . org-export-filter-dynamic-block-functions)
190 (:filter-entity . org-export-filter-entity-functions)
191 (:filter-example-block . org-export-filter-example-block-functions)
192 (:filter-export-block . org-export-filter-export-block-functions)
193 (:filter-export-snippet . org-export-filter-export-snippet-functions)
194 (:filter-final-output . org-export-filter-final-output-functions)
195 (:filter-fixed-width . org-export-filter-fixed-width-functions)
196 (:filter-footnote-definition . org-export-filter-footnote-definition-functions)
197 (:filter-footnote-reference . org-export-filter-footnote-reference-functions)
198 (:filter-headline . org-export-filter-headline-functions)
199 (:filter-horizontal-rule . org-export-filter-horizontal-rule-functions)
200 (:filter-inline-babel-call . org-export-filter-inline-babel-call-functions)
201 (:filter-inline-src-block . org-export-filter-inline-src-block-functions)
202 (:filter-inlinetask . org-export-filter-inlinetask-functions)
203 (:filter-italic . org-export-filter-italic-functions)
204 (:filter-item . org-export-filter-item-functions)
205 (:filter-keyword . org-export-filter-keyword-functions)
206 (:filter-latex-environment . org-export-filter-latex-environment-functions)
207 (:filter-latex-fragment . org-export-filter-latex-fragment-functions)
208 (:filter-line-break . org-export-filter-line-break-functions)
209 (:filter-link . org-export-filter-link-functions)
210 (:filter-node-property . org-export-filter-node-property-functions)
211 (:filter-options . org-export-filter-options-functions)
212 (:filter-paragraph . org-export-filter-paragraph-functions)
213 (:filter-parse-tree . org-export-filter-parse-tree-functions)
214 (:filter-plain-list . org-export-filter-plain-list-functions)
215 (:filter-plain-text . org-export-filter-plain-text-functions)
216 (:filter-planning . org-export-filter-planning-functions)
217 (:filter-property-drawer . org-export-filter-property-drawer-functions)
218 (:filter-quote-block . org-export-filter-quote-block-functions)
219 (:filter-radio-target . org-export-filter-radio-target-functions)
220 (:filter-section . org-export-filter-section-functions)
221 (:filter-special-block . org-export-filter-special-block-functions)
222 (:filter-src-block . org-export-filter-src-block-functions)
223 (:filter-statistics-cookie . org-export-filter-statistics-cookie-functions)
224 (:filter-strike-through . org-export-filter-strike-through-functions)
225 (:filter-subscript . org-export-filter-subscript-functions)
226 (:filter-superscript . org-export-filter-superscript-functions)
227 (:filter-table . org-export-filter-table-functions)
228 (:filter-table-cell . org-export-filter-table-cell-functions)
229 (:filter-table-row . org-export-filter-table-row-functions)
230 (:filter-target . org-export-filter-target-functions)
231 (:filter-timestamp . org-export-filter-timestamp-functions)
232 (:filter-underline . org-export-filter-underline-functions)
233 (:filter-verbatim . org-export-filter-verbatim-functions)
234 (:filter-verse-block . org-export-filter-verse-block-functions))
235 "Alist between filters properties and initial values.
237 The key of each association is a property name accessible through
238 the communication channel. Its value is a configurable global
239 variable defining initial filters.
241 This list is meant to install user specified filters. Back-end
242 developers may install their own filters using
243 `org-export-define-backend'. Filters defined there will always
244 be prepended to the current list, so they always get applied
245 first.")
247 (defconst org-export-default-inline-image-rule
248 `(("file" .
249 ,(format "\\.%s\\'"
250 (regexp-opt
251 '("png" "jpeg" "jpg" "gif" "tiff" "tif" "xbm"
252 "xpm" "pbm" "pgm" "ppm") t))))
253 "Default rule for link matching an inline image.
254 This rule applies to links with no description. By default, it
255 will be considered as an inline image if it targets a local file
256 whose extension is either \"png\", \"jpeg\", \"jpg\", \"gif\",
257 \"tiff\", \"tif\", \"xbm\", \"xpm\", \"pbm\", \"pgm\" or \"ppm\".
258 See `org-export-inline-image-p' for more information about
259 rules.")
261 (defconst org-export-ignored-local-variables
262 '(org-font-lock-keywords
263 org-element--cache org-element--cache-objects org-element--cache-sync-keys
264 org-element--cache-sync-requests org-element--cache-sync-timer)
265 "List of variables not copied through upon buffer duplication.
266 Export process takes place on a copy of the original buffer.
267 When this copy is created, all Org related local variables not in
268 this list are copied to the new buffer. Variables with an
269 unreadable value are also ignored.")
271 (defvar org-export-async-debug nil
272 "Non-nil means asynchronous export process should leave data behind.
274 This data is found in the appropriate \"*Org Export Process*\"
275 buffer, and in files prefixed with \"org-export-process\" and
276 located in `temporary-file-directory'.
278 When non-nil, it will also set `debug-on-error' to a non-nil
279 value in the external process.")
281 (defvar org-export-stack-contents nil
282 "Record asynchronously generated export results and processes.
283 This is an alist: its CAR is the source of the
284 result (destination file or buffer for a finished process,
285 original buffer for a running one) and its CDR is a list
286 containing the back-end used, as a symbol, and either a process
287 or the time at which it finished. It is used to build the menu
288 from `org-export-stack'.")
290 (defvar org-export-registered-backends nil
291 "List of backends currently available in the exporter.
292 This variable is set with `org-export-define-backend' and
293 `org-export-define-derived-backend' functions.")
295 (defvar org-export-dispatch-last-action nil
296 "Last command called from the dispatcher.
297 The value should be a list. Its CAR is the action, as a symbol,
298 and its CDR is a list of export options.")
300 (defvar org-export-dispatch-last-position (make-marker)
301 "The position where the last export command was created using the dispatcher.
302 This marker will be used with `C-u C-c C-e' to make sure export repetition
303 uses the same subtree if the previous command was restricted to a subtree.")
305 ;; For compatibility with Org < 8
306 (defvar org-export-current-backend nil
307 "Name, if any, of the back-end used during an export process.
309 Its value is a symbol such as `html', `latex', `ascii', or nil if
310 the back-end is anonymous (see `org-export-create-backend') or if
311 there is no export process in progress.
313 It can be used to teach Babel blocks how to act differently
314 according to the back-end used.")
318 ;;; User-configurable Variables
320 ;; Configuration for the masses.
322 ;; They should never be accessed directly, as their value is to be
323 ;; stored in a property list (cf. `org-export-options-alist').
324 ;; Back-ends will read their value from there instead.
326 (defgroup org-export nil
327 "Options for exporting Org mode files."
328 :tag "Org Export"
329 :group 'org)
331 (defgroup org-export-general nil
332 "General options for export engine."
333 :tag "Org Export General"
334 :group 'org-export)
336 (defcustom org-export-with-archived-trees 'headline
337 "Whether sub-trees with the ARCHIVE tag should be exported.
339 This can have three different values:
340 nil Do not export, pretend this tree is not present.
341 t Do export the entire tree.
342 `headline' Only export the headline, but skip the tree below it.
344 This option can also be set with the OPTIONS keyword,
345 e.g. \"arch:nil\"."
346 :group 'org-export-general
347 :type '(choice
348 (const :tag "Not at all" nil)
349 (const :tag "Headline only" headline)
350 (const :tag "Entirely" t))
351 :safe (lambda (x) (memq x '(t nil headline))))
353 (defcustom org-export-with-author t
354 "Non-nil means insert author name into the exported file.
355 This option can also be set with the OPTIONS keyword,
356 e.g. \"author:nil\"."
357 :group 'org-export-general
358 :type 'boolean
359 :safe #'booleanp)
361 (defcustom org-export-with-clocks nil
362 "Non-nil means export CLOCK keywords.
363 This option can also be set with the OPTIONS keyword,
364 e.g. \"c:t\"."
365 :group 'org-export-general
366 :type 'boolean
367 :safe #'booleanp)
369 (defcustom org-export-with-creator nil
370 "Non-nil means the postamble should contain a creator sentence.
372 The sentence can be set in `org-export-creator-string', which
373 see.
375 This option can also be set with the OPTIONS keyword, e.g.,
376 \"creator:t\"."
377 :group 'org-export-general
378 :version "25.2"
379 :package-version '(Org . "8.3")
380 :type 'boolean
381 :safe #'booleanp)
383 (defcustom org-export-with-date t
384 "Non-nil means insert date in the exported document.
385 This option can also be set with the OPTIONS keyword,
386 e.g. \"date:nil\"."
387 :group 'org-export-general
388 :type 'boolean
389 :safe #'booleanp)
391 (defcustom org-export-date-timestamp-format nil
392 "Time-stamp format string to use for DATE keyword.
394 The format string, when specified, only applies if date consists
395 in a single time-stamp. Otherwise its value will be ignored.
397 See `format-time-string' for details on how to build this
398 string."
399 :group 'org-export-general
400 :type '(choice
401 (string :tag "Time-stamp format string")
402 (const :tag "No format string" nil))
403 :safe (lambda (x) (or (null x) (stringp x))))
405 (defcustom org-export-creator-string
406 (format "Emacs %s (Org mode %s)"
407 emacs-version
408 (if (fboundp 'org-version) (org-version) "unknown version"))
409 "Information about the creator of the document.
410 This option can also be set on with the CREATOR keyword."
411 :group 'org-export-general
412 :type '(string :tag "Creator string")
413 :safe #'stringp)
415 (defcustom org-export-with-drawers '(not "LOGBOOK")
416 "Non-nil means export contents of standard drawers.
418 When t, all drawers are exported. This may also be a list of
419 drawer names to export, as strings. If that list starts with
420 `not', only drawers with such names will be ignored.
422 This variable doesn't apply to properties drawers. See
423 `org-export-with-properties' instead.
425 This option can also be set with the OPTIONS keyword,
426 e.g. \"d:nil\"."
427 :group 'org-export-general
428 :version "24.4"
429 :package-version '(Org . "8.0")
430 :type '(choice
431 (const :tag "All drawers" t)
432 (const :tag "None" nil)
433 (repeat :tag "Selected drawers"
434 (string :tag "Drawer name"))
435 (list :tag "Ignored drawers"
436 (const :format "" not)
437 (repeat :tag "Specify names of drawers to ignore during export"
438 :inline t
439 (string :tag "Drawer name"))))
440 :safe (lambda (x) (or (booleanp x)
441 (and (listp x)
442 (or (cl-every #'stringp x)
443 (and (eq (nth 0 x) 'not)
444 (cl-every #'stringp (cdr x))))))))
446 (defcustom org-export-with-email nil
447 "Non-nil means insert author email into the exported file.
448 This option can also be set with the OPTIONS keyword,
449 e.g. \"email:t\"."
450 :group 'org-export-general
451 :type 'boolean
452 :safe #'booleanp)
454 (defcustom org-export-with-emphasize t
455 "Non-nil means interpret *word*, /word/, _word_ and +word+.
457 If the export target supports emphasizing text, the word will be
458 typeset in bold, italic, with an underline or strike-through,
459 respectively.
461 This option can also be set with the OPTIONS keyword,
462 e.g. \"*:nil\"."
463 :group 'org-export-general
464 :type 'boolean
465 :safe #'booleanp)
467 (defcustom org-export-exclude-tags '("noexport")
468 "Tags that exclude a tree from export.
470 All trees carrying any of these tags will be excluded from
471 export. This is without condition, so even subtrees inside that
472 carry one of the `org-export-select-tags' will be removed.
474 This option can also be set with the EXCLUDE_TAGS keyword."
475 :group 'org-export-general
476 :type '(repeat (string :tag "Tag"))
477 :safe (lambda (x) (and (listp x) (cl-every #'stringp x))))
479 (defcustom org-export-with-fixed-width t
480 "Non-nil means export lines starting with \":\".
481 This option can also be set with the OPTIONS keyword,
482 e.g. \"::nil\"."
483 :group 'org-export-general
484 :version "24.4"
485 :package-version '(Org . "8.0")
486 :type 'boolean
487 :safe #'booleanp)
489 (defcustom org-export-with-footnotes t
490 "Non-nil means Org footnotes should be exported.
491 This option can also be set with the OPTIONS keyword,
492 e.g. \"f:nil\"."
493 :group 'org-export-general
494 :type 'boolean
495 :safe #'booleanp)
497 (defcustom org-export-with-latex t
498 "Non-nil means process LaTeX environments and fragments.
500 This option can also be set with the OPTIONS line,
501 e.g. \"tex:verbatim\". Allowed values are:
503 nil Ignore math snippets.
504 `verbatim' Keep everything in verbatim.
505 t Allow export of math snippets."
506 :group 'org-export-general
507 :version "24.4"
508 :package-version '(Org . "8.0")
509 :type '(choice
510 (const :tag "Do not process math in any way" nil)
511 (const :tag "Interpret math snippets" t)
512 (const :tag "Leave math verbatim" verbatim))
513 :safe (lambda (x) (memq x '(t nil verbatim))))
515 (defcustom org-export-headline-levels 3
516 "The last level which is still exported as a headline.
518 Inferior levels will usually produce itemize or enumerate lists
519 when exported, but back-end behavior may differ.
521 This option can also be set with the OPTIONS keyword,
522 e.g. \"H:2\"."
523 :group 'org-export-general
524 :type 'integer
525 :safe #'integerp)
527 (defcustom org-export-default-language "en"
528 "The default language for export and clocktable translations, as a string.
529 This may have an association in
530 `org-clock-clocktable-language-setup',
531 `org-export-smart-quotes-alist' and `org-export-dictionary'.
532 This option can also be set with the LANGUAGE keyword."
533 :group 'org-export-general
534 :type '(string :tag "Language")
535 :safe #'stringp)
537 (defcustom org-export-preserve-breaks nil
538 "Non-nil means preserve all line breaks when exporting.
539 This option can also be set with the OPTIONS keyword,
540 e.g. \"\\n:t\"."
541 :group 'org-export-general
542 :type 'boolean
543 :safe #'booleanp)
545 (defcustom org-export-with-entities t
546 "Non-nil means interpret entities when exporting.
548 For example, HTML export converts \\alpha to &alpha; and \\AA to
549 &Aring;.
551 For a list of supported names, see the constant `org-entities'
552 and the user option `org-entities-user'.
554 This option can also be set with the OPTIONS keyword,
555 e.g. \"e:nil\"."
556 :group 'org-export-general
557 :type 'boolean
558 :safe #'booleanp)
560 (defcustom org-export-with-inlinetasks t
561 "Non-nil means inlinetasks should be exported.
562 This option can also be set with the OPTIONS keyword,
563 e.g. \"inline:nil\"."
564 :group 'org-export-general
565 :version "24.4"
566 :package-version '(Org . "8.0")
567 :type 'boolean
568 :safe #'booleanp)
570 (defcustom org-export-with-planning nil
571 "Non-nil means include planning info in export.
573 Planning info is the line containing either SCHEDULED:,
574 DEADLINE:, CLOSED: time-stamps, or a combination of them.
576 This option can also be set with the OPTIONS keyword,
577 e.g. \"p:t\"."
578 :group 'org-export-general
579 :version "24.4"
580 :package-version '(Org . "8.0")
581 :type 'boolean
582 :safe #'booleanp)
584 (defcustom org-export-with-priority nil
585 "Non-nil means include priority cookies in export.
586 This option can also be set with the OPTIONS keyword,
587 e.g. \"pri:t\"."
588 :group 'org-export-general
589 :type 'boolean
590 :safe #'booleanp)
592 (defcustom org-export-with-properties nil
593 "Non-nil means export contents of properties drawers.
595 When t, all properties are exported. This may also be a list of
596 properties to export, as strings.
598 This option can also be set with the OPTIONS keyword,
599 e.g. \"prop:t\"."
600 :group 'org-export-general
601 :version "24.4"
602 :package-version '(Org . "8.3")
603 :type '(choice
604 (const :tag "All properties" t)
605 (const :tag "None" nil)
606 (repeat :tag "Selected properties"
607 (string :tag "Property name")))
608 :safe (lambda (x) (or (booleanp x)
609 (and (listp x) (cl-every #'stringp x)))))
611 (defcustom org-export-with-section-numbers t
612 "Non-nil means add section numbers to headlines when exporting.
614 When set to an integer n, numbering will only happen for
615 headlines whose relative level is higher or equal to n.
617 This option can also be set with the OPTIONS keyword,
618 e.g. \"num:t\"."
619 :group 'org-export-general
620 :type 'boolean
621 :safe #'booleanp)
623 (defcustom org-export-select-tags '("export")
624 "Tags that select a tree for export.
626 If any such tag is found in a buffer, all trees that do not carry
627 one of these tags will be ignored during export. Inside trees
628 that are selected like this, you can still deselect a subtree by
629 tagging it with one of the `org-export-exclude-tags'.
631 This option can also be set with the SELECT_TAGS keyword."
632 :group 'org-export-general
633 :type '(repeat (string :tag "Tag"))
634 :safe (lambda (x) (and (listp x) (cl-every #'stringp x))))
636 (defcustom org-export-with-smart-quotes nil
637 "Non-nil means activate smart quotes during export.
638 This option can also be set with the OPTIONS keyword,
639 e.g., \"':t\".
641 When setting this to non-nil, you need to take care of
642 using the correct Babel package when exporting to LaTeX.
643 E.g., you can load Babel for french like this:
645 #+LATEX_HEADER: \\usepackage[french]{babel}"
646 :group 'org-export-general
647 :version "24.4"
648 :package-version '(Org . "8.0")
649 :type 'boolean
650 :safe #'booleanp)
652 (defcustom org-export-with-special-strings t
653 "Non-nil means interpret \"\\-\", \"--\" and \"---\" for export.
655 When this option is turned on, these strings will be exported as:
657 Org HTML LaTeX UTF-8
658 -----+----------+--------+-------
659 \\- &shy; \\-
660 -- &ndash; -- –
661 --- &mdash; --- —
662 ... &hellip; \\ldots …
664 This option can also be set with the OPTIONS keyword,
665 e.g. \"-:nil\"."
666 :group 'org-export-general
667 :type 'boolean
668 :safe #'booleanp)
670 (defcustom org-export-with-statistics-cookies t
671 "Non-nil means include statistics cookies in export.
672 This option can also be set with the OPTIONS keyword,
673 e.g. \"stat:nil\""
674 :group 'org-export-general
675 :version "24.4"
676 :package-version '(Org . "8.0")
677 :type 'boolean
678 :safe #'booleanp)
680 (defcustom org-export-with-sub-superscripts t
681 "Non-nil means interpret \"_\" and \"^\" for export.
683 If you want to control how Org displays those characters, see
684 `org-use-sub-superscripts'. `org-export-with-sub-superscripts'
685 used to be an alias for `org-use-sub-superscripts' in Org <8.0,
686 it is not anymore.
688 When this option is turned on, you can use TeX-like syntax for
689 sub- and superscripts and see them exported correctly.
691 You can also set the option with #+OPTIONS: ^:t
693 Several characters after \"_\" or \"^\" will be considered as a
694 single item - so grouping with {} is normally not needed. For
695 example, the following things will be parsed as single sub- or
696 superscripts:
698 10^24 or 10^tau several digits will be considered 1 item.
699 10^-12 or 10^-tau a leading sign with digits or a word
700 x^2-y^3 will be read as x^2 - y^3, because items are
701 terminated by almost any nonword/nondigit char.
702 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
704 Still, ambiguity is possible. So when in doubt, use {} to enclose
705 the sub/superscript. If you set this variable to the symbol `{}',
706 the braces are *required* in order to trigger interpretations as
707 sub/superscript. This can be helpful in documents that need \"_\"
708 frequently in plain text."
709 :group 'org-export-general
710 :version "24.4"
711 :package-version '(Org . "8.0")
712 :type '(choice
713 (const :tag "Interpret them" t)
714 (const :tag "Curly brackets only" {})
715 (const :tag "Do not interpret them" nil))
716 :safe (lambda (x) (memq x '(t nil {}))))
718 (defcustom org-export-with-toc t
719 "Non-nil means create a table of contents in exported files.
721 The TOC contains headlines with levels up
722 to`org-export-headline-levels'. When an integer, include levels
723 up to N in the toc, this may then be different from
724 `org-export-headline-levels', but it will not be allowed to be
725 larger than the number of headline levels. When nil, no table of
726 contents is made.
728 This option can also be set with the OPTIONS keyword,
729 e.g. \"toc:nil\" or \"toc:3\"."
730 :group 'org-export-general
731 :type '(choice
732 (const :tag "No Table of Contents" nil)
733 (const :tag "Full Table of Contents" t)
734 (integer :tag "TOC to level"))
735 :safe (lambda (x) (or (booleanp x)
736 (integerp x))))
738 (defcustom org-export-with-tables t
739 "Non-nil means export tables.
740 This option can also be set with the OPTIONS keyword,
741 e.g. \"|:nil\"."
742 :group 'org-export-general
743 :version "24.4"
744 :package-version '(Org . "8.0")
745 :type 'boolean
746 :safe #'booleanp)
748 (defcustom org-export-with-tags t
749 "If nil, do not export tags, just remove them from headlines.
751 If this is the symbol `not-in-toc', tags will be removed from
752 table of contents entries, but still be shown in the headlines of
753 the document.
755 This option can also be set with the OPTIONS keyword,
756 e.g. \"tags:nil\"."
757 :group 'org-export-general
758 :type '(choice
759 (const :tag "Off" nil)
760 (const :tag "Not in TOC" not-in-toc)
761 (const :tag "On" t))
762 :safe (lambda (x) (memq x '(t nil not-in-toc))))
764 (defcustom org-export-with-tasks t
765 "Non-nil means include TODO items for export.
767 This may have the following values:
768 t include tasks independent of state.
769 `todo' include only tasks that are not yet done.
770 `done' include only tasks that are already done.
771 nil ignore all tasks.
772 list of keywords include tasks with these keywords.
774 This option can also be set with the OPTIONS keyword,
775 e.g. \"tasks:nil\"."
776 :group 'org-export-general
777 :type '(choice
778 (const :tag "All tasks" t)
779 (const :tag "No tasks" nil)
780 (const :tag "Not-done tasks" todo)
781 (const :tag "Only done tasks" done)
782 (repeat :tag "Specific TODO keywords"
783 (string :tag "Keyword")))
784 :safe (lambda (x) (or (memq x '(nil t todo done))
785 (and (listp x)
786 (cl-every #'stringp x)))))
788 (defcustom org-export-with-title t
789 "Non-nil means print title into the exported file.
790 This option can also be set with the OPTIONS keyword,
791 e.g. \"title:nil\"."
792 :group 'org-export-general
793 :version "25.2"
794 :package-version '(Org . "8.3")
795 :type 'boolean
796 :safe #'booleanp)
798 (defcustom org-export-time-stamp-file t
799 "Non-nil means insert a time stamp into the exported file.
800 The time stamp shows when the file was created. This option can
801 also be set with the OPTIONS keyword, e.g. \"timestamp:nil\"."
802 :group 'org-export-general
803 :type 'boolean
804 :safe #'booleanp)
806 (defcustom org-export-with-timestamps t
807 "Non nil means allow timestamps in export.
809 It can be set to any of the following values:
810 t export all timestamps.
811 `active' export active timestamps only.
812 `inactive' export inactive timestamps only.
813 nil do not export timestamps
815 This only applies to timestamps isolated in a paragraph
816 containing only timestamps. Other timestamps are always
817 exported.
819 This option can also be set with the OPTIONS keyword, e.g.
820 \"<:nil\"."
821 :group 'org-export-general
822 :type '(choice
823 (const :tag "All timestamps" t)
824 (const :tag "Only active timestamps" active)
825 (const :tag "Only inactive timestamps" inactive)
826 (const :tag "No timestamp" nil))
827 :safe (lambda (x) (memq x '(t nil active inactive))))
829 (defcustom org-export-with-todo-keywords t
830 "Non-nil means include TODO keywords in export.
831 When nil, remove all these keywords from the export. This option
832 can also be set with the OPTIONS keyword, e.g. \"todo:nil\"."
833 :group 'org-export-general
834 :type 'boolean)
836 (defcustom org-export-allow-bind-keywords nil
837 "Non-nil means BIND keywords can define local variable values.
838 This is a potential security risk, which is why the default value
839 is nil. You can also allow them through local buffer variables."
840 :group 'org-export-general
841 :version "24.4"
842 :package-version '(Org . "8.0")
843 :type 'boolean)
845 (defcustom org-export-with-broken-links nil
846 "Non-nil means do not raise an error on broken links.
848 When this variable is non-nil, broken links are ignored, without
849 stopping the export process. If it is set to `mark', broken
850 links are marked as such in the output, with a string like
852 [BROKEN LINK: path]
854 where PATH is the un-resolvable reference.
856 This option can also be set with the OPTIONS keyword, e.g.,
857 \"broken-links:mark\"."
858 :group 'org-export-general
859 :version "25.2"
860 :package-version '(Org . "9.0")
861 :type '(choice
862 (const :tag "Ignore broken links" t)
863 (const :tag "Mark broken links in output" mark)
864 (const :tag "Raise an error" nil)))
866 (defcustom org-export-snippet-translation-alist nil
867 "Alist between export snippets back-ends and exporter back-ends.
869 This variable allows providing shortcuts for export snippets.
871 For example, with a value of \\='((\"h\" . \"html\")), the
872 HTML back-end will recognize the contents of \"@@h:<b>@@\" as
873 HTML code while every other back-end will ignore it."
874 :group 'org-export-general
875 :version "24.4"
876 :package-version '(Org . "8.0")
877 :type '(repeat
878 (cons (string :tag "Shortcut")
879 (string :tag "Back-end")))
880 :safe (lambda (x)
881 (and (listp x)
882 (cl-every #'consp x)
883 (cl-every #'stringp (mapcar #'car x))
884 (cl-every #'stringp (mapcar #'cdr x)))))
886 (defcustom org-export-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 "25.2"
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 "25.2"
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 (defun org-export-get-backend (name)
1023 "Return export back-end named after NAME.
1024 NAME is a symbol. Return nil if no such back-end is found."
1025 (catch 'found
1026 (dolist (b org-export-registered-backends)
1027 (when (eq (org-export-backend-name b) name)
1028 (throw 'found b)))))
1030 (defun org-export-register-backend (backend)
1031 "Register BACKEND as a known export back-end.
1032 BACKEND is a structure with `org-export-backend' type."
1033 ;; Refuse to register an unnamed back-end.
1034 (unless (org-export-backend-name backend)
1035 (error "Cannot register a unnamed export back-end"))
1036 ;; Refuse to register a back-end with an unknown parent.
1037 (let ((parent (org-export-backend-parent backend)))
1038 (when (and parent (not (org-export-get-backend parent)))
1039 (error "Cannot use unknown \"%s\" back-end as a parent" parent)))
1040 ;; If a back-end with the same name as BACKEND is already
1041 ;; registered, replace it with BACKEND. Otherwise, simply add
1042 ;; BACKEND to the list of registered back-ends.
1043 (let ((old (org-export-get-backend (org-export-backend-name backend))))
1044 (if old (setcar (memq old org-export-registered-backends) backend)
1045 (push backend org-export-registered-backends))))
1047 (defun org-export-barf-if-invalid-backend (backend)
1048 "Signal an error if BACKEND isn't defined."
1049 (unless (org-export-backend-p backend)
1050 (error "Unknown \"%s\" back-end: Aborting export" backend)))
1052 (defun org-export-derived-backend-p (backend &rest backends)
1053 "Non-nil if BACKEND is derived from one of BACKENDS.
1054 BACKEND is an export back-end, as returned by, e.g.,
1055 `org-export-create-backend', or a symbol referring to
1056 a registered back-end. BACKENDS is constituted of symbols."
1057 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
1058 (when backend
1059 (catch 'exit
1060 (while (org-export-backend-parent backend)
1061 (when (memq (org-export-backend-name backend) backends)
1062 (throw 'exit t))
1063 (setq backend
1064 (org-export-get-backend (org-export-backend-parent backend))))
1065 (memq (org-export-backend-name backend) backends))))
1067 (defun org-export-get-all-transcoders (backend)
1068 "Return full translation table for BACKEND.
1070 BACKEND is an export back-end, as return by, e.g,,
1071 `org-export-create-backend'. Return value is an alist where
1072 keys are element or object types, as symbols, and values are
1073 transcoders.
1075 Unlike to `org-export-backend-transcoders', this function
1076 also returns transcoders inherited from parent back-ends,
1077 if any."
1078 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
1079 (when backend
1080 (let ((transcoders (org-export-backend-transcoders backend))
1081 parent)
1082 (while (setq parent (org-export-backend-parent backend))
1083 (setq backend (org-export-get-backend parent))
1084 (setq transcoders
1085 (append transcoders (org-export-backend-transcoders backend))))
1086 transcoders)))
1088 (defun org-export-get-all-options (backend)
1089 "Return export options for BACKEND.
1091 BACKEND is an export back-end, as return by, e.g,,
1092 `org-export-create-backend'. See `org-export-options-alist'
1093 for the shape of the return value.
1095 Unlike to `org-export-backend-options', this function also
1096 returns options inherited from parent back-ends, if any."
1097 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
1098 (when backend
1099 (let ((options (org-export-backend-options backend))
1100 parent)
1101 (while (setq parent (org-export-backend-parent backend))
1102 (setq backend (org-export-get-backend parent))
1103 (setq options (append options (org-export-backend-options backend))))
1104 options)))
1106 (defun org-export-get-all-filters (backend)
1107 "Return complete list of filters for BACKEND.
1109 BACKEND is an export back-end, as return by, e.g,,
1110 `org-export-create-backend'. Return value is an alist where
1111 keys are symbols and values lists of functions.
1113 Unlike to `org-export-backend-filters', this function also
1114 returns filters inherited from parent back-ends, if any."
1115 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
1116 (when backend
1117 (let ((filters (org-export-backend-filters backend))
1118 parent)
1119 (while (setq parent (org-export-backend-parent backend))
1120 (setq backend (org-export-get-backend parent))
1121 (setq filters (append filters (org-export-backend-filters backend))))
1122 filters)))
1124 (defun org-export-define-backend (backend transcoders &rest body)
1125 "Define a new back-end BACKEND.
1127 TRANSCODERS is an alist between object or element types and
1128 functions handling them.
1130 These functions should return a string without any trailing
1131 space, or nil. They must accept three arguments: the object or
1132 element itself, its contents or nil when it isn't recursive and
1133 the property list used as a communication channel.
1135 Contents, when not nil, are stripped from any global indentation
1136 \(although the relative one is preserved). They also always end
1137 with a single newline character.
1139 If, for a given type, no function is found, that element or
1140 object type will simply be ignored, along with any blank line or
1141 white space at its end. The same will happen if the function
1142 returns the nil value. If that function returns the empty
1143 string, the type will be ignored, but the blank lines or white
1144 spaces will be kept.
1146 In addition to element and object types, one function can be
1147 associated to the `template' (or `inner-template') symbol and
1148 another one to the `plain-text' symbol.
1150 The former returns the final transcoded string, and can be used
1151 to add a preamble and a postamble to document's body. It must
1152 accept two arguments: the transcoded string and the property list
1153 containing export options. A function associated to `template'
1154 will not be applied if export has option \"body-only\".
1155 A function associated to `inner-template' is always applied.
1157 The latter, when defined, is to be called on every text not
1158 recognized as an element or an object. It must accept two
1159 arguments: the text string and the information channel. It is an
1160 appropriate place to protect special chars relative to the
1161 back-end.
1163 BODY can start with pre-defined keyword arguments. The following
1164 keywords are understood:
1166 :filters-alist
1168 Alist between filters and function, or list of functions,
1169 specific to the back-end. See `org-export-filters-alist' for
1170 a list of all allowed filters. Filters defined here
1171 shouldn't make a back-end test, as it may prevent back-ends
1172 derived from this one to behave properly.
1174 :menu-entry
1176 Menu entry for the export dispatcher. It should be a list
1177 like:
1179 \\='(KEY DESCRIPTION-OR-ORDINAL ACTION-OR-MENU)
1181 where :
1183 KEY is a free character selecting the back-end.
1185 DESCRIPTION-OR-ORDINAL is either a string or a number.
1187 If it is a string, is will be used to name the back-end in
1188 its menu entry. If it is a number, the following menu will
1189 be displayed as a sub-menu of the back-end with the same
1190 KEY. Also, the number will be used to determine in which
1191 order such sub-menus will appear (lowest first).
1193 ACTION-OR-MENU is either a function or an alist.
1195 If it is an action, it will be called with four
1196 arguments (booleans): ASYNC, SUBTREEP, VISIBLE-ONLY and
1197 BODY-ONLY. See `org-export-as' for further explanations on
1198 some of them.
1200 If it is an alist, associations should follow the
1201 pattern:
1203 \\='(KEY DESCRIPTION ACTION)
1205 where KEY, DESCRIPTION and ACTION are described above.
1207 Valid values include:
1209 \\='(?m \"My Special Back-end\" my-special-export-function)
1213 \\='(?l \"Export to LaTeX\"
1214 (?p \"As PDF file\" org-latex-export-to-pdf)
1215 (?o \"As PDF file and open\"
1216 (lambda (a s v b)
1217 (if a (org-latex-export-to-pdf t s v b)
1218 (org-open-file
1219 (org-latex-export-to-pdf nil s v b)))))))
1221 or the following, which will be added to the previous
1222 sub-menu,
1224 \\='(?l 1
1225 ((?B \"As TEX buffer (Beamer)\" org-beamer-export-as-latex)
1226 (?P \"As PDF file (Beamer)\" org-beamer-export-to-pdf)))
1228 :options-alist
1230 Alist between back-end specific properties introduced in
1231 communication channel and how their value are acquired. See
1232 `org-export-options-alist' for more information about
1233 structure of the values."
1234 (declare (indent 1))
1235 (let (filters menu-entry options)
1236 (while (keywordp (car body))
1237 (let ((keyword (pop body)))
1238 (pcase keyword
1239 (:filters-alist (setq filters (pop body)))
1240 (:menu-entry (setq menu-entry (pop body)))
1241 (:options-alist (setq options (pop body)))
1242 (_ (error "Unknown keyword: %s" keyword)))))
1243 (org-export-register-backend
1244 (org-export-create-backend :name backend
1245 :transcoders transcoders
1246 :options options
1247 :filters filters
1248 :menu menu-entry))))
1250 (defun org-export-define-derived-backend (child parent &rest body)
1251 "Create a new back-end as a variant of an existing one.
1253 CHILD is the name of the derived back-end. PARENT is the name of
1254 the parent back-end.
1256 BODY can start with pre-defined keyword arguments. The following
1257 keywords are understood:
1259 :filters-alist
1261 Alist of filters that will overwrite or complete filters
1262 defined in PARENT back-end. See `org-export-filters-alist'
1263 for a list of allowed filters.
1265 :menu-entry
1267 Menu entry for the export dispatcher. See
1268 `org-export-define-backend' for more information about the
1269 expected value.
1271 :options-alist
1273 Alist of back-end specific properties that will overwrite or
1274 complete those defined in PARENT back-end. Refer to
1275 `org-export-options-alist' for more information about
1276 structure of the values.
1278 :translate-alist
1280 Alist of element and object types and transcoders that will
1281 overwrite or complete transcode table from PARENT back-end.
1282 Refer to `org-export-define-backend' for detailed information
1283 about transcoders.
1285 As an example, here is how one could define \"my-latex\" back-end
1286 as a variant of `latex' back-end with a custom template function:
1288 (org-export-define-derived-backend \\='my-latex \\='latex
1289 :translate-alist \\='((template . my-latex-template-fun)))
1291 The back-end could then be called with, for example:
1293 (org-export-to-buffer \\='my-latex \"*Test my-latex*\")"
1294 (declare (indent 2))
1295 (let (filters menu-entry options transcoders)
1296 (while (keywordp (car body))
1297 (let ((keyword (pop body)))
1298 (pcase keyword
1299 (:filters-alist (setq filters (pop body)))
1300 (:menu-entry (setq menu-entry (pop body)))
1301 (:options-alist (setq options (pop body)))
1302 (:translate-alist (setq transcoders (pop body)))
1303 (_ (error "Unknown keyword: %s" keyword)))))
1304 (org-export-register-backend
1305 (org-export-create-backend :name child
1306 :parent parent
1307 :transcoders transcoders
1308 :options options
1309 :filters filters
1310 :menu menu-entry))))
1314 ;;; The Communication Channel
1316 ;; During export process, every function has access to a number of
1317 ;; properties. They are of two types:
1319 ;; 1. Environment options are collected once at the very beginning of
1320 ;; the process, out of the original buffer and configuration.
1321 ;; Collecting them is handled by `org-export-get-environment'
1322 ;; function.
1324 ;; Most environment options are defined through the
1325 ;; `org-export-options-alist' variable.
1327 ;; 2. Tree properties are extracted directly from the parsed tree,
1328 ;; just before export, by `org-export--collect-tree-properties'.
1330 ;;;; Environment Options
1332 ;; Environment options encompass all parameters defined outside the
1333 ;; scope of the parsed data. They come from five sources, in
1334 ;; increasing precedence order:
1336 ;; - Global variables,
1337 ;; - Buffer's attributes,
1338 ;; - Options keyword symbols,
1339 ;; - Buffer keywords,
1340 ;; - Subtree properties.
1342 ;; The central internal function with regards to environment options
1343 ;; is `org-export-get-environment'. It updates global variables with
1344 ;; "#+BIND:" keywords, then retrieve and prioritize properties from
1345 ;; the different sources.
1347 ;; The internal functions doing the retrieval are:
1348 ;; `org-export--get-global-options',
1349 ;; `org-export--get-buffer-attributes',
1350 ;; `org-export--parse-option-keyword',
1351 ;; `org-export--get-subtree-options' and
1352 ;; `org-export--get-inbuffer-options'
1354 ;; Also, `org-export--list-bound-variables' collects bound variables
1355 ;; along with their value in order to set them as buffer local
1356 ;; variables later in the process.
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 (blob options selected)
1809 "Non-nil when element or object BLOB 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 blob)
1814 (clock (not (plist-get options :with-clocks)))
1815 (drawer
1816 (let ((with-drawers-p (plist-get options :with-drawers)))
1817 (or (not with-drawers-p)
1818 (and (consp with-drawers-p)
1819 ;; If `:with-drawers' value starts with `not', ignore
1820 ;; every drawer whose name belong to that list.
1821 ;; Otherwise, ignore drawers whose name isn't in that
1822 ;; list.
1823 (let ((name (org-element-property :drawer-name blob)))
1824 (if (eq (car with-drawers-p) 'not)
1825 (member-ignore-case name (cdr with-drawers-p))
1826 (not (member-ignore-case name with-drawers-p))))))))
1827 (fixed-width (not (plist-get options :with-fixed-width)))
1828 ((footnote-definition footnote-reference)
1829 (not (plist-get options :with-footnotes)))
1830 ((headline inlinetask)
1831 (let ((with-tasks (plist-get options :with-tasks))
1832 (todo (org-element-property :todo-keyword blob))
1833 (todo-type (org-element-property :todo-type blob))
1834 (archived (plist-get options :with-archived-trees))
1835 (tags (org-export-get-tags blob options nil t)))
1837 (and (eq (org-element-type blob) 'inlinetask)
1838 (not (plist-get options :with-inlinetasks)))
1839 ;; Ignore subtrees with an exclude tag.
1840 (cl-loop for k in (plist-get options :exclude-tags)
1841 thereis (member k tags))
1842 ;; When a select tag is present in the buffer, ignore any tree
1843 ;; without it.
1844 (and selected (not (memq blob selected)))
1845 ;; Ignore commented sub-trees.
1846 (org-element-property :commentedp blob)
1847 ;; Ignore archived subtrees if `:with-archived-trees' is nil.
1848 (and (not archived) (org-element-property :archivedp blob))
1849 ;; Ignore tasks, if specified by `:with-tasks' property.
1850 (and todo
1851 (or (not with-tasks)
1852 (and (memq with-tasks '(todo done))
1853 (not (eq todo-type with-tasks)))
1854 (and (consp with-tasks) (not (member todo with-tasks))))))))
1855 ((latex-environment latex-fragment) (not (plist-get options :with-latex)))
1856 (node-property
1857 (let ((properties-set (plist-get options :with-properties)))
1858 (cond ((null properties-set) t)
1859 ((consp properties-set)
1860 (not (member-ignore-case (org-element-property :key blob)
1861 properties-set))))))
1862 (planning (not (plist-get options :with-planning)))
1863 (property-drawer (not (plist-get options :with-properties)))
1864 (statistics-cookie (not (plist-get options :with-statistics-cookies)))
1865 (table (not (plist-get options :with-tables)))
1866 (table-cell
1867 (and (org-export-table-has-special-column-p
1868 (org-export-get-parent-table blob))
1869 (org-export-first-sibling-p blob options)))
1870 (table-row (org-export-table-row-is-special-p blob options))
1871 (timestamp
1872 ;; `:with-timestamps' only applies to isolated timestamps
1873 ;; objects, i.e. timestamp objects in a paragraph containing only
1874 ;; timestamps and whitespaces.
1875 (when (let ((parent (org-export-get-parent-element blob)))
1876 (and (memq (org-element-type parent) '(paragraph verse-block))
1877 (not (org-element-map parent
1878 (cons 'plain-text
1879 (remq 'timestamp org-element-all-objects))
1880 (lambda (obj)
1881 (or (not (stringp obj)) (org-string-nw-p obj)))
1882 options t))))
1883 (cl-case (plist-get options :with-timestamps)
1884 ((nil) t)
1885 (active
1886 (not (memq (org-element-property :type blob) '(active active-range))))
1887 (inactive
1888 (not (memq (org-element-property :type blob)
1889 '(inactive inactive-range)))))))))
1892 ;;; The Transcoder
1894 ;; `org-export-data' reads a parse tree (obtained with, i.e.
1895 ;; `org-element-parse-buffer') and transcodes it into a specified
1896 ;; back-end output. It takes care of filtering out elements or
1897 ;; objects according to export options and organizing the output blank
1898 ;; lines and white space are preserved. The function memoizes its
1899 ;; results, so it is cheap to call it within transcoders.
1901 ;; It is possible to modify locally the back-end used by
1902 ;; `org-export-data' or even use a temporary back-end by using
1903 ;; `org-export-data-with-backend'.
1905 ;; `org-export-transcoder' is an accessor returning appropriate
1906 ;; translator function for a given element or object.
1908 (defun org-export-transcoder (blob info)
1909 "Return appropriate transcoder for BLOB.
1910 INFO is a plist containing export directives."
1911 (let ((type (org-element-type blob)))
1912 ;; Return contents only for complete parse trees.
1913 (if (eq type 'org-data) (lambda (_datum contents _info) contents)
1914 (let ((transcoder (cdr (assq type (plist-get info :translate-alist)))))
1915 (and (functionp transcoder) transcoder)))))
1917 (defun org-export-data (data info)
1918 "Convert DATA into current back-end format.
1920 DATA is a parse tree, an element or an object or a secondary
1921 string. INFO is a plist holding export options.
1923 Return a string."
1924 (or (gethash data (plist-get info :exported-data))
1925 ;; Handle broken links according to
1926 ;; `org-export-with-broken-links'.
1927 (cl-macrolet
1928 ((broken-link-handler
1929 (&rest body)
1930 `(condition-case err
1931 (progn ,@body)
1932 (org-link-broken
1933 (pcase (plist-get info :with-broken-links)
1934 (`nil (user-error "Unable to resolve link: %S" (nth 1 err)))
1935 (`mark (org-export-data
1936 (format "[BROKEN LINK: %s]" (nth 1 err)) info))
1937 (_ nil))))))
1938 (let* ((type (org-element-type data))
1939 (parent (org-export-get-parent data))
1940 (results
1941 (cond
1942 ;; Ignored element/object.
1943 ((memq data (plist-get info :ignore-list)) nil)
1944 ;; Plain text.
1945 ((eq type 'plain-text)
1946 (org-export-filter-apply-functions
1947 (plist-get info :filter-plain-text)
1948 (let ((transcoder (org-export-transcoder data info)))
1949 (if transcoder (funcall transcoder data info) data))
1950 info))
1951 ;; Secondary string.
1952 ((not type)
1953 (mapconcat (lambda (obj) (org-export-data obj info)) data ""))
1954 ;; Element/Object without contents or, as a special
1955 ;; case, headline with archive tag and archived trees
1956 ;; restricted to title only.
1957 ((or (not (org-element-contents data))
1958 (and (eq type 'headline)
1959 (eq (plist-get info :with-archived-trees) 'headline)
1960 (org-element-property :archivedp data)))
1961 (let ((transcoder (org-export-transcoder data info)))
1962 (or (and (functionp transcoder)
1963 (broken-link-handler
1964 (funcall transcoder data nil info)))
1965 ;; Export snippets never return a nil value so
1966 ;; that white spaces following them are never
1967 ;; ignored.
1968 (and (eq type 'export-snippet) ""))))
1969 ;; Element/Object with contents.
1971 (let ((transcoder (org-export-transcoder data info)))
1972 (when transcoder
1973 (let* ((greaterp (memq type org-element-greater-elements))
1974 (objectp
1975 (and (not greaterp)
1976 (memq type org-element-recursive-objects)))
1977 (contents
1978 (mapconcat
1979 (lambda (element) (org-export-data element info))
1980 (org-element-contents
1981 (if (or greaterp objectp) data
1982 ;; Elements directly containing
1983 ;; objects must have their indentation
1984 ;; normalized first.
1985 (org-element-normalize-contents
1986 data
1987 ;; When normalizing contents of the
1988 ;; first paragraph in an item or
1989 ;; a footnote definition, ignore
1990 ;; first line's indentation: there is
1991 ;; none and it might be misleading.
1992 (when (eq type 'paragraph)
1993 (and
1994 (eq (car (org-element-contents parent))
1995 data)
1996 (memq (org-element-type parent)
1997 '(footnote-definition item)))))))
1998 "")))
1999 (broken-link-handler
2000 (funcall transcoder data
2001 (if (not greaterp) contents
2002 (org-element-normalize-string contents))
2003 info)))))))))
2004 ;; Final result will be memoized before being returned.
2005 (puthash
2006 data
2007 (cond
2008 ((not results) "")
2009 ((memq type '(org-data plain-text nil)) results)
2010 ;; Append the same white space between elements or objects
2011 ;; as in the original buffer, and call appropriate filters.
2013 (org-export-filter-apply-functions
2014 (plist-get info (intern (format ":filter-%s" type)))
2015 (let ((blank (or (org-element-property :post-blank data) 0)))
2016 (if (eq (org-element-class data parent) 'object)
2017 (concat results (make-string blank ?\s))
2018 (concat (org-element-normalize-string results)
2019 (make-string blank ?\n))))
2020 info)))
2021 (plist-get info :exported-data))))))
2023 (defun org-export-data-with-backend (data backend info)
2024 "Convert DATA into BACKEND format.
2026 DATA is an element, an object, a secondary string or a string.
2027 BACKEND is a symbol. INFO is a plist used as a communication
2028 channel.
2030 Unlike to `org-export-with-backend', this function will
2031 recursively convert DATA using BACKEND translation table."
2032 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
2033 ;; Set-up a new communication channel with translations defined in
2034 ;; BACKEND as the translate table and a new hash table for
2035 ;; memoization.
2036 (let ((new-info
2037 (org-combine-plists
2038 info
2039 (list :back-end backend
2040 :translate-alist (org-export-get-all-transcoders backend)
2041 ;; Size of the hash table is reduced since this
2042 ;; function will probably be used on small trees.
2043 :exported-data (make-hash-table :test 'eq :size 401)))))
2044 (prog1 (org-export-data data new-info)
2045 ;; Preserve `:internal-references', as those do not depend on
2046 ;; the back-end used; we need to make sure that any new
2047 ;; reference when the temporary back-end was active gets through
2048 ;; the default one.
2049 (plist-put info :internal-references
2050 (plist-get new-info :internal-references)))))
2052 (defun org-export-expand (blob contents &optional with-affiliated)
2053 "Expand a parsed element or object to its original state.
2055 BLOB is either an element or an object. CONTENTS is its
2056 contents, as a string or nil.
2058 When optional argument WITH-AFFILIATED is non-nil, add affiliated
2059 keywords before output."
2060 (let ((type (org-element-type blob)))
2061 (concat (and with-affiliated
2062 (eq (org-element-class blob) 'element)
2063 (org-element--interpret-affiliated-keywords blob))
2064 (funcall (intern (format "org-element-%s-interpreter" type))
2065 blob contents))))
2069 ;;; The Filter System
2071 ;; Filters allow end-users to tweak easily the transcoded output.
2072 ;; They are the functional counterpart of hooks, as every filter in
2073 ;; a set is applied to the return value of the previous one.
2075 ;; Every set is back-end agnostic. Although, a filter is always
2076 ;; called, in addition to the string it applies to, with the back-end
2077 ;; used as argument, so it's easy for the end-user to add back-end
2078 ;; specific filters in the set. The communication channel, as
2079 ;; a plist, is required as the third argument.
2081 ;; From the developer side, filters sets can be installed in the
2082 ;; process with the help of `org-export-define-backend', which
2083 ;; internally stores filters as an alist. Each association has a key
2084 ;; among the following symbols and a function or a list of functions
2085 ;; as value.
2087 ;; - `:filter-options' applies to the property list containing export
2088 ;; options. Unlike to other filters, functions in this list accept
2089 ;; two arguments instead of three: the property list containing
2090 ;; export options and the back-end. Users can set its value through
2091 ;; `org-export-filter-options-functions' variable.
2093 ;; - `:filter-parse-tree' applies directly to the complete parsed
2094 ;; tree. Users can set it through
2095 ;; `org-export-filter-parse-tree-functions' variable.
2097 ;; - `:filter-body' applies to the body of the output, before template
2098 ;; translator chimes in. Users can set it through
2099 ;; `org-export-filter-body-functions' variable.
2101 ;; - `:filter-final-output' applies to the final transcoded string.
2102 ;; Users can set it with `org-export-filter-final-output-functions'
2103 ;; variable.
2105 ;; - `:filter-plain-text' applies to any string not recognized as Org
2106 ;; syntax. `org-export-filter-plain-text-functions' allows users to
2107 ;; configure it.
2109 ;; - `:filter-TYPE' applies on the string returned after an element or
2110 ;; object of type TYPE has been transcoded. A user can modify
2111 ;; `org-export-filter-TYPE-functions' to install these filters.
2113 ;; All filters sets are applied with
2114 ;; `org-export-filter-apply-functions' function. Filters in a set are
2115 ;; applied in a LIFO fashion. It allows developers to be sure that
2116 ;; their filters will be applied first.
2118 ;; Filters properties are installed in communication channel with
2119 ;; `org-export-install-filters' function.
2121 ;; Eventually, two hooks (`org-export-before-processing-hook' and
2122 ;; `org-export-before-parsing-hook') are run at the beginning of the
2123 ;; export process and just before parsing to allow for heavy structure
2124 ;; modifications.
2127 ;;;; Hooks
2129 (defvar org-export-before-processing-hook nil
2130 "Hook run at the beginning of the export process.
2132 This is run before include keywords and macros are expanded and
2133 Babel code blocks executed, on a copy of the original buffer
2134 being exported. Visibility and narrowing are preserved. Point
2135 is at the beginning of the buffer.
2137 Every function in this hook will be called with one argument: the
2138 back-end currently used, as a symbol.")
2140 (defvar org-export-before-parsing-hook nil
2141 "Hook run before parsing an export buffer.
2143 This is run after include keywords and macros have been expanded
2144 and 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.")
2152 ;;;; Special Filters
2154 (defvar org-export-filter-options-functions nil
2155 "List of functions applied to the export options.
2156 Each filter is called with two arguments: the export options, as
2157 a plist, and the back-end, as a symbol. It must return
2158 a property list containing export options.")
2160 (defvar org-export-filter-parse-tree-functions nil
2161 "List of functions applied to the parsed tree.
2162 Each filter is called with three arguments: the parse tree, as
2163 returned by `org-element-parse-buffer', the back-end, as
2164 a symbol, and the communication channel, as a plist. It must
2165 return the modified parse tree to transcode.")
2167 (defvar org-export-filter-plain-text-functions nil
2168 "List of functions applied to plain text.
2169 Each filter is called with three arguments: a string which
2170 contains no Org syntax, the back-end, as a symbol, and the
2171 communication channel, as a plist. It must return a string or
2172 nil.")
2174 (defvar org-export-filter-body-functions nil
2175 "List of functions applied to transcoded body.
2176 Each filter is called with three arguments: a string which
2177 contains no Org syntax, the back-end, as a symbol, and the
2178 communication channel, as a plist. It must return a string or
2179 nil.")
2181 (defvar org-export-filter-final-output-functions nil
2182 "List of functions applied to the transcoded string.
2183 Each filter is called with three arguments: the full transcoded
2184 string, the back-end, as a symbol, and the communication channel,
2185 as a plist. It must return a string that will be used as the
2186 final export output.")
2189 ;;;; Elements Filters
2191 (defvar org-export-filter-babel-call-functions nil
2192 "List of functions applied to a transcoded babel-call.
2193 Each filter is called with three arguments: the transcoded data,
2194 as a string, the back-end, as a symbol, and the communication
2195 channel, as a plist. It must return a string or nil.")
2197 (defvar org-export-filter-center-block-functions nil
2198 "List of functions applied to a transcoded center block.
2199 Each filter is called with three arguments: the transcoded data,
2200 as a string, the back-end, as a symbol, and the communication
2201 channel, as a plist. It must return a string or nil.")
2203 (defvar org-export-filter-clock-functions nil
2204 "List of functions applied to a transcoded clock.
2205 Each filter is called with three arguments: the transcoded data,
2206 as a string, the back-end, as a symbol, and the communication
2207 channel, as a plist. It must return a string or nil.")
2209 (defvar org-export-filter-diary-sexp-functions nil
2210 "List of functions applied to a transcoded diary-sexp.
2211 Each filter is called with three arguments: the transcoded data,
2212 as a string, the back-end, as a symbol, and the communication
2213 channel, as a plist. It must return a string or nil.")
2215 (defvar org-export-filter-drawer-functions nil
2216 "List of functions applied to a transcoded drawer.
2217 Each filter is called with three arguments: the transcoded data,
2218 as a string, the back-end, as a symbol, and the communication
2219 channel, as a plist. It must return a string or nil.")
2221 (defvar org-export-filter-dynamic-block-functions nil
2222 "List of functions applied to a transcoded dynamic-block.
2223 Each filter is called with three arguments: the transcoded data,
2224 as a string, the back-end, as a symbol, and the communication
2225 channel, as a plist. It must return a string or nil.")
2227 (defvar org-export-filter-example-block-functions nil
2228 "List of functions applied to a transcoded example-block.
2229 Each filter is called with three arguments: the transcoded data,
2230 as a string, the back-end, as a symbol, and the communication
2231 channel, as a plist. It must return a string or nil.")
2233 (defvar org-export-filter-export-block-functions nil
2234 "List of functions applied to a transcoded export-block.
2235 Each filter is called with three arguments: the transcoded data,
2236 as a string, the back-end, as a symbol, and the communication
2237 channel, as a plist. It must return a string or nil.")
2239 (defvar org-export-filter-fixed-width-functions nil
2240 "List of functions applied to a transcoded fixed-width.
2241 Each filter is called with three arguments: the transcoded data,
2242 as a string, the back-end, as a symbol, and the communication
2243 channel, as a plist. It must return a string or nil.")
2245 (defvar org-export-filter-footnote-definition-functions nil
2246 "List of functions applied to a transcoded footnote-definition.
2247 Each filter is called with three arguments: the transcoded data,
2248 as a string, the back-end, as a symbol, and the communication
2249 channel, as a plist. It must return a string or nil.")
2251 (defvar org-export-filter-headline-functions nil
2252 "List of functions applied to a transcoded headline.
2253 Each filter is called with three arguments: the transcoded data,
2254 as a string, the back-end, as a symbol, and the communication
2255 channel, as a plist. It must return a string or nil.")
2257 (defvar org-export-filter-horizontal-rule-functions nil
2258 "List of functions applied to a transcoded horizontal-rule.
2259 Each filter is called with three arguments: the transcoded data,
2260 as a string, the back-end, as a symbol, and the communication
2261 channel, as a plist. It must return a string or nil.")
2263 (defvar org-export-filter-inlinetask-functions nil
2264 "List of functions applied to a transcoded inlinetask.
2265 Each filter is called with three arguments: the transcoded data,
2266 as a string, the back-end, as a symbol, and the communication
2267 channel, as a plist. It must return a string or nil.")
2269 (defvar org-export-filter-item-functions nil
2270 "List of functions applied to a transcoded item.
2271 Each filter is called with three arguments: the transcoded data,
2272 as a string, the back-end, as a symbol, and the communication
2273 channel, as a plist. It must return a string or nil.")
2275 (defvar org-export-filter-keyword-functions nil
2276 "List of functions applied to a transcoded keyword.
2277 Each filter is called with three arguments: the transcoded data,
2278 as a string, the back-end, as a symbol, and the communication
2279 channel, as a plist. It must return a string or nil.")
2281 (defvar org-export-filter-latex-environment-functions nil
2282 "List of functions applied to a transcoded latex-environment.
2283 Each filter is called with three arguments: the transcoded data,
2284 as a string, the back-end, as a symbol, and the communication
2285 channel, as a plist. It must return a string or nil.")
2287 (defvar org-export-filter-node-property-functions nil
2288 "List of functions applied to a transcoded node-property.
2289 Each filter is called with three arguments: the transcoded data,
2290 as a string, the back-end, as a symbol, and the communication
2291 channel, as a plist. It must return a string or nil.")
2293 (defvar org-export-filter-paragraph-functions nil
2294 "List of functions applied to a transcoded paragraph.
2295 Each filter is called with three arguments: the transcoded data,
2296 as a string, the back-end, as a symbol, and the communication
2297 channel, as a plist. It must return a string or nil.")
2299 (defvar org-export-filter-plain-list-functions nil
2300 "List of functions applied to a transcoded plain-list.
2301 Each filter is called with three arguments: the transcoded data,
2302 as a string, the back-end, as a symbol, and the communication
2303 channel, as a plist. It must return a string or nil.")
2305 (defvar org-export-filter-planning-functions nil
2306 "List of functions applied to a transcoded planning.
2307 Each filter is called with three arguments: the transcoded data,
2308 as a string, the back-end, as a symbol, and the communication
2309 channel, as a plist. It must return a string or nil.")
2311 (defvar org-export-filter-property-drawer-functions nil
2312 "List of functions applied to a transcoded property-drawer.
2313 Each filter is called with three arguments: the transcoded data,
2314 as a string, the back-end, as a symbol, and the communication
2315 channel, as a plist. It must return a string or nil.")
2317 (defvar org-export-filter-quote-block-functions nil
2318 "List of functions applied to a transcoded quote block.
2319 Each filter is called with three arguments: the transcoded quote
2320 data, as a string, the back-end, as a symbol, and the
2321 communication channel, as a plist. It must return a string or
2322 nil.")
2324 (defvar org-export-filter-section-functions nil
2325 "List of functions applied to a transcoded section.
2326 Each filter is called with three arguments: the transcoded data,
2327 as a string, the back-end, as a symbol, and the communication
2328 channel, as a plist. It must return a string or nil.")
2330 (defvar org-export-filter-special-block-functions nil
2331 "List of functions applied to a transcoded special block.
2332 Each filter is called with three arguments: the transcoded data,
2333 as a string, the back-end, as a symbol, and the communication
2334 channel, as a plist. It must return a string or nil.")
2336 (defvar org-export-filter-src-block-functions nil
2337 "List of functions applied to a transcoded src-block.
2338 Each filter is called with three arguments: the transcoded data,
2339 as a string, the back-end, as a symbol, and the communication
2340 channel, as a plist. It must return a string or nil.")
2342 (defvar org-export-filter-table-functions nil
2343 "List of functions applied to a transcoded table.
2344 Each filter is called with three arguments: the transcoded data,
2345 as a string, the back-end, as a symbol, and the communication
2346 channel, as a plist. It must return a string or nil.")
2348 (defvar org-export-filter-table-cell-functions nil
2349 "List of functions applied to a transcoded table-cell.
2350 Each filter is called with three arguments: the transcoded data,
2351 as a string, the back-end, as a symbol, and the communication
2352 channel, as a plist. It must return a string or nil.")
2354 (defvar org-export-filter-table-row-functions nil
2355 "List of functions applied to a transcoded table-row.
2356 Each filter is called with three arguments: the transcoded data,
2357 as a string, the back-end, as a symbol, and the communication
2358 channel, as a plist. It must return a string or nil.")
2360 (defvar org-export-filter-verse-block-functions nil
2361 "List of functions applied to a transcoded verse block.
2362 Each filter is called with three arguments: the transcoded data,
2363 as a string, the back-end, as a symbol, and the communication
2364 channel, as a plist. It must return a string or nil.")
2367 ;;;; Objects Filters
2369 (defvar org-export-filter-bold-functions nil
2370 "List of functions applied to transcoded bold text.
2371 Each filter is called with three arguments: the transcoded data,
2372 as a string, the back-end, as a symbol, and the communication
2373 channel, as a plist. It must return a string or nil.")
2375 (defvar org-export-filter-code-functions nil
2376 "List of functions applied to transcoded code text.
2377 Each filter is called with three arguments: the transcoded data,
2378 as a string, the back-end, as a symbol, and the communication
2379 channel, as a plist. It must return a string or nil.")
2381 (defvar org-export-filter-entity-functions nil
2382 "List of functions applied to a transcoded entity.
2383 Each filter is called with three arguments: the transcoded data,
2384 as a string, the back-end, as a symbol, and the communication
2385 channel, as a plist. It must return a string or nil.")
2387 (defvar org-export-filter-export-snippet-functions nil
2388 "List of functions applied to a transcoded export-snippet.
2389 Each filter is called with three arguments: the transcoded data,
2390 as a string, the back-end, as a symbol, and the communication
2391 channel, as a plist. It must return a string or nil.")
2393 (defvar org-export-filter-footnote-reference-functions nil
2394 "List of functions applied to a transcoded footnote-reference.
2395 Each filter is called with three arguments: the transcoded data,
2396 as a string, the back-end, as a symbol, and the communication
2397 channel, as a plist. It must return a string or nil.")
2399 (defvar org-export-filter-inline-babel-call-functions nil
2400 "List of functions applied to a transcoded inline-babel-call.
2401 Each filter is called with three arguments: the transcoded data,
2402 as a string, the back-end, as a symbol, and the communication
2403 channel, as a plist. It must return a string or nil.")
2405 (defvar org-export-filter-inline-src-block-functions nil
2406 "List of functions applied to a transcoded inline-src-block.
2407 Each filter is called with three arguments: the transcoded data,
2408 as a string, the back-end, as a symbol, and the communication
2409 channel, as a plist. It must return a string or nil.")
2411 (defvar org-export-filter-italic-functions nil
2412 "List of functions applied to transcoded italic text.
2413 Each filter is called with three arguments: the transcoded data,
2414 as a string, the back-end, as a symbol, and the communication
2415 channel, as a plist. It must return a string or nil.")
2417 (defvar org-export-filter-latex-fragment-functions nil
2418 "List of functions applied to a transcoded latex-fragment.
2419 Each filter is called with three arguments: the transcoded data,
2420 as a string, the back-end, as a symbol, and the communication
2421 channel, as a plist. It must return a string or nil.")
2423 (defvar org-export-filter-line-break-functions nil
2424 "List of functions applied to a transcoded line-break.
2425 Each filter is called with three arguments: the transcoded data,
2426 as a string, the back-end, as a symbol, and the communication
2427 channel, as a plist. It must return a string or nil.")
2429 (defvar org-export-filter-link-functions nil
2430 "List of functions applied to a transcoded link.
2431 Each filter is called with three arguments: the transcoded data,
2432 as a string, the back-end, as a symbol, and the communication
2433 channel, as a plist. It must return a string or nil.")
2435 (defvar org-export-filter-radio-target-functions nil
2436 "List of functions applied to a transcoded radio-target.
2437 Each filter is called with three arguments: the transcoded data,
2438 as a string, the back-end, as a symbol, and the communication
2439 channel, as a plist. It must return a string or nil.")
2441 (defvar org-export-filter-statistics-cookie-functions nil
2442 "List of functions applied to a transcoded statistics-cookie.
2443 Each filter is called with three arguments: the transcoded data,
2444 as a string, the back-end, as a symbol, and the communication
2445 channel, as a plist. It must return a string or nil.")
2447 (defvar org-export-filter-strike-through-functions nil
2448 "List of functions applied to transcoded strike-through text.
2449 Each filter is called with three arguments: the transcoded data,
2450 as a string, the back-end, as a symbol, and the communication
2451 channel, as a plist. It must return a string or nil.")
2453 (defvar org-export-filter-subscript-functions nil
2454 "List of functions applied to a transcoded subscript.
2455 Each filter is called with three arguments: the transcoded data,
2456 as a string, the back-end, as a symbol, and the communication
2457 channel, as a plist. It must return a string or nil.")
2459 (defvar org-export-filter-superscript-functions nil
2460 "List of functions applied to a transcoded superscript.
2461 Each filter is called with three arguments: the transcoded data,
2462 as a string, the back-end, as a symbol, and the communication
2463 channel, as a plist. It must return a string or nil.")
2465 (defvar org-export-filter-target-functions nil
2466 "List of functions applied to a transcoded target.
2467 Each filter is called with three arguments: the transcoded data,
2468 as a string, the back-end, as a symbol, and the communication
2469 channel, as a plist. It must return a string or nil.")
2471 (defvar org-export-filter-timestamp-functions nil
2472 "List of functions applied to a transcoded timestamp.
2473 Each filter is called with three arguments: the transcoded data,
2474 as a string, the back-end, as a symbol, and the communication
2475 channel, as a plist. It must return a string or nil.")
2477 (defvar org-export-filter-underline-functions nil
2478 "List of functions applied to transcoded underline text.
2479 Each filter is called with three arguments: the transcoded data,
2480 as a string, the back-end, as a symbol, and the communication
2481 channel, as a plist. It must return a string or nil.")
2483 (defvar org-export-filter-verbatim-functions nil
2484 "List of functions applied to transcoded verbatim text.
2485 Each filter is called with three arguments: the transcoded data,
2486 as a string, the back-end, as a symbol, and the communication
2487 channel, as a plist. It must return a string or nil.")
2490 ;;;; Filters Tools
2492 ;; Internal function `org-export-install-filters' installs filters
2493 ;; hard-coded in back-ends (developer filters) and filters from global
2494 ;; variables (user filters) in the communication channel.
2496 ;; Internal function `org-export-filter-apply-functions' takes care
2497 ;; about applying each filter in order to a given data. It ignores
2498 ;; filters returning a nil value but stops whenever a filter returns
2499 ;; an empty string.
2501 (defun org-export-filter-apply-functions (filters value info)
2502 "Call every function in FILTERS.
2504 Functions are called with three arguments: a value, the export
2505 back-end name and the communication channel. First function in
2506 FILTERS is called with VALUE as its first argument. Second
2507 function in FILTERS is called with the previous result as its
2508 value, etc.
2510 Functions returning nil are skipped. Any function returning the
2511 empty string ends the process, which returns the empty string.
2513 Call is done in a LIFO fashion, to be sure that developer
2514 specified filters, if any, are called first."
2515 (catch :exit
2516 (let* ((backend (plist-get info :back-end))
2517 (backend-name (and backend (org-export-backend-name backend))))
2518 (dolist (filter filters value)
2519 (let ((result (funcall filter value backend-name info)))
2520 (cond ((not result))
2521 ((equal result "") (throw :exit ""))
2522 (t (setq value result))))))))
2524 (defun org-export-install-filters (info)
2525 "Install filters properties in communication channel.
2526 INFO is a plist containing the current communication channel.
2527 Return the updated communication channel."
2528 (let (plist)
2529 ;; Install user-defined filters with `org-export-filters-alist'
2530 ;; and filters already in INFO (through ext-plist mechanism).
2531 (dolist (p org-export-filters-alist)
2532 (let* ((prop (car p))
2533 (info-value (plist-get info prop))
2534 (default-value (symbol-value (cdr p))))
2535 (setq plist
2536 (plist-put plist prop
2537 ;; Filters in INFO will be called
2538 ;; before those user provided.
2539 (append (if (listp info-value) info-value
2540 (list info-value))
2541 default-value)))))
2542 ;; Prepend back-end specific filters to that list.
2543 (dolist (p (org-export-get-all-filters (plist-get info :back-end)))
2544 ;; Single values get consed, lists are appended.
2545 (let ((key (car p)) (value (cdr p)))
2546 (when value
2547 (setq plist
2548 (plist-put
2549 plist key
2550 (if (atom value) (cons value (plist-get plist key))
2551 (append value (plist-get plist key))))))))
2552 ;; Return new communication channel.
2553 (org-combine-plists info plist)))
2557 ;;; Core functions
2559 ;; This is the room for the main function, `org-export-as', along with
2560 ;; its derivative, `org-export-string-as'.
2561 ;; `org-export--copy-to-kill-ring-p' determines if output of these
2562 ;; function should be added to kill ring.
2564 ;; Note that `org-export-as' doesn't really parse the current buffer,
2565 ;; but a copy of it (with the same buffer-local variables and
2566 ;; visibility), where macros and include keywords are expanded and
2567 ;; Babel blocks are executed, if appropriate.
2568 ;; `org-export-with-buffer-copy' macro prepares that copy.
2570 ;; File inclusion is taken care of by
2571 ;; `org-export-expand-include-keyword' and
2572 ;; `org-export--prepare-file-contents'. Structure wise, including
2573 ;; a whole Org file in a buffer often makes little sense. For
2574 ;; example, if the file contains a headline and the include keyword
2575 ;; was within an item, the item should contain the headline. That's
2576 ;; why file inclusion should be done before any structure can be
2577 ;; associated to the file, that is before parsing.
2579 ;; `org-export-insert-default-template' is a command to insert
2580 ;; a default template (or a back-end specific template) at point or in
2581 ;; current subtree.
2583 (defun org-export-copy-buffer ()
2584 "Return a copy of the current buffer.
2585 The copy preserves Org buffer-local variables, visibility and
2586 narrowing."
2587 (let ((copy-buffer-fun (org-export--generate-copy-script (current-buffer)))
2588 (new-buf (generate-new-buffer (buffer-name))))
2589 (with-current-buffer new-buf
2590 (funcall copy-buffer-fun)
2591 (set-buffer-modified-p nil))
2592 new-buf))
2594 (defmacro org-export-with-buffer-copy (&rest body)
2595 "Apply BODY in a copy of the current buffer.
2596 The copy preserves local variables, visibility and contents of
2597 the original buffer. Point is at the beginning of the buffer
2598 when BODY is applied."
2599 (declare (debug t))
2600 (org-with-gensyms (buf-copy)
2601 `(let ((,buf-copy (org-export-copy-buffer)))
2602 (unwind-protect
2603 (with-current-buffer ,buf-copy
2604 (goto-char (point-min))
2605 (progn ,@body))
2606 (and (buffer-live-p ,buf-copy)
2607 ;; Kill copy without confirmation.
2608 (progn (with-current-buffer ,buf-copy
2609 (restore-buffer-modified-p nil))
2610 (kill-buffer ,buf-copy)))))))
2612 (defun org-export--generate-copy-script (buffer)
2613 "Generate a function duplicating BUFFER.
2615 The copy will preserve local variables, visibility, contents and
2616 narrowing of the original buffer. If a region was active in
2617 BUFFER, contents will be narrowed to that region instead.
2619 The resulting function can be evaluated at a later time, from
2620 another buffer, effectively cloning the original buffer there.
2622 The function assumes BUFFER's major mode is `org-mode'."
2623 (with-current-buffer buffer
2624 `(lambda ()
2625 (let ((inhibit-modification-hooks t))
2626 ;; Set major mode. Ignore `org-mode-hook' as it has been run
2627 ;; already in BUFFER.
2628 (let ((org-mode-hook nil) (org-inhibit-startup t)) (org-mode))
2629 ;; Copy specific buffer local variables and variables set
2630 ;; through BIND keywords.
2631 ,@(let ((bound-variables (org-export--list-bound-variables))
2632 vars)
2633 (dolist (entry (buffer-local-variables (buffer-base-buffer)) vars)
2634 (when (consp entry)
2635 (let ((var (car entry))
2636 (val (cdr entry)))
2637 (and (not (memq var org-export-ignored-local-variables))
2638 (or (memq var
2639 '(default-directory
2640 buffer-file-name
2641 buffer-file-coding-system))
2642 (assq var bound-variables)
2643 (string-match "^\\(org-\\|orgtbl-\\)"
2644 (symbol-name var)))
2645 ;; Skip unreadable values, as they cannot be
2646 ;; sent to external process.
2647 (or (not val) (ignore-errors (read (format "%S" val))))
2648 (push `(set (make-local-variable (quote ,var))
2649 (quote ,val))
2650 vars))))))
2651 ;; Whole buffer contents.
2652 (insert
2653 ,(org-with-wide-buffer
2654 (buffer-substring-no-properties
2655 (point-min) (point-max))))
2656 ;; Narrowing.
2657 ,(if (org-region-active-p)
2658 `(narrow-to-region ,(region-beginning) ,(region-end))
2659 `(narrow-to-region ,(point-min) ,(point-max)))
2660 ;; Current position of point.
2661 (goto-char ,(point))
2662 ;; Overlays with invisible property.
2663 ,@(let (ov-set)
2664 (dolist (ov (overlays-in (point-min) (point-max)) ov-set)
2665 (let ((invis-prop (overlay-get ov 'invisible)))
2666 (when invis-prop
2667 (push `(overlay-put
2668 (make-overlay ,(overlay-start ov)
2669 ,(overlay-end ov))
2670 'invisible (quote ,invis-prop))
2671 ov-set)))))))))
2673 (defun org-export--delete-comments ()
2674 "Delete commented areas in the buffer.
2675 Commented areas are comments, comment blocks, commented trees and
2676 inlinetasks. Trailing blank lines after a comment or a comment
2677 block are removed, as long as it doesn't alter the structure of
2678 the document. Narrowing, if any, is ignored."
2679 (org-with-wide-buffer
2680 (goto-char (point-min))
2681 (let* ((case-fold-search t)
2682 (comment-re "^[ \t]*#\\(?: \\|$\\|\\+end_comment\\)")
2683 (regexp (concat org-outline-regexp-bol ".*" org-comment-string "\\|"
2684 comment-re)))
2685 (while (re-search-forward regexp nil t)
2686 (let ((element (org-element-at-point)))
2687 (pcase (org-element-type element)
2688 ((or `headline `inlinetask)
2689 (when (org-element-property :commentedp element)
2690 (delete-region (org-element-property :begin element)
2691 (org-element-property :end element))))
2692 ((or `comment `comment-block)
2693 (let* ((parent (org-element-property :parent element))
2694 (start (org-element-property :begin element))
2695 (end (org-element-property :end element))
2696 ;; We remove trailing blank lines. Doing so could
2697 ;; modify the structure of the document. Therefore
2698 ;; we ensure that any comment between elements is
2699 ;; replaced with one empty line, so as to keep them
2700 ;; separated.
2701 (add-blank?
2702 (save-excursion
2703 (goto-char start)
2704 (not (or (bobp)
2705 (eq (org-element-property :contents-begin parent)
2706 start)
2707 (eq (org-element-property :contents-end parent)
2708 end)
2709 (progn
2710 (forward-line -1)
2711 (or (looking-at-p "^[ \t]*$")
2712 (org-with-limited-levels
2713 (org-at-heading-p)))))))))
2714 (delete-region start end)
2715 (when add-blank? (insert "\n"))))))))))
2717 (defun org-export--prune-tree (data info)
2718 "Prune non exportable elements from DATA.
2719 DATA is the parse tree to traverse. INFO is the plist holding
2720 export info. Also set `:ignore-list' in INFO to a list of
2721 objects which should be ignored during export, but not removed
2722 from tree."
2723 (letrec ((ignore nil)
2724 ;; First find trees containing a select tag, if any.
2725 (selected (org-export--selected-trees data info))
2726 (walk-data
2727 (lambda (data)
2728 ;; Prune non-exportable elements and objects from tree.
2729 ;; As a special case, special rows and cells from tables
2730 ;; are stored in IGNORE, as they still need to be
2731 ;; accessed during export.
2732 (when data
2733 (let ((type (org-element-type data)))
2734 (if (org-export--skip-p data info selected)
2735 (if (memq type '(table-cell table-row)) (push data ignore)
2736 (org-element-extract-element data))
2737 (if (and (eq type 'headline)
2738 (eq (plist-get info :with-archived-trees)
2739 'headline)
2740 (org-element-property :archivedp data))
2741 ;; If headline is archived but tree below has
2742 ;; to be skipped, remove contents.
2743 (org-element-set-contents data)
2744 ;; Move into recursive objects/elements.
2745 (mapc walk-data (org-element-contents data)))
2746 ;; Move into secondary string, if any.
2747 (dolist (p (cdr (assq type
2748 org-element-secondary-value-alist)))
2749 (mapc walk-data (org-element-property p data))))))))
2750 (definitions
2751 ;; Collect definitions before possibly pruning them so as
2752 ;; to avoid parsing them again if they are required.
2753 (org-element-map data '(footnote-definition footnote-reference)
2754 (lambda (f)
2755 (cond
2756 ((eq (org-element-type f) 'footnote-definition) f)
2757 ((eq (org-element-property :type f) 'standard) nil)
2758 (t (let ((label (org-element-property :label f)))
2759 (when label ;Skip anonymous references.
2760 (apply
2761 #'org-element-create
2762 'footnote-definition `(:label ,label :post-blank 1)
2763 (org-element-contents f))))))))))
2764 ;; If a select tag is active, also ignore the section before the
2765 ;; first headline, if any.
2766 (when selected
2767 (let ((first-element (car (org-element-contents data))))
2768 (when (eq (org-element-type first-element) 'section)
2769 (org-element-extract-element first-element))))
2770 ;; Prune tree and communication channel.
2771 (funcall walk-data data)
2772 (dolist (entry (append
2773 ;; Priority is given to back-end specific options.
2774 (org-export-get-all-options (plist-get info :back-end))
2775 org-export-options-alist))
2776 (when (eq (nth 4 entry) 'parse)
2777 (funcall walk-data (plist-get info (car entry)))))
2778 (let ((missing (org-export--missing-definitions data definitions)))
2779 (funcall walk-data missing)
2780 (org-export--install-footnote-definitions missing data))
2781 ;; Eventually set `:ignore-list'.
2782 (plist-put info :ignore-list ignore)))
2784 (defun org-export--missing-definitions (tree definitions)
2785 "List footnote definitions missing from TREE.
2786 Missing definitions are searched within DEFINITIONS, which is
2787 a list of footnote definitions or in the widened buffer."
2788 (let* ((list-labels
2789 (lambda (data)
2790 ;; List all footnote labels encountered in DATA. Inline
2791 ;; footnote references are ignored.
2792 (org-element-map data 'footnote-reference
2793 (lambda (reference)
2794 (and (eq (org-element-property :type reference) 'standard)
2795 (org-element-property :label reference))))))
2796 defined undefined missing-definitions)
2797 ;; Partition DIRECT-REFERENCES between DEFINED and UNDEFINED
2798 ;; references.
2799 (let ((known-definitions
2800 (org-element-map tree '(footnote-reference footnote-definition)
2801 (lambda (f)
2802 (and (or (eq (org-element-type f) 'footnote-definition)
2803 (eq (org-element-property :type f) 'inline))
2804 (org-element-property :label f)))))
2805 seen)
2806 (dolist (l (funcall list-labels tree))
2807 (cond ((member l seen))
2808 ((member l known-definitions) (push l defined))
2809 (t (push l undefined)))))
2810 ;; Complete MISSING-DEFINITIONS by finding the definition of every
2811 ;; undefined label, first by looking into DEFINITIONS, then by
2812 ;; searching the widened buffer. This is a recursive process
2813 ;; since definitions found can themselves contain an undefined
2814 ;; reference.
2815 (while undefined
2816 (let* ((label (pop undefined))
2817 (definition
2818 (cond
2819 ((cl-some
2820 (lambda (d) (and (equal (org-element-property :label d) label)
2822 definitions))
2823 ((pcase (org-footnote-get-definition label)
2824 (`(,_ ,beg . ,_)
2825 (org-with-wide-buffer
2826 (goto-char beg)
2827 (let ((datum (org-element-context)))
2828 (if (eq (org-element-type datum) 'footnote-reference)
2829 datum
2830 ;; Parse definition with contents.
2831 (save-restriction
2832 (narrow-to-region
2833 (org-element-property :begin datum)
2834 (org-element-property :end datum))
2835 (org-element-map (org-element-parse-buffer)
2836 'footnote-definition #'identity nil t))))))
2837 (_ nil)))
2838 (t (user-error "Definition not found for footnote %s" label)))))
2839 (push label defined)
2840 (push definition missing-definitions)
2841 ;; Look for footnote references within DEFINITION, since
2842 ;; we may need to also find their definition.
2843 (dolist (l (funcall list-labels definition))
2844 (unless (or (member l defined) ;Known label
2845 (member l undefined)) ;Processed later
2846 (push l undefined)))))
2847 ;; MISSING-DEFINITIONS may contain footnote references with inline
2848 ;; definitions. Make sure those are changed into real footnote
2849 ;; definitions.
2850 (mapcar (lambda (d)
2851 (if (eq (org-element-type d) 'footnote-definition) d
2852 (let ((label (org-element-property :label d)))
2853 (apply #'org-element-create
2854 'footnote-definition `(:label ,label :post-blank 1)
2855 (org-element-contents d)))))
2856 missing-definitions)))
2858 (defun org-export--install-footnote-definitions (definitions tree)
2859 "Install footnote definitions in tree.
2861 DEFINITIONS is the list of footnote definitions to install. TREE
2862 is the parse tree.
2864 If there is a footnote section in TREE, definitions found are
2865 appended to it. If `org-footnote-section' is non-nil, a new
2866 footnote section containing all definitions is inserted in TREE.
2867 Otherwise, definitions are appended at the end of the section
2868 containing their first reference."
2869 (cond
2870 ((null definitions))
2871 ;; If there is a footnote section, insert definitions there.
2872 ((let ((footnote-section
2873 (org-element-map tree 'headline
2874 (lambda (h) (and (org-element-property :footnote-section-p h) h))
2875 nil t)))
2876 (and footnote-section
2877 (apply #'org-element-adopt-elements
2878 footnote-section
2879 (nreverse definitions)))))
2880 ;; If there should be a footnote section, create one containing all
2881 ;; the definitions at the end of the tree.
2882 (org-footnote-section
2883 (org-element-adopt-elements
2884 tree
2885 (org-element-create 'headline
2886 (list :footnote-section-p t
2887 :level 1
2888 :title org-footnote-section)
2889 (apply #'org-element-create
2890 'section
2892 (nreverse definitions)))))
2893 ;; Otherwise add each definition at the end of the section where it
2894 ;; is first referenced.
2896 (letrec ((seen nil)
2897 (insert-definitions
2898 (lambda (data)
2899 ;; Insert footnote definitions in the same section as
2900 ;; their first reference in DATA.
2901 (org-element-map data 'footnote-reference
2902 (lambda (reference)
2903 (when (eq (org-element-property :type reference) 'standard)
2904 (let ((label (org-element-property :label reference)))
2905 (unless (member label seen)
2906 (push label seen)
2907 (let ((definition
2908 (cl-some
2909 (lambda (d)
2910 (and (equal (org-element-property :label d)
2911 label)
2913 definitions)))
2914 (org-element-adopt-elements
2915 (org-element-lineage reference '(section))
2916 definition)
2917 ;; Also insert definitions for nested
2918 ;; references, if any.
2919 (funcall insert-definitions definition))))))))))
2920 (funcall insert-definitions tree)))))
2922 (defun org-export--remove-uninterpreted-data (data info)
2923 "Change uninterpreted elements back into Org syntax.
2924 DATA is the parse tree. INFO is a plist containing export
2925 options. Each uninterpreted element or object is changed back
2926 into a string. Contents, if any, are not modified. The parse
2927 tree is modified by side effect."
2928 (org-export--remove-uninterpreted-data-1 data info)
2929 (dolist (entry org-export-options-alist)
2930 (when (eq (nth 4 entry) 'parse)
2931 (let ((p (car entry)))
2932 (plist-put info
2934 (org-export--remove-uninterpreted-data-1
2935 (plist-get info p)
2936 info))))))
2938 (defun org-export--remove-uninterpreted-data-1 (data info)
2939 "Change uninterpreted elements back into Org syntax.
2940 DATA is a parse tree or a secondary string. INFO is a plist
2941 containing export options. It is modified by side effect and
2942 returned by the function."
2943 (org-element-map data
2944 '(entity bold italic latex-environment latex-fragment strike-through
2945 subscript superscript underline)
2946 (lambda (blob)
2947 (let ((new
2948 (cl-case (org-element-type blob)
2949 ;; ... entities...
2950 (entity
2951 (and (not (plist-get info :with-entities))
2952 (list (concat
2953 (org-export-expand blob nil)
2954 (make-string
2955 (or (org-element-property :post-blank blob) 0)
2956 ?\s)))))
2957 ;; ... emphasis...
2958 ((bold italic strike-through underline)
2959 (and (not (plist-get info :with-emphasize))
2960 (let ((marker (cl-case (org-element-type blob)
2961 (bold "*")
2962 (italic "/")
2963 (strike-through "+")
2964 (underline "_"))))
2965 (append
2966 (list marker)
2967 (org-element-contents blob)
2968 (list (concat
2969 marker
2970 (make-string
2971 (or (org-element-property :post-blank blob)
2973 ?\s)))))))
2974 ;; ... LaTeX environments and fragments...
2975 ((latex-environment latex-fragment)
2976 (and (eq (plist-get info :with-latex) 'verbatim)
2977 (list (org-export-expand blob nil))))
2978 ;; ... sub/superscripts...
2979 ((subscript superscript)
2980 (let ((sub/super-p (plist-get info :with-sub-superscript))
2981 (bracketp (org-element-property :use-brackets-p blob)))
2982 (and (or (not sub/super-p)
2983 (and (eq sub/super-p '{}) (not bracketp)))
2984 (append
2985 (list (concat
2986 (if (eq (org-element-type blob) 'subscript)
2988 "^")
2989 (and bracketp "{")))
2990 (org-element-contents blob)
2991 (list (concat
2992 (and bracketp "}")
2993 (and (org-element-property :post-blank blob)
2994 (make-string
2995 (org-element-property :post-blank blob)
2996 ?\s)))))))))))
2997 (when new
2998 ;; Splice NEW at BLOB location in parse tree.
2999 (dolist (e new (org-element-extract-element blob))
3000 (unless (equal e "") (org-element-insert-before e blob))))))
3001 info nil nil t)
3002 ;; Return modified parse tree.
3003 data)
3005 ;;;###autoload
3006 (defun org-export-as
3007 (backend &optional subtreep visible-only body-only ext-plist)
3008 "Transcode current Org buffer into BACKEND code.
3010 BACKEND is either an export back-end, as returned by, e.g.,
3011 `org-export-create-backend', or a symbol referring to
3012 a registered back-end.
3014 If narrowing is active in the current buffer, only transcode its
3015 narrowed part.
3017 If a region is active, transcode that region.
3019 When optional argument SUBTREEP is non-nil, transcode the
3020 sub-tree at point, extracting information from the headline
3021 properties first.
3023 When optional argument VISIBLE-ONLY is non-nil, don't export
3024 contents of hidden elements.
3026 When optional argument BODY-ONLY is non-nil, only return body
3027 code, without surrounding template.
3029 Optional argument EXT-PLIST, when provided, is a property list
3030 with external parameters overriding Org default settings, but
3031 still inferior to file-local settings.
3033 Return code as a string."
3034 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
3035 (org-export-barf-if-invalid-backend backend)
3036 (save-excursion
3037 (save-restriction
3038 ;; Narrow buffer to an appropriate region or subtree for
3039 ;; parsing. If parsing subtree, be sure to remove main
3040 ;; headline, planning data and property drawer.
3041 (cond ((org-region-active-p)
3042 (narrow-to-region (region-beginning) (region-end)))
3043 (subtreep
3044 (org-narrow-to-subtree)
3045 (goto-char (point-min))
3046 (org-end-of-meta-data)
3047 (narrow-to-region (point) (point-max))))
3048 ;; Initialize communication channel with original buffer
3049 ;; attributes, unavailable in its copy.
3050 (let* ((org-export-current-backend (org-export-backend-name backend))
3051 (info (org-combine-plists
3052 (org-export--get-export-attributes
3053 backend subtreep visible-only body-only)
3054 (org-export--get-buffer-attributes)))
3055 (parsed-keywords
3056 (delq nil
3057 (mapcar (lambda (o) (and (eq (nth 4 o) 'parse) (nth 1 o)))
3058 (append (org-export-get-all-options backend)
3059 org-export-options-alist))))
3060 tree)
3061 ;; Update communication channel and get parse tree. Buffer
3062 ;; isn't parsed directly. Instead, all buffer modifications
3063 ;; and consequent parsing are undertaken in a temporary copy.
3064 (org-export-with-buffer-copy
3065 ;; Run first hook with current back-end's name as argument.
3066 (run-hook-with-args 'org-export-before-processing-hook
3067 (org-export-backend-name backend))
3068 ;; Include files, delete comments and expand macros.
3069 (org-export-expand-include-keyword)
3070 (org-export--delete-comments)
3071 (org-macro-initialize-templates)
3072 (org-macro-replace-all
3073 (append org-macro-templates org-export-global-macros)
3074 nil parsed-keywords)
3075 ;; Refresh buffer properties and radio targets after
3076 ;; potentially invasive previous changes. Likewise, do it
3077 ;; again after executing Babel code.
3078 (org-set-regexps-and-options)
3079 (org-update-radio-target-regexp)
3080 (when org-export-use-babel
3081 (org-babel-exp-process-buffer)
3082 (org-set-regexps-and-options)
3083 (org-update-radio-target-regexp))
3084 ;; Run last hook with current back-end's name as argument.
3085 ;; Update buffer properties and radio targets one last time
3086 ;; before parsing.
3087 (goto-char (point-min))
3088 (save-excursion
3089 (run-hook-with-args 'org-export-before-parsing-hook
3090 (org-export-backend-name backend)))
3091 (org-set-regexps-and-options)
3092 (org-update-radio-target-regexp)
3093 ;; Update communication channel with environment. Also
3094 ;; install user's and developer's filters.
3095 (setq info
3096 (org-export-install-filters
3097 (org-combine-plists
3098 info (org-export-get-environment backend subtreep ext-plist))))
3099 ;; Call options filters and update export options. We do not
3100 ;; use `org-export-filter-apply-functions' here since the
3101 ;; arity of such filters is different.
3102 (let ((backend-name (org-export-backend-name backend)))
3103 (dolist (filter (plist-get info :filter-options))
3104 (let ((result (funcall filter info backend-name)))
3105 (when result (setq info result)))))
3106 ;; Expand export-specific set of macros: {{{author}}},
3107 ;; {{{date(FORMAT)}}}, {{{email}}} and {{{title}}}. It must
3108 ;; be done once regular macros have been expanded, since
3109 ;; parsed keywords may contain one of them.
3110 (org-macro-replace-all
3111 (list
3112 (cons "author" (org-element-interpret-data (plist-get info :author)))
3113 (cons "date"
3114 (let* ((date (plist-get info :date))
3115 (value (or (org-element-interpret-data date) "")))
3116 (if (and (consp date)
3117 (not (cdr date))
3118 (eq (org-element-type (car date)) 'timestamp))
3119 (format "(eval (if (org-string-nw-p \"$1\") %s %S))"
3120 (format "(org-timestamp-format '%S \"$1\")"
3121 (org-element-copy (car date)))
3122 value)
3123 value)))
3124 (cons "email" (org-element-interpret-data (plist-get info :email)))
3125 (cons "title" (org-element-interpret-data (plist-get info :title)))
3126 (cons "results" "$1"))
3127 'finalize
3128 parsed-keywords)
3129 ;; Parse buffer.
3130 (setq tree (org-element-parse-buffer nil visible-only))
3131 ;; Prune tree from non-exported elements and transform
3132 ;; uninterpreted elements or objects in both parse tree and
3133 ;; communication channel.
3134 (org-export--prune-tree tree info)
3135 (org-export--remove-uninterpreted-data tree info)
3136 ;; Call parse tree filters.
3137 (setq tree
3138 (org-export-filter-apply-functions
3139 (plist-get info :filter-parse-tree) tree info))
3140 ;; Now tree is complete, compute its properties and add them
3141 ;; to communication channel.
3142 (setq info (org-export--collect-tree-properties tree info))
3143 ;; Eventually transcode TREE. Wrap the resulting string into
3144 ;; a template.
3145 (let* ((body (org-element-normalize-string
3146 (or (org-export-data tree info) "")))
3147 (inner-template (cdr (assq 'inner-template
3148 (plist-get info :translate-alist))))
3149 (full-body (org-export-filter-apply-functions
3150 (plist-get info :filter-body)
3151 (if (not (functionp inner-template)) body
3152 (funcall inner-template body info))
3153 info))
3154 (template (cdr (assq 'template
3155 (plist-get info :translate-alist)))))
3156 ;; Remove all text properties since they cannot be
3157 ;; retrieved from an external process. Finally call
3158 ;; final-output filter and return result.
3159 (org-no-properties
3160 (org-export-filter-apply-functions
3161 (plist-get info :filter-final-output)
3162 (if (or (not (functionp template)) body-only) full-body
3163 (funcall template full-body info))
3164 info))))))))
3166 ;;;###autoload
3167 (defun org-export-string-as (string backend &optional body-only ext-plist)
3168 "Transcode STRING into BACKEND code.
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.
3174 When optional argument BODY-ONLY is non-nil, only return body
3175 code, without preamble nor postamble.
3177 Optional argument EXT-PLIST, when provided, is a property list
3178 with external parameters overriding Org default settings, but
3179 still inferior to file-local settings.
3181 Return code as a string."
3182 (with-temp-buffer
3183 (insert string)
3184 (let ((org-inhibit-startup t)) (org-mode))
3185 (org-export-as backend nil nil body-only ext-plist)))
3187 ;;;###autoload
3188 (defun org-export-replace-region-by (backend)
3189 "Replace the active region by its export to BACKEND.
3190 BACKEND is either an export back-end, as returned by, e.g.,
3191 `org-export-create-backend', or a symbol referring to
3192 a registered back-end."
3193 (unless (org-region-active-p) (user-error "No active region to replace"))
3194 (insert
3195 (org-export-string-as
3196 (delete-and-extract-region (region-beginning) (region-end)) backend t)))
3198 ;;;###autoload
3199 (defun org-export-insert-default-template (&optional backend subtreep)
3200 "Insert all export keywords with default values at beginning of line.
3202 BACKEND is a symbol referring to the name of a registered export
3203 back-end, for which specific export options should be added to
3204 the template, or `default' for default template. When it is nil,
3205 the user will be prompted for a category.
3207 If SUBTREEP is non-nil, export configuration will be set up
3208 locally for the subtree through node properties."
3209 (interactive)
3210 (unless (derived-mode-p 'org-mode) (user-error "Not in an Org mode buffer"))
3211 (when (and subtreep (org-before-first-heading-p))
3212 (user-error "No subtree to set export options for"))
3213 (let ((node (and subtreep (save-excursion (org-back-to-heading t) (point))))
3214 (backend
3215 (or backend
3216 (intern
3217 (org-completing-read
3218 "Options category: "
3219 (cons "default"
3220 (mapcar (lambda (b)
3221 (symbol-name (org-export-backend-name b)))
3222 org-export-registered-backends))
3223 nil t))))
3224 options keywords)
3225 ;; Populate OPTIONS and KEYWORDS.
3226 (dolist (entry (cond ((eq backend 'default) org-export-options-alist)
3227 ((org-export-backend-p backend)
3228 (org-export-backend-options backend))
3229 (t (org-export-backend-options
3230 (org-export-get-backend backend)))))
3231 (let ((keyword (nth 1 entry))
3232 (option (nth 2 entry)))
3233 (cond
3234 (keyword (unless (assoc keyword keywords)
3235 (let ((value
3236 (if (eq (nth 4 entry) 'split)
3237 (mapconcat #'identity (eval (nth 3 entry)) " ")
3238 (eval (nth 3 entry)))))
3239 (push (cons keyword value) keywords))))
3240 (option (unless (assoc option options)
3241 (push (cons option (eval (nth 3 entry))) options))))))
3242 ;; Move to an appropriate location in order to insert options.
3243 (unless subtreep (beginning-of-line))
3244 ;; First (multiple) OPTIONS lines. Never go past fill-column.
3245 (when options
3246 (let ((items
3247 (mapcar
3248 #'(lambda (opt) (format "%s:%S" (car opt) (cdr opt)))
3249 (sort options (lambda (k1 k2) (string< (car k1) (car k2)))))))
3250 (if subtreep
3251 (org-entry-put
3252 node "EXPORT_OPTIONS" (mapconcat 'identity items " "))
3253 (while items
3254 (insert "#+OPTIONS:")
3255 (let ((width 10))
3256 (while (and items
3257 (< (+ width (length (car items)) 1) fill-column))
3258 (let ((item (pop items)))
3259 (insert " " item)
3260 (cl-incf width (1+ (length item))))))
3261 (insert "\n")))))
3262 ;; Then the rest of keywords, in the order specified in either
3263 ;; `org-export-options-alist' or respective export back-ends.
3264 (dolist (key (nreverse keywords))
3265 (let ((val (cond ((equal (car key) "DATE")
3266 (or (cdr key)
3267 (with-temp-buffer
3268 (org-insert-time-stamp (current-time)))))
3269 ((equal (car key) "TITLE")
3270 (or (let ((visited-file
3271 (buffer-file-name (buffer-base-buffer))))
3272 (and visited-file
3273 (file-name-sans-extension
3274 (file-name-nondirectory visited-file))))
3275 (buffer-name (buffer-base-buffer))))
3276 (t (cdr key)))))
3277 (if subtreep (org-entry-put node (concat "EXPORT_" (car key)) val)
3278 (insert
3279 (format "#+%s:%s\n"
3280 (car key)
3281 (if (org-string-nw-p val) (format " %s" val) ""))))))))
3283 (defun org-export-expand-include-keyword (&optional included dir footnotes)
3284 "Expand every include keyword in buffer.
3285 Optional argument INCLUDED is a list of included file names along
3286 with their line restriction, when appropriate. It is used to
3287 avoid infinite recursion. Optional argument DIR is the current
3288 working directory. It is used to properly resolve relative
3289 paths. Optional argument FOOTNOTES is a hash-table used for
3290 storing and resolving footnotes. It is created automatically."
3291 (let ((case-fold-search t)
3292 (file-prefix (make-hash-table :test #'equal))
3293 (current-prefix 0)
3294 (footnotes (or footnotes (make-hash-table :test #'equal)))
3295 (include-re "^[ \t]*#\\+INCLUDE:"))
3296 ;; If :minlevel is not set the text-property
3297 ;; `:org-include-induced-level' will be used to determine the
3298 ;; relative level when expanding INCLUDE.
3299 ;; Only affects included Org documents.
3300 (goto-char (point-min))
3301 (while (re-search-forward include-re nil t)
3302 (put-text-property (line-beginning-position) (line-end-position)
3303 :org-include-induced-level
3304 (1+ (org-reduced-level (or (org-current-level) 0)))))
3305 ;; Expand INCLUDE keywords.
3306 (goto-char (point-min))
3307 (while (re-search-forward include-re nil t)
3308 (let ((element (save-match-data (org-element-at-point))))
3309 (when (eq (org-element-type element) 'keyword)
3310 (beginning-of-line)
3311 ;; Extract arguments from keyword's value.
3312 (let* ((value (org-element-property :value element))
3313 (ind (org-get-indentation))
3314 location
3315 (file
3316 (and (string-match
3317 "^\\(\".+?\"\\|\\S-+\\)\\(?:\\s-+\\|$\\)" value)
3318 (prog1
3319 (save-match-data
3320 (let ((matched (match-string 1 value)))
3321 (when (string-match "\\(::\\(.*?\\)\\)\"?\\'"
3322 matched)
3323 (setq location (match-string 2 matched))
3324 (setq matched
3325 (replace-match "" nil nil matched 1)))
3326 (expand-file-name
3327 (org-unbracket-string "\"" "\"" matched)
3328 dir)))
3329 (setq value (replace-match "" nil nil value)))))
3330 (only-contents
3331 (and (string-match ":only-contents *\\([^: \r\t\n]\\S-*\\)?"
3332 value)
3333 (prog1 (org-not-nil (match-string 1 value))
3334 (setq value (replace-match "" nil nil value)))))
3335 (lines
3336 (and (string-match
3337 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\""
3338 value)
3339 (prog1 (match-string 1 value)
3340 (setq value (replace-match "" nil nil value)))))
3341 (env (cond
3342 ((string-match "\\<example\\>" value) 'literal)
3343 ((string-match "\\<export\\(?: +\\(.*\\)\\)?" value)
3344 'literal)
3345 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
3346 'literal)))
3347 ;; Minimal level of included file defaults to the child
3348 ;; level of the current headline, if any, or one. It
3349 ;; only applies is the file is meant to be included as
3350 ;; an Org one.
3351 (minlevel
3352 (and (not env)
3353 (if (string-match ":minlevel +\\([0-9]+\\)" value)
3354 (prog1 (string-to-number (match-string 1 value))
3355 (setq value (replace-match "" nil nil value)))
3356 (get-text-property (point)
3357 :org-include-induced-level))))
3358 (args (and (eq env 'literal) (match-string 1 value)))
3359 (block (and (string-match "\\<\\(\\S-+\\)\\>" value)
3360 (match-string 1 value))))
3361 ;; Remove keyword.
3362 (delete-region (point) (line-beginning-position 2))
3363 (cond
3364 ((not file) nil)
3365 ((not (file-readable-p file))
3366 (error "Cannot include file %s" file))
3367 ;; Check if files has already been parsed. Look after
3368 ;; inclusion lines too, as different parts of the same file
3369 ;; can be included too.
3370 ((member (list file lines) included)
3371 (error "Recursive file inclusion: %s" file))
3373 (cond
3374 ((eq env 'literal)
3375 (insert
3376 (let ((ind-str (make-string ind ?\s))
3377 (arg-str (if (stringp args) (format " %s" args) ""))
3378 (contents
3379 (org-escape-code-in-string
3380 (org-export--prepare-file-contents file lines))))
3381 (format "%s#+BEGIN_%s%s\n%s%s#+END_%s\n"
3382 ind-str block arg-str contents ind-str block))))
3383 ((stringp block)
3384 (insert
3385 (let ((ind-str (make-string ind ?\s))
3386 (contents
3387 (org-export--prepare-file-contents file lines)))
3388 (format "%s#+BEGIN_%s\n%s%s#+END_%s\n"
3389 ind-str block contents ind-str block))))
3391 (insert
3392 (with-temp-buffer
3393 (let ((org-inhibit-startup t)
3394 (lines
3395 (if location
3396 (org-export--inclusion-absolute-lines
3397 file location only-contents lines)
3398 lines)))
3399 (org-mode)
3400 (insert
3401 (org-export--prepare-file-contents
3402 file lines ind minlevel
3403 (or (gethash file file-prefix)
3404 (puthash file (cl-incf current-prefix) file-prefix))
3405 footnotes)))
3406 (org-export-expand-include-keyword
3407 (cons (list file lines) included)
3408 (file-name-directory file)
3409 footnotes)
3410 (buffer-string)))))
3411 ;; Expand footnotes after all files have been included.
3412 ;; Footnotes are stored at end of buffer.
3413 (unless included
3414 (org-with-wide-buffer
3415 (goto-char (point-max))
3416 (maphash (lambda (k v) (insert (format "\n[fn:%s] %s\n" k v)))
3417 footnotes)))))))))))
3419 (defun org-export--inclusion-absolute-lines (file location only-contents lines)
3420 "Resolve absolute lines for an included file with file-link.
3422 FILE is string file-name of the file to include. LOCATION is a
3423 string name within FILE to be included (located via
3424 `org-link-search'). If ONLY-CONTENTS is non-nil only the
3425 contents of the named element will be included, as determined
3426 Org-Element. If LINES is non-nil only those lines are included.
3428 Return a string of lines to be included in the format expected by
3429 `org-export--prepare-file-contents'."
3430 (with-temp-buffer
3431 (insert-file-contents file)
3432 (unless (eq major-mode 'org-mode)
3433 (let ((org-inhibit-startup t)) (org-mode)))
3434 (condition-case err
3435 ;; Enforce consistent search.
3436 (let ((org-link-search-must-match-exact-headline nil))
3437 (org-link-search location))
3438 (error
3439 (error "%s for %s::%s" (error-message-string err) file location)))
3440 (let* ((element (org-element-at-point))
3441 (contents-begin
3442 (and only-contents (org-element-property :contents-begin element))))
3443 (narrow-to-region
3444 (or contents-begin (org-element-property :begin element))
3445 (org-element-property (if contents-begin :contents-end :end) element))
3446 (when (and only-contents
3447 (memq (org-element-type element) '(headline inlinetask)))
3448 ;; Skip planning line and property-drawer.
3449 (goto-char (point-min))
3450 (when (looking-at-p org-planning-line-re) (forward-line))
3451 (when (looking-at org-property-drawer-re) (goto-char (match-end 0)))
3452 (unless (bolp) (forward-line))
3453 (narrow-to-region (point) (point-max))))
3454 (when lines
3455 (org-skip-whitespace)
3456 (beginning-of-line)
3457 (let* ((lines (split-string lines "-"))
3458 (lbeg (string-to-number (car lines)))
3459 (lend (string-to-number (cadr lines)))
3460 (beg (if (zerop lbeg) (point-min)
3461 (goto-char (point-min))
3462 (forward-line (1- lbeg))
3463 (point)))
3464 (end (if (zerop lend) (point-max)
3465 (goto-char beg)
3466 (forward-line (1- lend))
3467 (point))))
3468 (narrow-to-region beg end)))
3469 (let ((end (point-max)))
3470 (goto-char (point-min))
3471 (widen)
3472 (let ((start-line (line-number-at-pos)))
3473 (format "%d-%d"
3474 start-line
3475 (save-excursion
3476 (+ start-line
3477 (let ((counter 0))
3478 (while (< (point) end) (cl-incf counter) (forward-line))
3479 counter))))))))
3481 (defun org-export--prepare-file-contents
3482 (file &optional lines ind minlevel id footnotes)
3483 "Prepare contents of FILE for inclusion and return it as a string.
3485 When optional argument LINES is a string specifying a range of
3486 lines, include only those lines.
3488 Optional argument IND, when non-nil, is an integer specifying the
3489 global indentation of returned contents. Since its purpose is to
3490 allow an included file to stay in the same environment it was
3491 created (e.g., a list item), it doesn't apply past the first
3492 headline encountered.
3494 Optional argument MINLEVEL, when non-nil, is an integer
3495 specifying the level that any top-level headline in the included
3496 file should have.
3498 Optional argument ID is an integer that will be inserted before
3499 each footnote definition and reference if FILE is an Org file.
3500 This is useful to avoid conflicts when more than one Org file
3501 with footnotes is included in a document.
3503 Optional argument FOOTNOTES is a hash-table to store footnotes in
3504 the included document."
3505 (with-temp-buffer
3506 (insert-file-contents file)
3507 (when lines
3508 (let* ((lines (split-string lines "-"))
3509 (lbeg (string-to-number (car lines)))
3510 (lend (string-to-number (cadr lines)))
3511 (beg (if (zerop lbeg) (point-min)
3512 (goto-char (point-min))
3513 (forward-line (1- lbeg))
3514 (point)))
3515 (end (if (zerop lend) (point-max)
3516 (goto-char (point-min))
3517 (forward-line (1- lend))
3518 (point))))
3519 (narrow-to-region beg end)))
3520 ;; Remove blank lines at beginning and end of contents. The logic
3521 ;; behind that removal is that blank lines around include keyword
3522 ;; override blank lines in included file.
3523 (goto-char (point-min))
3524 (org-skip-whitespace)
3525 (beginning-of-line)
3526 (delete-region (point-min) (point))
3527 (goto-char (point-max))
3528 (skip-chars-backward " \r\t\n")
3529 (forward-line)
3530 (delete-region (point) (point-max))
3531 ;; If IND is set, preserve indentation of include keyword until
3532 ;; the first headline encountered.
3533 (when (and ind (> ind 0))
3534 (unless (eq major-mode 'org-mode)
3535 (let ((org-inhibit-startup t)) (org-mode)))
3536 (goto-char (point-min))
3537 (let ((ind-str (make-string ind ?\s)))
3538 (while (not (or (eobp) (looking-at org-outline-regexp-bol)))
3539 ;; Do not move footnote definitions out of column 0.
3540 (unless (and (looking-at org-footnote-definition-re)
3541 (eq (org-element-type (org-element-at-point))
3542 'footnote-definition))
3543 (insert ind-str))
3544 (forward-line))))
3545 ;; When MINLEVEL is specified, compute minimal level for headlines
3546 ;; in the file (CUR-MIN), and remove stars to each headline so
3547 ;; that headlines with minimal level have a level of MINLEVEL.
3548 (when minlevel
3549 (unless (eq major-mode 'org-mode)
3550 (let ((org-inhibit-startup t)) (org-mode)))
3551 (org-with-limited-levels
3552 (let ((levels (org-map-entries
3553 (lambda () (org-reduced-level (org-current-level))))))
3554 (when levels
3555 (let ((offset (- minlevel (apply #'min levels))))
3556 (unless (zerop offset)
3557 (when org-odd-levels-only (setq offset (* offset 2)))
3558 ;; Only change stars, don't bother moving whole
3559 ;; sections.
3560 (org-map-entries
3561 (lambda ()
3562 (if (< offset 0) (delete-char (abs offset))
3563 (insert (make-string offset ?*)))))))))))
3564 ;; Append ID to all footnote references and definitions, so they
3565 ;; become file specific and cannot collide with footnotes in other
3566 ;; included files. Further, collect relevant footnote definitions
3567 ;; outside of LINES, in order to reintroduce them later.
3568 (when id
3569 (let ((marker-min (point-min-marker))
3570 (marker-max (point-max-marker))
3571 (get-new-label
3572 (lambda (label)
3573 ;; Generate new label from LABEL by prefixing it with
3574 ;; "-ID-".
3575 (format "-%d-%s" id label)))
3576 (set-new-label
3577 (lambda (f old new)
3578 ;; Replace OLD label with NEW in footnote F.
3579 (save-excursion
3580 (goto-char (+ (org-element-property :begin f) 4))
3581 (looking-at (regexp-quote old))
3582 (replace-match new))))
3583 (seen-alist))
3584 (goto-char (point-min))
3585 (while (re-search-forward org-footnote-re nil t)
3586 (let ((footnote (save-excursion
3587 (backward-char)
3588 (org-element-context))))
3589 (when (memq (org-element-type footnote)
3590 '(footnote-definition footnote-reference))
3591 (let* ((label (org-element-property :label footnote)))
3592 ;; Update the footnote-reference at point and collect
3593 ;; the new label, which is only used for footnotes
3594 ;; outsides LINES.
3595 (when label
3596 (let ((seen (cdr (assoc label seen-alist))))
3597 (if seen (funcall set-new-label footnote label seen)
3598 (let ((new (funcall get-new-label label)))
3599 (push (cons label new) seen-alist)
3600 (org-with-wide-buffer
3601 (let* ((def (org-footnote-get-definition label))
3602 (beg (nth 1 def)))
3603 (when (and def
3604 (or (< beg marker-min)
3605 (>= beg marker-max)))
3606 ;; Store since footnote-definition is
3607 ;; outside of LINES.
3608 (puthash new
3609 (org-element-normalize-string (nth 3 def))
3610 footnotes))))
3611 (funcall set-new-label footnote label new)))))))))
3612 (set-marker marker-min nil)
3613 (set-marker marker-max nil)))
3614 (org-element-normalize-string (buffer-string))))
3616 (defun org-export--copy-to-kill-ring-p ()
3617 "Return a non-nil value when output should be added to the kill ring.
3618 See also `org-export-copy-to-kill-ring'."
3619 (if (eq org-export-copy-to-kill-ring 'if-interactive)
3620 (not (or executing-kbd-macro noninteractive))
3621 (eq org-export-copy-to-kill-ring t)))
3625 ;;; Tools For Back-Ends
3627 ;; A whole set of tools is available to help build new exporters. Any
3628 ;; function general enough to have its use across many back-ends
3629 ;; should be added here.
3631 ;;;; For Affiliated Keywords
3633 ;; `org-export-read-attribute' reads a property from a given element
3634 ;; as a plist. It can be used to normalize affiliated keywords'
3635 ;; syntax.
3637 ;; Since captions can span over multiple lines and accept dual values,
3638 ;; their internal representation is a bit tricky. Therefore,
3639 ;; `org-export-get-caption' transparently returns a given element's
3640 ;; caption as a secondary string.
3642 (defun org-export-read-attribute (attribute element &optional property)
3643 "Turn ATTRIBUTE property from ELEMENT into a plist.
3645 When optional argument PROPERTY is non-nil, return the value of
3646 that property within attributes.
3648 This function assumes attributes are defined as \":keyword
3649 value\" pairs. It is appropriate for `:attr_html' like
3650 properties.
3652 All values will become strings except the empty string and
3653 \"nil\", which will become nil. Also, values containing only
3654 double quotes will be read as-is, which means that \"\" value
3655 will become the empty string."
3656 (let* ((prepare-value
3657 (lambda (str)
3658 (save-match-data
3659 (cond ((member str '(nil "" "nil")) nil)
3660 ((string-match "^\"\\(\"+\\)?\"$" str)
3661 (or (match-string 1 str) ""))
3662 (t str)))))
3663 (attributes
3664 (let ((value (org-element-property attribute element)))
3665 (when value
3666 (let ((s (mapconcat 'identity value " ")) result)
3667 (while (string-match
3668 "\\(?:^\\|[ \t]+\\)\\(:[-a-zA-Z0-9_]+\\)\\([ \t]+\\|$\\)"
3670 (let ((value (substring s 0 (match-beginning 0))))
3671 (push (funcall prepare-value value) result))
3672 (push (intern (match-string 1 s)) result)
3673 (setq s (substring s (match-end 0))))
3674 ;; Ignore any string before first property with `cdr'.
3675 (cdr (nreverse (cons (funcall prepare-value s) result))))))))
3676 (if property (plist-get attributes property) attributes)))
3678 (defun org-export-get-caption (element &optional shortp)
3679 "Return caption from ELEMENT as a secondary string.
3681 When optional argument SHORTP is non-nil, return short caption,
3682 as a secondary string, instead.
3684 Caption lines are separated by a white space."
3685 (let ((full-caption (org-element-property :caption element)) caption)
3686 (dolist (line full-caption (cdr caption))
3687 (let ((cap (funcall (if shortp 'cdr 'car) line)))
3688 (when cap
3689 (setq caption (nconc (list " ") (copy-sequence cap) caption)))))))
3692 ;;;; For Derived Back-ends
3694 ;; `org-export-with-backend' is a function allowing to locally use
3695 ;; another back-end to transcode some object or element. In a derived
3696 ;; back-end, it may be used as a fall-back function once all specific
3697 ;; cases have been treated.
3699 (defun org-export-with-backend (backend data &optional contents info)
3700 "Call a transcoder from BACKEND on DATA.
3701 BACKEND is an export back-end, as returned by, e.g.,
3702 `org-export-create-backend', or a symbol referring to
3703 a registered back-end. DATA is an Org element, object, secondary
3704 string or string. CONTENTS, when non-nil, is the transcoded
3705 contents of DATA element, as a string. INFO, when non-nil, is
3706 the communication channel used for export, as a plist."
3707 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
3708 (org-export-barf-if-invalid-backend backend)
3709 (let ((type (org-element-type data)))
3710 (when (memq type '(nil org-data)) (error "No foreign transcoder available"))
3711 (let* ((all-transcoders (org-export-get-all-transcoders backend))
3712 (transcoder (cdr (assq type all-transcoders))))
3713 (unless (functionp transcoder) (error "No foreign transcoder available"))
3714 (let ((new-info
3715 (org-combine-plists
3716 info (list
3717 :back-end backend
3718 :translate-alist all-transcoders
3719 :exported-data (make-hash-table :test #'eq :size 401)))))
3720 ;; `:internal-references' are shared across back-ends.
3721 (prog1 (funcall transcoder data contents new-info)
3722 (plist-put info :internal-references
3723 (plist-get new-info :internal-references)))))))
3726 ;;;; For Export Snippets
3728 ;; Every export snippet is transmitted to the back-end. Though, the
3729 ;; latter will only retain one type of export-snippet, ignoring
3730 ;; others, based on the former's target back-end. The function
3731 ;; `org-export-snippet-backend' returns that back-end for a given
3732 ;; export-snippet.
3734 (defun org-export-snippet-backend (export-snippet)
3735 "Return EXPORT-SNIPPET targeted back-end as a symbol.
3736 Translation, with `org-export-snippet-translation-alist', is
3737 applied."
3738 (let ((back-end (org-element-property :back-end export-snippet)))
3739 (intern
3740 (or (cdr (assoc back-end org-export-snippet-translation-alist))
3741 back-end))))
3744 ;;;; For Footnotes
3746 ;; `org-export-collect-footnote-definitions' is a tool to list
3747 ;; actually used footnotes definitions in the whole parse tree, or in
3748 ;; a headline, in order to add footnote listings throughout the
3749 ;; transcoded data.
3751 ;; `org-export-footnote-first-reference-p' is a predicate used by some
3752 ;; back-ends, when they need to attach the footnote definition only to
3753 ;; the first occurrence of the corresponding label.
3755 ;; `org-export-get-footnote-definition' and
3756 ;; `org-export-get-footnote-number' provide easier access to
3757 ;; additional information relative to a footnote reference.
3759 (defun org-export-get-footnote-definition (footnote-reference info)
3760 "Return definition of FOOTNOTE-REFERENCE as parsed data.
3761 INFO is the plist used as a communication channel. If no such
3762 definition can be found, raise an error."
3763 (let ((label (org-element-property :label footnote-reference)))
3764 (if (not label) (org-element-contents footnote-reference)
3765 (let ((cache (or (plist-get info :footnote-definition-cache)
3766 (let ((hash (make-hash-table :test #'equal)))
3767 (plist-put info :footnote-definition-cache hash)
3768 hash))))
3770 (gethash label cache)
3771 (puthash label
3772 (org-element-map (plist-get info :parse-tree)
3773 '(footnote-definition footnote-reference)
3774 (lambda (f)
3775 (cond
3776 ;; Skip any footnote with a different label.
3777 ;; Also skip any standard footnote reference
3778 ;; with the same label since those cannot
3779 ;; contain a definition.
3780 ((not (equal (org-element-property :label f) label)) nil)
3781 ((eq (org-element-property :type f) 'standard) nil)
3782 ((org-element-contents f))
3783 ;; Even if the contents are empty, we can not
3784 ;; return nil since that would eventually raise
3785 ;; the error. Instead, return the equivalent
3786 ;; empty string.
3787 (t "")))
3788 info t)
3789 cache)
3790 (error "Definition not found for footnote %s" label))))))
3792 (defun org-export--footnote-reference-map
3793 (function data info &optional body-first)
3794 "Apply FUNCTION on every footnote reference in DATA.
3795 INFO is a plist containing export state. By default, as soon as
3796 a new footnote reference is encountered, FUNCTION is called onto
3797 its definition. However, if BODY-FIRST is non-nil, this step is
3798 delayed until the end of the process."
3799 (letrec ((definitions nil)
3800 (seen-refs nil)
3801 (search-ref
3802 (lambda (data delayp)
3803 ;; Search footnote references through DATA, filling
3804 ;; SEEN-REFS along the way. When DELAYP is non-nil,
3805 ;; store footnote definitions so they can be entered
3806 ;; later.
3807 (org-element-map data 'footnote-reference
3808 (lambda (f)
3809 (funcall function f)
3810 (let ((--label (org-element-property :label f)))
3811 (unless (and --label (member --label seen-refs))
3812 (when --label (push --label seen-refs))
3813 ;; Search for subsequent references in footnote
3814 ;; definition so numbering follows reading
3815 ;; logic, unless DELAYP in non-nil.
3816 (cond
3817 (delayp
3818 (push (org-export-get-footnote-definition f info)
3819 definitions))
3820 ;; Do not force entering inline definitions,
3821 ;; since `org-element-map' already traverses
3822 ;; them at the right time.
3823 ((eq (org-element-property :type f) 'inline))
3824 (t (funcall search-ref
3825 (org-export-get-footnote-definition f info)
3826 nil))))))
3827 info nil
3828 ;; Don't enter footnote definitions since it will
3829 ;; happen when their first reference is found.
3830 ;; Moreover, if DELAYP is non-nil, make sure we
3831 ;; postpone entering definitions of inline references.
3832 (if delayp '(footnote-definition footnote-reference)
3833 'footnote-definition)))))
3834 (funcall search-ref data body-first)
3835 (funcall search-ref (nreverse definitions) nil)))
3837 (defun org-export-collect-footnote-definitions (info &optional data body-first)
3838 "Return an alist between footnote numbers, labels and definitions.
3840 INFO is the current export state, as a plist.
3842 Definitions are collected throughout the whole parse tree, or
3843 DATA when non-nil.
3845 Sorting is done by order of references. As soon as a new
3846 reference is encountered, other references are searched within
3847 its definition. However, if BODY-FIRST is non-nil, this step is
3848 delayed after the whole tree is checked. This alters results
3849 when references are found in footnote definitions.
3851 Definitions either appear as Org data or as a secondary string
3852 for inlined footnotes. Unreferenced definitions are ignored."
3853 (let ((n 0) labels alist)
3854 (org-export--footnote-reference-map
3855 (lambda (f)
3856 ;; Collect footnote number, label and definition.
3857 (let ((l (org-element-property :label f)))
3858 (unless (and l (member l labels))
3859 (cl-incf n)
3860 (push (list n l (org-export-get-footnote-definition f info)) alist))
3861 (when l (push l labels))))
3862 (or data (plist-get info :parse-tree)) info body-first)
3863 (nreverse alist)))
3865 (defun org-export-footnote-first-reference-p
3866 (footnote-reference info &optional data body-first)
3867 "Non-nil when a footnote reference is the first one for its label.
3869 FOOTNOTE-REFERENCE is the footnote reference being considered.
3870 INFO is a plist containing current export state.
3872 Search is done throughout the whole parse tree, or DATA when
3873 non-nil.
3875 By default, as soon as a new footnote reference is encountered,
3876 other references are searched within its definition. However, if
3877 BODY-FIRST is non-nil, this step is delayed after the whole tree
3878 is checked. This alters results when references are found in
3879 footnote definitions."
3880 (let ((label (org-element-property :label footnote-reference)))
3881 ;; Anonymous footnotes are always a first reference.
3882 (or (not label)
3883 (catch 'exit
3884 (org-export--footnote-reference-map
3885 (lambda (f)
3886 (let ((l (org-element-property :label f)))
3887 (when (and l label (string= label l))
3888 (throw 'exit (eq footnote-reference f)))))
3889 (or data (plist-get info :parse-tree)) info body-first)))))
3891 (defun org-export-get-footnote-number (footnote info &optional data body-first)
3892 "Return number associated to a footnote.
3894 FOOTNOTE is either a footnote reference or a footnote definition.
3895 INFO is the plist containing export state.
3897 Number is unique throughout the whole parse tree, or DATA, when
3898 non-nil.
3900 By default, as soon as a new footnote reference is encountered,
3901 counting process moves into its definition. However, if
3902 BODY-FIRST is non-nil, this step is delayed until the end of the
3903 process, leading to a different order when footnotes are nested."
3904 (let ((count 0)
3905 (seen)
3906 (label (org-element-property :label footnote)))
3907 (catch 'exit
3908 (org-export--footnote-reference-map
3909 (lambda (f)
3910 (let ((l (org-element-property :label f)))
3911 (cond
3912 ;; Anonymous footnote match: return number.
3913 ((and (not l) (not label) (eq footnote f)) (throw 'exit (1+ count)))
3914 ;; Labels match: return number.
3915 ((and label l (string= label l)) (throw 'exit (1+ count)))
3916 ;; Otherwise store label and increase counter if label
3917 ;; wasn't encountered yet.
3918 ((not l) (cl-incf count))
3919 ((not (member l seen)) (push l seen) (cl-incf count)))))
3920 (or data (plist-get info :parse-tree)) info body-first))))
3923 ;;;; For Headlines
3925 ;; `org-export-get-relative-level' is a shortcut to get headline
3926 ;; level, relatively to the lower headline level in the parsed tree.
3928 ;; `org-export-get-headline-number' returns the section number of an
3929 ;; headline, while `org-export-number-to-roman' allows it to be
3930 ;; converted to roman numbers. With an optional argument,
3931 ;; `org-export-get-headline-number' returns a number to unnumbered
3932 ;; headlines (used for internal id).
3934 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
3935 ;; `org-export-last-sibling-p' are three useful predicates when it
3936 ;; comes to fulfill the `:headline-levels' property.
3938 ;; `org-export-get-tags', `org-export-get-category' and
3939 ;; `org-export-get-node-property' extract useful information from an
3940 ;; headline or a parent headline. They all handle inheritance.
3942 ;; `org-export-get-alt-title' tries to retrieve an alternative title,
3943 ;; as a secondary string, suitable for table of contents. It falls
3944 ;; back onto default title.
3946 (defun org-export-get-relative-level (headline info)
3947 "Return HEADLINE relative level within current parsed tree.
3948 INFO is a plist holding contextual information."
3949 (+ (org-element-property :level headline)
3950 (or (plist-get info :headline-offset) 0)))
3952 (defun org-export-low-level-p (headline info)
3953 "Non-nil when HEADLINE is considered as low level.
3955 INFO is a plist used as a communication channel.
3957 A low level headlines has a relative level greater than
3958 `:headline-levels' property value.
3960 Return value is the difference between HEADLINE relative level
3961 and the last level being considered as high enough, or nil."
3962 (let ((limit (plist-get info :headline-levels)))
3963 (when (wholenump limit)
3964 (let ((level (org-export-get-relative-level headline info)))
3965 (and (> level limit) (- level limit))))))
3967 (defun org-export-get-headline-number (headline info)
3968 "Return numbered HEADLINE numbering as a list of numbers.
3969 INFO is a plist holding contextual information."
3970 (and (org-export-numbered-headline-p headline info)
3971 (cdr (assq headline (plist-get info :headline-numbering)))))
3973 (defun org-export-numbered-headline-p (headline info)
3974 "Return a non-nil value if HEADLINE element should be numbered.
3975 INFO is a plist used as a communication channel."
3976 (unless (cl-some
3977 (lambda (head) (org-not-nil (org-element-property :UNNUMBERED head)))
3978 (org-element-lineage headline nil t))
3979 (let ((sec-num (plist-get info :section-numbers))
3980 (level (org-export-get-relative-level headline info)))
3981 (if (wholenump sec-num) (<= level sec-num) sec-num))))
3983 (defun org-export-number-to-roman (n)
3984 "Convert integer N into a roman numeral."
3985 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
3986 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
3987 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
3988 ( 1 . "I")))
3989 (res ""))
3990 (if (<= n 0)
3991 (number-to-string n)
3992 (while roman
3993 (if (>= n (caar roman))
3994 (setq n (- n (caar roman))
3995 res (concat res (cdar roman)))
3996 (pop roman)))
3997 res)))
3999 (defun org-export-get-tags (element info &optional tags inherited)
4000 "Return list of tags associated to ELEMENT.
4002 ELEMENT has either an `headline' or an `inlinetask' type. INFO
4003 is a plist used as a communication channel.
4005 When non-nil, optional argument TAGS should be a list of strings.
4006 Any tag belonging to this list will also be removed.
4008 When optional argument INHERITED is non-nil, tags can also be
4009 inherited from parent headlines and FILETAGS keywords."
4010 (cl-remove-if
4011 (lambda (tag) (member tag tags))
4012 (if (not inherited) (org-element-property :tags element)
4013 ;; Build complete list of inherited tags.
4014 (let ((current-tag-list (org-element-property :tags element)))
4015 (dolist (parent (org-element-lineage element))
4016 (dolist (tag (org-element-property :tags parent))
4017 (when (and (memq (org-element-type parent) '(headline inlinetask))
4018 (not (member tag current-tag-list)))
4019 (push tag current-tag-list))))
4020 ;; Add FILETAGS keywords and return results.
4021 (org-uniquify (append (plist-get info :filetags) current-tag-list))))))
4023 (defun org-export-get-node-property (property blob &optional inherited)
4024 "Return node PROPERTY value for BLOB.
4026 PROPERTY is an upcase symbol (i.e. `:COOKIE_DATA'). BLOB is an
4027 element or object.
4029 If optional argument INHERITED is non-nil, the value can be
4030 inherited from a parent headline.
4032 Return value is a string or nil."
4033 (let ((headline (if (eq (org-element-type blob) 'headline) blob
4034 (org-export-get-parent-headline blob))))
4035 (if (not inherited) (org-element-property property blob)
4036 (let ((parent headline))
4037 (catch 'found
4038 (while parent
4039 (when (plist-member (nth 1 parent) property)
4040 (throw 'found (org-element-property property parent)))
4041 (setq parent (org-element-property :parent parent))))))))
4043 (defun org-export-get-category (blob info)
4044 "Return category for element or object BLOB.
4046 INFO is a plist used as a communication channel.
4048 CATEGORY is automatically inherited from a parent headline, from
4049 #+CATEGORY: keyword or created out of original file name. If all
4050 fail, the fall-back value is \"???\"."
4051 (or (org-export-get-node-property :CATEGORY blob t)
4052 (org-element-map (plist-get info :parse-tree) 'keyword
4053 (lambda (kwd)
4054 (when (equal (org-element-property :key kwd) "CATEGORY")
4055 (org-element-property :value kwd)))
4056 info 'first-match)
4057 (let ((file (plist-get info :input-file)))
4058 (and file (file-name-sans-extension (file-name-nondirectory file))))
4059 "???"))
4061 (defun org-export-get-alt-title (headline _)
4062 "Return alternative title for HEADLINE, as a secondary string.
4063 If no optional title is defined, fall-back to the regular title."
4064 (let ((alt (org-element-property :ALT_TITLE headline)))
4065 (if alt (org-element-parse-secondary-string
4066 alt (org-element-restriction 'headline) headline)
4067 (org-element-property :title headline))))
4069 (defun org-export-first-sibling-p (blob info)
4070 "Non-nil when BLOB is the first sibling in its parent.
4071 BLOB is an element or an object. If BLOB is a headline, non-nil
4072 means it is the first sibling in the sub-tree. INFO is a plist
4073 used as a communication channel."
4074 (memq (org-element-type (org-export-get-previous-element blob info))
4075 '(nil section)))
4077 (defun org-export-last-sibling-p (blob info)
4078 "Non-nil when BLOB is the last sibling in its parent.
4079 BLOB is an element or an object. INFO is a plist used as
4080 a communication channel."
4081 (not (org-export-get-next-element blob info)))
4084 ;;;; For Keywords
4086 ;; `org-export-get-date' returns a date appropriate for the document
4087 ;; to about to be exported. In particular, it takes care of
4088 ;; `org-export-date-timestamp-format'.
4090 (defun org-export-get-date (info &optional fmt)
4091 "Return date value for the current document.
4093 INFO is a plist used as a communication channel. FMT, when
4094 non-nil, is a time format string that will be applied on the date
4095 if it consists in a single timestamp object. It defaults to
4096 `org-export-date-timestamp-format' when nil.
4098 A proper date can be a secondary string, a string or nil. It is
4099 meant to be translated with `org-export-data' or alike."
4100 (let ((date (plist-get info :date))
4101 (fmt (or fmt org-export-date-timestamp-format)))
4102 (cond ((not date) nil)
4103 ((and fmt
4104 (not (cdr date))
4105 (eq (org-element-type (car date)) 'timestamp))
4106 (org-timestamp-format (car date) fmt))
4107 (t date))))
4110 ;;;; For Links
4112 ;; `org-export-custom-protocol-maybe' handles custom protocol defined
4113 ;; in `org-link-parameters'.
4115 ;; `org-export-get-coderef-format' returns an appropriate format
4116 ;; string for coderefs.
4118 ;; `org-export-inline-image-p' returns a non-nil value when the link
4119 ;; provided should be considered as an inline image.
4121 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
4122 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
4123 ;; returns an appropriate unique identifier.
4125 ;; `org-export-resolve-id-link' returns the first headline with
4126 ;; specified id or custom-id in parse tree, the path to the external
4127 ;; file with the id.
4129 ;; `org-export-resolve-coderef' associates a reference to a line
4130 ;; number in the element it belongs, or returns the reference itself
4131 ;; when the element isn't numbered.
4133 ;; `org-export-file-uri' expands a filename as stored in :path value
4134 ;; of a "file" link into a file URI.
4136 ;; Broken links raise a `org-link-broken' error, which is caught by
4137 ;; `org-export-data' for further processing, depending on
4138 ;; `org-export-with-broken-links' value.
4140 (org-define-error 'org-link-broken "Unable to resolve link; aborting")
4142 (defun org-export-custom-protocol-maybe (link desc backend)
4143 "Try exporting LINK with a dedicated function.
4145 DESC is its description, as a string, or nil. BACKEND is the
4146 back-end used for export, as a symbol.
4148 Return output as a string, or nil if no protocol handles LINK.
4150 A custom protocol has precedence over regular back-end export.
4151 The function ignores links with an implicit type (e.g.,
4152 \"custom-id\")."
4153 (let ((type (org-element-property :type link)))
4154 (unless (or (member type '("coderef" "custom-id" "fuzzy" "radio"))
4155 (not backend))
4156 (let ((protocol (org-link-get-parameter type :export)))
4157 (and (functionp protocol)
4158 (funcall protocol
4159 (org-link-unescape (org-element-property :path link))
4160 desc
4161 backend))))))
4163 (defun org-export-get-coderef-format (path desc)
4164 "Return format string for code reference link.
4165 PATH is the link path. DESC is its description."
4166 (save-match-data
4167 (cond ((not desc) "%s")
4168 ((string-match (regexp-quote (concat "(" path ")")) desc)
4169 (replace-match "%s" t t desc))
4170 (t desc))))
4172 (defun org-export-inline-image-p (link &optional rules)
4173 "Non-nil if LINK object points to an inline image.
4175 Optional argument is a set of RULES defining inline images. It
4176 is an alist where associations have the following shape:
4178 (TYPE . REGEXP)
4180 Applying a rule means apply REGEXP against LINK's path when its
4181 type is TYPE. The function will return a non-nil value if any of
4182 the provided rules is non-nil. The default rule is
4183 `org-export-default-inline-image-rule'.
4185 This only applies to links without a description."
4186 (and (not (org-element-contents link))
4187 (let ((case-fold-search t))
4188 (cl-some (lambda (rule)
4189 (and (string= (org-element-property :type link) (car rule))
4190 (string-match-p (cdr rule)
4191 (org-element-property :path link))))
4192 (or rules org-export-default-inline-image-rule)))))
4194 (defun org-export-insert-image-links (data info &optional rules)
4195 "Insert image links in DATA.
4197 Org syntax do not support nested links. Nevertheless, some
4198 export back-ends support image as descriptions of links. Since
4199 images are really link to image files, we need to make an
4200 exception about link nesting.
4202 This function recognizes links whose contents are really images
4203 and turn them into proper nested links. It is meant to be used
4204 as a parse tree filter in back-ends supporting such constructs.
4206 DATA is a parse tree. INFO is the current state of the export
4207 process, as a plist.
4209 A description is a valid images if it matches any rule in RULES,
4210 if non-nil, or `org-export-default-inline-image-rule' otherwise.
4211 See `org-export-inline-image-p' for more information about the
4212 structure of RULES.
4214 Return modified DATA."
4215 (let ((link-re (format "\\`\\(?:%s\\|%s\\)\\'"
4216 org-plain-link-re
4217 org-angle-link-re))
4218 (case-fold-search t))
4219 (org-element-map data 'link
4220 (lambda (l)
4221 (let ((contents (org-element-interpret-data (org-element-contents l))))
4222 (when (and (org-string-nw-p contents)
4223 (string-match link-re contents))
4224 (let ((type (match-string 1 contents))
4225 (path (match-string 2 contents)))
4226 (when (cl-some (lambda (rule)
4227 (and (string= type (car rule))
4228 (string-match-p (cdr rule) path)))
4229 (or rules org-export-default-inline-image-rule))
4230 (org-element-set-contents
4232 (with-temp-buffer
4233 (save-excursion (insert contents))
4234 (org-element-link-parser))))))))
4235 info nil nil t))
4236 data)
4238 (defun org-export-resolve-coderef (ref info)
4239 "Resolve a code reference REF.
4241 INFO is a plist used as a communication channel.
4243 Return associated line number in source code, or REF itself,
4244 depending on src-block or example element's switches. Throw an
4245 error if no block contains REF."
4246 (or (org-element-map (plist-get info :parse-tree) '(example-block src-block)
4247 (lambda (el)
4248 (with-temp-buffer
4249 (insert (org-trim (org-element-property :value el)))
4250 (let* ((label-fmt (or (org-element-property :label-fmt el)
4251 org-coderef-label-format))
4252 (ref-re (org-src-coderef-regexp label-fmt ref)))
4253 ;; Element containing REF is found. Resolve it to
4254 ;; either a label or a line number, as needed.
4255 (when (re-search-backward ref-re nil t)
4256 (if (org-element-property :use-labels el) ref
4257 (+ (or (org-export-get-loc el info) 0)
4258 (line-number-at-pos)))))))
4259 info 'first-match)
4260 (signal 'org-link-broken (list ref))))
4262 (defun org-export-search-cells (datum)
4263 "List search cells for element or object DATUM.
4265 A search cell follows the pattern (TYPE . SEARCH) where
4267 TYPE is a symbol among `headline', `custom-id', `target' and
4268 `other'.
4270 SEARCH is the string a link is expected to match. More
4271 accurately, it is
4273 - headline's title, as a list of strings, if TYPE is
4274 `headline'.
4276 - CUSTOM_ID value, as a string, if TYPE is `custom-id'.
4278 - target's or radio-target's name as a list of strings if
4279 TYPE is `target'.
4281 - NAME affiliated keyword is TYPE is `other'.
4283 A search cell is the internal representation of a fuzzy link. It
4284 ignores white spaces and statistics cookies, if applicable."
4285 (pcase (org-element-type datum)
4286 (`headline
4287 (let ((title (split-string
4288 (replace-regexp-in-string
4289 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]" ""
4290 (org-element-property :raw-value datum)))))
4291 (delq nil
4292 (list
4293 (cons 'headline title)
4294 (cons 'other title)
4295 (let ((custom-id (org-element-property :custom-id datum)))
4296 (and custom-id (cons 'custom-id custom-id)))))))
4297 (`target
4298 (list (cons 'target (split-string (org-element-property :value datum)))))
4299 ((and (let name (org-element-property :name datum))
4300 (guard name))
4301 (list (cons 'other (split-string name))))
4302 (_ nil)))
4304 (defun org-export-string-to-search-cell (s)
4305 "Return search cells associated to string S.
4306 S is either the path of a fuzzy link or a search option, i.e., it
4307 tries to match either a headline (through custom ID or title),
4308 a target or a named element."
4309 (pcase (string-to-char s)
4310 (?* (list (cons 'headline (split-string (substring s 1)))))
4311 (?# (list (cons 'custom-id (substring s 1))))
4312 ((let search (split-string s))
4313 (list (cons 'target search) (cons 'other search)))))
4315 (defun org-export-match-search-cell-p (datum cells)
4316 "Non-nil when DATUM matches search cells CELLS.
4317 DATUM is an element or object. CELLS is a list of search cells,
4318 as returned by `org-export-search-cells'."
4319 (let ((targets (org-export-search-cells datum)))
4320 (and targets (cl-some (lambda (cell) (member cell targets)) cells))))
4322 (defun org-export-resolve-fuzzy-link (link info)
4323 "Return LINK destination.
4325 INFO is a plist holding contextual information.
4327 Return value can be an object or an element:
4329 - If LINK path matches a target object (i.e. <<path>>) return it.
4331 - If LINK path exactly matches the name affiliated keyword
4332 (i.e. #+NAME: path) of an element, return that element.
4334 - If LINK path exactly matches any headline name, return that
4335 element.
4337 - Otherwise, throw an error.
4339 Assume LINK type is \"fuzzy\". White spaces are not
4340 significant."
4341 (let* ((search-cells (org-export-string-to-search-cell
4342 (org-link-unescape (org-element-property :path link))))
4343 (link-cache (or (plist-get info :resolve-fuzzy-link-cache)
4344 (let ((table (make-hash-table :test #'eq)))
4345 (plist-put info :resolve-fuzzy-link-cache table)
4346 table)))
4347 (cached (gethash search-cells link-cache 'not-found)))
4348 (if (not (eq cached 'not-found)) cached
4349 (let ((matches
4350 (org-element-map (plist-get info :parse-tree)
4351 (cons 'target org-element-all-elements)
4352 (lambda (datum)
4353 (and (org-export-match-search-cell-p datum search-cells)
4354 datum)))))
4355 (unless matches
4356 (signal 'org-link-broken
4357 (list (org-element-property :raw-path link))))
4358 (puthash
4359 search-cells
4360 ;; There can be multiple matches for un-typed searches, i.e.,
4361 ;; for searches not starting with # or *. In this case,
4362 ;; prioritize targets and names over headline titles.
4363 ;; Matching both a name and a target is not valid, and
4364 ;; therefore undefined.
4365 (or (cl-some (lambda (datum)
4366 (and (not (eq (org-element-type datum) 'headline))
4367 datum))
4368 matches)
4369 (car matches))
4370 link-cache)))))
4372 (defun org-export-resolve-id-link (link info)
4373 "Return headline referenced as LINK destination.
4375 INFO is a plist used as a communication channel.
4377 Return value can be the headline element matched in current parse
4378 tree or a file name. Assume LINK type is either \"id\" or
4379 \"custom-id\". Throw an error if no match is found."
4380 (let ((id (org-element-property :path link)))
4381 ;; First check if id is within the current parse tree.
4382 (or (org-element-map (plist-get info :parse-tree) 'headline
4383 (lambda (headline)
4384 (when (or (equal (org-element-property :ID headline) id)
4385 (equal (org-element-property :CUSTOM_ID headline) id))
4386 headline))
4387 info 'first-match)
4388 ;; Otherwise, look for external files.
4389 (cdr (assoc id (plist-get info :id-alist)))
4390 (signal 'org-link-broken (list id)))))
4392 (defun org-export-resolve-radio-link (link info)
4393 "Return radio-target object referenced as LINK destination.
4395 INFO is a plist used as a communication channel.
4397 Return value can be a radio-target object or nil. Assume LINK
4398 has type \"radio\"."
4399 (let ((path (replace-regexp-in-string
4400 "[ \r\t\n]+" " " (org-element-property :path link))))
4401 (org-element-map (plist-get info :parse-tree) 'radio-target
4402 (lambda (radio)
4403 (and (eq (compare-strings
4404 (replace-regexp-in-string
4405 "[ \r\t\n]+" " " (org-element-property :value radio))
4406 nil nil path nil nil t)
4408 radio))
4409 info 'first-match)))
4411 (defun org-export-file-uri (filename)
4412 "Return file URI associated to FILENAME."
4413 (cond ((string-match-p "\\`//" filename) (concat "file:" filename))
4414 ((not (file-name-absolute-p filename)) filename)
4415 ((org-file-remote-p filename) (concat "file:/" filename))
4416 (t (concat "file://" (expand-file-name filename)))))
4419 ;;;; For References
4421 ;; `org-export-get-reference' associate a unique reference for any
4422 ;; object or element. It uses `org-export-new-reference' and
4423 ;; `org-export-format-reference' to, respectively, generate new
4424 ;; internal references and turn them into a string suitable for
4425 ;; output.
4427 ;; `org-export-get-ordinal' associates a sequence number to any object
4428 ;; or element.
4430 (defun org-export-new-reference (references)
4431 "Return a unique reference, among REFERENCES.
4432 REFERENCES is an alist whose values are in-use references, as
4433 numbers. Returns a number, which is the internal representation
4434 of a reference. See also `org-export-format-reference'."
4435 ;; Generate random 7 digits hexadecimal numbers. Collisions
4436 ;; increase exponentially with the numbers of references. However,
4437 ;; the odds for encountering at least one collision with 1000 active
4438 ;; references in the same document are roughly 0.2%, so this
4439 ;; shouldn't be the bottleneck.
4440 (let ((new (random #x10000000)))
4441 (while (rassq new references) (setq new (random #x10000000)))
4442 new))
4444 (defun org-export-format-reference (reference)
4445 "Format REFERENCE into a string.
4446 REFERENCE is a number representing a reference, as returned by
4447 `org-export-new-reference', which see."
4448 (format "org%07x" reference))
4450 (defun org-export-get-reference (datum info)
4451 "Return a unique reference for DATUM, as a string.
4453 DATUM is either an element or an object. INFO is the current
4454 export state, as a plist.
4456 This function checks `:crossrefs' property in INFO for search
4457 cells matching DATUM before creating a new reference. Returned
4458 reference consists of alphanumeric characters only."
4459 (let ((cache (plist-get info :internal-references)))
4460 (or (car (rassq datum cache))
4461 (let* ((crossrefs (plist-get info :crossrefs))
4462 (cells (org-export-search-cells datum))
4463 ;; Preserve any pre-existing association between
4464 ;; a search cell and a reference, i.e., when some
4465 ;; previously published document referenced a location
4466 ;; within current file (see
4467 ;; `org-publish-resolve-external-link').
4469 ;; However, there is no guarantee that search cells are
4470 ;; unique, e.g., there might be duplicate custom ID or
4471 ;; two headings with the same title in the file.
4473 ;; As a consequence, before re-using any reference to
4474 ;; an element or object, we check that it doesn't refer
4475 ;; to a previous element or object.
4476 (new (or (cl-some
4477 (lambda (cell)
4478 (let ((stored (cdr (assoc cell crossrefs))))
4479 (when stored
4480 (let ((old (org-export-format-reference stored)))
4481 (and (not (assoc old cache)) stored)))))
4482 cells)
4483 (org-export-new-reference cache)))
4484 (reference-string (org-export-format-reference new)))
4485 ;; Cache contains both data already associated to
4486 ;; a reference and in-use internal references, so as to make
4487 ;; unique references.
4488 (dolist (cell cells) (push (cons cell new) cache))
4489 ;; Retain a direct association between reference string and
4490 ;; DATUM since (1) not every object or element can be given
4491 ;; a search cell (2) it permits quick lookup.
4492 (push (cons reference-string datum) cache)
4493 (plist-put info :internal-references cache)
4494 reference-string))))
4496 (defun org-export-get-ordinal (element info &optional types predicate)
4497 "Return ordinal number of an element or object.
4499 ELEMENT is the element or object considered. INFO is the plist
4500 used as a communication channel.
4502 Optional argument TYPES, when non-nil, is a list of element or
4503 object types, as symbols, that should also be counted in.
4504 Otherwise, only provided element's type is considered.
4506 Optional argument PREDICATE is a function returning a non-nil
4507 value if the current element or object should be counted in. It
4508 accepts two arguments: the element or object being considered and
4509 the plist used as a communication channel. This allows counting
4510 only a certain type of object (i.e. inline images).
4512 Return value is a list of numbers if ELEMENT is a headline or an
4513 item. It is nil for keywords. It represents the footnote number
4514 for footnote definitions and footnote references. If ELEMENT is
4515 a target, return the same value as if ELEMENT was the closest
4516 table, item or headline containing the target. In any other
4517 case, return the sequence number of ELEMENT among elements or
4518 objects of the same type."
4519 ;; Ordinal of a target object refer to the ordinal of the closest
4520 ;; table, item, or headline containing the object.
4521 (when (eq (org-element-type element) 'target)
4522 (setq element
4523 (org-element-lineage
4524 element
4525 '(footnote-definition footnote-reference headline item table))))
4526 (cl-case (org-element-type element)
4527 ;; Special case 1: A headline returns its number as a list.
4528 (headline (org-export-get-headline-number element info))
4529 ;; Special case 2: An item returns its number as a list.
4530 (item (let ((struct (org-element-property :structure element)))
4531 (org-list-get-item-number
4532 (org-element-property :begin element)
4533 struct
4534 (org-list-prevs-alist struct)
4535 (org-list-parents-alist struct))))
4536 ((footnote-definition footnote-reference)
4537 (org-export-get-footnote-number element info))
4538 (otherwise
4539 (let ((counter 0))
4540 ;; Increment counter until ELEMENT is found again.
4541 (org-element-map (plist-get info :parse-tree)
4542 (or types (org-element-type element))
4543 (lambda (el)
4544 (cond
4545 ((eq element el) (1+ counter))
4546 ((not predicate) (cl-incf counter) nil)
4547 ((funcall predicate el info) (cl-incf counter) nil)))
4548 info 'first-match)))))
4551 ;;;; For Src-Blocks
4553 ;; `org-export-get-loc' counts number of code lines accumulated in
4554 ;; src-block or example-block elements with a "+n" switch until
4555 ;; a given element, excluded. Note: "-n" switches reset that count.
4557 ;; `org-export-unravel-code' extracts source code (along with a code
4558 ;; references alist) from an `element-block' or `src-block' type
4559 ;; element.
4561 ;; `org-export-format-code' applies a formatting function to each line
4562 ;; of code, providing relative line number and code reference when
4563 ;; appropriate. Since it doesn't access the original element from
4564 ;; which the source code is coming, it expects from the code calling
4565 ;; it to know if lines should be numbered and if code references
4566 ;; should appear.
4568 ;; Eventually, `org-export-format-code-default' is a higher-level
4569 ;; function (it makes use of the two previous functions) which handles
4570 ;; line numbering and code references inclusion, and returns source
4571 ;; code in a format suitable for plain text or verbatim output.
4573 (defun org-export-get-loc (element info)
4574 "Return count of lines of code before ELEMENT.
4576 ELEMENT is an example-block or src-block element. INFO is the
4577 plist used as a communication channel.
4579 Count includes every line of code in example-block or src-block
4580 with a \"+n\" or \"-n\" switch before block. Return nil if
4581 ELEMENT doesn't allow line numbering."
4582 (pcase (org-element-property :number-lines element)
4583 (`(new . ,n) n)
4584 (`(continued . ,n)
4585 (let ((loc 0))
4586 (org-element-map (plist-get info :parse-tree) '(src-block example-block)
4587 (lambda (el)
4588 ;; ELEMENT is reached: Quit loop and return locs.
4589 (if (eq el element) (+ loc n)
4590 ;; Only count lines from src-block and example-block
4591 ;; elements with a "+n" or "-n" switch.
4592 (let ((linum (org-element-property :number-lines el)))
4593 (when linum
4594 (let ((lines (org-count-lines
4595 (org-trim (org-element-property :value el)))))
4596 ;; Accumulate locs or reset them.
4597 (pcase linum
4598 (`(new . ,n) (setq loc (+ n lines)))
4599 (`(continued . ,n) (cl-incf loc (+ n lines)))))))
4600 nil)) ;Return nil to stay in the loop.
4601 info 'first-match)))))
4603 (defun org-export-unravel-code (element)
4604 "Clean source code and extract references out of it.
4606 ELEMENT has either a `src-block' an `example-block' type.
4608 Return a cons cell whose CAR is the source code, cleaned from any
4609 reference, protective commas and spurious indentation, and CDR is
4610 an alist between relative line number (integer) and name of code
4611 reference on that line (string)."
4612 (let* ((line 0) refs
4613 (value (org-element-property :value element))
4614 ;; Get code and clean it. Remove blank lines at its
4615 ;; beginning and end.
4616 (code (replace-regexp-in-string
4617 "\\`\\([ \t]*\n\\)+" ""
4618 (replace-regexp-in-string
4619 "\\([ \t]*\n\\)*[ \t]*\\'" "\n"
4620 (if (or org-src-preserve-indentation
4621 (org-element-property :preserve-indent element))
4622 value
4623 (org-remove-indentation value)))))
4624 ;; Build a regexp matching a loc with a reference.
4625 (ref-re (org-src-coderef-regexp (org-src-coderef-format element))))
4626 ;; Return value.
4627 (cons
4628 ;; Code with references removed.
4629 (org-element-normalize-string
4630 (mapconcat
4631 (lambda (loc)
4632 (cl-incf line)
4633 (if (not (string-match ref-re loc)) loc
4634 ;; Ref line: remove ref, and signal its position in REFS.
4635 (push (cons line (match-string 3 loc)) refs)
4636 (replace-match "" nil nil loc 1)))
4637 (org-split-string code "\n") "\n"))
4638 ;; Reference alist.
4639 refs)))
4641 (defun org-export-format-code (code fun &optional num-lines ref-alist)
4642 "Format CODE by applying FUN line-wise and return it.
4644 CODE is a string representing the code to format. FUN is
4645 a function. It must accept three arguments: a line of
4646 code (string), the current line number (integer) or nil and the
4647 reference associated to the current line (string) or nil.
4649 Optional argument NUM-LINES can be an integer representing the
4650 number of code lines accumulated until the current code. Line
4651 numbers passed to FUN will take it into account. If it is nil,
4652 FUN's second argument will always be nil. This number can be
4653 obtained with `org-export-get-loc' function.
4655 Optional argument REF-ALIST can be an alist between relative line
4656 number (i.e. ignoring NUM-LINES) and the name of the code
4657 reference on it. If it is nil, FUN's third argument will always
4658 be nil. It can be obtained through the use of
4659 `org-export-unravel-code' function."
4660 (let ((--locs (org-split-string code "\n"))
4661 (--line 0))
4662 (org-element-normalize-string
4663 (mapconcat
4664 (lambda (--loc)
4665 (cl-incf --line)
4666 (let ((--ref (cdr (assq --line ref-alist))))
4667 (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
4668 --locs "\n"))))
4670 (defun org-export-format-code-default (element info)
4671 "Return source code from ELEMENT, formatted in a standard way.
4673 ELEMENT is either a `src-block' or `example-block' element. INFO
4674 is a plist used as a communication channel.
4676 This function takes care of line numbering and code references
4677 inclusion. Line numbers, when applicable, appear at the
4678 beginning of the line, separated from the code by two white
4679 spaces. Code references, on the other hand, appear flushed to
4680 the right, separated by six white spaces from the widest line of
4681 code."
4682 ;; Extract code and references.
4683 (let* ((code-info (org-export-unravel-code element))
4684 (code (car code-info))
4685 (code-lines (org-split-string code "\n")))
4686 (if (null code-lines) ""
4687 (let* ((refs (and (org-element-property :retain-labels element)
4688 (cdr code-info)))
4689 ;; Handle line numbering.
4690 (num-start (org-export-get-loc element info))
4691 (num-fmt
4692 (and num-start
4693 (format "%%%ds "
4694 (length (number-to-string
4695 (+ (length code-lines) num-start))))))
4696 ;; Prepare references display, if required. Any reference
4697 ;; should start six columns after the widest line of code,
4698 ;; wrapped with parenthesis.
4699 (max-width
4700 (+ (apply 'max (mapcar 'length code-lines))
4701 (if (not num-start) 0 (length (format num-fmt num-start))))))
4702 (org-export-format-code
4703 code
4704 (lambda (loc line-num ref)
4705 (let ((number-str (and num-fmt (format num-fmt line-num))))
4706 (concat
4707 number-str
4709 (and ref
4710 (concat (make-string
4711 (- (+ 6 max-width)
4712 (+ (length loc) (length number-str))) ? )
4713 (format "(%s)" ref))))))
4714 num-start refs)))))
4717 ;;;; For Tables
4719 ;; `org-export-table-has-special-column-p' and and
4720 ;; `org-export-table-row-is-special-p' are predicates used to look for
4721 ;; meta-information about the table structure.
4723 ;; `org-table-has-header-p' tells when the rows before the first rule
4724 ;; should be considered as table's header.
4726 ;; `org-export-table-cell-width', `org-export-table-cell-alignment'
4727 ;; and `org-export-table-cell-borders' extract information from
4728 ;; a table-cell element.
4730 ;; `org-export-table-dimensions' gives the number on rows and columns
4731 ;; in the table, ignoring horizontal rules and special columns.
4732 ;; `org-export-table-cell-address', given a table-cell object, returns
4733 ;; the absolute address of a cell. On the other hand,
4734 ;; `org-export-get-table-cell-at' does the contrary.
4736 ;; `org-export-table-cell-starts-colgroup-p',
4737 ;; `org-export-table-cell-ends-colgroup-p',
4738 ;; `org-export-table-row-starts-rowgroup-p',
4739 ;; `org-export-table-row-ends-rowgroup-p',
4740 ;; `org-export-table-row-starts-header-p',
4741 ;; `org-export-table-row-ends-header-p' and
4742 ;; `org-export-table-row-in-header-p' indicate position of current row
4743 ;; or cell within the table.
4745 (defun org-export-table-has-special-column-p (table)
4746 "Non-nil when TABLE has a special column.
4747 All special columns will be ignored during export."
4748 ;; The table has a special column when every first cell of every row
4749 ;; has an empty value or contains a symbol among "/", "#", "!", "$",
4750 ;; "*" "_" and "^". Though, do not consider a first column
4751 ;; containing only empty cells as special.
4752 (let ((special-column? 'empty))
4753 (catch 'exit
4754 (dolist (row (org-element-contents table))
4755 (when (eq (org-element-property :type row) 'standard)
4756 (let ((value (org-element-contents
4757 (car (org-element-contents row)))))
4758 (cond ((member value
4759 '(("/") ("#") ("!") ("$") ("*") ("_") ("^")))
4760 (setq special-column? 'special))
4761 ((null value))
4762 (t (throw 'exit nil))))))
4763 (eq special-column? 'special))))
4765 (defun org-export-table-has-header-p (table info)
4766 "Non-nil when TABLE has a header.
4768 INFO is a plist used as a communication channel.
4770 A table has a header when it contains at least two row groups."
4771 (let* ((cache (or (plist-get info :table-header-cache)
4772 (let ((table (make-hash-table :test #'eq)))
4773 (plist-put info :table-header-cache table)
4774 table)))
4775 (cached (gethash table cache 'no-cache)))
4776 (if (not (eq cached 'no-cache)) cached
4777 (let ((rowgroup 1) row-flag)
4778 (puthash table
4779 (org-element-map table 'table-row
4780 (lambda (row)
4781 (cond
4782 ((> rowgroup 1) t)
4783 ((and row-flag
4784 (eq (org-element-property :type row) 'rule))
4785 (cl-incf rowgroup)
4786 (setq row-flag nil))
4787 ((and (not row-flag)
4788 (eq (org-element-property :type row) 'standard))
4789 (setq row-flag t)
4790 nil)))
4791 info 'first-match)
4792 cache)))))
4794 (defun org-export-table-row-is-special-p (table-row _)
4795 "Non-nil if TABLE-ROW is considered special.
4796 All special rows will be ignored during export."
4797 (when (eq (org-element-property :type table-row) 'standard)
4798 (let ((first-cell (org-element-contents
4799 (car (org-element-contents table-row)))))
4800 ;; A row is special either when...
4802 ;; ... it starts with a field only containing "/",
4803 (equal first-cell '("/"))
4804 ;; ... the table contains a special column and the row start
4805 ;; with a marking character among, "^", "_", "$" or "!",
4806 (and (org-export-table-has-special-column-p
4807 (org-export-get-parent table-row))
4808 (member first-cell '(("^") ("_") ("$") ("!"))))
4809 ;; ... it contains only alignment cookies and empty cells.
4810 (let ((special-row-p 'empty))
4811 (catch 'exit
4812 (dolist (cell (org-element-contents table-row))
4813 (let ((value (org-element-contents cell)))
4814 ;; Since VALUE is a secondary string, the following
4815 ;; checks avoid expanding it with `org-export-data'.
4816 (cond ((not value))
4817 ((and (not (cdr value))
4818 (stringp (car value))
4819 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'"
4820 (car value)))
4821 (setq special-row-p 'cookie))
4822 (t (throw 'exit nil)))))
4823 (eq special-row-p 'cookie)))))))
4825 (defun org-export-table-row-group (table-row info)
4826 "Return TABLE-ROW's group number, as an integer.
4828 INFO is a plist used as the communication channel.
4830 Return value is the group number, as an integer, or nil for
4831 special rows and rows separators. First group is also table's
4832 header."
4833 (when (eq (org-element-property :type table-row) 'standard)
4834 (let* ((cache (or (plist-get info :table-row-group-cache)
4835 (let ((table (make-hash-table :test #'eq)))
4836 (plist-put info :table-row-group-cache table)
4837 table)))
4838 (cached (gethash table-row cache 'no-cache)))
4839 (if (not (eq cached 'no-cache)) cached
4840 ;; First time a row is queried, populate cache with all the
4841 ;; rows from the table.
4842 (let ((group 0) row-flag)
4843 (org-element-map (org-export-get-parent table-row) 'table-row
4844 (lambda (row)
4845 (if (eq (org-element-property :type row) 'rule)
4846 (setq row-flag nil)
4847 (unless row-flag (cl-incf group) (setq row-flag t))
4848 (puthash row group cache)))
4849 info))
4850 (gethash table-row cache)))))
4852 (defun org-export-table-cell-width (table-cell info)
4853 "Return TABLE-CELL contents width.
4855 INFO is a plist used as the communication channel.
4857 Return value is the width given by the last width cookie in the
4858 same column as TABLE-CELL, or nil."
4859 (let* ((row (org-export-get-parent table-cell))
4860 (table (org-export-get-parent row))
4861 (cells (org-element-contents row))
4862 (columns (length cells))
4863 (column (- columns (length (memq table-cell cells))))
4864 (cache (or (plist-get info :table-cell-width-cache)
4865 (let ((table (make-hash-table :test #'eq)))
4866 (plist-put info :table-cell-width-cache table)
4867 table)))
4868 (width-vector (or (gethash table cache)
4869 (puthash table (make-vector columns 'empty) cache)))
4870 (value (aref width-vector column)))
4871 (if (not (eq value 'empty)) value
4872 (let (cookie-width)
4873 (dolist (row (org-element-contents table)
4874 (aset width-vector column cookie-width))
4875 (when (org-export-table-row-is-special-p row info)
4876 ;; In a special row, try to find a width cookie at COLUMN.
4877 (let* ((value (org-element-contents
4878 (elt (org-element-contents row) column)))
4879 (cookie (car value)))
4880 ;; The following checks avoid expanding unnecessarily
4881 ;; the cell with `org-export-data'.
4882 (when (and value
4883 (not (cdr value))
4884 (stringp cookie)
4885 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'" cookie)
4886 (match-string 1 cookie))
4887 (setq cookie-width
4888 (string-to-number (match-string 1 cookie)))))))))))
4890 (defun org-export-table-cell-alignment (table-cell info)
4891 "Return TABLE-CELL contents alignment.
4893 INFO is a plist used as the communication channel.
4895 Return alignment as specified by the last alignment cookie in the
4896 same column as TABLE-CELL. If no such cookie is found, a default
4897 alignment value will be deduced from fraction of numbers in the
4898 column (see `org-table-number-fraction' for more information).
4899 Possible values are `left', `right' and `center'."
4900 ;; Load `org-table-number-fraction' and `org-table-number-regexp'.
4901 (require 'org-table)
4902 (let* ((row (org-export-get-parent table-cell))
4903 (table (org-export-get-parent row))
4904 (cells (org-element-contents row))
4905 (columns (length cells))
4906 (column (- columns (length (memq table-cell cells))))
4907 (cache (or (plist-get info :table-cell-alignment-cache)
4908 (let ((table (make-hash-table :test #'eq)))
4909 (plist-put info :table-cell-alignment-cache table)
4910 table)))
4911 (align-vector (or (gethash table cache)
4912 (puthash table (make-vector columns nil) cache))))
4913 (or (aref align-vector column)
4914 (let ((number-cells 0)
4915 (total-cells 0)
4916 cookie-align
4917 previous-cell-number-p)
4918 (dolist (row (org-element-contents (org-export-get-parent row)))
4919 (cond
4920 ;; In a special row, try to find an alignment cookie at
4921 ;; COLUMN.
4922 ((org-export-table-row-is-special-p row info)
4923 (let ((value (org-element-contents
4924 (elt (org-element-contents row) column))))
4925 ;; Since VALUE is a secondary string, the following
4926 ;; checks avoid useless expansion through
4927 ;; `org-export-data'.
4928 (when (and value
4929 (not (cdr value))
4930 (stringp (car value))
4931 (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'"
4932 (car value))
4933 (match-string 1 (car value)))
4934 (setq cookie-align (match-string 1 (car value))))))
4935 ;; Ignore table rules.
4936 ((eq (org-element-property :type row) 'rule))
4937 ;; In a standard row, check if cell's contents are
4938 ;; expressing some kind of number. Increase NUMBER-CELLS
4939 ;; accordingly. Though, don't bother if an alignment
4940 ;; cookie has already defined cell's alignment.
4941 ((not cookie-align)
4942 (let ((value (org-export-data
4943 (org-element-contents
4944 (elt (org-element-contents row) column))
4945 info)))
4946 (cl-incf total-cells)
4947 ;; Treat an empty cell as a number if it follows
4948 ;; a number.
4949 (if (not (or (string-match org-table-number-regexp value)
4950 (and (string= value "") previous-cell-number-p)))
4951 (setq previous-cell-number-p nil)
4952 (setq previous-cell-number-p t)
4953 (cl-incf number-cells))))))
4954 ;; Return value. Alignment specified by cookies has
4955 ;; precedence over alignment deduced from cell's contents.
4956 (aset align-vector
4957 column
4958 (cond ((equal cookie-align "l") 'left)
4959 ((equal cookie-align "r") 'right)
4960 ((equal cookie-align "c") 'center)
4961 ((>= (/ (float number-cells) total-cells)
4962 org-table-number-fraction)
4963 'right)
4964 (t 'left)))))))
4966 (defun org-export-table-cell-borders (table-cell info)
4967 "Return TABLE-CELL borders.
4969 INFO is a plist used as a communication channel.
4971 Return value is a list of symbols, or nil. Possible values are:
4972 `top', `bottom', `above', `below', `left' and `right'. Note:
4973 `top' (resp. `bottom') only happen for a cell in the first
4974 row (resp. last row) of the table, ignoring table rules, if any.
4976 Returned borders ignore special rows."
4977 (let* ((row (org-export-get-parent table-cell))
4978 (table (org-export-get-parent-table table-cell))
4979 borders)
4980 ;; Top/above border? TABLE-CELL has a border above when a rule
4981 ;; used to demarcate row groups can be found above. Hence,
4982 ;; finding a rule isn't sufficient to push `above' in BORDERS:
4983 ;; another regular row has to be found above that rule.
4984 (let (rule-flag)
4985 (catch 'exit
4986 ;; Look at every row before the current one.
4987 (dolist (row (cdr (memq row (reverse (org-element-contents table)))))
4988 (cond ((eq (org-element-property :type row) 'rule)
4989 (setq rule-flag t))
4990 ((not (org-export-table-row-is-special-p row info))
4991 (if rule-flag (throw 'exit (push 'above borders))
4992 (throw 'exit nil)))))
4993 ;; No rule above, or rule found starts the table (ignoring any
4994 ;; special row): TABLE-CELL is at the top of the table.
4995 (when rule-flag (push 'above borders))
4996 (push 'top borders)))
4997 ;; Bottom/below border? TABLE-CELL has a border below when next
4998 ;; non-regular row below is a rule.
4999 (let (rule-flag)
5000 (catch 'exit
5001 ;; Look at every row after the current one.
5002 (dolist (row (cdr (memq row (org-element-contents table))))
5003 (cond ((eq (org-element-property :type row) 'rule)
5004 (setq rule-flag t))
5005 ((not (org-export-table-row-is-special-p row info))
5006 (if rule-flag (throw 'exit (push 'below borders))
5007 (throw 'exit nil)))))
5008 ;; No rule below, or rule found ends the table (modulo some
5009 ;; special row): TABLE-CELL is at the bottom of the table.
5010 (when rule-flag (push 'below borders))
5011 (push 'bottom borders)))
5012 ;; Right/left borders? They can only be specified by column
5013 ;; groups. Column groups are defined in a row starting with "/".
5014 ;; Also a column groups row only contains "<", "<>", ">" or blank
5015 ;; cells.
5016 (catch 'exit
5017 (let ((column (let ((cells (org-element-contents row)))
5018 (- (length cells) (length (memq table-cell cells))))))
5019 ;; Table rows are read in reverse order so last column groups
5020 ;; row has precedence over any previous one.
5021 (dolist (row (reverse (org-element-contents table)))
5022 (unless (eq (org-element-property :type row) 'rule)
5023 (when (equal (org-element-contents
5024 (car (org-element-contents row)))
5025 '("/"))
5026 (let ((column-groups
5027 (mapcar
5028 (lambda (cell)
5029 (let ((value (org-element-contents cell)))
5030 (when (member value '(("<") ("<>") (">") nil))
5031 (car value))))
5032 (org-element-contents row))))
5033 ;; There's a left border when previous cell, if
5034 ;; any, ends a group, or current one starts one.
5035 (when (or (and (not (zerop column))
5036 (member (elt column-groups (1- column))
5037 '(">" "<>")))
5038 (member (elt column-groups column) '("<" "<>")))
5039 (push 'left borders))
5040 ;; There's a right border when next cell, if any,
5041 ;; starts a group, or current one ends one.
5042 (when (or (and (/= (1+ column) (length column-groups))
5043 (member (elt column-groups (1+ column))
5044 '("<" "<>")))
5045 (member (elt column-groups column) '(">" "<>")))
5046 (push 'right borders))
5047 (throw 'exit nil)))))))
5048 ;; Return value.
5049 borders))
5051 (defun org-export-table-cell-starts-colgroup-p (table-cell info)
5052 "Non-nil when TABLE-CELL is at the beginning of a column group.
5053 INFO is a plist used as a communication channel."
5054 ;; A cell starts a column group either when it is at the beginning
5055 ;; of a row (or after the special column, if any) or when it has
5056 ;; a left border.
5057 (or (eq (org-element-map (org-export-get-parent table-cell) 'table-cell
5058 'identity info 'first-match)
5059 table-cell)
5060 (memq 'left (org-export-table-cell-borders table-cell info))))
5062 (defun org-export-table-cell-ends-colgroup-p (table-cell info)
5063 "Non-nil when TABLE-CELL is at the end of a column group.
5064 INFO is a plist used as a communication channel."
5065 ;; A cell ends a column group either when it is at the end of a row
5066 ;; or when it has a right border.
5067 (or (eq (car (last (org-element-contents
5068 (org-export-get-parent table-cell))))
5069 table-cell)
5070 (memq 'right (org-export-table-cell-borders table-cell info))))
5072 (defun org-export-table-row-starts-rowgroup-p (table-row info)
5073 "Non-nil when TABLE-ROW is at the beginning of a row group.
5074 INFO is a plist used as a communication channel."
5075 (unless (or (eq (org-element-property :type table-row) 'rule)
5076 (org-export-table-row-is-special-p table-row info))
5077 (let ((borders (org-export-table-cell-borders
5078 (car (org-element-contents table-row)) info)))
5079 (or (memq 'top borders) (memq 'above borders)))))
5081 (defun org-export-table-row-ends-rowgroup-p (table-row info)
5082 "Non-nil when TABLE-ROW is at the end of a row group.
5083 INFO is a plist used as a communication channel."
5084 (unless (or (eq (org-element-property :type table-row) 'rule)
5085 (org-export-table-row-is-special-p table-row info))
5086 (let ((borders (org-export-table-cell-borders
5087 (car (org-element-contents table-row)) info)))
5088 (or (memq 'bottom borders) (memq 'below borders)))))
5090 (defun org-export-table-row-in-header-p (table-row info)
5091 "Non-nil when TABLE-ROW is located within table's header.
5092 INFO is a plist used as a communication channel. Always return
5093 nil for special rows and rows separators."
5094 (and (org-export-table-has-header-p
5095 (org-export-get-parent-table table-row) info)
5096 (eql (org-export-table-row-group table-row info) 1)))
5098 (defun org-export-table-row-starts-header-p (table-row info)
5099 "Non-nil when TABLE-ROW is the first table header's row.
5100 INFO is a plist used as a communication channel."
5101 (and (org-export-table-row-in-header-p table-row info)
5102 (org-export-table-row-starts-rowgroup-p table-row info)))
5104 (defun org-export-table-row-ends-header-p (table-row info)
5105 "Non-nil when TABLE-ROW is the last table header's row.
5106 INFO is a plist used as a communication channel."
5107 (and (org-export-table-row-in-header-p table-row info)
5108 (org-export-table-row-ends-rowgroup-p table-row info)))
5110 (defun org-export-table-row-number (table-row info)
5111 "Return TABLE-ROW number.
5112 INFO is a plist used as a communication channel. Return value is
5113 zero-indexed and ignores separators. The function returns nil
5114 for special rows and separators."
5115 (when (eq (org-element-property :type table-row) 'standard)
5116 (let* ((cache (or (plist-get info :table-row-number-cache)
5117 (let ((table (make-hash-table :test #'eq)))
5118 (plist-put info :table-row-number-cache table)
5119 table)))
5120 (cached (gethash table-row cache 'no-cache)))
5121 (if (not (eq cached 'no-cache)) cached
5122 ;; First time a row is queried, populate cache with all the
5123 ;; rows from the table.
5124 (let ((number -1))
5125 (org-element-map (org-export-get-parent-table table-row) 'table-row
5126 (lambda (row)
5127 (when (eq (org-element-property :type row) 'standard)
5128 (puthash row (cl-incf number) cache)))
5129 info))
5130 (gethash table-row cache)))))
5132 (defun org-export-table-dimensions (table info)
5133 "Return TABLE dimensions.
5135 INFO is a plist used as a communication channel.
5137 Return value is a CONS like (ROWS . COLUMNS) where
5138 ROWS (resp. COLUMNS) is the number of exportable
5139 rows (resp. columns)."
5140 (let (first-row (columns 0) (rows 0))
5141 ;; Set number of rows, and extract first one.
5142 (org-element-map table 'table-row
5143 (lambda (row)
5144 (when (eq (org-element-property :type row) 'standard)
5145 (cl-incf rows)
5146 (unless first-row (setq first-row row)))) info)
5147 ;; Set number of columns.
5148 (org-element-map first-row 'table-cell (lambda (_) (cl-incf columns)) info)
5149 ;; Return value.
5150 (cons rows columns)))
5152 (defun org-export-table-cell-address (table-cell info)
5153 "Return address of a regular TABLE-CELL object.
5155 TABLE-CELL is the cell considered. INFO is a plist used as
5156 a communication channel.
5158 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
5159 zero-based index. Only exportable cells are considered. The
5160 function returns nil for other cells."
5161 (let* ((table-row (org-export-get-parent table-cell))
5162 (row-number (org-export-table-row-number table-row info)))
5163 (when row-number
5164 (cons row-number
5165 (let ((col-count 0))
5166 (org-element-map table-row 'table-cell
5167 (lambda (cell)
5168 (if (eq cell table-cell) col-count (cl-incf col-count) nil))
5169 info 'first-match))))))
5171 (defun org-export-get-table-cell-at (address table info)
5172 "Return regular table-cell object at ADDRESS in TABLE.
5174 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
5175 zero-based index. TABLE is a table type element. INFO is
5176 a plist used as a communication channel.
5178 If no table-cell, among exportable cells, is found at ADDRESS,
5179 return nil."
5180 (let ((column-pos (cdr address)) (column-count 0))
5181 (org-element-map
5182 ;; Row at (car address) or nil.
5183 (let ((row-pos (car address)) (row-count 0))
5184 (org-element-map table 'table-row
5185 (lambda (row)
5186 (cond ((eq (org-element-property :type row) 'rule) nil)
5187 ((= row-count row-pos) row)
5188 (t (cl-incf row-count) nil)))
5189 info 'first-match))
5190 'table-cell
5191 (lambda (cell)
5192 (if (= column-count column-pos) cell
5193 (cl-incf column-count) nil))
5194 info 'first-match)))
5197 ;;;; For Tables Of Contents
5199 ;; `org-export-collect-headlines' builds a list of all exportable
5200 ;; headline elements, maybe limited to a certain depth. One can then
5201 ;; easily parse it and transcode it.
5203 ;; Building lists of tables, figures or listings is quite similar.
5204 ;; Once the generic function `org-export-collect-elements' is defined,
5205 ;; `org-export-collect-tables', `org-export-collect-figures' and
5206 ;; `org-export-collect-listings' can be derived from it.
5208 (defun org-export-collect-headlines (info &optional n scope)
5209 "Collect headlines in order to build a table of contents.
5211 INFO is a plist used as a communication channel.
5213 When optional argument N is an integer, it specifies the depth of
5214 the table of contents. Otherwise, it is set to the value of the
5215 last headline level. See `org-export-headline-levels' for more
5216 information.
5218 Optional argument SCOPE, when non-nil, is an element. If it is
5219 a headline, only children of SCOPE are collected. Otherwise,
5220 collect children of the headline containing provided element. If
5221 there is no such headline, collect all headlines. In any case,
5222 argument N becomes relative to the level of that headline.
5224 Return a list of all exportable headlines as parsed elements.
5225 Footnote sections are ignored."
5226 (let* ((scope (cond ((not scope) (plist-get info :parse-tree))
5227 ((eq (org-element-type scope) 'headline) scope)
5228 ((org-export-get-parent-headline scope))
5229 (t (plist-get info :parse-tree))))
5230 (limit (plist-get info :headline-levels))
5231 (n (if (not (wholenump n)) limit
5232 (min (if (eq (org-element-type scope) 'org-data) n
5233 (+ (org-export-get-relative-level scope info) n))
5234 limit))))
5235 (org-element-map (org-element-contents scope) 'headline
5236 (lambda (headline)
5237 (unless (org-element-property :footnote-section-p headline)
5238 (let ((level (org-export-get-relative-level headline info)))
5239 (and (<= level n) headline))))
5240 info)))
5242 (defun org-export-collect-elements (type info &optional predicate)
5243 "Collect referenceable elements of a determined type.
5245 TYPE can be a symbol or a list of symbols specifying element
5246 types to search. Only elements with a caption are collected.
5248 INFO is a plist used as a communication channel.
5250 When non-nil, optional argument PREDICATE is a function accepting
5251 one argument, an element of type TYPE. It returns a non-nil
5252 value when that element should be collected.
5254 Return a list of all elements found, in order of appearance."
5255 (org-element-map (plist-get info :parse-tree) type
5256 (lambda (element)
5257 (and (org-element-property :caption element)
5258 (or (not predicate) (funcall predicate element))
5259 element))
5260 info))
5262 (defun org-export-collect-tables (info)
5263 "Build a list of tables.
5264 INFO is a plist used as a communication channel.
5266 Return a list of table elements with a caption."
5267 (org-export-collect-elements 'table info))
5269 (defun org-export-collect-figures (info predicate)
5270 "Build a list of figures.
5272 INFO is a plist used as a communication channel. PREDICATE is
5273 a function which accepts one argument: a paragraph element and
5274 whose return value is non-nil when that element should be
5275 collected.
5277 A figure is a paragraph type element, with a caption, verifying
5278 PREDICATE. The latter has to be provided since a \"figure\" is
5279 a vague concept that may depend on back-end.
5281 Return a list of elements recognized as figures."
5282 (org-export-collect-elements 'paragraph info predicate))
5284 (defun org-export-collect-listings (info)
5285 "Build a list of src blocks.
5287 INFO is a plist used as a communication channel.
5289 Return a list of src-block elements with a caption."
5290 (org-export-collect-elements 'src-block info))
5293 ;;;; Smart Quotes
5295 ;; The main function for the smart quotes sub-system is
5296 ;; `org-export-activate-smart-quotes', which replaces every quote in
5297 ;; a given string from the parse tree with its "smart" counterpart.
5299 ;; Dictionary for smart quotes is stored in
5300 ;; `org-export-smart-quotes-alist'.
5302 (defconst org-export-smart-quotes-alist
5303 '(("ar"
5304 (primary-opening
5305 :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5306 :texinfo "@guillemetleft{}")
5307 (primary-closing
5308 :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5309 :texinfo "@guillemetright{}")
5310 (secondary-opening :utf-8 "‹" :html "&lsaquo;" :latex "\\guilsinglleft{}"
5311 :texinfo "@guilsinglleft{}")
5312 (secondary-closing :utf-8 "›" :html "&rsaquo;" :latex "\\guilsinglright{}"
5313 :texinfo "@guilsinglright{}")
5314 (apostrophe :utf-8 "’" :html "&rsquo;"))
5315 ("da"
5316 ;; one may use: »...«, "...", ›...‹, or '...'.
5317 ;; http://sproget.dk/raad-og-regler/retskrivningsregler/retskrivningsregler/a7-40-60/a7-58-anforselstegn/
5318 ;; LaTeX quotes require Babel!
5319 (primary-opening
5320 :utf-8 "»" :html "&raquo;" :latex ">>" :texinfo "@guillemetright{}")
5321 (primary-closing
5322 :utf-8 "«" :html "&laquo;" :latex "<<" :texinfo "@guillemetleft{}")
5323 (secondary-opening
5324 :utf-8 "›" :html "&rsaquo;" :latex "\\frq{}" :texinfo "@guilsinglright{}")
5325 (secondary-closing
5326 :utf-8 "‹" :html "&lsaquo;" :latex "\\flq{}" :texinfo "@guilsingleft{}")
5327 (apostrophe :utf-8 "’" :html "&rsquo;"))
5328 ("de"
5329 (primary-opening
5330 :utf-8 "„" :html "&bdquo;" :latex "\"`" :texinfo "@quotedblbase{}")
5331 (primary-closing
5332 :utf-8 "“" :html "&ldquo;" :latex "\"'" :texinfo "@quotedblleft{}")
5333 (secondary-opening
5334 :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}" :texinfo "@quotesinglbase{}")
5335 (secondary-closing
5336 :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}" :texinfo "@quoteleft{}")
5337 (apostrophe :utf-8 "’" :html "&rsquo;"))
5338 ("en"
5339 (primary-opening :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
5340 (primary-closing :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
5341 (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5342 (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5343 (apostrophe :utf-8 "’" :html "&rsquo;"))
5344 ("es"
5345 (primary-opening
5346 :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5347 :texinfo "@guillemetleft{}")
5348 (primary-closing
5349 :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5350 :texinfo "@guillemetright{}")
5351 (secondary-opening :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
5352 (secondary-closing :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
5353 (apostrophe :utf-8 "’" :html "&rsquo;"))
5354 ("fr"
5355 (primary-opening
5356 :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
5357 :texinfo "@guillemetleft{}@tie{}")
5358 (primary-closing
5359 :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
5360 :texinfo "@tie{}@guillemetright{}")
5361 (secondary-opening
5362 :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
5363 :texinfo "@guillemetleft{}@tie{}")
5364 (secondary-closing :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
5365 :texinfo "@tie{}@guillemetright{}")
5366 (apostrophe :utf-8 "’" :html "&rsquo;"))
5367 ("is"
5368 (primary-opening
5369 :utf-8 "„" :html "&bdquo;" :latex "\"`" :texinfo "@quotedblbase{}")
5370 (primary-closing
5371 :utf-8 "“" :html "&ldquo;" :latex "\"'" :texinfo "@quotedblleft{}")
5372 (secondary-opening
5373 :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}" :texinfo "@quotesinglbase{}")
5374 (secondary-closing
5375 :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}" :texinfo "@quoteleft{}")
5376 (apostrophe :utf-8 "’" :html "&rsquo;"))
5377 ("no"
5378 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5379 (primary-opening
5380 :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5381 :texinfo "@guillemetleft{}")
5382 (primary-closing
5383 :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5384 :texinfo "@guillemetright{}")
5385 (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5386 (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5387 (apostrophe :utf-8 "’" :html "&rsquo;"))
5388 ("nb"
5389 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5390 (primary-opening
5391 :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5392 :texinfo "@guillemetleft{}")
5393 (primary-closing
5394 :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5395 :texinfo "@guillemetright{}")
5396 (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5397 (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5398 (apostrophe :utf-8 "’" :html "&rsquo;"))
5399 ("nn"
5400 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5401 (primary-opening
5402 :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5403 :texinfo "@guillemetleft{}")
5404 (primary-closing
5405 :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5406 :texinfo "@guillemetright{}")
5407 (secondary-opening :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5408 (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5409 (apostrophe :utf-8 "’" :html "&rsquo;"))
5410 ("ru"
5411 ;; 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
5412 ;; http://www.artlebedev.ru/kovodstvo/sections/104/
5413 (primary-opening :utf-8 "«" :html "&laquo;" :latex "{}<<"
5414 :texinfo "@guillemetleft{}")
5415 (primary-closing :utf-8 "»" :html "&raquo;" :latex ">>{}"
5416 :texinfo "@guillemetright{}")
5417 (secondary-opening
5418 :utf-8 "„" :html "&bdquo;" :latex "\\glqq{}" :texinfo "@quotedblbase{}")
5419 (secondary-closing
5420 :utf-8 "“" :html "&ldquo;" :latex "\\grqq{}" :texinfo "@quotedblleft{}")
5421 (apostrophe :utf-8 "’" :html: "&#39;"))
5422 ("sv"
5423 ;; based on https://sv.wikipedia.org/wiki/Citattecken
5424 (primary-opening :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
5425 (primary-closing :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
5426 (secondary-opening :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "`")
5427 (secondary-closing :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "'")
5428 (apostrophe :utf-8 "’" :html "&rsquo;")))
5429 "Smart quotes translations.
5431 Alist whose CAR is a language string and CDR is an alist with
5432 quote type as key and a plist associating various encodings to
5433 their translation as value.
5435 A quote type can be any symbol among `primary-opening',
5436 `primary-closing', `secondary-opening', `secondary-closing' and
5437 `apostrophe'.
5439 Valid encodings include `:utf-8', `:html', `:latex' and
5440 `:texinfo'.
5442 If no translation is found, the quote character is left as-is.")
5444 (defun org-export--smart-quote-status (s info)
5445 "Return smart quote status at the beginning of string S.
5446 INFO is the current export state, as a plist."
5447 (let* ((parent (org-element-property :parent s))
5448 (cache (or (plist-get info :smart-quote-cache)
5449 (let ((table (make-hash-table :test #'eq)))
5450 (plist-put info :smart-quote-cache table)
5451 table)))
5452 (value (gethash parent cache 'missing-data)))
5453 (if (not (eq value 'missing-data)) (cdr (assq s value))
5454 (let (level1-open full-status)
5455 (org-element-map
5456 (let ((secondary (org-element-secondary-p s)))
5457 (if secondary (org-element-property secondary parent)
5458 (org-element-contents parent)))
5459 'plain-text
5460 (lambda (text)
5461 (let ((start 0) current-status)
5462 (while (setq start (string-match "['\"]" text start))
5463 (push
5464 (cond
5465 ((equal (match-string 0 text) "\"")
5466 (setf level1-open (not level1-open))
5467 (if level1-open 'primary-opening 'primary-closing))
5468 ;; Not already in a level 1 quote: this is an
5469 ;; apostrophe.
5470 ((not level1-open) 'apostrophe)
5471 ;; Extract previous char and next char. As
5472 ;; a special case, they can also be set to `blank',
5473 ;; `no-blank' or nil. Then determine if current
5474 ;; match is allowed as an opening quote or a closing
5475 ;; quote.
5477 (let* ((previous
5478 (if (> start 0) (substring text (1- start) start)
5479 (let ((p (org-export-get-previous-element
5480 text info)))
5481 (cond ((not p) nil)
5482 ((stringp p) (substring p -1))
5483 ((memq (org-element-property :post-blank p)
5484 '(0 nil))
5485 'no-blank)
5486 (t 'blank)))))
5487 (next
5488 (if (< (1+ start) (length text))
5489 (substring text (1+ start) (+ start 2))
5490 (let ((n (org-export-get-next-element text info)))
5491 (cond ((not n) nil)
5492 ((stringp n) (substring n 0 1))
5493 (t 'no-blank)))))
5494 (allow-open
5495 (and (if (stringp previous)
5496 (string-match "\\s\"\\|\\s-\\|\\s("
5497 previous)
5498 (memq previous '(blank nil)))
5499 (if (stringp next)
5500 (string-match "\\w\\|\\s.\\|\\s_" next)
5501 (eq next 'no-blank))))
5502 (allow-close
5503 (and (if (stringp previous)
5504 (string-match "\\w\\|\\s.\\|\\s_" previous)
5505 (eq previous 'no-blank))
5506 (if (stringp next)
5507 (string-match "\\s-\\|\\s)\\|\\s.\\|\\s\""
5508 next)
5509 (memq next '(blank nil))))))
5510 (cond
5511 ((and allow-open allow-close) (error "Should not happen"))
5512 (allow-open 'secondary-opening)
5513 (allow-close 'secondary-closing)
5514 (t 'apostrophe)))))
5515 current-status)
5516 (cl-incf start))
5517 (when current-status
5518 (push (cons text (nreverse current-status)) full-status))))
5519 info nil org-element-recursive-objects)
5520 (puthash parent full-status cache)
5521 (cdr (assq s full-status))))))
5523 (defun org-export-activate-smart-quotes (s encoding info &optional original)
5524 "Replace regular quotes with \"smart\" quotes in string S.
5526 ENCODING is a symbol among `:html', `:latex', `:texinfo' and
5527 `:utf-8'. INFO is a plist used as a communication channel.
5529 The function has to retrieve information about string
5530 surroundings in parse tree. It can only happen with an
5531 unmodified string. Thus, if S has already been through another
5532 process, a non-nil ORIGINAL optional argument will provide that
5533 original string.
5535 Return the new string."
5536 (let ((quote-status
5537 (copy-sequence (org-export--smart-quote-status (or original s) info))))
5538 (replace-regexp-in-string
5539 "['\"]"
5540 (lambda (match)
5541 (or (plist-get
5542 (cdr (assq (pop quote-status)
5543 (cdr (assoc (plist-get info :language)
5544 org-export-smart-quotes-alist))))
5545 encoding)
5546 match))
5547 s nil t)))
5549 ;;;; Topology
5551 ;; Here are various functions to retrieve information about the
5552 ;; neighborhood of a given element or object. Neighbors of interest
5553 ;; are direct parent (`org-export-get-parent'), parent headline
5554 ;; (`org-export-get-parent-headline'), first element containing an
5555 ;; object, (`org-export-get-parent-element'), parent table
5556 ;; (`org-export-get-parent-table'), previous element or object
5557 ;; (`org-export-get-previous-element') and next element or object
5558 ;; (`org-export-get-next-element').
5560 ;; defsubst org-export-get-parent must be defined before first use
5562 (defun org-export-get-parent-headline (blob)
5563 "Return BLOB parent headline or nil.
5564 BLOB is the element or object being considered."
5565 (org-element-lineage blob '(headline)))
5567 (defun org-export-get-parent-element (object)
5568 "Return first element containing OBJECT or nil.
5569 OBJECT is the object to consider."
5570 (org-element-lineage object org-element-all-elements))
5572 (defun org-export-get-parent-table (object)
5573 "Return OBJECT parent table or nil.
5574 OBJECT is either a `table-cell' or `table-element' type object."
5575 (org-element-lineage object '(table)))
5577 (defun org-export-get-previous-element (blob info &optional n)
5578 "Return previous element or object.
5580 BLOB is an element or object. INFO is a plist used as
5581 a communication channel. Return previous exportable element or
5582 object, a string, or nil.
5584 When optional argument N is a positive integer, return a list
5585 containing up to N siblings before BLOB, from farthest to
5586 closest. With any other non-nil value, return a list containing
5587 all of them."
5588 (let* ((secondary (org-element-secondary-p blob))
5589 (parent (org-export-get-parent blob))
5590 (siblings
5591 (if secondary (org-element-property secondary parent)
5592 (org-element-contents parent)))
5593 prev)
5594 (catch 'exit
5595 (dolist (obj (cdr (memq blob (reverse siblings))) prev)
5596 (cond ((memq obj (plist-get info :ignore-list)))
5597 ((null n) (throw 'exit obj))
5598 ((not (wholenump n)) (push obj prev))
5599 ((zerop n) (throw 'exit prev))
5600 (t (cl-decf n) (push obj prev)))))))
5602 (defun org-export-get-next-element (blob info &optional n)
5603 "Return next element or object.
5605 BLOB is an element or object. INFO is a plist used as
5606 a communication channel. Return next exportable element or
5607 object, a string, or nil.
5609 When optional argument N is a positive integer, return a list
5610 containing up to N siblings after BLOB, from closest to farthest.
5611 With any other non-nil value, return a list containing all of
5612 them."
5613 (let* ((secondary (org-element-secondary-p blob))
5614 (parent (org-export-get-parent blob))
5615 (siblings
5616 (cdr (memq blob
5617 (if secondary (org-element-property secondary parent)
5618 (org-element-contents parent)))))
5619 next)
5620 (catch 'exit
5621 (dolist (obj siblings (nreverse next))
5622 (cond ((memq obj (plist-get info :ignore-list)))
5623 ((null n) (throw 'exit obj))
5624 ((not (wholenump n)) (push obj next))
5625 ((zerop n) (throw 'exit (nreverse next)))
5626 (t (cl-decf n) (push obj next)))))))
5629 ;;;; Translation
5631 ;; `org-export-translate' translates a string according to the language
5632 ;; specified by the LANGUAGE keyword. `org-export-dictionary' contains
5633 ;; the dictionary used for the translation.
5635 (defconst org-export-dictionary
5636 '(("%e %n: %c"
5637 ("fr" :default "%e %n : %c" :html "%e&nbsp;%n&nbsp;: %c"))
5638 ("Author"
5639 ("ar" :default "تأليف")
5640 ("ca" :default "Autor")
5641 ("cs" :default "Autor")
5642 ("da" :default "Forfatter")
5643 ("de" :default "Autor")
5644 ("eo" :html "A&#365;toro")
5645 ("es" :default "Autor")
5646 ("et" :default "Autor")
5647 ("fi" :html "Tekij&auml;")
5648 ("fr" :default "Auteur")
5649 ("hu" :default "Szerz&otilde;")
5650 ("is" :html "H&ouml;fundur")
5651 ("it" :default "Autore")
5652 ("ja" :default "著者" :html "&#33879;&#32773;")
5653 ("nl" :default "Auteur")
5654 ("no" :default "Forfatter")
5655 ("nb" :default "Forfatter")
5656 ("nn" :default "Forfattar")
5657 ("pl" :default "Autor")
5658 ("pt_BR" :default "Autor")
5659 ("ru" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5660 ("sv" :html "F&ouml;rfattare")
5661 ("uk" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5662 ("zh-CN" :html "&#20316;&#32773;" :utf-8 "作者")
5663 ("zh-TW" :html "&#20316;&#32773;" :utf-8 "作者"))
5664 ("Continued from previous page"
5665 ("ar" :default "تتمة الصفحة السابقة")
5666 ("de" :default "Fortsetzung von vorheriger Seite")
5667 ("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")
5668 ("fr" :default "Suite de la page précédente")
5669 ("it" :default "Continua da pagina precedente")
5670 ("ja" :default "前ページからの続き")
5671 ("nl" :default "Vervolg van vorige pagina")
5672 ("pt" :default "Continuação da página anterior")
5673 ("ru" :html "(&#1055;&#1088;&#1086;&#1076;&#1086;&#1083;&#1078;&#1077;&#1085;&#1080;&#1077;)"
5674 :utf-8 "(Продолжение)"))
5675 ("Continued on next page"
5676 ("ar" :default "التتمة في الصفحة التالية")
5677 ("de" :default "Fortsetzung nächste Seite")
5678 ("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")
5679 ("fr" :default "Suite page suivante")
5680 ("it" :default "Continua alla pagina successiva")
5681 ("ja" :default "次ページに続く")
5682 ("nl" :default "Vervolg op volgende pagina")
5683 ("pt" :default "Continua na página seguinte")
5684 ("ru" :html "(&#1055;&#1088;&#1086;&#1076;&#1086;&#1083;&#1078;&#1077;&#1085;&#1080;&#1077; &#1089;&#1083;&#1077;&#1076;&#1091;&#1077;&#1090;)"
5685 :utf-8 "(Продолжение следует)"))
5686 ("Date"
5687 ("ar" :default "بتاريخ")
5688 ("ca" :default "Data")
5689 ("cs" :default "Datum")
5690 ("da" :default "Dato")
5691 ("de" :default "Datum")
5692 ("eo" :default "Dato")
5693 ("es" :default "Fecha")
5694 ("et" :html "Kuup&#228;ev" :utf-8 "Kuupäev")
5695 ("fi" :html "P&auml;iv&auml;m&auml;&auml;r&auml;")
5696 ("hu" :html "D&aacute;tum")
5697 ("is" :default "Dagsetning")
5698 ("it" :default "Data")
5699 ("ja" :default "日付" :html "&#26085;&#20184;")
5700 ("nl" :default "Datum")
5701 ("no" :default "Dato")
5702 ("nb" :default "Dato")
5703 ("nn" :default "Dato")
5704 ("pl" :default "Data")
5705 ("pt_BR" :default "Data")
5706 ("ru" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5707 ("sv" :default "Datum")
5708 ("uk" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5709 ("zh-CN" :html "&#26085;&#26399;" :utf-8 "日期")
5710 ("zh-TW" :html "&#26085;&#26399;" :utf-8 "日期"))
5711 ("Equation"
5712 ("ar" :default "معادلة")
5713 ("da" :default "Ligning")
5714 ("de" :default "Gleichung")
5715 ("es" :ascii "Ecuacion" :html "Ecuaci&oacute;n" :default "Ecuación")
5716 ("et" :html "V&#245;rrand" :utf-8 "Võrrand")
5717 ("fr" :ascii "Equation" :default "Équation")
5718 ("is" :default "Jafna")
5719 ("ja" :default "方程式")
5720 ("no" :default "Ligning")
5721 ("nb" :default "Ligning")
5722 ("nn" :default "Likning")
5723 ("pt_BR" :html "Equa&ccedil;&atilde;o" :default "Equação" :ascii "Equacao")
5724 ("ru" :html "&#1059;&#1088;&#1072;&#1074;&#1085;&#1077;&#1085;&#1080;&#1077;"
5725 :utf-8 "Уравнение")
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 ("sv" :default "Illustration %d")
5758 ("zh-CN" :html "&#22270;%d&nbsp;" :utf-8 "图%d "))
5759 ("Footnotes"
5760 ("ar" :default "الهوامش")
5761 ("ca" :html "Peus de p&agrave;gina")
5762 ("cs" :default "Pozn\xe1mky pod carou")
5763 ("da" :default "Fodnoter")
5764 ("de" :html "Fu&szlig;noten" :default "Fußnoten")
5765 ("eo" :default "Piednotoj")
5766 ("es" :ascii "Nota al pie de pagina" :html "Nota al pie de p&aacute;gina" :default "Nota al pie de página")
5767 ("et" :html "Allm&#228;rkused" :utf-8 "Allmärkused")
5768 ("fi" :default "Alaviitteet")
5769 ("fr" :default "Notes de bas de page")
5770 ("hu" :html "L&aacute;bjegyzet")
5771 ("is" :html "Aftanm&aacute;lsgreinar")
5772 ("it" :html "Note a pi&egrave; di pagina")
5773 ("ja" :default "脚注" :html "&#33050;&#27880;")
5774 ("nl" :default "Voetnoten")
5775 ("no" :default "Fotnoter")
5776 ("nb" :default "Fotnoter")
5777 ("nn" :default "Fotnotar")
5778 ("pl" :default "Przypis")
5779 ("pt_BR" :html "Notas de Rodap&eacute;" :default "Notas de Rodapé" :ascii "Notas de Rodape")
5780 ("ru" :html "&#1057;&#1085;&#1086;&#1089;&#1082;&#1080;" :utf-8 "Сноски")
5781 ("sv" :default "Fotnoter")
5782 ("uk" :html "&#1055;&#1088;&#1080;&#1084;&#1110;&#1090;&#1082;&#1080;"
5783 :utf-8 "Примітки")
5784 ("zh-CN" :html "&#33050;&#27880;" :utf-8 "脚注")
5785 ("zh-TW" :html "&#33139;&#35387;" :utf-8 "腳註"))
5786 ("List of Listings"
5787 ("ar" :default "قائمة بالبرامج")
5788 ("da" :default "Programmer")
5789 ("de" :default "Programmauflistungsverzeichnis")
5790 ("es" :ascii "Indice de Listados de programas" :html "&Iacute;ndice de Listados de programas" :default "Índice de Listados de programas")
5791 ("et" :default "Loendite nimekiri")
5792 ("fr" :default "Liste des programmes")
5793 ("ja" :default "ソースコード目次")
5794 ("no" :default "Dataprogrammer")
5795 ("nb" :default "Dataprogrammer")
5796 ("ru" :html "&#1057;&#1087;&#1080;&#1089;&#1086;&#1082; &#1088;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1086;&#1082;"
5797 :utf-8 "Список распечаток")
5798 ("zh-CN" :html "&#20195;&#30721;&#30446;&#24405;" :utf-8 "代码目录"))
5799 ("List of Tables"
5800 ("ar" :default "قائمة بالجداول")
5801 ("da" :default "Tabeller")
5802 ("de" :default "Tabellenverzeichnis")
5803 ("es" :ascii "Indice de tablas" :html "&Iacute;ndice de tablas" :default "Índice de tablas")
5804 ("et" :default "Tabelite nimekiri")
5805 ("fr" :default "Liste des tableaux")
5806 ("is" :default "Töfluskrá" :html "T&ouml;fluskr&aacute;")
5807 ("ja" :default "表目次")
5808 ("no" :default "Tabeller")
5809 ("nb" :default "Tabeller")
5810 ("nn" :default "Tabeller")
5811 ("pt_BR" :default "Índice de Tabelas" :ascii "Indice de Tabelas")
5812 ("ru" :html "&#1057;&#1087;&#1080;&#1089;&#1086;&#1082; &#1090;&#1072;&#1073;&#1083;&#1080;&#1094;"
5813 :utf-8 "Список таблиц")
5814 ("sv" :default "Tabeller")
5815 ("zh-CN" :html "&#34920;&#26684;&#30446;&#24405;" :utf-8 "表格目录"))
5816 ("Listing"
5817 ("ar" :default "برنامج")
5818 ("da" :default "Program")
5819 ("de" :default "Programmlisting")
5820 ("es" :default "Listado de programa")
5821 ("et" :default "Loend")
5822 ("fr" :default "Programme" :html "Programme")
5823 ("ja" :default "ソースコード")
5824 ("no" :default "Dataprogram")
5825 ("nb" :default "Dataprogram")
5826 ("pt_BR" :default "Listagem")
5827 ("ru" :html "&#1056;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1082;&#1072;"
5828 :utf-8 "Распечатка")
5829 ("zh-CN" :html "&#20195;&#30721;" :utf-8 "代码"))
5830 ("Listing %d:"
5831 ("ar" :default "برنامج %d:")
5832 ("da" :default "Program %d")
5833 ("de" :default "Programmlisting %d")
5834 ("es" :default "Listado de programa %d")
5835 ("et" :default "Loend %d")
5836 ("fr" :default "Programme %d :" :html "Programme&nbsp;%d&nbsp;:")
5837 ("ja" :default "ソースコード%d:")
5838 ("no" :default "Dataprogram %d")
5839 ("nb" :default "Dataprogram %d")
5840 ("pt_BR" :default "Listagem %d")
5841 ("ru" :html "&#1056;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1082;&#1072; %d.:"
5842 :utf-8 "Распечатка %d.:")
5843 ("zh-CN" :html "&#20195;&#30721;%d&nbsp;" :utf-8 "代码%d "))
5844 ("References"
5845 ("ar" :default "المراجع")
5846 ("fr" :ascii "References" :default "Références")
5847 ("de" :default "Quellen")
5848 ("es" :default "Referencias"))
5849 ("See figure %s"
5850 ("fr" :default "cf. figure %s"
5851 :html "cf.&nbsp;figure&nbsp;%s" :latex "cf.~figure~%s"))
5852 ("See listing %s"
5853 ("fr" :default "cf. programme %s"
5854 :html "cf.&nbsp;programme&nbsp;%s" :latex "cf.~programme~%s"))
5855 ("See section %s"
5856 ("ar" :default "انظر قسم %s")
5857 ("da" :default "jævnfør afsnit %s")
5858 ("de" :default "siehe Abschnitt %s")
5859 ("es" :ascii "Vea seccion %s" :html "Vea secci&oacute;n %s" :default "Vea sección %s")
5860 ("et" :html "Vaata peat&#252;kki %s" :utf-8 "Vaata peatükki %s")
5861 ("fr" :default "cf. section %s")
5862 ("ja" :default "セクション %s を参照")
5863 ("pt_BR" :html "Veja a se&ccedil;&atilde;o %s" :default "Veja a seção %s"
5864 :ascii "Veja a secao %s")
5865 ("ru" :html "&#1057;&#1084;. &#1088;&#1072;&#1079;&#1076;&#1077;&#1083; %s"
5866 :utf-8 "См. раздел %s")
5867 ("zh-CN" :html "&#21442;&#35265;&#31532;%s&#33410;" :utf-8 "参见第%s节"))
5868 ("See table %s"
5869 ("fr" :default "cf. tableau %s"
5870 :html "cf.&nbsp;tableau&nbsp;%s" :latex "cf.~tableau~%s"))
5871 ("Table"
5872 ("ar" :default "جدول")
5873 ("de" :default "Tabelle")
5874 ("es" :default "Tabla")
5875 ("et" :default "Tabel")
5876 ("fr" :default "Tableau")
5877 ("is" :default "Tafla")
5878 ("ja" :default "表" :html "&#34920;")
5879 ("pt_BR" :default "Tabela")
5880 ("ru" :html "&#1058;&#1072;&#1073;&#1083;&#1080;&#1094;&#1072;"
5881 :utf-8 "Таблица")
5882 ("zh-CN" :html "&#34920;" :utf-8 "表"))
5883 ("Table %d:"
5884 ("ar" :default "جدول %d:")
5885 ("da" :default "Tabel %d")
5886 ("de" :default "Tabelle %d")
5887 ("es" :default "Tabla %d")
5888 ("et" :default "Tabel %d")
5889 ("fr" :default "Tableau %d :")
5890 ("is" :default "Tafla %d")
5891 ("ja" :default "表%d:" :html "&#34920;%d:")
5892 ("no" :default "Tabell %d")
5893 ("nb" :default "Tabell %d")
5894 ("nn" :default "Tabell %d")
5895 ("pt_BR" :default "Tabela %d")
5896 ("ru" :html "&#1058;&#1072;&#1073;&#1083;&#1080;&#1094;&#1072; %d.:"
5897 :utf-8 "Таблица %d.:")
5898 ("sv" :default "Tabell %d")
5899 ("zh-CN" :html "&#34920;%d&nbsp;" :utf-8 "表%d "))
5900 ("Table of Contents"
5901 ("ar" :default "قائمة المحتويات")
5902 ("ca" :html "&Iacute;ndex")
5903 ("cs" :default "Obsah")
5904 ("da" :default "Indhold")
5905 ("de" :default "Inhaltsverzeichnis")
5906 ("eo" :default "Enhavo")
5907 ("es" :ascii "Indice" :html "&Iacute;ndice" :default "Índice")
5908 ("et" :default "Sisukord")
5909 ("fi" :html "Sis&auml;llysluettelo")
5910 ("fr" :ascii "Sommaire" :default "Table des matières")
5911 ("hu" :html "Tartalomjegyz&eacute;k")
5912 ("is" :default "Efnisyfirlit")
5913 ("it" :default "Indice")
5914 ("ja" :default "目次" :html "&#30446;&#27425;")
5915 ("nl" :default "Inhoudsopgave")
5916 ("no" :default "Innhold")
5917 ("nb" :default "Innhold")
5918 ("nn" :default "Innhald")
5919 ("pl" :html "Spis tre&#x015b;ci")
5920 ("pt_BR" :html "&Iacute;ndice" :utf8 "Índice" :ascii "Indice")
5921 ("ru" :html "&#1057;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1077;"
5922 :utf-8 "Содержание")
5923 ("sv" :html "Inneh&aring;ll")
5924 ("uk" :html "&#1047;&#1084;&#1110;&#1089;&#1090;" :utf-8 "Зміст")
5925 ("zh-CN" :html "&#30446;&#24405;" :utf-8 "目录")
5926 ("zh-TW" :html "&#30446;&#37636;" :utf-8 "目錄"))
5927 ("Unknown reference"
5928 ("ar" :default "مرجع غير معرّف")
5929 ("da" :default "ukendt reference")
5930 ("de" :default "Unbekannter Verweis")
5931 ("es" :default "Referencia desconocida")
5932 ("et" :default "Tundmatu viide")
5933 ("fr" :ascii "Destination inconnue" :default "Référence inconnue")
5934 ("ja" :default "不明な参照先")
5935 ("pt_BR" :default "Referência desconhecida"
5936 :ascii "Referencia desconhecida")
5937 ("ru" :html "&#1053;&#1077;&#1080;&#1079;&#1074;&#1077;&#1089;&#1090;&#1085;&#1072;&#1103; &#1089;&#1089;&#1099;&#1083;&#1082;&#1072;"
5938 :utf-8 "Неизвестная ссылка")
5939 ("zh-CN" :html "&#26410;&#30693;&#24341;&#29992;" :utf-8 "未知引用")))
5940 "Dictionary for export engine.
5942 Alist whose car is the string to translate and cdr is an alist
5943 whose car is the language string and cdr is a plist whose
5944 properties are possible charsets and values translated terms.
5946 It is used as a database for `org-export-translate'. Since this
5947 function returns the string as-is if no translation was found,
5948 the variable only needs to record values different from the
5949 entry.")
5951 (defun org-export-translate (s encoding info)
5952 "Translate string S according to language specification.
5954 ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1'
5955 and `:utf-8'. INFO is a plist used as a communication channel.
5957 Translation depends on `:language' property. Return the
5958 translated string. If no translation is found, try to fall back
5959 to `:default' encoding. If it fails, return S."
5960 (let* ((lang (plist-get info :language))
5961 (translations (cdr (assoc lang
5962 (cdr (assoc s org-export-dictionary))))))
5963 (or (plist-get translations encoding)
5964 (plist-get translations :default)
5965 s)))
5969 ;;; Asynchronous Export
5971 ;; `org-export-async-start' is the entry point for asynchronous
5972 ;; export. It recreates current buffer (including visibility,
5973 ;; narrowing and visited file) in an external Emacs process, and
5974 ;; evaluates a command there. It then applies a function on the
5975 ;; returned results in the current process.
5977 ;; At a higher level, `org-export-to-buffer' and `org-export-to-file'
5978 ;; allow exporting to a buffer or a file, asynchronously or not.
5980 ;; `org-export-output-file-name' is an auxiliary function meant to be
5981 ;; used with `org-export-to-file'. With a given extension, it tries
5982 ;; to provide a canonical file name to write export output to.
5984 ;; Asynchronously generated results are never displayed directly.
5985 ;; Instead, they are stored in `org-export-stack-contents'. They can
5986 ;; then be retrieved by calling `org-export-stack'.
5988 ;; Export Stack is viewed through a dedicated major mode
5989 ;;`org-export-stack-mode' and tools: `org-export-stack-refresh',
5990 ;;`org-export-stack-delete', `org-export-stack-view' and
5991 ;;`org-export-stack-clear'.
5993 ;; For back-ends, `org-export-add-to-stack' add a new source to stack.
5994 ;; It should be used whenever `org-export-async-start' is called.
5996 (defmacro org-export-async-start (fun &rest body)
5997 "Call function FUN on the results returned by BODY evaluation.
5999 FUN is an anonymous function of one argument. BODY evaluation
6000 happens in an asynchronous process, from a buffer which is an
6001 exact copy of the current one.
6003 Use `org-export-add-to-stack' in FUN in order to register results
6004 in the stack.
6006 This is a low level function. See also `org-export-to-buffer'
6007 and `org-export-to-file' for more specialized functions."
6008 (declare (indent 1) (debug t))
6009 (org-with-gensyms (process temp-file copy-fun proc-buffer coding)
6010 ;; Write the full sexp evaluating BODY in a copy of the current
6011 ;; buffer to a temporary file, as it may be too long for program
6012 ;; args in `start-process'.
6013 `(with-temp-message "Initializing asynchronous export process"
6014 (let ((,copy-fun (org-export--generate-copy-script (current-buffer)))
6015 (,temp-file (make-temp-file "org-export-process"))
6016 (,coding buffer-file-coding-system))
6017 (with-temp-file ,temp-file
6018 (insert
6019 ;; Null characters (from variable values) are inserted
6020 ;; within the file. As a consequence, coding system for
6021 ;; buffer contents will not be recognized properly. So,
6022 ;; we make sure it is the same as the one used to display
6023 ;; the original buffer.
6024 (format ";; -*- coding: %s; -*-\n%S"
6025 ,coding
6026 `(with-temp-buffer
6027 (when org-export-async-debug '(setq debug-on-error t))
6028 ;; Ignore `kill-emacs-hook' and code evaluation
6029 ;; queries from Babel as we need a truly
6030 ;; non-interactive process.
6031 (setq kill-emacs-hook nil
6032 org-babel-confirm-evaluate-answer-no t)
6033 ;; Initialize export framework.
6034 (require 'ox)
6035 ;; Re-create current buffer there.
6036 (funcall ,,copy-fun)
6037 (restore-buffer-modified-p nil)
6038 ;; Sexp to evaluate in the buffer.
6039 (print (progn ,,@body))))))
6040 ;; Start external process.
6041 (let* ((process-connection-type nil)
6042 (,proc-buffer (generate-new-buffer-name "*Org Export Process*"))
6043 (,process
6044 (apply
6045 #'start-process
6046 (append
6047 (list "org-export-process"
6048 ,proc-buffer
6049 (expand-file-name invocation-name invocation-directory)
6050 "--batch")
6051 (if org-export-async-init-file
6052 (list "-Q" "-l" org-export-async-init-file)
6053 (list "-l" user-init-file))
6054 (list "-l" ,temp-file)))))
6055 ;; Register running process in stack.
6056 (org-export-add-to-stack (get-buffer ,proc-buffer) nil ,process)
6057 ;; Set-up sentinel in order to catch results.
6058 (let ((handler ,fun))
6059 (set-process-sentinel
6060 ,process
6061 `(lambda (p status)
6062 (let ((proc-buffer (process-buffer p)))
6063 (when (eq (process-status p) 'exit)
6064 (unwind-protect
6065 (if (zerop (process-exit-status p))
6066 (unwind-protect
6067 (let ((results
6068 (with-current-buffer proc-buffer
6069 (goto-char (point-max))
6070 (backward-sexp)
6071 (read (current-buffer)))))
6072 (funcall ,handler results))
6073 (unless org-export-async-debug
6074 (and (get-buffer proc-buffer)
6075 (kill-buffer proc-buffer))))
6076 (org-export-add-to-stack proc-buffer nil p)
6077 (ding)
6078 (message "Process `%s' exited abnormally" p))
6079 (unless org-export-async-debug
6080 (delete-file ,,temp-file)))))))))))))
6082 ;;;###autoload
6083 (defun org-export-to-buffer
6084 (backend buffer
6085 &optional async subtreep visible-only body-only ext-plist
6086 post-process)
6087 "Call `org-export-as' with output to a specified buffer.
6089 BACKEND is either an export back-end, as returned by, e.g.,
6090 `org-export-create-backend', or a symbol referring to
6091 a registered back-end.
6093 BUFFER is the name of the output buffer. If it already exists,
6094 it will be erased first, otherwise, it will be created.
6096 A non-nil optional argument ASYNC means the process should happen
6097 asynchronously. The resulting buffer should then be accessible
6098 through the `org-export-stack' interface. When ASYNC is nil, the
6099 buffer is displayed if `org-export-show-temporary-export-buffer'
6100 is non-nil.
6102 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
6103 EXT-PLIST are similar to those used in `org-export-as', which
6104 see.
6106 Optional argument POST-PROCESS is a function which should accept
6107 no argument. It is always called within the current process,
6108 from BUFFER, with point at its beginning. Export back-ends can
6109 use it to set a major mode there, e.g,
6111 (defun org-latex-export-as-latex
6112 (&optional async subtreep visible-only body-only ext-plist)
6113 (interactive)
6114 (org-export-to-buffer \\='latex \"*Org LATEX Export*\"
6115 async subtreep visible-only body-only ext-plist (lambda () (LaTeX-mode))))
6117 This function returns BUFFER."
6118 (declare (indent 2))
6119 (if async
6120 (org-export-async-start
6121 `(lambda (output)
6122 (with-current-buffer (get-buffer-create ,buffer)
6123 (erase-buffer)
6124 (setq buffer-file-coding-system ',buffer-file-coding-system)
6125 (insert output)
6126 (goto-char (point-min))
6127 (org-export-add-to-stack (current-buffer) ',backend)
6128 (ignore-errors (funcall ,post-process))))
6129 `(org-export-as
6130 ',backend ,subtreep ,visible-only ,body-only ',ext-plist))
6131 (let ((output
6132 (org-export-as backend subtreep visible-only body-only ext-plist))
6133 (buffer (get-buffer-create buffer))
6134 (encoding buffer-file-coding-system))
6135 (when (and (org-string-nw-p output) (org-export--copy-to-kill-ring-p))
6136 (org-kill-new output))
6137 (with-current-buffer buffer
6138 (erase-buffer)
6139 (setq buffer-file-coding-system encoding)
6140 (insert output)
6141 (goto-char (point-min))
6142 (and (functionp post-process) (funcall post-process)))
6143 (when org-export-show-temporary-export-buffer
6144 (switch-to-buffer-other-window buffer))
6145 buffer)))
6147 ;;;###autoload
6148 (defun org-export-to-file
6149 (backend file &optional async subtreep visible-only body-only ext-plist
6150 post-process)
6151 "Call `org-export-as' with output to a specified file.
6153 BACKEND is either an export back-end, as returned by, e.g.,
6154 `org-export-create-backend', or a symbol referring to
6155 a registered back-end. FILE is the name of the output file, as
6156 a string.
6158 A non-nil optional argument ASYNC means the process should happen
6159 asynchronously. The resulting buffer will then be accessible
6160 through the `org-export-stack' interface.
6162 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
6163 EXT-PLIST are similar to those used in `org-export-as', which
6164 see.
6166 Optional argument POST-PROCESS is called with FILE as its
6167 argument and happens asynchronously when ASYNC is non-nil. It
6168 has to return a file name, or nil. Export back-ends can use this
6169 to send the output file through additional processing, e.g,
6171 (defun org-latex-export-to-latex
6172 (&optional async subtreep visible-only body-only ext-plist)
6173 (interactive)
6174 (let ((outfile (org-export-output-file-name \".tex\" subtreep)))
6175 (org-export-to-file \\='latex outfile
6176 async subtreep visible-only body-only ext-plist
6177 (lambda (file) (org-latex-compile file)))
6179 The function returns either a file name returned by POST-PROCESS,
6180 or FILE."
6181 (declare (indent 2))
6182 (if (not (file-writable-p file)) (error "Output file not writable")
6183 (let ((ext-plist (org-combine-plists `(:output-file ,file) ext-plist))
6184 (encoding (or org-export-coding-system buffer-file-coding-system)))
6185 (if async
6186 (org-export-async-start
6187 `(lambda (file)
6188 (org-export-add-to-stack (expand-file-name file) ',backend))
6189 `(let ((output
6190 (org-export-as
6191 ',backend ,subtreep ,visible-only ,body-only
6192 ',ext-plist)))
6193 (with-temp-buffer
6194 (insert output)
6195 (let ((coding-system-for-write ',encoding))
6196 (write-file ,file)))
6197 (or (ignore-errors (funcall ',post-process ,file)) ,file)))
6198 (let ((output (org-export-as
6199 backend subtreep visible-only body-only ext-plist)))
6200 (with-temp-buffer
6201 (insert output)
6202 (let ((coding-system-for-write encoding))
6203 (write-file file)))
6204 (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p output))
6205 (org-kill-new output))
6206 ;; Get proper return value.
6207 (or (and (functionp post-process) (funcall post-process file))
6208 file))))))
6210 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
6211 "Return output file's name according to buffer specifications.
6213 EXTENSION is a string representing the output file extension,
6214 with the leading dot.
6216 With a non-nil optional argument SUBTREEP, try to determine
6217 output file's name by looking for \"EXPORT_FILE_NAME\" property
6218 of subtree at point.
6220 When optional argument PUB-DIR is set, use it as the publishing
6221 directory.
6223 Return file name as a string."
6224 (let* ((visited-file (buffer-file-name (buffer-base-buffer)))
6225 (base-name
6226 (concat
6227 (file-name-sans-extension
6229 ;; Check EXPORT_FILE_NAME subtree property.
6230 (and subtreep (org-entry-get nil "EXPORT_FILE_NAME" 'selective))
6231 ;; Check #+EXPORT_FILE_NAME keyword.
6232 (org-with-point-at (point-min)
6233 (catch :found
6234 (let ((case-fold-search t))
6235 (while (re-search-forward
6236 "^[ \t]*#\\+EXPORT_FILE_NAME:[ \t]+\\S-" nil t)
6237 (let ((element (org-element-at-point)))
6238 (when (eq 'keyword (org-element-type element))
6239 (throw :found
6240 (org-element-property :value element))))))))
6241 ;; Extract from buffer's associated file, if any.
6242 (and visited-file (file-name-nondirectory visited-file))
6243 ;; Can't determine file name on our own: ask user.
6244 (read-file-name
6245 "Output file: " pub-dir nil nil nil
6246 (lambda (n) (string= extension (file-name-extension n t))))))
6247 extension))
6248 (output-file
6249 ;; Build file name. Enforce EXTENSION over whatever user
6250 ;; may have come up with. PUB-DIR, if defined, always has
6251 ;; precedence over any provided path.
6252 (cond
6253 (pub-dir (concat (file-name-as-directory pub-dir)
6254 (file-name-nondirectory base-name)))
6255 ((file-name-absolute-p base-name) base-name)
6256 (t base-name))))
6257 ;; If writing to OUTPUT-FILE would overwrite original file, append
6258 ;; EXTENSION another time to final name.
6259 (if (and visited-file (file-equal-p visited-file output-file))
6260 (concat output-file extension)
6261 output-file)))
6263 (defun org-export-add-to-stack (source backend &optional process)
6264 "Add a new result to export stack if not present already.
6266 SOURCE is a buffer or a file name containing export results.
6267 BACKEND is a symbol representing export back-end used to generate
6270 Entries already pointing to SOURCE and unavailable entries are
6271 removed beforehand. Return the new stack."
6272 (setq org-export-stack-contents
6273 (cons (list source backend (or process (current-time)))
6274 (org-export-stack-remove source))))
6276 (defun org-export-stack ()
6277 "Menu for asynchronous export results and running processes."
6278 (interactive)
6279 (let ((buffer (get-buffer-create "*Org Export Stack*")))
6280 (with-current-buffer buffer
6281 (org-export-stack-mode)
6282 (tabulated-list-print t))
6283 (pop-to-buffer buffer))
6284 (message "Type \"q\" to quit, \"?\" for help"))
6286 (defun org-export-stack-clear ()
6287 "Remove all entries from export stack."
6288 (interactive)
6289 (setq org-export-stack-contents nil))
6291 (defun org-export-stack-refresh ()
6292 "Refresh the export stack."
6293 (interactive)
6294 (tabulated-list-print t))
6296 (defun org-export-stack-remove (&optional source)
6297 "Remove export results at point from stack.
6298 If optional argument SOURCE is non-nil, remove it instead."
6299 (interactive)
6300 (let ((source (or source (org-export--stack-source-at-point))))
6301 (setq org-export-stack-contents
6302 (cl-remove-if (lambda (el) (equal (car el) source))
6303 org-export-stack-contents))))
6305 (defun org-export-stack-view (&optional in-emacs)
6306 "View export results at point in stack.
6307 With an optional prefix argument IN-EMACS, force viewing files
6308 within Emacs."
6309 (interactive "P")
6310 (let ((source (org-export--stack-source-at-point)))
6311 (cond ((processp source)
6312 (org-switch-to-buffer-other-window (process-buffer source)))
6313 ((bufferp source) (org-switch-to-buffer-other-window source))
6314 (t (org-open-file source in-emacs)))))
6316 (defvar org-export-stack-mode-map
6317 (let ((km (make-sparse-keymap)))
6318 (set-keymap-parent km tabulated-list-mode-map)
6319 (define-key km " " 'next-line)
6320 (define-key km "\C-n" 'next-line)
6321 (define-key km [down] 'next-line)
6322 (define-key km "\C-p" 'previous-line)
6323 (define-key km "\C-?" 'previous-line)
6324 (define-key km [up] 'previous-line)
6325 (define-key km "C" 'org-export-stack-clear)
6326 (define-key km "v" 'org-export-stack-view)
6327 (define-key km (kbd "RET") 'org-export-stack-view)
6328 (define-key km "d" 'org-export-stack-remove)
6330 "Keymap for Org Export Stack.")
6332 (define-derived-mode org-export-stack-mode tabulated-list-mode "Org-Stack"
6333 "Mode for displaying asynchronous export stack.
6335 Type `\\[org-export-stack]' to visualize the asynchronous export
6336 stack.
6338 In an Org Export Stack buffer, use \
6339 \\<org-export-stack-mode-map>`\\[org-export-stack-view]' to view export output
6340 on current line, `\\[org-export-stack-remove]' to remove it from the stack and \
6341 `\\[org-export-stack-clear]' to clear
6342 stack completely.
6344 Removing entries in a stack buffer does not affect files
6345 or buffers, only display.
6347 \\{org-export-stack-mode-map}"
6348 (setq tabulated-list-format
6349 (vector (list "#" 4 #'org-export--stack-num-predicate)
6350 (list "Back-End" 12 t)
6351 (list "Age" 6 nil)
6352 (list "Source" 0 nil)))
6353 (setq tabulated-list-sort-key (cons "#" nil))
6354 (setq tabulated-list-entries #'org-export--stack-generate)
6355 (add-hook 'tabulated-list-revert-hook #'org-export--stack-generate nil t)
6356 (add-hook 'post-command-hook #'org-export-stack-refresh nil t)
6357 (tabulated-list-init-header))
6359 (defun org-export--stack-generate ()
6360 "Generate the asynchronous export stack for display.
6361 Unavailable sources are removed from the list. Return a list
6362 appropriate for `tabulated-list-print'."
6363 ;; Clear stack from exited processes, dead buffers or non-existent
6364 ;; files.
6365 (setq org-export-stack-contents
6366 (cl-remove-if-not
6367 (lambda (el)
6368 (if (processp (nth 2 el))
6369 (buffer-live-p (process-buffer (nth 2 el)))
6370 (let ((source (car el)))
6371 (if (bufferp source) (buffer-live-p source)
6372 (file-exists-p source)))))
6373 org-export-stack-contents))
6374 ;; Update `tabulated-list-entries'.
6375 (let ((counter 0))
6376 (mapcar
6377 (lambda (entry)
6378 (let ((source (car entry)))
6379 (list source
6380 (vector
6381 ;; Counter.
6382 (number-to-string (cl-incf counter))
6383 ;; Back-End.
6384 (if (nth 1 entry) (symbol-name (nth 1 entry)) "")
6385 ;; Age.
6386 (let ((info (nth 2 entry)))
6387 (if (processp info) (symbol-name (process-status info))
6388 (format-seconds "%h:%.2m" (float-time (time-since info)))))
6389 ;; Source.
6390 (if (stringp source) source (buffer-name source))))))
6391 org-export-stack-contents)))
6393 (defun org-export--stack-num-predicate (a b)
6394 (< (string-to-number (aref (nth 1 a) 0))
6395 (string-to-number (aref (nth 1 b) 0))))
6397 (defun org-export--stack-source-at-point ()
6398 "Return source from export results at point in stack."
6399 (let ((source (car (nth (1- (org-current-line)) org-export-stack-contents))))
6400 (if (not source) (error "Source unavailable, please refresh buffer")
6401 (let ((source-name (if (stringp source) source (buffer-name source))))
6402 (if (save-excursion
6403 (beginning-of-line)
6404 (looking-at-p (concat ".* +" (regexp-quote source-name) "$")))
6405 source
6406 ;; SOURCE is not consistent with current line. The stack
6407 ;; view is outdated.
6408 (error (substitute-command-keys
6409 "Source unavailable; type `\\[org-export-stack-refresh]' \
6410 to refresh buffer")))))))
6414 ;;; The Dispatcher
6416 ;; `org-export-dispatch' is the standard interactive way to start an
6417 ;; export process. It uses `org-export--dispatch-ui' as a subroutine
6418 ;; for its interface, which, in turn, delegates response to key
6419 ;; pressed to `org-export--dispatch-action'.
6421 ;;;###autoload
6422 (defun org-export-dispatch (&optional arg)
6423 "Export dispatcher for Org mode.
6425 It provides an access to common export related tasks in a buffer.
6426 Its interface comes in two flavors: standard and expert.
6428 While both share the same set of bindings, only the former
6429 displays the valid keys associations in a dedicated buffer.
6430 Scrolling (resp. line-wise motion) in this buffer is done with
6431 SPC and DEL (resp. C-n and C-p) keys.
6433 Set variable `org-export-dispatch-use-expert-ui' to switch to one
6434 flavor or the other.
6436 When ARG is `\\[universal-argument]', repeat the last export action, with the\
6437 same
6438 set of options used back then, on the current buffer.
6440 When ARG is `\\[universal-argument] \\[universal-argument]', display the \
6441 asynchronous export stack."
6442 (interactive "P")
6443 (let* ((input
6444 (cond ((equal arg '(16)) '(stack))
6445 ((and arg org-export-dispatch-last-action))
6446 (t (save-window-excursion
6447 (unwind-protect
6448 (progn
6449 ;; Remember where we are
6450 (move-marker org-export-dispatch-last-position
6451 (point)
6452 (org-base-buffer (current-buffer)))
6453 ;; Get and store an export command
6454 (setq org-export-dispatch-last-action
6455 (org-export--dispatch-ui
6456 (list org-export-initial-scope
6457 (and org-export-in-background 'async))
6459 org-export-dispatch-use-expert-ui)))
6460 (and (get-buffer "*Org Export Dispatcher*")
6461 (kill-buffer "*Org Export Dispatcher*")))))))
6462 (action (car input))
6463 (optns (cdr input)))
6464 (unless (memq 'subtree optns)
6465 (move-marker org-export-dispatch-last-position nil))
6466 (cl-case action
6467 ;; First handle special hard-coded actions.
6468 (template (org-export-insert-default-template nil optns))
6469 (stack (org-export-stack))
6470 (publish-current-file
6471 (org-publish-current-file (memq 'force optns) (memq 'async optns)))
6472 (publish-current-project
6473 (org-publish-current-project (memq 'force optns) (memq 'async optns)))
6474 (publish-choose-project
6475 (org-publish (assoc (completing-read
6476 "Publish project: "
6477 org-publish-project-alist nil t)
6478 org-publish-project-alist)
6479 (memq 'force optns)
6480 (memq 'async optns)))
6481 (publish-all (org-publish-all (memq 'force optns) (memq 'async optns)))
6482 (otherwise
6483 (save-excursion
6484 (when arg
6485 ;; Repeating command, maybe move cursor to restore subtree
6486 ;; context.
6487 (if (eq (marker-buffer org-export-dispatch-last-position)
6488 (org-base-buffer (current-buffer)))
6489 (goto-char org-export-dispatch-last-position)
6490 ;; We are in a different buffer, forget position.
6491 (move-marker org-export-dispatch-last-position nil)))
6492 (funcall action
6493 ;; Return a symbol instead of a list to ease
6494 ;; asynchronous export macro use.
6495 (and (memq 'async optns) t)
6496 (and (memq 'subtree optns) t)
6497 (and (memq 'visible optns) t)
6498 (and (memq 'body optns) t)))))))
6500 (defun org-export--dispatch-ui (options first-key expertp)
6501 "Handle interface for `org-export-dispatch'.
6503 OPTIONS is a list containing current interactive options set for
6504 export. It can contain any of the following symbols:
6505 `body' toggles a body-only export
6506 `subtree' restricts export to current subtree
6507 `visible' restricts export to visible part of buffer.
6508 `force' force publishing files.
6509 `async' use asynchronous export process
6511 FIRST-KEY is the key pressed to select the first level menu. It
6512 is nil when this menu hasn't been selected yet.
6514 EXPERTP, when non-nil, triggers expert UI. In that case, no help
6515 buffer is provided, but indications about currently active
6516 options are given in the prompt. Moreover, [?] allows switching
6517 back to standard interface."
6518 (let* ((fontify-key
6519 (lambda (key &optional access-key)
6520 ;; Fontify KEY string. Optional argument ACCESS-KEY, when
6521 ;; non-nil is the required first-level key to activate
6522 ;; KEY. When its value is t, activate KEY independently
6523 ;; on the first key, if any. A nil value means KEY will
6524 ;; only be activated at first level.
6525 (if (or (eq access-key t) (eq access-key first-key))
6526 (propertize key 'face 'org-warning)
6527 key)))
6528 (fontify-value
6529 (lambda (value)
6530 ;; Fontify VALUE string.
6531 (propertize value 'face 'font-lock-variable-name-face)))
6532 ;; Prepare menu entries by extracting them from registered
6533 ;; back-ends and sorting them by access key and by ordinal,
6534 ;; if any.
6535 (entries
6536 (sort (sort (delq nil
6537 (mapcar #'org-export-backend-menu
6538 org-export-registered-backends))
6539 (lambda (a b)
6540 (let ((key-a (nth 1 a))
6541 (key-b (nth 1 b)))
6542 (cond ((and (numberp key-a) (numberp key-b))
6543 (< key-a key-b))
6544 ((numberp key-b) t)))))
6545 'car-less-than-car))
6546 ;; Compute a list of allowed keys based on the first key
6547 ;; pressed, if any. Some keys
6548 ;; (?^B, ?^V, ?^S, ?^F, ?^A, ?&, ?# and ?q) are always
6549 ;; available.
6550 (allowed-keys
6551 (nconc (list 2 22 19 6 1)
6552 (if (not first-key) (org-uniquify (mapcar 'car entries))
6553 (let (sub-menu)
6554 (dolist (entry entries (sort (mapcar 'car sub-menu) '<))
6555 (when (eq (car entry) first-key)
6556 (setq sub-menu (append (nth 2 entry) sub-menu))))))
6557 (cond ((eq first-key ?P) (list ?f ?p ?x ?a))
6558 ((not first-key) (list ?P)))
6559 (list ?& ?#)
6560 (when expertp (list ??))
6561 (list ?q)))
6562 ;; Build the help menu for standard UI.
6563 (help
6564 (unless expertp
6565 (concat
6566 ;; Options are hard-coded.
6567 (format "[%s] Body only: %s [%s] Visible only: %s
6568 \[%s] Export scope: %s [%s] Force publishing: %s
6569 \[%s] Async export: %s\n\n"
6570 (funcall fontify-key "C-b" t)
6571 (funcall fontify-value
6572 (if (memq 'body options) "On " "Off"))
6573 (funcall fontify-key "C-v" t)
6574 (funcall fontify-value
6575 (if (memq 'visible options) "On " "Off"))
6576 (funcall fontify-key "C-s" t)
6577 (funcall fontify-value
6578 (if (memq 'subtree options) "Subtree" "Buffer "))
6579 (funcall fontify-key "C-f" t)
6580 (funcall fontify-value
6581 (if (memq 'force options) "On " "Off"))
6582 (funcall fontify-key "C-a" t)
6583 (funcall fontify-value
6584 (if (memq 'async options) "On " "Off")))
6585 ;; Display registered back-end entries. When a key
6586 ;; appears for the second time, do not create another
6587 ;; entry, but append its sub-menu to existing menu.
6588 (let (last-key)
6589 (mapconcat
6590 (lambda (entry)
6591 (let ((top-key (car entry)))
6592 (concat
6593 (unless (eq top-key last-key)
6594 (setq last-key top-key)
6595 (format "\n[%s] %s\n"
6596 (funcall fontify-key (char-to-string top-key))
6597 (nth 1 entry)))
6598 (let ((sub-menu (nth 2 entry)))
6599 (unless (functionp sub-menu)
6600 ;; Split sub-menu into two columns.
6601 (let ((index -1))
6602 (concat
6603 (mapconcat
6604 (lambda (sub-entry)
6605 (cl-incf index)
6606 (format
6607 (if (zerop (mod index 2)) " [%s] %-26s"
6608 "[%s] %s\n")
6609 (funcall fontify-key
6610 (char-to-string (car sub-entry))
6611 top-key)
6612 (nth 1 sub-entry)))
6613 sub-menu "")
6614 (when (zerop (mod index 2)) "\n"))))))))
6615 entries ""))
6616 ;; Publishing menu is hard-coded.
6617 (format "\n[%s] Publish
6618 [%s] Current file [%s] Current project
6619 [%s] Choose project [%s] All projects\n\n\n"
6620 (funcall fontify-key "P")
6621 (funcall fontify-key "f" ?P)
6622 (funcall fontify-key "p" ?P)
6623 (funcall fontify-key "x" ?P)
6624 (funcall fontify-key "a" ?P))
6625 (format "[%s] Export stack [%s] Insert template\n"
6626 (funcall fontify-key "&" t)
6627 (funcall fontify-key "#" t))
6628 (format "[%s] %s"
6629 (funcall fontify-key "q" t)
6630 (if first-key "Main menu" "Exit")))))
6631 ;; Build prompts for both standard and expert UI.
6632 (standard-prompt (unless expertp "Export command: "))
6633 (expert-prompt
6634 (when expertp
6635 (format
6636 "Export command (C-%s%s%s%s%s) [%s]: "
6637 (if (memq 'body options) (funcall fontify-key "b" t) "b")
6638 (if (memq 'visible options) (funcall fontify-key "v" t) "v")
6639 (if (memq 'subtree options) (funcall fontify-key "s" t) "s")
6640 (if (memq 'force options) (funcall fontify-key "f" t) "f")
6641 (if (memq 'async options) (funcall fontify-key "a" t) "a")
6642 (mapconcat (lambda (k)
6643 ;; Strip control characters.
6644 (unless (< k 27) (char-to-string k)))
6645 allowed-keys "")))))
6646 ;; With expert UI, just read key with a fancy prompt. In standard
6647 ;; UI, display an intrusive help buffer.
6648 (if expertp
6649 (org-export--dispatch-action
6650 expert-prompt allowed-keys entries options first-key expertp)
6651 ;; At first call, create frame layout in order to display menu.
6652 (unless (get-buffer "*Org Export Dispatcher*")
6653 (delete-other-windows)
6654 (org-switch-to-buffer-other-window
6655 (get-buffer-create "*Org Export Dispatcher*"))
6656 (setq cursor-type nil
6657 header-line-format "Use SPC, DEL, C-n or C-p to navigate.")
6658 ;; Make sure that invisible cursor will not highlight square
6659 ;; brackets.
6660 (set-syntax-table (copy-syntax-table))
6661 (modify-syntax-entry ?\[ "w"))
6662 ;; At this point, the buffer containing the menu exists and is
6663 ;; visible in the current window. So, refresh it.
6664 (with-current-buffer "*Org Export Dispatcher*"
6665 ;; Refresh help. Maintain display continuity by re-visiting
6666 ;; previous window position.
6667 (let ((pos (window-start)))
6668 (erase-buffer)
6669 (insert help)
6670 (set-window-start nil pos)))
6671 (org-fit-window-to-buffer)
6672 (org-export--dispatch-action
6673 standard-prompt allowed-keys entries options first-key expertp))))
6675 (defun org-export--dispatch-action
6676 (prompt allowed-keys entries options first-key expertp)
6677 "Read a character from command input and act accordingly.
6679 PROMPT is the displayed prompt, as a string. ALLOWED-KEYS is
6680 a list of characters available at a given step in the process.
6681 ENTRIES is a list of menu entries. OPTIONS, FIRST-KEY and
6682 EXPERTP are the same as defined in `org-export--dispatch-ui',
6683 which see.
6685 Toggle export options when required. Otherwise, return value is
6686 a list with action as CAR and a list of interactive export
6687 options as CDR."
6688 (let (key)
6689 ;; Scrolling: when in non-expert mode, act on motion keys (C-n,
6690 ;; C-p, SPC, DEL).
6691 (while (and (setq key (read-char-exclusive prompt))
6692 (not expertp)
6693 (memq key '(14 16 ?\s ?\d)))
6694 (cl-case key
6695 (14 (if (not (pos-visible-in-window-p (point-max)))
6696 (ignore-errors (scroll-up 1))
6697 (message "End of buffer")
6698 (sit-for 1)))
6699 (16 (if (not (pos-visible-in-window-p (point-min)))
6700 (ignore-errors (scroll-down 1))
6701 (message "Beginning of buffer")
6702 (sit-for 1)))
6703 (?\s (if (not (pos-visible-in-window-p (point-max)))
6704 (scroll-up nil)
6705 (message "End of buffer")
6706 (sit-for 1)))
6707 (?\d (if (not (pos-visible-in-window-p (point-min)))
6708 (scroll-down nil)
6709 (message "Beginning of buffer")
6710 (sit-for 1)))))
6711 (cond
6712 ;; Ignore undefined associations.
6713 ((not (memq key allowed-keys))
6714 (ding)
6715 (unless expertp (message "Invalid key") (sit-for 1))
6716 (org-export--dispatch-ui options first-key expertp))
6717 ;; q key at first level aborts export. At second level, cancel
6718 ;; first key instead.
6719 ((eq key ?q) (if (not first-key) (error "Export aborted")
6720 (org-export--dispatch-ui options nil expertp)))
6721 ;; Help key: Switch back to standard interface if expert UI was
6722 ;; active.
6723 ((eq key ??) (org-export--dispatch-ui options first-key nil))
6724 ;; Send request for template insertion along with export scope.
6725 ((eq key ?#) (cons 'template (memq 'subtree options)))
6726 ;; Switch to asynchronous export stack.
6727 ((eq key ?&) '(stack))
6728 ;; Toggle options: C-b (2) C-v (22) C-s (19) C-f (6) C-a (1).
6729 ((memq key '(2 22 19 6 1))
6730 (org-export--dispatch-ui
6731 (let ((option (cl-case key (2 'body) (22 'visible) (19 'subtree)
6732 (6 'force) (1 'async))))
6733 (if (memq option options) (remq option options)
6734 (cons option options)))
6735 first-key expertp))
6736 ;; Action selected: Send key and options back to
6737 ;; `org-export-dispatch'.
6738 ((or first-key (functionp (nth 2 (assq key entries))))
6739 (cons (cond
6740 ((not first-key) (nth 2 (assq key entries)))
6741 ;; Publishing actions are hard-coded. Send a special
6742 ;; signal to `org-export-dispatch'.
6743 ((eq first-key ?P)
6744 (cl-case key
6745 (?f 'publish-current-file)
6746 (?p 'publish-current-project)
6747 (?x 'publish-choose-project)
6748 (?a 'publish-all)))
6749 ;; Return first action associated to FIRST-KEY + KEY
6750 ;; path. Indeed, derived backends can share the same
6751 ;; FIRST-KEY.
6752 (t (catch 'found
6753 (dolist (entry (member (assq first-key entries) entries))
6754 (let ((match (assq key (nth 2 entry))))
6755 (when match (throw 'found (nth 2 match))))))))
6756 options))
6757 ;; Otherwise, enter sub-menu.
6758 (t (org-export--dispatch-ui options key expertp)))))
6762 (provide 'ox)
6764 ;; Local variables:
6765 ;; generated-autoload-file: "org-loaddefs.el"
6766 ;; End:
6768 ;;; ox.el ends here