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