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