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