ox: New smart quote algorithm
[org-mode.git] / lisp / ox.el
blobcb2c903bae8baee7ae4fdf84fdd94ec1dc2d1f12
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 space)
102 (:date "DATE" nil nil t)
103 (:author "AUTHOR" nil user-full-name t)
104 (:email "EMAIL" nil user-mail-address t)
105 (:description "DESCRIPTION" nil nil newline)
106 (:keywords "KEYWORDS" nil nil space)
107 (:language "LANGUAGE" nil org-export-default-language t)
108 (:select-tags "SELECT_TAGS" nil org-export-select-tags split)
109 (:exclude-tags "EXCLUDE_TAGS" nil org-export-exclude-tags split)
110 (:creator "CREATOR" nil org-export-creator-string)
111 (:headline-levels nil "H" org-export-headline-levels)
112 (:preserve-breaks nil "\\n" org-export-preserve-breaks)
113 (:section-numbers nil "num" org-export-with-section-numbers)
114 (:time-stamp-file nil "timestamp" org-export-time-stamp-file)
115 (:with-archived-trees nil "arch" org-export-with-archived-trees)
116 (:with-author nil "author" org-export-with-author)
117 (:with-clocks nil "c" org-export-with-clocks)
118 (:with-creator nil "creator" org-export-with-creator)
119 (:with-date nil "date" org-export-with-date)
120 (:with-drawers nil "d" org-export-with-drawers)
121 (:with-email nil "email" org-export-with-email)
122 (:with-emphasize nil "*" org-export-with-emphasize)
123 (:with-entities nil "e" org-export-with-entities)
124 (:with-fixed-width nil ":" org-export-with-fixed-width)
125 (:with-footnotes nil "f" org-export-with-footnotes)
126 (:with-inlinetasks nil "inline" org-export-with-inlinetasks)
127 (:with-latex nil "tex" org-export-with-latex)
128 (:with-planning nil "p" org-export-with-planning)
129 (:with-priority nil "pri" org-export-with-priority)
130 (:with-properties nil "prop" org-export-with-properties)
131 (:with-smart-quotes nil "'" org-export-with-smart-quotes)
132 (:with-special-strings nil "-" org-export-with-special-strings)
133 (:with-statistics-cookies nil "stat" org-export-with-statistics-cookies)
134 (:with-sub-superscript nil "^" org-export-with-sub-superscripts)
135 (:with-toc nil "toc" org-export-with-toc)
136 (:with-tables nil "|" org-export-with-tables)
137 (:with-tags nil "tags" org-export-with-tags)
138 (:with-tasks nil "tasks" org-export-with-tasks)
139 (:with-timestamps nil "<" org-export-with-timestamps)
140 (:with-title nil "title" org-export-with-title)
141 (:with-todo-keywords nil "todo" org-export-with-todo-keywords))
142 "Alist between export properties and ways to set them.
144 The CAR of the alist is the property name, and the CDR is a list
145 like (KEYWORD OPTION DEFAULT BEHAVIOR) where:
147 KEYWORD is a string representing a buffer keyword, or nil. Each
148 property defined this way can also be set, during subtree
149 export, through a headline property named after the keyword
150 with the \"EXPORT_\" prefix (i.e. DATE keyword and EXPORT_DATE
151 property).
152 OPTION is a string that could be found in an #+OPTIONS: line.
153 DEFAULT is the default value for the property.
154 BEHAVIOR determines how Org should handle multiple keywords for
155 the same property. It is a symbol among:
156 nil Keep old value and discard the new one.
157 t Replace old value with the new one.
158 `space' Concatenate the values, separating them with a space.
159 `newline' Concatenate the values, separating them with
160 a newline.
161 `split' Split values at white spaces, and cons them to the
162 previous list.
164 Values set through KEYWORD and OPTION have precedence over
165 DEFAULT.
167 All these properties should be back-end agnostic. Back-end
168 specific properties are set through `org-export-define-backend'.
169 Properties redefined there have precedence over these.")
171 (defconst org-export-special-keywords '("FILETAGS" "SETUPFILE" "OPTIONS")
172 "List of in-buffer keywords that require special treatment.
173 These keywords are not directly associated to a property. The
174 way they are handled must be hard-coded into
175 `org-export--get-inbuffer-options' function.")
177 (defconst org-export-document-properties
178 (delq nil
179 (mapcar (lambda (option)
180 (and (member (nth 1 option) org-element-document-properties)
181 (car option)))
182 org-export-options-alist))
183 "List of properties containing parsed data.")
185 (defconst org-export-filters-alist
186 '((:filter-body . org-export-filter-body-functions)
187 (:filter-bold . org-export-filter-bold-functions)
188 (:filter-babel-call . org-export-filter-babel-call-functions)
189 (:filter-center-block . org-export-filter-center-block-functions)
190 (:filter-clock . org-export-filter-clock-functions)
191 (:filter-code . org-export-filter-code-functions)
192 (:filter-diary-sexp . org-export-filter-diary-sexp-functions)
193 (:filter-drawer . org-export-filter-drawer-functions)
194 (:filter-dynamic-block . org-export-filter-dynamic-block-functions)
195 (:filter-entity . org-export-filter-entity-functions)
196 (:filter-example-block . org-export-filter-example-block-functions)
197 (:filter-export-block . org-export-filter-export-block-functions)
198 (:filter-export-snippet . org-export-filter-export-snippet-functions)
199 (:filter-final-output . org-export-filter-final-output-functions)
200 (:filter-fixed-width . org-export-filter-fixed-width-functions)
201 (:filter-footnote-definition . org-export-filter-footnote-definition-functions)
202 (:filter-footnote-reference . org-export-filter-footnote-reference-functions)
203 (:filter-headline . org-export-filter-headline-functions)
204 (:filter-horizontal-rule . org-export-filter-horizontal-rule-functions)
205 (:filter-inline-babel-call . org-export-filter-inline-babel-call-functions)
206 (:filter-inline-src-block . org-export-filter-inline-src-block-functions)
207 (:filter-inlinetask . org-export-filter-inlinetask-functions)
208 (:filter-italic . org-export-filter-italic-functions)
209 (:filter-item . org-export-filter-item-functions)
210 (:filter-keyword . org-export-filter-keyword-functions)
211 (:filter-latex-environment . org-export-filter-latex-environment-functions)
212 (:filter-latex-fragment . org-export-filter-latex-fragment-functions)
213 (:filter-line-break . org-export-filter-line-break-functions)
214 (:filter-link . org-export-filter-link-functions)
215 (:filter-node-property . org-export-filter-node-property-functions)
216 (:filter-options . org-export-filter-options-functions)
217 (:filter-paragraph . org-export-filter-paragraph-functions)
218 (:filter-parse-tree . org-export-filter-parse-tree-functions)
219 (:filter-plain-list . org-export-filter-plain-list-functions)
220 (:filter-plain-text . org-export-filter-plain-text-functions)
221 (:filter-planning . org-export-filter-planning-functions)
222 (:filter-property-drawer . org-export-filter-property-drawer-functions)
223 (:filter-quote-block . org-export-filter-quote-block-functions)
224 (:filter-radio-target . org-export-filter-radio-target-functions)
225 (:filter-section . org-export-filter-section-functions)
226 (:filter-special-block . org-export-filter-special-block-functions)
227 (:filter-src-block . org-export-filter-src-block-functions)
228 (:filter-statistics-cookie . org-export-filter-statistics-cookie-functions)
229 (:filter-strike-through . org-export-filter-strike-through-functions)
230 (:filter-subscript . org-export-filter-subscript-functions)
231 (:filter-superscript . org-export-filter-superscript-functions)
232 (:filter-table . org-export-filter-table-functions)
233 (:filter-table-cell . org-export-filter-table-cell-functions)
234 (:filter-table-row . org-export-filter-table-row-functions)
235 (:filter-target . org-export-filter-target-functions)
236 (:filter-timestamp . org-export-filter-timestamp-functions)
237 (:filter-underline . org-export-filter-underline-functions)
238 (:filter-verbatim . org-export-filter-verbatim-functions)
239 (:filter-verse-block . org-export-filter-verse-block-functions))
240 "Alist between filters properties and initial values.
242 The key of each association is a property name accessible through
243 the communication channel. Its value is a configurable global
244 variable defining initial filters.
246 This list is meant to install user specified filters. Back-end
247 developers may install their own filters using
248 `org-export-define-backend'. Filters defined there will always
249 be prepended to the current list, so they always get applied
250 first.")
252 (defconst org-export-default-inline-image-rule
253 `(("file" .
254 ,(format "\\.%s\\'"
255 (regexp-opt
256 '("png" "jpeg" "jpg" "gif" "tiff" "tif" "xbm"
257 "xpm" "pbm" "pgm" "ppm") t))))
258 "Default rule for link matching an inline image.
259 This rule applies to links with no description. By default, it
260 will be considered as an inline image if it targets a local file
261 whose extension is either \"png\", \"jpeg\", \"jpg\", \"gif\",
262 \"tiff\", \"tif\", \"xbm\", \"xpm\", \"pbm\", \"pgm\" or \"ppm\".
263 See `org-export-inline-image-p' for more information about
264 rules.")
266 (defconst org-export-ignored-local-variables
267 '(org-font-lock-keywords
268 org-element--cache org-element--cache-objects org-element--cache-sync-keys
269 org-element--cache-sync-requests org-element--cache-sync-timer)
270 "List of variables not copied through upon buffer duplication.
271 Export process takes place on a copy of the original buffer.
272 When this copy is created, all Org related local variables not in
273 this list are copied to the new buffer. Variables with an
274 unreadable value are also ignored.")
276 (defvar org-export-async-debug nil
277 "Non-nil means asynchronous export process should leave data behind.
279 This data is found in the appropriate \"*Org Export Process*\"
280 buffer, and in files prefixed with \"org-export-process\" and
281 located in `temporary-file-directory'.
283 When non-nil, it will also set `debug-on-error' to a non-nil
284 value in the external process.")
286 (defvar org-export-stack-contents nil
287 "Record asynchronously generated export results and processes.
288 This is an alist: its CAR is the source of the
289 result (destination file or buffer for a finished process,
290 original buffer for a running one) and its CDR is a list
291 containing the back-end used, as a symbol, and either a process
292 or the time at which it finished. It is used to build the menu
293 from `org-export-stack'.")
295 (defvar org-export--registered-backends nil
296 "List of backends currently available in the exporter.
297 This variable is set with `org-export-define-backend' and
298 `org-export-define-derived-backend' functions.")
300 (defvar org-export-dispatch-last-action nil
301 "Last command called from the dispatcher.
302 The value should be a list. Its CAR is the action, as a symbol,
303 and its CDR is a list of export options.")
305 (defvar org-export-dispatch-last-position (make-marker)
306 "The position where the last export command was created using the dispatcher.
307 This marker will be used with `C-u C-c C-e' to make sure export repetition
308 uses the same subtree if the previous command was restricted to a subtree.")
310 ;; For compatibility with Org < 8
311 (defvar org-export-current-backend nil
312 "Name, if any, of the back-end used during an export process.
314 Its value is a symbol such as `html', `latex', `ascii', or nil if
315 the back-end is anonymous (see `org-export-create-backend') or if
316 there is no export process in progress.
318 It can be used to teach Babel blocks how to act differently
319 according to the back-end used.")
323 ;;; User-configurable Variables
325 ;; Configuration for the masses.
327 ;; They should never be accessed directly, as their value is to be
328 ;; stored in a property list (cf. `org-export-options-alist').
329 ;; Back-ends will read their value from there instead.
331 (defgroup org-export nil
332 "Options for exporting Org mode files."
333 :tag "Org Export"
334 :group 'org)
336 (defgroup org-export-general nil
337 "General options for export engine."
338 :tag "Org Export General"
339 :group 'org-export)
341 (defcustom org-export-with-archived-trees 'headline
342 "Whether sub-trees with the ARCHIVE tag should be exported.
344 This can have three different values:
345 nil Do not export, pretend this tree is not present.
346 t Do export the entire tree.
347 `headline' Only export the headline, but skip the tree below it.
349 This option can also be set with the OPTIONS keyword,
350 e.g. \"arch:nil\"."
351 :group 'org-export-general
352 :type '(choice
353 (const :tag "Not at all" nil)
354 (const :tag "Headline only" headline)
355 (const :tag "Entirely" t)))
357 (defcustom org-export-with-author t
358 "Non-nil means insert author name into the exported file.
359 This option can also be set with the OPTIONS keyword,
360 e.g. \"author:nil\"."
361 :group 'org-export-general
362 :type 'boolean)
364 (defcustom org-export-with-clocks nil
365 "Non-nil means export CLOCK keywords.
366 This option can also be set with the OPTIONS keyword,
367 e.g. \"c:t\"."
368 :group 'org-export-general
369 :type 'boolean)
371 (defcustom org-export-with-creator nil
372 "Non-nil means the postamble should contain a creator sentence.
374 The sentence can be set in `org-export-creator-string', which
375 see.
377 This option can also be set with the OPTIONS keyword, e.g.,
378 \"creator:t\"."
379 :group 'org-export-general
380 :version "25.1"
381 :package-version '(Org . "8.3")
382 :type 'boolean)
384 (defcustom org-export-with-date t
385 "Non-nil means insert date in the exported document.
386 This option can also be set with the OPTIONS keyword,
387 e.g. \"date:nil\"."
388 :group 'org-export-general
389 :type 'boolean)
391 (defcustom org-export-date-timestamp-format nil
392 "Time-stamp format string to use for DATE keyword.
394 The format string, when specified, only applies if date consists
395 in a single time-stamp. Otherwise its value will be ignored.
397 See `format-time-string' for details on how to build this
398 string."
399 :group 'org-export-general
400 :type '(choice
401 (string :tag "Time-stamp format string")
402 (const :tag "No format string" nil)))
404 (defcustom org-export-creator-string
405 (format "Emacs %s (Org mode %s)"
406 emacs-version
407 (if (fboundp 'org-version) (org-version) "unknown version"))
408 "Information about the creator of the document.
409 This option can also be set on with the CREATOR keyword."
410 :group 'org-export-general
411 :type '(string :tag "Creator string"))
413 (defcustom org-export-with-drawers '(not "LOGBOOK")
414 "Non-nil means export contents of standard drawers.
416 When t, all drawers are exported. This may also be a list of
417 drawer names to export, as strings. If that list starts with
418 `not', only drawers with such names will be ignored.
420 This variable doesn't apply to properties drawers. See
421 `org-export-with-properties' instead.
423 This option can also be set with the OPTIONS keyword,
424 e.g. \"d:nil\"."
425 :group 'org-export-general
426 :version "24.4"
427 :package-version '(Org . "8.0")
428 :type '(choice
429 (const :tag "All drawers" t)
430 (const :tag "None" nil)
431 (repeat :tag "Selected drawers"
432 (string :tag "Drawer name"))
433 (list :tag "Ignored drawers"
434 (const :format "" not)
435 (repeat :tag "Specify names of drawers to ignore during export"
436 :inline t
437 (string :tag "Drawer name")))))
439 (defcustom org-export-with-email nil
440 "Non-nil means insert author email into the exported file.
441 This option can also be set with the OPTIONS keyword,
442 e.g. \"email:t\"."
443 :group 'org-export-general
444 :type 'boolean)
446 (defcustom org-export-with-emphasize t
447 "Non-nil means interpret *word*, /word/, _word_ and +word+.
449 If the export target supports emphasizing text, the word will be
450 typeset in bold, italic, with an underline or strike-through,
451 respectively.
453 This option can also be set with the OPTIONS keyword,
454 e.g. \"*:nil\"."
455 :group 'org-export-general
456 :type 'boolean)
458 (defcustom org-export-exclude-tags '("noexport")
459 "Tags that exclude a tree from export.
461 All trees carrying any of these tags will be excluded from
462 export. This is without condition, so even subtrees inside that
463 carry one of the `org-export-select-tags' will be removed.
465 This option can also be set with the EXCLUDE_TAGS keyword."
466 :group 'org-export-general
467 :type '(repeat (string :tag "Tag")))
469 (defcustom org-export-with-fixed-width t
470 "Non-nil means export lines starting with \":\".
471 This option can also be set with the OPTIONS keyword,
472 e.g. \"::nil\"."
473 :group 'org-export-general
474 :version "24.4"
475 :package-version '(Org . "8.0")
476 :type 'boolean)
478 (defcustom org-export-with-footnotes t
479 "Non-nil means Org footnotes should be exported.
480 This option can also be set with the OPTIONS keyword,
481 e.g. \"f:nil\"."
482 :group 'org-export-general
483 :type 'boolean)
485 (defcustom org-export-with-latex t
486 "Non-nil means process LaTeX environments and fragments.
488 This option can also be set with the OPTIONS line,
489 e.g. \"tex:verbatim\". Allowed values are:
491 nil Ignore math snippets.
492 `verbatim' Keep everything in verbatim.
493 t Allow export of math snippets."
494 :group 'org-export-general
495 :version "24.4"
496 :package-version '(Org . "8.0")
497 :type '(choice
498 (const :tag "Do not process math in any way" nil)
499 (const :tag "Interpret math snippets" t)
500 (const :tag "Leave math verbatim" verbatim)))
502 (defcustom org-export-headline-levels 3
503 "The last level which is still exported as a headline.
505 Inferior levels will usually produce itemize or enumerate lists
506 when exported, but back-end behaviour may differ.
508 This option can also be set with the OPTIONS keyword,
509 e.g. \"H:2\"."
510 :group 'org-export-general
511 :type 'integer)
513 (defcustom org-export-default-language "en"
514 "The default language for export and clocktable translations, as a string.
515 This may have an association in
516 `org-clock-clocktable-language-setup',
517 `org-export-smart-quotes-alist' and `org-export-dictionary'.
518 This option can also be set with the LANGUAGE keyword."
519 :group 'org-export-general
520 :type '(string :tag "Language"))
522 (defcustom org-export-preserve-breaks nil
523 "Non-nil means preserve all line breaks when exporting.
524 This option can also be set with the OPTIONS keyword,
525 e.g. \"\\n:t\"."
526 :group 'org-export-general
527 :type 'boolean)
529 (defcustom org-export-with-entities t
530 "Non-nil means interpret entities when exporting.
532 For example, HTML export converts \\alpha to &alpha; and \\AA to
533 &Aring;.
535 For a list of supported names, see the constant `org-entities'
536 and the user option `org-entities-user'.
538 This option can also be set with the OPTIONS keyword,
539 e.g. \"e:nil\"."
540 :group 'org-export-general
541 :type 'boolean)
543 (defcustom org-export-with-inlinetasks t
544 "Non-nil means inlinetasks should be exported.
545 This option can also be set with the OPTIONS keyword,
546 e.g. \"inline:nil\"."
547 :group 'org-export-general
548 :version "24.4"
549 :package-version '(Org . "8.0")
550 :type 'boolean)
552 (defcustom org-export-with-planning nil
553 "Non-nil means include planning info in export.
555 Planning info is the line containing either SCHEDULED:,
556 DEADLINE:, CLOSED: time-stamps, or a combination of them.
558 This option can also be set with the OPTIONS keyword,
559 e.g. \"p:t\"."
560 :group 'org-export-general
561 :version "24.4"
562 :package-version '(Org . "8.0")
563 :type 'boolean)
565 (defcustom org-export-with-priority nil
566 "Non-nil means include priority cookies in export.
567 This option can also be set with the OPTIONS keyword,
568 e.g. \"pri:t\"."
569 :group 'org-export-general
570 :type 'boolean)
572 (defcustom org-export-with-properties nil
573 "Non-nil means export contents of properties drawers.
575 When t, all properties are exported. This may also be a list of
576 properties to export, as strings.
578 This option can also be set with the OPTIONS keyword,
579 e.g. \"prop:t\"."
580 :group 'org-export-general
581 :version "24.4"
582 :package-version '(Org . "8.3")
583 :type '(choice
584 (const :tag "All properties" t)
585 (const :tag "None" nil)
586 (repeat :tag "Selected properties"
587 (string :tag "Property name"))))
589 (defcustom org-export-with-section-numbers t
590 "Non-nil means add section numbers to headlines when exporting.
592 When set to an integer n, numbering will only happen for
593 headlines whose relative level is higher or equal to n.
595 This option can also be set with the OPTIONS keyword,
596 e.g. \"num:t\"."
597 :group 'org-export-general
598 :type 'boolean)
600 (defcustom org-export-select-tags '("export")
601 "Tags that select a tree for export.
603 If any such tag is found in a buffer, all trees that do not carry
604 one of these tags will be ignored during export. Inside trees
605 that are selected like this, you can still deselect a subtree by
606 tagging it with one of the `org-export-exclude-tags'.
608 This option can also be set with the SELECT_TAGS keyword."
609 :group 'org-export-general
610 :type '(repeat (string :tag "Tag")))
612 (defcustom org-export-with-smart-quotes nil
613 "Non-nil means activate smart quotes during export.
614 This option can also be set with the OPTIONS keyword,
615 e.g., \"':t\".
617 When setting this to non-nil, you need to take care of
618 using the correct Babel package when exporting to LaTeX.
619 E.g., you can load Babel for french like this:
621 #+LATEX_HEADER: \\usepackage[french]{babel}"
622 :group 'org-export-general
623 :version "24.4"
624 :package-version '(Org . "8.0")
625 :type 'boolean)
627 (defcustom org-export-with-special-strings t
628 "Non-nil means interpret \"\\-\", \"--\" and \"---\" for export.
630 When this option is turned on, these strings will be exported as:
632 Org HTML LaTeX UTF-8
633 -----+----------+--------+-------
634 \\- &shy; \\-
635 -- &ndash; -- –
636 --- &mdash; --- —
637 ... &hellip; \\ldots …
639 This option can also be set with the OPTIONS keyword,
640 e.g. \"-:nil\"."
641 :group 'org-export-general
642 :type 'boolean)
644 (defcustom org-export-with-statistics-cookies t
645 "Non-nil means include statistics cookies in export.
646 This option can also be set with the OPTIONS keyword,
647 e.g. \"stat:nil\""
648 :group 'org-export-general
649 :version "24.4"
650 :package-version '(Org . "8.0")
651 :type 'boolean)
653 (defcustom org-export-with-sub-superscripts t
654 "Non-nil means interpret \"_\" and \"^\" for export.
656 If you want to control how Org displays those characters, see
657 `org-use-sub-superscripts'. `org-export-with-sub-superscripts'
658 used to be an alias for `org-use-sub-superscripts' in Org <8.0,
659 it is not anymore.
661 When this option is turned on, you can use TeX-like syntax for
662 sub- and superscripts and see them exported correctly.
664 You can also set the option with #+OPTIONS: ^:t
666 Several characters after \"_\" or \"^\" will be considered as a
667 single item - so grouping with {} is normally not needed. For
668 example, the following things will be parsed as single sub- or
669 superscripts:
671 10^24 or 10^tau several digits will be considered 1 item.
672 10^-12 or 10^-tau a leading sign with digits or a word
673 x^2-y^3 will be read as x^2 - y^3, because items are
674 terminated by almost any nonword/nondigit char.
675 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
677 Still, ambiguity is possible. So when in doubt, use {} to enclose
678 the sub/superscript. If you set this variable to the symbol `{}',
679 the braces are *required* in order to trigger interpretations as
680 sub/superscript. This can be helpful in documents that need \"_\"
681 frequently in plain text."
682 :group 'org-export-general
683 :version "24.4"
684 :package-version '(Org . "8.0")
685 :type '(choice
686 (const :tag "Interpret them" t)
687 (const :tag "Curly brackets only" {})
688 (const :tag "Do not interpret them" nil)))
690 (defcustom org-export-with-toc t
691 "Non-nil means create a table of contents in exported files.
693 The TOC contains headlines with levels up
694 to`org-export-headline-levels'. When an integer, include levels
695 up to N in the toc, this may then be different from
696 `org-export-headline-levels', but it will not be allowed to be
697 larger than the number of headline levels. When nil, no table of
698 contents is made.
700 This option can also be set with the OPTIONS keyword,
701 e.g. \"toc:nil\" or \"toc:3\"."
702 :group 'org-export-general
703 :type '(choice
704 (const :tag "No Table of Contents" nil)
705 (const :tag "Full Table of Contents" t)
706 (integer :tag "TOC to level")))
708 (defcustom org-export-with-tables t
709 "Non-nil means export tables.
710 This option can also be set with the OPTIONS keyword,
711 e.g. \"|:nil\"."
712 :group 'org-export-general
713 :version "24.4"
714 :package-version '(Org . "8.0")
715 :type 'boolean)
717 (defcustom org-export-with-tags t
718 "If nil, do not export tags, just remove them from headlines.
720 If this is the symbol `not-in-toc', tags will be removed from
721 table of contents entries, but still be shown in the headlines of
722 the document.
724 This option can also be set with the OPTIONS keyword,
725 e.g. \"tags:nil\"."
726 :group 'org-export-general
727 :type '(choice
728 (const :tag "Off" nil)
729 (const :tag "Not in TOC" not-in-toc)
730 (const :tag "On" t)))
732 (defcustom org-export-with-tasks t
733 "Non-nil means include TODO items for export.
735 This may have the following values:
736 t include tasks independent of state.
737 `todo' include only tasks that are not yet done.
738 `done' include only tasks that are already done.
739 nil ignore all tasks.
740 list of keywords include tasks with these keywords.
742 This option can also be set with the OPTIONS keyword,
743 e.g. \"tasks:nil\"."
744 :group 'org-export-general
745 :type '(choice
746 (const :tag "All tasks" t)
747 (const :tag "No tasks" nil)
748 (const :tag "Not-done tasks" todo)
749 (const :tag "Only done tasks" done)
750 (repeat :tag "Specific TODO keywords"
751 (string :tag "Keyword"))))
753 (defcustom org-export-with-title t
754 "Non-nil means print title into the exported file.
755 This option can also be set with the OPTIONS keyword,
756 e.g. \"title:nil\"."
757 :group 'org-export-general
758 :version "25.1"
759 :package-version '(Org . "8.3")
760 :type 'boolean)
762 (defcustom org-export-time-stamp-file t
763 "Non-nil means insert a time stamp into the exported file.
764 The time stamp shows when the file was created. This option can
765 also be set with the OPTIONS keyword, e.g. \"timestamp:nil\"."
766 :group 'org-export-general
767 :type 'boolean)
769 (defcustom org-export-with-timestamps t
770 "Non nil means allow timestamps in export.
772 It can be set to any of the following values:
773 t export all timestamps.
774 `active' export active timestamps only.
775 `inactive' export inactive timestamps only.
776 nil do not export timestamps
778 This only applies to timestamps isolated in a paragraph
779 containing only timestamps. Other timestamps are always
780 exported.
782 This option can also be set with the OPTIONS keyword, e.g.
783 \"<:nil\"."
784 :group 'org-export-general
785 :type '(choice
786 (const :tag "All timestamps" t)
787 (const :tag "Only active timestamps" active)
788 (const :tag "Only inactive timestamps" inactive)
789 (const :tag "No timestamp" nil)))
791 (defcustom org-export-with-todo-keywords t
792 "Non-nil means include TODO keywords in export.
793 When nil, remove all these keywords from the export. This option
794 can also be set with the OPTIONS keyword, e.g. \"todo:nil\"."
795 :group 'org-export-general
796 :type 'boolean)
798 (defcustom org-export-allow-bind-keywords nil
799 "Non-nil means BIND keywords can define local variable values.
800 This is a potential security risk, which is why the default value
801 is nil. You can also allow them through local buffer variables."
802 :group 'org-export-general
803 :version "24.4"
804 :package-version '(Org . "8.0")
805 :type 'boolean)
807 (defcustom org-export-snippet-translation-alist nil
808 "Alist between export snippets back-ends and exporter back-ends.
810 This variable allows to provide shortcuts for export snippets.
812 For example, with a value of '\(\(\"h\" . \"html\"\)\), the
813 HTML back-end will recognize the contents of \"@@h:<b>@@\" as
814 HTML code while every other back-end will ignore it."
815 :group 'org-export-general
816 :version "24.4"
817 :package-version '(Org . "8.0")
818 :type '(repeat
819 (cons (string :tag "Shortcut")
820 (string :tag "Back-end"))))
822 (defcustom org-export-coding-system nil
823 "Coding system for the exported file."
824 :group 'org-export-general
825 :version "24.4"
826 :package-version '(Org . "8.0")
827 :type 'coding-system)
829 (defcustom org-export-copy-to-kill-ring nil
830 "Non-nil means pushing export output to the kill ring.
831 This variable is ignored during asynchronous export."
832 :group 'org-export-general
833 :version "25.1"
834 :package-version '(Org . "8.3")
835 :type '(choice
836 (const :tag "Always" t)
837 (const :tag "When export is done interactively" if-interactive)
838 (const :tag "Never" nil)))
840 (defcustom org-export-initial-scope 'buffer
841 "The initial scope when exporting with `org-export-dispatch'.
842 This variable can be either set to `buffer' or `subtree'."
843 :group 'org-export-general
844 :type '(choice
845 (const :tag "Export current buffer" buffer)
846 (const :tag "Export current subtree" subtree)))
848 (defcustom org-export-show-temporary-export-buffer t
849 "Non-nil means show buffer after exporting to temp buffer.
850 When Org exports to a file, the buffer visiting that file is never
851 shown, but remains buried. However, when exporting to
852 a temporary buffer, that buffer is popped up in a second window.
853 When this variable is nil, the buffer remains buried also in
854 these cases."
855 :group 'org-export-general
856 :type 'boolean)
858 (defcustom org-export-in-background nil
859 "Non-nil means export and publishing commands will run in background.
860 Results from an asynchronous export are never displayed
861 automatically. But you can retrieve them with \\[org-export-stack]."
862 :group 'org-export-general
863 :version "24.4"
864 :package-version '(Org . "8.0")
865 :type 'boolean)
867 (defcustom org-export-async-init-file nil
868 "File used to initialize external export process.
870 Value must be either nil or an absolute file name. When nil, the
871 external process is launched like a regular Emacs session,
872 loading user's initialization file and any site specific
873 configuration. If a file is provided, it, and only it, is loaded
874 at start-up.
876 Therefore, using a specific configuration makes the process to
877 load faster and the export more portable."
878 :group 'org-export-general
879 :version "24.4"
880 :package-version '(Org . "8.0")
881 :type '(choice
882 (const :tag "Regular startup" nil)
883 (file :tag "Specific start-up file" :must-match t)))
885 (defcustom org-export-dispatch-use-expert-ui nil
886 "Non-nil means using a non-intrusive `org-export-dispatch'.
887 In that case, no help buffer is displayed. Though, an indicator
888 for current export scope is added to the prompt (\"b\" when
889 output is restricted to body only, \"s\" when it is restricted to
890 the current subtree, \"v\" when only visible elements are
891 considered for export, \"f\" when publishing functions should be
892 passed the FORCE argument and \"a\" when the export should be
893 asynchronous). Also, \[?] allows to switch back to standard
894 mode."
895 :group 'org-export-general
896 :version "24.4"
897 :package-version '(Org . "8.0")
898 :type 'boolean)
902 ;;; Defining Back-ends
904 ;; An export back-end is a structure with `org-export-backend' type
905 ;; and `name', `parent', `transcoders', `options', `filters', `blocks'
906 ;; and `menu' slots.
908 ;; At the lowest level, a back-end is created with
909 ;; `org-export-create-backend' function.
911 ;; A named back-end can be registered with
912 ;; `org-export-register-backend' function. A registered back-end can
913 ;; later be referred to by its name, with `org-export-get-backend'
914 ;; function. Also, such a back-end can become the parent of a derived
915 ;; back-end from which slot values will be inherited by default.
916 ;; `org-export-derived-backend-p' can check if a given back-end is
917 ;; derived from a list of back-end names.
919 ;; `org-export-get-all-transcoders', `org-export-get-all-options' and
920 ;; `org-export-get-all-filters' return the full alist of transcoders,
921 ;; options and filters, including those inherited from ancestors.
923 ;; At a higher level, `org-export-define-backend' is the standard way
924 ;; to define an export back-end. If the new back-end is similar to
925 ;; a registered back-end, `org-export-define-derived-backend' may be
926 ;; used instead.
928 ;; Eventually `org-export-barf-if-invalid-backend' returns an error
929 ;; when a given back-end hasn't been registered yet.
931 (defstruct (org-export-backend (:constructor org-export-create-backend)
932 (:copier nil))
933 name parent transcoders options filters blocks menu)
935 (defun org-export-get-backend (name)
936 "Return export back-end named after NAME.
937 NAME is a symbol. Return nil if no such back-end is found."
938 (catch 'found
939 (dolist (b org-export--registered-backends)
940 (when (eq (org-export-backend-name b) name)
941 (throw 'found b)))))
943 (defun org-export-register-backend (backend)
944 "Register BACKEND as a known export back-end.
945 BACKEND is a structure with `org-export-backend' type."
946 ;; Refuse to register an unnamed back-end.
947 (unless (org-export-backend-name backend)
948 (error "Cannot register a unnamed export back-end"))
949 ;; Refuse to register a back-end with an unknown parent.
950 (let ((parent (org-export-backend-parent backend)))
951 (when (and parent (not (org-export-get-backend parent)))
952 (error "Cannot use unknown \"%s\" back-end as a parent" parent)))
953 ;; Register dedicated export blocks in the parser.
954 (dolist (name (org-export-backend-blocks backend))
955 (add-to-list 'org-element-block-name-alist
956 (cons name 'org-element-export-block-parser)))
957 ;; If a back-end with the same name as BACKEND is already
958 ;; registered, replace it with BACKEND. Otherwise, simply add
959 ;; BACKEND to the list of registered back-ends.
960 (let ((old (org-export-get-backend (org-export-backend-name backend))))
961 (if old (setcar (memq old org-export--registered-backends) backend)
962 (push backend org-export--registered-backends))))
964 (defun org-export-barf-if-invalid-backend (backend)
965 "Signal an error if BACKEND isn't defined."
966 (unless (org-export-backend-p backend)
967 (error "Unknown \"%s\" back-end: Aborting export" backend)))
969 (defun org-export-derived-backend-p (backend &rest backends)
970 "Non-nil if BACKEND is derived from one of BACKENDS.
971 BACKEND is an export back-end, as returned by, e.g.,
972 `org-export-create-backend', or a symbol referring to
973 a registered back-end. BACKENDS is constituted of symbols."
974 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
975 (when backend
976 (catch 'exit
977 (while (org-export-backend-parent backend)
978 (when (memq (org-export-backend-name backend) backends)
979 (throw 'exit t))
980 (setq backend
981 (org-export-get-backend (org-export-backend-parent backend))))
982 (memq (org-export-backend-name backend) backends))))
984 (defun org-export-get-all-transcoders (backend)
985 "Return full translation table for BACKEND.
987 BACKEND is an export back-end, as return by, e.g,,
988 `org-export-create-backend'. Return value is an alist where
989 keys are element or object types, as symbols, and values are
990 transcoders.
992 Unlike to `org-export-backend-transcoders', this function
993 also returns transcoders inherited from parent back-ends,
994 if any."
995 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
996 (when backend
997 (let ((transcoders (org-export-backend-transcoders backend))
998 parent)
999 (while (setq parent (org-export-backend-parent backend))
1000 (setq backend (org-export-get-backend parent))
1001 (setq transcoders
1002 (append transcoders (org-export-backend-transcoders backend))))
1003 transcoders)))
1005 (defun org-export-get-all-options (backend)
1006 "Return export options for BACKEND.
1008 BACKEND is an export back-end, as return by, e.g,,
1009 `org-export-create-backend'. See `org-export-options-alist'
1010 for the shape of the return value.
1012 Unlike to `org-export-backend-options', this function also
1013 returns options inherited from parent back-ends, if any."
1014 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
1015 (when backend
1016 (let ((options (org-export-backend-options backend))
1017 parent)
1018 (while (setq parent (org-export-backend-parent backend))
1019 (setq backend (org-export-get-backend parent))
1020 (setq options (append options (org-export-backend-options backend))))
1021 options)))
1023 (defun org-export-get-all-filters (backend)
1024 "Return complete list of filters for BACKEND.
1026 BACKEND is an export back-end, as return by, e.g,,
1027 `org-export-create-backend'. Return value is an alist where
1028 keys are symbols and values lists of functions.
1030 Unlike to `org-export-backend-filters', this function also
1031 returns filters inherited from parent back-ends, if any."
1032 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
1033 (when backend
1034 (let ((filters (org-export-backend-filters backend))
1035 parent)
1036 (while (setq parent (org-export-backend-parent backend))
1037 (setq backend (org-export-get-backend parent))
1038 (setq filters (append filters (org-export-backend-filters backend))))
1039 filters)))
1041 (defun org-export-define-backend (backend transcoders &rest body)
1042 "Define a new back-end BACKEND.
1044 TRANSCODERS is an alist between object or element types and
1045 functions handling them.
1047 These functions should return a string without any trailing
1048 space, or nil. They must accept three arguments: the object or
1049 element itself, its contents or nil when it isn't recursive and
1050 the property list used as a communication channel.
1052 Contents, when not nil, are stripped from any global indentation
1053 \(although the relative one is preserved). They also always end
1054 with a single newline character.
1056 If, for a given type, no function is found, that element or
1057 object type will simply be ignored, along with any blank line or
1058 white space at its end. The same will happen if the function
1059 returns the nil value. If that function returns the empty
1060 string, the type will be ignored, but the blank lines or white
1061 spaces will be kept.
1063 In addition to element and object types, one function can be
1064 associated to the `template' (or `inner-template') symbol and
1065 another one to the `plain-text' symbol.
1067 The former returns the final transcoded string, and can be used
1068 to add a preamble and a postamble to document's body. It must
1069 accept two arguments: the transcoded string and the property list
1070 containing export options. A function associated to `template'
1071 will not be applied if export has option \"body-only\".
1072 A function associated to `inner-template' is always applied.
1074 The latter, when defined, is to be called on every text not
1075 recognized as an element or an object. It must accept two
1076 arguments: the text string and the information channel. It is an
1077 appropriate place to protect special chars relative to the
1078 back-end.
1080 BODY can start with pre-defined keyword arguments. The following
1081 keywords are understood:
1083 :export-block
1085 String, or list of strings, representing block names that
1086 will not be parsed. This is used to specify blocks that will
1087 contain raw code specific to the back-end. These blocks
1088 still have to be handled by the relative `export-block' type
1089 translator.
1091 :filters-alist
1093 Alist between filters and function, or list of functions,
1094 specific to the back-end. See `org-export-filters-alist' for
1095 a list of all allowed filters. Filters defined here
1096 shouldn't make a back-end test, as it may prevent back-ends
1097 derived from this one to behave properly.
1099 :menu-entry
1101 Menu entry for the export dispatcher. It should be a list
1102 like:
1104 '(KEY DESCRIPTION-OR-ORDINAL ACTION-OR-MENU)
1106 where :
1108 KEY is a free character selecting the back-end.
1110 DESCRIPTION-OR-ORDINAL is either a string or a number.
1112 If it is a string, is will be used to name the back-end in
1113 its menu entry. If it is a number, the following menu will
1114 be displayed as a sub-menu of the back-end with the same
1115 KEY. Also, the number will be used to determine in which
1116 order such sub-menus will appear (lowest first).
1118 ACTION-OR-MENU is either a function or an alist.
1120 If it is an action, it will be called with four
1121 arguments (booleans): ASYNC, SUBTREEP, VISIBLE-ONLY and
1122 BODY-ONLY. See `org-export-as' for further explanations on
1123 some of them.
1125 If it is an alist, associations should follow the
1126 pattern:
1128 '(KEY DESCRIPTION ACTION)
1130 where KEY, DESCRIPTION and ACTION are described above.
1132 Valid values include:
1134 '(?m \"My Special Back-end\" my-special-export-function)
1138 '(?l \"Export to LaTeX\"
1139 \(?p \"As PDF file\" org-latex-export-to-pdf)
1140 \(?o \"As PDF file and open\"
1141 \(lambda (a s v b)
1142 \(if a (org-latex-export-to-pdf t s v b)
1143 \(org-open-file
1144 \(org-latex-export-to-pdf nil s v b)))))))
1146 or the following, which will be added to the previous
1147 sub-menu,
1149 '(?l 1
1150 \((?B \"As TEX buffer (Beamer)\" org-beamer-export-as-latex)
1151 \(?P \"As PDF file (Beamer)\" org-beamer-export-to-pdf)))
1153 :options-alist
1155 Alist between back-end specific properties introduced in
1156 communication channel and how their value are acquired. See
1157 `org-export-options-alist' for more information about
1158 structure of the values."
1159 (declare (indent 1))
1160 (let (blocks filters menu-entry options contents)
1161 (while (keywordp (car body))
1162 (let ((keyword (pop body)))
1163 (case keyword
1164 (:export-block (let ((names (pop body)))
1165 (setq blocks (if (consp names) (mapcar 'upcase names)
1166 (list (upcase names))))))
1167 (:filters-alist (setq filters (pop body)))
1168 (:menu-entry (setq menu-entry (pop body)))
1169 (:options-alist (setq options (pop body)))
1170 (t (error "Unknown keyword: %s" keyword)))))
1171 (org-export-register-backend
1172 (org-export-create-backend :name backend
1173 :transcoders transcoders
1174 :options options
1175 :filters filters
1176 :blocks blocks
1177 :menu menu-entry))))
1179 (defun org-export-define-derived-backend (child parent &rest body)
1180 "Create a new back-end as a variant of an existing one.
1182 CHILD is the name of the derived back-end. PARENT is the name of
1183 the parent back-end.
1185 BODY can start with pre-defined keyword arguments. The following
1186 keywords are understood:
1188 :export-block
1190 String, or list of strings, representing block names that
1191 will not be parsed. This is used to specify blocks that will
1192 contain raw code specific to the back-end. These blocks
1193 still have to be handled by the relative `export-block' type
1194 translator.
1196 :filters-alist
1198 Alist of filters that will overwrite or complete filters
1199 defined in PARENT back-end. See `org-export-filters-alist'
1200 for a list of allowed filters.
1202 :menu-entry
1204 Menu entry for the export dispatcher. See
1205 `org-export-define-backend' for more information about the
1206 expected value.
1208 :options-alist
1210 Alist of back-end specific properties that will overwrite or
1211 complete those defined in PARENT back-end. Refer to
1212 `org-export-options-alist' for more information about
1213 structure of the values.
1215 :translate-alist
1217 Alist of element and object types and transcoders that will
1218 overwrite or complete transcode table from PARENT back-end.
1219 Refer to `org-export-define-backend' for detailed information
1220 about transcoders.
1222 As an example, here is how one could define \"my-latex\" back-end
1223 as a variant of `latex' back-end with a custom template function:
1225 \(org-export-define-derived-backend 'my-latex 'latex
1226 :translate-alist '((template . my-latex-template-fun)))
1228 The back-end could then be called with, for example:
1230 \(org-export-to-buffer 'my-latex \"*Test my-latex*\")"
1231 (declare (indent 2))
1232 (let (blocks filters menu-entry options transcoders contents)
1233 (while (keywordp (car body))
1234 (let ((keyword (pop body)))
1235 (case keyword
1236 (:export-block (let ((names (pop body)))
1237 (setq blocks (if (consp names) (mapcar 'upcase names)
1238 (list (upcase names))))))
1239 (:filters-alist (setq filters (pop body)))
1240 (:menu-entry (setq menu-entry (pop body)))
1241 (:options-alist (setq options (pop body)))
1242 (:translate-alist (setq transcoders (pop body)))
1243 (t (error "Unknown keyword: %s" keyword)))))
1244 (org-export-register-backend
1245 (org-export-create-backend :name child
1246 :parent parent
1247 :transcoders transcoders
1248 :options options
1249 :filters filters
1250 :blocks blocks
1251 :menu menu-entry))))
1255 ;;; The Communication Channel
1257 ;; During export process, every function has access to a number of
1258 ;; properties. They are of two types:
1260 ;; 1. Environment options are collected once at the very beginning of
1261 ;; the process, out of the original buffer and configuration.
1262 ;; Collecting them is handled by `org-export-get-environment'
1263 ;; function.
1265 ;; Most environment options are defined through the
1266 ;; `org-export-options-alist' variable.
1268 ;; 2. Tree properties are extracted directly from the parsed tree,
1269 ;; just before export, by `org-export-collect-tree-properties'.
1271 ;;;; Environment Options
1273 ;; Environment options encompass all parameters defined outside the
1274 ;; scope of the parsed data. They come from five sources, in
1275 ;; increasing precedence order:
1277 ;; - Global variables,
1278 ;; - Buffer's attributes,
1279 ;; - Options keyword symbols,
1280 ;; - Buffer keywords,
1281 ;; - Subtree properties.
1283 ;; The central internal function with regards to environment options
1284 ;; is `org-export-get-environment'. It updates global variables with
1285 ;; "#+BIND:" keywords, then retrieve and prioritize properties from
1286 ;; the different sources.
1288 ;; The internal functions doing the retrieval are:
1289 ;; `org-export--get-global-options',
1290 ;; `org-export--get-buffer-attributes',
1291 ;; `org-export--parse-option-keyword',
1292 ;; `org-export--get-subtree-options' and
1293 ;; `org-export--get-inbuffer-options'
1295 ;; Also, `org-export--list-bound-variables' collects bound variables
1296 ;; along with their value in order to set them as buffer local
1297 ;; variables later in the process.
1299 (defun org-export-get-environment (&optional backend subtreep ext-plist)
1300 "Collect export options from the current buffer.
1302 Optional argument BACKEND is an export back-end, as returned by
1303 `org-export-create-backend'.
1305 When optional argument SUBTREEP is non-nil, assume the export is
1306 done against the current sub-tree.
1308 Third optional argument EXT-PLIST is a property list with
1309 external parameters overriding Org default settings, but still
1310 inferior to file-local settings."
1311 ;; First install #+BIND variables since these must be set before
1312 ;; global options are read.
1313 (dolist (pair (org-export--list-bound-variables))
1314 (org-set-local (car pair) (nth 1 pair)))
1315 ;; Get and prioritize export options...
1316 (org-combine-plists
1317 ;; ... from global variables...
1318 (org-export--get-global-options backend)
1319 ;; ... from an external property list...
1320 ext-plist
1321 ;; ... from in-buffer settings...
1322 (org-export--get-inbuffer-options backend)
1323 ;; ... and from subtree, when appropriate.
1324 (and subtreep (org-export--get-subtree-options backend))
1325 ;; Eventually add misc. properties.
1326 (list
1327 :back-end
1328 backend
1329 :translate-alist (org-export-get-all-transcoders backend)
1330 :footnote-definition-alist
1331 ;; Footnotes definitions must be collected in the original
1332 ;; buffer, as there's no insurance that they will still be in
1333 ;; the parse tree, due to possible narrowing.
1334 (let (alist)
1335 (org-with-wide-buffer
1336 (goto-char (point-min))
1337 (while (re-search-forward org-footnote-re nil t)
1338 (backward-char)
1339 (let ((fn (save-match-data (org-element-context))))
1340 (case (org-element-type fn)
1341 (footnote-definition
1342 (push
1343 (cons (org-element-property :label fn)
1344 (let ((cbeg (org-element-property :contents-begin fn)))
1345 (when cbeg
1346 (org-element--parse-elements
1347 cbeg (org-element-property :contents-end fn)
1348 nil nil nil nil (list 'org-data nil)))))
1349 alist))
1350 (footnote-reference
1351 (let ((label (org-element-property :label fn))
1352 (cbeg (org-element-property :contents-begin fn)))
1353 (when (and label cbeg
1354 (eq (org-element-property :type fn) 'inline))
1355 (push
1356 (cons label
1357 (org-element-parse-secondary-string
1358 (buffer-substring
1359 cbeg (org-element-property :contents-end fn))
1360 (org-element-restriction 'footnote-reference)))
1361 alist)))))))
1362 alist))
1363 :id-alist
1364 ;; Collect id references.
1365 (let (alist)
1366 (org-with-wide-buffer
1367 (goto-char (point-min))
1368 (while (re-search-forward "\\[\\[id:\\S-+?\\]" nil t)
1369 (let ((link (org-element-context)))
1370 (when (eq (org-element-type link) 'link)
1371 (let* ((id (org-element-property :path link))
1372 (file (car (org-id-find id))))
1373 (when file
1374 (push (cons id (file-relative-name file)) alist)))))))
1375 alist))))
1377 (defun org-export--parse-option-keyword (options &optional backend)
1378 "Parse an OPTIONS line and return values as a plist.
1379 Optional argument BACKEND is an export back-end, as returned by,
1380 e.g., `org-export-create-backend'. It specifies which back-end
1381 specific items to read, if any."
1382 (let* ((all
1383 ;; Priority is given to back-end specific options.
1384 (append (and backend (org-export-get-all-options backend))
1385 org-export-options-alist))
1386 plist)
1387 (dolist (option all)
1388 (let ((property (car option))
1389 (item (nth 2 option)))
1390 (when (and item
1391 (not (plist-member plist property))
1392 (string-match (concat "\\(\\`\\|[ \t]\\)"
1393 (regexp-quote item)
1394 ":\\(([^)\n]+)\\|[^ \t\n\r;,.]*\\)")
1395 options))
1396 (setq plist (plist-put plist
1397 property
1398 (car (read-from-string
1399 (match-string 2 options))))))))
1400 plist))
1402 (defun org-export--get-subtree-options (&optional backend)
1403 "Get export options in subtree at point.
1404 Optional argument BACKEND is an export back-end, as returned by,
1405 e.g., `org-export-create-backend'. It specifies back-end used
1406 for export. Return options as a plist."
1407 ;; For each buffer keyword, create a headline property setting the
1408 ;; same property in communication channel. The name for the property
1409 ;; is the keyword with "EXPORT_" appended to it.
1410 (org-with-wide-buffer
1411 (let (prop plist)
1412 ;; Make sure point is at a heading.
1413 (if (org-at-heading-p) (org-up-heading-safe) (org-back-to-heading t))
1414 ;; Take care of EXPORT_TITLE. If it isn't defined, use headline's
1415 ;; title (with no todo keyword, priority cookie or tag) as its
1416 ;; fallback value.
1417 (when (setq prop (or (org-entry-get (point) "EXPORT_TITLE")
1418 (progn (looking-at org-complex-heading-regexp)
1419 (org-match-string-no-properties 4))))
1420 (setq plist
1421 (plist-put
1422 plist :title
1423 (org-element-parse-secondary-string
1424 prop (org-element-restriction 'keyword)))))
1425 ;; EXPORT_OPTIONS are parsed in a non-standard way.
1426 (when (setq prop (org-entry-get (point) "EXPORT_OPTIONS"))
1427 (setq plist
1428 (nconc plist (org-export--parse-option-keyword prop backend))))
1429 ;; Handle other keywords. TITLE keyword is excluded as it has
1430 ;; been handled already.
1431 (let ((seen '("TITLE")))
1432 (mapc
1433 (lambda (option)
1434 (let ((property (car option))
1435 (keyword (nth 1 option)))
1436 (when (and keyword (not (member keyword seen)))
1437 (let* ((subtree-prop (concat "EXPORT_" keyword))
1438 ;; Export properties are not case-sensitive.
1439 (value (let ((case-fold-search t))
1440 (org-entry-get (point) subtree-prop))))
1441 (push keyword seen)
1442 (when (and value (not (plist-member plist property)))
1443 (setq plist
1444 (plist-put
1445 plist
1446 property
1447 (cond
1448 ;; Parse VALUE if required.
1449 ((member keyword org-element-document-properties)
1450 (org-element-parse-secondary-string
1451 value (org-element-restriction 'keyword)))
1452 ;; If BEHAVIOR is `split' expected value is
1453 ;; a list of strings, not a string.
1454 ((eq (nth 4 option) 'split) (org-split-string value))
1455 (t value)))))))))
1456 ;; Look for both general keywords and back-end specific
1457 ;; options, with priority given to the latter.
1458 (append (and backend (org-export-get-all-options backend))
1459 org-export-options-alist)))
1460 ;; Return value.
1461 plist)))
1463 (defun org-export--get-inbuffer-options (&optional backend)
1464 "Return current buffer export options, as a plist.
1466 Optional argument BACKEND, when non-nil, is an export back-end,
1467 as returned by, e.g., `org-export-create-backend'. It specifies
1468 which back-end specific options should also be read in the
1469 process.
1471 Assume buffer is in Org mode. Narrowing, if any, is ignored."
1472 (let* (plist
1473 get-options ; For byte-compiler.
1474 (case-fold-search t)
1475 (options (append
1476 ;; Priority is given to back-end specific options.
1477 (and backend (org-export-get-all-options backend))
1478 org-export-options-alist))
1479 (regexp (format "^[ \t]*#\\+%s:"
1480 (regexp-opt (nconc (delq nil (mapcar #'cadr options))
1481 org-export-special-keywords))))
1482 (find-properties
1483 (lambda (keyword)
1484 ;; Return all properties associated to KEYWORD.
1485 (let (properties)
1486 (dolist (option options properties)
1487 (when (equal (nth 1 option) keyword)
1488 (pushnew (car option) properties))))))
1489 (get-options
1490 (lambda (&optional files plist)
1491 ;; Recursively read keywords in buffer. FILES is a list
1492 ;; of files read so far. PLIST is the current property
1493 ;; list obtained.
1494 (org-with-wide-buffer
1495 (goto-char (point-min))
1496 (while (re-search-forward regexp nil t)
1497 (let ((element (org-element-at-point)))
1498 (when (eq (org-element-type element) 'keyword)
1499 (let ((key (org-element-property :key element))
1500 (val (org-element-property :value element)))
1501 (cond
1502 ;; Options in `org-export-special-keywords'.
1503 ((equal key "SETUPFILE")
1504 (let ((file (expand-file-name
1505 (org-remove-double-quotes (org-trim val)))))
1506 ;; Avoid circular dependencies.
1507 (unless (member file files)
1508 (with-temp-buffer
1509 (insert (org-file-contents file 'noerror))
1510 (let ((org-inhibit-startup t)) (org-mode))
1511 (setq plist (funcall get-options
1512 (cons file files) plist))))))
1513 ((equal key "OPTIONS")
1514 (setq plist
1515 (org-combine-plists
1516 plist
1517 (org-export--parse-option-keyword val backend))))
1518 ((equal key "FILETAGS")
1519 (setq plist
1520 (org-combine-plists
1521 plist
1522 (list :filetags
1523 (org-uniquify
1524 (append (org-split-string val ":")
1525 (plist-get plist :filetags)))))))
1527 ;; Options in `org-export-options-alist'.
1528 (dolist (property (funcall find-properties key))
1529 (let ((behaviour (nth 4 (assq property options))))
1530 (setq plist
1531 (plist-put
1532 plist property
1533 ;; Handle value depending on specified
1534 ;; BEHAVIOR.
1535 (case behaviour
1536 (space
1537 (if (not (plist-get plist property))
1538 (org-trim val)
1539 (concat (plist-get plist property)
1541 (org-trim val))))
1542 (newline
1543 (org-trim
1544 (concat (plist-get plist property)
1545 "\n"
1546 (org-trim val))))
1547 (split `(,@(plist-get plist property)
1548 ,@(org-split-string val)))
1549 ((t) val)
1550 (otherwise
1551 (if (not (plist-member plist property)) val
1552 (plist-get plist property))))))))))))))
1553 ;; Return final value.
1554 plist))))
1555 ;; Read options in the current buffer.
1556 (setq plist (funcall get-options
1557 (and buffer-file-name (list buffer-file-name)) nil))
1558 ;; Parse keywords specified in `org-element-document-properties'
1559 ;; and return PLIST.
1560 (dolist (keyword org-element-document-properties plist)
1561 (dolist (property (funcall find-properties keyword))
1562 (let ((value (plist-get plist property)))
1563 (when (stringp value)
1564 (setq plist
1565 (plist-put plist property
1566 (org-element-parse-secondary-string
1567 value (org-element-restriction 'keyword))))))))))
1569 (defun org-export--get-buffer-attributes ()
1570 "Return properties related to buffer attributes, as a plist."
1571 (list :input-buffer (buffer-name (buffer-base-buffer))
1572 :input-file (buffer-file-name (buffer-base-buffer))))
1574 (defun org-export--get-global-options (&optional backend)
1575 "Return global export options as a plist.
1576 Optional argument BACKEND, if non-nil, is an export back-end, as
1577 returned by, e.g., `org-export-create-backend'. It specifies
1578 which back-end specific export options should also be read in the
1579 process."
1580 (let (plist
1581 ;; Priority is given to back-end specific options.
1582 (all (append (and backend (org-export-get-all-options backend))
1583 org-export-options-alist)))
1584 (dolist (cell all plist)
1585 (let ((prop (car cell)))
1586 (unless (plist-member plist prop)
1587 (setq plist
1588 (plist-put
1589 plist
1590 prop
1591 ;; Evaluate default value provided. If keyword is
1592 ;; a member of `org-element-document-properties',
1593 ;; parse it as a secondary string before storing it.
1594 (let ((value (eval (nth 3 cell))))
1595 (if (and (stringp value)
1596 (member (nth 1 cell)
1597 org-element-document-properties))
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 (let ((type (org-element-type data)))
2695 (if (org-export--skip-p data info selected)
2696 (if (memq type '(table-cell table-row)) (push data ignore)
2697 (org-element-extract-element data))
2698 (if (and (eq type 'headline)
2699 (eq (plist-get info :with-archived-trees) 'headline)
2700 (org-element-property :archivedp data))
2701 ;; If headline is archived but tree below has to
2702 ;; be skipped, remove contents.
2703 (org-element-set-contents data)
2704 ;; Move into secondary string, if any.
2705 (let ((sec-prop
2706 (cdr (assq type org-element-secondary-value-alist))))
2707 (when sec-prop
2708 (mapc walk-data (org-element-property sec-prop data))))
2709 ;; Move into recursive objects/elements.
2710 (mapc walk-data (org-element-contents data))))))))
2711 ;; If a select tag is active, also ignore the section before the
2712 ;; first headline, if any.
2713 (when selected
2714 (let ((first-element (car (org-element-contents data))))
2715 (when (eq (org-element-type first-element) 'section)
2716 (org-element-extract-element first-element))))
2717 ;; Prune tree and communication channel.
2718 (funcall walk-data data)
2719 (dolist (prop org-export-document-properties)
2720 (funcall walk-data (plist-get info prop)))
2721 ;; Eventually set `:ignore-list'.
2722 (plist-put info :ignore-list ignore)))
2724 (defun org-export--remove-uninterpreted-data (data info)
2725 "Change uninterpreted elements back into Org syntax.
2726 DATA is the parse tree. INFO is a plist containing export
2727 options. Each uninterpreted element or object is changed back
2728 into a string. Contents, if any, are not modified. The parse
2729 tree is modified by side effect."
2730 (org-export--remove-uninterpreted-data-1 data info)
2731 (dolist (prop org-export-document-properties)
2732 (plist-put info
2733 prop
2734 (org-export--remove-uninterpreted-data-1
2735 (plist-get info prop)
2736 info))))
2738 (defun org-export--remove-uninterpreted-data-1 (data info)
2739 "Change uninterpreted elements back into Org syntax.
2740 DATA is a parse tree or a secondary string. INFO is a plist
2741 containing export options. It is modified by side effect and
2742 returned by the function."
2743 (org-element-map data
2744 '(entity bold italic latex-environment latex-fragment strike-through
2745 subscript superscript underline)
2746 (lambda (blob)
2747 (let ((new
2748 (case (org-element-type blob)
2749 ;; ... entities...
2750 (entity
2751 (and (not (plist-get info :with-entities))
2752 (list (concat
2753 (org-export-expand blob nil)
2754 (make-string
2755 (or (org-element-property :post-blank blob) 0)
2756 ?\s)))))
2757 ;; ... emphasis...
2758 ((bold italic strike-through underline)
2759 (and (not (plist-get info :with-emphasize))
2760 (let ((marker (case (org-element-type blob)
2761 (bold "*")
2762 (italic "/")
2763 (strike-through "+")
2764 (underline "_"))))
2765 (append
2766 (list marker)
2767 (org-element-contents blob)
2768 (list (concat
2769 marker
2770 (make-string
2771 (or (org-element-property :post-blank blob)
2773 ?\s)))))))
2774 ;; ... LaTeX environments and fragments...
2775 ((latex-environment latex-fragment)
2776 (and (eq (plist-get info :with-latex) 'verbatim)
2777 (list (org-export-expand blob nil))))
2778 ;; ... sub/superscripts...
2779 ((subscript superscript)
2780 (let ((sub/super-p (plist-get info :with-sub-superscript))
2781 (bracketp (org-element-property :use-brackets-p blob)))
2782 (and (or (not sub/super-p)
2783 (and (eq sub/super-p '{}) (not bracketp)))
2784 (append
2785 (list (concat
2786 (if (eq (org-element-type blob) 'subscript)
2788 "^")
2789 (and bracketp "{")))
2790 (org-element-contents blob)
2791 (list (concat
2792 (and bracketp "}")
2793 (and (org-element-property :post-blank blob)
2794 (make-string
2795 (org-element-property :post-blank blob)
2796 ?\s)))))))))))
2797 (when new
2798 ;; Splice NEW at BLOB location in parse tree.
2799 (dolist (e new (org-element-extract-element blob))
2800 (unless (string= e "") (org-element-insert-before e blob))))))
2801 info)
2802 ;; Return modified parse tree.
2803 data)
2805 ;;;###autoload
2806 (defun org-export-as
2807 (backend &optional subtreep visible-only body-only ext-plist)
2808 "Transcode current Org buffer into BACKEND code.
2810 BACKEND is either an export back-end, as returned by, e.g.,
2811 `org-export-create-backend', or a symbol referring to
2812 a registered back-end.
2814 If narrowing is active in the current buffer, only transcode its
2815 narrowed part.
2817 If a region is active, transcode that region.
2819 When optional argument SUBTREEP is non-nil, transcode the
2820 sub-tree at point, extracting information from the headline
2821 properties first.
2823 When optional argument VISIBLE-ONLY is non-nil, don't export
2824 contents of hidden elements.
2826 When optional argument BODY-ONLY is non-nil, only return body
2827 code, without surrounding template.
2829 Optional argument EXT-PLIST, when provided, is a property list
2830 with external parameters overriding Org default settings, but
2831 still inferior to file-local settings.
2833 Return code as a string."
2834 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
2835 (org-export-barf-if-invalid-backend backend)
2836 (save-excursion
2837 (save-restriction
2838 ;; Narrow buffer to an appropriate region or subtree for
2839 ;; parsing. If parsing subtree, be sure to remove main headline
2840 ;; too.
2841 (cond ((org-region-active-p)
2842 (narrow-to-region (region-beginning) (region-end)))
2843 (subtreep
2844 (org-narrow-to-subtree)
2845 (goto-char (point-min))
2846 (forward-line)
2847 (narrow-to-region (point) (point-max))))
2848 ;; Initialize communication channel with original buffer
2849 ;; attributes, unavailable in its copy.
2850 (let* ((org-export-current-backend (org-export-backend-name backend))
2851 (info (org-combine-plists
2852 (list :export-options
2853 (delq nil
2854 (list (and subtreep 'subtree)
2855 (and visible-only 'visible-only)
2856 (and body-only 'body-only))))
2857 (org-export--get-buffer-attributes)))
2858 tree)
2859 ;; Update communication channel and get parse tree. Buffer
2860 ;; isn't parsed directly. Instead, a temporary copy is
2861 ;; created, where include keywords, macros are expanded and
2862 ;; code blocks are evaluated.
2863 (org-export-with-buffer-copy
2864 ;; Run first hook with current back-end's name as argument.
2865 (run-hook-with-args 'org-export-before-processing-hook
2866 (org-export-backend-name backend))
2867 (org-export-expand-include-keyword)
2868 (org-export--delete-comments)
2869 ;; Update macro templates since #+INCLUDE keywords might have
2870 ;; added some new ones.
2871 (org-macro-initialize-templates)
2872 (org-macro-replace-all org-macro-templates)
2873 (org-export-execute-babel-code)
2874 ;; Update radio targets since keyword inclusion might have
2875 ;; added some more.
2876 (org-update-radio-target-regexp)
2877 ;; Run last hook with current back-end's name as argument.
2878 (goto-char (point-min))
2879 (save-excursion
2880 (run-hook-with-args 'org-export-before-parsing-hook
2881 (org-export-backend-name backend)))
2882 ;; Update communication channel with environment. Also
2883 ;; install user's and developer's filters.
2884 (setq info
2885 (org-export-install-filters
2886 (org-combine-plists
2887 info (org-export-get-environment backend subtreep ext-plist))))
2888 ;; Call options filters and update export options. We do not
2889 ;; use `org-export-filter-apply-functions' here since the
2890 ;; arity of such filters is different.
2891 (let ((backend-name (org-export-backend-name backend)))
2892 (dolist (filter (plist-get info :filter-options))
2893 (let ((result (funcall filter info backend-name)))
2894 (when result (setq info result)))))
2895 ;; Expand export-specific set of macros: {{{author}}},
2896 ;; {{{date(FORMAT)}}}, {{{email}}} and {{{title}}}. It must
2897 ;; be done once regular macros have been expanded, since
2898 ;; document keywords may contain one of them.
2899 (org-macro-replace-all
2900 (list (cons "author"
2901 (org-element-interpret-data (plist-get info :author)))
2902 (cons "date"
2903 (let* ((date (plist-get info :date))
2904 (value (or (org-element-interpret-data date) "")))
2905 (if (and (not (cdr date))
2906 (eq (org-element-type (car date)) 'timestamp))
2907 (format "(eval (if (org-string-nw-p \"$1\") %s %S))"
2908 (format "(org-timestamp-format '%S \"$1\")"
2909 (org-element-copy (car date)))
2910 value)
2911 value)))
2912 ;; EMAIL is not a parsed keyword: store it as-is.
2913 (cons "email" (or (plist-get info :email) ""))
2914 (cons "title"
2915 (org-element-interpret-data (plist-get info :title)))
2916 (cons "results" "$1"))
2917 'finalize)
2918 ;; Parse buffer.
2919 (setq tree (org-element-parse-buffer nil visible-only))
2920 ;; Prune tree from non-exported elements and transform
2921 ;; uninterpreted elements or objects in both parse tree and
2922 ;; communication channel.
2923 (org-export--prune-tree tree info)
2924 (org-export--remove-uninterpreted-data tree info)
2925 ;; Parse buffer, handle uninterpreted elements or objects,
2926 ;; then call parse-tree filters.
2927 (setq tree
2928 (org-export-filter-apply-functions
2929 (plist-get info :filter-parse-tree) tree info))
2930 ;; Now tree is complete, compute its properties and add them
2931 ;; to communication channel.
2932 (setq info
2933 (org-combine-plists
2934 info (org-export-collect-tree-properties tree info)))
2935 ;; Eventually transcode TREE. Wrap the resulting string into
2936 ;; a template.
2937 (let* ((body (org-element-normalize-string
2938 (or (org-export-data tree info) "")))
2939 (inner-template (cdr (assq 'inner-template
2940 (plist-get info :translate-alist))))
2941 (full-body (org-export-filter-apply-functions
2942 (plist-get info :filter-body)
2943 (if (not (functionp inner-template)) body
2944 (funcall inner-template body info))
2945 info))
2946 (template (cdr (assq 'template
2947 (plist-get info :translate-alist)))))
2948 ;; Remove all text properties since they cannot be
2949 ;; retrieved from an external process. Finally call
2950 ;; final-output filter and return result.
2951 (org-no-properties
2952 (org-export-filter-apply-functions
2953 (plist-get info :filter-final-output)
2954 (if (or (not (functionp template)) body-only) full-body
2955 (funcall template full-body info))
2956 info))))))))
2958 ;;;###autoload
2959 (defun org-export-string-as (string backend &optional body-only ext-plist)
2960 "Transcode STRING into BACKEND code.
2962 BACKEND is either an export back-end, as returned by, e.g.,
2963 `org-export-create-backend', or a symbol referring to
2964 a registered back-end.
2966 When optional argument BODY-ONLY is non-nil, only return body
2967 code, without preamble nor postamble.
2969 Optional argument EXT-PLIST, when provided, is a property list
2970 with external parameters overriding Org default settings, but
2971 still inferior to file-local settings.
2973 Return code as a string."
2974 (with-temp-buffer
2975 (insert string)
2976 (let ((org-inhibit-startup t)) (org-mode))
2977 (org-export-as backend nil nil body-only ext-plist)))
2979 ;;;###autoload
2980 (defun org-export-replace-region-by (backend)
2981 "Replace the active region by its export to BACKEND.
2982 BACKEND is either an export back-end, as returned by, e.g.,
2983 `org-export-create-backend', or a symbol referring to
2984 a registered back-end."
2985 (if (not (org-region-active-p))
2986 (user-error "No active region to replace")
2987 (let* ((beg (region-beginning))
2988 (end (region-end))
2989 (str (buffer-substring beg end)) rpl)
2990 (setq rpl (org-export-string-as str backend t))
2991 (delete-region beg end)
2992 (insert rpl))))
2994 ;;;###autoload
2995 (defun org-export-insert-default-template (&optional backend subtreep)
2996 "Insert all export keywords with default values at beginning of line.
2998 BACKEND is a symbol referring to the name of a registered export
2999 back-end, for which specific export options should be added to
3000 the template, or `default' for default template. When it is nil,
3001 the user will be prompted for a category.
3003 If SUBTREEP is non-nil, export configuration will be set up
3004 locally for the subtree through node properties."
3005 (interactive)
3006 (unless (derived-mode-p 'org-mode) (user-error "Not in an Org mode buffer"))
3007 (when (and subtreep (org-before-first-heading-p))
3008 (user-error "No subtree to set export options for"))
3009 (let ((node (and subtreep (save-excursion (org-back-to-heading t) (point))))
3010 (backend
3011 (or backend
3012 (intern
3013 (org-completing-read
3014 "Options category: "
3015 (cons "default"
3016 (mapcar #'(lambda (b)
3017 (symbol-name (org-export-backend-name b)))
3018 org-export--registered-backends))
3019 nil t))))
3020 options keywords)
3021 ;; Populate OPTIONS and KEYWORDS.
3022 (dolist (entry (cond ((eq backend 'default) org-export-options-alist)
3023 ((org-export-backend-p backend)
3024 (org-export-backend-options backend))
3025 (t (org-export-backend-options
3026 (org-export-get-backend backend)))))
3027 (let ((keyword (nth 1 entry))
3028 (option (nth 2 entry)))
3029 (cond
3030 (keyword (unless (assoc keyword keywords)
3031 (let ((value
3032 (if (eq (nth 4 entry) 'split)
3033 (mapconcat #'identity (eval (nth 3 entry)) " ")
3034 (eval (nth 3 entry)))))
3035 (push (cons keyword value) keywords))))
3036 (option (unless (assoc option options)
3037 (push (cons option (eval (nth 3 entry))) options))))))
3038 ;; Move to an appropriate location in order to insert options.
3039 (unless subtreep (beginning-of-line))
3040 ;; First (multiple) OPTIONS lines. Never go past fill-column.
3041 (when options
3042 (let ((items
3043 (mapcar
3044 #'(lambda (opt) (format "%s:%S" (car opt) (cdr opt)))
3045 (sort options (lambda (k1 k2) (string< (car k1) (car k2)))))))
3046 (if subtreep
3047 (org-entry-put
3048 node "EXPORT_OPTIONS" (mapconcat 'identity items " "))
3049 (while items
3050 (insert "#+OPTIONS:")
3051 (let ((width 10))
3052 (while (and items
3053 (< (+ width (length (car items)) 1) fill-column))
3054 (let ((item (pop items)))
3055 (insert " " item)
3056 (incf width (1+ (length item))))))
3057 (insert "\n")))))
3058 ;; Then the rest of keywords, in the order specified in either
3059 ;; `org-export-options-alist' or respective export back-ends.
3060 (dolist (key (nreverse keywords))
3061 (let ((val (cond ((equal (car key) "DATE")
3062 (or (cdr key)
3063 (with-temp-buffer
3064 (org-insert-time-stamp (current-time)))))
3065 ((equal (car key) "TITLE")
3066 (or (let ((visited-file
3067 (buffer-file-name (buffer-base-buffer))))
3068 (and visited-file
3069 (file-name-sans-extension
3070 (file-name-nondirectory visited-file))))
3071 (buffer-name (buffer-base-buffer))))
3072 (t (cdr key)))))
3073 (if subtreep (org-entry-put node (concat "EXPORT_" (car key)) val)
3074 (insert
3075 (format "#+%s:%s\n"
3076 (car key)
3077 (if (org-string-nw-p val) (format " %s" val) ""))))))))
3079 (defun org-export-expand-include-keyword (&optional included dir footnotes)
3080 "Expand every include keyword in buffer.
3081 Optional argument INCLUDED is a list of included file names along
3082 with their line restriction, when appropriate. It is used to
3083 avoid infinite recursion. Optional argument DIR is the current
3084 working directory. It is used to properly resolve relative
3085 paths. Optional argument FOOTNOTES is a hash-table used for
3086 storing and resolving footnotes. It is created automatically."
3087 (let ((case-fold-search t)
3088 (file-prefix (make-hash-table :test #'equal))
3089 (current-prefix 0)
3090 (footnotes (or footnotes (make-hash-table :test #'equal)))
3091 (include-re "^[ \t]*#\\+INCLUDE:"))
3092 ;; If :minlevel is not set the text-property
3093 ;; `:org-include-induced-level' will be used to determine the
3094 ;; relative level when expanding INCLUDE.
3095 ;; Only affects included Org documents.
3096 (goto-char (point-min))
3097 (while (re-search-forward include-re nil t)
3098 (put-text-property (line-beginning-position) (line-end-position)
3099 :org-include-induced-level
3100 (1+ (org-reduced-level (or (org-current-level) 0)))))
3101 ;; Expand INCLUDE keywords.
3102 (goto-char (point-min))
3103 (while (re-search-forward include-re nil t)
3104 (let ((element (save-match-data (org-element-at-point))))
3105 (when (eq (org-element-type element) 'keyword)
3106 (beginning-of-line)
3107 ;; Extract arguments from keyword's value.
3108 (let* ((value (org-element-property :value element))
3109 (ind (org-get-indentation))
3110 location
3111 (file (and (string-match
3112 "^\\(\".+?\"\\|\\S-+\\)\\(?:\\s-+\\|$\\)" value)
3113 (prog1
3114 (save-match-data
3115 (let ((matched (match-string 1 value)))
3116 (when (string-match "\\(::\\(.*?\\)\\)\"?\\'" matched)
3117 (setq location (match-string 2 matched))
3118 (setq matched
3119 (replace-match "" nil nil matched 1)))
3120 (expand-file-name
3121 (org-remove-double-quotes
3122 matched)
3123 dir)))
3124 (setq value (replace-match "" nil nil value)))))
3125 (only-contents
3126 (and (string-match ":only-contents *\\([^: \r\t\n]\\S-*\\)?" value)
3127 (prog1 (org-not-nil (match-string 1 value))
3128 (setq value (replace-match "" nil nil value)))))
3129 (lines
3130 (and (string-match
3131 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\""
3132 value)
3133 (prog1 (match-string 1 value)
3134 (setq value (replace-match "" nil nil value)))))
3135 (env (cond ((string-match "\\<example\\>" value)
3136 'literal)
3137 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
3138 'literal)))
3139 ;; Minimal level of included file defaults to the child
3140 ;; level of the current headline, if any, or one. It
3141 ;; only applies is the file is meant to be included as
3142 ;; an Org one.
3143 (minlevel
3144 (and (not env)
3145 (if (string-match ":minlevel +\\([0-9]+\\)" value)
3146 (prog1 (string-to-number (match-string 1 value))
3147 (setq value (replace-match "" nil nil value)))
3148 (get-text-property (point) :org-include-induced-level))))
3149 (src-args (and (eq env 'literal)
3150 (match-string 1 value)))
3151 (block (and (string-match "\\<\\(\\S-+\\)\\>" value)
3152 (match-string 1 value))))
3153 ;; Remove keyword.
3154 (delete-region (point) (progn (forward-line) (point)))
3155 (cond
3156 ((not file) nil)
3157 ((not (file-readable-p file))
3158 (error "Cannot include file %s" file))
3159 ;; Check if files has already been parsed. Look after
3160 ;; inclusion lines too, as different parts of the same file
3161 ;; can be included too.
3162 ((member (list file lines) included)
3163 (error "Recursive file inclusion: %s" file))
3165 (cond
3166 ((eq env 'literal)
3167 (insert
3168 (let ((ind-str (make-string ind ? ))
3169 (arg-str (if (stringp src-args)
3170 (format " %s" src-args)
3171 ""))
3172 (contents
3173 (org-escape-code-in-string
3174 (org-export--prepare-file-contents file lines))))
3175 (format "%s#+BEGIN_%s%s\n%s%s#+END_%s\n"
3176 ind-str block arg-str contents ind-str block))))
3177 ((stringp block)
3178 (insert
3179 (let ((ind-str (make-string ind ? ))
3180 (contents
3181 (org-export--prepare-file-contents file lines)))
3182 (format "%s#+BEGIN_%s\n%s%s#+END_%s\n"
3183 ind-str block contents ind-str block))))
3185 (insert
3186 (with-temp-buffer
3187 (let ((org-inhibit-startup t)
3188 (lines
3189 (if location
3190 (org-export--inclusion-absolute-lines
3191 file location only-contents lines)
3192 lines)))
3193 (org-mode)
3194 (insert (org-export--prepare-file-contents
3195 file lines ind minlevel
3196 (or (gethash file file-prefix)
3197 (puthash file (incf current-prefix) file-prefix))
3198 footnotes)))
3199 (org-export-expand-include-keyword
3200 (cons (list file lines) included)
3201 (file-name-directory file)
3202 footnotes)
3203 (buffer-string)))))
3204 ;; Expand footnotes after all files have been
3205 ;; included. Footnotes are stored at end of buffer.
3206 (unless included
3207 (org-with-wide-buffer
3208 (goto-char (point-max))
3209 (maphash (lambda (ref def) (insert (format "\n[%s] %s\n" ref def)))
3210 footnotes)))))))))))
3212 (defun org-export--inclusion-absolute-lines (file location only-contents lines)
3213 "Resolve absolute lines for an included file with file-link.
3215 FILE is string file-name of the file to include. LOCATION is a
3216 string name within FILE to be included (located via
3217 `org-link-search'). If ONLY-CONTENTS is non-nil only the
3218 contents of the named element will be included, as determined
3219 Org-Element. If LINES is non-nil only those lines are included.
3221 Return a string of lines to be included in the format expected by
3222 `org-export--prepare-file-contents'."
3223 (with-temp-buffer
3224 (insert-file-contents file)
3225 (unless (eq major-mode 'org-mode)
3226 (let ((org-inhibit-startup t)) (org-mode)))
3227 (condition-case err
3228 ;; Enforce consistent search.
3229 (let ((org-link-search-must-match-exact-headline t))
3230 (org-link-search location))
3231 (error
3232 (error (format "%s for %s::%s" (error-message-string err) file location))))
3233 (let* ((element (org-element-at-point))
3234 (contents-begin
3235 (and only-contents (org-element-property :contents-begin element))))
3236 (narrow-to-region
3237 (or contents-begin (org-element-property :begin element))
3238 (org-element-property (if contents-begin :contents-end :end) element))
3239 (when (and only-contents
3240 (memq (org-element-type element) '(headline inlinetask)))
3241 ;; Skip planning line and property-drawer.
3242 (goto-char (point-min))
3243 (when (org-looking-at-p org-planning-line-re) (forward-line))
3244 (when (looking-at org-property-drawer-re) (goto-char (match-end 0)))
3245 (unless (bolp) (forward-line))
3246 (narrow-to-region (point) (point-max))))
3247 (when lines
3248 (org-skip-whitespace)
3249 (beginning-of-line)
3250 (let* ((lines (split-string lines "-"))
3251 (lbeg (string-to-number (car lines)))
3252 (lend (string-to-number (cadr lines)))
3253 (beg (if (zerop lbeg) (point-min)
3254 (goto-char (point-min))
3255 (forward-line (1- lbeg))
3256 (point)))
3257 (end (if (zerop lend) (point-max)
3258 (goto-char beg)
3259 (forward-line (1- lend))
3260 (point))))
3261 (narrow-to-region beg end)))
3262 (let ((end (point-max)))
3263 (goto-char (point-min))
3264 (widen)
3265 (let ((start-line (line-number-at-pos)))
3266 (format "%d-%d"
3267 start-line
3268 (save-excursion
3269 (+ start-line
3270 (let ((counter 0))
3271 (while (< (point) end) (incf counter) (forward-line))
3272 counter))))))))
3274 (defun org-export--update-footnote-label (ref-begin digit-label id)
3275 "Prefix footnote-label at point REF-BEGIN in buffer with ID.
3277 REF-BEGIN corresponds to the property `:begin' of objects of type
3278 footnote-definition and footnote-reference.
3280 If DIGIT-LABEL is non-nil the label is assumed to be of the form
3281 \[N] where N is one or more numbers.
3283 Return the new label."
3284 (goto-char (1+ ref-begin))
3285 (buffer-substring (point)
3286 (progn
3287 (if digit-label (insert (format "fn:%d-" id))
3288 (forward-char 3)
3289 (insert (format "%d-" id)))
3290 (1- (search-forward "]")))))
3292 (defun org-export--prepare-file-contents (file &optional lines ind minlevel id footnotes)
3293 "Prepare contents of FILE for inclusion and return it as a string.
3295 When optional argument LINES is a string specifying a range of
3296 lines, include only those lines.
3298 Optional argument IND, when non-nil, is an integer specifying the
3299 global indentation of returned contents. Since its purpose is to
3300 allow an included file to stay in the same environment it was
3301 created \(i.e. a list item), it doesn't apply past the first
3302 headline encountered.
3304 Optional argument MINLEVEL, when non-nil, is an integer
3305 specifying the level that any top-level headline in the included
3306 file should have.
3307 Optional argument ID is an integer that will be inserted before
3308 each footnote definition and reference if FILE is an Org file.
3309 This is useful to avoid conflicts when more than one Org file
3310 with footnotes is included in a document.
3312 Optional argument FOOTNOTES is a hash-table to store footnotes in
3313 the included document.
3315 (with-temp-buffer
3316 (insert-file-contents file)
3317 (when lines
3318 (let* ((lines (split-string lines "-"))
3319 (lbeg (string-to-number (car lines)))
3320 (lend (string-to-number (cadr lines)))
3321 (beg (if (zerop lbeg) (point-min)
3322 (goto-char (point-min))
3323 (forward-line (1- lbeg))
3324 (point)))
3325 (end (if (zerop lend) (point-max)
3326 (goto-char (point-min))
3327 (forward-line (1- lend))
3328 (point))))
3329 (narrow-to-region beg end)))
3330 ;; Remove blank lines at beginning and end of contents. The logic
3331 ;; behind that removal is that blank lines around include keyword
3332 ;; override blank lines in included file.
3333 (goto-char (point-min))
3334 (org-skip-whitespace)
3335 (beginning-of-line)
3336 (delete-region (point-min) (point))
3337 (goto-char (point-max))
3338 (skip-chars-backward " \r\t\n")
3339 (forward-line)
3340 (delete-region (point) (point-max))
3341 ;; If IND is set, preserve indentation of include keyword until
3342 ;; the first headline encountered.
3343 (when ind
3344 (unless (eq major-mode 'org-mode)
3345 (let ((org-inhibit-startup t)) (org-mode)))
3346 (goto-char (point-min))
3347 (let ((ind-str (make-string ind ? )))
3348 (while (not (or (eobp) (looking-at org-outline-regexp-bol)))
3349 ;; Do not move footnote definitions out of column 0.
3350 (unless (and (looking-at org-footnote-definition-re)
3351 (eq (org-element-type (org-element-at-point))
3352 'footnote-definition))
3353 (insert ind-str))
3354 (forward-line))))
3355 ;; When MINLEVEL is specified, compute minimal level for headlines
3356 ;; in the file (CUR-MIN), and remove stars to each headline so
3357 ;; that headlines with minimal level have a level of MINLEVEL.
3358 (when minlevel
3359 (unless (eq major-mode 'org-mode)
3360 (let ((org-inhibit-startup t)) (org-mode)))
3361 (org-with-limited-levels
3362 (let ((levels (org-map-entries
3363 (lambda () (org-reduced-level (org-current-level))))))
3364 (when levels
3365 (let ((offset (- minlevel (apply 'min levels))))
3366 (unless (zerop offset)
3367 (when org-odd-levels-only (setq offset (* offset 2)))
3368 ;; Only change stars, don't bother moving whole
3369 ;; sections.
3370 (org-map-entries
3371 (lambda () (if (< offset 0) (delete-char (abs offset))
3372 (insert (make-string offset ?*)))))))))))
3373 ;; Append ID to all footnote references and definitions, so they
3374 ;; become file specific and cannot collide with footnotes in other
3375 ;; included files. Further, collect relevant footnotes outside of
3376 ;; LINES.
3377 (when id
3378 (let ((marker-min (point-min-marker))
3379 (marker-max (point-max-marker)))
3380 (goto-char (point-min))
3381 (while (re-search-forward org-footnote-re nil t)
3382 (let ((reference (org-element-context)))
3383 (when (eq (org-element-type reference) 'footnote-reference)
3384 (let* ((label (org-element-property :label reference))
3385 (digit-label (and label (org-string-match-p "\\`[0-9]+\\'" label))))
3386 ;; Update the footnote-reference at point and collect
3387 ;; the new label, which is only used for footnotes
3388 ;; outsides LINES.
3389 (when label
3390 ;; If label is akin to [1] convert it to [fn:ID-1].
3391 ;; Otherwise add "ID-" after "fn:".
3392 (let ((new-label (org-export--update-footnote-label
3393 (org-element-property :begin reference) digit-label id)))
3394 (unless (eq (org-element-property :type reference) 'inline)
3395 (org-with-wide-buffer
3396 (let* ((definition (org-footnote-get-definition label))
3397 (beginning (nth 1 definition)))
3398 (unless definition
3399 (error "Definition not found for footnote %s in file %s" label file))
3400 (if (or (< beginning marker-min) (> beginning marker-max))
3401 ;; Store since footnote-definition is outside of LINES.
3402 (puthash new-label
3403 (org-element-normalize-string (nth 3 definition))
3404 footnotes)
3405 ;; Update label of definition since it is included directly.
3406 (org-export--update-footnote-label beginning digit-label id)))))))))))
3407 (set-marker marker-min nil)
3408 (set-marker marker-max nil)))
3409 (org-element-normalize-string (buffer-string))))
3411 (defun org-export-execute-babel-code ()
3412 "Execute every Babel code in the visible part of current buffer."
3413 ;; Get a pristine copy of current buffer so Babel references can be
3414 ;; properly resolved.
3415 (let ((reference (org-export-copy-buffer)))
3416 (unwind-protect (org-babel-exp-process-buffer reference)
3417 (kill-buffer reference))))
3419 (defun org-export--copy-to-kill-ring-p ()
3420 "Return a non-nil value when output should be added to the kill ring.
3421 See also `org-export-copy-to-kill-ring'."
3422 (if (eq org-export-copy-to-kill-ring 'if-interactive)
3423 (not (or executing-kbd-macro noninteractive))
3424 (eq org-export-copy-to-kill-ring t)))
3428 ;;; Tools For Back-Ends
3430 ;; A whole set of tools is available to help build new exporters. Any
3431 ;; function general enough to have its use across many back-ends
3432 ;; should be added here.
3434 ;;;; For Affiliated Keywords
3436 ;; `org-export-read-attribute' reads a property from a given element
3437 ;; as a plist. It can be used to normalize affiliated keywords'
3438 ;; syntax.
3440 ;; Since captions can span over multiple lines and accept dual values,
3441 ;; their internal representation is a bit tricky. Therefore,
3442 ;; `org-export-get-caption' transparently returns a given element's
3443 ;; caption as a secondary string.
3445 (defun org-export-read-attribute (attribute element &optional property)
3446 "Turn ATTRIBUTE property from ELEMENT into a plist.
3448 When optional argument PROPERTY is non-nil, return the value of
3449 that property within attributes.
3451 This function assumes attributes are defined as \":keyword
3452 value\" pairs. It is appropriate for `:attr_html' like
3453 properties.
3455 All values will become strings except the empty string and
3456 \"nil\", which will become nil. Also, values containing only
3457 double quotes will be read as-is, which means that \"\" value
3458 will become the empty string."
3459 (let* ((prepare-value
3460 (lambda (str)
3461 (save-match-data
3462 (cond ((member str '(nil "" "nil")) nil)
3463 ((string-match "^\"\\(\"+\\)?\"$" str)
3464 (or (match-string 1 str) ""))
3465 (t str)))))
3466 (attributes
3467 (let ((value (org-element-property attribute element)))
3468 (when value
3469 (let ((s (mapconcat 'identity value " ")) result)
3470 (while (string-match
3471 "\\(?:^\\|[ \t]+\\)\\(:[-a-zA-Z0-9_]+\\)\\([ \t]+\\|$\\)"
3473 (let ((value (substring s 0 (match-beginning 0))))
3474 (push (funcall prepare-value value) result))
3475 (push (intern (match-string 1 s)) result)
3476 (setq s (substring s (match-end 0))))
3477 ;; Ignore any string before first property with `cdr'.
3478 (cdr (nreverse (cons (funcall prepare-value s) result))))))))
3479 (if property (plist-get attributes property) attributes)))
3481 (defun org-export-get-caption (element &optional shortp)
3482 "Return caption from ELEMENT as a secondary string.
3484 When optional argument SHORTP is non-nil, return short caption,
3485 as a secondary string, instead.
3487 Caption lines are separated by a white space."
3488 (let ((full-caption (org-element-property :caption element)) caption)
3489 (dolist (line full-caption (cdr caption))
3490 (let ((cap (funcall (if shortp 'cdr 'car) line)))
3491 (when cap
3492 (setq caption (nconc (list " ") (copy-sequence cap) caption)))))))
3495 ;;;; For Derived Back-ends
3497 ;; `org-export-with-backend' is a function allowing to locally use
3498 ;; another back-end to transcode some object or element. In a derived
3499 ;; back-end, it may be used as a fall-back function once all specific
3500 ;; cases have been treated.
3502 (defun org-export-with-backend (backend data &optional contents info)
3503 "Call a transcoder from BACKEND on DATA.
3504 BACKEND is an export back-end, as returned by, e.g.,
3505 `org-export-create-backend', or a symbol referring to
3506 a registered back-end. DATA is an Org element, object, secondary
3507 string or string. CONTENTS, when non-nil, is the transcoded
3508 contents of DATA element, as a string. INFO, when non-nil, is
3509 the communication channel used for export, as a plist."
3510 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
3511 (org-export-barf-if-invalid-backend backend)
3512 (let ((type (org-element-type data)))
3513 (if (memq type '(nil org-data)) (error "No foreign transcoder available")
3514 (let* ((all-transcoders (org-export-get-all-transcoders backend))
3515 (transcoder (cdr (assq type all-transcoders))))
3516 (if (not (functionp transcoder))
3517 (error "No foreign transcoder available")
3518 (funcall
3519 transcoder data contents
3520 (org-combine-plists
3521 info (list :back-end backend
3522 :translate-alist all-transcoders
3523 :exported-data (make-hash-table :test 'eq :size 401)))))))))
3526 ;;;; For Export Snippets
3528 ;; Every export snippet is transmitted to the back-end. Though, the
3529 ;; latter will only retain one type of export-snippet, ignoring
3530 ;; others, based on the former's target back-end. The function
3531 ;; `org-export-snippet-backend' returns that back-end for a given
3532 ;; export-snippet.
3534 (defun org-export-snippet-backend (export-snippet)
3535 "Return EXPORT-SNIPPET targeted back-end as a symbol.
3536 Translation, with `org-export-snippet-translation-alist', is
3537 applied."
3538 (let ((back-end (org-element-property :back-end export-snippet)))
3539 (intern
3540 (or (cdr (assoc back-end org-export-snippet-translation-alist))
3541 back-end))))
3544 ;;;; For Footnotes
3546 ;; `org-export-collect-footnote-definitions' is a tool to list
3547 ;; actually used footnotes definitions in the whole parse tree, or in
3548 ;; a headline, in order to add footnote listings throughout the
3549 ;; transcoded data.
3551 ;; `org-export-footnote-first-reference-p' is a predicate used by some
3552 ;; back-ends, when they need to attach the footnote definition only to
3553 ;; the first occurrence of the corresponding label.
3555 ;; `org-export-get-footnote-definition' and
3556 ;; `org-export-get-footnote-number' provide easier access to
3557 ;; additional information relative to a footnote reference.
3559 (defun org-export-get-footnote-definition (footnote-reference info)
3560 "Return definition of FOOTNOTE-REFERENCE as parsed data.
3561 INFO is the plist used as a communication channel. If no such
3562 definition can be found, raise an error."
3563 (let ((label (org-element-property :label footnote-reference)))
3564 (or (if label
3565 (cdr (assoc label (plist-get info :footnote-definition-alist)))
3566 (org-element-contents footnote-reference))
3567 (error "Definition not found for footnote %s" label))))
3569 (defun org-export--footnote-reference-map
3570 (function data info &optional body-first)
3571 "Apply FUNCTION on every footnote reference in DATA.
3572 INFO is a plist containing export state. By default, as soon as
3573 a new footnote reference is encountered, FUNCTION is called onto
3574 its definition. However, if BODY-FIRST is non-nil, this step is
3575 delayed until the end of the process."
3576 (let* ((definitions)
3577 (seen-refs)
3578 (search-ref) ; For byte-compiler.
3579 (search-ref
3580 (lambda (data delayp)
3581 ;; Search footnote references through DATA, filling
3582 ;; SEEN-REFS along the way. When DELAYP is non-nil, store
3583 ;; footnote definitions so they can be entered later.
3584 (org-element-map data 'footnote-reference
3585 (lambda (f)
3586 (funcall function f)
3587 (let ((--label (org-element-property :label f)))
3588 (unless (and --label (member --label seen-refs))
3589 (when --label (push --label seen-refs))
3590 ;; Search for subsequent references in footnote
3591 ;; definition so numbering follows reading logic,
3592 ;; unless DELAYP in non-nil.
3593 (cond
3594 (delayp
3595 (push (org-export-get-footnote-definition f info)
3596 definitions))
3597 ;; Do not force entering inline definitions,
3598 ;; since `org-element-map' already traverses them
3599 ;; at the right time.
3600 ((eq (org-element-property :type f) 'inline))
3601 (t (funcall search-ref
3602 (org-export-get-footnote-definition f info)
3603 nil))))))
3604 info nil
3605 ;; Don't enter footnote definitions since it will happen
3606 ;; when their first reference is found. Moreover, if
3607 ;; DELAYP is non-nil, make sure we postpone entering
3608 ;; definitions of inline references.
3609 (if delayp '(footnote-definition footnote-reference)
3610 'footnote-definition)))))
3611 (funcall search-ref data body-first)
3612 (funcall search-ref (nreverse definitions) nil)))
3614 (defun org-export-collect-footnote-definitions (info &optional data body-first)
3615 "Return an alist between footnote numbers, labels and definitions.
3617 INFO is the current export state, as a plist.
3619 Definitions are collected throughout the whole parse tree, or
3620 DATA when non-nil.
3622 Sorting is done by order of references. As soon as a new
3623 reference is encountered, other references are searched within
3624 its definition. However, if BODY-FIRST is non-nil, this step is
3625 delayed after the whole tree is checked. This alters results
3626 when references are found in footnote definitions.
3628 Definitions either appear as Org data or as a secondary string
3629 for inlined footnotes. Unreferenced definitions are ignored."
3630 (let ((n 0) labels alist)
3631 (org-export--footnote-reference-map
3632 (lambda (f)
3633 ;; Collect footnote number, label and definition.
3634 (let ((l (org-element-property :label f)))
3635 (unless (and l (member l labels))
3636 (incf n)
3637 (push (list n l (org-export-get-footnote-definition f info)) alist))
3638 (when l (push l labels))))
3639 (or data (plist-get info :parse-tree)) info body-first)
3640 (nreverse alist)))
3642 (defun org-export-footnote-first-reference-p
3643 (footnote-reference info &optional data body-first)
3644 "Non-nil when a footnote reference is the first one for its label.
3646 FOOTNOTE-REFERENCE is the footnote reference being considered.
3647 INFO is a plist containing current export state.
3649 Search is done throughout the whole parse tree, or DATA when
3650 non-nil.
3652 By default, as soon as a new footnote reference is encountered,
3653 other references are searched within its definition. However, if
3654 BODY-FIRST is non-nil, this step is delayed after the whole tree
3655 is checked. This alters results when references are found in
3656 footnote definitions."
3657 (let ((label (org-element-property :label footnote-reference)))
3658 ;; Anonymous footnotes are always a first reference.
3659 (or (not label)
3660 (catch 'exit
3661 (org-export--footnote-reference-map
3662 (lambda (f)
3663 (let ((l (org-element-property :label f)))
3664 (when (and l label (string= label l))
3665 (throw 'exit (eq footnote-reference f)))))
3666 (or data (plist-get info :parse-tree)) info body-first)))))
3668 (defun org-export-get-footnote-number (footnote info &optional data body-first)
3669 "Return number associated to a footnote.
3671 FOOTNOTE is either a footnote reference or a footnote definition.
3672 INFO is the plist containing export state.
3674 Number is unique throughout the whole parse tree, or DATA, when
3675 non-nil.
3677 By default, as soon as a new footnote reference is encountered,
3678 counting process moves into its definition. However, if
3679 BODY-FIRST is non-nil, this step is delayed until the end of the
3680 process, leading to a different order when footnotes are nested."
3681 (let ((count 0)
3682 (seen)
3683 (label (org-element-property :label footnote)))
3684 (catch 'exit
3685 (org-export--footnote-reference-map
3686 (lambda (f)
3687 (let ((l (org-element-property :label f)))
3688 (cond
3689 ;; Anonymous footnote match: return number.
3690 ((and (not l) (not label) (eq footnote f)) (throw 'exit (1+ count)))
3691 ;; Labels match: return number.
3692 ((and label l (string= label l)) (throw 'exit (1+ count)))
3693 ;; Otherwise store label and increase counter if label
3694 ;; wasn't encountered yet.
3695 ((not l) (incf count))
3696 ((not (member l seen)) (push l seen) (incf count)))))
3697 (or data (plist-get info :parse-tree)) info body-first))))
3700 ;;;; For Headlines
3702 ;; `org-export-get-relative-level' is a shortcut to get headline
3703 ;; level, relatively to the lower headline level in the parsed tree.
3705 ;; `org-export-get-headline-number' returns the section number of an
3706 ;; headline, while `org-export-number-to-roman' allows to convert it
3707 ;; to roman numbers. With an optional argument,
3708 ;; `org-export-get-headline-number' returns a number to unnumbered
3709 ;; headlines (used for internal id).
3711 ;; `org-export-get-headline-id' returns the unique internal id of a
3712 ;; headline.
3714 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
3715 ;; `org-export-last-sibling-p' are three useful predicates when it
3716 ;; comes to fulfill the `:headline-levels' property.
3718 ;; `org-export-get-tags', `org-export-get-category' and
3719 ;; `org-export-get-node-property' extract useful information from an
3720 ;; headline or a parent headline. They all handle inheritance.
3722 ;; `org-export-get-alt-title' tries to retrieve an alternative title,
3723 ;; as a secondary string, suitable for table of contents. It falls
3724 ;; back onto default title.
3726 (defun org-export-get-relative-level (headline info)
3727 "Return HEADLINE relative level within current parsed tree.
3728 INFO is a plist holding contextual information."
3729 (+ (org-element-property :level headline)
3730 (or (plist-get info :headline-offset) 0)))
3732 (defun org-export-low-level-p (headline info)
3733 "Non-nil when HEADLINE is considered as low level.
3735 INFO is a plist used as a communication channel.
3737 A low level headlines has a relative level greater than
3738 `:headline-levels' property value.
3740 Return value is the difference between HEADLINE relative level
3741 and the last level being considered as high enough, or nil."
3742 (let ((limit (plist-get info :headline-levels)))
3743 (when (wholenump limit)
3744 (let ((level (org-export-get-relative-level headline info)))
3745 (and (> level limit) (- level limit))))))
3747 (defun org-export-get-headline-id (headline info)
3748 "Return a unique ID for HEADLINE.
3749 INFO is a plist holding contextual information."
3750 (let ((numbered (org-export-numbered-headline-p headline info)))
3751 (concat
3752 (if numbered "sec-" "unnumbered-")
3753 (mapconcat #'number-to-string
3754 (if numbered
3755 (org-export-get-headline-number headline info)
3756 (cdr (assq headline (plist-get info :unnumbered-headline-id)))) "-"))))
3758 (defun org-export-get-headline-number (headline info)
3759 "Return numbered HEADLINE numbering as a list of numbers.
3760 INFO is a plist holding contextual information."
3761 (and (org-export-numbered-headline-p headline info)
3762 (cdr (assq headline (plist-get info :headline-numbering)))))
3764 (defun org-export-numbered-headline-p (headline info)
3765 "Return a non-nil value if HEADLINE element should be numbered.
3766 INFO is a plist used as a communication channel."
3767 (unless (org-some
3768 (lambda (head) (org-not-nil (org-element-property :UNNUMBERED head)))
3769 (org-element-lineage headline nil t))
3770 (let ((sec-num (plist-get info :section-numbers))
3771 (level (org-export-get-relative-level headline info)))
3772 (if (wholenump sec-num) (<= level sec-num) sec-num))))
3774 (defun org-export-number-to-roman (n)
3775 "Convert integer N into a roman numeral."
3776 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
3777 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
3778 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
3779 ( 1 . "I")))
3780 (res ""))
3781 (if (<= n 0)
3782 (number-to-string n)
3783 (while roman
3784 (if (>= n (caar roman))
3785 (setq n (- n (caar roman))
3786 res (concat res (cdar roman)))
3787 (pop roman)))
3788 res)))
3790 (defun org-export-get-tags (element info &optional tags inherited)
3791 "Return list of tags associated to ELEMENT.
3793 ELEMENT has either an `headline' or an `inlinetask' type. INFO
3794 is a plist used as a communication channel.
3796 Select tags (see `org-export-select-tags') and exclude tags (see
3797 `org-export-exclude-tags') are removed from the list.
3799 When non-nil, optional argument TAGS should be a list of strings.
3800 Any tag belonging to this list will also be removed.
3802 When optional argument INHERITED is non-nil, tags can also be
3803 inherited from parent headlines and FILETAGS keywords."
3804 (org-remove-if
3805 (lambda (tag) (or (member tag (plist-get info :select-tags))
3806 (member tag (plist-get info :exclude-tags))
3807 (member tag tags)))
3808 (if (not inherited) (org-element-property :tags element)
3809 ;; Build complete list of inherited tags.
3810 (let ((current-tag-list (org-element-property :tags element)))
3811 (dolist (parent (org-element-lineage element))
3812 (dolist (tag (org-element-property :tags parent))
3813 (when (and (memq (org-element-type parent) '(headline inlinetask))
3814 (not (member tag current-tag-list)))
3815 (push tag current-tag-list))))
3816 ;; Add FILETAGS keywords and return results.
3817 (org-uniquify (append (plist-get info :filetags) current-tag-list))))))
3819 (defun org-export-get-node-property (property blob &optional inherited)
3820 "Return node PROPERTY value for BLOB.
3822 PROPERTY is an upcase symbol (i.e. `:COOKIE_DATA'). BLOB is an
3823 element or object.
3825 If optional argument INHERITED is non-nil, the value can be
3826 inherited from a parent headline.
3828 Return value is a string or nil."
3829 (let ((headline (if (eq (org-element-type blob) 'headline) blob
3830 (org-export-get-parent-headline blob))))
3831 (if (not inherited) (org-element-property property blob)
3832 (let ((parent headline) value)
3833 (catch 'found
3834 (while parent
3835 (when (plist-member (nth 1 parent) property)
3836 (throw 'found (org-element-property property parent)))
3837 (setq parent (org-element-property :parent parent))))))))
3839 (defun org-export-get-category (blob info)
3840 "Return category for element or object BLOB.
3842 INFO is a plist used as a communication channel.
3844 CATEGORY is automatically inherited from a parent headline, from
3845 #+CATEGORY: keyword or created out of original file name. If all
3846 fail, the fall-back value is \"???\"."
3847 (or (org-export-get-node-property :CATEGORY blob t)
3848 (org-element-map (plist-get info :parse-tree) 'keyword
3849 (lambda (kwd)
3850 (when (equal (org-element-property :key kwd) "CATEGORY")
3851 (org-element-property :value kwd)))
3852 info 'first-match)
3853 (let ((file (plist-get info :input-file)))
3854 (and file (file-name-sans-extension (file-name-nondirectory file))))
3855 "???"))
3857 (defun org-export-get-alt-title (headline info)
3858 "Return alternative title for HEADLINE, as a secondary string.
3859 INFO is a plist used as a communication channel. If no optional
3860 title is defined, fall-back to the regular title."
3861 (let ((alt (org-element-property :ALT_TITLE headline)))
3862 (if alt (org-element-parse-secondary-string
3863 alt (org-element-restriction 'headline) headline)
3864 (org-element-property :title headline))))
3866 (defun org-export-first-sibling-p (blob info)
3867 "Non-nil when BLOB is the first sibling in its parent.
3868 BLOB is an element or an object. If BLOB is a headline, non-nil
3869 means it is the first sibling in the sub-tree. INFO is a plist
3870 used as a communication channel."
3871 (memq (org-element-type (org-export-get-previous-element blob info))
3872 '(nil section)))
3874 (defun org-export-last-sibling-p (blob info)
3875 "Non-nil when BLOB is the last sibling in its parent.
3876 BLOB is an element or an object. INFO is a plist used as
3877 a communication channel."
3878 (not (org-export-get-next-element blob info)))
3881 ;;;; For Keywords
3883 ;; `org-export-get-date' returns a date appropriate for the document
3884 ;; to about to be exported. In particular, it takes care of
3885 ;; `org-export-date-timestamp-format'.
3887 (defun org-export-get-date (info &optional fmt)
3888 "Return date value for the current document.
3890 INFO is a plist used as a communication channel. FMT, when
3891 non-nil, is a time format string that will be applied on the date
3892 if it consists in a single timestamp object. It defaults to
3893 `org-export-date-timestamp-format' when nil.
3895 A proper date can be a secondary string, a string or nil. It is
3896 meant to be translated with `org-export-data' or alike."
3897 (let ((date (plist-get info :date))
3898 (fmt (or fmt org-export-date-timestamp-format)))
3899 (cond ((not date) nil)
3900 ((and fmt
3901 (not (cdr date))
3902 (eq (org-element-type (car date)) 'timestamp))
3903 (org-timestamp-format (car date) fmt))
3904 (t date))))
3907 ;;;; For Links
3909 ;; `org-export-custom-protocol-maybe' handles custom protocol defined
3910 ;; with `org-add-link-type', which see.
3912 ;; `org-export-solidify-link-text' turns a string into a safer version
3913 ;; for links, replacing most non-standard characters with hyphens.
3915 ;; `org-export-get-coderef-format' returns an appropriate format
3916 ;; string for coderefs.
3918 ;; `org-export-inline-image-p' returns a non-nil value when the link
3919 ;; provided should be considered as an inline image.
3921 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
3922 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
3923 ;; returns an appropriate unique identifier when found, or nil.
3925 ;; `org-export-resolve-id-link' returns the first headline with
3926 ;; specified id or custom-id in parse tree, the path to the external
3927 ;; file with the id or nil when neither was found.
3929 ;; `org-export-resolve-coderef' associates a reference to a line
3930 ;; number in the element it belongs, or returns the reference itself
3931 ;; when the element isn't numbered.
3933 (defun org-export-solidify-link-text (s)
3934 "Take link text S and make a safe target out of it."
3935 (save-match-data
3936 (mapconcat 'identity (org-split-string s "[^a-zA-Z0-9_.-:]+") "-")))
3938 (defun org-export-custom-protocol-maybe (link desc backend)
3939 "Try exporting LINK with a dedicated function.
3941 DESC is its description, as a string, or nil. BACKEND is the
3942 back-end used for export, as a symbol.
3944 Return output as a string, or nil if no protocol handles LINK.
3946 A custom protocol has precedence over regular back-end export.
3947 The function ignores links with an implicit type (e.g.,
3948 \"custom-id\")."
3949 (let ((type (org-element-property :type link)))
3950 (unless (or (member type '("coderef" "custom-id" "fuzzy" "radio"))
3951 (not backend))
3952 (let ((protocol (nth 2 (assoc type org-link-protocols))))
3953 (and (functionp protocol)
3954 (funcall protocol
3955 (org-link-unescape (org-element-property :path link))
3956 desc
3957 backend))))))
3959 (defun org-export-get-coderef-format (path desc)
3960 "Return format string for code reference link.
3961 PATH is the link path. DESC is its description."
3962 (save-match-data
3963 (cond ((not desc) "%s")
3964 ((string-match (regexp-quote (concat "(" path ")")) desc)
3965 (replace-match "%s" t t desc))
3966 (t desc))))
3968 (defun org-export-inline-image-p (link &optional rules)
3969 "Non-nil if LINK object points to an inline image.
3971 Optional argument is a set of RULES defining inline images. It
3972 is an alist where associations have the following shape:
3974 \(TYPE . REGEXP)
3976 Applying a rule means apply REGEXP against LINK's path when its
3977 type is TYPE. The function will return a non-nil value if any of
3978 the provided rules is non-nil. The default rule is
3979 `org-export-default-inline-image-rule'.
3981 This only applies to links without a description."
3982 (and (not (org-element-contents link))
3983 (let ((case-fold-search t))
3984 (catch 'exit
3985 (dolist (rule (or rules org-export-default-inline-image-rule))
3986 (and (string= (org-element-property :type link) (car rule))
3987 (org-string-match-p (cdr rule)
3988 (org-element-property :path link))
3989 (throw 'exit t)))))))
3991 (defun org-export-resolve-coderef (ref info)
3992 "Resolve a code reference REF.
3994 INFO is a plist used as a communication channel.
3996 Return associated line number in source code, or REF itself,
3997 depending on src-block or example element's switches. Throw an
3998 error if no block contains REF."
3999 (or (org-element-map (plist-get info :parse-tree) '(example-block src-block)
4000 (lambda (el)
4001 (with-temp-buffer
4002 (insert (org-trim (org-element-property :value el)))
4003 (let* ((label-fmt (regexp-quote
4004 (or (org-element-property :label-fmt el)
4005 org-coderef-label-format)))
4006 (ref-re
4007 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
4008 (format label-fmt ref))))
4009 ;; Element containing REF is found. Resolve it to
4010 ;; either a label or a line number, as needed.
4011 (when (re-search-backward ref-re nil t)
4012 (cond
4013 ((org-element-property :use-labels el) ref)
4014 ((eq (org-element-property :number-lines el) 'continued)
4015 (+ (org-export-get-loc el info) (line-number-at-pos)))
4016 (t (line-number-at-pos)))))))
4017 info 'first-match)
4018 (user-error "Unable to resolve code reference: %s" ref)))
4020 (defun org-export-resolve-fuzzy-link (link info)
4021 "Return LINK destination.
4023 INFO is a plist holding contextual information.
4025 Return value can be an object, an element, or nil:
4027 - If LINK path matches a target object (i.e. <<path>>) return it.
4029 - If LINK path exactly matches the name affiliated keyword
4030 \(i.e. #+NAME: path) of an element, return that element.
4032 - If LINK path exactly matches any headline name, return that
4033 element. If more than one headline share that name, priority
4034 will be given to the one with the closest common ancestor, if
4035 any, or the first one in the parse tree otherwise.
4037 - Otherwise, throw an error.
4039 Assume LINK type is \"fuzzy\". White spaces are not
4040 significant."
4041 (let* ((raw-path (org-element-property :path link))
4042 (match-title-p (eq (aref raw-path 0) ?*))
4043 ;; Split PATH at white spaces so matches are space
4044 ;; insensitive.
4045 (path (org-split-string
4046 (if match-title-p (substring raw-path 1) raw-path)))
4047 ;; Cache for destinations that are not position dependent.
4048 (link-cache
4049 (or (plist-get info :resolve-fuzzy-link-cache)
4050 (plist-get (setq info (plist-put info :resolve-fuzzy-link-cache
4051 (make-hash-table :test 'equal)))
4052 :resolve-fuzzy-link-cache)))
4053 (cached (gethash path link-cache 'not-found)))
4054 (cond
4055 ;; Destination is not position dependent: use cached value.
4056 ((and (not match-title-p) (not (eq cached 'not-found))) cached)
4057 ;; First try to find a matching "<<path>>" unless user specified
4058 ;; he was looking for a headline (path starts with a "*"
4059 ;; character).
4060 ((and (not match-title-p)
4061 (let ((match (org-element-map (plist-get info :parse-tree) 'target
4062 (lambda (blob)
4063 (and (equal (org-split-string
4064 (org-element-property :value blob))
4065 path)
4066 blob))
4067 info 'first-match)))
4068 (and match (puthash path match link-cache)))))
4069 ;; Then try to find an element with a matching "#+NAME: path"
4070 ;; affiliated keyword.
4071 ((and (not match-title-p)
4072 (let ((match (org-element-map (plist-get info :parse-tree)
4073 org-element-all-elements
4074 (lambda (el)
4075 (let ((name (org-element-property :name el)))
4076 (when (and name
4077 (equal (org-split-string name) path))
4078 el)))
4079 info 'first-match)))
4080 (and match (puthash path match link-cache)))))
4081 ;; Last case: link either points to a headline or to nothingness.
4082 ;; Try to find the source, with priority given to headlines with
4083 ;; the closest common ancestor. If such candidate is found,
4084 ;; return it, otherwise signal an error.
4086 (let ((find-headline
4087 (function
4088 ;; Return first headline whose `:raw-value' property is
4089 ;; NAME in parse tree DATA, or nil. Statistics cookies
4090 ;; are ignored.
4091 (lambda (name data)
4092 (org-element-map data 'headline
4093 (lambda (headline)
4094 (when (equal (org-split-string
4095 (replace-regexp-in-string
4096 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
4097 (org-element-property :raw-value headline)))
4098 name)
4099 headline))
4100 info 'first-match)))))
4101 ;; Search among headlines sharing an ancestor with link, from
4102 ;; closest to farthest.
4103 (catch 'exit
4104 (dolist (parent
4105 (let ((parent-hl (org-export-get-parent-headline link)))
4106 (if (not parent-hl) (list (plist-get info :parse-tree))
4107 (org-element-lineage parent-hl nil t))))
4108 (let ((foundp (funcall find-headline path parent)))
4109 (when foundp (throw 'exit foundp))))
4110 ;; No destination found: error.
4111 (user-error "Unable to resolve link \"%s\"" raw-path)))))))
4113 (defun org-export-resolve-id-link (link info)
4114 "Return headline referenced as LINK destination.
4116 INFO is a plist used as a communication channel.
4118 Return value can be the headline element matched in current parse
4119 tree or a file name. Assume LINK type is either \"id\" or
4120 \"custom-id\". Throw an error if no match is found."
4121 (let ((id (org-element-property :path link)))
4122 ;; First check if id is within the current parse tree.
4123 (or (org-element-map (plist-get info :parse-tree) 'headline
4124 (lambda (headline)
4125 (when (or (equal (org-element-property :ID headline) id)
4126 (equal (org-element-property :CUSTOM_ID headline) id))
4127 headline))
4128 info 'first-match)
4129 ;; Otherwise, look for external files.
4130 (cdr (assoc id (plist-get info :id-alist)))
4131 (user-error "Unable to resolve ID \"%s\"" id))))
4133 (defun org-export-resolve-radio-link (link info)
4134 "Return radio-target object referenced as LINK destination.
4136 INFO is a plist used as a communication channel.
4138 Return value can be a radio-target object or nil. Assume LINK
4139 has type \"radio\"."
4140 (let ((path (replace-regexp-in-string
4141 "[ \r\t\n]+" " " (org-element-property :path link))))
4142 (org-element-map (plist-get info :parse-tree) 'radio-target
4143 (lambda (radio)
4144 (and (eq (compare-strings
4145 (replace-regexp-in-string
4146 "[ \r\t\n]+" " " (org-element-property :value radio))
4147 nil nil path nil nil t)
4149 radio))
4150 info 'first-match)))
4153 ;;;; For References
4155 ;; `org-export-get-ordinal' associates a sequence number to any object
4156 ;; or element.
4158 (defun org-export-get-ordinal (element info &optional types predicate)
4159 "Return ordinal number of an element or object.
4161 ELEMENT is the element or object considered. INFO is the plist
4162 used as a communication channel.
4164 Optional argument TYPES, when non-nil, is a list of element or
4165 object types, as symbols, that should also be counted in.
4166 Otherwise, only provided element's type is considered.
4168 Optional argument PREDICATE is a function returning a non-nil
4169 value if the current element or object should be counted in. It
4170 accepts two arguments: the element or object being considered and
4171 the plist used as a communication channel. This allows to count
4172 only a certain type of objects (i.e. inline images).
4174 Return value is a list of numbers if ELEMENT is a headline or an
4175 item. It is nil for keywords. It represents the footnote number
4176 for footnote definitions and footnote references. If ELEMENT is
4177 a target, return the same value as if ELEMENT was the closest
4178 table, item or headline containing the target. In any other
4179 case, return the sequence number of ELEMENT among elements or
4180 objects of the same type."
4181 ;; Ordinal of a target object refer to the ordinal of the closest
4182 ;; table, item, or headline containing the object.
4183 (when (eq (org-element-type element) 'target)
4184 (setq element
4185 (org-element-lineage
4186 element
4187 '(footnote-definition footnote-reference headline item table))))
4188 (case (org-element-type element)
4189 ;; Special case 1: A headline returns its number as a list.
4190 (headline (org-export-get-headline-number element info))
4191 ;; Special case 2: An item returns its number as a list.
4192 (item (let ((struct (org-element-property :structure element)))
4193 (org-list-get-item-number
4194 (org-element-property :begin element)
4195 struct
4196 (org-list-prevs-alist struct)
4197 (org-list-parents-alist struct))))
4198 ((footnote-definition footnote-reference)
4199 (org-export-get-footnote-number element info))
4200 (otherwise
4201 (let ((counter 0))
4202 ;; Increment counter until ELEMENT is found again.
4203 (org-element-map (plist-get info :parse-tree)
4204 (or types (org-element-type element))
4205 (lambda (el)
4206 (cond
4207 ((eq element el) (1+ counter))
4208 ((not predicate) (incf counter) nil)
4209 ((funcall predicate el info) (incf counter) nil)))
4210 info 'first-match)))))
4213 ;;;; For Src-Blocks
4215 ;; `org-export-get-loc' counts number of code lines accumulated in
4216 ;; src-block or example-block elements with a "+n" switch until
4217 ;; a given element, excluded. Note: "-n" switches reset that count.
4219 ;; `org-export-unravel-code' extracts source code (along with a code
4220 ;; references alist) from an `element-block' or `src-block' type
4221 ;; element.
4223 ;; `org-export-format-code' applies a formatting function to each line
4224 ;; of code, providing relative line number and code reference when
4225 ;; appropriate. Since it doesn't access the original element from
4226 ;; which the source code is coming, it expects from the code calling
4227 ;; it to know if lines should be numbered and if code references
4228 ;; should appear.
4230 ;; Eventually, `org-export-format-code-default' is a higher-level
4231 ;; function (it makes use of the two previous functions) which handles
4232 ;; line numbering and code references inclusion, and returns source
4233 ;; code in a format suitable for plain text or verbatim output.
4235 (defun org-export-get-loc (element info)
4236 "Return accumulated lines of code up to ELEMENT.
4238 INFO is the plist used as a communication channel.
4240 ELEMENT is excluded from count."
4241 (let ((loc 0))
4242 (org-element-map (plist-get info :parse-tree)
4243 `(src-block example-block ,(org-element-type element))
4244 (lambda (el)
4245 (cond
4246 ;; ELEMENT is reached: Quit the loop.
4247 ((eq el element))
4248 ;; Only count lines from src-block and example-block elements
4249 ;; with a "+n" or "-n" switch. A "-n" switch resets counter.
4250 ((not (memq (org-element-type el) '(src-block example-block))) nil)
4251 ((let ((linums (org-element-property :number-lines el)))
4252 (when linums
4253 ;; Accumulate locs or reset them.
4254 (let ((lines (org-count-lines
4255 (org-trim (org-element-property :value el)))))
4256 (setq loc (if (eq linums 'new) lines (+ loc lines))))))
4257 ;; Return nil to stay in the loop.
4258 nil)))
4259 info 'first-match)
4260 ;; Return value.
4261 loc))
4263 (defun org-export-unravel-code (element)
4264 "Clean source code and extract references out of it.
4266 ELEMENT has either a `src-block' an `example-block' type.
4268 Return a cons cell whose CAR is the source code, cleaned from any
4269 reference, protective commas and spurious indentation, and CDR is
4270 an alist between relative line number (integer) and name of code
4271 reference on that line (string)."
4272 (let* ((line 0) refs
4273 (value (org-element-property :value element))
4274 ;; Get code and clean it. Remove blank lines at its
4275 ;; beginning and end.
4276 (code (replace-regexp-in-string
4277 "\\`\\([ \t]*\n\\)+" ""
4278 (replace-regexp-in-string
4279 "\\([ \t]*\n\\)*[ \t]*\\'" "\n"
4280 (if (or org-src-preserve-indentation
4281 (org-element-property :preserve-indent element))
4282 value
4283 (org-element-remove-indentation value)))))
4284 ;; Get format used for references.
4285 (label-fmt (regexp-quote
4286 (or (org-element-property :label-fmt element)
4287 org-coderef-label-format)))
4288 ;; Build a regexp matching a loc with a reference.
4289 (with-ref-re
4290 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)[ \t]*\\)$"
4291 (replace-regexp-in-string
4292 "%s" "\\([-a-zA-Z0-9_ ]+\\)" label-fmt nil t))))
4293 ;; Return value.
4294 (cons
4295 ;; Code with references removed.
4296 (org-element-normalize-string
4297 (mapconcat
4298 (lambda (loc)
4299 (incf line)
4300 (if (not (string-match with-ref-re loc)) loc
4301 ;; Ref line: remove ref, and signal its position in REFS.
4302 (push (cons line (match-string 3 loc)) refs)
4303 (replace-match "" nil nil loc 1)))
4304 (org-split-string code "\n") "\n"))
4305 ;; Reference alist.
4306 refs)))
4308 (defun org-export-format-code (code fun &optional num-lines ref-alist)
4309 "Format CODE by applying FUN line-wise and return it.
4311 CODE is a string representing the code to format. FUN is
4312 a function. It must accept three arguments: a line of
4313 code (string), the current line number (integer) or nil and the
4314 reference associated to the current line (string) or nil.
4316 Optional argument NUM-LINES can be an integer representing the
4317 number of code lines accumulated until the current code. Line
4318 numbers passed to FUN will take it into account. If it is nil,
4319 FUN's second argument will always be nil. This number can be
4320 obtained with `org-export-get-loc' function.
4322 Optional argument REF-ALIST can be an alist between relative line
4323 number (i.e. ignoring NUM-LINES) and the name of the code
4324 reference on it. If it is nil, FUN's third argument will always
4325 be nil. It can be obtained through the use of
4326 `org-export-unravel-code' function."
4327 (let ((--locs (org-split-string code "\n"))
4328 (--line 0))
4329 (org-element-normalize-string
4330 (mapconcat
4331 (lambda (--loc)
4332 (incf --line)
4333 (let ((--ref (cdr (assq --line ref-alist))))
4334 (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
4335 --locs "\n"))))
4337 (defun org-export-format-code-default (element info)
4338 "Return source code from ELEMENT, formatted in a standard way.
4340 ELEMENT is either a `src-block' or `example-block' element. INFO
4341 is a plist used as a communication channel.
4343 This function takes care of line numbering and code references
4344 inclusion. Line numbers, when applicable, appear at the
4345 beginning of the line, separated from the code by two white
4346 spaces. Code references, on the other hand, appear flushed to
4347 the right, separated by six white spaces from the widest line of
4348 code."
4349 ;; Extract code and references.
4350 (let* ((code-info (org-export-unravel-code element))
4351 (code (car code-info))
4352 (code-lines (org-split-string code "\n")))
4353 (if (null code-lines) ""
4354 (let* ((refs (and (org-element-property :retain-labels element)
4355 (cdr code-info)))
4356 ;; Handle line numbering.
4357 (num-start (case (org-element-property :number-lines element)
4358 (continued (org-export-get-loc element info))
4359 (new 0)))
4360 (num-fmt
4361 (and num-start
4362 (format "%%%ds "
4363 (length (number-to-string
4364 (+ (length code-lines) num-start))))))
4365 ;; Prepare references display, if required. Any reference
4366 ;; should start six columns after the widest line of code,
4367 ;; wrapped with parenthesis.
4368 (max-width
4369 (+ (apply 'max (mapcar 'length code-lines))
4370 (if (not num-start) 0 (length (format num-fmt num-start))))))
4371 (org-export-format-code
4372 code
4373 (lambda (loc line-num ref)
4374 (let ((number-str (and num-fmt (format num-fmt line-num))))
4375 (concat
4376 number-str
4378 (and ref
4379 (concat (make-string
4380 (- (+ 6 max-width)
4381 (+ (length loc) (length number-str))) ? )
4382 (format "(%s)" ref))))))
4383 num-start refs)))))
4386 ;;;; For Tables
4388 ;; `org-export-table-has-special-column-p' and and
4389 ;; `org-export-table-row-is-special-p' are predicates used to look for
4390 ;; meta-information about the table structure.
4392 ;; `org-table-has-header-p' tells when the rows before the first rule
4393 ;; should be considered as table's header.
4395 ;; `org-export-table-cell-width', `org-export-table-cell-alignment'
4396 ;; and `org-export-table-cell-borders' extract information from
4397 ;; a table-cell element.
4399 ;; `org-export-table-dimensions' gives the number on rows and columns
4400 ;; in the table, ignoring horizontal rules and special columns.
4401 ;; `org-export-table-cell-address', given a table-cell object, returns
4402 ;; the absolute address of a cell. On the other hand,
4403 ;; `org-export-get-table-cell-at' does the contrary.
4405 ;; `org-export-table-cell-starts-colgroup-p',
4406 ;; `org-export-table-cell-ends-colgroup-p',
4407 ;; `org-export-table-row-starts-rowgroup-p',
4408 ;; `org-export-table-row-ends-rowgroup-p',
4409 ;; `org-export-table-row-starts-header-p',
4410 ;; `org-export-table-row-ends-header-p' and
4411 ;; `org-export-table-row-in-header-p' indicate position of current row
4412 ;; or cell within the table.
4414 (defun org-export-table-has-special-column-p (table)
4415 "Non-nil when TABLE has a special column.
4416 All special columns will be ignored during export."
4417 ;; The table has a special column when every first cell of every row
4418 ;; has an empty value or contains a symbol among "/", "#", "!", "$",
4419 ;; "*" "_" and "^". Though, do not consider a first row containing
4420 ;; only empty cells as special.
4421 (let ((special-column-p 'empty))
4422 (catch 'exit
4423 (mapc
4424 (lambda (row)
4425 (when (eq (org-element-property :type row) 'standard)
4426 (let ((value (org-element-contents
4427 (car (org-element-contents row)))))
4428 (cond ((member value '(("/") ("#") ("!") ("$") ("*") ("_") ("^")))
4429 (setq special-column-p 'special))
4430 ((not value))
4431 (t (throw 'exit nil))))))
4432 (org-element-contents table))
4433 (eq special-column-p 'special))))
4435 (defun org-export-table-has-header-p (table info)
4436 "Non-nil when TABLE has a header.
4438 INFO is a plist used as a communication channel.
4440 A table has a header when it contains at least two row groups."
4441 (let ((cache (or (plist-get info :table-header-cache)
4442 (plist-get (setq info
4443 (plist-put info :table-header-cache
4444 (make-hash-table :test 'eq)))
4445 :table-header-cache))))
4446 (or (gethash table cache)
4447 (let ((rowgroup 1) row-flag)
4448 (puthash
4449 table
4450 (org-element-map table 'table-row
4451 (lambda (row)
4452 (cond
4453 ((> rowgroup 1) t)
4454 ((and row-flag (eq (org-element-property :type row) 'rule))
4455 (incf rowgroup) (setq row-flag nil))
4456 ((and (not row-flag) (eq (org-element-property :type row)
4457 'standard))
4458 (setq row-flag t) nil)))
4459 info 'first-match)
4460 cache)))))
4462 (defun org-export-table-row-is-special-p (table-row info)
4463 "Non-nil if TABLE-ROW is considered special.
4465 INFO is a plist used as the communication channel.
4467 All special rows will be ignored during export."
4468 (when (eq (org-element-property :type table-row) 'standard)
4469 (let ((first-cell (org-element-contents
4470 (car (org-element-contents table-row)))))
4471 ;; A row is special either when...
4473 ;; ... it starts with a field only containing "/",
4474 (equal first-cell '("/"))
4475 ;; ... the table contains a special column and the row start
4476 ;; with a marking character among, "^", "_", "$" or "!",
4477 (and (org-export-table-has-special-column-p
4478 (org-export-get-parent table-row))
4479 (member first-cell '(("^") ("_") ("$") ("!"))))
4480 ;; ... it contains only alignment cookies and empty cells.
4481 (let ((special-row-p 'empty))
4482 (catch 'exit
4483 (mapc
4484 (lambda (cell)
4485 (let ((value (org-element-contents cell)))
4486 ;; Since VALUE is a secondary string, the following
4487 ;; checks avoid expanding it with `org-export-data'.
4488 (cond ((not value))
4489 ((and (not (cdr value))
4490 (stringp (car value))
4491 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'"
4492 (car value)))
4493 (setq special-row-p 'cookie))
4494 (t (throw 'exit nil)))))
4495 (org-element-contents table-row))
4496 (eq special-row-p 'cookie)))))))
4498 (defun org-export-table-row-group (table-row info)
4499 "Return TABLE-ROW's group number, as an integer.
4501 INFO is a plist used as the communication channel.
4503 Return value is the group number, as an integer, or nil for
4504 special rows and rows separators. First group is also table's
4505 header."
4506 (let ((cache (or (plist-get info :table-row-group-cache)
4507 (plist-get (setq info
4508 (plist-put info :table-row-group-cache
4509 (make-hash-table :test 'eq)))
4510 :table-row-group-cache))))
4511 (cond ((gethash table-row cache))
4512 ((eq (org-element-property :type table-row) 'rule) nil)
4513 (t (let ((group 0) row-flag)
4514 (org-element-map (org-export-get-parent table-row) 'table-row
4515 (lambda (row)
4516 (if (eq (org-element-property :type row) 'rule)
4517 (setq row-flag nil)
4518 (unless row-flag (incf group) (setq row-flag t)))
4519 (when (eq table-row row) (puthash table-row group cache)))
4520 info 'first-match))))))
4522 (defun org-export-table-cell-width (table-cell info)
4523 "Return TABLE-CELL contents width.
4525 INFO is a plist used as the communication channel.
4527 Return value is the width given by the last width cookie in the
4528 same column as TABLE-CELL, or nil."
4529 (let* ((row (org-export-get-parent table-cell))
4530 (table (org-export-get-parent row))
4531 (cells (org-element-contents row))
4532 (columns (length cells))
4533 (column (- columns (length (memq table-cell cells))))
4534 (cache (or (plist-get info :table-cell-width-cache)
4535 (plist-get (setq info
4536 (plist-put info :table-cell-width-cache
4537 (make-hash-table :test 'eq)))
4538 :table-cell-width-cache)))
4539 (width-vector (or (gethash table cache)
4540 (puthash table (make-vector columns 'empty) cache)))
4541 (value (aref width-vector column)))
4542 (if (not (eq value 'empty)) value
4543 (let (cookie-width)
4544 (dolist (row (org-element-contents table)
4545 (aset width-vector column cookie-width))
4546 (when (org-export-table-row-is-special-p row info)
4547 ;; In a special row, try to find a width cookie at COLUMN.
4548 (let* ((value (org-element-contents
4549 (elt (org-element-contents row) column)))
4550 (cookie (car value)))
4551 ;; The following checks avoid expanding unnecessarily
4552 ;; the cell with `org-export-data'.
4553 (when (and value
4554 (not (cdr value))
4555 (stringp cookie)
4556 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'" cookie)
4557 (match-string 1 cookie))
4558 (setq cookie-width
4559 (string-to-number (match-string 1 cookie)))))))))))
4561 (defun org-export-table-cell-alignment (table-cell info)
4562 "Return TABLE-CELL contents alignment.
4564 INFO is a plist used as the communication channel.
4566 Return alignment as specified by the last alignment cookie in the
4567 same column as TABLE-CELL. If no such cookie is found, a default
4568 alignment value will be deduced from fraction of numbers in the
4569 column (see `org-table-number-fraction' for more information).
4570 Possible values are `left', `right' and `center'."
4571 ;; Load `org-table-number-fraction' and `org-table-number-regexp'.
4572 (require 'org-table)
4573 (let* ((row (org-export-get-parent table-cell))
4574 (table (org-export-get-parent row))
4575 (cells (org-element-contents row))
4576 (columns (length cells))
4577 (column (- columns (length (memq table-cell cells))))
4578 (cache (or (plist-get info :table-cell-alignment-cache)
4579 (plist-get (setq info
4580 (plist-put info :table-cell-alignment-cache
4581 (make-hash-table :test 'eq)))
4582 :table-cell-alignment-cache)))
4583 (align-vector (or (gethash table cache)
4584 (puthash table (make-vector columns nil) cache))))
4585 (or (aref align-vector column)
4586 (let ((number-cells 0)
4587 (total-cells 0)
4588 cookie-align
4589 previous-cell-number-p)
4590 (dolist (row (org-element-contents (org-export-get-parent row)))
4591 (cond
4592 ;; In a special row, try to find an alignment cookie at
4593 ;; COLUMN.
4594 ((org-export-table-row-is-special-p row info)
4595 (let ((value (org-element-contents
4596 (elt (org-element-contents row) column))))
4597 ;; Since VALUE is a secondary string, the following
4598 ;; checks avoid useless expansion through
4599 ;; `org-export-data'.
4600 (when (and value
4601 (not (cdr value))
4602 (stringp (car value))
4603 (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'"
4604 (car value))
4605 (match-string 1 (car value)))
4606 (setq cookie-align (match-string 1 (car value))))))
4607 ;; Ignore table rules.
4608 ((eq (org-element-property :type row) 'rule))
4609 ;; In a standard row, check if cell's contents are
4610 ;; expressing some kind of number. Increase NUMBER-CELLS
4611 ;; accordingly. Though, don't bother if an alignment
4612 ;; cookie has already defined cell's alignment.
4613 ((not cookie-align)
4614 (let ((value (org-export-data
4615 (org-element-contents
4616 (elt (org-element-contents row) column))
4617 info)))
4618 (incf total-cells)
4619 ;; Treat an empty cell as a number if it follows
4620 ;; a number.
4621 (if (not (or (string-match org-table-number-regexp value)
4622 (and (string= value "") previous-cell-number-p)))
4623 (setq previous-cell-number-p nil)
4624 (setq previous-cell-number-p t)
4625 (incf number-cells))))))
4626 ;; Return value. Alignment specified by cookies has
4627 ;; precedence over alignment deduced from cell's contents.
4628 (aset align-vector
4629 column
4630 (cond ((equal cookie-align "l") 'left)
4631 ((equal cookie-align "r") 'right)
4632 ((equal cookie-align "c") 'center)
4633 ((>= (/ (float number-cells) total-cells)
4634 org-table-number-fraction)
4635 'right)
4636 (t 'left)))))))
4638 (defun org-export-table-cell-borders (table-cell info)
4639 "Return TABLE-CELL borders.
4641 INFO is a plist used as a communication channel.
4643 Return value is a list of symbols, or nil. Possible values are:
4644 `top', `bottom', `above', `below', `left' and `right'. Note:
4645 `top' (resp. `bottom') only happen for a cell in the first
4646 row (resp. last row) of the table, ignoring table rules, if any.
4648 Returned borders ignore special rows."
4649 (let* ((row (org-export-get-parent table-cell))
4650 (table (org-export-get-parent-table table-cell))
4651 borders)
4652 ;; Top/above border? TABLE-CELL has a border above when a rule
4653 ;; used to demarcate row groups can be found above. Hence,
4654 ;; finding a rule isn't sufficient to push `above' in BORDERS:
4655 ;; another regular row has to be found above that rule.
4656 (let (rule-flag)
4657 (catch 'exit
4658 (mapc (lambda (row)
4659 (cond ((eq (org-element-property :type row) 'rule)
4660 (setq rule-flag t))
4661 ((not (org-export-table-row-is-special-p row info))
4662 (if rule-flag (throw 'exit (push 'above borders))
4663 (throw 'exit nil)))))
4664 ;; Look at every row before the current one.
4665 (cdr (memq row (reverse (org-element-contents table)))))
4666 ;; No rule above, or rule found starts the table (ignoring any
4667 ;; special row): TABLE-CELL is at the top of the table.
4668 (when rule-flag (push 'above borders))
4669 (push 'top borders)))
4670 ;; Bottom/below border? TABLE-CELL has a border below when next
4671 ;; non-regular row below is a rule.
4672 (let (rule-flag)
4673 (catch 'exit
4674 (mapc (lambda (row)
4675 (cond ((eq (org-element-property :type row) 'rule)
4676 (setq rule-flag t))
4677 ((not (org-export-table-row-is-special-p row info))
4678 (if rule-flag (throw 'exit (push 'below borders))
4679 (throw 'exit nil)))))
4680 ;; Look at every row after the current one.
4681 (cdr (memq row (org-element-contents table))))
4682 ;; No rule below, or rule found ends the table (modulo some
4683 ;; special row): TABLE-CELL is at the bottom of the table.
4684 (when rule-flag (push 'below borders))
4685 (push 'bottom borders)))
4686 ;; Right/left borders? They can only be specified by column
4687 ;; groups. Column groups are defined in a row starting with "/".
4688 ;; Also a column groups row only contains "<", "<>", ">" or blank
4689 ;; cells.
4690 (catch 'exit
4691 (let ((column (let ((cells (org-element-contents row)))
4692 (- (length cells) (length (memq table-cell cells))))))
4693 (mapc
4694 (lambda (row)
4695 (unless (eq (org-element-property :type row) 'rule)
4696 (when (equal (org-element-contents
4697 (car (org-element-contents row)))
4698 '("/"))
4699 (let ((column-groups
4700 (mapcar
4701 (lambda (cell)
4702 (let ((value (org-element-contents cell)))
4703 (when (member value '(("<") ("<>") (">") nil))
4704 (car value))))
4705 (org-element-contents row))))
4706 ;; There's a left border when previous cell, if
4707 ;; any, ends a group, or current one starts one.
4708 (when (or (and (not (zerop column))
4709 (member (elt column-groups (1- column))
4710 '(">" "<>")))
4711 (member (elt column-groups column) '("<" "<>")))
4712 (push 'left borders))
4713 ;; There's a right border when next cell, if any,
4714 ;; starts a group, or current one ends one.
4715 (when (or (and (/= (1+ column) (length column-groups))
4716 (member (elt column-groups (1+ column))
4717 '("<" "<>")))
4718 (member (elt column-groups column) '(">" "<>")))
4719 (push 'right borders))
4720 (throw 'exit nil)))))
4721 ;; Table rows are read in reverse order so last column groups
4722 ;; row has precedence over any previous one.
4723 (reverse (org-element-contents table)))))
4724 ;; Return value.
4725 borders))
4727 (defun org-export-table-cell-starts-colgroup-p (table-cell info)
4728 "Non-nil when TABLE-CELL is at the beginning of a column group.
4729 INFO is a plist used as a communication channel."
4730 ;; A cell starts a column group either when it is at the beginning
4731 ;; of a row (or after the special column, if any) or when it has
4732 ;; a left border.
4733 (or (eq (org-element-map (org-export-get-parent table-cell) 'table-cell
4734 'identity info 'first-match)
4735 table-cell)
4736 (memq 'left (org-export-table-cell-borders table-cell info))))
4738 (defun org-export-table-cell-ends-colgroup-p (table-cell info)
4739 "Non-nil when TABLE-CELL is at the end of a column group.
4740 INFO is a plist used as a communication channel."
4741 ;; A cell ends a column group either when it is at the end of a row
4742 ;; or when it has a right border.
4743 (or (eq (car (last (org-element-contents
4744 (org-export-get-parent table-cell))))
4745 table-cell)
4746 (memq 'right (org-export-table-cell-borders table-cell info))))
4748 (defun org-export-table-row-starts-rowgroup-p (table-row info)
4749 "Non-nil when TABLE-ROW is at the beginning of a row group.
4750 INFO is a plist used as a communication channel."
4751 (unless (or (eq (org-element-property :type table-row) 'rule)
4752 (org-export-table-row-is-special-p table-row info))
4753 (let ((borders (org-export-table-cell-borders
4754 (car (org-element-contents table-row)) info)))
4755 (or (memq 'top borders) (memq 'above borders)))))
4757 (defun org-export-table-row-ends-rowgroup-p (table-row info)
4758 "Non-nil when TABLE-ROW is at the end of a row group.
4759 INFO is a plist used as a communication channel."
4760 (unless (or (eq (org-element-property :type table-row) 'rule)
4761 (org-export-table-row-is-special-p table-row info))
4762 (let ((borders (org-export-table-cell-borders
4763 (car (org-element-contents table-row)) info)))
4764 (or (memq 'bottom borders) (memq 'below borders)))))
4766 (defun org-export-table-row-in-header-p (table-row info)
4767 "Non-nil when TABLE-ROW is located within table's header.
4768 INFO is a plist used as a communication channel. Always return
4769 nil for special rows and rows separators."
4770 (and (org-export-table-has-header-p
4771 (org-export-get-parent-table table-row) info)
4772 (eql (org-export-table-row-group table-row info) 1)))
4774 (defun org-export-table-row-starts-header-p (table-row info)
4775 "Non-nil when TABLE-ROW is the first table header's row.
4776 INFO is a plist used as a communication channel."
4777 (and (org-export-table-row-in-header-p table-row info)
4778 (org-export-table-row-starts-rowgroup-p table-row info)))
4780 (defun org-export-table-row-ends-header-p (table-row info)
4781 "Non-nil when TABLE-ROW is the last table header's row.
4782 INFO is a plist used as a communication channel."
4783 (and (org-export-table-row-in-header-p table-row info)
4784 (org-export-table-row-ends-rowgroup-p table-row info)))
4786 (defun org-export-table-row-number (table-row info)
4787 "Return TABLE-ROW number.
4788 INFO is a plist used as a communication channel. Return value is
4789 zero-based and ignores separators. The function returns nil for
4790 special columns and separators."
4791 (when (and (eq (org-element-property :type table-row) 'standard)
4792 (not (org-export-table-row-is-special-p table-row info)))
4793 (let ((number 0))
4794 (org-element-map (org-export-get-parent-table table-row) 'table-row
4795 (lambda (row)
4796 (cond ((eq row table-row) number)
4797 ((eq (org-element-property :type row) 'standard)
4798 (incf number) nil)))
4799 info 'first-match))))
4801 (defun org-export-table-dimensions (table info)
4802 "Return TABLE dimensions.
4804 INFO is a plist used as a communication channel.
4806 Return value is a CONS like (ROWS . COLUMNS) where
4807 ROWS (resp. COLUMNS) is the number of exportable
4808 rows (resp. columns)."
4809 (let (first-row (columns 0) (rows 0))
4810 ;; Set number of rows, and extract first one.
4811 (org-element-map table 'table-row
4812 (lambda (row)
4813 (when (eq (org-element-property :type row) 'standard)
4814 (incf rows)
4815 (unless first-row (setq first-row row)))) info)
4816 ;; Set number of columns.
4817 (org-element-map first-row 'table-cell (lambda (cell) (incf columns)) info)
4818 ;; Return value.
4819 (cons rows columns)))
4821 (defun org-export-table-cell-address (table-cell info)
4822 "Return address of a regular TABLE-CELL object.
4824 TABLE-CELL is the cell considered. INFO is a plist used as
4825 a communication channel.
4827 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4828 zero-based index. Only exportable cells are considered. The
4829 function returns nil for other cells."
4830 (let* ((table-row (org-export-get-parent table-cell))
4831 (row-number (org-export-table-row-number table-row info)))
4832 (when row-number
4833 (cons row-number
4834 (let ((col-count 0))
4835 (org-element-map table-row 'table-cell
4836 (lambda (cell)
4837 (if (eq cell table-cell) col-count (incf col-count) nil))
4838 info 'first-match))))))
4840 (defun org-export-get-table-cell-at (address table info)
4841 "Return regular table-cell object at ADDRESS in TABLE.
4843 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4844 zero-based index. TABLE is a table type element. INFO is
4845 a plist used as a communication channel.
4847 If no table-cell, among exportable cells, is found at ADDRESS,
4848 return nil."
4849 (let ((column-pos (cdr address)) (column-count 0))
4850 (org-element-map
4851 ;; Row at (car address) or nil.
4852 (let ((row-pos (car address)) (row-count 0))
4853 (org-element-map table 'table-row
4854 (lambda (row)
4855 (cond ((eq (org-element-property :type row) 'rule) nil)
4856 ((= row-count row-pos) row)
4857 (t (incf row-count) nil)))
4858 info 'first-match))
4859 'table-cell
4860 (lambda (cell)
4861 (if (= column-count column-pos) cell
4862 (incf column-count) nil))
4863 info 'first-match)))
4866 ;;;; For Tables Of Contents
4868 ;; `org-export-collect-headlines' builds a list of all exportable
4869 ;; headline elements, maybe limited to a certain depth. One can then
4870 ;; easily parse it and transcode it.
4872 ;; Building lists of tables, figures or listings is quite similar.
4873 ;; Once the generic function `org-export-collect-elements' is defined,
4874 ;; `org-export-collect-tables', `org-export-collect-figures' and
4875 ;; `org-export-collect-listings' can be derived from it.
4877 (defun org-export-collect-headlines (info &optional n scope)
4878 "Collect headlines in order to build a table of contents.
4880 INFO is a plist used as a communication channel.
4882 When optional argument N is an integer, it specifies the depth of
4883 the table of contents. Otherwise, it is set to the value of the
4884 last headline level. See `org-export-headline-levels' for more
4885 information.
4887 Optional argument SCOPE, when non-nil, is an element. If it is
4888 a headline, only children of SCOPE are collected. Otherwise,
4889 collect children of the headline containing provided element. If
4890 there is no such headline, collect all headlines. In any case,
4891 argument N becomes relative to the level of that headline.
4893 Return a list of all exportable headlines as parsed elements.
4894 Footnote sections are ignored."
4895 (let* ((scope (cond ((not scope) (plist-get info :parse-tree))
4896 ((eq (org-element-type scope) 'headline) scope)
4897 ((org-export-get-parent-headline scope))
4898 (t (plist-get info :parse-tree))))
4899 (limit (plist-get info :headline-levels))
4900 (n (if (not (wholenump n)) limit
4901 (min (if (eq (org-element-type scope) 'org-data) n
4902 (+ (org-export-get-relative-level scope info) n))
4903 limit))))
4904 (org-element-map (org-element-contents scope) 'headline
4905 (lambda (headline)
4906 (unless (org-element-property :footnote-section-p headline)
4907 (let ((level (org-export-get-relative-level headline info)))
4908 (and (<= level n) headline))))
4909 info)))
4911 (defun org-export-collect-elements (type info &optional predicate)
4912 "Collect referenceable elements of a determined type.
4914 TYPE can be a symbol or a list of symbols specifying element
4915 types to search. Only elements with a caption are collected.
4917 INFO is a plist used as a communication channel.
4919 When non-nil, optional argument PREDICATE is a function accepting
4920 one argument, an element of type TYPE. It returns a non-nil
4921 value when that element should be collected.
4923 Return a list of all elements found, in order of appearance."
4924 (org-element-map (plist-get info :parse-tree) type
4925 (lambda (element)
4926 (and (org-element-property :caption element)
4927 (or (not predicate) (funcall predicate element))
4928 element))
4929 info))
4931 (defun org-export-collect-tables (info)
4932 "Build a list of tables.
4933 INFO is a plist used as a communication channel.
4935 Return a list of table elements with a caption."
4936 (org-export-collect-elements 'table info))
4938 (defun org-export-collect-figures (info predicate)
4939 "Build a list of figures.
4941 INFO is a plist used as a communication channel. PREDICATE is
4942 a function which accepts one argument: a paragraph element and
4943 whose return value is non-nil when that element should be
4944 collected.
4946 A figure is a paragraph type element, with a caption, verifying
4947 PREDICATE. The latter has to be provided since a \"figure\" is
4948 a vague concept that may depend on back-end.
4950 Return a list of elements recognized as figures."
4951 (org-export-collect-elements 'paragraph info predicate))
4953 (defun org-export-collect-listings (info)
4954 "Build a list of src blocks.
4956 INFO is a plist used as a communication channel.
4958 Return a list of src-block elements with a caption."
4959 (org-export-collect-elements 'src-block info))
4962 ;;;; Smart Quotes
4964 ;; The main function for the smart quotes sub-system is
4965 ;; `org-export-activate-smart-quotes', which replaces every quote in
4966 ;; a given string from the parse tree with its "smart" counterpart.
4968 ;; Dictionary for smart quotes is stored in
4969 ;; `org-export-smart-quotes-alist'.
4971 ;; Internally, regexps matching potential smart quotes (checks at
4972 ;; string boundaries are also necessary) are defined in
4973 ;; `org-export-smart-quotes-regexps'.
4975 (defconst org-export-smart-quotes-alist
4976 '(("da"
4977 ;; one may use: »...«, "...", ›...‹, or '...'.
4978 ;; http://sproget.dk/raad-og-regler/retskrivningsregler/retskrivningsregler/a7-40-60/a7-58-anforselstegn/
4979 ;; LaTeX quotes require Babel!
4980 (opening-double-quote :utf-8 "»" :html "&raquo;" :latex ">>"
4981 :texinfo "@guillemetright{}")
4982 (closing-double-quote :utf-8 "«" :html "&laquo;" :latex "<<"
4983 :texinfo "@guillemetleft{}")
4984 (opening-single-quote :utf-8 "›" :html "&rsaquo;" :latex "\\frq{}"
4985 :texinfo "@guilsinglright{}")
4986 (closing-single-quote :utf-8 "‹" :html "&lsaquo;" :latex "\\flq{}"
4987 :texinfo "@guilsingleft{}")
4988 (apostrophe :utf-8 "’" :html "&rsquo;"))
4989 ("de"
4990 (opening-double-quote :utf-8 "„" :html "&bdquo;" :latex "\"`"
4991 :texinfo "@quotedblbase{}")
4992 (closing-double-quote :utf-8 "“" :html "&ldquo;" :latex "\"'"
4993 :texinfo "@quotedblleft{}")
4994 (opening-single-quote :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}"
4995 :texinfo "@quotesinglbase{}")
4996 (closing-single-quote :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}"
4997 :texinfo "@quoteleft{}")
4998 (apostrophe :utf-8 "’" :html "&rsquo;"))
4999 ("en"
5000 (opening-double-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
5001 (closing-double-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
5002 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5003 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5004 (apostrophe :utf-8 "’" :html "&rsquo;"))
5005 ("es"
5006 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5007 :texinfo "@guillemetleft{}")
5008 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5009 :texinfo "@guillemetright{}")
5010 (opening-single-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
5011 (closing-single-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
5012 (apostrophe :utf-8 "’" :html "&rsquo;"))
5013 ("fr"
5014 (opening-double-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
5015 :texinfo "@guillemetleft{}@tie{}")
5016 (closing-double-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
5017 :texinfo "@tie{}@guillemetright{}")
5018 (opening-single-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
5019 :texinfo "@guillemetleft{}@tie{}")
5020 (closing-single-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
5021 :texinfo "@tie{}@guillemetright{}")
5022 (apostrophe :utf-8 "’" :html "&rsquo;"))
5023 ("no"
5024 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5025 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5026 :texinfo "@guillemetleft{}")
5027 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5028 :texinfo "@guillemetright{}")
5029 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5030 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5031 (apostrophe :utf-8 "’" :html "&rsquo;"))
5032 ("nb"
5033 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5034 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5035 :texinfo "@guillemetleft{}")
5036 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5037 :texinfo "@guillemetright{}")
5038 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5039 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5040 (apostrophe :utf-8 "’" :html "&rsquo;"))
5041 ("nn"
5042 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5043 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5044 :texinfo "@guillemetleft{}")
5045 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5046 :texinfo "@guillemetright{}")
5047 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5048 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5049 (apostrophe :utf-8 "’" :html "&rsquo;"))
5050 ("ru"
5051 ;; 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
5052 ;; http://www.artlebedev.ru/kovodstvo/sections/104/
5053 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "{}<<"
5054 :texinfo "@guillemetleft{}")
5055 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex ">>{}"
5056 :texinfo "@guillemetright{}")
5057 (opening-single-quote :utf-8 "„" :html "&bdquo;" :latex "\\glqq{}"
5058 :texinfo "@quotedblbase{}")
5059 (closing-single-quote :utf-8 "“" :html "&ldquo;" :latex "\\grqq{}"
5060 :texinfo "@quotedblleft{}")
5061 (apostrophe :utf-8 "’" :html: "&#39;"))
5062 ("sv"
5063 ;; based on https://sv.wikipedia.org/wiki/Citattecken
5064 (opening-double-quote :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
5065 (closing-double-quote :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
5066 (opening-single-quote :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "`")
5067 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "'")
5068 (apostrophe :utf-8 "’" :html "&rsquo;"))
5070 "Smart quotes translations.
5072 Alist whose CAR is a language string and CDR is an alist with
5073 quote type as key and a plist associating various encodings to
5074 their translation as value.
5076 A quote type can be any symbol among `opening-double-quote',
5077 `closing-double-quote', `opening-single-quote',
5078 `closing-single-quote' and `apostrophe'.
5080 Valid encodings include `:utf-8', `:html', `:latex' and
5081 `:texinfo'.
5083 If no translation is found, the quote character is left as-is.")
5085 (defun org-export--smart-quote-status (s info)
5086 "Return smart quote status at the beginning of string S.
5087 INFO is the current export state, as a plist."
5088 (let* ((parent (org-element-property :parent s))
5089 (cache (or (plist-get info :smart-quote-cache)
5090 (let ((table (make-hash-table :test #'eq)))
5091 (plist-put info :smart-quote-cache table)
5092 table)))
5093 (value (gethash parent cache 'missing-data)))
5094 (if (not (eq value 'missing-data)) (cdr (assq s value))
5095 (let (level1-open level2-open full-status)
5096 (org-element-map parent 'plain-text
5097 (lambda (text)
5098 (let ((start 0) current-status)
5099 (while (setq start (string-match "['\"]" text start))
5100 (incf start)
5101 (push
5102 (cond
5103 ((equal (match-string 0 text) "\"")
5104 (setf level1-open (not level1-open))
5105 (setf level2-open nil)
5106 (if level1-open 'opening-double-quote 'closing-double-quote))
5107 ;; Not already in a level 1 quote: this is an
5108 ;; apostrophe.
5109 ((not level1-open) 'apostrophe)
5110 ;; Apostrophe.
5111 ((org-string-match-p "\\S-'\\S-" text) 'apostrophe)
5112 ;; Apostrophe at the beginning of a string. Check
5113 ;; white space at the end of the last object.
5114 ((and (org-string-match-p "\\`'\\S-" text)
5115 (let ((p (org-export-get-previous-element text info)))
5116 (and p
5117 (if (stringp p)
5118 (not (org-string-match-p "[ \t]\\'" p))
5119 (memq (org-element-property :post-blank p)
5120 '(0 nil))))))
5121 'apostrophe)
5122 ;; Apostrophe at the end of a string. Check white
5123 ;; space at the beginning of the next object, which
5124 ;; can only happen if that object is a string.
5125 ((and (org-string-match-p "\\S-'\\'" text)
5126 (let ((n (org-export-get-next-element text info)))
5127 (and n
5128 (not (and (stringp n)
5129 (org-string-match-p "\\`[ \t]" n))))))
5130 'apostrophe)
5131 ;; Lonesome apostrophe. Check white space around
5132 ;; both ends.
5133 ((and (equal text "'")
5134 (let ((p (org-export-get-previous-element text info)))
5135 (and p
5136 (if (stringp p)
5137 (not (org-string-match-p "[ \t]\\'" p))
5138 (memq (org-element-property :post-blank p)
5139 '(0 nil)))
5140 (let ((n (org-export-get-next-element text info)))
5141 (and n
5142 (not (and (stringp n)
5143 (org-string-match-p "\\`[ \t]"
5144 n))))))))
5145 'apostrophe)
5146 ;; Else, consider it as a level 2 quote.
5147 (t (setf level2-open (not level2-open))
5148 (if level2-open 'opening-single-quote
5149 'closing-single-quote)))
5150 current-status))
5151 (when current-status
5152 (push (cons text (nreverse current-status)) full-status))))
5153 info nil org-element-recursive-objects)
5154 (puthash parent full-status cache)
5155 (cdr (assq s full-status))))))
5157 (defun org-export-activate-smart-quotes (s encoding info &optional original)
5158 "Replace regular quotes with \"smart\" quotes in string S.
5160 ENCODING is a symbol among `:html', `:latex', `:texinfo' and
5161 `:utf-8'. INFO is a plist used as a communication channel.
5163 The function has to retrieve information about string
5164 surroundings in parse tree. It can only happen with an
5165 unmodified string. Thus, if S has already been through another
5166 process, a non-nil ORIGINAL optional argument will provide that
5167 original string.
5169 Return the new string."
5170 (let ((quote-status
5171 (copy-sequence (org-export--smart-quote-status (or original s) info))))
5172 (replace-regexp-in-string
5173 "['\"]"
5174 (lambda (match)
5175 (or (plist-get
5176 (cdr (assq (pop quote-status)
5177 (cdr (assoc (plist-get info :language)
5178 org-export-smart-quotes-alist))))
5179 encoding)
5180 match))
5181 s nil t)))
5183 ;;;; Topology
5185 ;; Here are various functions to retrieve information about the
5186 ;; neighborhood of a given element or object. Neighbors of interest
5187 ;; are direct parent (`org-export-get-parent'), parent headline
5188 ;; (`org-export-get-parent-headline'), first element containing an
5189 ;; object, (`org-export-get-parent-element'), parent table
5190 ;; (`org-export-get-parent-table'), previous element or object
5191 ;; (`org-export-get-previous-element') and next element or object
5192 ;; (`org-export-get-next-element').
5194 ;; defsubst org-export-get-parent must be defined before first use
5196 (define-obsolete-function-alias
5197 'org-export-get-genealogy 'org-element-lineage "25.1")
5199 (defun org-export-get-parent-headline (blob)
5200 "Return BLOB parent headline or nil.
5201 BLOB is the element or object being considered."
5202 (org-element-lineage blob '(headline)))
5204 (defun org-export-get-parent-element (object)
5205 "Return first element containing OBJECT or nil.
5206 OBJECT is the object to consider."
5207 (org-element-lineage object org-element-all-elements))
5209 (defun org-export-get-parent-table (object)
5210 "Return OBJECT parent table or nil.
5211 OBJECT is either a `table-cell' or `table-element' type object."
5212 (org-element-lineage object '(table)))
5214 (defun org-export-get-previous-element (blob info &optional n)
5215 "Return previous element or object.
5217 BLOB is an element or object. INFO is a plist used as
5218 a communication channel. Return previous exportable element or
5219 object, a string, or nil.
5221 When optional argument N is a positive integer, return a list
5222 containing up to N siblings before BLOB, from farthest to
5223 closest. With any other non-nil value, return a list containing
5224 all of them."
5225 (let* ((secondary (org-element-secondary-p blob))
5226 (parent (org-export-get-parent blob))
5227 (siblings
5228 (if secondary (org-element-property secondary parent)
5229 (org-element-contents parent)))
5230 prev)
5231 (catch 'exit
5232 (dolist (obj (cdr (memq blob (reverse siblings))) prev)
5233 (cond ((memq obj (plist-get info :ignore-list)))
5234 ((null n) (throw 'exit obj))
5235 ((not (wholenump n)) (push obj prev))
5236 ((zerop n) (throw 'exit prev))
5237 (t (decf n) (push obj prev)))))))
5239 (defun org-export-get-next-element (blob info &optional n)
5240 "Return next element or object.
5242 BLOB is an element or object. INFO is a plist used as
5243 a communication channel. Return next exportable element or
5244 object, a string, or nil.
5246 When optional argument N is a positive integer, return a list
5247 containing up to N siblings after BLOB, from closest to farthest.
5248 With any other non-nil value, return a list containing all of
5249 them."
5250 (let* ((secondary (org-element-secondary-p blob))
5251 (parent (org-export-get-parent blob))
5252 (siblings
5253 (cdr (memq blob
5254 (if secondary (org-element-property secondary parent)
5255 (org-element-contents parent)))))
5256 next)
5257 (catch 'exit
5258 (dolist (obj siblings (nreverse next))
5259 (cond ((memq obj (plist-get info :ignore-list)))
5260 ((null n) (throw 'exit obj))
5261 ((not (wholenump n)) (push obj next))
5262 ((zerop n) (throw 'exit (nreverse next)))
5263 (t (decf n) (push obj next)))))))
5266 ;;;; Translation
5268 ;; `org-export-translate' translates a string according to the language
5269 ;; specified by the LANGUAGE keyword. `org-export-dictionary' contains
5270 ;; the dictionary used for the translation.
5272 (defconst org-export-dictionary
5273 '(("%e %n: %c"
5274 ("fr" :default "%e %n : %c" :html "%e&nbsp;%n&nbsp;: %c"))
5275 ("Author"
5276 ("ca" :default "Autor")
5277 ("cs" :default "Autor")
5278 ("da" :default "Forfatter")
5279 ("de" :default "Autor")
5280 ("eo" :html "A&#365;toro")
5281 ("es" :default "Autor")
5282 ("et" :default "Autor")
5283 ("fi" :html "Tekij&auml;")
5284 ("fr" :default "Auteur")
5285 ("hu" :default "Szerz&otilde;")
5286 ("is" :html "H&ouml;fundur")
5287 ("it" :default "Autore")
5288 ("ja" :default "著者" :html "&#33879;&#32773;")
5289 ("nl" :default "Auteur")
5290 ("no" :default "Forfatter")
5291 ("nb" :default "Forfatter")
5292 ("nn" :default "Forfattar")
5293 ("pl" :default "Autor")
5294 ("pt_BR" :default "Autor")
5295 ("ru" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5296 ("sv" :html "F&ouml;rfattare")
5297 ("uk" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5298 ("zh-CN" :html "&#20316;&#32773;" :utf-8 "作者")
5299 ("zh-TW" :html "&#20316;&#32773;" :utf-8 "作者"))
5300 ("Continued from previous page"
5301 ("de" :default "Fortsetzung von vorheriger Seite")
5302 ("es" :default "Continúa de la página anterior")
5303 ("fr" :default "Suite de la page précédente")
5304 ("it" :default "Continua da pagina precedente")
5305 ("ja" :default "前ページからの続き")
5306 ("nl" :default "Vervolg van vorige pagina")
5307 ("pt" :default "Continuação da página anterior")
5308 ("ru" :html "(&#1055;&#1088;&#1086;&#1076;&#1086;&#1083;&#1078;&#1077;&#1085;&#1080;&#1077;)"
5309 :utf-8 "(Продолжение)"))
5310 ("Continued on next page"
5311 ("de" :default "Fortsetzung nächste Seite")
5312 ("es" :default "Continúa en la siguiente página")
5313 ("fr" :default "Suite page suivante")
5314 ("it" :default "Continua alla pagina successiva")
5315 ("ja" :default "次ページに続く")
5316 ("nl" :default "Vervolg op volgende pagina")
5317 ("pt" :default "Continua na página seguinte")
5318 ("ru" :html "(&#1055;&#1088;&#1086;&#1076;&#1086;&#1083;&#1078;&#1077;&#1085;&#1080;&#1077; &#1089;&#1083;&#1077;&#1076;&#1091;&#1077;&#1090;)"
5319 :utf-8 "(Продолжение следует)"))
5320 ("Date"
5321 ("ca" :default "Data")
5322 ("cs" :default "Datum")
5323 ("da" :default "Dato")
5324 ("de" :default "Datum")
5325 ("eo" :default "Dato")
5326 ("es" :default "Fecha")
5327 ("et" :html "Kuup&#228;ev" :utf-8 "Kuupäev")
5328 ("fi" :html "P&auml;iv&auml;m&auml;&auml;r&auml;")
5329 ("hu" :html "D&aacute;tum")
5330 ("is" :default "Dagsetning")
5331 ("it" :default "Data")
5332 ("ja" :default "日付" :html "&#26085;&#20184;")
5333 ("nl" :default "Datum")
5334 ("no" :default "Dato")
5335 ("nb" :default "Dato")
5336 ("nn" :default "Dato")
5337 ("pl" :default "Data")
5338 ("pt_BR" :default "Data")
5339 ("ru" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5340 ("sv" :default "Datum")
5341 ("uk" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5342 ("zh-CN" :html "&#26085;&#26399;" :utf-8 "日期")
5343 ("zh-TW" :html "&#26085;&#26399;" :utf-8 "日期"))
5344 ("Equation"
5345 ("da" :default "Ligning")
5346 ("de" :default "Gleichung")
5347 ("es" :html "Ecuaci&oacute;n" :default "Ecuación")
5348 ("et" :html "V&#245;rrand" :utf-8 "Võrrand")
5349 ("fr" :ascii "Equation" :default "Équation")
5350 ("ja" :default "方程式")
5351 ("no" :default "Ligning")
5352 ("nb" :default "Ligning")
5353 ("nn" :default "Likning")
5354 ("pt_BR" :html "Equa&ccedil;&atilde;o" :default "Equação" :ascii "Equacao")
5355 ("ru" :html "&#1059;&#1088;&#1072;&#1074;&#1085;&#1077;&#1085;&#1080;&#1077;"
5356 :utf-8 "Уравнение")
5357 ("sv" :default "Ekvation")
5358 ("zh-CN" :html "&#26041;&#31243;" :utf-8 "方程"))
5359 ("Figure"
5360 ("da" :default "Figur")
5361 ("de" :default "Abbildung")
5362 ("es" :default "Figura")
5363 ("et" :default "Joonis")
5364 ("ja" :default "図" :html "&#22259;")
5365 ("no" :default "Illustrasjon")
5366 ("nb" :default "Illustrasjon")
5367 ("nn" :default "Illustrasjon")
5368 ("pt_BR" :default "Figura")
5369 ("ru" :html "&#1056;&#1080;&#1089;&#1091;&#1085;&#1086;&#1082;" :utf-8 "Рисунок")
5370 ("sv" :default "Illustration")
5371 ("zh-CN" :html "&#22270;" :utf-8 "图"))
5372 ("Figure %d:"
5373 ("da" :default "Figur %d")
5374 ("de" :default "Abbildung %d:")
5375 ("es" :default "Figura %d:")
5376 ("et" :default "Joonis %d:")
5377 ("fr" :default "Figure %d :" :html "Figure&nbsp;%d&nbsp;:")
5378 ("ja" :default "図%d: " :html "&#22259;%d: ")
5379 ("no" :default "Illustrasjon %d")
5380 ("nb" :default "Illustrasjon %d")
5381 ("nn" :default "Illustrasjon %d")
5382 ("pt_BR" :default "Figura %d:")
5383 ("ru" :html "&#1056;&#1080;&#1089;. %d.:" :utf-8 "Рис. %d.:")
5384 ("sv" :default "Illustration %d")
5385 ("zh-CN" :html "&#22270;%d&nbsp;" :utf-8 "图%d "))
5386 ("Footnotes"
5387 ("ca" :html "Peus de p&agrave;gina")
5388 ("cs" :default "Pozn\xe1mky pod carou")
5389 ("da" :default "Fodnoter")
5390 ("de" :html "Fu&szlig;noten" :default "Fußnoten")
5391 ("eo" :default "Piednotoj")
5392 ("es" :html "Nota al pie de p&aacute;gina" :default "Nota al pie de página")
5393 ("et" :html "Allm&#228;rkused" :utf-8 "Allmärkused")
5394 ("fi" :default "Alaviitteet")
5395 ("fr" :default "Notes de bas de page")
5396 ("hu" :html "L&aacute;bjegyzet")
5397 ("is" :html "Aftanm&aacute;lsgreinar")
5398 ("it" :html "Note a pi&egrave; di pagina")
5399 ("ja" :default "脚注" :html "&#33050;&#27880;")
5400 ("nl" :default "Voetnoten")
5401 ("no" :default "Fotnoter")
5402 ("nb" :default "Fotnoter")
5403 ("nn" :default "Fotnotar")
5404 ("pl" :default "Przypis")
5405 ("pt_BR" :html "Notas de Rodap&eacute;" :default "Notas de Rodapé" :ascii "Notas de Rodape")
5406 ("ru" :html "&#1057;&#1085;&#1086;&#1089;&#1082;&#1080;" :utf-8 "Сноски")
5407 ("sv" :default "Fotnoter")
5408 ("uk" :html "&#1055;&#1088;&#1080;&#1084;&#1110;&#1090;&#1082;&#1080;"
5409 :utf-8 "Примітки")
5410 ("zh-CN" :html "&#33050;&#27880;" :utf-8 "脚注")
5411 ("zh-TW" :html "&#33139;&#35387;" :utf-8 "腳註"))
5412 ("List of Listings"
5413 ("da" :default "Programmer")
5414 ("de" :default "Programmauflistungsverzeichnis")
5415 ("es" :default "Indice de Listados de programas")
5416 ("et" :default "Loendite nimekiri")
5417 ("fr" :default "Liste des programmes")
5418 ("ja" :default "ソースコード目次")
5419 ("no" :default "Dataprogrammer")
5420 ("nb" :default "Dataprogrammer")
5421 ("ru" :html "&#1057;&#1087;&#1080;&#1089;&#1086;&#1082; &#1088;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1086;&#1082;"
5422 :utf-8 "Список распечаток")
5423 ("zh-CN" :html "&#20195;&#30721;&#30446;&#24405;" :utf-8 "代码目录"))
5424 ("List of Tables"
5425 ("da" :default "Tabeller")
5426 ("de" :default "Tabellenverzeichnis")
5427 ("es" :default "Indice de tablas")
5428 ("et" :default "Tabelite nimekiri")
5429 ("fr" :default "Liste des tableaux")
5430 ("ja" :default "表目次")
5431 ("no" :default "Tabeller")
5432 ("nb" :default "Tabeller")
5433 ("nn" :default "Tabeller")
5434 ("pt_BR" :default "Índice de Tabelas" :ascii "Indice de Tabelas")
5435 ("ru" :html "&#1057;&#1087;&#1080;&#1089;&#1086;&#1082; &#1090;&#1072;&#1073;&#1083;&#1080;&#1094;"
5436 :utf-8 "Список таблиц")
5437 ("sv" :default "Tabeller")
5438 ("zh-CN" :html "&#34920;&#26684;&#30446;&#24405;" :utf-8 "表格目录"))
5439 ("Listing %d:"
5440 ("da" :default "Program %d")
5441 ("de" :default "Programmlisting %d")
5442 ("es" :default "Listado de programa %d")
5443 ("et" :default "Loend %d")
5444 ("fr" :default "Programme %d :" :html "Programme&nbsp;%d&nbsp;:")
5445 ("ja" :default "ソースコード%d:")
5446 ("no" :default "Dataprogram %d")
5447 ("nb" :default "Dataprogram %d")
5448 ("pt_BR" :default "Listagem %d")
5449 ("ru" :html "&#1056;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1082;&#1072; %d.:"
5450 :utf-8 "Распечатка %d.:")
5451 ("zh-CN" :html "&#20195;&#30721;%d&nbsp;" :utf-8 "代码%d "))
5452 ("References"
5453 ("fr" :ascii "References" :default "Références")
5454 ("de" :default "Quellen"))
5455 ("See section %s"
5456 ("da" :default "jævnfør afsnit %s")
5457 ("de" :default "siehe Abschnitt %s")
5458 ("es" :default "vea seccion %s")
5459 ("et" :html "Vaata peat&#252;kki %s" :utf-8 "Vaata peatükki %s")
5460 ("fr" :default "cf. section %s")
5461 ("ja" :default "セクション %s を参照")
5462 ("pt_BR" :html "Veja a se&ccedil;&atilde;o %s" :default "Veja a seção %s"
5463 :ascii "Veja a secao %s")
5464 ("ru" :html "&#1057;&#1084;. &#1088;&#1072;&#1079;&#1076;&#1077;&#1083; %s"
5465 :utf-8 "См. раздел %s")
5466 ("zh-CN" :html "&#21442;&#35265;&#31532;%s&#33410;" :utf-8 "参见第%s节"))
5467 ("Table"
5468 ("de" :default "Tabelle")
5469 ("es" :default "Tabla")
5470 ("et" :default "Tabel")
5471 ("fr" :default "Tableau")
5472 ("ja" :default "表" :html "&#34920;")
5473 ("pt_BR" :default "Tabela")
5474 ("ru" :html "&#1058;&#1072;&#1073;&#1083;&#1080;&#1094;&#1072;"
5475 :utf-8 "Таблица")
5476 ("zh-CN" :html "&#34920;" :utf-8 "表"))
5477 ("Table %d:"
5478 ("da" :default "Tabel %d")
5479 ("de" :default "Tabelle %d")
5480 ("es" :default "Tabla %d")
5481 ("et" :default "Tabel %d")
5482 ("fr" :default "Tableau %d :")
5483 ("ja" :default "表%d:" :html "&#34920;%d:")
5484 ("no" :default "Tabell %d")
5485 ("nb" :default "Tabell %d")
5486 ("nn" :default "Tabell %d")
5487 ("pt_BR" :default "Tabela %d")
5488 ("ru" :html "&#1058;&#1072;&#1073;&#1083;&#1080;&#1094;&#1072; %d.:"
5489 :utf-8 "Таблица %d.:")
5490 ("sv" :default "Tabell %d")
5491 ("zh-CN" :html "&#34920;%d&nbsp;" :utf-8 "表%d "))
5492 ("Table of Contents"
5493 ("ca" :html "&Iacute;ndex")
5494 ("cs" :default "Obsah")
5495 ("da" :default "Indhold")
5496 ("de" :default "Inhaltsverzeichnis")
5497 ("eo" :default "Enhavo")
5498 ("es" :html "&Iacute;ndice")
5499 ("et" :default "Sisukord")
5500 ("fi" :html "Sis&auml;llysluettelo")
5501 ("fr" :ascii "Sommaire" :default "Table des matières")
5502 ("hu" :html "Tartalomjegyz&eacute;k")
5503 ("is" :default "Efnisyfirlit")
5504 ("it" :default "Indice")
5505 ("ja" :default "目次" :html "&#30446;&#27425;")
5506 ("nl" :default "Inhoudsopgave")
5507 ("no" :default "Innhold")
5508 ("nb" :default "Innhold")
5509 ("nn" :default "Innhald")
5510 ("pl" :html "Spis tre&#x015b;ci")
5511 ("pt_BR" :html "&Iacute;ndice" :utf8 "Índice" :ascii "Indice")
5512 ("ru" :html "&#1057;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1077;"
5513 :utf-8 "Содержание")
5514 ("sv" :html "Inneh&aring;ll")
5515 ("uk" :html "&#1047;&#1084;&#1110;&#1089;&#1090;" :utf-8 "Зміст")
5516 ("zh-CN" :html "&#30446;&#24405;" :utf-8 "目录")
5517 ("zh-TW" :html "&#30446;&#37636;" :utf-8 "目錄"))
5518 ("Unknown reference"
5519 ("da" :default "ukendt reference")
5520 ("de" :default "Unbekannter Verweis")
5521 ("es" :default "referencia desconocida")
5522 ("et" :default "Tundmatu viide")
5523 ("fr" :ascii "Destination inconnue" :default "Référence inconnue")
5524 ("ja" :default "不明な参照先")
5525 ("pt_BR" :default "Referência desconhecida"
5526 :ascii "Referencia desconhecida")
5527 ("ru" :html "&#1053;&#1077;&#1080;&#1079;&#1074;&#1077;&#1089;&#1090;&#1085;&#1072;&#1103; &#1089;&#1089;&#1099;&#1083;&#1082;&#1072;"
5528 :utf-8 "Неизвестная ссылка")
5529 ("zh-CN" :html "&#26410;&#30693;&#24341;&#29992;" :utf-8 "未知引用")))
5530 "Dictionary for export engine.
5532 Alist whose car is the string to translate and cdr is an alist
5533 whose car is the language string and cdr is a plist whose
5534 properties are possible charsets and values translated terms.
5536 It is used as a database for `org-export-translate'. Since this
5537 function returns the string as-is if no translation was found,
5538 the variable only needs to record values different from the
5539 entry.")
5541 (defun org-export-translate (s encoding info)
5542 "Translate string S according to language specification.
5544 ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1'
5545 and `:utf-8'. INFO is a plist used as a communication channel.
5547 Translation depends on `:language' property. Return the
5548 translated string. If no translation is found, try to fall back
5549 to `:default' encoding. If it fails, return S."
5550 (let* ((lang (plist-get info :language))
5551 (translations (cdr (assoc lang
5552 (cdr (assoc s org-export-dictionary))))))
5553 (or (plist-get translations encoding)
5554 (plist-get translations :default)
5555 s)))
5559 ;;; Asynchronous Export
5561 ;; `org-export-async-start' is the entry point for asynchronous
5562 ;; export. It recreates current buffer (including visibility,
5563 ;; narrowing and visited file) in an external Emacs process, and
5564 ;; evaluates a command there. It then applies a function on the
5565 ;; returned results in the current process.
5567 ;; At a higher level, `org-export-to-buffer' and `org-export-to-file'
5568 ;; allow to export to a buffer or a file, asynchronously or not.
5570 ;; `org-export-output-file-name' is an auxiliary function meant to be
5571 ;; used with `org-export-to-file'. With a given extension, it tries
5572 ;; to provide a canonical file name to write export output to.
5574 ;; Asynchronously generated results are never displayed directly.
5575 ;; Instead, they are stored in `org-export-stack-contents'. They can
5576 ;; then be retrieved by calling `org-export-stack'.
5578 ;; Export Stack is viewed through a dedicated major mode
5579 ;;`org-export-stack-mode' and tools: `org-export-stack-refresh',
5580 ;;`org-export-stack-delete', `org-export-stack-view' and
5581 ;;`org-export-stack-clear'.
5583 ;; For back-ends, `org-export-add-to-stack' add a new source to stack.
5584 ;; It should be used whenever `org-export-async-start' is called.
5586 (defmacro org-export-async-start (fun &rest body)
5587 "Call function FUN on the results returned by BODY evaluation.
5589 FUN is an anonymous function of one argument. BODY evaluation
5590 happens in an asynchronous process, from a buffer which is an
5591 exact copy of the current one.
5593 Use `org-export-add-to-stack' in FUN in order to register results
5594 in the stack.
5596 This is a low level function. See also `org-export-to-buffer'
5597 and `org-export-to-file' for more specialized functions."
5598 (declare (indent 1) (debug t))
5599 (org-with-gensyms (process temp-file copy-fun proc-buffer coding)
5600 ;; Write the full sexp evaluating BODY in a copy of the current
5601 ;; buffer to a temporary file, as it may be too long for program
5602 ;; args in `start-process'.
5603 `(with-temp-message "Initializing asynchronous export process"
5604 (let ((,copy-fun (org-export--generate-copy-script (current-buffer)))
5605 (,temp-file (make-temp-file "org-export-process"))
5606 (,coding buffer-file-coding-system))
5607 (with-temp-file ,temp-file
5608 (insert
5609 ;; Null characters (from variable values) are inserted
5610 ;; within the file. As a consequence, coding system for
5611 ;; buffer contents will not be recognized properly. So,
5612 ;; we make sure it is the same as the one used to display
5613 ;; the original buffer.
5614 (format ";; -*- coding: %s; -*-\n%S"
5615 ,coding
5616 `(with-temp-buffer
5617 (when org-export-async-debug '(setq debug-on-error t))
5618 ;; Ignore `kill-emacs-hook' and code evaluation
5619 ;; queries from Babel as we need a truly
5620 ;; non-interactive process.
5621 (setq kill-emacs-hook nil
5622 org-babel-confirm-evaluate-answer-no t)
5623 ;; Initialize export framework.
5624 (require 'ox)
5625 ;; Re-create current buffer there.
5626 (funcall ,,copy-fun)
5627 (restore-buffer-modified-p nil)
5628 ;; Sexp to evaluate in the buffer.
5629 (print (progn ,,@body))))))
5630 ;; Start external process.
5631 (let* ((process-connection-type nil)
5632 (,proc-buffer (generate-new-buffer-name "*Org Export Process*"))
5633 (,process
5634 (apply
5635 #'start-process
5636 (append
5637 (list "org-export-process"
5638 ,proc-buffer
5639 (expand-file-name invocation-name invocation-directory)
5640 "--batch")
5641 (if org-export-async-init-file
5642 (list "-Q" "-l" org-export-async-init-file)
5643 (list "-l" user-init-file))
5644 (list "-l" ,temp-file)))))
5645 ;; Register running process in stack.
5646 (org-export-add-to-stack (get-buffer ,proc-buffer) nil ,process)
5647 ;; Set-up sentinel in order to catch results.
5648 (let ((handler ,fun))
5649 (set-process-sentinel
5650 ,process
5651 `(lambda (p status)
5652 (let ((proc-buffer (process-buffer p)))
5653 (when (eq (process-status p) 'exit)
5654 (unwind-protect
5655 (if (zerop (process-exit-status p))
5656 (unwind-protect
5657 (let ((results
5658 (with-current-buffer proc-buffer
5659 (goto-char (point-max))
5660 (backward-sexp)
5661 (read (current-buffer)))))
5662 (funcall ,handler results))
5663 (unless org-export-async-debug
5664 (and (get-buffer proc-buffer)
5665 (kill-buffer proc-buffer))))
5666 (org-export-add-to-stack proc-buffer nil p)
5667 (ding)
5668 (message "Process '%s' exited abnormally" p))
5669 (unless org-export-async-debug
5670 (delete-file ,,temp-file)))))))))))))
5672 ;;;###autoload
5673 (defun org-export-to-buffer
5674 (backend buffer
5675 &optional async subtreep visible-only body-only ext-plist
5676 post-process)
5677 "Call `org-export-as' with output to a specified buffer.
5679 BACKEND is either an export back-end, as returned by, e.g.,
5680 `org-export-create-backend', or a symbol referring to
5681 a registered back-end.
5683 BUFFER is the name of the output buffer. If it already exists,
5684 it will be erased first, otherwise, it will be created.
5686 A non-nil optional argument ASYNC means the process should happen
5687 asynchronously. The resulting buffer should then be accessible
5688 through the `org-export-stack' interface. When ASYNC is nil, the
5689 buffer is displayed if `org-export-show-temporary-export-buffer'
5690 is non-nil.
5692 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
5693 EXT-PLIST are similar to those used in `org-export-as', which
5694 see.
5696 Optional argument POST-PROCESS is a function which should accept
5697 no argument. It is always called within the current process,
5698 from BUFFER, with point at its beginning. Export back-ends can
5699 use it to set a major mode there, e.g,
5701 \(defun org-latex-export-as-latex
5702 \(&optional async subtreep visible-only body-only ext-plist)
5703 \(interactive)
5704 \(org-export-to-buffer 'latex \"*Org LATEX Export*\"
5705 async subtreep visible-only body-only ext-plist (lambda () (LaTeX-mode))))
5707 This function returns BUFFER."
5708 (declare (indent 2))
5709 (if async
5710 (org-export-async-start
5711 `(lambda (output)
5712 (with-current-buffer (get-buffer-create ,buffer)
5713 (erase-buffer)
5714 (setq buffer-file-coding-system ',buffer-file-coding-system)
5715 (insert output)
5716 (goto-char (point-min))
5717 (org-export-add-to-stack (current-buffer) ',backend)
5718 (ignore-errors (funcall ,post-process))))
5719 `(org-export-as
5720 ',backend ,subtreep ,visible-only ,body-only ',ext-plist))
5721 (let ((output
5722 (org-export-as backend subtreep visible-only body-only ext-plist))
5723 (buffer (get-buffer-create buffer))
5724 (encoding buffer-file-coding-system))
5725 (when (and (org-string-nw-p output) (org-export--copy-to-kill-ring-p))
5726 (org-kill-new output))
5727 (with-current-buffer buffer
5728 (erase-buffer)
5729 (setq buffer-file-coding-system encoding)
5730 (insert output)
5731 (goto-char (point-min))
5732 (and (functionp post-process) (funcall post-process)))
5733 (when org-export-show-temporary-export-buffer
5734 (switch-to-buffer-other-window buffer))
5735 buffer)))
5737 ;;;###autoload
5738 (defun org-export-to-file
5739 (backend file &optional async subtreep visible-only body-only ext-plist
5740 post-process)
5741 "Call `org-export-as' with output to a specified file.
5743 BACKEND is either an export back-end, as returned by, e.g.,
5744 `org-export-create-backend', or a symbol referring to
5745 a registered back-end. FILE is the name of the output file, as
5746 a string.
5748 A non-nil optional argument ASYNC means the process should happen
5749 asynchronously. The resulting buffer will then be accessible
5750 through the `org-export-stack' interface.
5752 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
5753 EXT-PLIST are similar to those used in `org-export-as', which
5754 see.
5756 Optional argument POST-PROCESS is called with FILE as its
5757 argument and happens asynchronously when ASYNC is non-nil. It
5758 has to return a file name, or nil. Export back-ends can use this
5759 to send the output file through additional processing, e.g,
5761 \(defun org-latex-export-to-latex
5762 \(&optional async subtreep visible-only body-only ext-plist)
5763 \(interactive)
5764 \(let ((outfile (org-export-output-file-name \".tex\" subtreep)))
5765 \(org-export-to-file 'latex outfile
5766 async subtreep visible-only body-only ext-plist
5767 \(lambda (file) (org-latex-compile file)))
5769 The function returns either a file name returned by POST-PROCESS,
5770 or FILE."
5771 (declare (indent 2))
5772 (if (not (file-writable-p file)) (error "Output file not writable")
5773 (let ((ext-plist (org-combine-plists `(:output-file ,file) ext-plist))
5774 (encoding (or org-export-coding-system buffer-file-coding-system)))
5775 (if async
5776 (org-export-async-start
5777 `(lambda (file)
5778 (org-export-add-to-stack (expand-file-name file) ',backend))
5779 `(let ((output
5780 (org-export-as
5781 ',backend ,subtreep ,visible-only ,body-only
5782 ',ext-plist)))
5783 (with-temp-buffer
5784 (insert output)
5785 (let ((coding-system-for-write ',encoding))
5786 (write-file ,file)))
5787 (or (ignore-errors (funcall ',post-process ,file)) ,file)))
5788 (let ((output (org-export-as
5789 backend subtreep visible-only body-only ext-plist)))
5790 (with-temp-buffer
5791 (insert output)
5792 (let ((coding-system-for-write encoding))
5793 (write-file file)))
5794 (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p output))
5795 (org-kill-new output))
5796 ;; Get proper return value.
5797 (or (and (functionp post-process) (funcall post-process file))
5798 file))))))
5800 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
5801 "Return output file's name according to buffer specifications.
5803 EXTENSION is a string representing the output file extension,
5804 with the leading dot.
5806 With a non-nil optional argument SUBTREEP, try to determine
5807 output file's name by looking for \"EXPORT_FILE_NAME\" property
5808 of subtree at point.
5810 When optional argument PUB-DIR is set, use it as the publishing
5811 directory.
5813 When optional argument VISIBLE-ONLY is non-nil, don't export
5814 contents of hidden elements.
5816 Return file name as a string."
5817 (let* ((visited-file (buffer-file-name (buffer-base-buffer)))
5818 (base-name
5819 ;; File name may come from EXPORT_FILE_NAME subtree
5820 ;; property, assuming point is at beginning of said
5821 ;; sub-tree.
5822 (file-name-sans-extension
5823 (or (and subtreep
5824 (org-entry-get
5825 (save-excursion
5826 (ignore-errors (org-back-to-heading) (point)))
5827 "EXPORT_FILE_NAME" t))
5828 ;; File name may be extracted from buffer's associated
5829 ;; file, if any.
5830 (and visited-file (file-name-nondirectory visited-file))
5831 ;; Can't determine file name on our own: Ask user.
5832 (let ((read-file-name-function
5833 (and org-completion-use-ido 'ido-read-file-name)))
5834 (read-file-name
5835 "Output file: " pub-dir nil nil nil
5836 (lambda (name)
5837 (string= (file-name-extension name t) extension)))))))
5838 (output-file
5839 ;; Build file name. Enforce EXTENSION over whatever user
5840 ;; may have come up with. PUB-DIR, if defined, always has
5841 ;; precedence over any provided path.
5842 (cond
5843 (pub-dir
5844 (concat (file-name-as-directory pub-dir)
5845 (file-name-nondirectory base-name)
5846 extension))
5847 ((file-name-absolute-p base-name) (concat base-name extension))
5848 (t (concat (file-name-as-directory ".") base-name extension)))))
5849 ;; If writing to OUTPUT-FILE would overwrite original file, append
5850 ;; EXTENSION another time to final name.
5851 (if (and visited-file (org-file-equal-p visited-file output-file))
5852 (concat output-file extension)
5853 output-file)))
5855 (defun org-export-add-to-stack (source backend &optional process)
5856 "Add a new result to export stack if not present already.
5858 SOURCE is a buffer or a file name containing export results.
5859 BACKEND is a symbol representing export back-end used to generate
5862 Entries already pointing to SOURCE and unavailable entries are
5863 removed beforehand. Return the new stack."
5864 (setq org-export-stack-contents
5865 (cons (list source backend (or process (current-time)))
5866 (org-export-stack-remove source))))
5868 (defun org-export-stack ()
5869 "Menu for asynchronous export results and running processes."
5870 (interactive)
5871 (let ((buffer (get-buffer-create "*Org Export Stack*")))
5872 (set-buffer buffer)
5873 (when (zerop (buffer-size)) (org-export-stack-mode))
5874 (org-export-stack-refresh)
5875 (pop-to-buffer buffer))
5876 (message "Type \"q\" to quit, \"?\" for help"))
5878 (defun org-export--stack-source-at-point ()
5879 "Return source from export results at point in stack."
5880 (let ((source (car (nth (1- (org-current-line)) org-export-stack-contents))))
5881 (if (not source) (error "Source unavailable, please refresh buffer")
5882 (let ((source-name (if (stringp source) source (buffer-name source))))
5883 (if (save-excursion
5884 (beginning-of-line)
5885 (looking-at (concat ".* +" (regexp-quote source-name) "$")))
5886 source
5887 ;; SOURCE is not consistent with current line. The stack
5888 ;; view is outdated.
5889 (error "Source unavailable; type `g' to update buffer"))))))
5891 (defun org-export-stack-clear ()
5892 "Remove all entries from export stack."
5893 (interactive)
5894 (setq org-export-stack-contents nil))
5896 (defun org-export-stack-refresh (&rest dummy)
5897 "Refresh the asynchronous export stack.
5898 DUMMY is ignored. Unavailable sources are removed from the list.
5899 Return the new stack."
5900 (let ((inhibit-read-only t))
5901 (org-preserve-lc
5902 (erase-buffer)
5903 (insert (concat
5904 (let ((counter 0))
5905 (mapconcat
5906 (lambda (entry)
5907 (let ((proc-p (processp (nth 2 entry))))
5908 (concat
5909 ;; Back-end.
5910 (format " %-12s " (or (nth 1 entry) ""))
5911 ;; Age.
5912 (let ((data (nth 2 entry)))
5913 (if proc-p (format " %6s " (process-status data))
5914 ;; Compute age of the results.
5915 (org-format-seconds
5916 "%4h:%.2m "
5917 (float-time (time-since data)))))
5918 ;; Source.
5919 (format " %s"
5920 (let ((source (car entry)))
5921 (if (stringp source) source
5922 (buffer-name source)))))))
5923 ;; Clear stack from exited processes, dead buffers or
5924 ;; non-existent files.
5925 (setq org-export-stack-contents
5926 (org-remove-if-not
5927 (lambda (el)
5928 (if (processp (nth 2 el))
5929 (buffer-live-p (process-buffer (nth 2 el)))
5930 (let ((source (car el)))
5931 (if (bufferp source) (buffer-live-p source)
5932 (file-exists-p source)))))
5933 org-export-stack-contents)) "\n")))))))
5935 (defun org-export-stack-remove (&optional source)
5936 "Remove export results at point from stack.
5937 If optional argument SOURCE is non-nil, remove it instead."
5938 (interactive)
5939 (let ((source (or source (org-export--stack-source-at-point))))
5940 (setq org-export-stack-contents
5941 (org-remove-if (lambda (el) (equal (car el) source))
5942 org-export-stack-contents))))
5944 (defun org-export-stack-view (&optional in-emacs)
5945 "View export results at point in stack.
5946 With an optional prefix argument IN-EMACS, force viewing files
5947 within Emacs."
5948 (interactive "P")
5949 (let ((source (org-export--stack-source-at-point)))
5950 (cond ((processp source)
5951 (org-switch-to-buffer-other-window (process-buffer source)))
5952 ((bufferp source) (org-switch-to-buffer-other-window source))
5953 (t (org-open-file source in-emacs)))))
5955 (defvar org-export-stack-mode-map
5956 (let ((km (make-sparse-keymap)))
5957 (define-key km " " 'next-line)
5958 (define-key km "n" 'next-line)
5959 (define-key km "\C-n" 'next-line)
5960 (define-key km [down] 'next-line)
5961 (define-key km "p" 'previous-line)
5962 (define-key km "\C-p" 'previous-line)
5963 (define-key km "\C-?" 'previous-line)
5964 (define-key km [up] 'previous-line)
5965 (define-key km "C" 'org-export-stack-clear)
5966 (define-key km "v" 'org-export-stack-view)
5967 (define-key km (kbd "RET") 'org-export-stack-view)
5968 (define-key km "d" 'org-export-stack-remove)
5970 "Keymap for Org Export Stack.")
5972 (define-derived-mode org-export-stack-mode special-mode "Org-Stack"
5973 "Mode for displaying asynchronous export stack.
5975 Type \\[org-export-stack] to visualize the asynchronous export
5976 stack.
5978 In an Org Export Stack buffer, use \\<org-export-stack-mode-map>\\[org-export-stack-view] to view export output
5979 on current line, \\[org-export-stack-remove] to remove it from the stack and \\[org-export-stack-clear] to clear
5980 stack completely.
5982 Removing entries in an Org Export Stack buffer doesn't affect
5983 files or buffers, only the display.
5985 \\{org-export-stack-mode-map}"
5986 (abbrev-mode 0)
5987 (auto-fill-mode 0)
5988 (setq buffer-read-only t
5989 buffer-undo-list t
5990 truncate-lines t
5991 header-line-format
5992 '(:eval
5993 (format " %-12s | %6s | %s" "Back-End" "Age" "Source")))
5994 (org-add-hook 'post-command-hook 'org-export-stack-refresh nil t)
5995 (set (make-local-variable 'revert-buffer-function)
5996 'org-export-stack-refresh))
6000 ;;; The Dispatcher
6002 ;; `org-export-dispatch' is the standard interactive way to start an
6003 ;; export process. It uses `org-export--dispatch-ui' as a subroutine
6004 ;; for its interface, which, in turn, delegates response to key
6005 ;; pressed to `org-export--dispatch-action'.
6007 ;;;###autoload
6008 (defun org-export-dispatch (&optional arg)
6009 "Export dispatcher for Org mode.
6011 It provides an access to common export related tasks in a buffer.
6012 Its interface comes in two flavors: standard and expert.
6014 While both share the same set of bindings, only the former
6015 displays the valid keys associations in a dedicated buffer.
6016 Scrolling (resp. line-wise motion) in this buffer is done with
6017 SPC and DEL (resp. C-n and C-p) keys.
6019 Set variable `org-export-dispatch-use-expert-ui' to switch to one
6020 flavor or the other.
6022 When ARG is \\[universal-argument], repeat the last export action, with the same set
6023 of options used back then, on the current buffer.
6025 When ARG is \\[universal-argument] \\[universal-argument], display the asynchronous export stack."
6026 (interactive "P")
6027 (let* ((input
6028 (cond ((equal arg '(16)) '(stack))
6029 ((and arg org-export-dispatch-last-action))
6030 (t (save-window-excursion
6031 (unwind-protect
6032 (progn
6033 ;; Remember where we are
6034 (move-marker org-export-dispatch-last-position
6035 (point)
6036 (org-base-buffer (current-buffer)))
6037 ;; Get and store an export command
6038 (setq org-export-dispatch-last-action
6039 (org-export--dispatch-ui
6040 (list org-export-initial-scope
6041 (and org-export-in-background 'async))
6043 org-export-dispatch-use-expert-ui)))
6044 (and (get-buffer "*Org Export Dispatcher*")
6045 (kill-buffer "*Org Export Dispatcher*")))))))
6046 (action (car input))
6047 (optns (cdr input)))
6048 (unless (memq 'subtree optns)
6049 (move-marker org-export-dispatch-last-position nil))
6050 (case action
6051 ;; First handle special hard-coded actions.
6052 (template (org-export-insert-default-template nil optns))
6053 (stack (org-export-stack))
6054 (publish-current-file
6055 (org-publish-current-file (memq 'force optns) (memq 'async optns)))
6056 (publish-current-project
6057 (org-publish-current-project (memq 'force optns) (memq 'async optns)))
6058 (publish-choose-project
6059 (org-publish (assoc (org-icompleting-read
6060 "Publish project: "
6061 org-publish-project-alist nil t)
6062 org-publish-project-alist)
6063 (memq 'force optns)
6064 (memq 'async optns)))
6065 (publish-all (org-publish-all (memq 'force optns) (memq 'async optns)))
6066 (otherwise
6067 (save-excursion
6068 (when arg
6069 ;; Repeating command, maybe move cursor to restore subtree
6070 ;; context.
6071 (if (eq (marker-buffer org-export-dispatch-last-position)
6072 (org-base-buffer (current-buffer)))
6073 (goto-char org-export-dispatch-last-position)
6074 ;; We are in a different buffer, forget position.
6075 (move-marker org-export-dispatch-last-position nil)))
6076 (funcall action
6077 ;; Return a symbol instead of a list to ease
6078 ;; asynchronous export macro use.
6079 (and (memq 'async optns) t)
6080 (and (memq 'subtree optns) t)
6081 (and (memq 'visible optns) t)
6082 (and (memq 'body optns) t)))))))
6084 (defun org-export--dispatch-ui (options first-key expertp)
6085 "Handle interface for `org-export-dispatch'.
6087 OPTIONS is a list containing current interactive options set for
6088 export. It can contain any of the following symbols:
6089 `body' toggles a body-only export
6090 `subtree' restricts export to current subtree
6091 `visible' restricts export to visible part of buffer.
6092 `force' force publishing files.
6093 `async' use asynchronous export process
6095 FIRST-KEY is the key pressed to select the first level menu. It
6096 is nil when this menu hasn't been selected yet.
6098 EXPERTP, when non-nil, triggers expert UI. In that case, no help
6099 buffer is provided, but indications about currently active
6100 options are given in the prompt. Moreover, \[?] allows to switch
6101 back to standard interface."
6102 (let* ((fontify-key
6103 (lambda (key &optional access-key)
6104 ;; Fontify KEY string. Optional argument ACCESS-KEY, when
6105 ;; non-nil is the required first-level key to activate
6106 ;; KEY. When its value is t, activate KEY independently
6107 ;; on the first key, if any. A nil value means KEY will
6108 ;; only be activated at first level.
6109 (if (or (eq access-key t) (eq access-key first-key))
6110 (org-propertize key 'face 'org-warning)
6111 key)))
6112 (fontify-value
6113 (lambda (value)
6114 ;; Fontify VALUE string.
6115 (org-propertize value 'face 'font-lock-variable-name-face)))
6116 ;; Prepare menu entries by extracting them from registered
6117 ;; back-ends and sorting them by access key and by ordinal,
6118 ;; if any.
6119 (entries
6120 (sort (sort (delq nil
6121 (mapcar 'org-export-backend-menu
6122 org-export--registered-backends))
6123 (lambda (a b)
6124 (let ((key-a (nth 1 a))
6125 (key-b (nth 1 b)))
6126 (cond ((and (numberp key-a) (numberp key-b))
6127 (< key-a key-b))
6128 ((numberp key-b) t)))))
6129 'car-less-than-car))
6130 ;; Compute a list of allowed keys based on the first key
6131 ;; pressed, if any. Some keys
6132 ;; (?^B, ?^V, ?^S, ?^F, ?^A, ?&, ?# and ?q) are always
6133 ;; available.
6134 (allowed-keys
6135 (nconc (list 2 22 19 6 1)
6136 (if (not first-key) (org-uniquify (mapcar 'car entries))
6137 (let (sub-menu)
6138 (dolist (entry entries (sort (mapcar 'car sub-menu) '<))
6139 (when (eq (car entry) first-key)
6140 (setq sub-menu (append (nth 2 entry) sub-menu))))))
6141 (cond ((eq first-key ?P) (list ?f ?p ?x ?a))
6142 ((not first-key) (list ?P)))
6143 (list ?& ?#)
6144 (when expertp (list ??))
6145 (list ?q)))
6146 ;; Build the help menu for standard UI.
6147 (help
6148 (unless expertp
6149 (concat
6150 ;; Options are hard-coded.
6151 (format "[%s] Body only: %s [%s] Visible only: %s
6152 \[%s] Export scope: %s [%s] Force publishing: %s
6153 \[%s] Async export: %s\n\n"
6154 (funcall fontify-key "C-b" t)
6155 (funcall fontify-value
6156 (if (memq 'body options) "On " "Off"))
6157 (funcall fontify-key "C-v" t)
6158 (funcall fontify-value
6159 (if (memq 'visible options) "On " "Off"))
6160 (funcall fontify-key "C-s" t)
6161 (funcall fontify-value
6162 (if (memq 'subtree options) "Subtree" "Buffer "))
6163 (funcall fontify-key "C-f" t)
6164 (funcall fontify-value
6165 (if (memq 'force options) "On " "Off"))
6166 (funcall fontify-key "C-a" t)
6167 (funcall fontify-value
6168 (if (memq 'async options) "On " "Off")))
6169 ;; Display registered back-end entries. When a key
6170 ;; appears for the second time, do not create another
6171 ;; entry, but append its sub-menu to existing menu.
6172 (let (last-key)
6173 (mapconcat
6174 (lambda (entry)
6175 (let ((top-key (car entry)))
6176 (concat
6177 (unless (eq top-key last-key)
6178 (setq last-key top-key)
6179 (format "\n[%s] %s\n"
6180 (funcall fontify-key (char-to-string top-key))
6181 (nth 1 entry)))
6182 (let ((sub-menu (nth 2 entry)))
6183 (unless (functionp sub-menu)
6184 ;; Split sub-menu into two columns.
6185 (let ((index -1))
6186 (concat
6187 (mapconcat
6188 (lambda (sub-entry)
6189 (incf index)
6190 (format
6191 (if (zerop (mod index 2)) " [%s] %-26s"
6192 "[%s] %s\n")
6193 (funcall fontify-key
6194 (char-to-string (car sub-entry))
6195 top-key)
6196 (nth 1 sub-entry)))
6197 sub-menu "")
6198 (when (zerop (mod index 2)) "\n"))))))))
6199 entries ""))
6200 ;; Publishing menu is hard-coded.
6201 (format "\n[%s] Publish
6202 [%s] Current file [%s] Current project
6203 [%s] Choose project [%s] All projects\n\n\n"
6204 (funcall fontify-key "P")
6205 (funcall fontify-key "f" ?P)
6206 (funcall fontify-key "p" ?P)
6207 (funcall fontify-key "x" ?P)
6208 (funcall fontify-key "a" ?P))
6209 (format "[%s] Export stack [%s] Insert template\n"
6210 (funcall fontify-key "&" t)
6211 (funcall fontify-key "#" t))
6212 (format "[%s] %s"
6213 (funcall fontify-key "q" t)
6214 (if first-key "Main menu" "Exit")))))
6215 ;; Build prompts for both standard and expert UI.
6216 (standard-prompt (unless expertp "Export command: "))
6217 (expert-prompt
6218 (when expertp
6219 (format
6220 "Export command (C-%s%s%s%s%s) [%s]: "
6221 (if (memq 'body options) (funcall fontify-key "b" t) "b")
6222 (if (memq 'visible options) (funcall fontify-key "v" t) "v")
6223 (if (memq 'subtree options) (funcall fontify-key "s" t) "s")
6224 (if (memq 'force options) (funcall fontify-key "f" t) "f")
6225 (if (memq 'async options) (funcall fontify-key "a" t) "a")
6226 (mapconcat (lambda (k)
6227 ;; Strip control characters.
6228 (unless (< k 27) (char-to-string k)))
6229 allowed-keys "")))))
6230 ;; With expert UI, just read key with a fancy prompt. In standard
6231 ;; UI, display an intrusive help buffer.
6232 (if expertp
6233 (org-export--dispatch-action
6234 expert-prompt allowed-keys entries options first-key expertp)
6235 ;; At first call, create frame layout in order to display menu.
6236 (unless (get-buffer "*Org Export Dispatcher*")
6237 (delete-other-windows)
6238 (org-switch-to-buffer-other-window
6239 (get-buffer-create "*Org Export Dispatcher*"))
6240 (setq cursor-type nil
6241 header-line-format "Use SPC, DEL, C-n or C-p to navigate.")
6242 ;; Make sure that invisible cursor will not highlight square
6243 ;; brackets.
6244 (set-syntax-table (copy-syntax-table))
6245 (modify-syntax-entry ?\[ "w"))
6246 ;; At this point, the buffer containing the menu exists and is
6247 ;; visible in the current window. So, refresh it.
6248 (with-current-buffer "*Org Export Dispatcher*"
6249 ;; Refresh help. Maintain display continuity by re-visiting
6250 ;; previous window position.
6251 (let ((pos (window-start)))
6252 (erase-buffer)
6253 (insert help)
6254 (set-window-start nil pos)))
6255 (org-fit-window-to-buffer)
6256 (org-export--dispatch-action
6257 standard-prompt allowed-keys entries options first-key expertp))))
6259 (defun org-export--dispatch-action
6260 (prompt allowed-keys entries options first-key expertp)
6261 "Read a character from command input and act accordingly.
6263 PROMPT is the displayed prompt, as a string. ALLOWED-KEYS is
6264 a list of characters available at a given step in the process.
6265 ENTRIES is a list of menu entries. OPTIONS, FIRST-KEY and
6266 EXPERTP are the same as defined in `org-export--dispatch-ui',
6267 which see.
6269 Toggle export options when required. Otherwise, return value is
6270 a list with action as CAR and a list of interactive export
6271 options as CDR."
6272 (let (key)
6273 ;; Scrolling: when in non-expert mode, act on motion keys (C-n,
6274 ;; C-p, SPC, DEL).
6275 (while (and (setq key (read-char-exclusive prompt))
6276 (not expertp)
6277 (memq key '(14 16 ?\s ?\d)))
6278 (case key
6279 (14 (if (not (pos-visible-in-window-p (point-max)))
6280 (ignore-errors (scroll-up 1))
6281 (message "End of buffer")
6282 (sit-for 1)))
6283 (16 (if (not (pos-visible-in-window-p (point-min)))
6284 (ignore-errors (scroll-down 1))
6285 (message "Beginning of buffer")
6286 (sit-for 1)))
6287 (?\s (if (not (pos-visible-in-window-p (point-max)))
6288 (scroll-up nil)
6289 (message "End of buffer")
6290 (sit-for 1)))
6291 (?\d (if (not (pos-visible-in-window-p (point-min)))
6292 (scroll-down nil)
6293 (message "Beginning of buffer")
6294 (sit-for 1)))))
6295 (cond
6296 ;; Ignore undefined associations.
6297 ((not (memq key allowed-keys))
6298 (ding)
6299 (unless expertp (message "Invalid key") (sit-for 1))
6300 (org-export--dispatch-ui options first-key expertp))
6301 ;; q key at first level aborts export. At second level, cancel
6302 ;; first key instead.
6303 ((eq key ?q) (if (not first-key) (error "Export aborted")
6304 (org-export--dispatch-ui options nil expertp)))
6305 ;; Help key: Switch back to standard interface if expert UI was
6306 ;; active.
6307 ((eq key ??) (org-export--dispatch-ui options first-key nil))
6308 ;; Send request for template insertion along with export scope.
6309 ((eq key ?#) (cons 'template (memq 'subtree options)))
6310 ;; Switch to asynchronous export stack.
6311 ((eq key ?&) '(stack))
6312 ;; Toggle options: C-b (2) C-v (22) C-s (19) C-f (6) C-a (1).
6313 ((memq key '(2 22 19 6 1))
6314 (org-export--dispatch-ui
6315 (let ((option (case key (2 'body) (22 'visible) (19 'subtree)
6316 (6 'force) (1 'async))))
6317 (if (memq option options) (remq option options)
6318 (cons option options)))
6319 first-key expertp))
6320 ;; Action selected: Send key and options back to
6321 ;; `org-export-dispatch'.
6322 ((or first-key (functionp (nth 2 (assq key entries))))
6323 (cons (cond
6324 ((not first-key) (nth 2 (assq key entries)))
6325 ;; Publishing actions are hard-coded. Send a special
6326 ;; signal to `org-export-dispatch'.
6327 ((eq first-key ?P)
6328 (case key
6329 (?f 'publish-current-file)
6330 (?p 'publish-current-project)
6331 (?x 'publish-choose-project)
6332 (?a 'publish-all)))
6333 ;; Return first action associated to FIRST-KEY + KEY
6334 ;; path. Indeed, derived backends can share the same
6335 ;; FIRST-KEY.
6336 (t (catch 'found
6337 (mapc (lambda (entry)
6338 (let ((match (assq key (nth 2 entry))))
6339 (when match (throw 'found (nth 2 match)))))
6340 (member (assq first-key entries) entries)))))
6341 options))
6342 ;; Otherwise, enter sub-menu.
6343 (t (org-export--dispatch-ui options key expertp)))))
6347 (provide 'ox)
6349 ;; Local variables:
6350 ;; generated-autoload-file: "org-loaddefs.el"
6351 ;; End:
6353 ;;; ox.el ends here