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