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