Merge branch 'maint'
[org-mode.git] / lisp / ox.el
blob246ec8b3f06ae8c820a493084cc3588bd41970c0
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")))
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")
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 (push (cons keyword v) cache) v))))
1396 (when value
1397 (setq plist
1398 (plist-put plist
1399 property
1400 (cl-case (nth 4 option)
1401 (parse
1402 (org-element-parse-secondary-string
1403 value (org-element-restriction 'keyword)))
1404 (split (org-split-string value))
1405 (t value))))))))))))
1407 (defun org-export--get-inbuffer-options (&optional backend)
1408 "Return current buffer export options, as a plist.
1410 Optional argument BACKEND, when non-nil, is an export back-end,
1411 as returned by, e.g., `org-export-create-backend'. It specifies
1412 which back-end specific options should also be read in the
1413 process.
1415 Assume buffer is in Org mode. Narrowing, if any, is ignored."
1416 (let* ((case-fold-search t)
1417 (options (append
1418 ;; Priority is given to back-end specific options.
1419 (and backend (org-export-get-all-options backend))
1420 org-export-options-alist))
1421 (regexp (format "^[ \t]*#\\+%s:"
1422 (regexp-opt (nconc (delq nil (mapcar #'cadr options))
1423 org-export-special-keywords))))
1424 plist to-parse)
1425 (letrec ((find-properties
1426 (lambda (keyword)
1427 ;; Return all properties associated to KEYWORD.
1428 (let (properties)
1429 (dolist (option options properties)
1430 (when (equal (nth 1 option) keyword)
1431 (cl-pushnew (car option) properties))))))
1432 (get-options
1433 (lambda (&optional files)
1434 ;; Recursively read keywords in buffer. FILES is
1435 ;; a list of files read so far. PLIST is the current
1436 ;; property list obtained.
1437 (org-with-wide-buffer
1438 (goto-char (point-min))
1439 (while (re-search-forward regexp nil t)
1440 (let ((element (org-element-at-point)))
1441 (when (eq (org-element-type element) 'keyword)
1442 (let ((key (org-element-property :key element))
1443 (val (org-element-property :value element)))
1444 (cond
1445 ;; Options in `org-export-special-keywords'.
1446 ((equal key "SETUPFILE")
1447 (let ((file
1448 (expand-file-name
1449 (org-remove-double-quotes (org-trim val)))))
1450 ;; Avoid circular dependencies.
1451 (unless (member file files)
1452 (with-temp-buffer
1453 (insert (org-file-contents file 'noerror))
1454 (let ((org-inhibit-startup t)) (org-mode))
1455 (funcall get-options (cons file files))))))
1456 ((equal key "OPTIONS")
1457 (setq plist
1458 (org-combine-plists
1459 plist
1460 (org-export--parse-option-keyword
1461 val backend))))
1462 ((equal key "FILETAGS")
1463 (setq plist
1464 (org-combine-plists
1465 plist
1466 (list :filetags
1467 (org-uniquify
1468 (append
1469 (org-split-string val ":")
1470 (plist-get plist :filetags)))))))
1472 ;; Options in `org-export-options-alist'.
1473 (dolist (property (funcall find-properties key))
1474 (setq
1475 plist
1476 (plist-put
1477 plist property
1478 ;; Handle value depending on specified
1479 ;; BEHAVIOR.
1480 (cl-case (nth 4 (assq property options))
1481 (parse
1482 (unless (memq property to-parse)
1483 (push property to-parse))
1484 ;; Even if `parse' implies `space'
1485 ;; behavior, we separate line with
1486 ;; "\n" so as to preserve
1487 ;; line-breaks. However, empty
1488 ;; lines are forbidden since `parse'
1489 ;; doesn't allow more than one
1490 ;; paragraph.
1491 (let ((old (plist-get plist property)))
1492 (cond ((not (org-string-nw-p val)) old)
1493 (old (concat old "\n" val))
1494 (t val))))
1495 (space
1496 (if (not (plist-get plist property))
1497 (org-trim val)
1498 (concat (plist-get plist property)
1500 (org-trim val))))
1501 (newline
1502 (org-trim
1503 (concat (plist-get plist property)
1504 "\n"
1505 (org-trim val))))
1506 (split `(,@(plist-get plist property)
1507 ,@(org-split-string val)))
1508 ((t) val)
1509 (otherwise
1510 (if (not (plist-member plist property)) val
1511 (plist-get plist property)))))))))))))))))
1512 ;; Read options in the current buffer and return value.
1513 (funcall get-options (and buffer-file-name (list buffer-file-name)))
1514 ;; Parse properties in TO-PARSE. Remove newline characters not
1515 ;; involved in line breaks to simulate `space' behavior.
1516 ;; Finally return options.
1517 (dolist (p to-parse plist)
1518 (let ((value (org-element-parse-secondary-string
1519 (plist-get plist p)
1520 (org-element-restriction 'keyword))))
1521 (org-element-map value 'plain-text
1522 (lambda (s)
1523 (org-element-set-element
1524 s (replace-regexp-in-string "\n" " " s))))
1525 (setq plist (plist-put plist p value)))))))
1527 (defun org-export--get-buffer-attributes ()
1528 "Return properties related to buffer attributes, as a plist."
1529 (list :input-buffer (buffer-name (buffer-base-buffer))
1530 :input-file (buffer-file-name (buffer-base-buffer))))
1532 (defun org-export--get-global-options (&optional backend)
1533 "Return global export options as a plist.
1534 Optional argument BACKEND, if non-nil, is an export back-end, as
1535 returned by, e.g., `org-export-create-backend'. It specifies
1536 which back-end specific export options should also be read in the
1537 process."
1538 (let (plist
1539 ;; Priority is given to back-end specific options.
1540 (all (append (and backend (org-export-get-all-options backend))
1541 org-export-options-alist)))
1542 (dolist (cell all plist)
1543 (let ((prop (car cell)))
1544 (unless (plist-member plist prop)
1545 (setq plist
1546 (plist-put
1547 plist
1548 prop
1549 ;; Evaluate default value provided.
1550 (let ((value (eval (nth 3 cell))))
1551 (if (eq (nth 4 cell) 'parse)
1552 (org-element-parse-secondary-string
1553 value (org-element-restriction 'keyword))
1554 value)))))))))
1556 (defun org-export--list-bound-variables ()
1557 "Return variables bound from BIND keywords in current buffer.
1558 Also look for BIND keywords in setup files. The return value is
1559 an alist where associations are (VARIABLE-NAME VALUE)."
1560 (when org-export-allow-bind-keywords
1561 (letrec ((collect-bind
1562 (lambda (files alist)
1563 ;; Return an alist between variable names and their
1564 ;; value. FILES is a list of setup files names read
1565 ;; so far, used to avoid circular dependencies. ALIST
1566 ;; is the alist collected so far.
1567 (let ((case-fold-search t))
1568 (org-with-wide-buffer
1569 (goto-char (point-min))
1570 (while (re-search-forward
1571 "^[ \t]*#\\+\\(BIND\\|SETUPFILE\\):" nil t)
1572 (let ((element (org-element-at-point)))
1573 (when (eq (org-element-type element) 'keyword)
1574 (let ((val (org-element-property :value element)))
1575 (if (equal (org-element-property :key element)
1576 "BIND")
1577 (push (read (format "(%s)" val)) alist)
1578 ;; Enter setup file.
1579 (let ((file (expand-file-name
1580 (org-remove-double-quotes val))))
1581 (unless (member file files)
1582 (with-temp-buffer
1583 (let ((org-inhibit-startup t)) (org-mode))
1584 (insert (org-file-contents file 'noerror))
1585 (setq alist
1586 (funcall collect-bind
1587 (cons file files)
1588 alist))))))))))
1589 alist)))))
1590 ;; Return value in appropriate order of appearance.
1591 (nreverse (funcall collect-bind nil nil)))))
1593 ;; defsubst org-export-get-parent must be defined before first use,
1594 ;; was originally defined in the topology section
1596 (defsubst org-export-get-parent (blob)
1597 "Return BLOB parent or nil.
1598 BLOB is the element or object considered."
1599 (org-element-property :parent blob))
1601 ;;;; Tree Properties
1603 ;; Tree properties are information extracted from parse tree. They
1604 ;; are initialized at the beginning of the transcoding process by
1605 ;; `org-export-collect-tree-properties'.
1607 ;; Dedicated functions focus on computing the value of specific tree
1608 ;; properties during initialization. Thus,
1609 ;; `org-export--populate-ignore-list' lists elements and objects that
1610 ;; should be skipped during export, `org-export--get-min-level' gets
1611 ;; the minimal exportable level, used as a basis to compute relative
1612 ;; level for headlines. Eventually
1613 ;; `org-export--collect-headline-numbering' builds an alist between
1614 ;; headlines and their numbering.
1616 (defun org-export-collect-tree-properties (data info)
1617 "Extract tree properties from parse tree.
1619 DATA is the parse tree from which information is retrieved. INFO
1620 is a list holding export options.
1622 Following tree properties are set or updated:
1624 `:exported-data' Hash table used to memoize results from
1625 `org-export-data'.
1627 `:headline-offset' Offset between true level of headlines and
1628 local level. An offset of -1 means a headline
1629 of level 2 should be considered as a level
1630 1 headline in the context.
1632 `:headline-numbering' Alist of all headlines as key an the
1633 associated numbering as value.
1635 Return updated plist."
1636 ;; Install the parse tree in the communication channel.
1637 (setq info (plist-put info :parse-tree data))
1638 ;; Compute `:headline-offset' in order to be able to use
1639 ;; `org-export-get-relative-level'.
1640 (setq info
1641 (plist-put info
1642 :headline-offset
1643 (- 1 (org-export--get-min-level data info))))
1644 ;; Properties order doesn't matter: get the rest of the tree
1645 ;; properties.
1646 (nconc
1647 `(:headline-numbering ,(org-export--collect-headline-numbering data info)
1648 :exported-data ,(make-hash-table :test 'eq :size 4001))
1649 info))
1651 (defun org-export--get-min-level (data options)
1652 "Return minimum exportable headline's level in DATA.
1653 DATA is parsed tree as returned by `org-element-parse-buffer'.
1654 OPTIONS is a plist holding export options."
1655 (catch 'exit
1656 (let ((min-level 10000))
1657 (mapc
1658 (lambda (blob)
1659 (when (and (eq (org-element-type blob) 'headline)
1660 (not (org-element-property :footnote-section-p blob))
1661 (not (memq blob (plist-get options :ignore-list))))
1662 (setq min-level (min (org-element-property :level blob) min-level)))
1663 (when (= min-level 1) (throw 'exit 1)))
1664 (org-element-contents data))
1665 ;; If no headline was found, for the sake of consistency, set
1666 ;; minimum level to 1 nonetheless.
1667 (if (= min-level 10000) 1 min-level))))
1669 (defun org-export--collect-headline-numbering (data options)
1670 "Return numbering of all exportable, numbered headlines in a parse tree.
1672 DATA is the parse tree. OPTIONS is the plist holding export
1673 options.
1675 Return an alist whose key is a headline and value is its
1676 associated numbering \(in the shape of a list of numbers\) or nil
1677 for a footnotes section."
1678 (let ((numbering (make-vector org-export-max-depth 0)))
1679 (org-element-map data 'headline
1680 (lambda (headline)
1681 (when (and (org-export-numbered-headline-p headline options)
1682 (not (org-element-property :footnote-section-p headline)))
1683 (let ((relative-level
1684 (1- (org-export-get-relative-level headline options))))
1685 (cons
1686 headline
1687 (cl-loop
1688 for n across numbering
1689 for idx from 0 to org-export-max-depth
1690 when (< idx relative-level) collect n
1691 when (= idx relative-level) collect (aset numbering idx (1+ n))
1692 when (> idx relative-level) do (aset numbering idx 0))))))
1693 options)))
1695 (defun org-export--selected-trees (data info)
1696 "List headlines and inlinetasks with a select tag in their tree.
1697 DATA is parsed data as returned by `org-element-parse-buffer'.
1698 INFO is a plist holding export options."
1699 (letrec ((selected-trees)
1700 (walk-data
1701 (lambda (data genealogy)
1702 (let ((type (org-element-type data)))
1703 (cond
1704 ((memq type '(headline inlinetask))
1705 (let ((tags (org-element-property :tags data)))
1706 (if (cl-loop for tag in (plist-get info :select-tags)
1707 thereis (member tag tags))
1708 ;; When a select tag is found, mark full
1709 ;; genealogy and every headline within the
1710 ;; tree as acceptable.
1711 (setq selected-trees
1712 (append
1713 genealogy
1714 (org-element-map data '(headline inlinetask)
1715 #'identity)
1716 selected-trees))
1717 ;; If at a headline, continue searching in tree,
1718 ;; recursively.
1719 (when (eq type 'headline)
1720 (dolist (el (org-element-contents data))
1721 (funcall walk-data el (cons data genealogy)))))))
1722 ((or (eq type 'org-data)
1723 (memq type org-element-greater-elements))
1724 (dolist (el (org-element-contents data))
1725 (funcall walk-data el genealogy))))))))
1726 (funcall walk-data data nil)
1727 selected-trees))
1729 (defun org-export--skip-p (blob options selected)
1730 "Non-nil when element or object BLOB should be skipped during export.
1731 OPTIONS is the plist holding export options. SELECTED, when
1732 non-nil, is a list of headlines or inlinetasks belonging to
1733 a tree with a select tag."
1734 (cl-case (org-element-type blob)
1735 (clock (not (plist-get options :with-clocks)))
1736 (drawer
1737 (let ((with-drawers-p (plist-get options :with-drawers)))
1738 (or (not with-drawers-p)
1739 (and (consp with-drawers-p)
1740 ;; If `:with-drawers' value starts with `not', ignore
1741 ;; every drawer whose name belong to that list.
1742 ;; Otherwise, ignore drawers whose name isn't in that
1743 ;; list.
1744 (let ((name (org-element-property :drawer-name blob)))
1745 (if (eq (car with-drawers-p) 'not)
1746 (member-ignore-case name (cdr with-drawers-p))
1747 (not (member-ignore-case name with-drawers-p))))))))
1748 (fixed-width (not (plist-get options :with-fixed-width)))
1749 ((footnote-definition footnote-reference)
1750 (not (plist-get options :with-footnotes)))
1751 ((headline inlinetask)
1752 (let ((with-tasks (plist-get options :with-tasks))
1753 (todo (org-element-property :todo-keyword blob))
1754 (todo-type (org-element-property :todo-type blob))
1755 (archived (plist-get options :with-archived-trees))
1756 (tags (org-element-property :tags blob)))
1758 (and (eq (org-element-type blob) 'inlinetask)
1759 (not (plist-get options :with-inlinetasks)))
1760 ;; Ignore subtrees with an exclude tag.
1761 (cl-loop for k in (plist-get options :exclude-tags)
1762 thereis (member k tags))
1763 ;; When a select tag is present in the buffer, ignore any tree
1764 ;; without it.
1765 (and selected (not (memq blob selected)))
1766 ;; Ignore commented sub-trees.
1767 (org-element-property :commentedp blob)
1768 ;; Ignore archived subtrees if `:with-archived-trees' is nil.
1769 (and (not archived) (org-element-property :archivedp blob))
1770 ;; Ignore tasks, if specified by `:with-tasks' property.
1771 (and todo
1772 (or (not with-tasks)
1773 (and (memq with-tasks '(todo done))
1774 (not (eq todo-type with-tasks)))
1775 (and (consp with-tasks) (not (member todo with-tasks))))))))
1776 ((latex-environment latex-fragment) (not (plist-get options :with-latex)))
1777 (node-property
1778 (let ((properties-set (plist-get options :with-properties)))
1779 (cond ((null properties-set) t)
1780 ((consp properties-set)
1781 (not (member-ignore-case (org-element-property :key blob)
1782 properties-set))))))
1783 (planning (not (plist-get options :with-planning)))
1784 (property-drawer (not (plist-get options :with-properties)))
1785 (statistics-cookie (not (plist-get options :with-statistics-cookies)))
1786 (table (not (plist-get options :with-tables)))
1787 (table-cell
1788 (and (org-export-table-has-special-column-p
1789 (org-export-get-parent-table blob))
1790 (org-export-first-sibling-p blob options)))
1791 (table-row (org-export-table-row-is-special-p blob options))
1792 (timestamp
1793 ;; `:with-timestamps' only applies to isolated timestamps
1794 ;; objects, i.e. timestamp objects in a paragraph containing only
1795 ;; timestamps and whitespaces.
1796 (when (let ((parent (org-export-get-parent-element blob)))
1797 (and (memq (org-element-type parent) '(paragraph verse-block))
1798 (not (org-element-map parent
1799 (cons 'plain-text
1800 (remq 'timestamp org-element-all-objects))
1801 (lambda (obj)
1802 (or (not (stringp obj)) (org-string-nw-p obj)))
1803 options t))))
1804 (cl-case (plist-get options :with-timestamps)
1805 ((nil) t)
1806 (active
1807 (not (memq (org-element-property :type blob) '(active active-range))))
1808 (inactive
1809 (not (memq (org-element-property :type blob)
1810 '(inactive inactive-range)))))))))
1813 ;;; The Transcoder
1815 ;; `org-export-data' reads a parse tree (obtained with, i.e.
1816 ;; `org-element-parse-buffer') and transcodes it into a specified
1817 ;; back-end output. It takes care of filtering out elements or
1818 ;; objects according to export options and organizing the output blank
1819 ;; lines and white space are preserved. The function memoizes its
1820 ;; results, so it is cheap to call it within transcoders.
1822 ;; It is possible to modify locally the back-end used by
1823 ;; `org-export-data' or even use a temporary back-end by using
1824 ;; `org-export-data-with-backend'.
1826 ;; `org-export-transcoder' is an accessor returning appropriate
1827 ;; translator function for a given element or object.
1829 (defun org-export-transcoder (blob info)
1830 "Return appropriate transcoder for BLOB.
1831 INFO is a plist containing export directives."
1832 (let ((type (org-element-type blob)))
1833 ;; Return contents only for complete parse trees.
1834 (if (eq type 'org-data) (lambda (_datum contents _info) contents)
1835 (let ((transcoder (cdr (assq type (plist-get info :translate-alist)))))
1836 (and (functionp transcoder) transcoder)))))
1838 (defun org-export-data (data info)
1839 "Convert DATA into current back-end format.
1841 DATA is a parse tree, an element or an object or a secondary
1842 string. INFO is a plist holding export options.
1844 Return a string."
1845 (or (gethash data (plist-get info :exported-data))
1846 (let* ((type (org-element-type data))
1847 (results
1848 (cond
1849 ;; Ignored element/object.
1850 ((memq data (plist-get info :ignore-list)) nil)
1851 ;; Plain text.
1852 ((eq type 'plain-text)
1853 (org-export-filter-apply-functions
1854 (plist-get info :filter-plain-text)
1855 (let ((transcoder (org-export-transcoder data info)))
1856 (if transcoder (funcall transcoder data info) data))
1857 info))
1858 ;; Secondary string.
1859 ((not type)
1860 (mapconcat (lambda (obj) (org-export-data obj info)) data ""))
1861 ;; Element/Object without contents or, as a special
1862 ;; case, headline with archive tag and archived trees
1863 ;; restricted to title only.
1864 ((or (not (org-element-contents data))
1865 (and (eq type 'headline)
1866 (eq (plist-get info :with-archived-trees) 'headline)
1867 (org-element-property :archivedp data)))
1868 (let ((transcoder (org-export-transcoder data info)))
1869 (or (and (functionp transcoder)
1870 (funcall transcoder data nil info))
1871 ;; Export snippets never return a nil value so
1872 ;; that white spaces following them are never
1873 ;; ignored.
1874 (and (eq type 'export-snippet) ""))))
1875 ;; Element/Object with contents.
1877 (let ((transcoder (org-export-transcoder data info)))
1878 (when transcoder
1879 (let* ((greaterp (memq type org-element-greater-elements))
1880 (objectp
1881 (and (not greaterp)
1882 (memq type org-element-recursive-objects)))
1883 (contents
1884 (mapconcat
1885 (lambda (element) (org-export-data element info))
1886 (org-element-contents
1887 (if (or greaterp objectp) data
1888 ;; Elements directly containing
1889 ;; objects must have their indentation
1890 ;; normalized first.
1891 (org-element-normalize-contents
1892 data
1893 ;; When normalizing contents of the
1894 ;; first paragraph in an item or
1895 ;; a footnote definition, ignore
1896 ;; first line's indentation: there is
1897 ;; none and it might be misleading.
1898 (when (eq type 'paragraph)
1899 (let ((parent (org-export-get-parent data)))
1900 (and
1901 (eq (car (org-element-contents parent))
1902 data)
1903 (memq (org-element-type parent)
1904 '(footnote-definition item))))))))
1905 "")))
1906 (funcall transcoder data
1907 (if (not greaterp) contents
1908 (org-element-normalize-string contents))
1909 info))))))))
1910 ;; Final result will be memoized before being returned.
1911 (puthash
1912 data
1913 (cond
1914 ((not results) "")
1915 ((memq type '(org-data plain-text nil)) results)
1916 ;; Append the same white space between elements or objects
1917 ;; as in the original buffer, and call appropriate filters.
1919 (let ((results
1920 (org-export-filter-apply-functions
1921 (plist-get info (intern (format ":filter-%s" type)))
1922 (let ((post-blank (or (org-element-property :post-blank data)
1923 0)))
1924 (if (memq type org-element-all-elements)
1925 (concat (org-element-normalize-string results)
1926 (make-string post-blank ?\n))
1927 (concat results (make-string post-blank ?\s))))
1928 info)))
1929 results)))
1930 (plist-get info :exported-data)))))
1932 (defun org-export-data-with-backend (data backend info)
1933 "Convert DATA into BACKEND format.
1935 DATA is an element, an object, a secondary string or a string.
1936 BACKEND is a symbol. INFO is a plist used as a communication
1937 channel.
1939 Unlike to `org-export-with-backend', this function will
1940 recursively convert DATA using BACKEND translation table."
1941 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
1942 (org-export-data
1943 data
1944 ;; Set-up a new communication channel with translations defined in
1945 ;; BACKEND as the translate table and a new hash table for
1946 ;; memoization.
1947 (org-combine-plists
1948 info
1949 (list :back-end backend
1950 :translate-alist (org-export-get-all-transcoders backend)
1951 ;; Size of the hash table is reduced since this function
1952 ;; will probably be used on small trees.
1953 :exported-data (make-hash-table :test 'eq :size 401)))))
1955 (defun org-export-expand (blob contents &optional with-affiliated)
1956 "Expand a parsed element or object to its original state.
1958 BLOB is either an element or an object. CONTENTS is its
1959 contents, as a string or nil.
1961 When optional argument WITH-AFFILIATED is non-nil, add affiliated
1962 keywords before output."
1963 (let ((type (org-element-type blob)))
1964 (concat (and with-affiliated (memq type org-element-all-elements)
1965 (org-element--interpret-affiliated-keywords blob))
1966 (funcall (intern (format "org-element-%s-interpreter" type))
1967 blob contents))))
1971 ;;; The Filter System
1973 ;; Filters allow end-users to tweak easily the transcoded output.
1974 ;; They are the functional counterpart of hooks, as every filter in
1975 ;; a set is applied to the return value of the previous one.
1977 ;; Every set is back-end agnostic. Although, a filter is always
1978 ;; called, in addition to the string it applies to, with the back-end
1979 ;; used as argument, so it's easy for the end-user to add back-end
1980 ;; specific filters in the set. The communication channel, as
1981 ;; a plist, is required as the third argument.
1983 ;; From the developer side, filters sets can be installed in the
1984 ;; process with the help of `org-export-define-backend', which
1985 ;; internally stores filters as an alist. Each association has a key
1986 ;; among the following symbols and a function or a list of functions
1987 ;; as value.
1989 ;; - `:filter-options' applies to the property list containing export
1990 ;; options. Unlike to other filters, functions in this list accept
1991 ;; two arguments instead of three: the property list containing
1992 ;; export options and the back-end. Users can set its value through
1993 ;; `org-export-filter-options-functions' variable.
1995 ;; - `:filter-parse-tree' applies directly to the complete parsed
1996 ;; tree. Users can set it through
1997 ;; `org-export-filter-parse-tree-functions' variable.
1999 ;; - `:filter-body' applies to the body of the output, before template
2000 ;; translator chimes in. Users can set it through
2001 ;; `org-export-filter-body-functions' variable.
2003 ;; - `:filter-final-output' applies to the final transcoded string.
2004 ;; Users can set it with `org-export-filter-final-output-functions'
2005 ;; variable.
2007 ;; - `:filter-plain-text' applies to any string not recognized as Org
2008 ;; syntax. `org-export-filter-plain-text-functions' allows users to
2009 ;; configure it.
2011 ;; - `:filter-TYPE' applies on the string returned after an element or
2012 ;; object of type TYPE has been transcoded. A user can modify
2013 ;; `org-export-filter-TYPE-functions' to install these filters.
2015 ;; All filters sets are applied with
2016 ;; `org-export-filter-apply-functions' function. Filters in a set are
2017 ;; applied in a LIFO fashion. It allows developers to be sure that
2018 ;; their filters will be applied first.
2020 ;; Filters properties are installed in communication channel with
2021 ;; `org-export-install-filters' function.
2023 ;; Eventually, two hooks (`org-export-before-processing-hook' and
2024 ;; `org-export-before-parsing-hook') are run at the beginning of the
2025 ;; export process and just before parsing to allow for heavy structure
2026 ;; modifications.
2029 ;;;; Hooks
2031 (defvar org-export-before-processing-hook nil
2032 "Hook run at the beginning of the export process.
2034 This is run before include keywords and macros are expanded and
2035 Babel code blocks executed, on a copy of the original buffer
2036 being exported. Visibility and narrowing are preserved. Point
2037 is at the beginning of the buffer.
2039 Every function in this hook will be called with one argument: the
2040 back-end currently used, as a symbol.")
2042 (defvar org-export-before-parsing-hook nil
2043 "Hook run before parsing an export buffer.
2045 This is run after include keywords and macros have been expanded
2046 and Babel code blocks executed, on a copy of the original buffer
2047 being exported. Visibility and narrowing are preserved. Point
2048 is at the beginning of the buffer.
2050 Every function in this hook will be called with one argument: the
2051 back-end currently used, as a symbol.")
2054 ;;;; Special Filters
2056 (defvar org-export-filter-options-functions nil
2057 "List of functions applied to the export options.
2058 Each filter is called with two arguments: the export options, as
2059 a plist, and the back-end, as a symbol. It must return
2060 a property list containing export options.")
2062 (defvar org-export-filter-parse-tree-functions nil
2063 "List of functions applied to the parsed tree.
2064 Each filter is called with three arguments: the parse tree, as
2065 returned by `org-element-parse-buffer', the back-end, as
2066 a symbol, and the communication channel, as a plist. It must
2067 return the modified parse tree to transcode.")
2069 (defvar org-export-filter-plain-text-functions nil
2070 "List of functions applied to plain text.
2071 Each filter is called with three arguments: a string which
2072 contains no Org syntax, the back-end, as a symbol, and the
2073 communication channel, as a plist. It must return a string or
2074 nil.")
2076 (defvar org-export-filter-body-functions nil
2077 "List of functions applied to transcoded body.
2078 Each filter is called with three arguments: a string which
2079 contains no Org syntax, the back-end, as a symbol, and the
2080 communication channel, as a plist. It must return a string or
2081 nil.")
2083 (defvar org-export-filter-final-output-functions nil
2084 "List of functions applied to the transcoded string.
2085 Each filter is called with three arguments: the full transcoded
2086 string, the back-end, as a symbol, and the communication channel,
2087 as a plist. It must return a string that will be used as the
2088 final export output.")
2091 ;;;; Elements Filters
2093 (defvar org-export-filter-babel-call-functions nil
2094 "List of functions applied to a transcoded babel-call.
2095 Each filter is called with three arguments: the transcoded data,
2096 as a string, the back-end, as a symbol, and the communication
2097 channel, as a plist. It must return a string or nil.")
2099 (defvar org-export-filter-center-block-functions nil
2100 "List of functions applied to a transcoded center block.
2101 Each filter is called with three arguments: the transcoded data,
2102 as a string, the back-end, as a symbol, and the communication
2103 channel, as a plist. It must return a string or nil.")
2105 (defvar org-export-filter-clock-functions nil
2106 "List of functions applied to a transcoded clock.
2107 Each filter is called with three arguments: the transcoded data,
2108 as a string, the back-end, as a symbol, and the communication
2109 channel, as a plist. It must return a string or nil.")
2111 (defvar org-export-filter-diary-sexp-functions nil
2112 "List of functions applied to a transcoded diary-sexp.
2113 Each filter is called with three arguments: the transcoded data,
2114 as a string, the back-end, as a symbol, and the communication
2115 channel, as a plist. It must return a string or nil.")
2117 (defvar org-export-filter-drawer-functions nil
2118 "List of functions applied to a transcoded drawer.
2119 Each filter is called with three arguments: the transcoded data,
2120 as a string, the back-end, as a symbol, and the communication
2121 channel, as a plist. It must return a string or nil.")
2123 (defvar org-export-filter-dynamic-block-functions nil
2124 "List of functions applied to a transcoded dynamic-block.
2125 Each filter is called with three arguments: the transcoded data,
2126 as a string, the back-end, as a symbol, and the communication
2127 channel, as a plist. It must return a string or nil.")
2129 (defvar org-export-filter-example-block-functions nil
2130 "List of functions applied to a transcoded example-block.
2131 Each filter is called with three arguments: the transcoded data,
2132 as a string, the back-end, as a symbol, and the communication
2133 channel, as a plist. It must return a string or nil.")
2135 (defvar org-export-filter-export-block-functions nil
2136 "List of functions applied to a transcoded export-block.
2137 Each filter is called with three arguments: the transcoded data,
2138 as a string, the back-end, as a symbol, and the communication
2139 channel, as a plist. It must return a string or nil.")
2141 (defvar org-export-filter-fixed-width-functions nil
2142 "List of functions applied to a transcoded fixed-width.
2143 Each filter is called with three arguments: the transcoded data,
2144 as a string, the back-end, as a symbol, and the communication
2145 channel, as a plist. It must return a string or nil.")
2147 (defvar org-export-filter-footnote-definition-functions nil
2148 "List of functions applied to a transcoded footnote-definition.
2149 Each filter is called with three arguments: the transcoded data,
2150 as a string, the back-end, as a symbol, and the communication
2151 channel, as a plist. It must return a string or nil.")
2153 (defvar org-export-filter-headline-functions nil
2154 "List of functions applied to a transcoded headline.
2155 Each filter is called with three arguments: the transcoded data,
2156 as a string, the back-end, as a symbol, and the communication
2157 channel, as a plist. It must return a string or nil.")
2159 (defvar org-export-filter-horizontal-rule-functions nil
2160 "List of functions applied to a transcoded horizontal-rule.
2161 Each filter is called with three arguments: the transcoded data,
2162 as a string, the back-end, as a symbol, and the communication
2163 channel, as a plist. It must return a string or nil.")
2165 (defvar org-export-filter-inlinetask-functions nil
2166 "List of functions applied to a transcoded inlinetask.
2167 Each filter is called with three arguments: the transcoded data,
2168 as a string, the back-end, as a symbol, and the communication
2169 channel, as a plist. It must return a string or nil.")
2171 (defvar org-export-filter-item-functions nil
2172 "List of functions applied to a transcoded item.
2173 Each filter is called with three arguments: the transcoded data,
2174 as a string, the back-end, as a symbol, and the communication
2175 channel, as a plist. It must return a string or nil.")
2177 (defvar org-export-filter-keyword-functions nil
2178 "List of functions applied to a transcoded keyword.
2179 Each filter is called with three arguments: the transcoded data,
2180 as a string, the back-end, as a symbol, and the communication
2181 channel, as a plist. It must return a string or nil.")
2183 (defvar org-export-filter-latex-environment-functions nil
2184 "List of functions applied to a transcoded latex-environment.
2185 Each filter is called with three arguments: the transcoded data,
2186 as a string, the back-end, as a symbol, and the communication
2187 channel, as a plist. It must return a string or nil.")
2189 (defvar org-export-filter-node-property-functions nil
2190 "List of functions applied to a transcoded node-property.
2191 Each filter is called with three arguments: the transcoded data,
2192 as a string, the back-end, as a symbol, and the communication
2193 channel, as a plist. It must return a string or nil.")
2195 (defvar org-export-filter-paragraph-functions nil
2196 "List of functions applied to a transcoded paragraph.
2197 Each filter is called with three arguments: the transcoded data,
2198 as a string, the back-end, as a symbol, and the communication
2199 channel, as a plist. It must return a string or nil.")
2201 (defvar org-export-filter-plain-list-functions nil
2202 "List of functions applied to a transcoded plain-list.
2203 Each filter is called with three arguments: the transcoded data,
2204 as a string, the back-end, as a symbol, and the communication
2205 channel, as a plist. It must return a string or nil.")
2207 (defvar org-export-filter-planning-functions nil
2208 "List of functions applied to a transcoded planning.
2209 Each filter is called with three arguments: the transcoded data,
2210 as a string, the back-end, as a symbol, and the communication
2211 channel, as a plist. It must return a string or nil.")
2213 (defvar org-export-filter-property-drawer-functions nil
2214 "List of functions applied to a transcoded property-drawer.
2215 Each filter is called with three arguments: the transcoded data,
2216 as a string, the back-end, as a symbol, and the communication
2217 channel, as a plist. It must return a string or nil.")
2219 (defvar org-export-filter-quote-block-functions nil
2220 "List of functions applied to a transcoded quote block.
2221 Each filter is called with three arguments: the transcoded quote
2222 data, as a string, the back-end, as a symbol, and the
2223 communication channel, as a plist. It must return a string or
2224 nil.")
2226 (defvar org-export-filter-section-functions nil
2227 "List of functions applied to a transcoded section.
2228 Each filter is called with three arguments: the transcoded data,
2229 as a string, the back-end, as a symbol, and the communication
2230 channel, as a plist. It must return a string or nil.")
2232 (defvar org-export-filter-special-block-functions nil
2233 "List of functions applied to a transcoded special block.
2234 Each filter is called with three arguments: the transcoded data,
2235 as a string, the back-end, as a symbol, and the communication
2236 channel, as a plist. It must return a string or nil.")
2238 (defvar org-export-filter-src-block-functions nil
2239 "List of functions applied to a transcoded src-block.
2240 Each filter is called with three arguments: the transcoded data,
2241 as a string, the back-end, as a symbol, and the communication
2242 channel, as a plist. It must return a string or nil.")
2244 (defvar org-export-filter-table-functions nil
2245 "List of functions applied to a transcoded table.
2246 Each filter is called with three arguments: the transcoded data,
2247 as a string, the back-end, as a symbol, and the communication
2248 channel, as a plist. It must return a string or nil.")
2250 (defvar org-export-filter-table-cell-functions nil
2251 "List of functions applied to a transcoded table-cell.
2252 Each filter is called with three arguments: the transcoded data,
2253 as a string, the back-end, as a symbol, and the communication
2254 channel, as a plist. It must return a string or nil.")
2256 (defvar org-export-filter-table-row-functions nil
2257 "List of functions applied to a transcoded table-row.
2258 Each filter is called with three arguments: the transcoded data,
2259 as a string, the back-end, as a symbol, and the communication
2260 channel, as a plist. It must return a string or nil.")
2262 (defvar org-export-filter-verse-block-functions nil
2263 "List of functions applied to a transcoded verse block.
2264 Each filter is called with three arguments: the transcoded data,
2265 as a string, the back-end, as a symbol, and the communication
2266 channel, as a plist. It must return a string or nil.")
2269 ;;;; Objects Filters
2271 (defvar org-export-filter-bold-functions nil
2272 "List of functions applied to transcoded bold text.
2273 Each filter is called with three arguments: the transcoded data,
2274 as a string, the back-end, as a symbol, and the communication
2275 channel, as a plist. It must return a string or nil.")
2277 (defvar org-export-filter-code-functions nil
2278 "List of functions applied to transcoded code text.
2279 Each filter is called with three arguments: the transcoded data,
2280 as a string, the back-end, as a symbol, and the communication
2281 channel, as a plist. It must return a string or nil.")
2283 (defvar org-export-filter-entity-functions nil
2284 "List of functions applied to a transcoded entity.
2285 Each filter is called with three arguments: the transcoded data,
2286 as a string, the back-end, as a symbol, and the communication
2287 channel, as a plist. It must return a string or nil.")
2289 (defvar org-export-filter-export-snippet-functions nil
2290 "List of functions applied to a transcoded export-snippet.
2291 Each filter is called with three arguments: the transcoded data,
2292 as a string, the back-end, as a symbol, and the communication
2293 channel, as a plist. It must return a string or nil.")
2295 (defvar org-export-filter-footnote-reference-functions nil
2296 "List of functions applied to a transcoded footnote-reference.
2297 Each filter is called with three arguments: the transcoded data,
2298 as a string, the back-end, as a symbol, and the communication
2299 channel, as a plist. It must return a string or nil.")
2301 (defvar org-export-filter-inline-babel-call-functions nil
2302 "List of functions applied to a transcoded inline-babel-call.
2303 Each filter is called with three arguments: the transcoded data,
2304 as a string, the back-end, as a symbol, and the communication
2305 channel, as a plist. It must return a string or nil.")
2307 (defvar org-export-filter-inline-src-block-functions nil
2308 "List of functions applied to a transcoded inline-src-block.
2309 Each filter is called with three arguments: the transcoded data,
2310 as a string, the back-end, as a symbol, and the communication
2311 channel, as a plist. It must return a string or nil.")
2313 (defvar org-export-filter-italic-functions nil
2314 "List of functions applied to transcoded italic text.
2315 Each filter is called with three arguments: the transcoded data,
2316 as a string, the back-end, as a symbol, and the communication
2317 channel, as a plist. It must return a string or nil.")
2319 (defvar org-export-filter-latex-fragment-functions nil
2320 "List of functions applied to a transcoded latex-fragment.
2321 Each filter is called with three arguments: the transcoded data,
2322 as a string, the back-end, as a symbol, and the communication
2323 channel, as a plist. It must return a string or nil.")
2325 (defvar org-export-filter-line-break-functions nil
2326 "List of functions applied to a transcoded line-break.
2327 Each filter is called with three arguments: the transcoded data,
2328 as a string, the back-end, as a symbol, and the communication
2329 channel, as a plist. It must return a string or nil.")
2331 (defvar org-export-filter-link-functions nil
2332 "List of functions applied to a transcoded link.
2333 Each filter is called with three arguments: the transcoded data,
2334 as a string, the back-end, as a symbol, and the communication
2335 channel, as a plist. It must return a string or nil.")
2337 (defvar org-export-filter-radio-target-functions nil
2338 "List of functions applied to a transcoded radio-target.
2339 Each filter is called with three arguments: the transcoded data,
2340 as a string, the back-end, as a symbol, and the communication
2341 channel, as a plist. It must return a string or nil.")
2343 (defvar org-export-filter-statistics-cookie-functions nil
2344 "List of functions applied to a transcoded statistics-cookie.
2345 Each filter is called with three arguments: the transcoded data,
2346 as a string, the back-end, as a symbol, and the communication
2347 channel, as a plist. It must return a string or nil.")
2349 (defvar org-export-filter-strike-through-functions nil
2350 "List of functions applied to transcoded strike-through text.
2351 Each filter is called with three arguments: the transcoded data,
2352 as a string, the back-end, as a symbol, and the communication
2353 channel, as a plist. It must return a string or nil.")
2355 (defvar org-export-filter-subscript-functions nil
2356 "List of functions applied to a transcoded subscript.
2357 Each filter is called with three arguments: the transcoded data,
2358 as a string, the back-end, as a symbol, and the communication
2359 channel, as a plist. It must return a string or nil.")
2361 (defvar org-export-filter-superscript-functions nil
2362 "List of functions applied to a transcoded superscript.
2363 Each filter is called with three arguments: the transcoded data,
2364 as a string, the back-end, as a symbol, and the communication
2365 channel, as a plist. It must return a string or nil.")
2367 (defvar org-export-filter-target-functions nil
2368 "List of functions applied to a transcoded target.
2369 Each filter is called with three arguments: the transcoded data,
2370 as a string, the back-end, as a symbol, and the communication
2371 channel, as a plist. It must return a string or nil.")
2373 (defvar org-export-filter-timestamp-functions nil
2374 "List of functions applied to a transcoded timestamp.
2375 Each filter is called with three arguments: the transcoded data,
2376 as a string, the back-end, as a symbol, and the communication
2377 channel, as a plist. It must return a string or nil.")
2379 (defvar org-export-filter-underline-functions nil
2380 "List of functions applied to transcoded underline text.
2381 Each filter is called with three arguments: the transcoded data,
2382 as a string, the back-end, as a symbol, and the communication
2383 channel, as a plist. It must return a string or nil.")
2385 (defvar org-export-filter-verbatim-functions nil
2386 "List of functions applied to transcoded verbatim text.
2387 Each filter is called with three arguments: the transcoded data,
2388 as a string, the back-end, as a symbol, and the communication
2389 channel, as a plist. It must return a string or nil.")
2392 ;;;; Filters Tools
2394 ;; Internal function `org-export-install-filters' installs filters
2395 ;; hard-coded in back-ends (developer filters) and filters from global
2396 ;; variables (user filters) in the communication channel.
2398 ;; Internal function `org-export-filter-apply-functions' takes care
2399 ;; about applying each filter in order to a given data. It ignores
2400 ;; filters returning a nil value but stops whenever a filter returns
2401 ;; an empty string.
2403 (defun org-export-filter-apply-functions (filters value info)
2404 "Call every function in FILTERS.
2406 Functions are called with arguments VALUE, current export
2407 back-end's name and INFO. A function returning a nil value will
2408 be skipped. If it returns the empty string, the process ends and
2409 VALUE is ignored.
2411 Call is done in a LIFO fashion, to be sure that developer
2412 specified filters, if any, are called first."
2413 (catch 'exit
2414 (let* ((backend (plist-get info :back-end))
2415 (backend-name (and backend (org-export-backend-name backend))))
2416 (dolist (filter filters value)
2417 (let ((result (funcall filter value backend-name info)))
2418 (cond ((not result) value)
2419 ((equal value "") (throw 'exit nil))
2420 (t (setq value result))))))))
2422 (defun org-export-install-filters (info)
2423 "Install filters properties in communication channel.
2424 INFO is a plist containing the current communication channel.
2425 Return the updated communication channel."
2426 (let (plist)
2427 ;; Install user-defined filters with `org-export-filters-alist'
2428 ;; and filters already in INFO (through ext-plist mechanism).
2429 (mapc (lambda (p)
2430 (let* ((prop (car p))
2431 (info-value (plist-get info prop))
2432 (default-value (symbol-value (cdr p))))
2433 (setq plist
2434 (plist-put plist prop
2435 ;; Filters in INFO will be called
2436 ;; before those user provided.
2437 (append (if (listp info-value) info-value
2438 (list info-value))
2439 default-value)))))
2440 org-export-filters-alist)
2441 ;; Prepend back-end specific filters to that list.
2442 (mapc (lambda (p)
2443 ;; Single values get consed, lists are appended.
2444 (let ((key (car p)) (value (cdr p)))
2445 (when value
2446 (setq plist
2447 (plist-put
2448 plist key
2449 (if (atom value) (cons value (plist-get plist key))
2450 (append value (plist-get plist key))))))))
2451 (org-export-get-all-filters (plist-get info :back-end)))
2452 ;; Return new communication channel.
2453 (org-combine-plists info plist)))
2457 ;;; Core functions
2459 ;; This is the room for the main function, `org-export-as', along with
2460 ;; its derivative, `org-export-string-as'.
2461 ;; `org-export--copy-to-kill-ring-p' determines if output of these
2462 ;; function should be added to kill ring.
2464 ;; Note that `org-export-as' doesn't really parse the current buffer,
2465 ;; but a copy of it (with the same buffer-local variables and
2466 ;; visibility), where macros and include keywords are expanded and
2467 ;; Babel blocks are executed, if appropriate.
2468 ;; `org-export-with-buffer-copy' macro prepares that copy.
2470 ;; File inclusion is taken care of by
2471 ;; `org-export-expand-include-keyword' and
2472 ;; `org-export--prepare-file-contents'. Structure wise, including
2473 ;; a whole Org file in a buffer often makes little sense. For
2474 ;; example, if the file contains a headline and the include keyword
2475 ;; was within an item, the item should contain the headline. That's
2476 ;; why file inclusion should be done before any structure can be
2477 ;; associated to the file, that is before parsing.
2479 ;; `org-export-insert-default-template' is a command to insert
2480 ;; a default template (or a back-end specific template) at point or in
2481 ;; current subtree.
2483 (defun org-export-copy-buffer ()
2484 "Return a copy of the current buffer.
2485 The copy preserves Org buffer-local variables, visibility and
2486 narrowing."
2487 (let ((copy-buffer-fun (org-export--generate-copy-script (current-buffer)))
2488 (new-buf (generate-new-buffer (buffer-name))))
2489 (with-current-buffer new-buf
2490 (funcall copy-buffer-fun)
2491 (set-buffer-modified-p nil))
2492 new-buf))
2494 (defmacro org-export-with-buffer-copy (&rest body)
2495 "Apply BODY in a copy of the current buffer.
2496 The copy preserves local variables, visibility and contents of
2497 the original buffer. Point is at the beginning of the buffer
2498 when BODY is applied."
2499 (declare (debug t))
2500 (org-with-gensyms (buf-copy)
2501 `(let ((,buf-copy (org-export-copy-buffer)))
2502 (unwind-protect
2503 (with-current-buffer ,buf-copy
2504 (goto-char (point-min))
2505 (progn ,@body))
2506 (and (buffer-live-p ,buf-copy)
2507 ;; Kill copy without confirmation.
2508 (progn (with-current-buffer ,buf-copy
2509 (restore-buffer-modified-p nil))
2510 (kill-buffer ,buf-copy)))))))
2512 (defun org-export--generate-copy-script (buffer)
2513 "Generate a function duplicating BUFFER.
2515 The copy will preserve local variables, visibility, contents and
2516 narrowing of the original buffer. If a region was active in
2517 BUFFER, contents will be narrowed to that region instead.
2519 The resulting function can be evaluated at a later time, from
2520 another buffer, effectively cloning the original buffer there.
2522 The function assumes BUFFER's major mode is `org-mode'."
2523 (with-current-buffer buffer
2524 `(lambda ()
2525 (let ((inhibit-modification-hooks t))
2526 ;; Set major mode. Ignore `org-mode-hook' as it has been run
2527 ;; already in BUFFER.
2528 (let ((org-mode-hook nil) (org-inhibit-startup t)) (org-mode))
2529 ;; Copy specific buffer local variables and variables set
2530 ;; through BIND keywords.
2531 ,@(let ((bound-variables (org-export--list-bound-variables))
2532 vars)
2533 (dolist (entry (buffer-local-variables (buffer-base-buffer)) vars)
2534 (when (consp entry)
2535 (let ((var (car entry))
2536 (val (cdr entry)))
2537 (and (not (memq var org-export-ignored-local-variables))
2538 (or (memq var
2539 '(default-directory
2540 buffer-file-name
2541 buffer-file-coding-system))
2542 (assq var bound-variables)
2543 (string-match "^\\(org-\\|orgtbl-\\)"
2544 (symbol-name var)))
2545 ;; Skip unreadable values, as they cannot be
2546 ;; sent to external process.
2547 (or (not val) (ignore-errors (read (format "%S" val))))
2548 (push `(set (make-local-variable (quote ,var))
2549 (quote ,val))
2550 vars))))))
2551 ;; Whole buffer contents.
2552 (insert
2553 ,(org-with-wide-buffer
2554 (buffer-substring-no-properties
2555 (point-min) (point-max))))
2556 ;; Narrowing.
2557 ,(if (org-region-active-p)
2558 `(narrow-to-region ,(region-beginning) ,(region-end))
2559 `(narrow-to-region ,(point-min) ,(point-max)))
2560 ;; Current position of point.
2561 (goto-char ,(point))
2562 ;; Overlays with invisible property.
2563 ,@(let (ov-set)
2564 (mapc
2565 (lambda (ov)
2566 (let ((invis-prop (overlay-get ov 'invisible)))
2567 (when invis-prop
2568 (push `(overlay-put
2569 (make-overlay ,(overlay-start ov)
2570 ,(overlay-end ov))
2571 'invisible (quote ,invis-prop))
2572 ov-set))))
2573 (overlays-in (point-min) (point-max)))
2574 ov-set)))))
2576 (defun org-export--delete-comments ()
2577 "Delete commented areas in the buffer.
2578 Commented areas are comments, comment blocks, commented trees and
2579 inlinetasks. Trailing blank lines after a comment or a comment
2580 block are preserved. Narrowing, if any, is ignored."
2581 (org-with-wide-buffer
2582 (goto-char (point-min))
2583 (let ((regexp (concat org-outline-regexp-bol ".*" org-comment-string
2584 "\\|"
2585 "^[ \t]*#\\(?: \\|$\\|\\+begin_comment\\)"))
2586 (case-fold-search t))
2587 (while (re-search-forward regexp nil t)
2588 (let ((e (org-element-at-point)))
2589 (cl-case (org-element-type e)
2590 ((comment comment-block)
2591 (delete-region (org-element-property :begin e)
2592 (progn (goto-char (org-element-property :end e))
2593 (skip-chars-backward " \r\t\n")
2594 (line-beginning-position 2))))
2595 ((headline inlinetask)
2596 (when (org-element-property :commentedp e)
2597 (delete-region (org-element-property :begin e)
2598 (org-element-property :end e))))))))))
2600 (defun org-export--prune-tree (data info)
2601 "Prune non exportable elements from DATA.
2602 DATA is the parse tree to traverse. INFO is the plist holding
2603 export info. Also set `:ignore-list' in INFO to a list of
2604 objects which should be ignored during export, but not removed
2605 from tree."
2606 (letrec ((ignore)
2607 ;; First find trees containing a select tag, if any.
2608 (selected (org-export--selected-trees data info))
2609 (walk-data
2610 (lambda (data)
2611 ;; Prune non-exportable elements and objects from tree.
2612 ;; As a special case, special rows and cells from tables
2613 ;; are stored in IGNORE, as they still need to be
2614 ;; accessed during export.
2615 (when data
2616 (let ((type (org-element-type data)))
2617 (if (org-export--skip-p data info selected)
2618 (if (memq type '(table-cell table-row)) (push data ignore)
2619 (org-element-extract-element data))
2620 (if (and (eq type 'headline)
2621 (eq (plist-get info :with-archived-trees)
2622 'headline)
2623 (org-element-property :archivedp data))
2624 ;; If headline is archived but tree below has
2625 ;; to be skipped, remove contents.
2626 (org-element-set-contents data)
2627 ;; Move into secondary string, if any.
2628 (let ((sec-prop
2629 (cdr (assq type
2630 org-element-secondary-value-alist))))
2631 (when sec-prop
2632 (mapc walk-data
2633 (org-element-property sec-prop data))))
2634 ;; Move into recursive objects/elements.
2635 (mapc walk-data (org-element-contents data)))))))))
2636 ;; If a select tag is active, also ignore the section before the
2637 ;; first headline, if any.
2638 (when selected
2639 (let ((first-element (car (org-element-contents data))))
2640 (when (eq (org-element-type first-element) 'section)
2641 (org-element-extract-element first-element))))
2642 ;; Prune tree and communication channel.
2643 (funcall walk-data data)
2644 (dolist (entry
2645 (append
2646 ;; Priority is given to back-end specific options.
2647 (org-export-get-all-options (plist-get info :back-end))
2648 org-export-options-alist))
2649 (when (eq (nth 4 entry) 'parse)
2650 (funcall walk-data (plist-get info (car entry)))))
2651 ;; Eventually set `:ignore-list'.
2652 (plist-put info :ignore-list ignore)))
2654 (defun org-export--remove-uninterpreted-data (data info)
2655 "Change uninterpreted elements back into Org syntax.
2656 DATA is the parse tree. INFO is a plist containing export
2657 options. Each uninterpreted element or object is changed back
2658 into a string. Contents, if any, are not modified. The parse
2659 tree is modified by side effect."
2660 (org-export--remove-uninterpreted-data-1 data info)
2661 (dolist (entry org-export-options-alist)
2662 (when (eq (nth 4 entry) 'parse)
2663 (let ((p (car entry)))
2664 (plist-put info
2666 (org-export--remove-uninterpreted-data-1
2667 (plist-get info p)
2668 info))))))
2670 (defun org-export--remove-uninterpreted-data-1 (data info)
2671 "Change uninterpreted elements back into Org syntax.
2672 DATA is a parse tree or a secondary string. INFO is a plist
2673 containing export options. It is modified by side effect and
2674 returned by the function."
2675 (org-element-map data
2676 '(entity bold italic latex-environment latex-fragment strike-through
2677 subscript superscript underline)
2678 (lambda (blob)
2679 (let ((new
2680 (cl-case (org-element-type blob)
2681 ;; ... entities...
2682 (entity
2683 (and (not (plist-get info :with-entities))
2684 (list (concat
2685 (org-export-expand blob nil)
2686 (make-string
2687 (or (org-element-property :post-blank blob) 0)
2688 ?\s)))))
2689 ;; ... emphasis...
2690 ((bold italic strike-through underline)
2691 (and (not (plist-get info :with-emphasize))
2692 (let ((marker (cl-case (org-element-type blob)
2693 (bold "*")
2694 (italic "/")
2695 (strike-through "+")
2696 (underline "_"))))
2697 (append
2698 (list marker)
2699 (org-element-contents blob)
2700 (list (concat
2701 marker
2702 (make-string
2703 (or (org-element-property :post-blank blob)
2705 ?\s)))))))
2706 ;; ... LaTeX environments and fragments...
2707 ((latex-environment latex-fragment)
2708 (and (eq (plist-get info :with-latex) 'verbatim)
2709 (list (org-export-expand blob nil))))
2710 ;; ... sub/superscripts...
2711 ((subscript superscript)
2712 (let ((sub/super-p (plist-get info :with-sub-superscript))
2713 (bracketp (org-element-property :use-brackets-p blob)))
2714 (and (or (not sub/super-p)
2715 (and (eq sub/super-p '{}) (not bracketp)))
2716 (append
2717 (list (concat
2718 (if (eq (org-element-type blob) 'subscript)
2720 "^")
2721 (and bracketp "{")))
2722 (org-element-contents blob)
2723 (list (concat
2724 (and bracketp "}")
2725 (and (org-element-property :post-blank blob)
2726 (make-string
2727 (org-element-property :post-blank blob)
2728 ?\s)))))))))))
2729 (when new
2730 ;; Splice NEW at BLOB location in parse tree.
2731 (dolist (e new (org-element-extract-element blob))
2732 (unless (string= e "") (org-element-insert-before e blob))))))
2733 info)
2734 ;; Return modified parse tree.
2735 data)
2737 (defun org-export--merge-external-footnote-definitions (tree)
2738 "Insert footnote definitions outside parsing scope in TREE.
2740 If there is a footnote section in TREE, definitions found are
2741 appended to it. If `org-footnote-section' is non-nil, a new
2742 footnote section containing all definitions is inserted in TREE.
2743 Otherwise, definitions are appended at the end of the section
2744 containing their first reference.
2746 Only definitions actually referred to within TREE, directly or
2747 not, are considered."
2748 (let* ((collect-labels
2749 (lambda (data)
2750 (org-element-map data 'footnote-reference
2751 (lambda (f)
2752 (and (eq (org-element-property :type f) 'standard)
2753 (org-element-property :label f))))))
2754 (referenced-labels (funcall collect-labels tree)))
2755 (when referenced-labels
2756 (let* ((definitions)
2757 (push-definition
2758 (lambda (datum)
2759 (cl-case (org-element-type datum)
2760 (footnote-definition
2761 (push (save-restriction
2762 (narrow-to-region (org-element-property :begin datum)
2763 (org-element-property :end datum))
2764 (org-element-map (org-element-parse-buffer)
2765 'footnote-definition #'identity nil t))
2766 definitions))
2767 (footnote-reference
2768 (let ((label (org-element-property :label datum))
2769 (cbeg (org-element-property :contents-begin datum)))
2770 (when (and label cbeg
2771 (eq (org-element-property :type datum) 'inline))
2772 (push
2773 (apply #'org-element-create
2774 'footnote-definition
2775 (list :label label :post-blank 1)
2776 (org-element-parse-secondary-string
2777 (buffer-substring
2778 cbeg (org-element-property :contents-end datum))
2779 (org-element-restriction 'footnote-reference)))
2780 definitions))))))))
2781 ;; Collect all out of scope definitions.
2782 (save-excursion
2783 (goto-char (point-min))
2784 (org-with-wide-buffer
2785 (while (re-search-backward org-footnote-re nil t)
2786 (funcall push-definition (org-element-context))))
2787 (goto-char (point-max))
2788 (org-with-wide-buffer
2789 (while (re-search-forward org-footnote-re nil t)
2790 (funcall push-definition (org-element-context)))))
2791 ;; Filter out definitions referenced neither in the original
2792 ;; tree nor in the external definitions.
2793 (let* ((directly-referenced
2794 (org-remove-if-not
2795 (lambda (d)
2796 (member (org-element-property :label d) referenced-labels))
2797 definitions))
2798 (all-labels
2799 (append (funcall collect-labels directly-referenced)
2800 referenced-labels)))
2801 (setq definitions
2802 (org-remove-if-not
2803 (lambda (d)
2804 (member (org-element-property :label d) all-labels))
2805 definitions)))
2806 ;; Install definitions in subtree.
2807 (cond
2808 ((null definitions))
2809 ;; If there is a footnote section, insert them here.
2810 ((let ((footnote-section
2811 (org-element-map tree 'headline
2812 (lambda (h)
2813 (and (org-element-property :footnote-section-p h) h))
2814 nil t)))
2815 (and footnote-section
2816 (apply #'org-element-adopt-elements (nreverse definitions)))))
2817 ;; If there should be a footnote section, create one containing
2818 ;; all the definitions at the end of the tree.
2819 (org-footnote-section
2820 (org-element-adopt-elements
2821 tree
2822 (org-element-create 'headline
2823 (list :footnote-section-p t
2824 :level 1
2825 :title org-footnote-section)
2826 (apply #'org-element-create
2827 'section
2829 (nreverse definitions)))))
2830 ;; Otherwise add each definition at the end of the section where
2831 ;; it is first referenced.
2833 (letrec ((seen)
2834 (insert-definitions
2835 (lambda (data)
2836 ;; Insert definitions in the same section as
2837 ;; their first reference in DATA.
2838 (org-element-map data 'footnote-reference
2839 (lambda (f)
2840 (when (eq (org-element-property :type f) 'standard)
2841 (let ((label (org-element-property :label f)))
2842 (unless (member label seen)
2843 (push label seen)
2844 (let ((definition
2845 (catch 'found
2846 (dolist (d definitions)
2847 (when (equal
2848 (org-element-property :label
2850 label)
2851 (setq definitions
2852 (delete d definitions))
2853 (throw 'found d))))))
2854 (when definition
2855 (org-element-adopt-elements
2856 (org-element-lineage f '(section))
2857 definition)
2858 (funcall insert-definitions
2859 definition)))))))))))
2860 (funcall insert-definitions tree))))))))
2862 ;;;###autoload
2863 (defun org-export-as
2864 (backend &optional subtreep visible-only body-only ext-plist)
2865 "Transcode current Org buffer into BACKEND code.
2867 BACKEND is either an export back-end, as returned by, e.g.,
2868 `org-export-create-backend', or a symbol referring to
2869 a registered back-end.
2871 If narrowing is active in the current buffer, only transcode its
2872 narrowed part.
2874 If a region is active, transcode that region.
2876 When optional argument SUBTREEP is non-nil, transcode the
2877 sub-tree at point, extracting information from the headline
2878 properties first.
2880 When optional argument VISIBLE-ONLY is non-nil, don't export
2881 contents of hidden elements.
2883 When optional argument BODY-ONLY is non-nil, only return body
2884 code, without surrounding template.
2886 Optional argument EXT-PLIST, when provided, is a property list
2887 with external parameters overriding Org default settings, but
2888 still inferior to file-local settings.
2890 Return code as a string."
2891 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
2892 (org-export-barf-if-invalid-backend backend)
2893 (save-excursion
2894 (save-restriction
2895 ;; Narrow buffer to an appropriate region or subtree for
2896 ;; parsing. If parsing subtree, be sure to remove main headline
2897 ;; too.
2898 (cond ((org-region-active-p)
2899 (narrow-to-region (region-beginning) (region-end)))
2900 (subtreep
2901 (org-narrow-to-subtree)
2902 (goto-char (point-min))
2903 (forward-line)
2904 (narrow-to-region (point) (point-max))))
2905 ;; Initialize communication channel with original buffer
2906 ;; attributes, unavailable in its copy.
2907 (let* ((org-export-current-backend (org-export-backend-name backend))
2908 (info (org-combine-plists
2909 (list :export-options
2910 (delq nil
2911 (list (and subtreep 'subtree)
2912 (and visible-only 'visible-only)
2913 (and body-only 'body-only))))
2914 (org-export--get-buffer-attributes)))
2915 (parsed-keywords
2916 (delq nil
2917 (mapcar (lambda (o) (and (eq (nth 4 o) 'parse) (nth 1 o)))
2918 (append (org-export-get-all-options backend)
2919 org-export-options-alist))))
2920 tree)
2921 ;; Update communication channel and get parse tree. Buffer
2922 ;; isn't parsed directly. Instead, all buffer modifications
2923 ;; and consequent parsing are undertaken in a temporary copy.
2924 (org-export-with-buffer-copy
2925 ;; Run first hook with current back-end's name as argument.
2926 (run-hook-with-args 'org-export-before-processing-hook
2927 (org-export-backend-name backend))
2928 ;; Include files, delete comments and expand macros.
2929 (org-export-expand-include-keyword)
2930 (org-export--delete-comments)
2931 (org-macro-initialize-templates)
2932 (org-macro-replace-all org-macro-templates nil parsed-keywords)
2933 ;; Refresh buffer properties and radio targets after
2934 ;; potentially invasive previous changes. Likewise, do it
2935 ;; again after executing Babel code.
2936 (org-set-regexps-and-options)
2937 (org-update-radio-target-regexp)
2938 (org-export-execute-babel-code)
2939 (org-set-regexps-and-options)
2940 (org-update-radio-target-regexp)
2941 ;; Run last hook with current back-end's name as argument.
2942 ;; Update buffer properties and radio targets one last time
2943 ;; before parsing.
2944 (goto-char (point-min))
2945 (save-excursion
2946 (run-hook-with-args 'org-export-before-parsing-hook
2947 (org-export-backend-name backend)))
2948 (org-set-regexps-and-options)
2949 (org-update-radio-target-regexp)
2950 ;; Update communication channel with environment. Also
2951 ;; install user's and developer's filters.
2952 (setq info
2953 (org-export-install-filters
2954 (org-combine-plists
2955 info (org-export-get-environment backend subtreep ext-plist))))
2956 ;; Call options filters and update export options. We do not
2957 ;; use `org-export-filter-apply-functions' here since the
2958 ;; arity of such filters is different.
2959 (let ((backend-name (org-export-backend-name backend)))
2960 (dolist (filter (plist-get info :filter-options))
2961 (let ((result (funcall filter info backend-name)))
2962 (when result (setq info result)))))
2963 ;; Expand export-specific set of macros: {{{author}}},
2964 ;; {{{date(FORMAT)}}}, {{{email}}} and {{{title}}}. It must
2965 ;; be done once regular macros have been expanded, since
2966 ;; parsed keywords may contain one of them.
2967 (org-macro-replace-all
2968 (list
2969 (cons "author" (org-element-interpret-data (plist-get info :author)))
2970 (cons "date"
2971 (let* ((date (plist-get info :date))
2972 (value (or (org-element-interpret-data date) "")))
2973 (if (and (consp date)
2974 (not (cdr date))
2975 (eq (org-element-type (car date)) 'timestamp))
2976 (format "(eval (if (org-string-nw-p \"$1\") %s %S))"
2977 (format "(org-timestamp-format '%S \"$1\")"
2978 (org-element-copy (car date)))
2979 value)
2980 value)))
2981 (cons "email" (org-element-interpret-data (plist-get info :email)))
2982 (cons "title" (org-element-interpret-data (plist-get info :title)))
2983 (cons "results" "$1"))
2984 'finalize
2985 parsed-keywords)
2986 ;; Parse buffer.
2987 (setq tree (org-element-parse-buffer nil visible-only))
2988 ;; Merge footnote definitions outside scope into parse tree.
2989 (org-export--merge-external-footnote-definitions tree)
2990 ;; Prune tree from non-exported elements and transform
2991 ;; uninterpreted elements or objects in both parse tree and
2992 ;; communication channel.
2993 (org-export--prune-tree tree info)
2994 (org-export--remove-uninterpreted-data tree info)
2995 ;; Call parse tree filters.
2996 (setq tree
2997 (org-export-filter-apply-functions
2998 (plist-get info :filter-parse-tree) tree info))
2999 ;; Now tree is complete, compute its properties and add them
3000 ;; to communication channel.
3001 (setq info
3002 (org-combine-plists
3003 info (org-export-collect-tree-properties tree info)))
3004 ;; Eventually transcode TREE. Wrap the resulting string into
3005 ;; a template.
3006 (let* ((body (org-element-normalize-string
3007 (or (org-export-data tree info) "")))
3008 (inner-template (cdr (assq 'inner-template
3009 (plist-get info :translate-alist))))
3010 (full-body (org-export-filter-apply-functions
3011 (plist-get info :filter-body)
3012 (if (not (functionp inner-template)) body
3013 (funcall inner-template body info))
3014 info))
3015 (template (cdr (assq 'template
3016 (plist-get info :translate-alist)))))
3017 ;; Remove all text properties since they cannot be
3018 ;; retrieved from an external process. Finally call
3019 ;; final-output filter and return result.
3020 (org-no-properties
3021 (org-export-filter-apply-functions
3022 (plist-get info :filter-final-output)
3023 (if (or (not (functionp template)) body-only) full-body
3024 (funcall template full-body info))
3025 info))))))))
3027 ;;;###autoload
3028 (defun org-export-string-as (string backend &optional body-only ext-plist)
3029 "Transcode STRING into BACKEND code.
3031 BACKEND is either an export back-end, as returned by, e.g.,
3032 `org-export-create-backend', or a symbol referring to
3033 a registered back-end.
3035 When optional argument BODY-ONLY is non-nil, only return body
3036 code, without preamble nor postamble.
3038 Optional argument EXT-PLIST, when provided, is a property list
3039 with external parameters overriding Org default settings, but
3040 still inferior to file-local settings.
3042 Return code as a string."
3043 (with-temp-buffer
3044 (insert string)
3045 (let ((org-inhibit-startup t)) (org-mode))
3046 (org-export-as backend nil nil body-only ext-plist)))
3048 ;;;###autoload
3049 (defun org-export-replace-region-by (backend)
3050 "Replace the active region by its export to BACKEND.
3051 BACKEND is either an export back-end, as returned by, e.g.,
3052 `org-export-create-backend', or a symbol referring to
3053 a registered back-end."
3054 (unless (org-region-active-p) (user-error "No active region to replace"))
3055 (insert
3056 (org-export-string-as
3057 (delete-and-extract-region (region-beginning) (region-end)) backend t)))
3059 ;;;###autoload
3060 (defun org-export-insert-default-template (&optional backend subtreep)
3061 "Insert all export keywords with default values at beginning of line.
3063 BACKEND is a symbol referring to the name of a registered export
3064 back-end, for which specific export options should be added to
3065 the template, or `default' for default template. When it is nil,
3066 the user will be prompted for a category.
3068 If SUBTREEP is non-nil, export configuration will be set up
3069 locally for the subtree through node properties."
3070 (interactive)
3071 (unless (derived-mode-p 'org-mode) (user-error "Not in an Org mode buffer"))
3072 (when (and subtreep (org-before-first-heading-p))
3073 (user-error "No subtree to set export options for"))
3074 (let ((node (and subtreep (save-excursion (org-back-to-heading t) (point))))
3075 (backend
3076 (or backend
3077 (intern
3078 (org-completing-read
3079 "Options category: "
3080 (cons "default"
3081 (mapcar (lambda (b)
3082 (symbol-name (org-export-backend-name b)))
3083 org-export-registered-backends))
3084 nil t))))
3085 options keywords)
3086 ;; Populate OPTIONS and KEYWORDS.
3087 (dolist (entry (cond ((eq backend 'default) org-export-options-alist)
3088 ((org-export-backend-p backend)
3089 (org-export-backend-options backend))
3090 (t (org-export-backend-options
3091 (org-export-get-backend backend)))))
3092 (let ((keyword (nth 1 entry))
3093 (option (nth 2 entry)))
3094 (cond
3095 (keyword (unless (assoc keyword keywords)
3096 (let ((value
3097 (if (eq (nth 4 entry) 'split)
3098 (mapconcat #'identity (eval (nth 3 entry)) " ")
3099 (eval (nth 3 entry)))))
3100 (push (cons keyword value) keywords))))
3101 (option (unless (assoc option options)
3102 (push (cons option (eval (nth 3 entry))) options))))))
3103 ;; Move to an appropriate location in order to insert options.
3104 (unless subtreep (beginning-of-line))
3105 ;; First (multiple) OPTIONS lines. Never go past fill-column.
3106 (when options
3107 (let ((items
3108 (mapcar
3109 #'(lambda (opt) (format "%s:%S" (car opt) (cdr opt)))
3110 (sort options (lambda (k1 k2) (string< (car k1) (car k2)))))))
3111 (if subtreep
3112 (org-entry-put
3113 node "EXPORT_OPTIONS" (mapconcat 'identity items " "))
3114 (while items
3115 (insert "#+OPTIONS:")
3116 (let ((width 10))
3117 (while (and items
3118 (< (+ width (length (car items)) 1) fill-column))
3119 (let ((item (pop items)))
3120 (insert " " item)
3121 (cl-incf width (1+ (length item))))))
3122 (insert "\n")))))
3123 ;; Then the rest of keywords, in the order specified in either
3124 ;; `org-export-options-alist' or respective export back-ends.
3125 (dolist (key (nreverse keywords))
3126 (let ((val (cond ((equal (car key) "DATE")
3127 (or (cdr key)
3128 (with-temp-buffer
3129 (org-insert-time-stamp (current-time)))))
3130 ((equal (car key) "TITLE")
3131 (or (let ((visited-file
3132 (buffer-file-name (buffer-base-buffer))))
3133 (and visited-file
3134 (file-name-sans-extension
3135 (file-name-nondirectory visited-file))))
3136 (buffer-name (buffer-base-buffer))))
3137 (t (cdr key)))))
3138 (if subtreep (org-entry-put node (concat "EXPORT_" (car key)) val)
3139 (insert
3140 (format "#+%s:%s\n"
3141 (car key)
3142 (if (org-string-nw-p val) (format " %s" val) ""))))))))
3144 (defun org-export-expand-include-keyword (&optional included dir footnotes)
3145 "Expand every include keyword in buffer.
3146 Optional argument INCLUDED is a list of included file names along
3147 with their line restriction, when appropriate. It is used to
3148 avoid infinite recursion. Optional argument DIR is the current
3149 working directory. It is used to properly resolve relative
3150 paths. Optional argument FOOTNOTES is a hash-table used for
3151 storing and resolving footnotes. It is created automatically."
3152 (let ((case-fold-search t)
3153 (file-prefix (make-hash-table :test #'equal))
3154 (current-prefix 0)
3155 (footnotes (or footnotes (make-hash-table :test #'equal)))
3156 (include-re "^[ \t]*#\\+INCLUDE:"))
3157 ;; If :minlevel is not set the text-property
3158 ;; `:org-include-induced-level' will be used to determine the
3159 ;; relative level when expanding INCLUDE.
3160 ;; Only affects included Org documents.
3161 (goto-char (point-min))
3162 (while (re-search-forward include-re nil t)
3163 (put-text-property (line-beginning-position) (line-end-position)
3164 :org-include-induced-level
3165 (1+ (org-reduced-level (or (org-current-level) 0)))))
3166 ;; Expand INCLUDE keywords.
3167 (goto-char (point-min))
3168 (while (re-search-forward include-re nil t)
3169 (let ((element (save-match-data (org-element-at-point))))
3170 (when (eq (org-element-type element) 'keyword)
3171 (beginning-of-line)
3172 ;; Extract arguments from keyword's value.
3173 (let* ((value (org-element-property :value element))
3174 (ind (org-get-indentation))
3175 location
3176 (file
3177 (and (string-match
3178 "^\\(\".+?\"\\|\\S-+\\)\\(?:\\s-+\\|$\\)" value)
3179 (prog1
3180 (save-match-data
3181 (let ((matched (match-string 1 value)))
3182 (when (string-match "\\(::\\(.*?\\)\\)\"?\\'"
3183 matched)
3184 (setq location (match-string 2 matched))
3185 (setq matched
3186 (replace-match "" nil nil matched 1)))
3187 (expand-file-name
3188 (org-remove-double-quotes
3189 matched)
3190 dir)))
3191 (setq value (replace-match "" nil nil value)))))
3192 (only-contents
3193 (and (string-match ":only-contents *\\([^: \r\t\n]\\S-*\\)?"
3194 value)
3195 (prog1 (org-not-nil (match-string 1 value))
3196 (setq value (replace-match "" nil nil value)))))
3197 (lines
3198 (and (string-match
3199 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\""
3200 value)
3201 (prog1 (match-string 1 value)
3202 (setq value (replace-match "" nil nil value)))))
3203 (env (cond ((string-match "\\<example\\>" value)
3204 'literal)
3205 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
3206 'literal)))
3207 ;; Minimal level of included file defaults to the child
3208 ;; level of the current headline, if any, or one. It
3209 ;; only applies is the file is meant to be included as
3210 ;; an Org one.
3211 (minlevel
3212 (and (not env)
3213 (if (string-match ":minlevel +\\([0-9]+\\)" value)
3214 (prog1 (string-to-number (match-string 1 value))
3215 (setq value (replace-match "" nil nil value)))
3216 (get-text-property (point)
3217 :org-include-induced-level))))
3218 (src-args (and (eq env 'literal)
3219 (match-string 1 value)))
3220 (block (and (string-match "\\<\\(\\S-+\\)\\>" value)
3221 (match-string 1 value))))
3222 ;; Remove keyword.
3223 (delete-region (point) (progn (forward-line) (point)))
3224 (cond
3225 ((not file) nil)
3226 ((not (file-readable-p file))
3227 (error "Cannot include file %s" file))
3228 ;; Check if files has already been parsed. Look after
3229 ;; inclusion lines too, as different parts of the same file
3230 ;; can be included too.
3231 ((member (list file lines) included)
3232 (error "Recursive file inclusion: %s" file))
3234 (cond
3235 ((eq env 'literal)
3236 (insert
3237 (let ((ind-str (make-string ind ? ))
3238 (arg-str (if (stringp src-args)
3239 (format " %s" src-args)
3240 ""))
3241 (contents
3242 (org-escape-code-in-string
3243 (org-export--prepare-file-contents file lines))))
3244 (format "%s#+BEGIN_%s%s\n%s%s#+END_%s\n"
3245 ind-str block arg-str contents ind-str block))))
3246 ((stringp block)
3247 (insert
3248 (let ((ind-str (make-string ind ? ))
3249 (contents
3250 (org-export--prepare-file-contents file lines)))
3251 (format "%s#+BEGIN_%s\n%s%s#+END_%s\n"
3252 ind-str block contents ind-str block))))
3254 (insert
3255 (with-temp-buffer
3256 (let ((org-inhibit-startup t)
3257 (lines
3258 (if location
3259 (org-export--inclusion-absolute-lines
3260 file location only-contents lines)
3261 lines)))
3262 (org-mode)
3263 (insert
3264 (org-export--prepare-file-contents
3265 file lines ind minlevel
3266 (or (gethash file file-prefix)
3267 (puthash file (cl-incf current-prefix) file-prefix))
3268 footnotes)))
3269 (org-export-expand-include-keyword
3270 (cons (list file lines) included)
3271 (file-name-directory file)
3272 footnotes)
3273 (buffer-string)))))
3274 ;; Expand footnotes after all files have been included.
3275 ;; Footnotes are stored at end of buffer.
3276 (unless included
3277 (org-with-wide-buffer
3278 (goto-char (point-max))
3279 (maphash (lambda (k v) (insert (format "\n[%s] %s\n" k v)))
3280 footnotes)))))))))))
3282 (defun org-export--inclusion-absolute-lines (file location only-contents lines)
3283 "Resolve absolute lines for an included file with file-link.
3285 FILE is string file-name of the file to include. LOCATION is a
3286 string name within FILE to be included (located via
3287 `org-link-search'). If ONLY-CONTENTS is non-nil only the
3288 contents of the named element will be included, as determined
3289 Org-Element. If LINES is non-nil only those lines are included.
3291 Return a string of lines to be included in the format expected by
3292 `org-export--prepare-file-contents'."
3293 (with-temp-buffer
3294 (insert-file-contents file)
3295 (unless (eq major-mode 'org-mode)
3296 (let ((org-inhibit-startup t)) (org-mode)))
3297 (condition-case err
3298 ;; Enforce consistent search.
3299 (let ((org-link-search-must-match-exact-headline nil))
3300 (org-link-search location))
3301 (error
3302 (error "%s for %s::%s" (error-message-string err) file location)))
3303 (let* ((element (org-element-at-point))
3304 (contents-begin
3305 (and only-contents (org-element-property :contents-begin element))))
3306 (narrow-to-region
3307 (or contents-begin (org-element-property :begin element))
3308 (org-element-property (if contents-begin :contents-end :end) element))
3309 (when (and only-contents
3310 (memq (org-element-type element) '(headline inlinetask)))
3311 ;; Skip planning line and property-drawer.
3312 (goto-char (point-min))
3313 (when (org-looking-at-p org-planning-line-re) (forward-line))
3314 (when (looking-at org-property-drawer-re) (goto-char (match-end 0)))
3315 (unless (bolp) (forward-line))
3316 (narrow-to-region (point) (point-max))))
3317 (when lines
3318 (org-skip-whitespace)
3319 (beginning-of-line)
3320 (let* ((lines (split-string lines "-"))
3321 (lbeg (string-to-number (car lines)))
3322 (lend (string-to-number (cadr lines)))
3323 (beg (if (zerop lbeg) (point-min)
3324 (goto-char (point-min))
3325 (forward-line (1- lbeg))
3326 (point)))
3327 (end (if (zerop lend) (point-max)
3328 (goto-char beg)
3329 (forward-line (1- lend))
3330 (point))))
3331 (narrow-to-region beg end)))
3332 (let ((end (point-max)))
3333 (goto-char (point-min))
3334 (widen)
3335 (let ((start-line (line-number-at-pos)))
3336 (format "%d-%d"
3337 start-line
3338 (save-excursion
3339 (+ start-line
3340 (let ((counter 0))
3341 (while (< (point) end) (cl-incf counter) (forward-line))
3342 counter))))))))
3344 (defun org-export--update-footnote-label (ref-begin digit-label id)
3345 "Prefix footnote-label at point REF-BEGIN in buffer with ID.
3347 REF-BEGIN corresponds to the property `:begin' of objects of type
3348 footnote-definition and footnote-reference.
3350 If DIGIT-LABEL is non-nil the label is assumed to be of the form
3351 \[N] where N is one or more numbers.
3353 Return the new label."
3354 (goto-char (1+ ref-begin))
3355 (buffer-substring (point)
3356 (progn
3357 (if digit-label (insert (format "fn:%d-" id))
3358 (forward-char 3)
3359 (insert (format "%d-" id)))
3360 (1- (search-forward "]")))))
3362 (defun org-export--prepare-file-contents
3363 (file &optional lines ind minlevel id footnotes)
3364 "Prepare contents of FILE for inclusion and return it as a string.
3366 When optional argument LINES is a string specifying a range of
3367 lines, include only those lines.
3369 Optional argument IND, when non-nil, is an integer specifying the
3370 global indentation of returned contents. Since its purpose is to
3371 allow an included file to stay in the same environment it was
3372 created \(i.e. a list item), it doesn't apply past the first
3373 headline encountered.
3375 Optional argument MINLEVEL, when non-nil, is an integer
3376 specifying the level that any top-level headline in the included
3377 file should have.
3378 Optional argument ID is an integer that will be inserted before
3379 each footnote definition and reference if FILE is an Org file.
3380 This is useful to avoid conflicts when more than one Org file
3381 with footnotes is included in a document.
3383 Optional argument FOOTNOTES is a hash-table to store footnotes in
3384 the included document.
3386 (with-temp-buffer
3387 (insert-file-contents file)
3388 (when lines
3389 (let* ((lines (split-string lines "-"))
3390 (lbeg (string-to-number (car lines)))
3391 (lend (string-to-number (cadr lines)))
3392 (beg (if (zerop lbeg) (point-min)
3393 (goto-char (point-min))
3394 (forward-line (1- lbeg))
3395 (point)))
3396 (end (if (zerop lend) (point-max)
3397 (goto-char (point-min))
3398 (forward-line (1- lend))
3399 (point))))
3400 (narrow-to-region beg end)))
3401 ;; Remove blank lines at beginning and end of contents. The logic
3402 ;; behind that removal is that blank lines around include keyword
3403 ;; override blank lines in included file.
3404 (goto-char (point-min))
3405 (org-skip-whitespace)
3406 (beginning-of-line)
3407 (delete-region (point-min) (point))
3408 (goto-char (point-max))
3409 (skip-chars-backward " \r\t\n")
3410 (forward-line)
3411 (delete-region (point) (point-max))
3412 ;; If IND is set, preserve indentation of include keyword until
3413 ;; the first headline encountered.
3414 (when ind
3415 (unless (eq major-mode 'org-mode)
3416 (let ((org-inhibit-startup t)) (org-mode)))
3417 (goto-char (point-min))
3418 (let ((ind-str (make-string ind ? )))
3419 (while (not (or (eobp) (looking-at org-outline-regexp-bol)))
3420 ;; Do not move footnote definitions out of column 0.
3421 (unless (and (looking-at org-footnote-definition-re)
3422 (eq (org-element-type (org-element-at-point))
3423 'footnote-definition))
3424 (insert ind-str))
3425 (forward-line))))
3426 ;; When MINLEVEL is specified, compute minimal level for headlines
3427 ;; in the file (CUR-MIN), and remove stars to each headline so
3428 ;; that headlines with minimal level have a level of MINLEVEL.
3429 (when minlevel
3430 (unless (eq major-mode 'org-mode)
3431 (let ((org-inhibit-startup t)) (org-mode)))
3432 (org-with-limited-levels
3433 (let ((levels (org-map-entries
3434 (lambda () (org-reduced-level (org-current-level))))))
3435 (when levels
3436 (let ((offset (- minlevel (apply 'min levels))))
3437 (unless (zerop offset)
3438 (when org-odd-levels-only (setq offset (* offset 2)))
3439 ;; Only change stars, don't bother moving whole
3440 ;; sections.
3441 (org-map-entries
3442 (lambda () (if (< offset 0) (delete-char (abs offset))
3443 (insert (make-string offset ?*)))))))))))
3444 ;; Append ID to all footnote references and definitions, so they
3445 ;; become file specific and cannot collide with footnotes in other
3446 ;; included files. Further, collect relevant footnotes outside of
3447 ;; LINES.
3448 (when id
3449 (let ((marker-min (point-min-marker))
3450 (marker-max (point-max-marker)))
3451 (goto-char (point-min))
3452 (while (re-search-forward org-footnote-re nil t)
3453 (let ((reference (org-element-context)))
3454 (when (eq (org-element-type reference) 'footnote-reference)
3455 (let* ((label (org-element-property :label reference))
3456 (digit-label
3457 (and label (org-string-match-p "\\`[0-9]+\\'" label))))
3458 ;; Update the footnote-reference at point and collect
3459 ;; the new label, which is only used for footnotes
3460 ;; outsides LINES.
3461 (when label
3462 ;; If label is akin to [1] convert it to [fn:ID-1].
3463 ;; Otherwise add "ID-" after "fn:".
3464 (let ((new-label (org-export--update-footnote-label
3465 (org-element-property :begin reference)
3466 digit-label id)))
3467 (unless (eq (org-element-property :type reference) 'inline)
3468 (org-with-wide-buffer
3469 (let* ((definition (org-footnote-get-definition label))
3470 (beginning (nth 1 definition)))
3471 (unless definition
3472 (error
3473 "Definition not found for footnote %s in file %s"
3474 label file))
3475 (if (or (< beginning marker-min)
3476 (> beginning marker-max))
3477 ;; Store since footnote-definition is
3478 ;; outside of LINES.
3479 (puthash new-label
3480 (org-element-normalize-string
3481 (nth 3 definition))
3482 footnotes)
3483 ;; Update label of definition since it is
3484 ;; included directly.
3485 (org-export--update-footnote-label
3486 beginning digit-label id)))))))))))
3487 (set-marker marker-min nil)
3488 (set-marker marker-max nil)))
3489 (org-element-normalize-string (buffer-string))))
3491 (defun org-export-execute-babel-code ()
3492 "Execute every Babel code in the visible part of current buffer."
3493 ;; Get a pristine copy of current buffer so Babel references can be
3494 ;; properly resolved.
3495 (let ((reference (org-export-copy-buffer)))
3496 (unwind-protect (org-babel-exp-process-buffer reference)
3497 (kill-buffer reference))))
3499 (defun org-export--copy-to-kill-ring-p ()
3500 "Return a non-nil value when output should be added to the kill ring.
3501 See also `org-export-copy-to-kill-ring'."
3502 (if (eq org-export-copy-to-kill-ring 'if-interactive)
3503 (not (or executing-kbd-macro noninteractive))
3504 (eq org-export-copy-to-kill-ring t)))
3508 ;;; Tools For Back-Ends
3510 ;; A whole set of tools is available to help build new exporters. Any
3511 ;; function general enough to have its use across many back-ends
3512 ;; should be added here.
3514 ;;;; For Affiliated Keywords
3516 ;; `org-export-read-attribute' reads a property from a given element
3517 ;; as a plist. It can be used to normalize affiliated keywords'
3518 ;; syntax.
3520 ;; Since captions can span over multiple lines and accept dual values,
3521 ;; their internal representation is a bit tricky. Therefore,
3522 ;; `org-export-get-caption' transparently returns a given element's
3523 ;; caption as a secondary string.
3525 (defun org-export-read-attribute (attribute element &optional property)
3526 "Turn ATTRIBUTE property from ELEMENT into a plist.
3528 When optional argument PROPERTY is non-nil, return the value of
3529 that property within attributes.
3531 This function assumes attributes are defined as \":keyword
3532 value\" pairs. It is appropriate for `:attr_html' like
3533 properties.
3535 All values will become strings except the empty string and
3536 \"nil\", which will become nil. Also, values containing only
3537 double quotes will be read as-is, which means that \"\" value
3538 will become the empty string."
3539 (let* ((prepare-value
3540 (lambda (str)
3541 (save-match-data
3542 (cond ((member str '(nil "" "nil")) nil)
3543 ((string-match "^\"\\(\"+\\)?\"$" str)
3544 (or (match-string 1 str) ""))
3545 (t str)))))
3546 (attributes
3547 (let ((value (org-element-property attribute element)))
3548 (when value
3549 (let ((s (mapconcat 'identity value " ")) result)
3550 (while (string-match
3551 "\\(?:^\\|[ \t]+\\)\\(:[-a-zA-Z0-9_]+\\)\\([ \t]+\\|$\\)"
3553 (let ((value (substring s 0 (match-beginning 0))))
3554 (push (funcall prepare-value value) result))
3555 (push (intern (match-string 1 s)) result)
3556 (setq s (substring s (match-end 0))))
3557 ;; Ignore any string before first property with `cdr'.
3558 (cdr (nreverse (cons (funcall prepare-value s) result))))))))
3559 (if property (plist-get attributes property) attributes)))
3561 (defun org-export-get-caption (element &optional shortp)
3562 "Return caption from ELEMENT as a secondary string.
3564 When optional argument SHORTP is non-nil, return short caption,
3565 as a secondary string, instead.
3567 Caption lines are separated by a white space."
3568 (let ((full-caption (org-element-property :caption element)) caption)
3569 (dolist (line full-caption (cdr caption))
3570 (let ((cap (funcall (if shortp 'cdr 'car) line)))
3571 (when cap
3572 (setq caption (nconc (list " ") (copy-sequence cap) caption)))))))
3575 ;;;; For Derived Back-ends
3577 ;; `org-export-with-backend' is a function allowing to locally use
3578 ;; another back-end to transcode some object or element. In a derived
3579 ;; back-end, it may be used as a fall-back function once all specific
3580 ;; cases have been treated.
3582 (defun org-export-with-backend (backend data &optional contents info)
3583 "Call a transcoder from BACKEND on DATA.
3584 BACKEND is an export back-end, as returned by, e.g.,
3585 `org-export-create-backend', or a symbol referring to
3586 a registered back-end. DATA is an Org element, object, secondary
3587 string or string. CONTENTS, when non-nil, is the transcoded
3588 contents of DATA element, as a string. INFO, when non-nil, is
3589 the communication channel used for export, as a plist."
3590 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
3591 (org-export-barf-if-invalid-backend backend)
3592 (let ((type (org-element-type data)))
3593 (if (memq type '(nil org-data)) (error "No foreign transcoder available")
3594 (let* ((all-transcoders (org-export-get-all-transcoders backend))
3595 (transcoder (cdr (assq type all-transcoders))))
3596 (if (not (functionp transcoder))
3597 (error "No foreign transcoder available")
3598 (funcall
3599 transcoder data contents
3600 (org-combine-plists
3601 info (list
3602 :back-end backend
3603 :translate-alist all-transcoders
3604 :exported-data (make-hash-table :test #'eq :size 401)))))))))
3607 ;;;; For Export Snippets
3609 ;; Every export snippet is transmitted to the back-end. Though, the
3610 ;; latter will only retain one type of export-snippet, ignoring
3611 ;; others, based on the former's target back-end. The function
3612 ;; `org-export-snippet-backend' returns that back-end for a given
3613 ;; export-snippet.
3615 (defun org-export-snippet-backend (export-snippet)
3616 "Return EXPORT-SNIPPET targeted back-end as a symbol.
3617 Translation, with `org-export-snippet-translation-alist', is
3618 applied."
3619 (let ((back-end (org-element-property :back-end export-snippet)))
3620 (intern
3621 (or (cdr (assoc back-end org-export-snippet-translation-alist))
3622 back-end))))
3625 ;;;; For Footnotes
3627 ;; `org-export-collect-footnote-definitions' is a tool to list
3628 ;; actually used footnotes definitions in the whole parse tree, or in
3629 ;; a headline, in order to add footnote listings throughout the
3630 ;; transcoded data.
3632 ;; `org-export-footnote-first-reference-p' is a predicate used by some
3633 ;; back-ends, when they need to attach the footnote definition only to
3634 ;; the first occurrence of the corresponding label.
3636 ;; `org-export-get-footnote-definition' and
3637 ;; `org-export-get-footnote-number' provide easier access to
3638 ;; additional information relative to a footnote reference.
3640 (defun org-export-get-footnote-definition (footnote-reference info)
3641 "Return definition of FOOTNOTE-REFERENCE as parsed data.
3642 INFO is the plist used as a communication channel. If no such
3643 definition can be found, raise an error."
3644 (let ((label (org-element-property :label footnote-reference)))
3645 (if (not label) (org-element-contents footnote-reference)
3646 (let ((cache (or (plist-get info :footnote-definition-cache)
3647 (let ((hash (make-hash-table :test #'equal)))
3648 (plist-put info :footnote-definition-cache hash)
3649 hash))))
3650 (or (gethash label cache)
3651 (puthash label
3652 (org-element-map (plist-get info :parse-tree)
3653 '(footnote-definition footnote-reference)
3654 (lambda (f)
3655 (and (equal (org-element-property :label f) label)
3656 (org-element-contents f)))
3657 info t)
3658 cache)
3659 (error "Definition not found for footnote %s" label))))))
3661 (defun org-export--footnote-reference-map
3662 (function data info &optional body-first)
3663 "Apply FUNCTION on every footnote reference in DATA.
3664 INFO is a plist containing export state. By default, as soon as
3665 a new footnote reference is encountered, FUNCTION is called onto
3666 its definition. However, if BODY-FIRST is non-nil, this step is
3667 delayed until the end of the process."
3668 (letrec ((definitions)
3669 (seen-refs)
3670 (search-ref
3671 (lambda (data delayp)
3672 ;; Search footnote references through DATA, filling
3673 ;; SEEN-REFS along the way. When DELAYP is non-nil,
3674 ;; store footnote definitions so they can be entered
3675 ;; later.
3676 (org-element-map data 'footnote-reference
3677 (lambda (f)
3678 (funcall function f)
3679 (let ((--label (org-element-property :label f)))
3680 (unless (and --label (member --label seen-refs))
3681 (when --label (push --label seen-refs))
3682 ;; Search for subsequent references in footnote
3683 ;; definition so numbering follows reading
3684 ;; logic, unless DELAYP in non-nil.
3685 (cond
3686 (delayp
3687 (push (org-export-get-footnote-definition f info)
3688 definitions))
3689 ;; Do not force entering inline definitions,
3690 ;; since `org-element-map' already traverses
3691 ;; them at the right time.
3692 ((eq (org-element-property :type f) 'inline))
3693 (t (funcall search-ref
3694 (org-export-get-footnote-definition f info)
3695 nil))))))
3696 info nil
3697 ;; Don't enter footnote definitions since it will
3698 ;; happen when their first reference is found.
3699 ;; Moreover, if DELAYP is non-nil, make sure we
3700 ;; postpone entering definitions of inline references.
3701 (if delayp '(footnote-definition footnote-reference)
3702 'footnote-definition)))))
3703 (funcall search-ref data body-first)
3704 (funcall search-ref (nreverse definitions) nil)))
3706 (defun org-export-collect-footnote-definitions (info &optional data body-first)
3707 "Return an alist between footnote numbers, labels and definitions.
3709 INFO is the current export state, as a plist.
3711 Definitions are collected throughout the whole parse tree, or
3712 DATA when non-nil.
3714 Sorting is done by order of references. As soon as a new
3715 reference is encountered, other references are searched within
3716 its definition. However, if BODY-FIRST is non-nil, this step is
3717 delayed after the whole tree is checked. This alters results
3718 when references are found in footnote definitions.
3720 Definitions either appear as Org data or as a secondary string
3721 for inlined footnotes. Unreferenced definitions are ignored."
3722 (let ((n 0) labels alist)
3723 (org-export--footnote-reference-map
3724 (lambda (f)
3725 ;; Collect footnote number, label and definition.
3726 (let ((l (org-element-property :label f)))
3727 (unless (and l (member l labels))
3728 (cl-incf n)
3729 (push (list n l (org-export-get-footnote-definition f info)) alist))
3730 (when l (push l labels))))
3731 (or data (plist-get info :parse-tree)) info body-first)
3732 (nreverse alist)))
3734 (defun org-export-footnote-first-reference-p
3735 (footnote-reference info &optional data body-first)
3736 "Non-nil when a footnote reference is the first one for its label.
3738 FOOTNOTE-REFERENCE is the footnote reference being considered.
3739 INFO is a plist containing current export state.
3741 Search is done throughout the whole parse tree, or DATA when
3742 non-nil.
3744 By default, as soon as a new footnote reference is encountered,
3745 other references are searched within its definition. However, if
3746 BODY-FIRST is non-nil, this step is delayed after the whole tree
3747 is checked. This alters results when references are found in
3748 footnote definitions."
3749 (let ((label (org-element-property :label footnote-reference)))
3750 ;; Anonymous footnotes are always a first reference.
3751 (or (not label)
3752 (catch 'exit
3753 (org-export--footnote-reference-map
3754 (lambda (f)
3755 (let ((l (org-element-property :label f)))
3756 (when (and l label (string= label l))
3757 (throw 'exit (eq footnote-reference f)))))
3758 (or data (plist-get info :parse-tree)) info body-first)))))
3760 (defun org-export-get-footnote-number (footnote info &optional data body-first)
3761 "Return number associated to a footnote.
3763 FOOTNOTE is either a footnote reference or a footnote definition.
3764 INFO is the plist containing export state.
3766 Number is unique throughout the whole parse tree, or DATA, when
3767 non-nil.
3769 By default, as soon as a new footnote reference is encountered,
3770 counting process moves into its definition. However, if
3771 BODY-FIRST is non-nil, this step is delayed until the end of the
3772 process, leading to a different order when footnotes are nested."
3773 (let ((count 0)
3774 (seen)
3775 (label (org-element-property :label footnote)))
3776 (catch 'exit
3777 (org-export--footnote-reference-map
3778 (lambda (f)
3779 (let ((l (org-element-property :label f)))
3780 (cond
3781 ;; Anonymous footnote match: return number.
3782 ((and (not l) (not label) (eq footnote f)) (throw 'exit (1+ count)))
3783 ;; Labels match: return number.
3784 ((and label l (string= label l)) (throw 'exit (1+ count)))
3785 ;; Otherwise store label and increase counter if label
3786 ;; wasn't encountered yet.
3787 ((not l) (cl-incf count))
3788 ((not (member l seen)) (push l seen) (cl-incf count)))))
3789 (or data (plist-get info :parse-tree)) info body-first))))
3792 ;;;; For Headlines
3794 ;; `org-export-get-relative-level' is a shortcut to get headline
3795 ;; level, relatively to the lower headline level in the parsed tree.
3797 ;; `org-export-get-headline-number' returns the section number of an
3798 ;; headline, while `org-export-number-to-roman' allows to convert it
3799 ;; to roman numbers. With an optional argument,
3800 ;; `org-export-get-headline-number' returns a number to unnumbered
3801 ;; headlines (used for internal id).
3803 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
3804 ;; `org-export-last-sibling-p' are three useful predicates when it
3805 ;; comes to fulfill the `:headline-levels' property.
3807 ;; `org-export-get-tags', `org-export-get-category' and
3808 ;; `org-export-get-node-property' extract useful information from an
3809 ;; headline or a parent headline. They all handle inheritance.
3811 ;; `org-export-get-alt-title' tries to retrieve an alternative title,
3812 ;; as a secondary string, suitable for table of contents. It falls
3813 ;; back onto default title.
3815 (defun org-export-get-relative-level (headline info)
3816 "Return HEADLINE relative level within current parsed tree.
3817 INFO is a plist holding contextual information."
3818 (+ (org-element-property :level headline)
3819 (or (plist-get info :headline-offset) 0)))
3821 (defun org-export-low-level-p (headline info)
3822 "Non-nil when HEADLINE is considered as low level.
3824 INFO is a plist used as a communication channel.
3826 A low level headlines has a relative level greater than
3827 `:headline-levels' property value.
3829 Return value is the difference between HEADLINE relative level
3830 and the last level being considered as high enough, or nil."
3831 (let ((limit (plist-get info :headline-levels)))
3832 (when (wholenump limit)
3833 (let ((level (org-export-get-relative-level headline info)))
3834 (and (> level limit) (- level limit))))))
3836 (defun org-export-get-headline-number (headline info)
3837 "Return numbered HEADLINE numbering as a list of numbers.
3838 INFO is a plist holding contextual information."
3839 (and (org-export-numbered-headline-p headline info)
3840 (cdr (assq headline (plist-get info :headline-numbering)))))
3842 (defun org-export-numbered-headline-p (headline info)
3843 "Return a non-nil value if HEADLINE element should be numbered.
3844 INFO is a plist used as a communication channel."
3845 (unless (org-some
3846 (lambda (head) (org-not-nil (org-element-property :UNNUMBERED head)))
3847 (org-element-lineage headline nil t))
3848 (let ((sec-num (plist-get info :section-numbers))
3849 (level (org-export-get-relative-level headline info)))
3850 (if (wholenump sec-num) (<= level sec-num) sec-num))))
3852 (defun org-export-number-to-roman (n)
3853 "Convert integer N into a roman numeral."
3854 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
3855 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
3856 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
3857 ( 1 . "I")))
3858 (res ""))
3859 (if (<= n 0)
3860 (number-to-string n)
3861 (while roman
3862 (if (>= n (caar roman))
3863 (setq n (- n (caar roman))
3864 res (concat res (cdar roman)))
3865 (pop roman)))
3866 res)))
3868 (defun org-export-get-tags (element info &optional tags inherited)
3869 "Return list of tags associated to ELEMENT.
3871 ELEMENT has either an `headline' or an `inlinetask' type. INFO
3872 is a plist used as a communication channel.
3874 Select tags (see `org-export-select-tags') and exclude tags (see
3875 `org-export-exclude-tags') are removed from the list.
3877 When non-nil, optional argument TAGS should be a list of strings.
3878 Any tag belonging to this list will also be removed.
3880 When optional argument INHERITED is non-nil, tags can also be
3881 inherited from parent headlines and FILETAGS keywords."
3882 (org-remove-if
3883 (lambda (tag) (or (member tag (plist-get info :select-tags))
3884 (member tag (plist-get info :exclude-tags))
3885 (member tag tags)))
3886 (if (not inherited) (org-element-property :tags element)
3887 ;; Build complete list of inherited tags.
3888 (let ((current-tag-list (org-element-property :tags element)))
3889 (dolist (parent (org-element-lineage element))
3890 (dolist (tag (org-element-property :tags parent))
3891 (when (and (memq (org-element-type parent) '(headline inlinetask))
3892 (not (member tag current-tag-list)))
3893 (push tag current-tag-list))))
3894 ;; Add FILETAGS keywords and return results.
3895 (org-uniquify (append (plist-get info :filetags) current-tag-list))))))
3897 (defun org-export-get-node-property (property blob &optional inherited)
3898 "Return node PROPERTY value for BLOB.
3900 PROPERTY is an upcase symbol (i.e. `:COOKIE_DATA'). BLOB is an
3901 element or object.
3903 If optional argument INHERITED is non-nil, the value can be
3904 inherited from a parent headline.
3906 Return value is a string or nil."
3907 (let ((headline (if (eq (org-element-type blob) 'headline) blob
3908 (org-export-get-parent-headline blob))))
3909 (if (not inherited) (org-element-property property blob)
3910 (let ((parent headline))
3911 (catch 'found
3912 (while parent
3913 (when (plist-member (nth 1 parent) property)
3914 (throw 'found (org-element-property property parent)))
3915 (setq parent (org-element-property :parent parent))))))))
3917 (defun org-export-get-category (blob info)
3918 "Return category for element or object BLOB.
3920 INFO is a plist used as a communication channel.
3922 CATEGORY is automatically inherited from a parent headline, from
3923 #+CATEGORY: keyword or created out of original file name. If all
3924 fail, the fall-back value is \"???\"."
3925 (or (org-export-get-node-property :CATEGORY blob t)
3926 (org-element-map (plist-get info :parse-tree) 'keyword
3927 (lambda (kwd)
3928 (when (equal (org-element-property :key kwd) "CATEGORY")
3929 (org-element-property :value kwd)))
3930 info 'first-match)
3931 (let ((file (plist-get info :input-file)))
3932 (and file (file-name-sans-extension (file-name-nondirectory file))))
3933 "???"))
3935 (defun org-export-get-alt-title (headline _)
3936 "Return alternative title for HEADLINE, as a secondary string.
3937 If no optional title is defined, fall-back to the regular title."
3938 (let ((alt (org-element-property :ALT_TITLE headline)))
3939 (if alt (org-element-parse-secondary-string
3940 alt (org-element-restriction 'headline) headline)
3941 (org-element-property :title headline))))
3943 (defun org-export-first-sibling-p (blob info)
3944 "Non-nil when BLOB is the first sibling in its parent.
3945 BLOB is an element or an object. If BLOB is a headline, non-nil
3946 means it is the first sibling in the sub-tree. INFO is a plist
3947 used as a communication channel."
3948 (memq (org-element-type (org-export-get-previous-element blob info))
3949 '(nil section)))
3951 (defun org-export-last-sibling-p (blob info)
3952 "Non-nil when BLOB is the last sibling in its parent.
3953 BLOB is an element or an object. INFO is a plist used as
3954 a communication channel."
3955 (not (org-export-get-next-element blob info)))
3958 ;;;; For Keywords
3960 ;; `org-export-get-date' returns a date appropriate for the document
3961 ;; to about to be exported. In particular, it takes care of
3962 ;; `org-export-date-timestamp-format'.
3964 (defun org-export-get-date (info &optional fmt)
3965 "Return date value for the current document.
3967 INFO is a plist used as a communication channel. FMT, when
3968 non-nil, is a time format string that will be applied on the date
3969 if it consists in a single timestamp object. It defaults to
3970 `org-export-date-timestamp-format' when nil.
3972 A proper date can be a secondary string, a string or nil. It is
3973 meant to be translated with `org-export-data' or alike."
3974 (let ((date (plist-get info :date))
3975 (fmt (or fmt org-export-date-timestamp-format)))
3976 (cond ((not date) nil)
3977 ((and fmt
3978 (not (cdr date))
3979 (eq (org-element-type (car date)) 'timestamp))
3980 (org-timestamp-format (car date) fmt))
3981 (t date))))
3984 ;;;; For Links
3986 ;; `org-export-custom-protocol-maybe' handles custom protocol defined
3987 ;; with `org-add-link-type', which see.
3989 ;; `org-export-get-coderef-format' returns an appropriate format
3990 ;; string for coderefs.
3992 ;; `org-export-inline-image-p' returns a non-nil value when the link
3993 ;; provided should be considered as an inline image.
3995 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
3996 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
3997 ;; returns an appropriate unique identifier when found, or nil.
3999 ;; `org-export-resolve-id-link' returns the first headline with
4000 ;; specified id or custom-id in parse tree, the path to the external
4001 ;; file with the id or nil when neither was found.
4003 ;; `org-export-resolve-coderef' associates a reference to a line
4004 ;; number in the element it belongs, or returns the reference itself
4005 ;; when the element isn't numbered.
4007 ;; `org-export-file-uri' expands a filename as stored in :path value
4008 ;; of a "file" link into a file URI.
4010 (defun org-export-custom-protocol-maybe (link desc backend)
4011 "Try exporting LINK with a dedicated function.
4013 DESC is its description, as a string, or nil. BACKEND is the
4014 back-end used for export, as a symbol.
4016 Return output as a string, or nil if no protocol handles LINK.
4018 A custom protocol has precedence over regular back-end export.
4019 The function ignores links with an implicit type (e.g.,
4020 \"custom-id\")."
4021 (let ((type (org-element-property :type link)))
4022 (unless (or (member type '("coderef" "custom-id" "fuzzy" "radio"))
4023 (not backend))
4024 (let ((protocol (nth 2 (assoc type org-link-protocols))))
4025 (and (functionp protocol)
4026 (funcall protocol
4027 (org-link-unescape (org-element-property :path link))
4028 desc
4029 backend))))))
4031 (defun org-export-get-coderef-format (path desc)
4032 "Return format string for code reference link.
4033 PATH is the link path. DESC is its description."
4034 (save-match-data
4035 (cond ((not desc) "%s")
4036 ((string-match (regexp-quote (concat "(" path ")")) desc)
4037 (replace-match "%s" t t desc))
4038 (t desc))))
4040 (defun org-export-inline-image-p (link &optional rules)
4041 "Non-nil if LINK object points to an inline image.
4043 Optional argument is a set of RULES defining inline images. It
4044 is an alist where associations have the following shape:
4046 \(TYPE . REGEXP)
4048 Applying a rule means apply REGEXP against LINK's path when its
4049 type is TYPE. The function will return a non-nil value if any of
4050 the provided rules is non-nil. The default rule is
4051 `org-export-default-inline-image-rule'.
4053 This only applies to links without a description."
4054 (and (not (org-element-contents link))
4055 (let ((case-fold-search t))
4056 (catch 'exit
4057 (dolist (rule (or rules org-export-default-inline-image-rule))
4058 (and (string= (org-element-property :type link) (car rule))
4059 (org-string-match-p (cdr rule)
4060 (org-element-property :path link))
4061 (throw 'exit t)))))))
4063 (defun org-export-resolve-coderef (ref info)
4064 "Resolve a code reference REF.
4066 INFO is a plist used as a communication channel.
4068 Return associated line number in source code, or REF itself,
4069 depending on src-block or example element's switches. Throw an
4070 error if no block contains REF."
4071 (or (org-element-map (plist-get info :parse-tree) '(example-block src-block)
4072 (lambda (el)
4073 (with-temp-buffer
4074 (insert (org-trim (org-element-property :value el)))
4075 (let* ((label-fmt (regexp-quote
4076 (or (org-element-property :label-fmt el)
4077 org-coderef-label-format)))
4078 (ref-re
4079 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
4080 (format label-fmt ref))))
4081 ;; Element containing REF is found. Resolve it to
4082 ;; either a label or a line number, as needed.
4083 (when (re-search-backward ref-re nil t)
4084 (cond
4085 ((org-element-property :use-labels el) ref)
4086 ((eq (org-element-property :number-lines el) 'continued)
4087 (+ (org-export-get-loc el info) (line-number-at-pos)))
4088 (t (line-number-at-pos)))))))
4089 info 'first-match)
4090 (user-error "Unable to resolve code reference: %s" ref)))
4092 (defun org-export-resolve-fuzzy-link (link info)
4093 "Return LINK destination.
4095 INFO is a plist holding contextual information.
4097 Return value can be an object, an element, or nil:
4099 - If LINK path matches a target object (i.e. <<path>>) return it.
4101 - If LINK path exactly matches the name affiliated keyword
4102 \(i.e. #+NAME: path) of an element, return that element.
4104 - If LINK path exactly matches any headline name, return that
4105 element.
4107 - Otherwise, throw an error.
4109 Assume LINK type is \"fuzzy\". White spaces are not
4110 significant."
4111 (let* ((raw-path (org-link-unescape (org-element-property :path link)))
4112 (headline-only (eq (string-to-char raw-path) ?*))
4113 ;; Split PATH at white spaces so matches are space
4114 ;; insensitive.
4115 (path (org-split-string
4116 (if headline-only (substring raw-path 1) raw-path)))
4117 (link-cache
4118 (or (plist-get info :resolve-fuzzy-link-cache)
4119 (plist-get (plist-put info
4120 :resolve-fuzzy-link-cache
4121 (make-hash-table :test #'equal))
4122 :resolve-fuzzy-link-cache)))
4123 (cached (gethash path link-cache 'not-found)))
4124 (if (not (eq cached 'not-found)) cached
4125 (let ((ast (plist-get info :parse-tree)))
4126 (puthash
4127 path
4128 (cond
4129 ;; First try to find a matching "<<path>>" unless user
4130 ;; specified he was looking for a headline (path starts with
4131 ;; a "*" character).
4132 ((and (not headline-only)
4133 (org-element-map ast 'target
4134 (lambda (datum)
4135 (and (equal (org-split-string
4136 (org-element-property :value datum))
4137 path)
4138 datum))
4139 info 'first-match)))
4140 ;; Then try to find an element with a matching "#+NAME: path"
4141 ;; affiliated keyword.
4142 ((and (not headline-only)
4143 (org-element-map ast org-element-all-elements
4144 (lambda (datum)
4145 (let ((name (org-element-property :name datum)))
4146 (and name (equal (org-split-string name) path) datum)))
4147 info 'first-match)))
4148 ;; Try to find a matching headline.
4149 ((org-element-map ast 'headline
4150 (lambda (h)
4151 (and (equal (org-split-string
4152 (replace-regexp-in-string
4153 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
4154 (org-element-property :raw-value h)))
4155 path)
4157 info 'first-match))
4158 (t (user-error "Unable to resolve link \"%s\"" raw-path)))
4159 link-cache)))))
4161 (defun org-export-resolve-id-link (link info)
4162 "Return headline referenced as LINK destination.
4164 INFO is a plist used as a communication channel.
4166 Return value can be the headline element matched in current parse
4167 tree or a file name. Assume LINK type is either \"id\" or
4168 \"custom-id\". Throw an error if no match is found."
4169 (let ((id (org-element-property :path link)))
4170 ;; First check if id is within the current parse tree.
4171 (or (org-element-map (plist-get info :parse-tree) 'headline
4172 (lambda (headline)
4173 (when (or (equal (org-element-property :ID headline) id)
4174 (equal (org-element-property :CUSTOM_ID headline) id))
4175 headline))
4176 info 'first-match)
4177 ;; Otherwise, look for external files.
4178 (cdr (assoc id (plist-get info :id-alist)))
4179 (user-error "Unable to resolve ID \"%s\"" id))))
4181 (defun org-export-resolve-radio-link (link info)
4182 "Return radio-target object referenced as LINK destination.
4184 INFO is a plist used as a communication channel.
4186 Return value can be a radio-target object or nil. Assume LINK
4187 has type \"radio\"."
4188 (let ((path (replace-regexp-in-string
4189 "[ \r\t\n]+" " " (org-element-property :path link))))
4190 (org-element-map (plist-get info :parse-tree) 'radio-target
4191 (lambda (radio)
4192 (and (eq (compare-strings
4193 (replace-regexp-in-string
4194 "[ \r\t\n]+" " " (org-element-property :value radio))
4195 nil nil path nil nil t)
4197 radio))
4198 info 'first-match)))
4200 (defun org-export-file-uri (filename)
4201 "Return file URI associated to FILENAME."
4202 (if (not (file-name-absolute-p filename)) filename
4203 (concat "file:/"
4204 (and (not (org-file-remote-p filename)) "/")
4205 (if (org-string-match-p "\\`~" filename)
4206 (expand-file-name filename)
4207 filename))))
4210 ;;;; For References
4212 ;; `org-export-get-reference' associate a unique reference for any
4213 ;; object or element.
4215 ;; `org-export-get-ordinal' associates a sequence number to any object
4216 ;; or element.
4218 (defun org-export-get-reference (datum info)
4219 "Return a unique reference for DATUM, as a string.
4220 DATUM is either an element or an object. INFO is the current
4221 export state, as a plist. Returned reference consists of
4222 alphanumeric characters only."
4223 (let ((type (org-element-type datum))
4224 (cache (or (plist-get info :internal-references)
4225 (let ((h (make-hash-table :test #'eq)))
4226 (plist-put info :internal-references h)
4227 h))))
4228 (or (gethash datum cache)
4229 (puthash datum
4230 (format "org%s%d"
4231 (if type
4232 (replace-regexp-in-string "-" "" (symbol-name type))
4233 "secondarystring")
4234 (cl-incf (gethash type cache 0)))
4235 cache))))
4237 (defun org-export-get-ordinal (element info &optional types predicate)
4238 "Return ordinal number of an element or object.
4240 ELEMENT is the element or object considered. INFO is the plist
4241 used as a communication channel.
4243 Optional argument TYPES, when non-nil, is a list of element or
4244 object types, as symbols, that should also be counted in.
4245 Otherwise, only provided element's type is considered.
4247 Optional argument PREDICATE is a function returning a non-nil
4248 value if the current element or object should be counted in. It
4249 accepts two arguments: the element or object being considered and
4250 the plist used as a communication channel. This allows to count
4251 only a certain type of objects (i.e. inline images).
4253 Return value is a list of numbers if ELEMENT is a headline or an
4254 item. It is nil for keywords. It represents the footnote number
4255 for footnote definitions and footnote references. If ELEMENT is
4256 a target, return the same value as if ELEMENT was the closest
4257 table, item or headline containing the target. In any other
4258 case, return the sequence number of ELEMENT among elements or
4259 objects of the same type."
4260 ;; Ordinal of a target object refer to the ordinal of the closest
4261 ;; table, item, or headline containing the object.
4262 (when (eq (org-element-type element) 'target)
4263 (setq element
4264 (org-element-lineage
4265 element
4266 '(footnote-definition footnote-reference headline item table))))
4267 (cl-case (org-element-type element)
4268 ;; Special case 1: A headline returns its number as a list.
4269 (headline (org-export-get-headline-number element info))
4270 ;; Special case 2: An item returns its number as a list.
4271 (item (let ((struct (org-element-property :structure element)))
4272 (org-list-get-item-number
4273 (org-element-property :begin element)
4274 struct
4275 (org-list-prevs-alist struct)
4276 (org-list-parents-alist struct))))
4277 ((footnote-definition footnote-reference)
4278 (org-export-get-footnote-number element info))
4279 (otherwise
4280 (let ((counter 0))
4281 ;; Increment counter until ELEMENT is found again.
4282 (org-element-map (plist-get info :parse-tree)
4283 (or types (org-element-type element))
4284 (lambda (el)
4285 (cond
4286 ((eq element el) (1+ counter))
4287 ((not predicate) (cl-incf counter) nil)
4288 ((funcall predicate el info) (cl-incf counter) nil)))
4289 info 'first-match)))))
4292 ;;;; For Src-Blocks
4294 ;; `org-export-get-loc' counts number of code lines accumulated in
4295 ;; src-block or example-block elements with a "+n" switch until
4296 ;; a given element, excluded. Note: "-n" switches reset that count.
4298 ;; `org-export-unravel-code' extracts source code (along with a code
4299 ;; references alist) from an `element-block' or `src-block' type
4300 ;; element.
4302 ;; `org-export-format-code' applies a formatting function to each line
4303 ;; of code, providing relative line number and code reference when
4304 ;; appropriate. Since it doesn't access the original element from
4305 ;; which the source code is coming, it expects from the code calling
4306 ;; it to know if lines should be numbered and if code references
4307 ;; should appear.
4309 ;; Eventually, `org-export-format-code-default' is a higher-level
4310 ;; function (it makes use of the two previous functions) which handles
4311 ;; line numbering and code references inclusion, and returns source
4312 ;; code in a format suitable for plain text or verbatim output.
4314 (defun org-export-get-loc (element info)
4315 "Return accumulated lines of code up to ELEMENT.
4317 INFO is the plist used as a communication channel.
4319 ELEMENT is excluded from count."
4320 (let ((loc 0))
4321 (org-element-map (plist-get info :parse-tree)
4322 `(src-block example-block ,(org-element-type element))
4323 (lambda (el)
4324 (cond
4325 ;; ELEMENT is reached: Quit the loop.
4326 ((eq el element))
4327 ;; Only count lines from src-block and example-block elements
4328 ;; with a "+n" or "-n" switch. A "-n" switch resets counter.
4329 ((not (memq (org-element-type el) '(src-block example-block))) nil)
4330 ((let ((linums (org-element-property :number-lines el)))
4331 (when linums
4332 ;; Accumulate locs or reset them.
4333 (let ((lines (org-count-lines
4334 (org-trim (org-element-property :value el)))))
4335 (setq loc (if (eq linums 'new) lines (+ loc lines))))))
4336 ;; Return nil to stay in the loop.
4337 nil)))
4338 info 'first-match)
4339 ;; Return value.
4340 loc))
4342 (defun org-export-unravel-code (element)
4343 "Clean source code and extract references out of it.
4345 ELEMENT has either a `src-block' an `example-block' type.
4347 Return a cons cell whose CAR is the source code, cleaned from any
4348 reference, protective commas and spurious indentation, and CDR is
4349 an alist between relative line number (integer) and name of code
4350 reference on that line (string)."
4351 (let* ((line 0) refs
4352 (value (org-element-property :value element))
4353 ;; Get code and clean it. Remove blank lines at its
4354 ;; beginning and end.
4355 (code (replace-regexp-in-string
4356 "\\`\\([ \t]*\n\\)+" ""
4357 (replace-regexp-in-string
4358 "\\([ \t]*\n\\)*[ \t]*\\'" "\n"
4359 (if (or org-src-preserve-indentation
4360 (org-element-property :preserve-indent element))
4361 value
4362 (org-element-remove-indentation value)))))
4363 ;; Get format used for references.
4364 (label-fmt (regexp-quote
4365 (or (org-element-property :label-fmt element)
4366 org-coderef-label-format)))
4367 ;; Build a regexp matching a loc with a reference.
4368 (with-ref-re
4369 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)[ \t]*\\)$"
4370 (replace-regexp-in-string
4371 "%s" "\\([-a-zA-Z0-9_ ]+\\)" label-fmt nil t))))
4372 ;; Return value.
4373 (cons
4374 ;; Code with references removed.
4375 (org-element-normalize-string
4376 (mapconcat
4377 (lambda (loc)
4378 (cl-incf line)
4379 (if (not (string-match with-ref-re loc)) loc
4380 ;; Ref line: remove ref, and signal its position in REFS.
4381 (push (cons line (match-string 3 loc)) refs)
4382 (replace-match "" nil nil loc 1)))
4383 (org-split-string code "\n") "\n"))
4384 ;; Reference alist.
4385 refs)))
4387 (defun org-export-format-code (code fun &optional num-lines ref-alist)
4388 "Format CODE by applying FUN line-wise and return it.
4390 CODE is a string representing the code to format. FUN is
4391 a function. It must accept three arguments: a line of
4392 code (string), the current line number (integer) or nil and the
4393 reference associated to the current line (string) or nil.
4395 Optional argument NUM-LINES can be an integer representing the
4396 number of code lines accumulated until the current code. Line
4397 numbers passed to FUN will take it into account. If it is nil,
4398 FUN's second argument will always be nil. This number can be
4399 obtained with `org-export-get-loc' function.
4401 Optional argument REF-ALIST can be an alist between relative line
4402 number (i.e. ignoring NUM-LINES) and the name of the code
4403 reference on it. If it is nil, FUN's third argument will always
4404 be nil. It can be obtained through the use of
4405 `org-export-unravel-code' function."
4406 (let ((--locs (org-split-string code "\n"))
4407 (--line 0))
4408 (org-element-normalize-string
4409 (mapconcat
4410 (lambda (--loc)
4411 (cl-incf --line)
4412 (let ((--ref (cdr (assq --line ref-alist))))
4413 (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
4414 --locs "\n"))))
4416 (defun org-export-format-code-default (element info)
4417 "Return source code from ELEMENT, formatted in a standard way.
4419 ELEMENT is either a `src-block' or `example-block' element. INFO
4420 is a plist used as a communication channel.
4422 This function takes care of line numbering and code references
4423 inclusion. Line numbers, when applicable, appear at the
4424 beginning of the line, separated from the code by two white
4425 spaces. Code references, on the other hand, appear flushed to
4426 the right, separated by six white spaces from the widest line of
4427 code."
4428 ;; Extract code and references.
4429 (let* ((code-info (org-export-unravel-code element))
4430 (code (car code-info))
4431 (code-lines (org-split-string code "\n")))
4432 (if (null code-lines) ""
4433 (let* ((refs (and (org-element-property :retain-labels element)
4434 (cdr code-info)))
4435 ;; Handle line numbering.
4436 (num-start (cl-case (org-element-property :number-lines element)
4437 (continued (org-export-get-loc element info))
4438 (new 0)))
4439 (num-fmt
4440 (and num-start
4441 (format "%%%ds "
4442 (length (number-to-string
4443 (+ (length code-lines) num-start))))))
4444 ;; Prepare references display, if required. Any reference
4445 ;; should start six columns after the widest line of code,
4446 ;; wrapped with parenthesis.
4447 (max-width
4448 (+ (apply 'max (mapcar 'length code-lines))
4449 (if (not num-start) 0 (length (format num-fmt num-start))))))
4450 (org-export-format-code
4451 code
4452 (lambda (loc line-num ref)
4453 (let ((number-str (and num-fmt (format num-fmt line-num))))
4454 (concat
4455 number-str
4457 (and ref
4458 (concat (make-string
4459 (- (+ 6 max-width)
4460 (+ (length loc) (length number-str))) ? )
4461 (format "(%s)" ref))))))
4462 num-start refs)))))
4465 ;;;; For Tables
4467 ;; `org-export-table-has-special-column-p' and and
4468 ;; `org-export-table-row-is-special-p' are predicates used to look for
4469 ;; meta-information about the table structure.
4471 ;; `org-table-has-header-p' tells when the rows before the first rule
4472 ;; should be considered as table's header.
4474 ;; `org-export-table-cell-width', `org-export-table-cell-alignment'
4475 ;; and `org-export-table-cell-borders' extract information from
4476 ;; a table-cell element.
4478 ;; `org-export-table-dimensions' gives the number on rows and columns
4479 ;; in the table, ignoring horizontal rules and special columns.
4480 ;; `org-export-table-cell-address', given a table-cell object, returns
4481 ;; the absolute address of a cell. On the other hand,
4482 ;; `org-export-get-table-cell-at' does the contrary.
4484 ;; `org-export-table-cell-starts-colgroup-p',
4485 ;; `org-export-table-cell-ends-colgroup-p',
4486 ;; `org-export-table-row-starts-rowgroup-p',
4487 ;; `org-export-table-row-ends-rowgroup-p',
4488 ;; `org-export-table-row-starts-header-p',
4489 ;; `org-export-table-row-ends-header-p' and
4490 ;; `org-export-table-row-in-header-p' indicate position of current row
4491 ;; or cell within the table.
4493 (defun org-export-table-has-special-column-p (table)
4494 "Non-nil when TABLE has a special column.
4495 All special columns will be ignored during export."
4496 ;; The table has a special column when every first cell of every row
4497 ;; has an empty value or contains a symbol among "/", "#", "!", "$",
4498 ;; "*" "_" and "^". Though, do not consider a first row containing
4499 ;; only empty cells as special.
4500 (let ((special-column-p 'empty))
4501 (catch 'exit
4502 (mapc
4503 (lambda (row)
4504 (when (eq (org-element-property :type row) 'standard)
4505 (let ((value (org-element-contents
4506 (car (org-element-contents row)))))
4507 (cond ((member value '(("/") ("#") ("!") ("$") ("*") ("_") ("^")))
4508 (setq special-column-p 'special))
4509 ((not value))
4510 (t (throw 'exit nil))))))
4511 (org-element-contents table))
4512 (eq special-column-p 'special))))
4514 (defun org-export-table-has-header-p (table info)
4515 "Non-nil when TABLE has a header.
4517 INFO is a plist used as a communication channel.
4519 A table has a header when it contains at least two row groups."
4520 (let ((cache (or (plist-get info :table-header-cache)
4521 (plist-get (setq info
4522 (plist-put info :table-header-cache
4523 (make-hash-table :test 'eq)))
4524 :table-header-cache))))
4525 (or (gethash table cache)
4526 (let ((rowgroup 1) row-flag)
4527 (puthash
4528 table
4529 (org-element-map table 'table-row
4530 (lambda (row)
4531 (cond
4532 ((> rowgroup 1) t)
4533 ((and row-flag (eq (org-element-property :type row) 'rule))
4534 (cl-incf rowgroup) (setq row-flag nil))
4535 ((and (not row-flag) (eq (org-element-property :type row)
4536 'standard))
4537 (setq row-flag t) nil)))
4538 info 'first-match)
4539 cache)))))
4541 (defun org-export-table-row-is-special-p (table-row _)
4542 "Non-nil if TABLE-ROW is considered special.
4543 All special rows will be ignored during export."
4544 (when (eq (org-element-property :type table-row) 'standard)
4545 (let ((first-cell (org-element-contents
4546 (car (org-element-contents table-row)))))
4547 ;; A row is special either when...
4549 ;; ... it starts with a field only containing "/",
4550 (equal first-cell '("/"))
4551 ;; ... the table contains a special column and the row start
4552 ;; with a marking character among, "^", "_", "$" or "!",
4553 (and (org-export-table-has-special-column-p
4554 (org-export-get-parent table-row))
4555 (member first-cell '(("^") ("_") ("$") ("!"))))
4556 ;; ... it contains only alignment cookies and empty cells.
4557 (let ((special-row-p 'empty))
4558 (catch 'exit
4559 (mapc
4560 (lambda (cell)
4561 (let ((value (org-element-contents cell)))
4562 ;; Since VALUE is a secondary string, the following
4563 ;; checks avoid expanding it with `org-export-data'.
4564 (cond ((not value))
4565 ((and (not (cdr value))
4566 (stringp (car value))
4567 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'"
4568 (car value)))
4569 (setq special-row-p 'cookie))
4570 (t (throw 'exit nil)))))
4571 (org-element-contents table-row))
4572 (eq special-row-p 'cookie)))))))
4574 (defun org-export-table-row-group (table-row info)
4575 "Return TABLE-ROW's group number, as an integer.
4577 INFO is a plist used as the communication channel.
4579 Return value is the group number, as an integer, or nil for
4580 special rows and rows separators. First group is also table's
4581 header."
4582 (let ((cache (or (plist-get info :table-row-group-cache)
4583 (plist-get (setq info
4584 (plist-put info :table-row-group-cache
4585 (make-hash-table :test 'eq)))
4586 :table-row-group-cache))))
4587 (cond ((gethash table-row cache))
4588 ((eq (org-element-property :type table-row) 'rule) nil)
4589 (t (let ((group 0) row-flag)
4590 (org-element-map (org-export-get-parent table-row) 'table-row
4591 (lambda (row)
4592 (if (eq (org-element-property :type row) 'rule)
4593 (setq row-flag nil)
4594 (unless row-flag (cl-incf group) (setq row-flag t)))
4595 (when (eq table-row row) (puthash table-row group cache)))
4596 info 'first-match))))))
4598 (defun org-export-table-cell-width (table-cell info)
4599 "Return TABLE-CELL contents width.
4601 INFO is a plist used as the communication channel.
4603 Return value is the width given by the last width cookie in the
4604 same column as TABLE-CELL, or nil."
4605 (let* ((row (org-export-get-parent table-cell))
4606 (table (org-export-get-parent row))
4607 (cells (org-element-contents row))
4608 (columns (length cells))
4609 (column (- columns (length (memq table-cell cells))))
4610 (cache (or (plist-get info :table-cell-width-cache)
4611 (plist-get (setq info
4612 (plist-put info :table-cell-width-cache
4613 (make-hash-table :test 'eq)))
4614 :table-cell-width-cache)))
4615 (width-vector (or (gethash table cache)
4616 (puthash table (make-vector columns 'empty) cache)))
4617 (value (aref width-vector column)))
4618 (if (not (eq value 'empty)) value
4619 (let (cookie-width)
4620 (dolist (row (org-element-contents table)
4621 (aset width-vector column cookie-width))
4622 (when (org-export-table-row-is-special-p row info)
4623 ;; In a special row, try to find a width cookie at COLUMN.
4624 (let* ((value (org-element-contents
4625 (elt (org-element-contents row) column)))
4626 (cookie (car value)))
4627 ;; The following checks avoid expanding unnecessarily
4628 ;; the cell with `org-export-data'.
4629 (when (and value
4630 (not (cdr value))
4631 (stringp cookie)
4632 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'" cookie)
4633 (match-string 1 cookie))
4634 (setq cookie-width
4635 (string-to-number (match-string 1 cookie)))))))))))
4637 (defun org-export-table-cell-alignment (table-cell info)
4638 "Return TABLE-CELL contents alignment.
4640 INFO is a plist used as the communication channel.
4642 Return alignment as specified by the last alignment cookie in the
4643 same column as TABLE-CELL. If no such cookie is found, a default
4644 alignment value will be deduced from fraction of numbers in the
4645 column (see `org-table-number-fraction' for more information).
4646 Possible values are `left', `right' and `center'."
4647 ;; Load `org-table-number-fraction' and `org-table-number-regexp'.
4648 (require 'org-table)
4649 (let* ((row (org-export-get-parent table-cell))
4650 (table (org-export-get-parent row))
4651 (cells (org-element-contents row))
4652 (columns (length cells))
4653 (column (- columns (length (memq table-cell cells))))
4654 (cache (or (plist-get info :table-cell-alignment-cache)
4655 (plist-get (setq info
4656 (plist-put info :table-cell-alignment-cache
4657 (make-hash-table :test 'eq)))
4658 :table-cell-alignment-cache)))
4659 (align-vector (or (gethash table cache)
4660 (puthash table (make-vector columns nil) cache))))
4661 (or (aref align-vector column)
4662 (let ((number-cells 0)
4663 (total-cells 0)
4664 cookie-align
4665 previous-cell-number-p)
4666 (dolist (row (org-element-contents (org-export-get-parent row)))
4667 (cond
4668 ;; In a special row, try to find an alignment cookie at
4669 ;; COLUMN.
4670 ((org-export-table-row-is-special-p row info)
4671 (let ((value (org-element-contents
4672 (elt (org-element-contents row) column))))
4673 ;; Since VALUE is a secondary string, the following
4674 ;; checks avoid useless expansion through
4675 ;; `org-export-data'.
4676 (when (and value
4677 (not (cdr value))
4678 (stringp (car value))
4679 (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'"
4680 (car value))
4681 (match-string 1 (car value)))
4682 (setq cookie-align (match-string 1 (car value))))))
4683 ;; Ignore table rules.
4684 ((eq (org-element-property :type row) 'rule))
4685 ;; In a standard row, check if cell's contents are
4686 ;; expressing some kind of number. Increase NUMBER-CELLS
4687 ;; accordingly. Though, don't bother if an alignment
4688 ;; cookie has already defined cell's alignment.
4689 ((not cookie-align)
4690 (let ((value (org-export-data
4691 (org-element-contents
4692 (elt (org-element-contents row) column))
4693 info)))
4694 (cl-incf total-cells)
4695 ;; Treat an empty cell as a number if it follows
4696 ;; a number.
4697 (if (not (or (string-match org-table-number-regexp value)
4698 (and (string= value "") previous-cell-number-p)))
4699 (setq previous-cell-number-p nil)
4700 (setq previous-cell-number-p t)
4701 (cl-incf number-cells))))))
4702 ;; Return value. Alignment specified by cookies has
4703 ;; precedence over alignment deduced from cell's contents.
4704 (aset align-vector
4705 column
4706 (cond ((equal cookie-align "l") 'left)
4707 ((equal cookie-align "r") 'right)
4708 ((equal cookie-align "c") 'center)
4709 ((>= (/ (float number-cells) total-cells)
4710 org-table-number-fraction)
4711 'right)
4712 (t 'left)))))))
4714 (defun org-export-table-cell-borders (table-cell info)
4715 "Return TABLE-CELL borders.
4717 INFO is a plist used as a communication channel.
4719 Return value is a list of symbols, or nil. Possible values are:
4720 `top', `bottom', `above', `below', `left' and `right'. Note:
4721 `top' (resp. `bottom') only happen for a cell in the first
4722 row (resp. last row) of the table, ignoring table rules, if any.
4724 Returned borders ignore special rows."
4725 (let* ((row (org-export-get-parent table-cell))
4726 (table (org-export-get-parent-table table-cell))
4727 borders)
4728 ;; Top/above border? TABLE-CELL has a border above when a rule
4729 ;; used to demarcate row groups can be found above. Hence,
4730 ;; finding a rule isn't sufficient to push `above' in BORDERS:
4731 ;; another regular row has to be found above that rule.
4732 (let (rule-flag)
4733 (catch 'exit
4734 (mapc (lambda (row)
4735 (cond ((eq (org-element-property :type row) 'rule)
4736 (setq rule-flag t))
4737 ((not (org-export-table-row-is-special-p row info))
4738 (if rule-flag (throw 'exit (push 'above borders))
4739 (throw 'exit nil)))))
4740 ;; Look at every row before the current one.
4741 (cdr (memq row (reverse (org-element-contents table)))))
4742 ;; No rule above, or rule found starts the table (ignoring any
4743 ;; special row): TABLE-CELL is at the top of the table.
4744 (when rule-flag (push 'above borders))
4745 (push 'top borders)))
4746 ;; Bottom/below border? TABLE-CELL has a border below when next
4747 ;; non-regular row below is a rule.
4748 (let (rule-flag)
4749 (catch 'exit
4750 (mapc (lambda (row)
4751 (cond ((eq (org-element-property :type row) 'rule)
4752 (setq rule-flag t))
4753 ((not (org-export-table-row-is-special-p row info))
4754 (if rule-flag (throw 'exit (push 'below borders))
4755 (throw 'exit nil)))))
4756 ;; Look at every row after the current one.
4757 (cdr (memq row (org-element-contents table))))
4758 ;; No rule below, or rule found ends the table (modulo some
4759 ;; special row): TABLE-CELL is at the bottom of the table.
4760 (when rule-flag (push 'below borders))
4761 (push 'bottom borders)))
4762 ;; Right/left borders? They can only be specified by column
4763 ;; groups. Column groups are defined in a row starting with "/".
4764 ;; Also a column groups row only contains "<", "<>", ">" or blank
4765 ;; cells.
4766 (catch 'exit
4767 (let ((column (let ((cells (org-element-contents row)))
4768 (- (length cells) (length (memq table-cell cells))))))
4769 (mapc
4770 (lambda (row)
4771 (unless (eq (org-element-property :type row) 'rule)
4772 (when (equal (org-element-contents
4773 (car (org-element-contents row)))
4774 '("/"))
4775 (let ((column-groups
4776 (mapcar
4777 (lambda (cell)
4778 (let ((value (org-element-contents cell)))
4779 (when (member value '(("<") ("<>") (">") nil))
4780 (car value))))
4781 (org-element-contents row))))
4782 ;; There's a left border when previous cell, if
4783 ;; any, ends a group, or current one starts one.
4784 (when (or (and (not (zerop column))
4785 (member (elt column-groups (1- column))
4786 '(">" "<>")))
4787 (member (elt column-groups column) '("<" "<>")))
4788 (push 'left borders))
4789 ;; There's a right border when next cell, if any,
4790 ;; starts a group, or current one ends one.
4791 (when (or (and (/= (1+ column) (length column-groups))
4792 (member (elt column-groups (1+ column))
4793 '("<" "<>")))
4794 (member (elt column-groups column) '(">" "<>")))
4795 (push 'right borders))
4796 (throw 'exit nil)))))
4797 ;; Table rows are read in reverse order so last column groups
4798 ;; row has precedence over any previous one.
4799 (reverse (org-element-contents table)))))
4800 ;; Return value.
4801 borders))
4803 (defun org-export-table-cell-starts-colgroup-p (table-cell info)
4804 "Non-nil when TABLE-CELL is at the beginning of a column group.
4805 INFO is a plist used as a communication channel."
4806 ;; A cell starts a column group either when it is at the beginning
4807 ;; of a row (or after the special column, if any) or when it has
4808 ;; a left border.
4809 (or (eq (org-element-map (org-export-get-parent table-cell) 'table-cell
4810 'identity info 'first-match)
4811 table-cell)
4812 (memq 'left (org-export-table-cell-borders table-cell info))))
4814 (defun org-export-table-cell-ends-colgroup-p (table-cell info)
4815 "Non-nil when TABLE-CELL is at the end of a column group.
4816 INFO is a plist used as a communication channel."
4817 ;; A cell ends a column group either when it is at the end of a row
4818 ;; or when it has a right border.
4819 (or (eq (car (last (org-element-contents
4820 (org-export-get-parent table-cell))))
4821 table-cell)
4822 (memq 'right (org-export-table-cell-borders table-cell info))))
4824 (defun org-export-table-row-starts-rowgroup-p (table-row info)
4825 "Non-nil when TABLE-ROW is at the beginning of a row group.
4826 INFO is a plist used as a communication channel."
4827 (unless (or (eq (org-element-property :type table-row) 'rule)
4828 (org-export-table-row-is-special-p table-row info))
4829 (let ((borders (org-export-table-cell-borders
4830 (car (org-element-contents table-row)) info)))
4831 (or (memq 'top borders) (memq 'above borders)))))
4833 (defun org-export-table-row-ends-rowgroup-p (table-row info)
4834 "Non-nil when TABLE-ROW is at the end of a row group.
4835 INFO is a plist used as a communication channel."
4836 (unless (or (eq (org-element-property :type table-row) 'rule)
4837 (org-export-table-row-is-special-p table-row info))
4838 (let ((borders (org-export-table-cell-borders
4839 (car (org-element-contents table-row)) info)))
4840 (or (memq 'bottom borders) (memq 'below borders)))))
4842 (defun org-export-table-row-in-header-p (table-row info)
4843 "Non-nil when TABLE-ROW is located within table's header.
4844 INFO is a plist used as a communication channel. Always return
4845 nil for special rows and rows separators."
4846 (and (org-export-table-has-header-p
4847 (org-export-get-parent-table table-row) info)
4848 (eql (org-export-table-row-group table-row info) 1)))
4850 (defun org-export-table-row-starts-header-p (table-row info)
4851 "Non-nil when TABLE-ROW is the first table header's row.
4852 INFO is a plist used as a communication channel."
4853 (and (org-export-table-row-in-header-p table-row info)
4854 (org-export-table-row-starts-rowgroup-p table-row info)))
4856 (defun org-export-table-row-ends-header-p (table-row info)
4857 "Non-nil when TABLE-ROW is the last table header's row.
4858 INFO is a plist used as a communication channel."
4859 (and (org-export-table-row-in-header-p table-row info)
4860 (org-export-table-row-ends-rowgroup-p table-row info)))
4862 (defun org-export-table-row-number (table-row info)
4863 "Return TABLE-ROW number.
4864 INFO is a plist used as a communication channel. Return value is
4865 zero-based and ignores separators. The function returns nil for
4866 special columns and separators."
4867 (when (and (eq (org-element-property :type table-row) 'standard)
4868 (not (org-export-table-row-is-special-p table-row info)))
4869 (let ((number 0))
4870 (org-element-map (org-export-get-parent-table table-row) 'table-row
4871 (lambda (row)
4872 (cond ((eq row table-row) number)
4873 ((eq (org-element-property :type row) 'standard)
4874 (cl-incf number) nil)))
4875 info 'first-match))))
4877 (defun org-export-table-dimensions (table info)
4878 "Return TABLE dimensions.
4880 INFO is a plist used as a communication channel.
4882 Return value is a CONS like (ROWS . COLUMNS) where
4883 ROWS (resp. COLUMNS) is the number of exportable
4884 rows (resp. columns)."
4885 (let (first-row (columns 0) (rows 0))
4886 ;; Set number of rows, and extract first one.
4887 (org-element-map table 'table-row
4888 (lambda (row)
4889 (when (eq (org-element-property :type row) 'standard)
4890 (cl-incf rows)
4891 (unless first-row (setq first-row row)))) info)
4892 ;; Set number of columns.
4893 (org-element-map first-row 'table-cell (lambda (_) (cl-incf columns)) info)
4894 ;; Return value.
4895 (cons rows columns)))
4897 (defun org-export-table-cell-address (table-cell info)
4898 "Return address of a regular TABLE-CELL object.
4900 TABLE-CELL is the cell considered. INFO is a plist used as
4901 a communication channel.
4903 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4904 zero-based index. Only exportable cells are considered. The
4905 function returns nil for other cells."
4906 (let* ((table-row (org-export-get-parent table-cell))
4907 (row-number (org-export-table-row-number table-row info)))
4908 (when row-number
4909 (cons row-number
4910 (let ((col-count 0))
4911 (org-element-map table-row 'table-cell
4912 (lambda (cell)
4913 (if (eq cell table-cell) col-count (cl-incf col-count) nil))
4914 info 'first-match))))))
4916 (defun org-export-get-table-cell-at (address table info)
4917 "Return regular table-cell object at ADDRESS in TABLE.
4919 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4920 zero-based index. TABLE is a table type element. INFO is
4921 a plist used as a communication channel.
4923 If no table-cell, among exportable cells, is found at ADDRESS,
4924 return nil."
4925 (let ((column-pos (cdr address)) (column-count 0))
4926 (org-element-map
4927 ;; Row at (car address) or nil.
4928 (let ((row-pos (car address)) (row-count 0))
4929 (org-element-map table 'table-row
4930 (lambda (row)
4931 (cond ((eq (org-element-property :type row) 'rule) nil)
4932 ((= row-count row-pos) row)
4933 (t (cl-incf row-count) nil)))
4934 info 'first-match))
4935 'table-cell
4936 (lambda (cell)
4937 (if (= column-count column-pos) cell
4938 (cl-incf column-count) nil))
4939 info 'first-match)))
4942 ;;;; For Tables Of Contents
4944 ;; `org-export-collect-headlines' builds a list of all exportable
4945 ;; headline elements, maybe limited to a certain depth. One can then
4946 ;; easily parse it and transcode it.
4948 ;; Building lists of tables, figures or listings is quite similar.
4949 ;; Once the generic function `org-export-collect-elements' is defined,
4950 ;; `org-export-collect-tables', `org-export-collect-figures' and
4951 ;; `org-export-collect-listings' can be derived from it.
4953 (defun org-export-collect-headlines (info &optional n scope)
4954 "Collect headlines in order to build a table of contents.
4956 INFO is a plist used as a communication channel.
4958 When optional argument N is an integer, it specifies the depth of
4959 the table of contents. Otherwise, it is set to the value of the
4960 last headline level. See `org-export-headline-levels' for more
4961 information.
4963 Optional argument SCOPE, when non-nil, is an element. If it is
4964 a headline, only children of SCOPE are collected. Otherwise,
4965 collect children of the headline containing provided element. If
4966 there is no such headline, collect all headlines. In any case,
4967 argument N becomes relative to the level of that headline.
4969 Return a list of all exportable headlines as parsed elements.
4970 Footnote sections are ignored."
4971 (let* ((scope (cond ((not scope) (plist-get info :parse-tree))
4972 ((eq (org-element-type scope) 'headline) scope)
4973 ((org-export-get-parent-headline scope))
4974 (t (plist-get info :parse-tree))))
4975 (limit (plist-get info :headline-levels))
4976 (n (if (not (wholenump n)) limit
4977 (min (if (eq (org-element-type scope) 'org-data) n
4978 (+ (org-export-get-relative-level scope info) n))
4979 limit))))
4980 (org-element-map (org-element-contents scope) 'headline
4981 (lambda (headline)
4982 (unless (org-element-property :footnote-section-p headline)
4983 (let ((level (org-export-get-relative-level headline info)))
4984 (and (<= level n) headline))))
4985 info)))
4987 (defun org-export-collect-elements (type info &optional predicate)
4988 "Collect referenceable elements of a determined type.
4990 TYPE can be a symbol or a list of symbols specifying element
4991 types to search. Only elements with a caption are collected.
4993 INFO is a plist used as a communication channel.
4995 When non-nil, optional argument PREDICATE is a function accepting
4996 one argument, an element of type TYPE. It returns a non-nil
4997 value when that element should be collected.
4999 Return a list of all elements found, in order of appearance."
5000 (org-element-map (plist-get info :parse-tree) type
5001 (lambda (element)
5002 (and (org-element-property :caption element)
5003 (or (not predicate) (funcall predicate element))
5004 element))
5005 info))
5007 (defun org-export-collect-tables (info)
5008 "Build a list of tables.
5009 INFO is a plist used as a communication channel.
5011 Return a list of table elements with a caption."
5012 (org-export-collect-elements 'table info))
5014 (defun org-export-collect-figures (info predicate)
5015 "Build a list of figures.
5017 INFO is a plist used as a communication channel. PREDICATE is
5018 a function which accepts one argument: a paragraph element and
5019 whose return value is non-nil when that element should be
5020 collected.
5022 A figure is a paragraph type element, with a caption, verifying
5023 PREDICATE. The latter has to be provided since a \"figure\" is
5024 a vague concept that may depend on back-end.
5026 Return a list of elements recognized as figures."
5027 (org-export-collect-elements 'paragraph info predicate))
5029 (defun org-export-collect-listings (info)
5030 "Build a list of src blocks.
5032 INFO is a plist used as a communication channel.
5034 Return a list of src-block elements with a caption."
5035 (org-export-collect-elements 'src-block info))
5038 ;;;; Smart Quotes
5040 ;; The main function for the smart quotes sub-system is
5041 ;; `org-export-activate-smart-quotes', which replaces every quote in
5042 ;; a given string from the parse tree with its "smart" counterpart.
5044 ;; Dictionary for smart quotes is stored in
5045 ;; `org-export-smart-quotes-alist'.
5047 (defconst org-export-smart-quotes-alist
5048 '(("da"
5049 ;; one may use: »...«, "...", ›...‹, or '...'.
5050 ;; http://sproget.dk/raad-og-regler/retskrivningsregler/retskrivningsregler/a7-40-60/a7-58-anforselstegn/
5051 ;; LaTeX quotes require Babel!
5052 (opening-double-quote :utf-8 "»" :html "&raquo;" :latex ">>"
5053 :texinfo "@guillemetright{}")
5054 (closing-double-quote :utf-8 "«" :html "&laquo;" :latex "<<"
5055 :texinfo "@guillemetleft{}")
5056 (opening-single-quote :utf-8 "›" :html "&rsaquo;" :latex "\\frq{}"
5057 :texinfo "@guilsinglright{}")
5058 (closing-single-quote :utf-8 "‹" :html "&lsaquo;" :latex "\\flq{}"
5059 :texinfo "@guilsingleft{}")
5060 (apostrophe :utf-8 "’" :html "&rsquo;"))
5061 ("de"
5062 (opening-double-quote :utf-8 "„" :html "&bdquo;" :latex "\"`"
5063 :texinfo "@quotedblbase{}")
5064 (closing-double-quote :utf-8 "“" :html "&ldquo;" :latex "\"'"
5065 :texinfo "@quotedblleft{}")
5066 (opening-single-quote :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}"
5067 :texinfo "@quotesinglbase{}")
5068 (closing-single-quote :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}"
5069 :texinfo "@quoteleft{}")
5070 (apostrophe :utf-8 "’" :html "&rsquo;"))
5071 ("en"
5072 (opening-double-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
5073 (closing-double-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
5074 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5075 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5076 (apostrophe :utf-8 "’" :html "&rsquo;"))
5077 ("es"
5078 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5079 :texinfo "@guillemetleft{}")
5080 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5081 :texinfo "@guillemetright{}")
5082 (opening-single-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
5083 (closing-single-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
5084 (apostrophe :utf-8 "’" :html "&rsquo;"))
5085 ("fr"
5086 (opening-double-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
5087 :texinfo "@guillemetleft{}@tie{}")
5088 (closing-double-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
5089 :texinfo "@tie{}@guillemetright{}")
5090 (opening-single-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
5091 :texinfo "@guillemetleft{}@tie{}")
5092 (closing-single-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
5093 :texinfo "@tie{}@guillemetright{}")
5094 (apostrophe :utf-8 "’" :html "&rsquo;"))
5095 ("no"
5096 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5097 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5098 :texinfo "@guillemetleft{}")
5099 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5100 :texinfo "@guillemetright{}")
5101 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5102 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5103 (apostrophe :utf-8 "’" :html "&rsquo;"))
5104 ("nb"
5105 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5106 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5107 :texinfo "@guillemetleft{}")
5108 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5109 :texinfo "@guillemetright{}")
5110 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5111 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5112 (apostrophe :utf-8 "’" :html "&rsquo;"))
5113 ("nn"
5114 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5115 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5116 :texinfo "@guillemetleft{}")
5117 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5118 :texinfo "@guillemetright{}")
5119 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5120 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5121 (apostrophe :utf-8 "’" :html "&rsquo;"))
5122 ("ru"
5123 ;; 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
5124 ;; http://www.artlebedev.ru/kovodstvo/sections/104/
5125 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "{}<<"
5126 :texinfo "@guillemetleft{}")
5127 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex ">>{}"
5128 :texinfo "@guillemetright{}")
5129 (opening-single-quote :utf-8 "„" :html "&bdquo;" :latex "\\glqq{}"
5130 :texinfo "@quotedblbase{}")
5131 (closing-single-quote :utf-8 "“" :html "&ldquo;" :latex "\\grqq{}"
5132 :texinfo "@quotedblleft{}")
5133 (apostrophe :utf-8 "’" :html: "&#39;"))
5134 ("sv"
5135 ;; based on https://sv.wikipedia.org/wiki/Citattecken
5136 (opening-double-quote :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
5137 (closing-double-quote :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
5138 (opening-single-quote :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "`")
5139 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "'")
5140 (apostrophe :utf-8 "’" :html "&rsquo;"))
5142 "Smart quotes translations.
5144 Alist whose CAR is a language string and CDR is an alist with
5145 quote type as key and a plist associating various encodings to
5146 their translation as value.
5148 A quote type can be any symbol among `opening-double-quote',
5149 `closing-double-quote', `opening-single-quote',
5150 `closing-single-quote' and `apostrophe'.
5152 Valid encodings include `:utf-8', `:html', `:latex' and
5153 `:texinfo'.
5155 If no translation is found, the quote character is left as-is.")
5157 (defun org-export--smart-quote-status (s info)
5158 "Return smart quote status at the beginning of string S.
5159 INFO is the current export state, as a plist."
5160 (let* ((parent (org-element-property :parent s))
5161 (cache (or (plist-get info :smart-quote-cache)
5162 (let ((table (make-hash-table :test #'eq)))
5163 (plist-put info :smart-quote-cache table)
5164 table)))
5165 (value (gethash parent cache 'missing-data)))
5166 (if (not (eq value 'missing-data)) (cdr (assq s value))
5167 (let (level1-open level2-open full-status)
5168 (org-element-map parent 'plain-text
5169 (lambda (text)
5170 (let ((start 0) current-status)
5171 (while (setq start (string-match "['\"]" text start))
5172 (cl-incf start)
5173 (push
5174 (cond
5175 ((equal (match-string 0 text) "\"")
5176 (setf level1-open (not level1-open))
5177 (setf level2-open nil)
5178 (if level1-open 'opening-double-quote 'closing-double-quote))
5179 ;; Not already in a level 1 quote: this is an
5180 ;; apostrophe.
5181 ((not level1-open) 'apostrophe)
5182 ;; Apostrophe.
5183 ((org-string-match-p "\\S-'\\S-" text) 'apostrophe)
5184 ;; Apostrophe at the beginning of a string. Check
5185 ;; white space at the end of the last object.
5186 ((and (org-string-match-p "\\`'\\S-" text)
5187 (let ((p (org-export-get-previous-element text info)))
5188 (and p
5189 (if (stringp p)
5190 (not (org-string-match-p "[ \t]\\'" p))
5191 (memq (org-element-property :post-blank p)
5192 '(0 nil))))))
5193 'apostrophe)
5194 ;; Apostrophe at the end of a string. Check white
5195 ;; space at the beginning of the next object, which
5196 ;; can only happen if that object is a string.
5197 ((and (org-string-match-p "\\S-'\\'" text)
5198 (let ((n (org-export-get-next-element text info)))
5199 (and n
5200 (not (and (stringp n)
5201 (org-string-match-p "\\`[ \t]" n))))))
5202 'apostrophe)
5203 ;; Lonesome apostrophe. Check white space around
5204 ;; both ends.
5205 ((and (equal text "'")
5206 (let ((p (org-export-get-previous-element text info)))
5207 (and p
5208 (if (stringp p)
5209 (not (org-string-match-p "[ \t]\\'" p))
5210 (memq (org-element-property :post-blank p)
5211 '(0 nil)))
5212 (let ((n (org-export-get-next-element text info)))
5213 (and n
5214 (not (and (stringp n)
5215 (org-string-match-p "\\`[ \t]"
5216 n))))))))
5217 'apostrophe)
5218 ;; Else, consider it as a level 2 quote.
5219 (t (setf level2-open (not level2-open))
5220 (if level2-open 'opening-single-quote
5221 'closing-single-quote)))
5222 current-status))
5223 (when current-status
5224 (push (cons text (nreverse current-status)) full-status))))
5225 info nil org-element-recursive-objects)
5226 (puthash parent full-status cache)
5227 (cdr (assq s full-status))))))
5229 (defun org-export-activate-smart-quotes (s encoding info &optional original)
5230 "Replace regular quotes with \"smart\" quotes in string S.
5232 ENCODING is a symbol among `:html', `:latex', `:texinfo' and
5233 `:utf-8'. INFO is a plist used as a communication channel.
5235 The function has to retrieve information about string
5236 surroundings in parse tree. It can only happen with an
5237 unmodified string. Thus, if S has already been through another
5238 process, a non-nil ORIGINAL optional argument will provide that
5239 original string.
5241 Return the new string."
5242 (let ((quote-status
5243 (copy-sequence (org-export--smart-quote-status (or original s) info))))
5244 (replace-regexp-in-string
5245 "['\"]"
5246 (lambda (match)
5247 (or (plist-get
5248 (cdr (assq (pop quote-status)
5249 (cdr (assoc (plist-get info :language)
5250 org-export-smart-quotes-alist))))
5251 encoding)
5252 match))
5253 s nil t)))
5255 ;;;; Topology
5257 ;; Here are various functions to retrieve information about the
5258 ;; neighborhood of a given element or object. Neighbors of interest
5259 ;; are direct parent (`org-export-get-parent'), parent headline
5260 ;; (`org-export-get-parent-headline'), first element containing an
5261 ;; object, (`org-export-get-parent-element'), parent table
5262 ;; (`org-export-get-parent-table'), previous element or object
5263 ;; (`org-export-get-previous-element') and next element or object
5264 ;; (`org-export-get-next-element').
5266 ;; defsubst org-export-get-parent must be defined before first use
5268 (define-obsolete-function-alias
5269 'org-export-get-genealogy 'org-element-lineage "25.1")
5271 (defun org-export-get-parent-headline (blob)
5272 "Return BLOB parent headline or nil.
5273 BLOB is the element or object being considered."
5274 (org-element-lineage blob '(headline)))
5276 (defun org-export-get-parent-element (object)
5277 "Return first element containing OBJECT or nil.
5278 OBJECT is the object to consider."
5279 (org-element-lineage object org-element-all-elements))
5281 (defun org-export-get-parent-table (object)
5282 "Return OBJECT parent table or nil.
5283 OBJECT is either a `table-cell' or `table-element' type object."
5284 (org-element-lineage object '(table)))
5286 (defun org-export-get-previous-element (blob info &optional n)
5287 "Return previous element or object.
5289 BLOB is an element or object. INFO is a plist used as
5290 a communication channel. Return previous exportable element or
5291 object, a string, or nil.
5293 When optional argument N is a positive integer, return a list
5294 containing up to N siblings before BLOB, from farthest to
5295 closest. With any other non-nil value, return a list containing
5296 all of them."
5297 (let* ((secondary (org-element-secondary-p blob))
5298 (parent (org-export-get-parent blob))
5299 (siblings
5300 (if secondary (org-element-property secondary parent)
5301 (org-element-contents parent)))
5302 prev)
5303 (catch 'exit
5304 (dolist (obj (cdr (memq blob (reverse siblings))) prev)
5305 (cond ((memq obj (plist-get info :ignore-list)))
5306 ((null n) (throw 'exit obj))
5307 ((not (wholenump n)) (push obj prev))
5308 ((zerop n) (throw 'exit prev))
5309 (t (cl-decf n) (push obj prev)))))))
5311 (defun org-export-get-next-element (blob info &optional n)
5312 "Return next element or object.
5314 BLOB is an element or object. INFO is a plist used as
5315 a communication channel. Return next exportable element or
5316 object, a string, or nil.
5318 When optional argument N is a positive integer, return a list
5319 containing up to N siblings after BLOB, from closest to farthest.
5320 With any other non-nil value, return a list containing all of
5321 them."
5322 (let* ((secondary (org-element-secondary-p blob))
5323 (parent (org-export-get-parent blob))
5324 (siblings
5325 (cdr (memq blob
5326 (if secondary (org-element-property secondary parent)
5327 (org-element-contents parent)))))
5328 next)
5329 (catch 'exit
5330 (dolist (obj siblings (nreverse next))
5331 (cond ((memq obj (plist-get info :ignore-list)))
5332 ((null n) (throw 'exit obj))
5333 ((not (wholenump n)) (push obj next))
5334 ((zerop n) (throw 'exit (nreverse next)))
5335 (t (cl-decf n) (push obj next)))))))
5338 ;;;; Translation
5340 ;; `org-export-translate' translates a string according to the language
5341 ;; specified by the LANGUAGE keyword. `org-export-dictionary' contains
5342 ;; the dictionary used for the translation.
5344 (defconst org-export-dictionary
5345 '(("%e %n: %c"
5346 ("fr" :default "%e %n : %c" :html "%e&nbsp;%n&nbsp;: %c"))
5347 ("Author"
5348 ("ca" :default "Autor")
5349 ("cs" :default "Autor")
5350 ("da" :default "Forfatter")
5351 ("de" :default "Autor")
5352 ("eo" :html "A&#365;toro")
5353 ("es" :default "Autor")
5354 ("et" :default "Autor")
5355 ("fi" :html "Tekij&auml;")
5356 ("fr" :default "Auteur")
5357 ("hu" :default "Szerz&otilde;")
5358 ("is" :html "H&ouml;fundur")
5359 ("it" :default "Autore")
5360 ("ja" :default "著者" :html "&#33879;&#32773;")
5361 ("nl" :default "Auteur")
5362 ("no" :default "Forfatter")
5363 ("nb" :default "Forfatter")
5364 ("nn" :default "Forfattar")
5365 ("pl" :default "Autor")
5366 ("pt_BR" :default "Autor")
5367 ("ru" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5368 ("sv" :html "F&ouml;rfattare")
5369 ("uk" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5370 ("zh-CN" :html "&#20316;&#32773;" :utf-8 "作者")
5371 ("zh-TW" :html "&#20316;&#32773;" :utf-8 "作者"))
5372 ("Continued from previous page"
5373 ("de" :default "Fortsetzung von vorheriger Seite")
5374 ("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")
5375 ("fr" :default "Suite de la page précédente")
5376 ("it" :default "Continua da pagina precedente")
5377 ("ja" :default "前ページからの続き")
5378 ("nl" :default "Vervolg van vorige pagina")
5379 ("pt" :default "Continuação da página anterior")
5380 ("ru" :html "(&#1055;&#1088;&#1086;&#1076;&#1086;&#1083;&#1078;&#1077;&#1085;&#1080;&#1077;)"
5381 :utf-8 "(Продолжение)"))
5382 ("Continued on next page"
5383 ("de" :default "Fortsetzung nächste Seite")
5384 ("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")
5385 ("fr" :default "Suite page suivante")
5386 ("it" :default "Continua alla pagina successiva")
5387 ("ja" :default "次ページに続く")
5388 ("nl" :default "Vervolg op volgende pagina")
5389 ("pt" :default "Continua na página seguinte")
5390 ("ru" :html "(&#1055;&#1088;&#1086;&#1076;&#1086;&#1083;&#1078;&#1077;&#1085;&#1080;&#1077; &#1089;&#1083;&#1077;&#1076;&#1091;&#1077;&#1090;)"
5391 :utf-8 "(Продолжение следует)"))
5392 ("Date"
5393 ("ca" :default "Data")
5394 ("cs" :default "Datum")
5395 ("da" :default "Dato")
5396 ("de" :default "Datum")
5397 ("eo" :default "Dato")
5398 ("es" :default "Fecha")
5399 ("et" :html "Kuup&#228;ev" :utf-8 "Kuupäev")
5400 ("fi" :html "P&auml;iv&auml;m&auml;&auml;r&auml;")
5401 ("hu" :html "D&aacute;tum")
5402 ("is" :default "Dagsetning")
5403 ("it" :default "Data")
5404 ("ja" :default "日付" :html "&#26085;&#20184;")
5405 ("nl" :default "Datum")
5406 ("no" :default "Dato")
5407 ("nb" :default "Dato")
5408 ("nn" :default "Dato")
5409 ("pl" :default "Data")
5410 ("pt_BR" :default "Data")
5411 ("ru" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5412 ("sv" :default "Datum")
5413 ("uk" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5414 ("zh-CN" :html "&#26085;&#26399;" :utf-8 "日期")
5415 ("zh-TW" :html "&#26085;&#26399;" :utf-8 "日期"))
5416 ("Equation"
5417 ("da" :default "Ligning")
5418 ("de" :default "Gleichung")
5419 ("es" :ascii "Ecuacion" :html "Ecuaci&oacute;n" :default "Ecuación")
5420 ("et" :html "V&#245;rrand" :utf-8 "Võrrand")
5421 ("fr" :ascii "Equation" :default "Équation")
5422 ("ja" :default "方程式")
5423 ("no" :default "Ligning")
5424 ("nb" :default "Ligning")
5425 ("nn" :default "Likning")
5426 ("pt_BR" :html "Equa&ccedil;&atilde;o" :default "Equação" :ascii "Equacao")
5427 ("ru" :html "&#1059;&#1088;&#1072;&#1074;&#1085;&#1077;&#1085;&#1080;&#1077;"
5428 :utf-8 "Уравнение")
5429 ("sv" :default "Ekvation")
5430 ("zh-CN" :html "&#26041;&#31243;" :utf-8 "方程"))
5431 ("Figure"
5432 ("da" :default "Figur")
5433 ("de" :default "Abbildung")
5434 ("es" :default "Figura")
5435 ("et" :default "Joonis")
5436 ("ja" :default "図" :html "&#22259;")
5437 ("no" :default "Illustrasjon")
5438 ("nb" :default "Illustrasjon")
5439 ("nn" :default "Illustrasjon")
5440 ("pt_BR" :default "Figura")
5441 ("ru" :html "&#1056;&#1080;&#1089;&#1091;&#1085;&#1086;&#1082;" :utf-8 "Рисунок")
5442 ("sv" :default "Illustration")
5443 ("zh-CN" :html "&#22270;" :utf-8 "图"))
5444 ("Figure %d:"
5445 ("da" :default "Figur %d")
5446 ("de" :default "Abbildung %d:")
5447 ("es" :default "Figura %d:")
5448 ("et" :default "Joonis %d:")
5449 ("fr" :default "Figure %d :" :html "Figure&nbsp;%d&nbsp;:")
5450 ("ja" :default "図%d: " :html "&#22259;%d: ")
5451 ("no" :default "Illustrasjon %d")
5452 ("nb" :default "Illustrasjon %d")
5453 ("nn" :default "Illustrasjon %d")
5454 ("pt_BR" :default "Figura %d:")
5455 ("ru" :html "&#1056;&#1080;&#1089;. %d.:" :utf-8 "Рис. %d.:")
5456 ("sv" :default "Illustration %d")
5457 ("zh-CN" :html "&#22270;%d&nbsp;" :utf-8 "图%d "))
5458 ("Footnotes"
5459 ("ca" :html "Peus de p&agrave;gina")
5460 ("cs" :default "Pozn\xe1mky pod carou")
5461 ("da" :default "Fodnoter")
5462 ("de" :html "Fu&szlig;noten" :default "Fußnoten")
5463 ("eo" :default "Piednotoj")
5464 ("es" :ascii "Nota al pie de pagina" :html "Nota al pie de p&aacute;gina" :default "Nota al pie de página")
5465 ("et" :html "Allm&#228;rkused" :utf-8 "Allmärkused")
5466 ("fi" :default "Alaviitteet")
5467 ("fr" :default "Notes de bas de page")
5468 ("hu" :html "L&aacute;bjegyzet")
5469 ("is" :html "Aftanm&aacute;lsgreinar")
5470 ("it" :html "Note a pi&egrave; di pagina")
5471 ("ja" :default "脚注" :html "&#33050;&#27880;")
5472 ("nl" :default "Voetnoten")
5473 ("no" :default "Fotnoter")
5474 ("nb" :default "Fotnoter")
5475 ("nn" :default "Fotnotar")
5476 ("pl" :default "Przypis")
5477 ("pt_BR" :html "Notas de Rodap&eacute;" :default "Notas de Rodapé" :ascii "Notas de Rodape")
5478 ("ru" :html "&#1057;&#1085;&#1086;&#1089;&#1082;&#1080;" :utf-8 "Сноски")
5479 ("sv" :default "Fotnoter")
5480 ("uk" :html "&#1055;&#1088;&#1080;&#1084;&#1110;&#1090;&#1082;&#1080;"
5481 :utf-8 "Примітки")
5482 ("zh-CN" :html "&#33050;&#27880;" :utf-8 "脚注")
5483 ("zh-TW" :html "&#33139;&#35387;" :utf-8 "腳註"))
5484 ("List of Listings"
5485 ("da" :default "Programmer")
5486 ("de" :default "Programmauflistungsverzeichnis")
5487 ("es" :ascii "Indice de Listados de programas" :html "&Iacute;ndice de Listados de programas" :default "Índice de Listados de programas")
5488 ("et" :default "Loendite nimekiri")
5489 ("fr" :default "Liste des programmes")
5490 ("ja" :default "ソースコード目次")
5491 ("no" :default "Dataprogrammer")
5492 ("nb" :default "Dataprogrammer")
5493 ("ru" :html "&#1057;&#1087;&#1080;&#1089;&#1086;&#1082; &#1088;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1086;&#1082;"
5494 :utf-8 "Список распечаток")
5495 ("zh-CN" :html "&#20195;&#30721;&#30446;&#24405;" :utf-8 "代码目录"))
5496 ("List of Tables"
5497 ("da" :default "Tabeller")
5498 ("de" :default "Tabellenverzeichnis")
5499 ("es" :ascii "Indice de tablas" :html "&Iacute;ndice de tablas" :default "Índice de tablas")
5500 ("et" :default "Tabelite nimekiri")
5501 ("fr" :default "Liste des tableaux")
5502 ("ja" :default "表目次")
5503 ("no" :default "Tabeller")
5504 ("nb" :default "Tabeller")
5505 ("nn" :default "Tabeller")
5506 ("pt_BR" :default "Índice de Tabelas" :ascii "Indice de Tabelas")
5507 ("ru" :html "&#1057;&#1087;&#1080;&#1089;&#1086;&#1082; &#1090;&#1072;&#1073;&#1083;&#1080;&#1094;"
5508 :utf-8 "Список таблиц")
5509 ("sv" :default "Tabeller")
5510 ("zh-CN" :html "&#34920;&#26684;&#30446;&#24405;" :utf-8 "表格目录"))
5511 ("Listing"
5512 ("da" :default "Program")
5513 ("de" :default "Programmlisting")
5514 ("es" :default "Listado de programa")
5515 ("et" :default "Loend")
5516 ("fr" :default "Programme" :html "Programme")
5517 ("ja" :default "ソースコード")
5518 ("no" :default "Dataprogram")
5519 ("nb" :default "Dataprogram")
5520 ("pt_BR" :default "Listagem")
5521 ("ru" :html "&#1056;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1082;&#1072;"
5522 :utf-8 "Распечатка")
5523 ("zh-CN" :html "&#20195;&#30721;" :utf-8 "代码"))
5524 ("Listing %d:"
5525 ("da" :default "Program %d")
5526 ("de" :default "Programmlisting %d")
5527 ("es" :default "Listado de programa %d")
5528 ("et" :default "Loend %d")
5529 ("fr" :default "Programme %d :" :html "Programme&nbsp;%d&nbsp;:")
5530 ("ja" :default "ソースコード%d:")
5531 ("no" :default "Dataprogram %d")
5532 ("nb" :default "Dataprogram %d")
5533 ("pt_BR" :default "Listagem %d")
5534 ("ru" :html "&#1056;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1082;&#1072; %d.:"
5535 :utf-8 "Распечатка %d.:")
5536 ("zh-CN" :html "&#20195;&#30721;%d&nbsp;" :utf-8 "代码%d "))
5537 ("References"
5538 ("fr" :ascii "References" :default "Références")
5539 ("de" :default "Quellen")
5540 ("es" :default "Referencias"))
5541 ("See section %s"
5542 ("da" :default "jævnfør afsnit %s")
5543 ("de" :default "siehe Abschnitt %s")
5544 ("es" :ascii "Vea seccion %s" :html "Vea secci&oacute;n %s" :default "Vea sección %s")
5545 ("et" :html "Vaata peat&#252;kki %s" :utf-8 "Vaata peatükki %s")
5546 ("fr" :default "cf. section %s")
5547 ("ja" :default "セクション %s を参照")
5548 ("pt_BR" :html "Veja a se&ccedil;&atilde;o %s" :default "Veja a seção %s"
5549 :ascii "Veja a secao %s")
5550 ("ru" :html "&#1057;&#1084;. &#1088;&#1072;&#1079;&#1076;&#1077;&#1083; %s"
5551 :utf-8 "См. раздел %s")
5552 ("zh-CN" :html "&#21442;&#35265;&#31532;%s&#33410;" :utf-8 "参见第%s节"))
5553 ("Table"
5554 ("de" :default "Tabelle")
5555 ("es" :default "Tabla")
5556 ("et" :default "Tabel")
5557 ("fr" :default "Tableau")
5558 ("ja" :default "表" :html "&#34920;")
5559 ("pt_BR" :default "Tabela")
5560 ("ru" :html "&#1058;&#1072;&#1073;&#1083;&#1080;&#1094;&#1072;"
5561 :utf-8 "Таблица")
5562 ("zh-CN" :html "&#34920;" :utf-8 "表"))
5563 ("Table %d:"
5564 ("da" :default "Tabel %d")
5565 ("de" :default "Tabelle %d")
5566 ("es" :default "Tabla %d")
5567 ("et" :default "Tabel %d")
5568 ("fr" :default "Tableau %d :")
5569 ("ja" :default "表%d:" :html "&#34920;%d:")
5570 ("no" :default "Tabell %d")
5571 ("nb" :default "Tabell %d")
5572 ("nn" :default "Tabell %d")
5573 ("pt_BR" :default "Tabela %d")
5574 ("ru" :html "&#1058;&#1072;&#1073;&#1083;&#1080;&#1094;&#1072; %d.:"
5575 :utf-8 "Таблица %d.:")
5576 ("sv" :default "Tabell %d")
5577 ("zh-CN" :html "&#34920;%d&nbsp;" :utf-8 "表%d "))
5578 ("Table of Contents"
5579 ("ca" :html "&Iacute;ndex")
5580 ("cs" :default "Obsah")
5581 ("da" :default "Indhold")
5582 ("de" :default "Inhaltsverzeichnis")
5583 ("eo" :default "Enhavo")
5584 ("es" :ascii "Indice" :html "&Iacute;ndice" :default "Índice")
5585 ("et" :default "Sisukord")
5586 ("fi" :html "Sis&auml;llysluettelo")
5587 ("fr" :ascii "Sommaire" :default "Table des matières")
5588 ("hu" :html "Tartalomjegyz&eacute;k")
5589 ("is" :default "Efnisyfirlit")
5590 ("it" :default "Indice")
5591 ("ja" :default "目次" :html "&#30446;&#27425;")
5592 ("nl" :default "Inhoudsopgave")
5593 ("no" :default "Innhold")
5594 ("nb" :default "Innhold")
5595 ("nn" :default "Innhald")
5596 ("pl" :html "Spis tre&#x015b;ci")
5597 ("pt_BR" :html "&Iacute;ndice" :utf8 "Índice" :ascii "Indice")
5598 ("ru" :html "&#1057;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1077;"
5599 :utf-8 "Содержание")
5600 ("sv" :html "Inneh&aring;ll")
5601 ("uk" :html "&#1047;&#1084;&#1110;&#1089;&#1090;" :utf-8 "Зміст")
5602 ("zh-CN" :html "&#30446;&#24405;" :utf-8 "目录")
5603 ("zh-TW" :html "&#30446;&#37636;" :utf-8 "目錄"))
5604 ("Unknown reference"
5605 ("da" :default "ukendt reference")
5606 ("de" :default "Unbekannter Verweis")
5607 ("es" :default "Referencia desconocida")
5608 ("et" :default "Tundmatu viide")
5609 ("fr" :ascii "Destination inconnue" :default "Référence inconnue")
5610 ("ja" :default "不明な参照先")
5611 ("pt_BR" :default "Referência desconhecida"
5612 :ascii "Referencia desconhecida")
5613 ("ru" :html "&#1053;&#1077;&#1080;&#1079;&#1074;&#1077;&#1089;&#1090;&#1085;&#1072;&#1103; &#1089;&#1089;&#1099;&#1083;&#1082;&#1072;"
5614 :utf-8 "Неизвестная ссылка")
5615 ("zh-CN" :html "&#26410;&#30693;&#24341;&#29992;" :utf-8 "未知引用")))
5616 "Dictionary for export engine.
5618 Alist whose car is the string to translate and cdr is an alist
5619 whose car is the language string and cdr is a plist whose
5620 properties are possible charsets and values translated terms.
5622 It is used as a database for `org-export-translate'. Since this
5623 function returns the string as-is if no translation was found,
5624 the variable only needs to record values different from the
5625 entry.")
5627 (defun org-export-translate (s encoding info)
5628 "Translate string S according to language specification.
5630 ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1'
5631 and `:utf-8'. INFO is a plist used as a communication channel.
5633 Translation depends on `:language' property. Return the
5634 translated string. If no translation is found, try to fall back
5635 to `:default' encoding. If it fails, return S."
5636 (let* ((lang (plist-get info :language))
5637 (translations (cdr (assoc lang
5638 (cdr (assoc s org-export-dictionary))))))
5639 (or (plist-get translations encoding)
5640 (plist-get translations :default)
5641 s)))
5645 ;;; Asynchronous Export
5647 ;; `org-export-async-start' is the entry point for asynchronous
5648 ;; export. It recreates current buffer (including visibility,
5649 ;; narrowing and visited file) in an external Emacs process, and
5650 ;; evaluates a command there. It then applies a function on the
5651 ;; returned results in the current process.
5653 ;; At a higher level, `org-export-to-buffer' and `org-export-to-file'
5654 ;; allow to export to a buffer or a file, asynchronously or not.
5656 ;; `org-export-output-file-name' is an auxiliary function meant to be
5657 ;; used with `org-export-to-file'. With a given extension, it tries
5658 ;; to provide a canonical file name to write export output to.
5660 ;; Asynchronously generated results are never displayed directly.
5661 ;; Instead, they are stored in `org-export-stack-contents'. They can
5662 ;; then be retrieved by calling `org-export-stack'.
5664 ;; Export Stack is viewed through a dedicated major mode
5665 ;;`org-export-stack-mode' and tools: `org-export-stack-refresh',
5666 ;;`org-export-stack-delete', `org-export-stack-view' and
5667 ;;`org-export-stack-clear'.
5669 ;; For back-ends, `org-export-add-to-stack' add a new source to stack.
5670 ;; It should be used whenever `org-export-async-start' is called.
5672 (defmacro org-export-async-start (fun &rest body)
5673 "Call function FUN on the results returned by BODY evaluation.
5675 FUN is an anonymous function of one argument. BODY evaluation
5676 happens in an asynchronous process, from a buffer which is an
5677 exact copy of the current one.
5679 Use `org-export-add-to-stack' in FUN in order to register results
5680 in the stack.
5682 This is a low level function. See also `org-export-to-buffer'
5683 and `org-export-to-file' for more specialized functions."
5684 (declare (indent 1) (debug t))
5685 (org-with-gensyms (process temp-file copy-fun proc-buffer coding)
5686 ;; Write the full sexp evaluating BODY in a copy of the current
5687 ;; buffer to a temporary file, as it may be too long for program
5688 ;; args in `start-process'.
5689 `(with-temp-message "Initializing asynchronous export process"
5690 (let ((,copy-fun (org-export--generate-copy-script (current-buffer)))
5691 (,temp-file (make-temp-file "org-export-process"))
5692 (,coding buffer-file-coding-system))
5693 (with-temp-file ,temp-file
5694 (insert
5695 ;; Null characters (from variable values) are inserted
5696 ;; within the file. As a consequence, coding system for
5697 ;; buffer contents will not be recognized properly. So,
5698 ;; we make sure it is the same as the one used to display
5699 ;; the original buffer.
5700 (format ";; -*- coding: %s; -*-\n%S"
5701 ,coding
5702 `(with-temp-buffer
5703 (when org-export-async-debug '(setq debug-on-error t))
5704 ;; Ignore `kill-emacs-hook' and code evaluation
5705 ;; queries from Babel as we need a truly
5706 ;; non-interactive process.
5707 (setq kill-emacs-hook nil
5708 org-babel-confirm-evaluate-answer-no t)
5709 ;; Initialize export framework.
5710 (require 'ox)
5711 ;; Re-create current buffer there.
5712 (funcall ,,copy-fun)
5713 (restore-buffer-modified-p nil)
5714 ;; Sexp to evaluate in the buffer.
5715 (print (progn ,,@body))))))
5716 ;; Start external process.
5717 (let* ((process-connection-type nil)
5718 (,proc-buffer (generate-new-buffer-name "*Org Export Process*"))
5719 (,process
5720 (apply
5721 #'start-process
5722 (append
5723 (list "org-export-process"
5724 ,proc-buffer
5725 (expand-file-name invocation-name invocation-directory)
5726 "--batch")
5727 (if org-export-async-init-file
5728 (list "-Q" "-l" org-export-async-init-file)
5729 (list "-l" user-init-file))
5730 (list "-l" ,temp-file)))))
5731 ;; Register running process in stack.
5732 (org-export-add-to-stack (get-buffer ,proc-buffer) nil ,process)
5733 ;; Set-up sentinel in order to catch results.
5734 (let ((handler ,fun))
5735 (set-process-sentinel
5736 ,process
5737 `(lambda (p status)
5738 (let ((proc-buffer (process-buffer p)))
5739 (when (eq (process-status p) 'exit)
5740 (unwind-protect
5741 (if (zerop (process-exit-status p))
5742 (unwind-protect
5743 (let ((results
5744 (with-current-buffer proc-buffer
5745 (goto-char (point-max))
5746 (backward-sexp)
5747 (read (current-buffer)))))
5748 (funcall ,handler results))
5749 (unless org-export-async-debug
5750 (and (get-buffer proc-buffer)
5751 (kill-buffer proc-buffer))))
5752 (org-export-add-to-stack proc-buffer nil p)
5753 (ding)
5754 (message "Process '%s' exited abnormally" p))
5755 (unless org-export-async-debug
5756 (delete-file ,,temp-file)))))))))))))
5758 ;;;###autoload
5759 (defun org-export-to-buffer
5760 (backend buffer
5761 &optional async subtreep visible-only body-only ext-plist
5762 post-process)
5763 "Call `org-export-as' with output to a specified buffer.
5765 BACKEND is either an export back-end, as returned by, e.g.,
5766 `org-export-create-backend', or a symbol referring to
5767 a registered back-end.
5769 BUFFER is the name of the output buffer. If it already exists,
5770 it will be erased first, otherwise, it will be created.
5772 A non-nil optional argument ASYNC means the process should happen
5773 asynchronously. The resulting buffer should then be accessible
5774 through the `org-export-stack' interface. When ASYNC is nil, the
5775 buffer is displayed if `org-export-show-temporary-export-buffer'
5776 is non-nil.
5778 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
5779 EXT-PLIST are similar to those used in `org-export-as', which
5780 see.
5782 Optional argument POST-PROCESS is a function which should accept
5783 no argument. It is always called within the current process,
5784 from BUFFER, with point at its beginning. Export back-ends can
5785 use it to set a major mode there, e.g,
5787 \(defun org-latex-export-as-latex
5788 \(&optional async subtreep visible-only body-only ext-plist)
5789 \(interactive)
5790 \(org-export-to-buffer 'latex \"*Org LATEX Export*\"
5791 async subtreep visible-only body-only ext-plist (lambda () (LaTeX-mode))))
5793 This function returns BUFFER."
5794 (declare (indent 2))
5795 (if async
5796 (org-export-async-start
5797 `(lambda (output)
5798 (with-current-buffer (get-buffer-create ,buffer)
5799 (erase-buffer)
5800 (setq buffer-file-coding-system ',buffer-file-coding-system)
5801 (insert output)
5802 (goto-char (point-min))
5803 (org-export-add-to-stack (current-buffer) ',backend)
5804 (ignore-errors (funcall ,post-process))))
5805 `(org-export-as
5806 ',backend ,subtreep ,visible-only ,body-only ',ext-plist))
5807 (let ((output
5808 (org-export-as backend subtreep visible-only body-only ext-plist))
5809 (buffer (get-buffer-create buffer))
5810 (encoding buffer-file-coding-system))
5811 (when (and (org-string-nw-p output) (org-export--copy-to-kill-ring-p))
5812 (org-kill-new output))
5813 (with-current-buffer buffer
5814 (erase-buffer)
5815 (setq buffer-file-coding-system encoding)
5816 (insert output)
5817 (goto-char (point-min))
5818 (and (functionp post-process) (funcall post-process)))
5819 (when org-export-show-temporary-export-buffer
5820 (switch-to-buffer-other-window buffer))
5821 buffer)))
5823 ;;;###autoload
5824 (defun org-export-to-file
5825 (backend file &optional async subtreep visible-only body-only ext-plist
5826 post-process)
5827 "Call `org-export-as' with output to a specified file.
5829 BACKEND is either an export back-end, as returned by, e.g.,
5830 `org-export-create-backend', or a symbol referring to
5831 a registered back-end. FILE is the name of the output file, as
5832 a string.
5834 A non-nil optional argument ASYNC means the process should happen
5835 asynchronously. The resulting buffer will then be accessible
5836 through the `org-export-stack' interface.
5838 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
5839 EXT-PLIST are similar to those used in `org-export-as', which
5840 see.
5842 Optional argument POST-PROCESS is called with FILE as its
5843 argument and happens asynchronously when ASYNC is non-nil. It
5844 has to return a file name, or nil. Export back-ends can use this
5845 to send the output file through additional processing, e.g,
5847 \(defun org-latex-export-to-latex
5848 \(&optional async subtreep visible-only body-only ext-plist)
5849 \(interactive)
5850 \(let ((outfile (org-export-output-file-name \".tex\" subtreep)))
5851 \(org-export-to-file 'latex outfile
5852 async subtreep visible-only body-only ext-plist
5853 \(lambda (file) (org-latex-compile file)))
5855 The function returns either a file name returned by POST-PROCESS,
5856 or FILE."
5857 (declare (indent 2))
5858 (if (not (file-writable-p file)) (error "Output file not writable")
5859 (let ((ext-plist (org-combine-plists `(:output-file ,file) ext-plist))
5860 (encoding (or org-export-coding-system buffer-file-coding-system)))
5861 (if async
5862 (org-export-async-start
5863 `(lambda (file)
5864 (org-export-add-to-stack (expand-file-name file) ',backend))
5865 `(let ((output
5866 (org-export-as
5867 ',backend ,subtreep ,visible-only ,body-only
5868 ',ext-plist)))
5869 (with-temp-buffer
5870 (insert output)
5871 (let ((coding-system-for-write ',encoding))
5872 (write-file ,file)))
5873 (or (ignore-errors (funcall ',post-process ,file)) ,file)))
5874 (let ((output (org-export-as
5875 backend subtreep visible-only body-only ext-plist)))
5876 (with-temp-buffer
5877 (insert output)
5878 (let ((coding-system-for-write encoding))
5879 (write-file file)))
5880 (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p output))
5881 (org-kill-new output))
5882 ;; Get proper return value.
5883 (or (and (functionp post-process) (funcall post-process file))
5884 file))))))
5886 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
5887 "Return output file's name according to buffer specifications.
5889 EXTENSION is a string representing the output file extension,
5890 with the leading dot.
5892 With a non-nil optional argument SUBTREEP, try to determine
5893 output file's name by looking for \"EXPORT_FILE_NAME\" property
5894 of subtree at point.
5896 When optional argument PUB-DIR is set, use it as the publishing
5897 directory.
5899 Return file name as a string."
5900 (let* ((visited-file (buffer-file-name (buffer-base-buffer)))
5901 (base-name
5902 ;; File name may come from EXPORT_FILE_NAME subtree
5903 ;; property, assuming point is at beginning of said
5904 ;; sub-tree.
5905 (file-name-sans-extension
5906 (or (and subtreep
5907 (org-entry-get
5908 (save-excursion
5909 (ignore-errors (org-back-to-heading) (point)))
5910 "EXPORT_FILE_NAME" t))
5911 ;; File name may be extracted from buffer's associated
5912 ;; file, if any.
5913 (and visited-file (file-name-nondirectory visited-file))
5914 ;; Can't determine file name on our own: Ask user.
5915 (let ((read-file-name-function
5916 (and org-completion-use-ido 'ido-read-file-name)))
5917 (read-file-name
5918 "Output file: " pub-dir nil nil nil
5919 (lambda (name)
5920 (string= (file-name-extension name t) extension)))))))
5921 (output-file
5922 ;; Build file name. Enforce EXTENSION over whatever user
5923 ;; may have come up with. PUB-DIR, if defined, always has
5924 ;; precedence over any provided path.
5925 (cond
5926 (pub-dir
5927 (concat (file-name-as-directory pub-dir)
5928 (file-name-nondirectory base-name)
5929 extension))
5930 ((file-name-absolute-p base-name) (concat base-name extension))
5931 (t (concat (file-name-as-directory ".") base-name extension)))))
5932 ;; If writing to OUTPUT-FILE would overwrite original file, append
5933 ;; EXTENSION another time to final name.
5934 (if (and visited-file (org-file-equal-p visited-file output-file))
5935 (concat output-file extension)
5936 output-file)))
5938 (defun org-export-add-to-stack (source backend &optional process)
5939 "Add a new result to export stack if not present already.
5941 SOURCE is a buffer or a file name containing export results.
5942 BACKEND is a symbol representing export back-end used to generate
5945 Entries already pointing to SOURCE and unavailable entries are
5946 removed beforehand. Return the new stack."
5947 (setq org-export-stack-contents
5948 (cons (list source backend (or process (current-time)))
5949 (org-export-stack-remove source))))
5951 (defun org-export-stack ()
5952 "Menu for asynchronous export results and running processes."
5953 (interactive)
5954 (let ((buffer (get-buffer-create "*Org Export Stack*")))
5955 (set-buffer buffer)
5956 (when (zerop (buffer-size)) (org-export-stack-mode))
5957 (org-export-stack-refresh)
5958 (pop-to-buffer buffer))
5959 (message "Type \"q\" to quit, \"?\" for help"))
5961 (defun org-export--stack-source-at-point ()
5962 "Return source from export results at point in stack."
5963 (let ((source (car (nth (1- (org-current-line)) org-export-stack-contents))))
5964 (if (not source) (error "Source unavailable, please refresh buffer")
5965 (let ((source-name (if (stringp source) source (buffer-name source))))
5966 (if (save-excursion
5967 (beginning-of-line)
5968 (looking-at (concat ".* +" (regexp-quote source-name) "$")))
5969 source
5970 ;; SOURCE is not consistent with current line. The stack
5971 ;; view is outdated.
5972 (error "Source unavailable; type `g' to update buffer"))))))
5974 (defun org-export-stack-clear ()
5975 "Remove all entries from export stack."
5976 (interactive)
5977 (setq org-export-stack-contents nil))
5979 (defun org-export-stack-refresh (&rest _)
5980 "Refresh the asynchronous export stack.
5981 Unavailable sources are removed from the list. Return the new
5982 stack."
5983 (let ((inhibit-read-only t))
5984 (org-preserve-lc
5985 (erase-buffer)
5986 (insert (concat
5987 (mapconcat
5988 (lambda (entry)
5989 (let ((proc-p (processp (nth 2 entry))))
5990 (concat
5991 ;; Back-end.
5992 (format " %-12s " (or (nth 1 entry) ""))
5993 ;; Age.
5994 (let ((data (nth 2 entry)))
5995 (if proc-p (format " %6s " (process-status data))
5996 ;; Compute age of the results.
5997 (org-format-seconds
5998 "%4h:%.2m "
5999 (float-time (time-since data)))))
6000 ;; Source.
6001 (format " %s"
6002 (let ((source (car entry)))
6003 (if (stringp source) source
6004 (buffer-name source)))))))
6005 ;; Clear stack from exited processes, dead buffers or
6006 ;; non-existent files.
6007 (setq org-export-stack-contents
6008 (org-remove-if-not
6009 (lambda (el)
6010 (if (processp (nth 2 el))
6011 (buffer-live-p (process-buffer (nth 2 el)))
6012 (let ((source (car el)))
6013 (if (bufferp source) (buffer-live-p source)
6014 (file-exists-p source)))))
6015 org-export-stack-contents)) "\n"))))))
6017 (defun org-export-stack-remove (&optional source)
6018 "Remove export results at point from stack.
6019 If optional argument SOURCE is non-nil, remove it instead."
6020 (interactive)
6021 (let ((source (or source (org-export--stack-source-at-point))))
6022 (setq org-export-stack-contents
6023 (org-remove-if (lambda (el) (equal (car el) source))
6024 org-export-stack-contents))))
6026 (defun org-export-stack-view (&optional in-emacs)
6027 "View export results at point in stack.
6028 With an optional prefix argument IN-EMACS, force viewing files
6029 within Emacs."
6030 (interactive "P")
6031 (let ((source (org-export--stack-source-at-point)))
6032 (cond ((processp source)
6033 (org-switch-to-buffer-other-window (process-buffer source)))
6034 ((bufferp source) (org-switch-to-buffer-other-window source))
6035 (t (org-open-file source in-emacs)))))
6037 (defvar org-export-stack-mode-map
6038 (let ((km (make-sparse-keymap)))
6039 (define-key km " " 'next-line)
6040 (define-key km "n" 'next-line)
6041 (define-key km "\C-n" 'next-line)
6042 (define-key km [down] 'next-line)
6043 (define-key km "p" 'previous-line)
6044 (define-key km "\C-p" 'previous-line)
6045 (define-key km "\C-?" 'previous-line)
6046 (define-key km [up] 'previous-line)
6047 (define-key km "C" 'org-export-stack-clear)
6048 (define-key km "v" 'org-export-stack-view)
6049 (define-key km (kbd "RET") 'org-export-stack-view)
6050 (define-key km "d" 'org-export-stack-remove)
6052 "Keymap for Org Export Stack.")
6054 (define-derived-mode org-export-stack-mode special-mode "Org-Stack"
6055 "Mode for displaying asynchronous export stack.
6057 Type \\[org-export-stack] to visualize the asynchronous export
6058 stack.
6060 In an Org Export Stack buffer, use \\<org-export-stack-mode-map>\\[org-export-stack-view] to view export output
6061 on current line, \\[org-export-stack-remove] to remove it from the stack and \\[org-export-stack-clear] to clear
6062 stack completely.
6064 Removing entries in an Org Export Stack buffer doesn't affect
6065 files or buffers, only the display.
6067 \\{org-export-stack-mode-map}"
6068 (abbrev-mode 0)
6069 (auto-fill-mode 0)
6070 (setq buffer-read-only t
6071 buffer-undo-list t
6072 truncate-lines t
6073 header-line-format
6074 '(:eval
6075 (format " %-12s | %6s | %s" "Back-End" "Age" "Source")))
6076 (org-add-hook 'post-command-hook 'org-export-stack-refresh nil t)
6077 (set (make-local-variable 'revert-buffer-function)
6078 'org-export-stack-refresh))
6082 ;;; The Dispatcher
6084 ;; `org-export-dispatch' is the standard interactive way to start an
6085 ;; export process. It uses `org-export--dispatch-ui' as a subroutine
6086 ;; for its interface, which, in turn, delegates response to key
6087 ;; pressed to `org-export--dispatch-action'.
6089 ;;;###autoload
6090 (defun org-export-dispatch (&optional arg)
6091 "Export dispatcher for Org mode.
6093 It provides an access to common export related tasks in a buffer.
6094 Its interface comes in two flavors: standard and expert.
6096 While both share the same set of bindings, only the former
6097 displays the valid keys associations in a dedicated buffer.
6098 Scrolling (resp. line-wise motion) in this buffer is done with
6099 SPC and DEL (resp. C-n and C-p) keys.
6101 Set variable `org-export-dispatch-use-expert-ui' to switch to one
6102 flavor or the other.
6104 When ARG is \\[universal-argument], repeat the last export action, with the same set
6105 of options used back then, on the current buffer.
6107 When ARG is \\[universal-argument] \\[universal-argument], display the asynchronous export stack."
6108 (interactive "P")
6109 (let* ((input
6110 (cond ((equal arg '(16)) '(stack))
6111 ((and arg org-export-dispatch-last-action))
6112 (t (save-window-excursion
6113 (unwind-protect
6114 (progn
6115 ;; Remember where we are
6116 (move-marker org-export-dispatch-last-position
6117 (point)
6118 (org-base-buffer (current-buffer)))
6119 ;; Get and store an export command
6120 (setq org-export-dispatch-last-action
6121 (org-export--dispatch-ui
6122 (list org-export-initial-scope
6123 (and org-export-in-background 'async))
6125 org-export-dispatch-use-expert-ui)))
6126 (and (get-buffer "*Org Export Dispatcher*")
6127 (kill-buffer "*Org Export Dispatcher*")))))))
6128 (action (car input))
6129 (optns (cdr input)))
6130 (unless (memq 'subtree optns)
6131 (move-marker org-export-dispatch-last-position nil))
6132 (cl-case action
6133 ;; First handle special hard-coded actions.
6134 (template (org-export-insert-default-template nil optns))
6135 (stack (org-export-stack))
6136 (publish-current-file
6137 (org-publish-current-file (memq 'force optns) (memq 'async optns)))
6138 (publish-current-project
6139 (org-publish-current-project (memq 'force optns) (memq 'async optns)))
6140 (publish-choose-project
6141 (org-publish (assoc (org-icompleting-read
6142 "Publish project: "
6143 org-publish-project-alist nil t)
6144 org-publish-project-alist)
6145 (memq 'force optns)
6146 (memq 'async optns)))
6147 (publish-all (org-publish-all (memq 'force optns) (memq 'async optns)))
6148 (otherwise
6149 (save-excursion
6150 (when arg
6151 ;; Repeating command, maybe move cursor to restore subtree
6152 ;; context.
6153 (if (eq (marker-buffer org-export-dispatch-last-position)
6154 (org-base-buffer (current-buffer)))
6155 (goto-char org-export-dispatch-last-position)
6156 ;; We are in a different buffer, forget position.
6157 (move-marker org-export-dispatch-last-position nil)))
6158 (funcall action
6159 ;; Return a symbol instead of a list to ease
6160 ;; asynchronous export macro use.
6161 (and (memq 'async optns) t)
6162 (and (memq 'subtree optns) t)
6163 (and (memq 'visible optns) t)
6164 (and (memq 'body optns) t)))))))
6166 (defun org-export--dispatch-ui (options first-key expertp)
6167 "Handle interface for `org-export-dispatch'.
6169 OPTIONS is a list containing current interactive options set for
6170 export. It can contain any of the following symbols:
6171 `body' toggles a body-only export
6172 `subtree' restricts export to current subtree
6173 `visible' restricts export to visible part of buffer.
6174 `force' force publishing files.
6175 `async' use asynchronous export process
6177 FIRST-KEY is the key pressed to select the first level menu. It
6178 is nil when this menu hasn't been selected yet.
6180 EXPERTP, when non-nil, triggers expert UI. In that case, no help
6181 buffer is provided, but indications about currently active
6182 options are given in the prompt. Moreover, \[?] allows to switch
6183 back to standard interface."
6184 (let* ((fontify-key
6185 (lambda (key &optional access-key)
6186 ;; Fontify KEY string. Optional argument ACCESS-KEY, when
6187 ;; non-nil is the required first-level key to activate
6188 ;; KEY. When its value is t, activate KEY independently
6189 ;; on the first key, if any. A nil value means KEY will
6190 ;; only be activated at first level.
6191 (if (or (eq access-key t) (eq access-key first-key))
6192 (org-propertize key 'face 'org-warning)
6193 key)))
6194 (fontify-value
6195 (lambda (value)
6196 ;; Fontify VALUE string.
6197 (org-propertize value 'face 'font-lock-variable-name-face)))
6198 ;; Prepare menu entries by extracting them from registered
6199 ;; back-ends and sorting them by access key and by ordinal,
6200 ;; if any.
6201 (entries
6202 (sort (sort (delq nil
6203 (mapcar #'org-export-backend-menu
6204 org-export-registered-backends))
6205 (lambda (a b)
6206 (let ((key-a (nth 1 a))
6207 (key-b (nth 1 b)))
6208 (cond ((and (numberp key-a) (numberp key-b))
6209 (< key-a key-b))
6210 ((numberp key-b) t)))))
6211 'car-less-than-car))
6212 ;; Compute a list of allowed keys based on the first key
6213 ;; pressed, if any. Some keys
6214 ;; (?^B, ?^V, ?^S, ?^F, ?^A, ?&, ?# and ?q) are always
6215 ;; available.
6216 (allowed-keys
6217 (nconc (list 2 22 19 6 1)
6218 (if (not first-key) (org-uniquify (mapcar 'car entries))
6219 (let (sub-menu)
6220 (dolist (entry entries (sort (mapcar 'car sub-menu) '<))
6221 (when (eq (car entry) first-key)
6222 (setq sub-menu (append (nth 2 entry) sub-menu))))))
6223 (cond ((eq first-key ?P) (list ?f ?p ?x ?a))
6224 ((not first-key) (list ?P)))
6225 (list ?& ?#)
6226 (when expertp (list ??))
6227 (list ?q)))
6228 ;; Build the help menu for standard UI.
6229 (help
6230 (unless expertp
6231 (concat
6232 ;; Options are hard-coded.
6233 (format "[%s] Body only: %s [%s] Visible only: %s
6234 \[%s] Export scope: %s [%s] Force publishing: %s
6235 \[%s] Async export: %s\n\n"
6236 (funcall fontify-key "C-b" t)
6237 (funcall fontify-value
6238 (if (memq 'body options) "On " "Off"))
6239 (funcall fontify-key "C-v" t)
6240 (funcall fontify-value
6241 (if (memq 'visible options) "On " "Off"))
6242 (funcall fontify-key "C-s" t)
6243 (funcall fontify-value
6244 (if (memq 'subtree options) "Subtree" "Buffer "))
6245 (funcall fontify-key "C-f" t)
6246 (funcall fontify-value
6247 (if (memq 'force options) "On " "Off"))
6248 (funcall fontify-key "C-a" t)
6249 (funcall fontify-value
6250 (if (memq 'async options) "On " "Off")))
6251 ;; Display registered back-end entries. When a key
6252 ;; appears for the second time, do not create another
6253 ;; entry, but append its sub-menu to existing menu.
6254 (let (last-key)
6255 (mapconcat
6256 (lambda (entry)
6257 (let ((top-key (car entry)))
6258 (concat
6259 (unless (eq top-key last-key)
6260 (setq last-key top-key)
6261 (format "\n[%s] %s\n"
6262 (funcall fontify-key (char-to-string top-key))
6263 (nth 1 entry)))
6264 (let ((sub-menu (nth 2 entry)))
6265 (unless (functionp sub-menu)
6266 ;; Split sub-menu into two columns.
6267 (let ((index -1))
6268 (concat
6269 (mapconcat
6270 (lambda (sub-entry)
6271 (cl-incf index)
6272 (format
6273 (if (zerop (mod index 2)) " [%s] %-26s"
6274 "[%s] %s\n")
6275 (funcall fontify-key
6276 (char-to-string (car sub-entry))
6277 top-key)
6278 (nth 1 sub-entry)))
6279 sub-menu "")
6280 (when (zerop (mod index 2)) "\n"))))))))
6281 entries ""))
6282 ;; Publishing menu is hard-coded.
6283 (format "\n[%s] Publish
6284 [%s] Current file [%s] Current project
6285 [%s] Choose project [%s] All projects\n\n\n"
6286 (funcall fontify-key "P")
6287 (funcall fontify-key "f" ?P)
6288 (funcall fontify-key "p" ?P)
6289 (funcall fontify-key "x" ?P)
6290 (funcall fontify-key "a" ?P))
6291 (format "[%s] Export stack [%s] Insert template\n"
6292 (funcall fontify-key "&" t)
6293 (funcall fontify-key "#" t))
6294 (format "[%s] %s"
6295 (funcall fontify-key "q" t)
6296 (if first-key "Main menu" "Exit")))))
6297 ;; Build prompts for both standard and expert UI.
6298 (standard-prompt (unless expertp "Export command: "))
6299 (expert-prompt
6300 (when expertp
6301 (format
6302 "Export command (C-%s%s%s%s%s) [%s]: "
6303 (if (memq 'body options) (funcall fontify-key "b" t) "b")
6304 (if (memq 'visible options) (funcall fontify-key "v" t) "v")
6305 (if (memq 'subtree options) (funcall fontify-key "s" t) "s")
6306 (if (memq 'force options) (funcall fontify-key "f" t) "f")
6307 (if (memq 'async options) (funcall fontify-key "a" t) "a")
6308 (mapconcat (lambda (k)
6309 ;; Strip control characters.
6310 (unless (< k 27) (char-to-string k)))
6311 allowed-keys "")))))
6312 ;; With expert UI, just read key with a fancy prompt. In standard
6313 ;; UI, display an intrusive help buffer.
6314 (if expertp
6315 (org-export--dispatch-action
6316 expert-prompt allowed-keys entries options first-key expertp)
6317 ;; At first call, create frame layout in order to display menu.
6318 (unless (get-buffer "*Org Export Dispatcher*")
6319 (delete-other-windows)
6320 (org-switch-to-buffer-other-window
6321 (get-buffer-create "*Org Export Dispatcher*"))
6322 (setq cursor-type nil
6323 header-line-format "Use SPC, DEL, C-n or C-p to navigate.")
6324 ;; Make sure that invisible cursor will not highlight square
6325 ;; brackets.
6326 (set-syntax-table (copy-syntax-table))
6327 (modify-syntax-entry ?\[ "w"))
6328 ;; At this point, the buffer containing the menu exists and is
6329 ;; visible in the current window. So, refresh it.
6330 (with-current-buffer "*Org Export Dispatcher*"
6331 ;; Refresh help. Maintain display continuity by re-visiting
6332 ;; previous window position.
6333 (let ((pos (window-start)))
6334 (erase-buffer)
6335 (insert help)
6336 (set-window-start nil pos)))
6337 (org-fit-window-to-buffer)
6338 (org-export--dispatch-action
6339 standard-prompt allowed-keys entries options first-key expertp))))
6341 (defun org-export--dispatch-action
6342 (prompt allowed-keys entries options first-key expertp)
6343 "Read a character from command input and act accordingly.
6345 PROMPT is the displayed prompt, as a string. ALLOWED-KEYS is
6346 a list of characters available at a given step in the process.
6347 ENTRIES is a list of menu entries. OPTIONS, FIRST-KEY and
6348 EXPERTP are the same as defined in `org-export--dispatch-ui',
6349 which see.
6351 Toggle export options when required. Otherwise, return value is
6352 a list with action as CAR and a list of interactive export
6353 options as CDR."
6354 (let (key)
6355 ;; Scrolling: when in non-expert mode, act on motion keys (C-n,
6356 ;; C-p, SPC, DEL).
6357 (while (and (setq key (read-char-exclusive prompt))
6358 (not expertp)
6359 (memq key '(14 16 ?\s ?\d)))
6360 (cl-case key
6361 (14 (if (not (pos-visible-in-window-p (point-max)))
6362 (ignore-errors (scroll-up 1))
6363 (message "End of buffer")
6364 (sit-for 1)))
6365 (16 (if (not (pos-visible-in-window-p (point-min)))
6366 (ignore-errors (scroll-down 1))
6367 (message "Beginning of buffer")
6368 (sit-for 1)))
6369 (?\s (if (not (pos-visible-in-window-p (point-max)))
6370 (scroll-up nil)
6371 (message "End of buffer")
6372 (sit-for 1)))
6373 (?\d (if (not (pos-visible-in-window-p (point-min)))
6374 (scroll-down nil)
6375 (message "Beginning of buffer")
6376 (sit-for 1)))))
6377 (cond
6378 ;; Ignore undefined associations.
6379 ((not (memq key allowed-keys))
6380 (ding)
6381 (unless expertp (message "Invalid key") (sit-for 1))
6382 (org-export--dispatch-ui options first-key expertp))
6383 ;; q key at first level aborts export. At second level, cancel
6384 ;; first key instead.
6385 ((eq key ?q) (if (not first-key) (error "Export aborted")
6386 (org-export--dispatch-ui options nil expertp)))
6387 ;; Help key: Switch back to standard interface if expert UI was
6388 ;; active.
6389 ((eq key ??) (org-export--dispatch-ui options first-key nil))
6390 ;; Send request for template insertion along with export scope.
6391 ((eq key ?#) (cons 'template (memq 'subtree options)))
6392 ;; Switch to asynchronous export stack.
6393 ((eq key ?&) '(stack))
6394 ;; Toggle options: C-b (2) C-v (22) C-s (19) C-f (6) C-a (1).
6395 ((memq key '(2 22 19 6 1))
6396 (org-export--dispatch-ui
6397 (let ((option (cl-case key (2 'body) (22 'visible) (19 'subtree)
6398 (6 'force) (1 'async))))
6399 (if (memq option options) (remq option options)
6400 (cons option options)))
6401 first-key expertp))
6402 ;; Action selected: Send key and options back to
6403 ;; `org-export-dispatch'.
6404 ((or first-key (functionp (nth 2 (assq key entries))))
6405 (cons (cond
6406 ((not first-key) (nth 2 (assq key entries)))
6407 ;; Publishing actions are hard-coded. Send a special
6408 ;; signal to `org-export-dispatch'.
6409 ((eq first-key ?P)
6410 (cl-case key
6411 (?f 'publish-current-file)
6412 (?p 'publish-current-project)
6413 (?x 'publish-choose-project)
6414 (?a 'publish-all)))
6415 ;; Return first action associated to FIRST-KEY + KEY
6416 ;; path. Indeed, derived backends can share the same
6417 ;; FIRST-KEY.
6418 (t (catch 'found
6419 (mapc (lambda (entry)
6420 (let ((match (assq key (nth 2 entry))))
6421 (when match (throw 'found (nth 2 match)))))
6422 (member (assq first-key entries) entries)))))
6423 options))
6424 ;; Otherwise, enter sub-menu.
6425 (t (org-export--dispatch-ui options key expertp)))))
6429 (provide 'ox)
6431 ;; Local variables:
6432 ;; generated-autoload-file: "org-loaddefs.el"
6433 ;; End:
6435 ;;; ox.el ends here