Radio targets cannot beging or end with whitespace
[org-mode.git] / lisp / ox.el
blobfc0e987390ee727321cd1179855f80074173df63
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 in 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. The exhaustive list
35 ;; of properties is given in "The Communication Channel" section of
36 ;; this file.
38 ;; - The transcoder walks the parse tree, ignores or treat as plain
39 ;; text elements and objects according to export options, and
40 ;; eventually calls back-end specific functions to do the real
41 ;; transcoding, concatenating their return value along the way.
43 ;; - The filter system is activated at the very beginning and the very
44 ;; end of the export process, and each time an element or an object
45 ;; has been converted. It is the entry point to fine-tune standard
46 ;; output from back-end transcoders. See "The Filter System"
47 ;; section for more information.
49 ;; The core function is `org-export-as'. It returns the transcoded
50 ;; buffer as a string.
52 ;; An export back-end is defined with `org-export-define-backend'.
53 ;; This function can also support specific buffer keywords, OPTION
54 ;; keyword's items and filters. Refer to function's documentation for
55 ;; more information.
57 ;; If the new back-end shares most properties with another one,
58 ;; `org-export-define-derived-backend' can be used to simplify the
59 ;; process.
61 ;; Any back-end can define its own variables. Among them, those
62 ;; customizable should belong to the `org-export-BACKEND' group.
64 ;; Tools for common tasks across back-ends are implemented in the
65 ;; following part of the file.
67 ;; Then, a wrapper macro for asynchronous export,
68 ;; `org-export-async-start', along with tools to display results. are
69 ;; given in the penultimate part.
71 ;; Eventually, a dispatcher (`org-export-dispatch') for standard
72 ;; back-ends is provided in the last one.
74 ;;; Code:
76 (eval-when-compile (require 'cl))
77 (require 'org-element)
78 (require 'org-macro)
79 (require 'ob-exp)
81 (declare-function org-publish "ox-publish" (project &optional force async))
82 (declare-function org-publish-all "ox-publish" (&optional force async))
83 (declare-function
84 org-publish-current-file "ox-publish" (&optional force async))
85 (declare-function org-publish-current-project "ox-publish"
86 (&optional force async))
88 (defvar org-publish-project-alist)
89 (defvar org-table-number-fraction)
90 (defvar org-table-number-regexp)
93 (defsubst org-export-get-parent (blob)
94 "Return BLOB parent or nil.
95 BLOB is the element or object considered."
96 (org-element-property :parent blob))
99 ;;; Internal Variables
101 ;; Among internal variables, the most important is
102 ;; `org-export-options-alist'. This variable define the global export
103 ;; options, shared between every exporter, and how they are acquired.
105 (defconst org-export-max-depth 19
106 "Maximum nesting depth for headlines, counting from 0.")
108 (defconst org-export-options-alist
109 '((:title "TITLE" nil nil space)
110 (:date "DATE" nil nil t)
111 (:author "AUTHOR" nil user-full-name t)
112 (:email "EMAIL" nil user-mail-address t)
113 (:description "DESCRIPTION" nil nil newline)
114 (:keywords "KEYWORDS" nil nil space)
115 (:language "LANGUAGE" nil org-export-default-language t)
116 (:select-tags "SELECT_TAGS" nil org-export-select-tags split)
117 (:exclude-tags "EXCLUDE_TAGS" nil org-export-exclude-tags split)
118 (:creator "CREATOR" nil org-export-creator-string)
119 (:headline-levels nil "H" org-export-headline-levels)
120 (:preserve-breaks nil "\\n" org-export-preserve-breaks)
121 (:section-numbers nil "num" org-export-with-section-numbers)
122 (:time-stamp-file nil "timestamp" org-export-time-stamp-file)
123 (:with-archived-trees nil "arch" org-export-with-archived-trees)
124 (:with-author nil "author" org-export-with-author)
125 (:with-clocks nil "c" org-export-with-clocks)
126 (:with-creator nil "creator" org-export-with-creator)
127 (:with-date nil "date" org-export-with-date)
128 (:with-drawers nil "d" org-export-with-drawers)
129 (:with-email nil "email" org-export-with-email)
130 (:with-emphasize nil "*" org-export-with-emphasize)
131 (:with-entities nil "e" org-export-with-entities)
132 (:with-fixed-width nil ":" org-export-with-fixed-width)
133 (:with-footnotes nil "f" org-export-with-footnotes)
134 (:with-inlinetasks nil "inline" org-export-with-inlinetasks)
135 (:with-latex nil "tex" org-export-with-latex)
136 (:with-planning nil "p" org-export-with-planning)
137 (:with-priority nil "pri" org-export-with-priority)
138 (:with-properties nil "prop" org-export-with-properties)
139 (:with-smart-quotes nil "'" org-export-with-smart-quotes)
140 (:with-special-strings nil "-" org-export-with-special-strings)
141 (:with-statistics-cookies nil "stat" org-export-with-statistics-cookies)
142 (:with-sub-superscript nil "^" org-export-with-sub-superscripts)
143 (:with-toc nil "toc" org-export-with-toc)
144 (:with-tables nil "|" org-export-with-tables)
145 (:with-tags nil "tags" org-export-with-tags)
146 (:with-tasks nil "tasks" org-export-with-tasks)
147 (:with-timestamps nil "<" org-export-with-timestamps)
148 (:with-todo-keywords nil "todo" org-export-with-todo-keywords))
149 "Alist between export properties and ways to set them.
151 The CAR of the alist is the property name, and the CDR is a list
152 like (KEYWORD OPTION DEFAULT BEHAVIOR) where:
154 KEYWORD is a string representing a buffer keyword, or nil. Each
155 property defined this way can also be set, during subtree
156 export, through a headline property named after the keyword
157 with the \"EXPORT_\" prefix (i.e. DATE keyword and EXPORT_DATE
158 property).
159 OPTION is a string that could be found in an #+OPTIONS: line.
160 DEFAULT is the default value for the property.
161 BEHAVIOR determines how Org should handle multiple keywords for
162 the same property. It is a symbol among:
163 nil Keep old value and discard the new one.
164 t Replace old value with the new one.
165 `space' Concatenate the values, separating them with a space.
166 `newline' Concatenate the values, separating them with
167 a newline.
168 `split' Split values at white spaces, and cons them to the
169 previous list.
171 Values set through KEYWORD and OPTION have precedence over
172 DEFAULT.
174 All these properties should be back-end agnostic. Back-end
175 specific properties are set through `org-export-define-backend'.
176 Properties redefined there have precedence over these.")
178 (defconst org-export-special-keywords '("FILETAGS" "SETUPFILE" "OPTIONS")
179 "List of in-buffer keywords that require special treatment.
180 These keywords are not directly associated to a property. The
181 way they are handled must be hard-coded into
182 `org-export--get-inbuffer-options' function.")
184 (defconst org-export-filters-alist
185 '((:filter-bold . org-export-filter-bold-functions)
186 (:filter-babel-call . org-export-filter-babel-call-functions)
187 (:filter-center-block . org-export-filter-center-block-functions)
188 (:filter-clock . org-export-filter-clock-functions)
189 (:filter-code . org-export-filter-code-functions)
190 (:filter-comment . org-export-filter-comment-functions)
191 (:filter-comment-block . org-export-filter-comment-block-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 'comment
372 "Non-nil means the postamble should contain a creator sentence.
374 The sentence can be set in `org-export-creator-string' and
375 defaults to \"Generated by Org mode XX in Emacs XXX.\".
377 If the value is `comment' insert it as a comment."
378 :group 'org-export-general
379 :type '(choice
380 (const :tag "No creator sentence" nil)
381 (const :tag "Sentence as a comment" comment)
382 (const :tag "Insert the sentence" t)))
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-time-stamp-file t
754 "Non-nil means insert a time stamp into the exported file.
755 The time stamp shows when the file was created. This option can
756 also be set with the OPTIONS keyword, e.g. \"timestamp:nil\"."
757 :group 'org-export-general
758 :type 'boolean)
760 (defcustom org-export-with-timestamps t
761 "Non nil means allow timestamps in export.
763 It can be set to any of the following values:
764 t export all timestamps.
765 `active' export active timestamps only.
766 `inactive' export inactive timestamps only.
767 nil do not export timestamps
769 This only applies to timestamps isolated in a paragraph
770 containing only timestamps. Other timestamps are always
771 exported.
773 This option can also be set with the OPTIONS keyword, e.g.
774 \"<:nil\"."
775 :group 'org-export-general
776 :type '(choice
777 (const :tag "All timestamps" t)
778 (const :tag "Only active timestamps" active)
779 (const :tag "Only inactive timestamps" inactive)
780 (const :tag "No timestamp" nil)))
782 (defcustom org-export-with-todo-keywords t
783 "Non-nil means include TODO keywords in export.
784 When nil, remove all these keywords from the export. This option
785 can also be set with the OPTIONS keyword, e.g. \"todo:nil\"."
786 :group 'org-export-general
787 :type 'boolean)
789 (defcustom org-export-allow-bind-keywords nil
790 "Non-nil means BIND keywords can define local variable values.
791 This is a potential security risk, which is why the default value
792 is nil. You can also allow them through local buffer variables."
793 :group 'org-export-general
794 :version "24.4"
795 :package-version '(Org . "8.0")
796 :type 'boolean)
798 (defcustom org-export-snippet-translation-alist nil
799 "Alist between export snippets back-ends and exporter back-ends.
801 This variable allows to provide shortcuts for export snippets.
803 For example, with a value of '\(\(\"h\" . \"html\"\)\), the
804 HTML back-end will recognize the contents of \"@@h:<b>@@\" as
805 HTML code while every other back-end will ignore it."
806 :group 'org-export-general
807 :version "24.4"
808 :package-version '(Org . "8.0")
809 :type '(repeat
810 (cons (string :tag "Shortcut")
811 (string :tag "Back-end"))))
813 (defcustom org-export-coding-system nil
814 "Coding system for the exported file."
815 :group 'org-export-general
816 :version "24.4"
817 :package-version '(Org . "8.0")
818 :type 'coding-system)
820 (defcustom org-export-copy-to-kill-ring 'if-interactive
821 "Should we push exported content to the kill ring?"
822 :group 'org-export-general
823 :version "24.3"
824 :type '(choice
825 (const :tag "Always" t)
826 (const :tag "When export is done interactively" if-interactive)
827 (const :tag "Never" nil)))
829 (defcustom org-export-initial-scope 'buffer
830 "The initial scope when exporting with `org-export-dispatch'.
831 This variable can be either set to `buffer' or `subtree'."
832 :group 'org-export-general
833 :type '(choice
834 (const :tag "Export current buffer" buffer)
835 (const :tag "Export current subtree" subtree)))
837 (defcustom org-export-show-temporary-export-buffer t
838 "Non-nil means show buffer after exporting to temp buffer.
839 When Org exports to a file, the buffer visiting that file is ever
840 shown, but remains buried. However, when exporting to
841 a temporary buffer, that buffer is popped up in a second window.
842 When this variable is nil, the buffer remains buried also in
843 these cases."
844 :group 'org-export-general
845 :type 'boolean)
847 (defcustom org-export-in-background nil
848 "Non-nil means export and publishing commands will run in background.
849 Results from an asynchronous export are never displayed
850 automatically. But you can retrieve them with \\[org-export-stack]."
851 :group 'org-export-general
852 :version "24.4"
853 :package-version '(Org . "8.0")
854 :type 'boolean)
856 (defcustom org-export-async-init-file nil
857 "File used to initialize external export process.
859 Value must be either nil or an absolute file name. When nil, the
860 external process is launched like a regular Emacs session,
861 loading user's initialization file and any site specific
862 configuration. If a file is provided, it, and only it, is loaded
863 at start-up.
865 Therefore, using a specific configuration makes the process to
866 load faster and the export more portable."
867 :group 'org-export-general
868 :version "24.4"
869 :package-version '(Org . "8.0")
870 :type '(choice
871 (const :tag "Regular startup" nil)
872 (file :tag "Specific start-up file" :must-match t)))
874 (defcustom org-export-dispatch-use-expert-ui nil
875 "Non-nil means using a non-intrusive `org-export-dispatch'.
876 In that case, no help buffer is displayed. Though, an indicator
877 for current export scope is added to the prompt (\"b\" when
878 output is restricted to body only, \"s\" when it is restricted to
879 the current subtree, \"v\" when only visible elements are
880 considered for export, \"f\" when publishing functions should be
881 passed the FORCE argument and \"a\" when the export should be
882 asynchronous). Also, \[?] allows to switch back to standard
883 mode."
884 :group 'org-export-general
885 :version "24.4"
886 :package-version '(Org . "8.0")
887 :type 'boolean)
891 ;;; Defining Back-ends
893 ;; An export back-end is a structure with `org-export-backend' type
894 ;; and `name', `parent', `transcoders', `options', `filters', `blocks'
895 ;; and `menu' slots.
897 ;; At the lowest level, a back-end is created with
898 ;; `org-export-create-backend' function.
900 ;; A named back-end can be registered with
901 ;; `org-export-register-backend' function. A registered back-end can
902 ;; later be referred to by its name, with `org-export-get-backend'
903 ;; function. Also, such a back-end can become the parent of a derived
904 ;; back-end from which slot values will be inherited by default.
905 ;; `org-export-derived-backend-p' can check if a given back-end is
906 ;; derived from a list of back-end names.
908 ;; `org-export-get-all-transcoders', `org-export-get-all-options' and
909 ;; `org-export-get-all-filters' return the full alist of transcoders,
910 ;; options and filters, including those inherited from ancestors.
912 ;; At a higher level, `org-export-define-backend' is the standard way
913 ;; to define an export back-end. If the new back-end is similar to
914 ;; a registered back-end, `org-export-define-derived-backend' may be
915 ;; used instead.
917 ;; Eventually `org-export-barf-if-invalid-backend' returns an error
918 ;; when a given back-end hasn't been registered yet.
920 (defstruct (org-export-backend (:constructor org-export-create-backend)
921 (:copier nil))
922 name parent transcoders options filters blocks menu)
924 (defun org-export-get-backend (name)
925 "Return export back-end named after NAME.
926 NAME is a symbol. Return nil if no such back-end is found."
927 (catch 'found
928 (dolist (b org-export--registered-backends)
929 (when (eq (org-export-backend-name b) name)
930 (throw 'found b)))))
932 (defun org-export-register-backend (backend)
933 "Register BACKEND as a known export back-end.
934 BACKEND is a structure with `org-export-backend' type."
935 ;; Refuse to register an unnamed back-end.
936 (unless (org-export-backend-name backend)
937 (error "Cannot register a unnamed export back-end"))
938 ;; Refuse to register a back-end with an unknown parent.
939 (let ((parent (org-export-backend-parent backend)))
940 (when (and parent (not (org-export-get-backend parent)))
941 (error "Cannot use unknown \"%s\" back-end as a parent" parent)))
942 ;; Register dedicated export blocks in the parser.
943 (dolist (name (org-export-backend-blocks backend))
944 (add-to-list 'org-element-block-name-alist
945 (cons name 'org-element-export-block-parser)))
946 ;; If a back-end with the same name as BACKEND is already
947 ;; registered, replace it with BACKEND. Otherwise, simply add
948 ;; BACKEND to the list of registered back-ends.
949 (let ((old (org-export-get-backend (org-export-backend-name backend))))
950 (if old (setcar (memq old org-export--registered-backends) backend)
951 (push backend org-export--registered-backends))))
953 (defun org-export-barf-if-invalid-backend (backend)
954 "Signal an error if BACKEND isn't defined."
955 (unless (org-export-backend-p backend)
956 (error "Unknown \"%s\" back-end: Aborting export" backend)))
958 (defun org-export-derived-backend-p (backend &rest backends)
959 "Non-nil if BACKEND is derived from one of BACKENDS.
960 BACKEND is an export back-end, as returned by, e.g.,
961 `org-export-create-backend', or a symbol referring to
962 a registered back-end. BACKENDS is constituted of symbols."
963 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
964 (when backend
965 (catch 'exit
966 (while (org-export-backend-parent backend)
967 (when (memq (org-export-backend-name backend) backends)
968 (throw 'exit t))
969 (setq backend
970 (org-export-get-backend (org-export-backend-parent backend))))
971 (memq (org-export-backend-name backend) backends))))
973 (defun org-export-get-all-transcoders (backend)
974 "Return full translation table for BACKEND.
976 BACKEND is an export back-end, as return by, e.g,,
977 `org-export-create-backend'. Return value is an alist where
978 keys are element or object types, as symbols, and values are
979 transcoders.
981 Unlike to `org-export-backend-transcoders', this function
982 also returns transcoders inherited from parent back-ends,
983 if any."
984 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
985 (when backend
986 (let ((transcoders (org-export-backend-transcoders backend))
987 parent)
988 (while (setq parent (org-export-backend-parent backend))
989 (setq backend (org-export-get-backend parent))
990 (setq transcoders
991 (append transcoders (org-export-backend-transcoders backend))))
992 transcoders)))
994 (defun org-export-get-all-options (backend)
995 "Return export options for BACKEND.
997 BACKEND is an export back-end, as return by, e.g,,
998 `org-export-create-backend'. See `org-export-options-alist'
999 for the shape of the return value.
1001 Unlike to `org-export-backend-options', this function also
1002 returns options inherited from parent back-ends, if any."
1003 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
1004 (when backend
1005 (let ((options (org-export-backend-options backend))
1006 parent)
1007 (while (setq parent (org-export-backend-parent backend))
1008 (setq backend (org-export-get-backend parent))
1009 (setq options (append options (org-export-backend-options backend))))
1010 options)))
1012 (defun org-export-get-all-filters (backend)
1013 "Return complete list of filters for BACKEND.
1015 BACKEND is an export back-end, as return by, e.g,,
1016 `org-export-create-backend'. Return value is an alist where
1017 keys are symbols and values lists of functions.
1019 Unlike to `org-export-backend-filters', this function also
1020 returns filters inherited from parent back-ends, if any."
1021 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
1022 (when backend
1023 (let ((filters (org-export-backend-filters backend))
1024 parent)
1025 (while (setq parent (org-export-backend-parent backend))
1026 (setq backend (org-export-get-backend parent))
1027 (setq filters (append filters (org-export-backend-filters backend))))
1028 filters)))
1030 (defun org-export-define-backend (backend transcoders &rest body)
1031 "Define a new back-end BACKEND.
1033 TRANSCODERS is an alist between object or element types and
1034 functions handling them.
1036 These functions should return a string without any trailing
1037 space, or nil. They must accept three arguments: the object or
1038 element itself, its contents or nil when it isn't recursive and
1039 the property list used as a communication channel.
1041 Contents, when not nil, are stripped from any global indentation
1042 \(although the relative one is preserved). They also always end
1043 with a single newline character.
1045 If, for a given type, no function is found, that element or
1046 object type will simply be ignored, along with any blank line or
1047 white space at its end. The same will happen if the function
1048 returns the nil value. If that function returns the empty
1049 string, the type will be ignored, but the blank lines or white
1050 spaces will be kept.
1052 In addition to element and object types, one function can be
1053 associated to the `template' (or `inner-template') symbol and
1054 another one to the `plain-text' symbol.
1056 The former returns the final transcoded string, and can be used
1057 to add a preamble and a postamble to document's body. It must
1058 accept two arguments: the transcoded string and the property list
1059 containing export options. A function associated to `template'
1060 will not be applied if export has option \"body-only\".
1061 A function associated to `inner-template' is always applied.
1063 The latter, when defined, is to be called on every text not
1064 recognized as an element or an object. It must accept two
1065 arguments: the text string and the information channel. It is an
1066 appropriate place to protect special chars relative to the
1067 back-end.
1069 BODY can start with pre-defined keyword arguments. The following
1070 keywords are understood:
1072 :export-block
1074 String, or list of strings, representing block names that
1075 will not be parsed. This is used to specify blocks that will
1076 contain raw code specific to the back-end. These blocks
1077 still have to be handled by the relative `export-block' type
1078 translator.
1080 :filters-alist
1082 Alist between filters and function, or list of functions,
1083 specific to the back-end. See `org-export-filters-alist' for
1084 a list of all allowed filters. Filters defined here
1085 shouldn't make a back-end test, as it may prevent back-ends
1086 derived from this one to behave properly.
1088 :menu-entry
1090 Menu entry for the export dispatcher. It should be a list
1091 like:
1093 '(KEY DESCRIPTION-OR-ORDINAL ACTION-OR-MENU)
1095 where :
1097 KEY is a free character selecting the back-end.
1099 DESCRIPTION-OR-ORDINAL is either a string or a number.
1101 If it is a string, is will be used to name the back-end in
1102 its menu entry. If it is a number, the following menu will
1103 be displayed as a sub-menu of the back-end with the same
1104 KEY. Also, the number will be used to determine in which
1105 order such sub-menus will appear (lowest first).
1107 ACTION-OR-MENU is either a function or an alist.
1109 If it is an action, it will be called with four
1110 arguments (booleans): ASYNC, SUBTREEP, VISIBLE-ONLY and
1111 BODY-ONLY. See `org-export-as' for further explanations on
1112 some of them.
1114 If it is an alist, associations should follow the
1115 pattern:
1117 '(KEY DESCRIPTION ACTION)
1119 where KEY, DESCRIPTION and ACTION are described above.
1121 Valid values include:
1123 '(?m \"My Special Back-end\" my-special-export-function)
1127 '(?l \"Export to LaTeX\"
1128 \(?p \"As PDF file\" org-latex-export-to-pdf)
1129 \(?o \"As PDF file and open\"
1130 \(lambda (a s v b)
1131 \(if a (org-latex-export-to-pdf t s v b)
1132 \(org-open-file
1133 \(org-latex-export-to-pdf nil s v b)))))))
1135 or the following, which will be added to the previous
1136 sub-menu,
1138 '(?l 1
1139 \((?B \"As TEX buffer (Beamer)\" org-beamer-export-as-latex)
1140 \(?P \"As PDF file (Beamer)\" org-beamer-export-to-pdf)))
1142 :options-alist
1144 Alist between back-end specific properties introduced in
1145 communication channel and how their value are acquired. See
1146 `org-export-options-alist' for more information about
1147 structure of the values."
1148 (declare (indent 1))
1149 (let (blocks filters menu-entry options contents)
1150 (while (keywordp (car body))
1151 (case (pop body)
1152 (:export-block (let ((names (pop body)))
1153 (setq blocks (if (consp names) (mapcar 'upcase names)
1154 (list (upcase names))))))
1155 (:filters-alist (setq filters (pop body)))
1156 (:menu-entry (setq menu-entry (pop body)))
1157 (:options-alist (setq options (pop body)))
1158 (t (pop body))))
1159 (org-export-register-backend
1160 (org-export-create-backend :name backend
1161 :transcoders transcoders
1162 :options options
1163 :filters filters
1164 :blocks blocks
1165 :menu menu-entry))))
1167 (defun org-export-define-derived-backend (child parent &rest body)
1168 "Create a new back-end as a variant of an existing one.
1170 CHILD is the name of the derived back-end. PARENT is the name of
1171 the parent back-end.
1173 BODY can start with pre-defined keyword arguments. The following
1174 keywords are understood:
1176 :export-block
1178 String, or list of strings, representing block names that
1179 will not be parsed. This is used to specify blocks that will
1180 contain raw code specific to the back-end. These blocks
1181 still have to be handled by the relative `export-block' type
1182 translator.
1184 :filters-alist
1186 Alist of filters that will overwrite or complete filters
1187 defined in PARENT back-end. See `org-export-filters-alist'
1188 for a list of allowed filters.
1190 :menu-entry
1192 Menu entry for the export dispatcher. See
1193 `org-export-define-backend' for more information about the
1194 expected value.
1196 :options-alist
1198 Alist of back-end specific properties that will overwrite or
1199 complete those defined in PARENT back-end. Refer to
1200 `org-export-options-alist' for more information about
1201 structure of the values.
1203 :translate-alist
1205 Alist of element and object types and transcoders that will
1206 overwrite or complete transcode table from PARENT back-end.
1207 Refer to `org-export-define-backend' for detailed information
1208 about transcoders.
1210 As an example, here is how one could define \"my-latex\" back-end
1211 as a variant of `latex' back-end with a custom template function:
1213 \(org-export-define-derived-backend 'my-latex 'latex
1214 :translate-alist '((template . my-latex-template-fun)))
1216 The back-end could then be called with, for example:
1218 \(org-export-to-buffer 'my-latex \"*Test my-latex*\")"
1219 (declare (indent 2))
1220 (let (blocks filters menu-entry options transcoders contents)
1221 (while (keywordp (car body))
1222 (case (pop body)
1223 (:export-block (let ((names (pop body)))
1224 (setq blocks (if (consp names) (mapcar 'upcase names)
1225 (list (upcase names))))))
1226 (:filters-alist (setq filters (pop body)))
1227 (:menu-entry (setq menu-entry (pop body)))
1228 (:options-alist (setq options (pop body)))
1229 (:translate-alist (setq transcoders (pop body)))
1230 (t (pop body))))
1231 (org-export-register-backend
1232 (org-export-create-backend :name child
1233 :parent parent
1234 :transcoders transcoders
1235 :options options
1236 :filters filters
1237 :blocks blocks
1238 :menu menu-entry))))
1242 ;;; The Communication Channel
1244 ;; During export process, every function has access to a number of
1245 ;; properties. They are of two types:
1247 ;; 1. Environment options are collected once at the very beginning of
1248 ;; the process, out of the original buffer and configuration.
1249 ;; Collecting them is handled by `org-export-get-environment'
1250 ;; function.
1252 ;; Most environment options are defined through the
1253 ;; `org-export-options-alist' variable.
1255 ;; 2. Tree properties are extracted directly from the parsed tree,
1256 ;; just before export, by `org-export-collect-tree-properties'.
1258 ;; Here is the full list of properties available during transcode
1259 ;; process, with their category and their value type.
1261 ;; + `:author' :: Author's name.
1262 ;; - category :: option
1263 ;; - type :: string
1265 ;; + `:back-end' :: Current back-end used for transcoding.
1266 ;; - category :: tree
1267 ;; - type :: structure
1269 ;; + `:creator' :: String to write as creation information.
1270 ;; - category :: option
1271 ;; - type :: string
1273 ;; + `:date' :: String to use as date.
1274 ;; - category :: option
1275 ;; - type :: string
1277 ;; + `:description' :: Description text for the current data.
1278 ;; - category :: option
1279 ;; - type :: string
1281 ;; + `:email' :: Author's email.
1282 ;; - category :: option
1283 ;; - type :: string
1285 ;; + `:exclude-tags' :: Tags for exclusion of subtrees from export
1286 ;; process.
1287 ;; - category :: option
1288 ;; - type :: list of strings
1290 ;; + `:export-options' :: List of export options available for current
1291 ;; process.
1292 ;; - category :: none
1293 ;; - type :: list of symbols, among `subtree', `body-only' and
1294 ;; `visible-only'.
1296 ;; + `:exported-data' :: Hash table used for memoizing
1297 ;; `org-export-data'.
1298 ;; - category :: tree
1299 ;; - type :: hash table
1301 ;; + `:filetags' :: List of global tags for buffer. Used by
1302 ;; `org-export-get-tags' to get tags with inheritance.
1303 ;; - category :: option
1304 ;; - type :: list of strings
1306 ;; + `:footnote-definition-alist' :: Alist between footnote labels and
1307 ;; their definition, as parsed data. Only non-inlined footnotes
1308 ;; are represented in this alist. Also, every definition isn't
1309 ;; guaranteed to be referenced in the parse tree. The purpose of
1310 ;; this property is to preserve definitions from oblivion
1311 ;; (i.e. when the parse tree comes from a part of the original
1312 ;; buffer), it isn't meant for direct use in a back-end. To
1313 ;; retrieve a definition relative to a reference, use
1314 ;; `org-export-get-footnote-definition' instead.
1315 ;; - category :: option
1316 ;; - type :: alist (STRING . LIST)
1318 ;; + `:headline-levels' :: Maximum level being exported as an
1319 ;; headline. Comparison is done with the relative level of
1320 ;; headlines in the parse tree, not necessarily with their
1321 ;; actual level.
1322 ;; - category :: option
1323 ;; - type :: integer
1325 ;; + `:headline-offset' :: Difference between relative and real level
1326 ;; of headlines in the parse tree. For example, a value of -1
1327 ;; means a level 2 headline should be considered as level
1328 ;; 1 (cf. `org-export-get-relative-level').
1329 ;; - category :: tree
1330 ;; - type :: integer
1332 ;; + `:headline-numbering' :: Alist between headlines and their
1333 ;; numbering, as a list of numbers
1334 ;; (cf. `org-export-get-headline-number').
1335 ;; - category :: tree
1336 ;; - type :: alist (INTEGER . LIST)
1338 ;; + `:id-alist' :: Alist between ID strings and destination file's
1339 ;; path, relative to current directory. It is used by
1340 ;; `org-export-resolve-id-link' to resolve ID links targeting an
1341 ;; external file.
1342 ;; - category :: option
1343 ;; - type :: alist (STRING . STRING)
1345 ;; + `:ignore-list' :: List of elements and objects that should be
1346 ;; ignored during export.
1347 ;; - category :: tree
1348 ;; - type :: list of elements and objects
1350 ;; + `:input-buffer' :: Original buffer name.
1351 ;; - category :: option
1352 ;; - type :: string
1354 ;; + `:input-file' :: Full path to input file, if any.
1355 ;; - category :: option
1356 ;; - type :: string or nil
1358 ;; + `:keywords' :: List of keywords attached to data.
1359 ;; - category :: option
1360 ;; - type :: string
1362 ;; + `:language' :: Default language used for translations.
1363 ;; - category :: option
1364 ;; - type :: string
1366 ;; + `:parse-tree' :: Whole parse tree, available at any time during
1367 ;; transcoding.
1368 ;; - category :: option
1369 ;; - type :: list (as returned by `org-element-parse-buffer')
1371 ;; + `:preserve-breaks' :: Non-nil means transcoding should preserve
1372 ;; all line breaks.
1373 ;; - category :: option
1374 ;; - type :: symbol (nil, t)
1376 ;; + `:section-numbers' :: Non-nil means transcoding should add
1377 ;; section numbers to headlines.
1378 ;; - category :: option
1379 ;; - type :: symbol (nil, t)
1381 ;; + `:select-tags' :: List of tags enforcing inclusion of sub-trees
1382 ;; in transcoding. When such a tag is present, subtrees without
1383 ;; it are de facto excluded from the process. See
1384 ;; `use-select-tags'.
1385 ;; - category :: option
1386 ;; - type :: list of strings
1388 ;; + `:time-stamp-file' :: Non-nil means transcoding should insert
1389 ;; a time stamp in the output.
1390 ;; - category :: option
1391 ;; - type :: symbol (nil, t)
1393 ;; + `:translate-alist' :: Alist between element and object types and
1394 ;; transcoding functions relative to the current back-end.
1395 ;; Special keys `inner-template', `template' and `plain-text' are
1396 ;; also possible.
1397 ;; - category :: option
1398 ;; - type :: alist (SYMBOL . FUNCTION)
1400 ;; + `:with-archived-trees' :: Non-nil when archived subtrees should
1401 ;; also be transcoded. If it is set to the `headline' symbol,
1402 ;; only the archived headline's name is retained.
1403 ;; - category :: option
1404 ;; - type :: symbol (nil, t, `headline')
1406 ;; + `:with-author' :: Non-nil means author's name should be included
1407 ;; in the output.
1408 ;; - category :: option
1409 ;; - type :: symbol (nil, t)
1411 ;; + `:with-clocks' :: Non-nil means clock keywords should be exported.
1412 ;; - category :: option
1413 ;; - type :: symbol (nil, t)
1415 ;; + `:with-creator' :: Non-nil means a creation sentence should be
1416 ;; inserted at the end of the transcoded string. If the value
1417 ;; is `comment', it should be commented.
1418 ;; - category :: option
1419 ;; - type :: symbol (`comment', nil, t)
1421 ;; + `:with-date' :: Non-nil means output should contain a date.
1422 ;; - category :: option
1423 ;; - type :. symbol (nil, t)
1425 ;; + `:with-drawers' :: Non-nil means drawers should be exported. If
1426 ;; its value is a list of names, only drawers with such names
1427 ;; will be transcoded. If that list starts with `not', drawer
1428 ;; with these names will be skipped.
1429 ;; - category :: option
1430 ;; - type :: symbol (nil, t) or list of strings
1432 ;; + `:with-email' :: Non-nil means output should contain author's
1433 ;; email.
1434 ;; - category :: option
1435 ;; - type :: symbol (nil, t)
1437 ;; + `:with-emphasize' :: Non-nil means emphasized text should be
1438 ;; interpreted.
1439 ;; - category :: option
1440 ;; - type :: symbol (nil, t)
1442 ;; + `:with-fixed-width' :: Non-nil if transcoder should export
1443 ;; strings starting with a colon as a fixed-with (verbatim) area.
1444 ;; - category :: option
1445 ;; - type :: symbol (nil, t)
1447 ;; + `:with-footnotes' :: Non-nil if transcoder should interpret
1448 ;; footnotes.
1449 ;; - category :: option
1450 ;; - type :: symbol (nil, t)
1452 ;; + `:with-latex' :: Non-nil means `latex-environment' elements and
1453 ;; `latex-fragment' objects should appear in export output. When
1454 ;; this property is set to `verbatim', they will be left as-is.
1455 ;; - category :: option
1456 ;; - type :: symbol (`verbatim', nil, t)
1458 ;; + `:with-planning' :: Non-nil means transcoding should include
1459 ;; planning info.
1460 ;; - category :: option
1461 ;; - type :: symbol (nil, t)
1463 ;; + `:with-priority' :: Non-nil means transcoding should include
1464 ;; priority cookies.
1465 ;; - category :: option
1466 ;; - type :: symbol (nil, t)
1468 ;; + `:with-smart-quotes' :: Non-nil means activate smart quotes in
1469 ;; plain text.
1470 ;; - category :: option
1471 ;; - type :: symbol (nil, t)
1473 ;; + `:with-special-strings' :: Non-nil means transcoding should
1474 ;; interpret special strings in plain text.
1475 ;; - category :: option
1476 ;; - type :: symbol (nil, t)
1478 ;; + `:with-sub-superscript' :: Non-nil means transcoding should
1479 ;; interpret subscript and superscript. With a value of "{}",
1480 ;; only interpret those using curly brackets.
1481 ;; - category :: option
1482 ;; - type :: symbol (nil, {}, t)
1484 ;; + `:with-tables' :: Non-nil means transcoding should export tables.
1485 ;; - category :: option
1486 ;; - type :: symbol (nil, t)
1488 ;; + `:with-tags' :: Non-nil means transcoding should keep tags in
1489 ;; headlines. A `not-in-toc' value will remove them from the
1490 ;; table of contents, if any, nonetheless.
1491 ;; - category :: option
1492 ;; - type :: symbol (nil, t, `not-in-toc')
1494 ;; + `:with-tasks' :: Non-nil means transcoding should include
1495 ;; headlines with a TODO keyword. A `todo' value will only
1496 ;; include headlines with a todo type keyword while a `done'
1497 ;; value will do the contrary. If a list of strings is provided,
1498 ;; only tasks with keywords belonging to that list will be kept.
1499 ;; - category :: option
1500 ;; - type :: symbol (t, todo, done, nil) or list of strings
1502 ;; + `:with-timestamps' :: Non-nil means transcoding should include
1503 ;; time stamps. Special value `active' (resp. `inactive') ask to
1504 ;; export only active (resp. inactive) timestamps. Otherwise,
1505 ;; completely remove them.
1506 ;; - category :: option
1507 ;; - type :: symbol: (`active', `inactive', t, nil)
1509 ;; + `:with-toc' :: Non-nil means that a table of contents has to be
1510 ;; added to the output. An integer value limits its depth.
1511 ;; - category :: option
1512 ;; - type :: symbol (nil, t or integer)
1514 ;; + `:with-todo-keywords' :: Non-nil means transcoding should
1515 ;; include TODO keywords.
1516 ;; - category :: option
1517 ;; - type :: symbol (nil, t)
1520 ;;;; Environment Options
1522 ;; Environment options encompass all parameters defined outside the
1523 ;; scope of the parsed data. They come from five sources, in
1524 ;; increasing precedence order:
1526 ;; - Global variables,
1527 ;; - Buffer's attributes,
1528 ;; - Options keyword symbols,
1529 ;; - Buffer keywords,
1530 ;; - Subtree properties.
1532 ;; The central internal function with regards to environment options
1533 ;; is `org-export-get-environment'. It updates global variables with
1534 ;; "#+BIND:" keywords, then retrieve and prioritize properties from
1535 ;; the different sources.
1537 ;; The internal functions doing the retrieval are:
1538 ;; `org-export--get-global-options',
1539 ;; `org-export--get-buffer-attributes',
1540 ;; `org-export--parse-option-keyword',
1541 ;; `org-export--get-subtree-options' and
1542 ;; `org-export--get-inbuffer-options'
1544 ;; Also, `org-export--list-bound-variables' collects bound variables
1545 ;; along with their value in order to set them as buffer local
1546 ;; variables later in the process.
1548 (defun org-export-get-environment (&optional backend subtreep ext-plist)
1549 "Collect export options from the current buffer.
1551 Optional argument BACKEND is an export back-end, as returned by
1552 `org-export-create-backend'.
1554 When optional argument SUBTREEP is non-nil, assume the export is
1555 done against the current sub-tree.
1557 Third optional argument EXT-PLIST is a property list with
1558 external parameters overriding Org default settings, but still
1559 inferior to file-local settings."
1560 ;; First install #+BIND variables since these must be set before
1561 ;; global options are read.
1562 (dolist (pair (org-export--list-bound-variables))
1563 (org-set-local (car pair) (nth 1 pair)))
1564 ;; Get and prioritize export options...
1565 (org-combine-plists
1566 ;; ... from global variables...
1567 (org-export--get-global-options backend)
1568 ;; ... from an external property list...
1569 ext-plist
1570 ;; ... from in-buffer settings...
1571 (org-export--get-inbuffer-options backend)
1572 ;; ... and from subtree, when appropriate.
1573 (and subtreep (org-export--get-subtree-options backend))
1574 ;; Eventually add misc. properties.
1575 (list
1576 :back-end
1577 backend
1578 :translate-alist (org-export-get-all-transcoders backend)
1579 :footnote-definition-alist
1580 ;; Footnotes definitions must be collected in the original
1581 ;; buffer, as there's no insurance that they will still be in
1582 ;; the parse tree, due to possible narrowing.
1583 (let (alist)
1584 (org-with-wide-buffer
1585 (goto-char (point-min))
1586 (while (re-search-forward org-footnote-definition-re nil t)
1587 (let ((def (save-match-data (org-element-at-point))))
1588 (when (eq (org-element-type def) 'footnote-definition)
1589 (push
1590 (cons (org-element-property :label def)
1591 (let ((cbeg (org-element-property :contents-begin def)))
1592 (when cbeg
1593 (org-element--parse-elements
1594 cbeg (org-element-property :contents-end def)
1595 nil nil nil nil (list 'org-data nil)))))
1596 alist))))
1597 alist))
1598 :id-alist
1599 ;; Collect id references.
1600 (let (alist)
1601 (org-with-wide-buffer
1602 (goto-char (point-min))
1603 (while (re-search-forward "\\[\\[id:\\S-+?\\]" nil t)
1604 (let ((link (org-element-context)))
1605 (when (eq (org-element-type link) 'link)
1606 (let* ((id (org-element-property :path link))
1607 (file (org-id-find-id-file id)))
1608 (when file
1609 (push (cons id (file-relative-name file)) alist)))))))
1610 alist))))
1612 (defun org-export--parse-option-keyword (options &optional backend)
1613 "Parse an OPTIONS line and return values as a plist.
1614 Optional argument BACKEND is an export back-end, as returned by,
1615 e.g., `org-export-create-backend'. It specifies which back-end
1616 specific items to read, if any."
1617 (let* ((all
1618 ;; Priority is given to back-end specific options.
1619 (append (and backend (org-export-get-all-options backend))
1620 org-export-options-alist))
1621 plist)
1622 (dolist (option all)
1623 (let ((property (car option))
1624 (item (nth 2 option)))
1625 (when (and item
1626 (not (plist-member plist property))
1627 (string-match (concat "\\(\\`\\|[ \t]\\)"
1628 (regexp-quote item)
1629 ":\\(([^)\n]+)\\|[^ \t\n\r;,.]*\\)")
1630 options))
1631 (setq plist (plist-put plist
1632 property
1633 (car (read-from-string
1634 (match-string 2 options))))))))
1635 plist))
1637 (defun org-export--get-subtree-options (&optional backend)
1638 "Get export options in subtree at point.
1639 Optional argument BACKEND is an export back-end, as returned by,
1640 e.g., `org-export-create-backend'. It specifies back-end used
1641 for export. Return options as a plist."
1642 ;; For each buffer keyword, create a headline property setting the
1643 ;; same property in communication channel. The name for the property
1644 ;; is the keyword with "EXPORT_" appended to it.
1645 (org-with-wide-buffer
1646 (let (prop plist)
1647 ;; Make sure point is at a heading.
1648 (if (org-at-heading-p) (org-up-heading-safe) (org-back-to-heading t))
1649 ;; Take care of EXPORT_TITLE. If it isn't defined, use headline's
1650 ;; title (with no todo keyword, priority cookie or tag) as its
1651 ;; fallback value.
1652 (when (setq prop (or (org-entry-get (point) "EXPORT_TITLE")
1653 (progn (looking-at org-complex-heading-regexp)
1654 (org-match-string-no-properties 4))))
1655 (setq plist
1656 (plist-put
1657 plist :title
1658 (org-element-parse-secondary-string
1659 prop (org-element-restriction 'keyword)))))
1660 ;; EXPORT_OPTIONS are parsed in a non-standard way.
1661 (when (setq prop (org-entry-get (point) "EXPORT_OPTIONS"))
1662 (setq plist
1663 (nconc plist (org-export--parse-option-keyword prop backend))))
1664 ;; Handle other keywords. TITLE keyword is excluded as it has
1665 ;; been handled already.
1666 (let ((seen '("TITLE")))
1667 (mapc
1668 (lambda (option)
1669 (let ((property (car option))
1670 (keyword (nth 1 option)))
1671 (when (and keyword (not (member keyword seen)))
1672 (let* ((subtree-prop (concat "EXPORT_" keyword))
1673 ;; Export properties are not case-sensitive.
1674 (value (let ((case-fold-search t))
1675 (org-entry-get (point) subtree-prop))))
1676 (push keyword seen)
1677 (when (and value (not (plist-member plist property)))
1678 (setq plist
1679 (plist-put
1680 plist
1681 property
1682 (cond
1683 ;; Parse VALUE if required.
1684 ((member keyword org-element-document-properties)
1685 (org-element-parse-secondary-string
1686 value (org-element-restriction 'keyword)))
1687 ;; If BEHAVIOR is `split' expected value is
1688 ;; a list of strings, not a string.
1689 ((eq (nth 4 option) 'split) (org-split-string value))
1690 (t value)))))))))
1691 ;; Look for both general keywords and back-end specific
1692 ;; options, with priority given to the latter.
1693 (append (and backend (org-export-get-all-options backend))
1694 org-export-options-alist)))
1695 ;; Return value.
1696 plist)))
1698 (defun org-export--get-inbuffer-options (&optional backend)
1699 "Return current buffer export options, as a plist.
1701 Optional argument BACKEND, when non-nil, is an export back-end,
1702 as returned by, e.g., `org-export-create-backend'. It specifies
1703 which back-end specific options should also be read in the
1704 process.
1706 Assume buffer is in Org mode. Narrowing, if any, is ignored."
1707 (let* (plist
1708 get-options ; For byte-compiler.
1709 (case-fold-search t)
1710 (options (append
1711 ;; Priority is given to back-end specific options.
1712 (and backend (org-export-get-all-options backend))
1713 org-export-options-alist))
1714 (regexp (format "^[ \t]*#\\+%s:"
1715 (regexp-opt (nconc (delq nil (mapcar 'cadr options))
1716 org-export-special-keywords))))
1717 (find-properties
1718 (lambda (keyword)
1719 ;; Return all properties associated to KEYWORD.
1720 (let (properties)
1721 (dolist (option options properties)
1722 (when (equal (nth 1 option) keyword)
1723 (pushnew (car option) properties))))))
1724 (get-options
1725 (lambda (&optional files plist)
1726 ;; Recursively read keywords in buffer. FILES is a list
1727 ;; of files read so far. PLIST is the current property
1728 ;; list obtained.
1729 (org-with-wide-buffer
1730 (goto-char (point-min))
1731 (while (re-search-forward regexp nil t)
1732 (let ((element (org-element-at-point)))
1733 (when (eq (org-element-type element) 'keyword)
1734 (let ((key (org-element-property :key element))
1735 (val (org-element-property :value element)))
1736 (cond
1737 ;; Options in `org-export-special-keywords'.
1738 ((equal key "SETUPFILE")
1739 (let ((file (expand-file-name
1740 (org-remove-double-quotes (org-trim val)))))
1741 ;; Avoid circular dependencies.
1742 (unless (member file files)
1743 (with-temp-buffer
1744 (insert (org-file-contents file 'noerror))
1745 (let ((org-inhibit-startup t)) (org-mode))
1746 (setq plist (funcall get-options
1747 (cons file files) plist))))))
1748 ((equal key "OPTIONS")
1749 (setq plist
1750 (org-combine-plists
1751 plist
1752 (org-export--parse-option-keyword val backend))))
1753 ((equal key "FILETAGS")
1754 (setq plist
1755 (org-combine-plists
1756 plist
1757 (list :filetags
1758 (org-uniquify
1759 (append (org-split-string val ":")
1760 (plist-get plist :filetags)))))))
1762 ;; Options in `org-export-options-alist'.
1763 (dolist (property (funcall find-properties key))
1764 (let ((behaviour (nth 4 (assq property options))))
1765 (setq plist
1766 (plist-put
1767 plist property
1768 ;; Handle value depending on specified
1769 ;; BEHAVIOR.
1770 (case behaviour
1771 (space
1772 (if (not (plist-get plist property))
1773 (org-trim val)
1774 (concat (plist-get plist property)
1776 (org-trim val))))
1777 (newline
1778 (org-trim
1779 (concat (plist-get plist property)
1780 "\n"
1781 (org-trim val))))
1782 (split `(,@(plist-get plist property)
1783 ,@(org-split-string val)))
1784 ('t val)
1785 (otherwise
1786 (if (not (plist-member plist property)) val
1787 (plist-get plist property))))))))))))))
1788 ;; Return final value.
1789 plist))))
1790 ;; Read options in the current buffer.
1791 (setq plist (funcall get-options
1792 (and buffer-file-name (list buffer-file-name)) nil))
1793 ;; Parse keywords specified in `org-element-document-properties'
1794 ;; and return PLIST.
1795 (dolist (keyword org-element-document-properties plist)
1796 (dolist (property (funcall find-properties keyword))
1797 (let ((value (plist-get plist property)))
1798 (when (stringp value)
1799 (setq plist
1800 (plist-put plist property
1801 (org-element-parse-secondary-string
1802 value (org-element-restriction 'keyword))))))))))
1804 (defun org-export--get-buffer-attributes ()
1805 "Return properties related to buffer attributes, as a plist."
1806 ;; Store full path of input file name, or nil. For internal use.
1807 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
1808 (list :input-buffer (buffer-name (buffer-base-buffer))
1809 :input-file visited-file
1810 :title (if (not visited-file) (buffer-name (buffer-base-buffer))
1811 (file-name-sans-extension
1812 (file-name-nondirectory visited-file))))))
1814 (defun org-export--get-global-options (&optional backend)
1815 "Return global export options as a plist.
1816 Optional argument BACKEND, if non-nil, is an export back-end, as
1817 returned by, e.g., `org-export-create-backend'. It specifies
1818 which back-end specific export options should also be read in the
1819 process."
1820 (let (plist
1821 ;; Priority is given to back-end specific options.
1822 (all (append (and backend (org-export-get-all-options backend))
1823 org-export-options-alist)))
1824 (dolist (cell all plist)
1825 (let ((prop (car cell))
1826 (default-value (nth 3 cell)))
1827 (unless (or (not default-value) (plist-member plist prop))
1828 (setq plist
1829 (plist-put
1830 plist
1831 prop
1832 ;; Eval default value provided. If keyword is
1833 ;; a member of `org-element-document-properties',
1834 ;; parse it as a secondary string before storing it.
1835 (let ((value (eval (nth 3 cell))))
1836 (if (not (stringp value)) value
1837 (let ((keyword (nth 1 cell)))
1838 (if (member keyword org-element-document-properties)
1839 (org-element-parse-secondary-string
1840 value (org-element-restriction 'keyword))
1841 value)))))))))))
1843 (defun org-export--list-bound-variables ()
1844 "Return variables bound from BIND keywords in current buffer.
1845 Also look for BIND keywords in setup files. The return value is
1846 an alist where associations are (VARIABLE-NAME VALUE)."
1847 (when org-export-allow-bind-keywords
1848 (let* (collect-bind ; For byte-compiler.
1849 (collect-bind
1850 (lambda (files alist)
1851 ;; Return an alist between variable names and their
1852 ;; value. FILES is a list of setup files names read so
1853 ;; far, used to avoid circular dependencies. ALIST is
1854 ;; the alist collected so far.
1855 (let ((case-fold-search t))
1856 (org-with-wide-buffer
1857 (goto-char (point-min))
1858 (while (re-search-forward
1859 "^[ \t]*#\\+\\(BIND\\|SETUPFILE\\):" nil t)
1860 (let ((element (org-element-at-point)))
1861 (when (eq (org-element-type element) 'keyword)
1862 (let ((val (org-element-property :value element)))
1863 (if (equal (org-element-property :key element) "BIND")
1864 (push (read (format "(%s)" val)) alist)
1865 ;; Enter setup file.
1866 (let ((file (expand-file-name
1867 (org-remove-double-quotes val))))
1868 (unless (member file files)
1869 (with-temp-buffer
1870 (let ((org-inhibit-startup t)) (org-mode))
1871 (insert (org-file-contents file 'noerror))
1872 (setq alist
1873 (funcall collect-bind
1874 (cons file files)
1875 alist))))))))))
1876 alist)))))
1877 ;; Return value in appropriate order of appearance.
1878 (nreverse (funcall collect-bind nil nil)))))
1881 ;;;; Tree Properties
1883 ;; Tree properties are information extracted from parse tree. They
1884 ;; are initialized at the beginning of the transcoding process by
1885 ;; `org-export-collect-tree-properties'.
1887 ;; Dedicated functions focus on computing the value of specific tree
1888 ;; properties during initialization. Thus,
1889 ;; `org-export--populate-ignore-list' lists elements and objects that
1890 ;; should be skipped during export, `org-export--get-min-level' gets
1891 ;; the minimal exportable level, used as a basis to compute relative
1892 ;; level for headlines. Eventually
1893 ;; `org-export--collect-headline-numbering' builds an alist between
1894 ;; headlines and their numbering.
1896 (defun org-export-collect-tree-properties (data info)
1897 "Extract tree properties from parse tree.
1899 DATA is the parse tree from which information is retrieved. INFO
1900 is a list holding export options.
1902 Following tree properties are set or updated:
1904 `:exported-data' Hash table used to memoize results from
1905 `org-export-data'.
1907 `:footnote-definition-alist' List of footnotes definitions in
1908 original buffer and current parse tree.
1910 `:headline-offset' Offset between true level of headlines and
1911 local level. An offset of -1 means a headline
1912 of level 2 should be considered as a level
1913 1 headline in the context.
1915 `:headline-numbering' Alist of all headlines as key an the
1916 associated numbering as value.
1918 `:ignore-list' List of elements that should be ignored during
1919 export.
1921 Return updated plist."
1922 ;; Install the parse tree in the communication channel, in order to
1923 ;; use `org-export-get-genealogy' and al.
1924 (setq info (plist-put info :parse-tree data))
1925 ;; Get the list of elements and objects to ignore, and put it into
1926 ;; `:ignore-list'. Do not overwrite any user ignore that might have
1927 ;; been done during parse tree filtering.
1928 (setq info
1929 (plist-put info
1930 :ignore-list
1931 (append (org-export--populate-ignore-list data info)
1932 (plist-get info :ignore-list))))
1933 ;; Compute `:headline-offset' in order to be able to use
1934 ;; `org-export-get-relative-level'.
1935 (setq info
1936 (plist-put info
1937 :headline-offset
1938 (- 1 (org-export--get-min-level data info))))
1939 ;; Update footnotes definitions list with definitions in parse tree.
1940 ;; This is required since buffer expansion might have modified
1941 ;; boundaries of footnote definitions contained in the parse tree.
1942 ;; This way, definitions in `footnote-definition-alist' are bound to
1943 ;; match those in the parse tree.
1944 (let ((defs (plist-get info :footnote-definition-alist)))
1945 (org-element-map data 'footnote-definition
1946 (lambda (fn)
1947 (push (cons (org-element-property :label fn)
1948 `(org-data nil ,@(org-element-contents fn)))
1949 defs)))
1950 (setq info (plist-put info :footnote-definition-alist defs)))
1951 ;; Properties order doesn't matter: get the rest of the tree
1952 ;; properties.
1953 (nconc
1954 `(:headline-numbering ,(org-export--collect-headline-numbering data info)
1955 :exported-data ,(make-hash-table :test 'eq :size 4001))
1956 info))
1958 (defun org-export--get-min-level (data options)
1959 "Return minimum exportable headline's level in DATA.
1960 DATA is parsed tree as returned by `org-element-parse-buffer'.
1961 OPTIONS is a plist holding export options."
1962 (catch 'exit
1963 (let ((min-level 10000))
1964 (mapc
1965 (lambda (blob)
1966 (when (and (eq (org-element-type blob) 'headline)
1967 (not (org-element-property :footnote-section-p blob))
1968 (not (memq blob (plist-get options :ignore-list))))
1969 (setq min-level (min (org-element-property :level blob) min-level)))
1970 (when (= min-level 1) (throw 'exit 1)))
1971 (org-element-contents data))
1972 ;; If no headline was found, for the sake of consistency, set
1973 ;; minimum level to 1 nonetheless.
1974 (if (= min-level 10000) 1 min-level))))
1976 (defun org-export--collect-headline-numbering (data options)
1977 "Return numbering of all exportable headlines in a parse tree.
1979 DATA is the parse tree. OPTIONS is the plist holding export
1980 options.
1982 Return an alist whose key is a headline and value is its
1983 associated numbering \(in the shape of a list of numbers\) or nil
1984 for a footnotes section."
1985 (let ((numbering (make-vector org-export-max-depth 0)))
1986 (org-element-map data 'headline
1987 (lambda (headline)
1988 (unless (org-element-property :footnote-section-p headline)
1989 (let ((relative-level
1990 (1- (org-export-get-relative-level headline options))))
1991 (cons
1992 headline
1993 (loop for n across numbering
1994 for idx from 0 to org-export-max-depth
1995 when (< idx relative-level) collect n
1996 when (= idx relative-level) collect (aset numbering idx (1+ n))
1997 when (> idx relative-level) do (aset numbering idx 0))))))
1998 options)))
2000 (defun org-export--populate-ignore-list (data options)
2001 "Return list of elements and objects to ignore during export.
2002 DATA is the parse tree to traverse. OPTIONS is the plist holding
2003 export options."
2004 (let* (walk-data
2005 ;; First find trees containing a select tag, if any.
2006 (selected (org-export--selected-trees data options))
2007 ;; If a select tag is active, also ignore the section before
2008 ;; the first headline, if any.
2009 (ignore (and selected
2010 (let ((first-element (car (org-element-contents data))))
2011 (and (eq (org-element-type first-element) 'section)
2012 first-element))))
2013 (walk-data
2014 (lambda (data)
2015 ;; Collect ignored elements or objects into IGNORE-LIST.
2016 (let ((type (org-element-type data)))
2017 (if (org-export--skip-p data options selected) (push data ignore)
2018 (if (and (eq type 'headline)
2019 (eq (plist-get options :with-archived-trees) 'headline)
2020 (org-element-property :archivedp data))
2021 ;; If headline is archived but tree below has
2022 ;; to be skipped, add it to ignore list.
2023 (dolist (element (org-element-contents data))
2024 (push element ignore))
2025 ;; Move into secondary string, if any.
2026 (let ((sec-prop
2027 (cdr (assq type org-element-secondary-value-alist))))
2028 (when sec-prop
2029 (mapc walk-data (org-element-property sec-prop data))))
2030 ;; Move into recursive objects/elements.
2031 (mapc walk-data (org-element-contents data))))))))
2032 ;; Main call.
2033 (funcall walk-data data)
2034 ;; Return value.
2035 ignore))
2037 (defun org-export--selected-trees (data info)
2038 "Return list of headlines and inlinetasks with a select tag in their tree.
2039 DATA is parsed data as returned by `org-element-parse-buffer'.
2040 INFO is a plist holding export options."
2041 (let* (selected-trees
2042 walk-data ; For byte-compiler.
2043 (walk-data
2044 (function
2045 (lambda (data genealogy)
2046 (let ((type (org-element-type data)))
2047 (cond
2048 ((memq type '(headline inlinetask))
2049 (let ((tags (org-element-property :tags data)))
2050 (if (loop for tag in (plist-get info :select-tags)
2051 thereis (member tag tags))
2052 ;; When a select tag is found, mark full
2053 ;; genealogy and every headline within the tree
2054 ;; as acceptable.
2055 (setq selected-trees
2056 (append
2057 genealogy
2058 (org-element-map data '(headline inlinetask)
2059 'identity)
2060 selected-trees))
2061 ;; If at a headline, continue searching in tree,
2062 ;; recursively.
2063 (when (eq type 'headline)
2064 (mapc (lambda (el)
2065 (funcall walk-data el (cons data genealogy)))
2066 (org-element-contents data))))))
2067 ((or (eq type 'org-data)
2068 (memq type org-element-greater-elements))
2069 (mapc (lambda (el) (funcall walk-data el genealogy))
2070 (org-element-contents data)))))))))
2071 (funcall walk-data data nil)
2072 selected-trees))
2074 (defun org-export--skip-p (blob options selected)
2075 "Non-nil when element or object BLOB should be skipped during export.
2076 OPTIONS is the plist holding export options. SELECTED, when
2077 non-nil, is a list of headlines or inlinetasks belonging to
2078 a tree with a select tag."
2079 (case (org-element-type blob)
2080 (clock (not (plist-get options :with-clocks)))
2081 (drawer
2082 (let ((with-drawers-p (plist-get options :with-drawers)))
2083 (or (not with-drawers-p)
2084 (and (consp with-drawers-p)
2085 ;; If `:with-drawers' value starts with `not', ignore
2086 ;; every drawer whose name belong to that list.
2087 ;; Otherwise, ignore drawers whose name isn't in that
2088 ;; list.
2089 (let ((name (org-element-property :drawer-name blob)))
2090 (if (eq (car with-drawers-p) 'not)
2091 (member-ignore-case name (cdr with-drawers-p))
2092 (not (member-ignore-case name with-drawers-p))))))))
2093 (fixed-width (not (plist-get options :with-fixed-width)))
2094 ((footnote-definition footnote-reference)
2095 (not (plist-get options :with-footnotes)))
2096 ((headline inlinetask)
2097 (let ((with-tasks (plist-get options :with-tasks))
2098 (todo (org-element-property :todo-keyword blob))
2099 (todo-type (org-element-property :todo-type blob))
2100 (archived (plist-get options :with-archived-trees))
2101 (tags (org-element-property :tags blob)))
2103 (and (eq (org-element-type blob) 'inlinetask)
2104 (not (plist-get options :with-inlinetasks)))
2105 ;; Ignore subtrees with an exclude tag.
2106 (loop for k in (plist-get options :exclude-tags)
2107 thereis (member k tags))
2108 ;; When a select tag is present in the buffer, ignore any tree
2109 ;; without it.
2110 (and selected (not (memq blob selected)))
2111 ;; Ignore commented sub-trees.
2112 (org-element-property :commentedp blob)
2113 ;; Ignore archived subtrees if `:with-archived-trees' is nil.
2114 (and (not archived) (org-element-property :archivedp blob))
2115 ;; Ignore tasks, if specified by `:with-tasks' property.
2116 (and todo
2117 (or (not with-tasks)
2118 (and (memq with-tasks '(todo done))
2119 (not (eq todo-type with-tasks)))
2120 (and (consp with-tasks) (not (member todo with-tasks))))))))
2121 ((latex-environment latex-fragment) (not (plist-get options :with-latex)))
2122 (node-property
2123 (let ((properties-set (plist-get options :with-properties)))
2124 (cond ((null properties-set) t)
2125 ((consp properties-set)
2126 (not (member-ignore-case (org-element-property :key blob)
2127 properties-set))))))
2128 (planning (not (plist-get options :with-planning)))
2129 (property-drawer (not (plist-get options :with-properties)))
2130 (statistics-cookie (not (plist-get options :with-statistics-cookies)))
2131 (table (not (plist-get options :with-tables)))
2132 (table-cell
2133 (and (org-export-table-has-special-column-p
2134 (org-export-get-parent-table blob))
2135 (not (org-export-get-previous-element blob options))))
2136 (table-row (org-export-table-row-is-special-p blob options))
2137 (timestamp
2138 ;; `:with-timestamps' only applies to isolated timestamps
2139 ;; objects, i.e. timestamp objects in a paragraph containing only
2140 ;; timestamps and whitespaces.
2141 (when (let ((parent (org-export-get-parent-element blob)))
2142 (and (memq (org-element-type parent) '(paragraph verse-block))
2143 (not (org-element-map parent
2144 (cons 'plain-text
2145 (remq 'timestamp org-element-all-objects))
2146 (lambda (obj)
2147 (or (not (stringp obj)) (org-string-nw-p obj)))
2148 options t))))
2149 (case (plist-get options :with-timestamps)
2150 ('nil t)
2151 (active
2152 (not (memq (org-element-property :type blob) '(active active-range))))
2153 (inactive
2154 (not (memq (org-element-property :type blob)
2155 '(inactive inactive-range)))))))))
2158 ;;; The Transcoder
2160 ;; `org-export-data' reads a parse tree (obtained with, i.e.
2161 ;; `org-element-parse-buffer') and transcodes it into a specified
2162 ;; back-end output. It takes care of filtering out elements or
2163 ;; objects according to export options and organizing the output blank
2164 ;; lines and white space are preserved. The function memoizes its
2165 ;; results, so it is cheap to call it within transcoders.
2167 ;; It is possible to modify locally the back-end used by
2168 ;; `org-export-data' or even use a temporary back-end by using
2169 ;; `org-export-data-with-backend'.
2171 ;; Internally, three functions handle the filtering of objects and
2172 ;; elements during the export. In particular,
2173 ;; `org-export-ignore-element' marks an element or object so future
2174 ;; parse tree traversals skip it and `org-export-expand' transforms
2175 ;; the others back into their original shape.
2177 ;; `org-export-transcoder' is an accessor returning appropriate
2178 ;; translator function for a given element or object.
2180 (defun org-export-transcoder (blob info)
2181 "Return appropriate transcoder for BLOB.
2182 INFO is a plist containing export directives."
2183 (let ((type (org-element-type blob)))
2184 ;; Return contents only for complete parse trees.
2185 (if (eq type 'org-data) (lambda (blob contents info) contents)
2186 (let ((transcoder (cdr (assq type (plist-get info :translate-alist)))))
2187 (and (functionp transcoder) transcoder)))))
2189 (defun org-export-data (data info)
2190 "Convert DATA into current back-end format.
2192 DATA is a parse tree, an element or an object or a secondary
2193 string. INFO is a plist holding export options.
2195 Return transcoded string."
2196 (let ((memo (gethash data (plist-get info :exported-data) 'no-memo)))
2197 (if (not (eq memo 'no-memo)) memo
2198 (let* ((type (org-element-type data))
2199 (results
2200 (cond
2201 ;; Ignored element/object.
2202 ((memq data (plist-get info :ignore-list)) nil)
2203 ;; Plain text.
2204 ((eq type 'plain-text)
2205 (org-export-filter-apply-functions
2206 (plist-get info :filter-plain-text)
2207 (let ((transcoder (org-export-transcoder data info)))
2208 (if transcoder (funcall transcoder data info) data))
2209 info))
2210 ;; Secondary string.
2211 ((not type)
2212 (mapconcat (lambda (obj) (org-export-data obj info)) data ""))
2213 ;; Element/Object without contents or, as a special case,
2214 ;; headline with archive tag and archived trees restricted
2215 ;; to title only.
2216 ((or (not (org-element-contents data))
2217 (and (eq type 'headline)
2218 (eq (plist-get info :with-archived-trees) 'headline)
2219 (org-element-property :archivedp data)))
2220 (let ((transcoder (org-export-transcoder data info)))
2221 (or (and (functionp transcoder)
2222 (funcall transcoder data nil info))
2223 ;; Export snippets never return a nil value so
2224 ;; that white spaces following them are never
2225 ;; ignored.
2226 (and (eq type 'export-snippet) ""))))
2227 ;; Element/Object with contents.
2229 (let ((transcoder (org-export-transcoder data info)))
2230 (when transcoder
2231 (let* ((greaterp (memq type org-element-greater-elements))
2232 (objectp
2233 (and (not greaterp)
2234 (memq type org-element-recursive-objects)))
2235 (contents
2236 (mapconcat
2237 (lambda (element) (org-export-data element info))
2238 (org-element-contents
2239 (if (or greaterp objectp) data
2240 ;; Elements directly containing objects
2241 ;; must have their indentation normalized
2242 ;; first.
2243 (org-element-normalize-contents
2244 data
2245 ;; When normalizing contents of the first
2246 ;; paragraph in an item or a footnote
2247 ;; definition, ignore first line's
2248 ;; indentation: there is none and it
2249 ;; might be misleading.
2250 (when (eq type 'paragraph)
2251 (let ((parent (org-export-get-parent data)))
2252 (and
2253 (eq (car (org-element-contents parent))
2254 data)
2255 (memq (org-element-type parent)
2256 '(footnote-definition item))))))))
2257 "")))
2258 (funcall transcoder data
2259 (if (not greaterp) contents
2260 (org-element-normalize-string contents))
2261 info))))))))
2262 ;; Final result will be memoized before being returned.
2263 (puthash
2264 data
2265 (cond
2266 ((not results) nil)
2267 ((memq type '(org-data plain-text nil)) results)
2268 ;; Append the same white space between elements or objects as in
2269 ;; the original buffer, and call appropriate filters.
2271 (let ((results
2272 (org-export-filter-apply-functions
2273 (plist-get info (intern (format ":filter-%s" type)))
2274 (let ((post-blank (or (org-element-property :post-blank data)
2275 0)))
2276 (if (memq type org-element-all-elements)
2277 (concat (org-element-normalize-string results)
2278 (make-string post-blank ?\n))
2279 (concat results (make-string post-blank ? ))))
2280 info)))
2281 results)))
2282 (plist-get info :exported-data))))))
2284 (defun org-export-data-with-backend (data backend info)
2285 "Convert DATA into BACKEND format.
2287 DATA is an element, an object, a secondary string or a string.
2288 BACKEND is a symbol. INFO is a plist used as a communication
2289 channel.
2291 Unlike to `org-export-with-backend', this function will
2292 recursively convert DATA using BACKEND translation table."
2293 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
2294 (org-export-data
2295 data
2296 ;; Set-up a new communication channel with translations defined in
2297 ;; BACKEND as the translate table and a new hash table for
2298 ;; memoization.
2299 (org-combine-plists
2300 info
2301 (list :back-end backend
2302 :translate-alist (org-export-get-all-transcoders backend)
2303 ;; Size of the hash table is reduced since this function
2304 ;; will probably be used on small trees.
2305 :exported-data (make-hash-table :test 'eq :size 401)))))
2307 (defun org-export-remove-uninterpreted-data (data info)
2308 "Change uninterpreted elements back into Org syntax.
2309 DATA is the parse tree. INFO is a plist containing export
2310 options. Each uninterpreted element or object is changed back
2311 into a string. Contents, if any, are not modified. The parse
2312 tree is modified by side effect and returned by the function."
2313 (org-export--remove-uninterpreted-data-1 data info)
2314 (dolist (prop '(:author :date :title))
2315 (plist-put info
2316 prop
2317 (org-export--remove-uninterpreted-data-1
2318 (plist-get info prop)
2319 info))))
2321 (defun org-export--remove-uninterpreted-data-1 (data info)
2322 "Change uninterpreted elements back into Org syntax.
2323 DATA is a parse tree or a secondary string. INFO is a plist
2324 containing export options. It is modified by side effect and
2325 returned by the function."
2326 (org-element-map data
2327 '(entity bold italic latex-environment latex-fragment strike-through
2328 subscript superscript underline)
2329 #'(lambda (blob)
2330 (let ((new
2331 (case (org-element-type blob)
2332 ;; ... entities...
2333 (entity
2334 (and (not (plist-get info :with-entities))
2335 (list (concat
2336 (org-export-expand blob nil)
2337 (make-string
2338 (or (org-element-property :post-blank blob) 0)
2339 ?\s)))))
2340 ;; ... emphasis...
2341 ((bold italic strike-through underline)
2342 (and (not (plist-get info :with-emphasize))
2343 (let ((marker (case (org-element-type blob)
2344 (bold "*")
2345 (italic "/")
2346 (strike-through "+")
2347 (underline "_"))))
2348 (append
2349 (list marker)
2350 (org-element-contents blob)
2351 (list (concat
2352 marker
2353 (make-string
2354 (or (org-element-property :post-blank blob)
2356 ?\s)))))))
2357 ;; ... LaTeX environments and fragments...
2358 ((latex-environment latex-fragment)
2359 (and (eq (plist-get info :with-latex) 'verbatim)
2360 (list (org-export-expand blob nil))))
2361 ;; ... sub/superscripts...
2362 ((subscript superscript)
2363 (let ((sub/super-p (plist-get info :with-sub-superscript))
2364 (bracketp (org-element-property :use-brackets-p blob)))
2365 (and (or (not sub/super-p)
2366 (and (eq sub/super-p '{}) (not bracketp)))
2367 (append
2368 (list (concat
2369 (if (eq (org-element-type blob) 'subscript)
2371 "^")
2372 (and bracketp "{")))
2373 (org-element-contents blob)
2374 (list (concat
2375 (and bracketp "}")
2376 (and (org-element-property :post-blank blob)
2377 (make-string
2378 (org-element-property :post-blank blob)
2379 ?\s)))))))))))
2380 (when new
2381 ;; Splice NEW at BLOB location in parse tree.
2382 (dolist (e new (org-element-extract-element blob))
2383 (unless (string= e "") (org-element-insert-before e blob))))))
2384 info)
2385 ;; Return modified parse tree.
2386 data)
2388 (defun org-export-expand (blob contents &optional with-affiliated)
2389 "Expand a parsed element or object to its original state.
2391 BLOB is either an element or an object. CONTENTS is its
2392 contents, as a string or nil.
2394 When optional argument WITH-AFFILIATED is non-nil, add affiliated
2395 keywords before output."
2396 (let ((type (org-element-type blob)))
2397 (concat (and with-affiliated (memq type org-element-all-elements)
2398 (org-element--interpret-affiliated-keywords blob))
2399 (funcall (intern (format "org-element-%s-interpreter" type))
2400 blob contents))))
2402 (defun org-export-ignore-element (element info)
2403 "Add ELEMENT to `:ignore-list' in INFO.
2405 Any element in `:ignore-list' will be skipped when using
2406 `org-element-map'. INFO is modified by side effects."
2407 (plist-put info :ignore-list (cons element (plist-get info :ignore-list))))
2411 ;;; The Filter System
2413 ;; Filters allow end-users to tweak easily the transcoded output.
2414 ;; They are the functional counterpart of hooks, as every filter in
2415 ;; a set is applied to the return value of the previous one.
2417 ;; Every set is back-end agnostic. Although, a filter is always
2418 ;; called, in addition to the string it applies to, with the back-end
2419 ;; used as argument, so it's easy for the end-user to add back-end
2420 ;; specific filters in the set. The communication channel, as
2421 ;; a plist, is required as the third argument.
2423 ;; From the developer side, filters sets can be installed in the
2424 ;; process with the help of `org-export-define-backend', which
2425 ;; internally stores filters as an alist. Each association has a key
2426 ;; among the following symbols and a function or a list of functions
2427 ;; as value.
2429 ;; - `:filter-options' applies to the property list containing export
2430 ;; options. Unlike to other filters, functions in this list accept
2431 ;; two arguments instead of three: the property list containing
2432 ;; export options and the back-end. Users can set its value through
2433 ;; `org-export-filter-options-functions' variable.
2435 ;; - `:filter-parse-tree' applies directly to the complete parsed
2436 ;; tree. Users can set it through
2437 ;; `org-export-filter-parse-tree-functions' variable.
2439 ;; - `:filter-final-output' applies to the final transcoded string.
2440 ;; Users can set it with `org-export-filter-final-output-functions'
2441 ;; variable
2443 ;; - `:filter-plain-text' applies to any string not recognized as Org
2444 ;; syntax. `org-export-filter-plain-text-functions' allows users to
2445 ;; configure it.
2447 ;; - `:filter-TYPE' applies on the string returned after an element or
2448 ;; object of type TYPE has been transcoded. A user can modify
2449 ;; `org-export-filter-TYPE-functions'
2451 ;; All filters sets are applied with
2452 ;; `org-export-filter-apply-functions' function. Filters in a set are
2453 ;; applied in a LIFO fashion. It allows developers to be sure that
2454 ;; their filters will be applied first.
2456 ;; Filters properties are installed in communication channel with
2457 ;; `org-export-install-filters' function.
2459 ;; Eventually, two hooks (`org-export-before-processing-hook' and
2460 ;; `org-export-before-parsing-hook') are run at the beginning of the
2461 ;; export process and just before parsing to allow for heavy structure
2462 ;; modifications.
2465 ;;;; Hooks
2467 (defvar org-export-before-processing-hook nil
2468 "Hook run at the beginning of the export process.
2470 This is run before include keywords and macros are expanded and
2471 Babel code blocks executed, on a copy of the original buffer
2472 being exported. Visibility and narrowing are preserved. Point
2473 is at the beginning of the buffer.
2475 Every function in this hook will be called with one argument: the
2476 back-end currently used, as a symbol.")
2478 (defvar org-export-before-parsing-hook nil
2479 "Hook run before parsing an export buffer.
2481 This is run after include keywords and macros have been expanded
2482 and Babel code blocks executed, on a copy of the original buffer
2483 being exported. Visibility and narrowing are preserved. Point
2484 is at the beginning of the buffer.
2486 Every function in this hook will be called with one argument: the
2487 back-end currently used, as a symbol.")
2490 ;;;; Special Filters
2492 (defvar org-export-filter-options-functions nil
2493 "List of functions applied to the export options.
2494 Each filter is called with two arguments: the export options, as
2495 a plist, and the back-end, as a symbol. It must return
2496 a property list containing export options.")
2498 (defvar org-export-filter-parse-tree-functions nil
2499 "List of functions applied to the parsed tree.
2500 Each filter is called with three arguments: the parse tree, as
2501 returned by `org-element-parse-buffer', the back-end, as
2502 a symbol, and the communication channel, as a plist. It must
2503 return the modified parse tree to transcode.")
2505 (defvar org-export-filter-plain-text-functions nil
2506 "List of functions applied to plain text.
2507 Each filter is called with three arguments: a string which
2508 contains no Org syntax, the back-end, as a symbol, and the
2509 communication channel, as a plist. It must return a string or
2510 nil.")
2512 (defvar org-export-filter-final-output-functions nil
2513 "List of functions applied to the transcoded string.
2514 Each filter is called with three arguments: the full transcoded
2515 string, the back-end, as a symbol, and the communication channel,
2516 as a plist. It must return a string that will be used as the
2517 final export output.")
2520 ;;;; Elements Filters
2522 (defvar org-export-filter-babel-call-functions nil
2523 "List of functions applied to a transcoded babel-call.
2524 Each filter is called with three arguments: the transcoded data,
2525 as a string, the back-end, as a symbol, and the communication
2526 channel, as a plist. It must return a string or nil.")
2528 (defvar org-export-filter-center-block-functions nil
2529 "List of functions applied to a transcoded center block.
2530 Each filter is called with three arguments: the transcoded data,
2531 as a string, the back-end, as a symbol, and the communication
2532 channel, as a plist. It must return a string or nil.")
2534 (defvar org-export-filter-clock-functions nil
2535 "List of functions applied to a transcoded clock.
2536 Each filter is called with three arguments: the transcoded data,
2537 as a string, the back-end, as a symbol, and the communication
2538 channel, as a plist. It must return a string or nil.")
2540 (defvar org-export-filter-comment-functions nil
2541 "List of functions applied to a transcoded comment.
2542 Each filter is called with three arguments: the transcoded data,
2543 as a string, the back-end, as a symbol, and the communication
2544 channel, as a plist. It must return a string or nil.")
2546 (defvar org-export-filter-comment-block-functions nil
2547 "List of functions applied to a transcoded comment-block.
2548 Each filter is called with three arguments: the transcoded data,
2549 as a string, the back-end, as a symbol, and the communication
2550 channel, as a plist. It must return a string or nil.")
2552 (defvar org-export-filter-diary-sexp-functions nil
2553 "List of functions applied to a transcoded diary-sexp.
2554 Each filter is called with three arguments: the transcoded data,
2555 as a string, the back-end, as a symbol, and the communication
2556 channel, as a plist. It must return a string or nil.")
2558 (defvar org-export-filter-drawer-functions nil
2559 "List of functions applied to a transcoded drawer.
2560 Each filter is called with three arguments: the transcoded data,
2561 as a string, the back-end, as a symbol, and the communication
2562 channel, as a plist. It must return a string or nil.")
2564 (defvar org-export-filter-dynamic-block-functions nil
2565 "List of functions applied to a transcoded dynamic-block.
2566 Each filter is called with three arguments: the transcoded data,
2567 as a string, the back-end, as a symbol, and the communication
2568 channel, as a plist. It must return a string or nil.")
2570 (defvar org-export-filter-example-block-functions nil
2571 "List of functions applied to a transcoded example-block.
2572 Each filter is called with three arguments: the transcoded data,
2573 as a string, the back-end, as a symbol, and the communication
2574 channel, as a plist. It must return a string or nil.")
2576 (defvar org-export-filter-export-block-functions nil
2577 "List of functions applied to a transcoded export-block.
2578 Each filter is called with three arguments: the transcoded data,
2579 as a string, the back-end, as a symbol, and the communication
2580 channel, as a plist. It must return a string or nil.")
2582 (defvar org-export-filter-fixed-width-functions nil
2583 "List of functions applied to a transcoded fixed-width.
2584 Each filter is called with three arguments: the transcoded data,
2585 as a string, the back-end, as a symbol, and the communication
2586 channel, as a plist. It must return a string or nil.")
2588 (defvar org-export-filter-footnote-definition-functions nil
2589 "List of functions applied to a transcoded footnote-definition.
2590 Each filter is called with three arguments: the transcoded data,
2591 as a string, the back-end, as a symbol, and the communication
2592 channel, as a plist. It must return a string or nil.")
2594 (defvar org-export-filter-headline-functions nil
2595 "List of functions applied to a transcoded headline.
2596 Each filter is called with three arguments: the transcoded data,
2597 as a string, the back-end, as a symbol, and the communication
2598 channel, as a plist. It must return a string or nil.")
2600 (defvar org-export-filter-horizontal-rule-functions nil
2601 "List of functions applied to a transcoded horizontal-rule.
2602 Each filter is called with three arguments: the transcoded data,
2603 as a string, the back-end, as a symbol, and the communication
2604 channel, as a plist. It must return a string or nil.")
2606 (defvar org-export-filter-inlinetask-functions nil
2607 "List of functions applied to a transcoded inlinetask.
2608 Each filter is called with three arguments: the transcoded data,
2609 as a string, the back-end, as a symbol, and the communication
2610 channel, as a plist. It must return a string or nil.")
2612 (defvar org-export-filter-item-functions nil
2613 "List of functions applied to a transcoded item.
2614 Each filter is called with three arguments: the transcoded data,
2615 as a string, the back-end, as a symbol, and the communication
2616 channel, as a plist. It must return a string or nil.")
2618 (defvar org-export-filter-keyword-functions nil
2619 "List of functions applied to a transcoded keyword.
2620 Each filter is called with three arguments: the transcoded data,
2621 as a string, the back-end, as a symbol, and the communication
2622 channel, as a plist. It must return a string or nil.")
2624 (defvar org-export-filter-latex-environment-functions nil
2625 "List of functions applied to a transcoded latex-environment.
2626 Each filter is called with three arguments: the transcoded data,
2627 as a string, the back-end, as a symbol, and the communication
2628 channel, as a plist. It must return a string or nil.")
2630 (defvar org-export-filter-node-property-functions nil
2631 "List of functions applied to a transcoded node-property.
2632 Each filter is called with three arguments: the transcoded data,
2633 as a string, the back-end, as a symbol, and the communication
2634 channel, as a plist. It must return a string or nil.")
2636 (defvar org-export-filter-paragraph-functions nil
2637 "List of functions applied to a transcoded paragraph.
2638 Each filter is called with three arguments: the transcoded data,
2639 as a string, the back-end, as a symbol, and the communication
2640 channel, as a plist. It must return a string or nil.")
2642 (defvar org-export-filter-plain-list-functions nil
2643 "List of functions applied to a transcoded plain-list.
2644 Each filter is called with three arguments: the transcoded data,
2645 as a string, the back-end, as a symbol, and the communication
2646 channel, as a plist. It must return a string or nil.")
2648 (defvar org-export-filter-planning-functions nil
2649 "List of functions applied to a transcoded planning.
2650 Each filter is called with three arguments: the transcoded data,
2651 as a string, the back-end, as a symbol, and the communication
2652 channel, as a plist. It must return a string or nil.")
2654 (defvar org-export-filter-property-drawer-functions nil
2655 "List of functions applied to a transcoded property-drawer.
2656 Each filter is called with three arguments: the transcoded data,
2657 as a string, the back-end, as a symbol, and the communication
2658 channel, as a plist. It must return a string or nil.")
2660 (defvar org-export-filter-quote-block-functions nil
2661 "List of functions applied to a transcoded quote block.
2662 Each filter is called with three arguments: the transcoded quote
2663 data, as a string, the back-end, as a symbol, and the
2664 communication channel, as a plist. It must return a string or
2665 nil.")
2667 (defvar org-export-filter-section-functions nil
2668 "List of functions applied to a transcoded section.
2669 Each filter is called with three arguments: the transcoded data,
2670 as a string, the back-end, as a symbol, and the communication
2671 channel, as a plist. It must return a string or nil.")
2673 (defvar org-export-filter-special-block-functions nil
2674 "List of functions applied to a transcoded special block.
2675 Each filter is called with three arguments: the transcoded data,
2676 as a string, the back-end, as a symbol, and the communication
2677 channel, as a plist. It must return a string or nil.")
2679 (defvar org-export-filter-src-block-functions nil
2680 "List of functions applied to a transcoded src-block.
2681 Each filter is called with three arguments: the transcoded data,
2682 as a string, the back-end, as a symbol, and the communication
2683 channel, as a plist. It must return a string or nil.")
2685 (defvar org-export-filter-table-functions nil
2686 "List of functions applied to a transcoded table.
2687 Each filter is called with three arguments: the transcoded data,
2688 as a string, the back-end, as a symbol, and the communication
2689 channel, as a plist. It must return a string or nil.")
2691 (defvar org-export-filter-table-cell-functions nil
2692 "List of functions applied to a transcoded table-cell.
2693 Each filter is called with three arguments: the transcoded data,
2694 as a string, the back-end, as a symbol, and the communication
2695 channel, as a plist. It must return a string or nil.")
2697 (defvar org-export-filter-table-row-functions nil
2698 "List of functions applied to a transcoded table-row.
2699 Each filter is called with three arguments: the transcoded data,
2700 as a string, the back-end, as a symbol, and the communication
2701 channel, as a plist. It must return a string or nil.")
2703 (defvar org-export-filter-verse-block-functions nil
2704 "List of functions applied to a transcoded verse block.
2705 Each filter is called with three arguments: the transcoded data,
2706 as a string, the back-end, as a symbol, and the communication
2707 channel, as a plist. It must return a string or nil.")
2710 ;;;; Objects Filters
2712 (defvar org-export-filter-bold-functions nil
2713 "List of functions applied to transcoded bold text.
2714 Each filter is called with three arguments: the transcoded data,
2715 as a string, the back-end, as a symbol, and the communication
2716 channel, as a plist. It must return a string or nil.")
2718 (defvar org-export-filter-code-functions nil
2719 "List of functions applied to transcoded code text.
2720 Each filter is called with three arguments: the transcoded data,
2721 as a string, the back-end, as a symbol, and the communication
2722 channel, as a plist. It must return a string or nil.")
2724 (defvar org-export-filter-entity-functions nil
2725 "List of functions applied to a transcoded entity.
2726 Each filter is called with three arguments: the transcoded data,
2727 as a string, the back-end, as a symbol, and the communication
2728 channel, as a plist. It must return a string or nil.")
2730 (defvar org-export-filter-export-snippet-functions nil
2731 "List of functions applied to a transcoded export-snippet.
2732 Each filter is called with three arguments: the transcoded data,
2733 as a string, the back-end, as a symbol, and the communication
2734 channel, as a plist. It must return a string or nil.")
2736 (defvar org-export-filter-footnote-reference-functions nil
2737 "List of functions applied to a transcoded footnote-reference.
2738 Each filter is called with three arguments: the transcoded data,
2739 as a string, the back-end, as a symbol, and the communication
2740 channel, as a plist. It must return a string or nil.")
2742 (defvar org-export-filter-inline-babel-call-functions nil
2743 "List of functions applied to a transcoded inline-babel-call.
2744 Each filter is called with three arguments: the transcoded data,
2745 as a string, the back-end, as a symbol, and the communication
2746 channel, as a plist. It must return a string or nil.")
2748 (defvar org-export-filter-inline-src-block-functions nil
2749 "List of functions applied to a transcoded inline-src-block.
2750 Each filter is called with three arguments: the transcoded data,
2751 as a string, the back-end, as a symbol, and the communication
2752 channel, as a plist. It must return a string or nil.")
2754 (defvar org-export-filter-italic-functions nil
2755 "List of functions applied to transcoded italic text.
2756 Each filter is called with three arguments: the transcoded data,
2757 as a string, the back-end, as a symbol, and the communication
2758 channel, as a plist. It must return a string or nil.")
2760 (defvar org-export-filter-latex-fragment-functions nil
2761 "List of functions applied to a transcoded latex-fragment.
2762 Each filter is called with three arguments: the transcoded data,
2763 as a string, the back-end, as a symbol, and the communication
2764 channel, as a plist. It must return a string or nil.")
2766 (defvar org-export-filter-line-break-functions nil
2767 "List of functions applied to a transcoded line-break.
2768 Each filter is called with three arguments: the transcoded data,
2769 as a string, the back-end, as a symbol, and the communication
2770 channel, as a plist. It must return a string or nil.")
2772 (defvar org-export-filter-link-functions nil
2773 "List of functions applied to a transcoded link.
2774 Each filter is called with three arguments: the transcoded data,
2775 as a string, the back-end, as a symbol, and the communication
2776 channel, as a plist. It must return a string or nil.")
2778 (defvar org-export-filter-radio-target-functions nil
2779 "List of functions applied to a transcoded radio-target.
2780 Each filter is called with three arguments: the transcoded data,
2781 as a string, the back-end, as a symbol, and the communication
2782 channel, as a plist. It must return a string or nil.")
2784 (defvar org-export-filter-statistics-cookie-functions nil
2785 "List of functions applied to a transcoded statistics-cookie.
2786 Each filter is called with three arguments: the transcoded data,
2787 as a string, the back-end, as a symbol, and the communication
2788 channel, as a plist. It must return a string or nil.")
2790 (defvar org-export-filter-strike-through-functions nil
2791 "List of functions applied to transcoded strike-through text.
2792 Each filter is called with three arguments: the transcoded data,
2793 as a string, the back-end, as a symbol, and the communication
2794 channel, as a plist. It must return a string or nil.")
2796 (defvar org-export-filter-subscript-functions nil
2797 "List of functions applied to a transcoded subscript.
2798 Each filter is called with three arguments: the transcoded data,
2799 as a string, the back-end, as a symbol, and the communication
2800 channel, as a plist. It must return a string or nil.")
2802 (defvar org-export-filter-superscript-functions nil
2803 "List of functions applied to a transcoded superscript.
2804 Each filter is called with three arguments: the transcoded data,
2805 as a string, the back-end, as a symbol, and the communication
2806 channel, as a plist. It must return a string or nil.")
2808 (defvar org-export-filter-target-functions nil
2809 "List of functions applied to a transcoded target.
2810 Each filter is called with three arguments: the transcoded data,
2811 as a string, the back-end, as a symbol, and the communication
2812 channel, as a plist. It must return a string or nil.")
2814 (defvar org-export-filter-timestamp-functions nil
2815 "List of functions applied to a transcoded timestamp.
2816 Each filter is called with three arguments: the transcoded data,
2817 as a string, the back-end, as a symbol, and the communication
2818 channel, as a plist. It must return a string or nil.")
2820 (defvar org-export-filter-underline-functions nil
2821 "List of functions applied to transcoded underline text.
2822 Each filter is called with three arguments: the transcoded data,
2823 as a string, the back-end, as a symbol, and the communication
2824 channel, as a plist. It must return a string or nil.")
2826 (defvar org-export-filter-verbatim-functions nil
2827 "List of functions applied to transcoded verbatim text.
2828 Each filter is called with three arguments: the transcoded data,
2829 as a string, the back-end, as a symbol, and the communication
2830 channel, as a plist. It must return a string or nil.")
2833 ;;;; Filters Tools
2835 ;; Internal function `org-export-install-filters' installs filters
2836 ;; hard-coded in back-ends (developer filters) and filters from global
2837 ;; variables (user filters) in the communication channel.
2839 ;; Internal function `org-export-filter-apply-functions' takes care
2840 ;; about applying each filter in order to a given data. It ignores
2841 ;; filters returning a nil value but stops whenever a filter returns
2842 ;; an empty string.
2844 (defun org-export-filter-apply-functions (filters value info)
2845 "Call every function in FILTERS.
2847 Functions are called with arguments VALUE, current export
2848 back-end's name and INFO. A function returning a nil value will
2849 be skipped. If it returns the empty string, the process ends and
2850 VALUE is ignored.
2852 Call is done in a LIFO fashion, to be sure that developer
2853 specified filters, if any, are called first."
2854 (catch 'exit
2855 (let* ((backend (plist-get info :back-end))
2856 (backend-name (and backend (org-export-backend-name backend))))
2857 (dolist (filter filters value)
2858 (let ((result (funcall filter value backend-name info)))
2859 (cond ((not result) value)
2860 ((equal value "") (throw 'exit nil))
2861 (t (setq value result))))))))
2863 (defun org-export-install-filters (info)
2864 "Install filters properties in communication channel.
2865 INFO is a plist containing the current communication channel.
2866 Return the updated communication channel."
2867 (let (plist)
2868 ;; Install user-defined filters with `org-export-filters-alist'
2869 ;; and filters already in INFO (through ext-plist mechanism).
2870 (mapc (lambda (p)
2871 (let* ((prop (car p))
2872 (info-value (plist-get info prop))
2873 (default-value (symbol-value (cdr p))))
2874 (setq plist
2875 (plist-put plist prop
2876 ;; Filters in INFO will be called
2877 ;; before those user provided.
2878 (append (if (listp info-value) info-value
2879 (list info-value))
2880 default-value)))))
2881 org-export-filters-alist)
2882 ;; Prepend back-end specific filters to that list.
2883 (mapc (lambda (p)
2884 ;; Single values get consed, lists are appended.
2885 (let ((key (car p)) (value (cdr p)))
2886 (when value
2887 (setq plist
2888 (plist-put
2889 plist key
2890 (if (atom value) (cons value (plist-get plist key))
2891 (append value (plist-get plist key))))))))
2892 (org-export-get-all-filters (plist-get info :back-end)))
2893 ;; Return new communication channel.
2894 (org-combine-plists info plist)))
2898 ;;; Core functions
2900 ;; This is the room for the main function, `org-export-as', along with
2901 ;; its derivative, `org-export-string-as'.
2902 ;; `org-export--copy-to-kill-ring-p' determines if output of these
2903 ;; function should be added to kill ring.
2905 ;; Note that `org-export-as' doesn't really parse the current buffer,
2906 ;; but a copy of it (with the same buffer-local variables and
2907 ;; visibility), where macros and include keywords are expanded and
2908 ;; Babel blocks are executed, if appropriate.
2909 ;; `org-export-with-buffer-copy' macro prepares that copy.
2911 ;; File inclusion is taken care of by
2912 ;; `org-export-expand-include-keyword' and
2913 ;; `org-export--prepare-file-contents'. Structure wise, including
2914 ;; a whole Org file in a buffer often makes little sense. For
2915 ;; example, if the file contains a headline and the include keyword
2916 ;; was within an item, the item should contain the headline. That's
2917 ;; why file inclusion should be done before any structure can be
2918 ;; associated to the file, that is before parsing.
2920 ;; `org-export-insert-default-template' is a command to insert
2921 ;; a default template (or a back-end specific template) at point or in
2922 ;; current subtree.
2924 (defun org-export-copy-buffer ()
2925 "Return a copy of the current buffer.
2926 The copy preserves Org buffer-local variables, visibility and
2927 narrowing."
2928 (let ((copy-buffer-fun (org-export--generate-copy-script (current-buffer)))
2929 (new-buf (generate-new-buffer (buffer-name))))
2930 (with-current-buffer new-buf
2931 (funcall copy-buffer-fun)
2932 (set-buffer-modified-p nil))
2933 new-buf))
2935 (defmacro org-export-with-buffer-copy (&rest body)
2936 "Apply BODY in a copy of the current buffer.
2937 The copy preserves local variables, visibility and contents of
2938 the original buffer. Point is at the beginning of the buffer
2939 when BODY is applied."
2940 (declare (debug t))
2941 (org-with-gensyms (buf-copy)
2942 `(let ((,buf-copy (org-export-copy-buffer)))
2943 (unwind-protect
2944 (with-current-buffer ,buf-copy
2945 (goto-char (point-min))
2946 (progn ,@body))
2947 (and (buffer-live-p ,buf-copy)
2948 ;; Kill copy without confirmation.
2949 (progn (with-current-buffer ,buf-copy
2950 (restore-buffer-modified-p nil))
2951 (kill-buffer ,buf-copy)))))))
2953 (defun org-export--generate-copy-script (buffer)
2954 "Generate a function duplicating BUFFER.
2956 The copy will preserve local variables, visibility, contents and
2957 narrowing of the original buffer. If a region was active in
2958 BUFFER, contents will be narrowed to that region instead.
2960 The resulting function can be evaluated at a later time, from
2961 another buffer, effectively cloning the original buffer there.
2963 The function assumes BUFFER's major mode is `org-mode'."
2964 (with-current-buffer buffer
2965 `(lambda ()
2966 (let ((inhibit-modification-hooks t))
2967 ;; Set major mode. Ignore `org-mode-hook' as it has been run
2968 ;; already in BUFFER.
2969 (let ((org-mode-hook nil) (org-inhibit-startup t)) (org-mode))
2970 ;; Copy specific buffer local variables and variables set
2971 ;; through BIND keywords.
2972 ,@(let ((bound-variables (org-export--list-bound-variables))
2973 vars)
2974 (dolist (entry (buffer-local-variables (buffer-base-buffer)) vars)
2975 (when (consp entry)
2976 (let ((var (car entry))
2977 (val (cdr entry)))
2978 (and (not (memq var org-export-ignored-local-variables))
2979 (or (memq var
2980 '(default-directory
2981 buffer-file-name
2982 buffer-file-coding-system))
2983 (assq var bound-variables)
2984 (string-match "^\\(org-\\|orgtbl-\\)"
2985 (symbol-name var)))
2986 ;; Skip unreadable values, as they cannot be
2987 ;; sent to external process.
2988 (or (not val) (ignore-errors (read (format "%S" val))))
2989 (push `(set (make-local-variable (quote ,var))
2990 (quote ,val))
2991 vars))))))
2992 ;; Whole buffer contents.
2993 (insert
2994 ,(org-with-wide-buffer
2995 (buffer-substring-no-properties
2996 (point-min) (point-max))))
2997 ;; Narrowing.
2998 ,(if (org-region-active-p)
2999 `(narrow-to-region ,(region-beginning) ,(region-end))
3000 `(narrow-to-region ,(point-min) ,(point-max)))
3001 ;; Current position of point.
3002 (goto-char ,(point))
3003 ;; Overlays with invisible property.
3004 ,@(let (ov-set)
3005 (mapc
3006 (lambda (ov)
3007 (let ((invis-prop (overlay-get ov 'invisible)))
3008 (when invis-prop
3009 (push `(overlay-put
3010 (make-overlay ,(overlay-start ov)
3011 ,(overlay-end ov))
3012 'invisible (quote ,invis-prop))
3013 ov-set))))
3014 (overlays-in (point-min) (point-max)))
3015 ov-set)))))
3017 ;;;###autoload
3018 (defun org-export-as
3019 (backend &optional subtreep visible-only body-only ext-plist)
3020 "Transcode current Org buffer into BACKEND code.
3022 BACKEND is either an export back-end, as returned by, e.g.,
3023 `org-export-create-backend', or a symbol referring to
3024 a registered back-end.
3026 If narrowing is active in the current buffer, only transcode its
3027 narrowed part.
3029 If a region is active, transcode that region.
3031 When optional argument SUBTREEP is non-nil, transcode the
3032 sub-tree at point, extracting information from the headline
3033 properties first.
3035 When optional argument VISIBLE-ONLY is non-nil, don't export
3036 contents of hidden elements.
3038 When optional argument BODY-ONLY is non-nil, only return body
3039 code, without surrounding template.
3041 Optional argument EXT-PLIST, when provided, is a property list
3042 with external parameters overriding Org default settings, but
3043 still inferior to file-local settings.
3045 Return code as a string."
3046 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
3047 (org-export-barf-if-invalid-backend backend)
3048 (save-excursion
3049 (save-restriction
3050 ;; Narrow buffer to an appropriate region or subtree for
3051 ;; parsing. If parsing subtree, be sure to remove main headline
3052 ;; too.
3053 (cond ((org-region-active-p)
3054 (narrow-to-region (region-beginning) (region-end)))
3055 (subtreep
3056 (org-narrow-to-subtree)
3057 (goto-char (point-min))
3058 (forward-line)
3059 (narrow-to-region (point) (point-max))))
3060 ;; Initialize communication channel with original buffer
3061 ;; attributes, unavailable in its copy.
3062 (let* ((org-export-current-backend (org-export-backend-name backend))
3063 (info (org-combine-plists
3064 (list :export-options
3065 (delq nil
3066 (list (and subtreep 'subtree)
3067 (and visible-only 'visible-only)
3068 (and body-only 'body-only))))
3069 (org-export--get-buffer-attributes)))
3070 tree)
3071 ;; Update communication channel and get parse tree. Buffer
3072 ;; isn't parsed directly. Instead, a temporary copy is
3073 ;; created, where include keywords, macros are expanded and
3074 ;; code blocks are evaluated.
3075 (org-export-with-buffer-copy
3076 ;; Run first hook with current back-end's name as argument.
3077 (run-hook-with-args 'org-export-before-processing-hook
3078 (org-export-backend-name backend))
3079 (org-export-expand-include-keyword)
3080 ;; Update macro templates since #+INCLUDE keywords might have
3081 ;; added some new ones.
3082 (org-macro-initialize-templates)
3083 (org-macro-replace-all org-macro-templates)
3084 (org-export-execute-babel-code)
3085 ;; Update radio targets since keyword inclusion might have
3086 ;; added some more.
3087 (org-update-radio-target-regexp)
3088 ;; Run last hook with current back-end's name as argument.
3089 (goto-char (point-min))
3090 (save-excursion
3091 (run-hook-with-args 'org-export-before-parsing-hook
3092 (org-export-backend-name backend)))
3093 ;; Update communication channel with environment. Also
3094 ;; install user's and developer's filters.
3095 (setq info
3096 (org-export-install-filters
3097 (org-combine-plists
3098 info (org-export-get-environment backend subtreep ext-plist))))
3099 ;; Expand export-specific set of macros: {{{author}}},
3100 ;; {{{date}}}, {{{email}}} and {{{title}}}. It must be done
3101 ;; once regular macros have been expanded, since document
3102 ;; keywords may contain one of them.
3103 (org-macro-replace-all
3104 (list (cons "author"
3105 (org-element-interpret-data (plist-get info :author)))
3106 (cons "date"
3107 (org-element-interpret-data (plist-get info :date)))
3108 ;; EMAIL is not a parsed keyword: store it as-is.
3109 (cons "email" (or (plist-get info :email) ""))
3110 (cons "title"
3111 (org-element-interpret-data (plist-get info :title)))))
3112 ;; Parse buffer.
3113 (setq tree (org-element-parse-buffer nil visible-only))
3114 ;; Handle left-over uninterpreted elements or objects in
3115 ;; parse tree and communication channel.
3116 (org-export-remove-uninterpreted-data tree info)
3117 ;; Call options filters and update export options. We do not
3118 ;; use `org-export-filter-apply-functions' here since the
3119 ;; arity of such filters is different.
3120 (let ((backend-name (org-export-backend-name backend)))
3121 (dolist (filter (plist-get info :filter-options))
3122 (let ((result (funcall filter info backend-name)))
3123 (when result (setq info result)))))
3124 ;; Parse buffer, handle uninterpreted elements or objects,
3125 ;; then call parse-tree filters.
3126 (setq tree
3127 (org-export-filter-apply-functions
3128 (plist-get info :filter-parse-tree) tree info))
3129 ;; Now tree is complete, compute its properties and add them
3130 ;; to communication channel.
3131 (setq info
3132 (org-combine-plists
3133 info (org-export-collect-tree-properties tree info)))
3134 ;; Eventually transcode TREE. Wrap the resulting string into
3135 ;; a template.
3136 (let* ((body (org-element-normalize-string
3137 (or (org-export-data tree info) "")))
3138 (inner-template (cdr (assq 'inner-template
3139 (plist-get info :translate-alist))))
3140 (full-body (if (not (functionp inner-template)) body
3141 (funcall inner-template body info)))
3142 (template (cdr (assq 'template
3143 (plist-get info :translate-alist)))))
3144 ;; Remove all text properties since they cannot be
3145 ;; retrieved from an external process. Finally call
3146 ;; final-output filter and return result.
3147 (org-no-properties
3148 (org-export-filter-apply-functions
3149 (plist-get info :filter-final-output)
3150 (if (or (not (functionp template)) body-only) full-body
3151 (funcall template full-body info))
3152 info))))))))
3154 ;;;###autoload
3155 (defun org-export-string-as (string backend &optional body-only ext-plist)
3156 "Transcode STRING into BACKEND code.
3158 BACKEND is either an export back-end, as returned by, e.g.,
3159 `org-export-create-backend', or a symbol referring to
3160 a registered back-end.
3162 When optional argument BODY-ONLY is non-nil, only return body
3163 code, without preamble nor postamble.
3165 Optional argument EXT-PLIST, when provided, is a property list
3166 with external parameters overriding Org default settings, but
3167 still inferior to file-local settings.
3169 Return code as a string."
3170 (with-temp-buffer
3171 (insert string)
3172 (let ((org-inhibit-startup t)) (org-mode))
3173 (org-export-as backend nil nil body-only ext-plist)))
3175 ;;;###autoload
3176 (defun org-export-replace-region-by (backend)
3177 "Replace the active region by its export to BACKEND.
3178 BACKEND is either an export back-end, as returned by, e.g.,
3179 `org-export-create-backend', or a symbol referring to
3180 a registered back-end."
3181 (if (not (org-region-active-p))
3182 (user-error "No active region to replace")
3183 (let* ((beg (region-beginning))
3184 (end (region-end))
3185 (str (buffer-substring beg end)) rpl)
3186 (setq rpl (org-export-string-as str backend t))
3187 (delete-region beg end)
3188 (insert rpl))))
3190 ;;;###autoload
3191 (defun org-export-insert-default-template (&optional backend subtreep)
3192 "Insert all export keywords with default values at beginning of line.
3194 BACKEND is a symbol referring to the name of a registered export
3195 back-end, for which specific export options should be added to
3196 the template, or `default' for default template. When it is nil,
3197 the user will be prompted for a category.
3199 If SUBTREEP is non-nil, export configuration will be set up
3200 locally for the subtree through node properties."
3201 (interactive)
3202 (unless (derived-mode-p 'org-mode) (user-error "Not in an Org mode buffer"))
3203 (when (and subtreep (org-before-first-heading-p))
3204 (user-error "No subtree to set export options for"))
3205 (let ((node (and subtreep (save-excursion (org-back-to-heading t) (point))))
3206 (backend
3207 (or backend
3208 (intern
3209 (org-completing-read
3210 "Options category: "
3211 (cons "default"
3212 (mapcar #'(lambda (b)
3213 (symbol-name (org-export-backend-name b)))
3214 org-export--registered-backends))
3215 nil t))))
3216 options keywords)
3217 ;; Populate OPTIONS and KEYWORDS.
3218 (dolist (entry (cond ((eq backend 'default) org-export-options-alist)
3219 ((org-export-backend-p backend)
3220 (org-export-backend-options backend))
3221 (t (org-export-backend-options
3222 (org-export-get-backend backend)))))
3223 (let ((keyword (nth 1 entry))
3224 (option (nth 2 entry)))
3225 (cond
3226 (keyword (unless (assoc keyword keywords)
3227 (let ((value
3228 (if (eq (nth 4 entry) 'split)
3229 (mapconcat #'identity (eval (nth 3 entry)) " ")
3230 (eval (nth 3 entry)))))
3231 (push (cons keyword value) keywords))))
3232 (option (unless (assoc option options)
3233 (push (cons option (eval (nth 3 entry))) options))))))
3234 ;; Move to an appropriate location in order to insert options.
3235 (unless subtreep (beginning-of-line))
3236 ;; First (multiple) OPTIONS lines. Never go past fill-column.
3237 (when options
3238 (let ((items
3239 (mapcar
3240 #'(lambda (opt) (format "%s:%S" (car opt) (cdr opt)))
3241 (sort options (lambda (k1 k2) (string< (car k1) (car k2)))))))
3242 (if subtreep
3243 (org-entry-put
3244 node "EXPORT_OPTIONS" (mapconcat 'identity items " "))
3245 (while items
3246 (insert "#+OPTIONS:")
3247 (let ((width 10))
3248 (while (and items
3249 (< (+ width (length (car items)) 1) fill-column))
3250 (let ((item (pop items)))
3251 (insert " " item)
3252 (incf width (1+ (length item))))))
3253 (insert "\n")))))
3254 ;; Then the rest of keywords, in the order specified in either
3255 ;; `org-export-options-alist' or respective export back-ends.
3256 (dolist (key (nreverse keywords))
3257 (let ((val (cond ((equal (car key) "DATE")
3258 (or (cdr key)
3259 (with-temp-buffer
3260 (org-insert-time-stamp (current-time)))))
3261 ((equal (car key) "TITLE")
3262 (or (let ((visited-file
3263 (buffer-file-name (buffer-base-buffer))))
3264 (and visited-file
3265 (file-name-sans-extension
3266 (file-name-nondirectory visited-file))))
3267 (buffer-name (buffer-base-buffer))))
3268 (t (cdr key)))))
3269 (if subtreep (org-entry-put node (concat "EXPORT_" (car key)) val)
3270 (insert
3271 (format "#+%s:%s\n"
3272 (car key)
3273 (if (org-string-nw-p val) (format " %s" val) ""))))))))
3275 (defun org-export-expand-include-keyword (&optional included dir)
3276 "Expand every include keyword in buffer.
3277 Optional argument INCLUDED is a list of included file names along
3278 with their line restriction, when appropriate. It is used to
3279 avoid infinite recursion. Optional argument DIR is the current
3280 working directory. It is used to properly resolve relative
3281 paths."
3282 (let ((case-fold-search t))
3283 (goto-char (point-min))
3284 (while (re-search-forward "^[ \t]*#\\+INCLUDE:" nil t)
3285 (let ((element (save-match-data (org-element-at-point))))
3286 (when (eq (org-element-type element) 'keyword)
3287 (beginning-of-line)
3288 ;; Extract arguments from keyword's value.
3289 (let* ((value (org-element-property :value element))
3290 (ind (org-get-indentation))
3291 (file (and (string-match
3292 "^\\(\".+?\"\\|\\S-+\\)\\(?:\\s-+\\|$\\)" value)
3293 (prog1 (expand-file-name
3294 (org-remove-double-quotes
3295 (match-string 1 value))
3296 dir)
3297 (setq value (replace-match "" nil nil value)))))
3298 (lines
3299 (and (string-match
3300 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\""
3301 value)
3302 (prog1 (match-string 1 value)
3303 (setq value (replace-match "" nil nil value)))))
3304 (env (cond ((string-match "\\<example\\>" value) 'example)
3305 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
3306 (match-string 1 value))))
3307 ;; Minimal level of included file defaults to the child
3308 ;; level of the current headline, if any, or one. It
3309 ;; only applies is the file is meant to be included as
3310 ;; an Org one.
3311 (minlevel
3312 (and (not env)
3313 (if (string-match ":minlevel +\\([0-9]+\\)" value)
3314 (prog1 (string-to-number (match-string 1 value))
3315 (setq value (replace-match "" nil nil value)))
3316 (let ((cur (org-current-level)))
3317 (if cur (1+ (org-reduced-level cur)) 1))))))
3318 ;; Remove keyword.
3319 (delete-region (point) (progn (forward-line) (point)))
3320 (cond
3321 ((not file) nil)
3322 ((not (file-readable-p file))
3323 (error "Cannot include file %s" file))
3324 ;; Check if files has already been parsed. Look after
3325 ;; inclusion lines too, as different parts of the same file
3326 ;; can be included too.
3327 ((member (list file lines) included)
3328 (error "Recursive file inclusion: %s" file))
3330 (cond
3331 ((eq env 'example)
3332 (insert
3333 (let ((ind-str (make-string ind ? ))
3334 (contents
3335 (org-escape-code-in-string
3336 (org-export--prepare-file-contents file lines))))
3337 (format "%s#+BEGIN_EXAMPLE\n%s%s#+END_EXAMPLE\n"
3338 ind-str contents ind-str))))
3339 ((stringp env)
3340 (insert
3341 (let ((ind-str (make-string ind ? ))
3342 (contents
3343 (org-escape-code-in-string
3344 (org-export--prepare-file-contents file lines))))
3345 (format "%s#+BEGIN_SRC %s\n%s%s#+END_SRC\n"
3346 ind-str env contents ind-str))))
3348 (insert
3349 (with-temp-buffer
3350 (let ((org-inhibit-startup t)) (org-mode))
3351 (insert
3352 (org-export--prepare-file-contents file lines ind minlevel))
3353 (org-export-expand-include-keyword
3354 (cons (list file lines) included)
3355 (file-name-directory file))
3356 (buffer-string)))))))))))))
3358 (defun org-export--prepare-file-contents (file &optional lines ind minlevel)
3359 "Prepare the contents of FILE for inclusion and return them as a string.
3361 When optional argument LINES is a string specifying a range of
3362 lines, include only those lines.
3364 Optional argument IND, when non-nil, is an integer specifying the
3365 global indentation of returned contents. Since its purpose is to
3366 allow an included file to stay in the same environment it was
3367 created \(i.e. a list item), it doesn't apply past the first
3368 headline encountered.
3370 Optional argument MINLEVEL, when non-nil, is an integer
3371 specifying the level that any top-level headline in the included
3372 file should have."
3373 (with-temp-buffer
3374 (insert-file-contents file)
3375 (when lines
3376 (let* ((lines (split-string lines "-"))
3377 (lbeg (string-to-number (car lines)))
3378 (lend (string-to-number (cadr lines)))
3379 (beg (if (zerop lbeg) (point-min)
3380 (goto-char (point-min))
3381 (forward-line (1- lbeg))
3382 (point)))
3383 (end (if (zerop lend) (point-max)
3384 (goto-char (point-min))
3385 (forward-line (1- lend))
3386 (point))))
3387 (narrow-to-region beg end)))
3388 ;; Remove blank lines at beginning and end of contents. The logic
3389 ;; behind that removal is that blank lines around include keyword
3390 ;; override blank lines in included file.
3391 (goto-char (point-min))
3392 (org-skip-whitespace)
3393 (beginning-of-line)
3394 (delete-region (point-min) (point))
3395 (goto-char (point-max))
3396 (skip-chars-backward " \r\t\n")
3397 (forward-line)
3398 (delete-region (point) (point-max))
3399 ;; If IND is set, preserve indentation of include keyword until
3400 ;; the first headline encountered.
3401 (when ind
3402 (unless (eq major-mode 'org-mode)
3403 (let ((org-inhibit-startup t)) (org-mode)))
3404 (goto-char (point-min))
3405 (let ((ind-str (make-string ind ? )))
3406 (while (not (or (eobp) (looking-at org-outline-regexp-bol)))
3407 ;; Do not move footnote definitions out of column 0.
3408 (unless (and (looking-at org-footnote-definition-re)
3409 (eq (org-element-type (org-element-at-point))
3410 'footnote-definition))
3411 (insert ind-str))
3412 (forward-line))))
3413 ;; When MINLEVEL is specified, compute minimal level for headlines
3414 ;; in the file (CUR-MIN), and remove stars to each headline so
3415 ;; that headlines with minimal level have a level of MINLEVEL.
3416 (when minlevel
3417 (unless (eq major-mode 'org-mode)
3418 (let ((org-inhibit-startup t)) (org-mode)))
3419 (org-with-limited-levels
3420 (let ((levels (org-map-entries
3421 (lambda () (org-reduced-level (org-current-level))))))
3422 (when levels
3423 (let ((offset (- minlevel (apply 'min levels))))
3424 (unless (zerop offset)
3425 (when org-odd-levels-only (setq offset (* offset 2)))
3426 ;; Only change stars, don't bother moving whole
3427 ;; sections.
3428 (org-map-entries
3429 (lambda () (if (< offset 0) (delete-char (abs offset))
3430 (insert (make-string offset ?*)))))))))))
3431 (org-element-normalize-string (buffer-string))))
3433 (defun org-export-execute-babel-code ()
3434 "Execute every Babel code in the visible part of current buffer."
3435 ;; Get a pristine copy of current buffer so Babel references can be
3436 ;; properly resolved.
3437 (let ((reference (org-export-copy-buffer)))
3438 (unwind-protect (org-babel-exp-process-buffer reference)
3439 (kill-buffer reference))))
3441 (defun org-export--copy-to-kill-ring-p ()
3442 "Return a non-nil value when output should be added to the kill ring.
3443 See also `org-export-copy-to-kill-ring'."
3444 (if (eq org-export-copy-to-kill-ring 'if-interactive)
3445 (not (or executing-kbd-macro noninteractive))
3446 (eq org-export-copy-to-kill-ring t)))
3450 ;;; Tools For Back-Ends
3452 ;; A whole set of tools is available to help build new exporters. Any
3453 ;; function general enough to have its use across many back-ends
3454 ;; should be added here.
3456 ;;;; For Affiliated Keywords
3458 ;; `org-export-read-attribute' reads a property from a given element
3459 ;; as a plist. It can be used to normalize affiliated keywords'
3460 ;; syntax.
3462 ;; Since captions can span over multiple lines and accept dual values,
3463 ;; their internal representation is a bit tricky. Therefore,
3464 ;; `org-export-get-caption' transparently returns a given element's
3465 ;; caption as a secondary string.
3467 (defun org-export-read-attribute (attribute element &optional property)
3468 "Turn ATTRIBUTE property from ELEMENT into a plist.
3470 When optional argument PROPERTY is non-nil, return the value of
3471 that property within attributes.
3473 This function assumes attributes are defined as \":keyword
3474 value\" pairs. It is appropriate for `:attr_html' like
3475 properties.
3477 All values will become strings except the empty string and
3478 \"nil\", which will become nil. Also, values containing only
3479 double quotes will be read as-is, which means that \"\" value
3480 will become the empty string."
3481 (let* ((prepare-value
3482 (lambda (str)
3483 (save-match-data
3484 (cond ((member str '(nil "" "nil")) nil)
3485 ((string-match "^\"\\(\"+\\)?\"$" str)
3486 (or (match-string 1 str) ""))
3487 (t str)))))
3488 (attributes
3489 (let ((value (org-element-property attribute element)))
3490 (when value
3491 (let ((s (mapconcat 'identity value " ")) result)
3492 (while (string-match
3493 "\\(?:^\\|[ \t]+\\)\\(:[-a-zA-Z0-9_]+\\)\\([ \t]+\\|$\\)"
3495 (let ((value (substring s 0 (match-beginning 0))))
3496 (push (funcall prepare-value value) result))
3497 (push (intern (match-string 1 s)) result)
3498 (setq s (substring s (match-end 0))))
3499 ;; Ignore any string before first property with `cdr'.
3500 (cdr (nreverse (cons (funcall prepare-value s) result))))))))
3501 (if property (plist-get attributes property) attributes)))
3503 (defun org-export-get-caption (element &optional shortp)
3504 "Return caption from ELEMENT as a secondary string.
3506 When optional argument SHORTP is non-nil, return short caption,
3507 as a secondary string, instead.
3509 Caption lines are separated by a white space."
3510 (let ((full-caption (org-element-property :caption element)) caption)
3511 (dolist (line full-caption (cdr caption))
3512 (let ((cap (funcall (if shortp 'cdr 'car) line)))
3513 (when cap
3514 (setq caption (nconc (list " ") (copy-sequence cap) caption)))))))
3517 ;;;; For Derived Back-ends
3519 ;; `org-export-with-backend' is a function allowing to locally use
3520 ;; another back-end to transcode some object or element. In a derived
3521 ;; back-end, it may be used as a fall-back function once all specific
3522 ;; cases have been treated.
3524 (defun org-export-with-backend (backend data &optional contents info)
3525 "Call a transcoder from BACKEND on DATA.
3526 BACKEND is an export back-end, as returned by, e.g.,
3527 `org-export-create-backend', or a symbol referring to
3528 a registered back-end. DATA is an Org element, object, secondary
3529 string or string. CONTENTS, when non-nil, is the transcoded
3530 contents of DATA element, as a string. INFO, when non-nil, is
3531 the communication channel used for export, as a plist."
3532 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
3533 (org-export-barf-if-invalid-backend backend)
3534 (let ((type (org-element-type data)))
3535 (if (memq type '(nil org-data)) (error "No foreign transcoder available")
3536 (let* ((all-transcoders (org-export-get-all-transcoders backend))
3537 (transcoder (cdr (assq type all-transcoders))))
3538 (if (not (functionp transcoder))
3539 (error "No foreign transcoder available")
3540 (funcall
3541 transcoder data contents
3542 (org-combine-plists
3543 info (list :back-end backend
3544 :translate-alist all-transcoders
3545 :exported-data (make-hash-table :test 'eq :size 401)))))))))
3548 ;;;; For Export Snippets
3550 ;; Every export snippet is transmitted to the back-end. Though, the
3551 ;; latter will only retain one type of export-snippet, ignoring
3552 ;; others, based on the former's target back-end. The function
3553 ;; `org-export-snippet-backend' returns that back-end for a given
3554 ;; export-snippet.
3556 (defun org-export-snippet-backend (export-snippet)
3557 "Return EXPORT-SNIPPET targeted back-end as a symbol.
3558 Translation, with `org-export-snippet-translation-alist', is
3559 applied."
3560 (let ((back-end (org-element-property :back-end export-snippet)))
3561 (intern
3562 (or (cdr (assoc back-end org-export-snippet-translation-alist))
3563 back-end))))
3566 ;;;; For Footnotes
3568 ;; `org-export-collect-footnote-definitions' is a tool to list
3569 ;; actually used footnotes definitions in the whole parse tree, or in
3570 ;; a headline, in order to add footnote listings throughout the
3571 ;; transcoded data.
3573 ;; `org-export-footnote-first-reference-p' is a predicate used by some
3574 ;; back-ends, when they need to attach the footnote definition only to
3575 ;; the first occurrence of the corresponding label.
3577 ;; `org-export-get-footnote-definition' and
3578 ;; `org-export-get-footnote-number' provide easier access to
3579 ;; additional information relative to a footnote reference.
3581 (defun org-export-collect-footnote-definitions (data info)
3582 "Return an alist between footnote numbers, labels and definitions.
3584 DATA is the parse tree from which definitions are collected.
3585 INFO is the plist used as a communication channel.
3587 Definitions are sorted by order of references. They either
3588 appear as Org data or as a secondary string for inlined
3589 footnotes. Unreferenced definitions are ignored."
3590 (let* (num-alist
3591 collect-fn ; for byte-compiler.
3592 (collect-fn
3593 (function
3594 (lambda (data)
3595 ;; Collect footnote number, label and definition in DATA.
3596 (org-element-map data 'footnote-reference
3597 (lambda (fn)
3598 (when (org-export-footnote-first-reference-p fn info)
3599 (let ((def (org-export-get-footnote-definition fn info)))
3600 (push
3601 (list (org-export-get-footnote-number fn info)
3602 (org-element-property :label fn)
3603 def)
3604 num-alist)
3605 ;; Also search in definition for nested footnotes.
3606 (when (eq (org-element-property :type fn) 'standard)
3607 (funcall collect-fn def)))))
3608 ;; Don't enter footnote definitions since it will happen
3609 ;; when their first reference is found.
3610 info nil 'footnote-definition)))))
3611 (funcall collect-fn (plist-get info :parse-tree))
3612 (reverse num-alist)))
3614 (defun org-export-footnote-first-reference-p (footnote-reference info)
3615 "Non-nil when a footnote reference is the first one for its label.
3617 FOOTNOTE-REFERENCE is the footnote reference being considered.
3618 INFO is the plist used as a communication channel."
3619 (let ((label (org-element-property :label footnote-reference)))
3620 ;; Anonymous footnotes are always a first reference.
3621 (if (not label) t
3622 ;; Otherwise, return the first footnote with the same LABEL and
3623 ;; test if it is equal to FOOTNOTE-REFERENCE.
3624 (let* (search-refs ; for byte-compiler.
3625 (search-refs
3626 (function
3627 (lambda (data)
3628 (org-element-map data 'footnote-reference
3629 (lambda (fn)
3630 (cond
3631 ((string= (org-element-property :label fn) label)
3632 (throw 'exit fn))
3633 ;; If FN isn't inlined, be sure to traverse its
3634 ;; definition before resuming search. See
3635 ;; comments in `org-export-get-footnote-number'
3636 ;; for more information.
3637 ((eq (org-element-property :type fn) 'standard)
3638 (funcall search-refs
3639 (org-export-get-footnote-definition fn info)))))
3640 ;; Don't enter footnote definitions since it will
3641 ;; happen when their first reference is found.
3642 info 'first-match 'footnote-definition)))))
3643 (eq (catch 'exit (funcall search-refs (plist-get info :parse-tree)))
3644 footnote-reference)))))
3646 (defun org-export-get-footnote-definition (footnote-reference info)
3647 "Return definition of FOOTNOTE-REFERENCE as parsed data.
3648 INFO is the plist used as a communication channel. If no such
3649 definition can be found, return the \"DEFINITION NOT FOUND\"
3650 string."
3651 (let ((label (org-element-property :label footnote-reference)))
3652 (or (org-element-property :inline-definition footnote-reference)
3653 (cdr (assoc label (plist-get info :footnote-definition-alist)))
3654 "DEFINITION NOT FOUND.")))
3656 (defun org-export-get-footnote-number (footnote info)
3657 "Return number associated to a footnote.
3659 FOOTNOTE is either a footnote reference or a footnote definition.
3660 INFO is the plist used as a communication channel."
3661 (let* ((label (org-element-property :label footnote))
3662 seen-refs
3663 search-ref ; For byte-compiler.
3664 (search-ref
3665 (function
3666 (lambda (data)
3667 ;; Search footnote references through DATA, filling
3668 ;; SEEN-REFS along the way.
3669 (org-element-map data 'footnote-reference
3670 (lambda (fn)
3671 (let ((fn-lbl (org-element-property :label fn)))
3672 (cond
3673 ;; Anonymous footnote match: return number.
3674 ((and (not fn-lbl) (eq fn footnote))
3675 (throw 'exit (1+ (length seen-refs))))
3676 ;; Labels match: return number.
3677 ((and label (string= label fn-lbl))
3678 (throw 'exit (1+ (length seen-refs))))
3679 ;; Anonymous footnote: it's always a new one.
3680 ;; Also, be sure to return nil from the `cond' so
3681 ;; `first-match' doesn't get us out of the loop.
3682 ((not fn-lbl) (push 'inline seen-refs) nil)
3683 ;; Label not seen so far: add it so SEEN-REFS.
3685 ;; Also search for subsequent references in
3686 ;; footnote definition so numbering follows
3687 ;; reading logic. Note that we don't have to care
3688 ;; about inline definitions, since
3689 ;; `org-element-map' already traverses them at the
3690 ;; right time.
3692 ;; Once again, return nil to stay in the loop.
3693 ((not (member fn-lbl seen-refs))
3694 (push fn-lbl seen-refs)
3695 (funcall search-ref
3696 (org-export-get-footnote-definition fn info))
3697 nil))))
3698 ;; Don't enter footnote definitions since it will
3699 ;; happen when their first reference is found.
3700 info 'first-match 'footnote-definition)))))
3701 (catch 'exit (funcall search-ref (plist-get info :parse-tree)))))
3704 ;;;; For Headlines
3706 ;; `org-export-get-relative-level' is a shortcut to get headline
3707 ;; level, relatively to the lower headline level in the parsed tree.
3709 ;; `org-export-get-headline-number' returns the section number of an
3710 ;; headline, while `org-export-number-to-roman' allows to convert it
3711 ;; to roman numbers.
3713 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
3714 ;; `org-export-last-sibling-p' are three useful predicates when it
3715 ;; comes to fulfill the `:headline-levels' property.
3717 ;; `org-export-get-tags', `org-export-get-category' and
3718 ;; `org-export-get-node-property' extract useful information from an
3719 ;; headline or a parent headline. They all handle inheritance.
3721 ;; `org-export-get-alt-title' tries to retrieve an alternative title,
3722 ;; as a secondary string, suitable for table of contents. It falls
3723 ;; back onto default title.
3725 (defun org-export-get-relative-level (headline info)
3726 "Return HEADLINE relative level within current parsed tree.
3727 INFO is a plist holding contextual information."
3728 (+ (org-element-property :level headline)
3729 (or (plist-get info :headline-offset) 0)))
3731 (defun org-export-low-level-p (headline info)
3732 "Non-nil when HEADLINE is considered as low level.
3734 INFO is a plist used as a communication channel.
3736 A low level headlines has a relative level greater than
3737 `:headline-levels' property value.
3739 Return value is the difference between HEADLINE relative level
3740 and the last level being considered as high enough, or nil."
3741 (let ((limit (plist-get info :headline-levels)))
3742 (when (wholenump limit)
3743 (let ((level (org-export-get-relative-level headline info)))
3744 (and (> level limit) (- level limit))))))
3746 (defun org-export-get-headline-number (headline info)
3747 "Return HEADLINE numbering as a list of numbers.
3748 INFO is a plist holding contextual information."
3749 (cdr (assoc headline (plist-get info :headline-numbering))))
3751 (defun org-export-numbered-headline-p (headline info)
3752 "Return a non-nil value if HEADLINE element should be numbered.
3753 INFO is a plist used as a communication channel."
3754 (let ((sec-num (plist-get info :section-numbers))
3755 (level (org-export-get-relative-level headline info)))
3756 (if (wholenump sec-num) (<= level sec-num) sec-num)))
3758 (defun org-export-number-to-roman (n)
3759 "Convert integer N into a roman numeral."
3760 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
3761 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
3762 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
3763 ( 1 . "I")))
3764 (res ""))
3765 (if (<= n 0)
3766 (number-to-string n)
3767 (while roman
3768 (if (>= n (caar roman))
3769 (setq n (- n (caar roman))
3770 res (concat res (cdar roman)))
3771 (pop roman)))
3772 res)))
3774 (defun org-export-get-tags (element info &optional tags inherited)
3775 "Return list of tags associated to ELEMENT.
3777 ELEMENT has either an `headline' or an `inlinetask' type. INFO
3778 is a plist used as a communication channel.
3780 Select tags (see `org-export-select-tags') and exclude tags (see
3781 `org-export-exclude-tags') are removed from the list.
3783 When non-nil, optional argument TAGS should be a list of strings.
3784 Any tag belonging to this list will also be removed.
3786 When optional argument INHERITED is non-nil, tags can also be
3787 inherited from parent headlines and FILETAGS keywords."
3788 (org-remove-if
3789 (lambda (tag) (or (member tag (plist-get info :select-tags))
3790 (member tag (plist-get info :exclude-tags))
3791 (member tag tags)))
3792 (if (not inherited) (org-element-property :tags element)
3793 ;; Build complete list of inherited tags.
3794 (let ((current-tag-list (org-element-property :tags element)))
3795 (mapc
3796 (lambda (parent)
3797 (mapc
3798 (lambda (tag)
3799 (when (and (memq (org-element-type parent) '(headline inlinetask))
3800 (not (member tag current-tag-list)))
3801 (push tag current-tag-list)))
3802 (org-element-property :tags parent)))
3803 (org-export-get-genealogy element))
3804 ;; Add FILETAGS keywords and return results.
3805 (org-uniquify (append (plist-get info :filetags) current-tag-list))))))
3807 (defun org-export-get-node-property (property blob &optional inherited)
3808 "Return node PROPERTY value for BLOB.
3810 PROPERTY is an upcase symbol (i.e. `:COOKIE_DATA'). BLOB is an
3811 element or object.
3813 If optional argument INHERITED is non-nil, the value can be
3814 inherited from a parent headline.
3816 Return value is a string or nil."
3817 (let ((headline (if (eq (org-element-type blob) 'headline) blob
3818 (org-export-get-parent-headline blob))))
3819 (if (not inherited) (org-element-property property blob)
3820 (let ((parent headline) value)
3821 (catch 'found
3822 (while parent
3823 (when (plist-member (nth 1 parent) property)
3824 (throw 'found (org-element-property property parent)))
3825 (setq parent (org-element-property :parent parent))))))))
3827 (defun org-export-get-category (blob info)
3828 "Return category for element or object BLOB.
3830 INFO is a plist used as a communication channel.
3832 CATEGORY is automatically inherited from a parent headline, from
3833 #+CATEGORY: keyword or created out of original file name. If all
3834 fail, the fall-back value is \"???\"."
3835 (or (let ((headline (if (eq (org-element-type blob) 'headline) blob
3836 (org-export-get-parent-headline blob))))
3837 ;; Almost like `org-export-node-property', but we cannot trust
3838 ;; `plist-member' as every headline has a `:CATEGORY'
3839 ;; property, would it be nil or equal to "???" (which has the
3840 ;; same meaning).
3841 (let ((parent headline) value)
3842 (catch 'found
3843 (while parent
3844 (let ((category (org-element-property :CATEGORY parent)))
3845 (and category (not (equal "???" category))
3846 (throw 'found category)))
3847 (setq parent (org-element-property :parent parent))))))
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 (or (org-element-property :alt-title headline)
3862 (org-element-property :title headline)))
3864 (defun org-export-first-sibling-p (headline info)
3865 "Non-nil when HEADLINE is the first sibling in its sub-tree.
3866 INFO is a plist used as a communication channel."
3867 (not (eq (org-element-type (org-export-get-previous-element headline info))
3868 'headline)))
3870 (defun org-export-last-sibling-p (headline info)
3871 "Non-nil when HEADLINE is the last sibling in its sub-tree.
3872 INFO is a plist used as a communication channel."
3873 (not (org-export-get-next-element headline info)))
3876 ;;;; For Keywords
3878 ;; `org-export-get-date' returns a date appropriate for the document
3879 ;; to about to be exported. In particular, it takes care of
3880 ;; `org-export-date-timestamp-format'.
3882 (defun org-export-get-date (info &optional fmt)
3883 "Return date value for the current document.
3885 INFO is a plist used as a communication channel. FMT, when
3886 non-nil, is a time format string that will be applied on the date
3887 if it consists in a single timestamp object. It defaults to
3888 `org-export-date-timestamp-format' when nil.
3890 A proper date can be a secondary string, a string or nil. It is
3891 meant to be translated with `org-export-data' or alike."
3892 (let ((date (plist-get info :date))
3893 (fmt (or fmt org-export-date-timestamp-format)))
3894 (cond ((not date) nil)
3895 ((and fmt
3896 (not (cdr date))
3897 (eq (org-element-type (car date)) 'timestamp))
3898 (org-timestamp-format (car date) fmt))
3899 (t date))))
3902 ;;;; For Links
3904 ;; `org-export-solidify-link-text' turns a string into a safer version
3905 ;; for links, replacing most non-standard characters with hyphens.
3907 ;; `org-export-get-coderef-format' returns an appropriate format
3908 ;; string for coderefs.
3910 ;; `org-export-inline-image-p' returns a non-nil value when the link
3911 ;; provided should be considered as an inline image.
3913 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
3914 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
3915 ;; returns an appropriate unique identifier when found, or nil.
3917 ;; `org-export-resolve-id-link' returns the first headline with
3918 ;; specified id or custom-id in parse tree, the path to the external
3919 ;; file with the id or nil when neither was found.
3921 ;; `org-export-resolve-coderef' associates a reference to a line
3922 ;; number in the element it belongs, or returns the reference itself
3923 ;; when the element isn't numbered.
3925 (defun org-export-solidify-link-text (s)
3926 "Take link text S and make a safe target out of it."
3927 (save-match-data
3928 (mapconcat 'identity (org-split-string s "[^a-zA-Z0-9_.-:]+") "-")))
3930 (defun org-export-get-coderef-format (path desc)
3931 "Return format string for code reference link.
3932 PATH is the link path. DESC is its description."
3933 (save-match-data
3934 (cond ((not desc) "%s")
3935 ((string-match (regexp-quote (concat "(" path ")")) desc)
3936 (replace-match "%s" t t desc))
3937 (t desc))))
3939 (defun org-export-inline-image-p (link &optional rules)
3940 "Non-nil if LINK object points to an inline image.
3942 Optional argument is a set of RULES defining inline images. It
3943 is an alist where associations have the following shape:
3945 \(TYPE . REGEXP)
3947 Applying a rule means apply REGEXP against LINK's path when its
3948 type is TYPE. The function will return a non-nil value if any of
3949 the provided rules is non-nil. The default rule is
3950 `org-export-default-inline-image-rule'.
3952 This only applies to links without a description."
3953 (and (not (org-element-contents link))
3954 (let ((case-fold-search t)
3955 (rules (or rules org-export-default-inline-image-rule)))
3956 (catch 'exit
3957 (mapc
3958 (lambda (rule)
3959 (and (string= (org-element-property :type link) (car rule))
3960 (string-match (cdr rule)
3961 (org-element-property :path link))
3962 (throw 'exit t)))
3963 rules)
3964 ;; Return nil if no rule matched.
3965 nil))))
3967 (defun org-export-resolve-coderef (ref info)
3968 "Resolve a code reference REF.
3970 INFO is a plist used as a communication channel.
3972 Return associated line number in source code, or REF itself,
3973 depending on src-block or example element's switches."
3974 (org-element-map (plist-get info :parse-tree) '(example-block src-block)
3975 (lambda (el)
3976 (with-temp-buffer
3977 (insert (org-trim (org-element-property :value el)))
3978 (let* ((label-fmt (regexp-quote
3979 (or (org-element-property :label-fmt el)
3980 org-coderef-label-format)))
3981 (ref-re
3982 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
3983 (replace-regexp-in-string "%s" ref label-fmt nil t))))
3984 ;; Element containing REF is found. Resolve it to either
3985 ;; a label or a line number, as needed.
3986 (when (re-search-backward ref-re nil t)
3987 (cond
3988 ((org-element-property :use-labels el) ref)
3989 ((eq (org-element-property :number-lines el) 'continued)
3990 (+ (org-export-get-loc el info) (line-number-at-pos)))
3991 (t (line-number-at-pos)))))))
3992 info 'first-match))
3994 (defun org-export-resolve-fuzzy-link (link info)
3995 "Return LINK destination.
3997 INFO is a plist holding contextual information.
3999 Return value can be an object, an element, or nil:
4001 - If LINK path matches a target object (i.e. <<path>>) return it.
4003 - If LINK path exactly matches the name affiliated keyword
4004 \(i.e. #+NAME: path) of an element, return that element.
4006 - If LINK path exactly matches any headline name, return that
4007 element. If more than one headline share that name, priority
4008 will be given to the one with the closest common ancestor, if
4009 any, or the first one in the parse tree otherwise.
4011 - Otherwise, return nil.
4013 Assume LINK type is \"fuzzy\". White spaces are not
4014 significant."
4015 (let* ((raw-path (org-element-property :path link))
4016 (match-title-p (eq (aref raw-path 0) ?*))
4017 ;; Split PATH at white spaces so matches are space
4018 ;; insensitive.
4019 (path (org-split-string
4020 (if match-title-p (substring raw-path 1) raw-path)))
4021 ;; Cache for destinations that are not position dependent.
4022 (link-cache
4023 (or (plist-get info :resolve-fuzzy-link-cache)
4024 (plist-get (setq info (plist-put info :resolve-fuzzy-link-cache
4025 (make-hash-table :test 'equal)))
4026 :resolve-fuzzy-link-cache)))
4027 (cached (gethash path link-cache 'not-found)))
4028 (cond
4029 ;; Destination is not position dependent: use cached value.
4030 ((and (not match-title-p) (not (eq cached 'not-found))) cached)
4031 ;; First try to find a matching "<<path>>" unless user specified
4032 ;; he was looking for a headline (path starts with a "*"
4033 ;; character).
4034 ((and (not match-title-p)
4035 (let ((match (org-element-map (plist-get info :parse-tree) 'target
4036 (lambda (blob)
4037 (and (equal (org-split-string
4038 (org-element-property :value blob))
4039 path)
4040 blob))
4041 info 'first-match)))
4042 (and match (puthash path match link-cache)))))
4043 ;; Then try to find an element with a matching "#+NAME: path"
4044 ;; affiliated keyword.
4045 ((and (not match-title-p)
4046 (let ((match (org-element-map (plist-get info :parse-tree)
4047 org-element-all-elements
4048 (lambda (el)
4049 (let ((name (org-element-property :name el)))
4050 (when (and name
4051 (equal (org-split-string name) path))
4052 el)))
4053 info 'first-match)))
4054 (and match (puthash path match link-cache)))))
4055 ;; Last case: link either points to a headline or to nothingness.
4056 ;; Try to find the source, with priority given to headlines with
4057 ;; the closest common ancestor. If such candidate is found,
4058 ;; return it, otherwise return nil.
4060 (let ((find-headline
4061 (function
4062 ;; Return first headline whose `:raw-value' property is
4063 ;; NAME in parse tree DATA, or nil. Statistics cookies
4064 ;; are ignored.
4065 (lambda (name data)
4066 (org-element-map data 'headline
4067 (lambda (headline)
4068 (when (equal (org-split-string
4069 (replace-regexp-in-string
4070 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
4071 (org-element-property :raw-value headline)))
4072 name)
4073 headline))
4074 info 'first-match)))))
4075 ;; Search among headlines sharing an ancestor with link, from
4076 ;; closest to farthest.
4077 (catch 'exit
4078 (mapc
4079 (lambda (parent)
4080 (let ((foundp (funcall find-headline path parent)))
4081 (when foundp (throw 'exit foundp))))
4082 (let ((parent-hl (org-export-get-parent-headline link)))
4083 (if (not parent-hl) (list (plist-get info :parse-tree))
4084 (cons parent-hl (org-export-get-genealogy parent-hl)))))
4085 ;; No destination found: return nil.
4086 (and (not match-title-p) (puthash path nil link-cache))))))))
4088 (defun org-export-resolve-id-link (link info)
4089 "Return headline referenced as LINK destination.
4091 INFO is a plist used as a communication channel.
4093 Return value can be the headline element matched in current parse
4094 tree, a file name or nil. Assume LINK type is either \"id\" or
4095 \"custom-id\"."
4096 (let ((id (org-element-property :path link)))
4097 ;; First check if id is within the current parse tree.
4098 (or (org-element-map (plist-get info :parse-tree) 'headline
4099 (lambda (headline)
4100 (when (or (string= (org-element-property :ID headline) id)
4101 (string= (org-element-property :CUSTOM_ID headline) id))
4102 headline))
4103 info 'first-match)
4104 ;; Otherwise, look for external files.
4105 (cdr (assoc id (plist-get info :id-alist))))))
4107 (defun org-export-resolve-radio-link (link info)
4108 "Return radio-target object referenced as LINK destination.
4110 INFO is a plist used as a communication channel.
4112 Return value can be a radio-target object or nil. Assume LINK
4113 has type \"radio\"."
4114 (let ((path (replace-regexp-in-string
4115 "[ \r\t\n]+" " " (org-element-property :path link))))
4116 (org-element-map (plist-get info :parse-tree) 'radio-target
4117 (lambda (radio)
4118 (and (eq (compare-strings
4119 (replace-regexp-in-string
4120 "[ \r\t\n]+" " " (org-element-property :value radio))
4121 nil nil path nil nil t)
4123 radio))
4124 info 'first-match)))
4127 ;;;; For References
4129 ;; `org-export-get-ordinal' associates a sequence number to any object
4130 ;; or element.
4132 (defun org-export-get-ordinal (element info &optional types predicate)
4133 "Return ordinal number of an element or object.
4135 ELEMENT is the element or object considered. INFO is the plist
4136 used as a communication channel.
4138 Optional argument TYPES, when non-nil, is a list of element or
4139 object types, as symbols, that should also be counted in.
4140 Otherwise, only provided element's type is considered.
4142 Optional argument PREDICATE is a function returning a non-nil
4143 value if the current element or object should be counted in. It
4144 accepts two arguments: the element or object being considered and
4145 the plist used as a communication channel. This allows to count
4146 only a certain type of objects (i.e. inline images).
4148 Return value is a list of numbers if ELEMENT is a headline or an
4149 item. It is nil for keywords. It represents the footnote number
4150 for footnote definitions and footnote references. If ELEMENT is
4151 a target, return the same value as if ELEMENT was the closest
4152 table, item or headline containing the target. In any other
4153 case, return the sequence number of ELEMENT among elements or
4154 objects of the same type."
4155 ;; Ordinal of a target object refer to the ordinal of the closest
4156 ;; table, item, or headline containing the object.
4157 (when (eq (org-element-type element) 'target)
4158 (setq element
4159 (loop for parent in (org-export-get-genealogy element)
4160 when
4161 (memq
4162 (org-element-type parent)
4163 '(footnote-definition footnote-reference headline item
4164 table))
4165 return parent)))
4166 (case (org-element-type element)
4167 ;; Special case 1: A headline returns its number as a list.
4168 (headline (org-export-get-headline-number element info))
4169 ;; Special case 2: An item returns its number as a list.
4170 (item (let ((struct (org-element-property :structure element)))
4171 (org-list-get-item-number
4172 (org-element-property :begin element)
4173 struct
4174 (org-list-prevs-alist struct)
4175 (org-list-parents-alist struct))))
4176 ((footnote-definition footnote-reference)
4177 (org-export-get-footnote-number element info))
4178 (otherwise
4179 (let ((counter 0))
4180 ;; Increment counter until ELEMENT is found again.
4181 (org-element-map (plist-get info :parse-tree)
4182 (or types (org-element-type element))
4183 (lambda (el)
4184 (cond
4185 ((eq element el) (1+ counter))
4186 ((not predicate) (incf counter) nil)
4187 ((funcall predicate el info) (incf counter) nil)))
4188 info 'first-match)))))
4191 ;;;; For Src-Blocks
4193 ;; `org-export-get-loc' counts number of code lines accumulated in
4194 ;; src-block or example-block elements with a "+n" switch until
4195 ;; a given element, excluded. Note: "-n" switches reset that count.
4197 ;; `org-export-unravel-code' extracts source code (along with a code
4198 ;; references alist) from an `element-block' or `src-block' type
4199 ;; element.
4201 ;; `org-export-format-code' applies a formatting function to each line
4202 ;; of code, providing relative line number and code reference when
4203 ;; appropriate. Since it doesn't access the original element from
4204 ;; which the source code is coming, it expects from the code calling
4205 ;; it to know if lines should be numbered and if code references
4206 ;; should appear.
4208 ;; Eventually, `org-export-format-code-default' is a higher-level
4209 ;; function (it makes use of the two previous functions) which handles
4210 ;; line numbering and code references inclusion, and returns source
4211 ;; code in a format suitable for plain text or verbatim output.
4213 (defun org-export-get-loc (element info)
4214 "Return accumulated lines of code up to ELEMENT.
4216 INFO is the plist used as a communication channel.
4218 ELEMENT is excluded from count."
4219 (let ((loc 0))
4220 (org-element-map (plist-get info :parse-tree)
4221 `(src-block example-block ,(org-element-type element))
4222 (lambda (el)
4223 (cond
4224 ;; ELEMENT is reached: Quit the loop.
4225 ((eq el element))
4226 ;; Only count lines from src-block and example-block elements
4227 ;; with a "+n" or "-n" switch. A "-n" switch resets counter.
4228 ((not (memq (org-element-type el) '(src-block example-block))) nil)
4229 ((let ((linums (org-element-property :number-lines el)))
4230 (when linums
4231 ;; Accumulate locs or reset them.
4232 (let ((lines (org-count-lines
4233 (org-trim (org-element-property :value el)))))
4234 (setq loc (if (eq linums 'new) lines (+ loc lines))))))
4235 ;; Return nil to stay in the loop.
4236 nil)))
4237 info 'first-match)
4238 ;; Return value.
4239 loc))
4241 (defun org-export-unravel-code (element)
4242 "Clean source code and extract references out of it.
4244 ELEMENT has either a `src-block' an `example-block' type.
4246 Return a cons cell whose CAR is the source code, cleaned from any
4247 reference, protective commas and spurious indentation, and CDR is
4248 an alist between relative line number (integer) and name of code
4249 reference on that line (string)."
4250 (let* ((line 0) refs
4251 (value (org-element-property :value element))
4252 ;; Get code and clean it. Remove blank lines at its
4253 ;; beginning and end.
4254 (code (replace-regexp-in-string
4255 "\\`\\([ \t]*\n\\)+" ""
4256 (replace-regexp-in-string
4257 "\\([ \t]*\n\\)*[ \t]*\\'" "\n"
4258 (if (or org-src-preserve-indentation
4259 (org-element-property :preserve-indent element))
4260 value
4261 (org-element-remove-indentation value)))))
4262 ;; Get format used for references.
4263 (label-fmt (regexp-quote
4264 (or (org-element-property :label-fmt element)
4265 org-coderef-label-format)))
4266 ;; Build a regexp matching a loc with a reference.
4267 (with-ref-re
4268 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)[ \t]*\\)$"
4269 (replace-regexp-in-string
4270 "%s" "\\([-a-zA-Z0-9_ ]+\\)" label-fmt nil t))))
4271 ;; Return value.
4272 (cons
4273 ;; Code with references removed.
4274 (org-element-normalize-string
4275 (mapconcat
4276 (lambda (loc)
4277 (incf line)
4278 (if (not (string-match with-ref-re loc)) loc
4279 ;; Ref line: remove ref, and signal its position in REFS.
4280 (push (cons line (match-string 3 loc)) refs)
4281 (replace-match "" nil nil loc 1)))
4282 (org-split-string code "\n") "\n"))
4283 ;; Reference alist.
4284 refs)))
4286 (defun org-export-format-code (code fun &optional num-lines ref-alist)
4287 "Format CODE by applying FUN line-wise and return it.
4289 CODE is a string representing the code to format. FUN is
4290 a function. It must accept three arguments: a line of
4291 code (string), the current line number (integer) or nil and the
4292 reference associated to the current line (string) or nil.
4294 Optional argument NUM-LINES can be an integer representing the
4295 number of code lines accumulated until the current code. Line
4296 numbers passed to FUN will take it into account. If it is nil,
4297 FUN's second argument will always be nil. This number can be
4298 obtained with `org-export-get-loc' function.
4300 Optional argument REF-ALIST can be an alist between relative line
4301 number (i.e. ignoring NUM-LINES) and the name of the code
4302 reference on it. If it is nil, FUN's third argument will always
4303 be nil. It can be obtained through the use of
4304 `org-export-unravel-code' function."
4305 (let ((--locs (org-split-string code "\n"))
4306 (--line 0))
4307 (org-element-normalize-string
4308 (mapconcat
4309 (lambda (--loc)
4310 (incf --line)
4311 (let ((--ref (cdr (assq --line ref-alist))))
4312 (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
4313 --locs "\n"))))
4315 (defun org-export-format-code-default (element info)
4316 "Return source code from ELEMENT, formatted in a standard way.
4318 ELEMENT is either a `src-block' or `example-block' element. INFO
4319 is a plist used as a communication channel.
4321 This function takes care of line numbering and code references
4322 inclusion. Line numbers, when applicable, appear at the
4323 beginning of the line, separated from the code by two white
4324 spaces. Code references, on the other hand, appear flushed to
4325 the right, separated by six white spaces from the widest line of
4326 code."
4327 ;; Extract code and references.
4328 (let* ((code-info (org-export-unravel-code element))
4329 (code (car code-info))
4330 (code-lines (org-split-string code "\n")))
4331 (if (null code-lines) ""
4332 (let* ((refs (and (org-element-property :retain-labels element)
4333 (cdr code-info)))
4334 ;; Handle line numbering.
4335 (num-start (case (org-element-property :number-lines element)
4336 (continued (org-export-get-loc element info))
4337 (new 0)))
4338 (num-fmt
4339 (and num-start
4340 (format "%%%ds "
4341 (length (number-to-string
4342 (+ (length code-lines) num-start))))))
4343 ;; Prepare references display, if required. Any reference
4344 ;; should start six columns after the widest line of code,
4345 ;; wrapped with parenthesis.
4346 (max-width
4347 (+ (apply 'max (mapcar 'length code-lines))
4348 (if (not num-start) 0 (length (format num-fmt num-start))))))
4349 (org-export-format-code
4350 code
4351 (lambda (loc line-num ref)
4352 (let ((number-str (and num-fmt (format num-fmt line-num))))
4353 (concat
4354 number-str
4356 (and ref
4357 (concat (make-string
4358 (- (+ 6 max-width)
4359 (+ (length loc) (length number-str))) ? )
4360 (format "(%s)" ref))))))
4361 num-start refs)))))
4364 ;;;; For Tables
4366 ;; `org-export-table-has-special-column-p' and and
4367 ;; `org-export-table-row-is-special-p' are predicates used to look for
4368 ;; meta-information about the table structure.
4370 ;; `org-table-has-header-p' tells when the rows before the first rule
4371 ;; should be considered as table's header.
4373 ;; `org-export-table-cell-width', `org-export-table-cell-alignment'
4374 ;; and `org-export-table-cell-borders' extract information from
4375 ;; a table-cell element.
4377 ;; `org-export-table-dimensions' gives the number on rows and columns
4378 ;; in the table, ignoring horizontal rules and special columns.
4379 ;; `org-export-table-cell-address', given a table-cell object, returns
4380 ;; the absolute address of a cell. On the other hand,
4381 ;; `org-export-get-table-cell-at' does the contrary.
4383 ;; `org-export-table-cell-starts-colgroup-p',
4384 ;; `org-export-table-cell-ends-colgroup-p',
4385 ;; `org-export-table-row-starts-rowgroup-p',
4386 ;; `org-export-table-row-ends-rowgroup-p',
4387 ;; `org-export-table-row-starts-header-p' and
4388 ;; `org-export-table-row-ends-header-p' indicate position of current
4389 ;; row or cell within the table.
4391 (defun org-export-table-has-special-column-p (table)
4392 "Non-nil when TABLE has a special column.
4393 All special columns will be ignored during export."
4394 ;; The table has a special column when every first cell of every row
4395 ;; has an empty value or contains a symbol among "/", "#", "!", "$",
4396 ;; "*" "_" and "^". Though, do not consider a first row containing
4397 ;; only empty cells as special.
4398 (let ((special-column-p 'empty))
4399 (catch 'exit
4400 (mapc
4401 (lambda (row)
4402 (when (eq (org-element-property :type row) 'standard)
4403 (let ((value (org-element-contents
4404 (car (org-element-contents row)))))
4405 (cond ((member value '(("/") ("#") ("!") ("$") ("*") ("_") ("^")))
4406 (setq special-column-p 'special))
4407 ((not value))
4408 (t (throw 'exit nil))))))
4409 (org-element-contents table))
4410 (eq special-column-p 'special))))
4412 (defun org-export-table-has-header-p (table info)
4413 "Non-nil when TABLE has a header.
4415 INFO is a plist used as a communication channel.
4417 A table has a header when it contains at least two row groups."
4418 (let ((cache (or (plist-get info :table-header-cache)
4419 (plist-get (setq info
4420 (plist-put info :table-header-cache
4421 (make-hash-table :test 'eq)))
4422 :table-header-cache))))
4423 (or (gethash table cache)
4424 (let ((rowgroup 1) row-flag)
4425 (puthash
4426 table
4427 (org-element-map table 'table-row
4428 (lambda (row)
4429 (cond
4430 ((> rowgroup 1) t)
4431 ((and row-flag (eq (org-element-property :type row) 'rule))
4432 (incf rowgroup) (setq row-flag nil))
4433 ((and (not row-flag) (eq (org-element-property :type row)
4434 'standard))
4435 (setq row-flag t) nil)))
4436 info 'first-match)
4437 cache)))))
4439 (defun org-export-table-row-is-special-p (table-row info)
4440 "Non-nil if TABLE-ROW is considered special.
4442 INFO is a plist used as the communication channel.
4444 All special rows will be ignored during export."
4445 (when (eq (org-element-property :type table-row) 'standard)
4446 (let ((first-cell (org-element-contents
4447 (car (org-element-contents table-row)))))
4448 ;; A row is special either when...
4450 ;; ... it starts with a field only containing "/",
4451 (equal first-cell '("/"))
4452 ;; ... the table contains a special column and the row start
4453 ;; with a marking character among, "^", "_", "$" or "!",
4454 (and (org-export-table-has-special-column-p
4455 (org-export-get-parent table-row))
4456 (member first-cell '(("^") ("_") ("$") ("!"))))
4457 ;; ... it contains only alignment cookies and empty cells.
4458 (let ((special-row-p 'empty))
4459 (catch 'exit
4460 (mapc
4461 (lambda (cell)
4462 (let ((value (org-element-contents cell)))
4463 ;; Since VALUE is a secondary string, the following
4464 ;; checks avoid expanding it with `org-export-data'.
4465 (cond ((not value))
4466 ((and (not (cdr value))
4467 (stringp (car value))
4468 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'"
4469 (car value)))
4470 (setq special-row-p 'cookie))
4471 (t (throw 'exit nil)))))
4472 (org-element-contents table-row))
4473 (eq special-row-p 'cookie)))))))
4475 (defun org-export-table-row-group (table-row info)
4476 "Return TABLE-ROW's group number, as an integer.
4478 INFO is a plist used as the communication channel.
4480 Return value is the group number, as an integer, or nil for
4481 special rows and rows separators. First group is also table's
4482 header."
4483 (let ((cache (or (plist-get info :table-row-group-cache)
4484 (plist-get (setq info
4485 (plist-put info :table-row-group-cache
4486 (make-hash-table :test 'eq)))
4487 :table-row-group-cache))))
4488 (cond ((gethash table-row cache))
4489 ((eq (org-element-property :type table-row) 'rule) nil)
4490 (t (let ((group 0) row-flag)
4491 (org-element-map (org-export-get-parent table-row) 'table-row
4492 (lambda (row)
4493 (if (eq (org-element-property :type row) 'rule)
4494 (setq row-flag nil)
4495 (unless row-flag (incf group) (setq row-flag t)))
4496 (when (eq table-row row) (puthash table-row group cache)))
4497 info 'first-match))))))
4499 (defun org-export-table-cell-width (table-cell info)
4500 "Return TABLE-CELL contents width.
4502 INFO is a plist used as the communication channel.
4504 Return value is the width given by the last width cookie in the
4505 same column as TABLE-CELL, or nil."
4506 (let* ((row (org-export-get-parent table-cell))
4507 (table (org-export-get-parent row))
4508 (cells (org-element-contents row))
4509 (columns (length cells))
4510 (column (- columns (length (memq table-cell cells))))
4511 (cache (or (plist-get info :table-cell-width-cache)
4512 (plist-get (setq info
4513 (plist-put info :table-cell-width-cache
4514 (make-hash-table :test 'eq)))
4515 :table-cell-width-cache)))
4516 (width-vector (or (gethash table cache)
4517 (puthash table (make-vector columns 'empty) cache)))
4518 (value (aref width-vector column)))
4519 (if (not (eq value 'empty)) value
4520 (let (cookie-width)
4521 (dolist (row (org-element-contents table)
4522 (aset width-vector column cookie-width))
4523 (when (org-export-table-row-is-special-p row info)
4524 ;; In a special row, try to find a width cookie at COLUMN.
4525 (let* ((value (org-element-contents
4526 (elt (org-element-contents row) column)))
4527 (cookie (car value)))
4528 ;; The following checks avoid expanding unnecessarily
4529 ;; the cell with `org-export-data'.
4530 (when (and value
4531 (not (cdr value))
4532 (stringp cookie)
4533 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'" cookie)
4534 (match-string 1 cookie))
4535 (setq cookie-width
4536 (string-to-number (match-string 1 cookie)))))))))))
4538 (defun org-export-table-cell-alignment (table-cell info)
4539 "Return TABLE-CELL contents alignment.
4541 INFO is a plist used as the communication channel.
4543 Return alignment as specified by the last alignment cookie in the
4544 same column as TABLE-CELL. If no such cookie is found, a default
4545 alignment value will be deduced from fraction of numbers in the
4546 column (see `org-table-number-fraction' for more information).
4547 Possible values are `left', `right' and `center'."
4548 ;; Load `org-table-number-fraction' and `org-table-number-regexp'.
4549 (require 'org-table)
4550 (let* ((row (org-export-get-parent table-cell))
4551 (table (org-export-get-parent row))
4552 (cells (org-element-contents row))
4553 (columns (length cells))
4554 (column (- columns (length (memq table-cell cells))))
4555 (cache (or (plist-get info :table-cell-alignment-cache)
4556 (plist-get (setq info
4557 (plist-put info :table-cell-alignment-cache
4558 (make-hash-table :test 'eq)))
4559 :table-cell-alignment-cache)))
4560 (align-vector (or (gethash table cache)
4561 (puthash table (make-vector columns nil) cache))))
4562 (or (aref align-vector column)
4563 (let ((number-cells 0)
4564 (total-cells 0)
4565 cookie-align
4566 previous-cell-number-p)
4567 (dolist (row (org-element-contents (org-export-get-parent row)))
4568 (cond
4569 ;; In a special row, try to find an alignment cookie at
4570 ;; COLUMN.
4571 ((org-export-table-row-is-special-p row info)
4572 (let ((value (org-element-contents
4573 (elt (org-element-contents row) column))))
4574 ;; Since VALUE is a secondary string, the following
4575 ;; checks avoid useless expansion through
4576 ;; `org-export-data'.
4577 (when (and value
4578 (not (cdr value))
4579 (stringp (car value))
4580 (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'"
4581 (car value))
4582 (match-string 1 (car value)))
4583 (setq cookie-align (match-string 1 (car value))))))
4584 ;; Ignore table rules.
4585 ((eq (org-element-property :type row) 'rule))
4586 ;; In a standard row, check if cell's contents are
4587 ;; expressing some kind of number. Increase NUMBER-CELLS
4588 ;; accordingly. Though, don't bother if an alignment
4589 ;; cookie has already defined cell's alignment.
4590 ((not cookie-align)
4591 (let ((value (org-export-data
4592 (org-element-contents
4593 (elt (org-element-contents row) column))
4594 info)))
4595 (incf total-cells)
4596 ;; Treat an empty cell as a number if it follows
4597 ;; a number.
4598 (if (not (or (string-match org-table-number-regexp value)
4599 (and (string= value "") previous-cell-number-p)))
4600 (setq previous-cell-number-p nil)
4601 (setq previous-cell-number-p t)
4602 (incf number-cells))))))
4603 ;; Return value. Alignment specified by cookies has
4604 ;; precedence over alignment deduced from cell's contents.
4605 (aset align-vector
4606 column
4607 (cond ((equal cookie-align "l") 'left)
4608 ((equal cookie-align "r") 'right)
4609 ((equal cookie-align "c") 'center)
4610 ((>= (/ (float number-cells) total-cells)
4611 org-table-number-fraction)
4612 'right)
4613 (t 'left)))))))
4615 (defun org-export-table-cell-borders (table-cell info)
4616 "Return TABLE-CELL borders.
4618 INFO is a plist used as a communication channel.
4620 Return value is a list of symbols, or nil. Possible values are:
4621 `top', `bottom', `above', `below', `left' and `right'. Note:
4622 `top' (resp. `bottom') only happen for a cell in the first
4623 row (resp. last row) of the table, ignoring table rules, if any.
4625 Returned borders ignore special rows."
4626 (let* ((row (org-export-get-parent table-cell))
4627 (table (org-export-get-parent-table table-cell))
4628 borders)
4629 ;; Top/above border? TABLE-CELL has a border above when a rule
4630 ;; used to demarcate row groups can be found above. Hence,
4631 ;; finding a rule isn't sufficient to push `above' in BORDERS:
4632 ;; another regular row has to be found above that rule.
4633 (let (rule-flag)
4634 (catch 'exit
4635 (mapc (lambda (row)
4636 (cond ((eq (org-element-property :type row) 'rule)
4637 (setq rule-flag t))
4638 ((not (org-export-table-row-is-special-p row info))
4639 (if rule-flag (throw 'exit (push 'above borders))
4640 (throw 'exit nil)))))
4641 ;; Look at every row before the current one.
4642 (cdr (memq row (reverse (org-element-contents table)))))
4643 ;; No rule above, or rule found starts the table (ignoring any
4644 ;; special row): TABLE-CELL is at the top of the table.
4645 (when rule-flag (push 'above borders))
4646 (push 'top borders)))
4647 ;; Bottom/below border? TABLE-CELL has a border below when next
4648 ;; non-regular row below is a rule.
4649 (let (rule-flag)
4650 (catch 'exit
4651 (mapc (lambda (row)
4652 (cond ((eq (org-element-property :type row) 'rule)
4653 (setq rule-flag t))
4654 ((not (org-export-table-row-is-special-p row info))
4655 (if rule-flag (throw 'exit (push 'below borders))
4656 (throw 'exit nil)))))
4657 ;; Look at every row after the current one.
4658 (cdr (memq row (org-element-contents table))))
4659 ;; No rule below, or rule found ends the table (modulo some
4660 ;; special row): TABLE-CELL is at the bottom of the table.
4661 (when rule-flag (push 'below borders))
4662 (push 'bottom borders)))
4663 ;; Right/left borders? They can only be specified by column
4664 ;; groups. Column groups are defined in a row starting with "/".
4665 ;; Also a column groups row only contains "<", "<>", ">" or blank
4666 ;; cells.
4667 (catch 'exit
4668 (let ((column (let ((cells (org-element-contents row)))
4669 (- (length cells) (length (memq table-cell cells))))))
4670 (mapc
4671 (lambda (row)
4672 (unless (eq (org-element-property :type row) 'rule)
4673 (when (equal (org-element-contents
4674 (car (org-element-contents row)))
4675 '("/"))
4676 (let ((column-groups
4677 (mapcar
4678 (lambda (cell)
4679 (let ((value (org-element-contents cell)))
4680 (when (member value '(("<") ("<>") (">") nil))
4681 (car value))))
4682 (org-element-contents row))))
4683 ;; There's a left border when previous cell, if
4684 ;; any, ends a group, or current one starts one.
4685 (when (or (and (not (zerop column))
4686 (member (elt column-groups (1- column))
4687 '(">" "<>")))
4688 (member (elt column-groups column) '("<" "<>")))
4689 (push 'left borders))
4690 ;; There's a right border when next cell, if any,
4691 ;; starts a group, or current one ends one.
4692 (when (or (and (/= (1+ column) (length column-groups))
4693 (member (elt column-groups (1+ column))
4694 '("<" "<>")))
4695 (member (elt column-groups column) '(">" "<>")))
4696 (push 'right borders))
4697 (throw 'exit nil)))))
4698 ;; Table rows are read in reverse order so last column groups
4699 ;; row has precedence over any previous one.
4700 (reverse (org-element-contents table)))))
4701 ;; Return value.
4702 borders))
4704 (defun org-export-table-cell-starts-colgroup-p (table-cell info)
4705 "Non-nil when TABLE-CELL is at the beginning of a column group.
4706 INFO is a plist used as a communication channel."
4707 ;; A cell starts a column group either when it is at the beginning
4708 ;; of a row (or after the special column, if any) or when it has
4709 ;; a left border.
4710 (or (eq (org-element-map (org-export-get-parent table-cell) 'table-cell
4711 'identity info 'first-match)
4712 table-cell)
4713 (memq 'left (org-export-table-cell-borders table-cell info))))
4715 (defun org-export-table-cell-ends-colgroup-p (table-cell info)
4716 "Non-nil when TABLE-CELL is at the end of a column group.
4717 INFO is a plist used as a communication channel."
4718 ;; A cell ends a column group either when it is at the end of a row
4719 ;; or when it has a right border.
4720 (or (eq (car (last (org-element-contents
4721 (org-export-get-parent table-cell))))
4722 table-cell)
4723 (memq 'right (org-export-table-cell-borders table-cell info))))
4725 (defun org-export-table-row-starts-rowgroup-p (table-row info)
4726 "Non-nil when TABLE-ROW is at the beginning of a row group.
4727 INFO is a plist used as a communication channel."
4728 (unless (or (eq (org-element-property :type table-row) 'rule)
4729 (org-export-table-row-is-special-p table-row info))
4730 (let ((borders (org-export-table-cell-borders
4731 (car (org-element-contents table-row)) info)))
4732 (or (memq 'top borders) (memq 'above borders)))))
4734 (defun org-export-table-row-ends-rowgroup-p (table-row info)
4735 "Non-nil when TABLE-ROW is at the end of a row group.
4736 INFO is a plist used as a communication channel."
4737 (unless (or (eq (org-element-property :type table-row) 'rule)
4738 (org-export-table-row-is-special-p table-row info))
4739 (let ((borders (org-export-table-cell-borders
4740 (car (org-element-contents table-row)) info)))
4741 (or (memq 'bottom borders) (memq 'below borders)))))
4743 (defun org-export-table-row-starts-header-p (table-row info)
4744 "Non-nil when TABLE-ROW is the first table header's row.
4745 INFO is a plist used as a communication channel."
4746 (and (org-export-table-has-header-p
4747 (org-export-get-parent-table table-row) info)
4748 (org-export-table-row-starts-rowgroup-p table-row info)
4749 (= (org-export-table-row-group table-row info) 1)))
4751 (defun org-export-table-row-ends-header-p (table-row info)
4752 "Non-nil when TABLE-ROW is the last table header's row.
4753 INFO is a plist used as a communication channel."
4754 (and (org-export-table-has-header-p
4755 (org-export-get-parent-table table-row) info)
4756 (org-export-table-row-ends-rowgroup-p table-row info)
4757 (= (org-export-table-row-group table-row info) 1)))
4759 (defun org-export-table-row-number (table-row info)
4760 "Return TABLE-ROW number.
4761 INFO is a plist used as a communication channel. Return value is
4762 zero-based and ignores separators. The function returns nil for
4763 special columns and separators."
4764 (when (and (eq (org-element-property :type table-row) 'standard)
4765 (not (org-export-table-row-is-special-p table-row info)))
4766 (let ((number 0))
4767 (org-element-map (org-export-get-parent-table table-row) 'table-row
4768 (lambda (row)
4769 (cond ((eq row table-row) number)
4770 ((eq (org-element-property :type row) 'standard)
4771 (incf number) nil)))
4772 info 'first-match))))
4774 (defun org-export-table-dimensions (table info)
4775 "Return TABLE dimensions.
4777 INFO is a plist used as a communication channel.
4779 Return value is a CONS like (ROWS . COLUMNS) where
4780 ROWS (resp. COLUMNS) is the number of exportable
4781 rows (resp. columns)."
4782 (let (first-row (columns 0) (rows 0))
4783 ;; Set number of rows, and extract first one.
4784 (org-element-map table 'table-row
4785 (lambda (row)
4786 (when (eq (org-element-property :type row) 'standard)
4787 (incf rows)
4788 (unless first-row (setq first-row row)))) info)
4789 ;; Set number of columns.
4790 (org-element-map first-row 'table-cell (lambda (cell) (incf columns)) info)
4791 ;; Return value.
4792 (cons rows columns)))
4794 (defun org-export-table-cell-address (table-cell info)
4795 "Return address of a regular TABLE-CELL object.
4797 TABLE-CELL is the cell considered. INFO is a plist used as
4798 a communication channel.
4800 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4801 zero-based index. Only exportable cells are considered. The
4802 function returns nil for other cells."
4803 (let* ((table-row (org-export-get-parent table-cell))
4804 (row-number (org-export-table-row-number table-row info)))
4805 (when row-number
4806 (cons row-number
4807 (let ((col-count 0))
4808 (org-element-map table-row 'table-cell
4809 (lambda (cell)
4810 (if (eq cell table-cell) col-count (incf col-count) nil))
4811 info 'first-match))))))
4813 (defun org-export-get-table-cell-at (address table info)
4814 "Return regular table-cell object at ADDRESS in TABLE.
4816 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4817 zero-based index. TABLE is a table type element. INFO is
4818 a plist used as a communication channel.
4820 If no table-cell, among exportable cells, is found at ADDRESS,
4821 return nil."
4822 (let ((column-pos (cdr address)) (column-count 0))
4823 (org-element-map
4824 ;; Row at (car address) or nil.
4825 (let ((row-pos (car address)) (row-count 0))
4826 (org-element-map table 'table-row
4827 (lambda (row)
4828 (cond ((eq (org-element-property :type row) 'rule) nil)
4829 ((= row-count row-pos) row)
4830 (t (incf row-count) nil)))
4831 info 'first-match))
4832 'table-cell
4833 (lambda (cell)
4834 (if (= column-count column-pos) cell
4835 (incf column-count) nil))
4836 info 'first-match)))
4839 ;;;; For Tables Of Contents
4841 ;; `org-export-collect-headlines' builds a list of all exportable
4842 ;; headline elements, maybe limited to a certain depth. One can then
4843 ;; easily parse it and transcode it.
4845 ;; Building lists of tables, figures or listings is quite similar.
4846 ;; Once the generic function `org-export-collect-elements' is defined,
4847 ;; `org-export-collect-tables', `org-export-collect-figures' and
4848 ;; `org-export-collect-listings' can be derived from it.
4850 (defun org-export-collect-headlines (info &optional n)
4851 "Collect headlines in order to build a table of contents.
4853 INFO is a plist used as a communication channel.
4855 When optional argument N is an integer, it specifies the depth of
4856 the table of contents. Otherwise, it is set to the value of the
4857 last headline level. See `org-export-headline-levels' for more
4858 information.
4860 Return a list of all exportable headlines as parsed elements.
4861 Footnote sections, if any, will be ignored."
4862 (let ((limit (plist-get info :headline-levels)))
4863 (setq n (if (wholenump n) (min n limit) limit))
4864 (org-element-map (plist-get info :parse-tree) 'headline
4865 #'(lambda (headline)
4866 (unless (org-element-property :footnote-section-p headline)
4867 (let ((level (org-export-get-relative-level headline info)))
4868 (and (<= level n) headline))))
4869 info)))
4871 (defun org-export-collect-elements (type info &optional predicate)
4872 "Collect referenceable elements of a determined type.
4874 TYPE can be a symbol or a list of symbols specifying element
4875 types to search. Only elements with a caption are collected.
4877 INFO is a plist used as a communication channel.
4879 When non-nil, optional argument PREDICATE is a function accepting
4880 one argument, an element of type TYPE. It returns a non-nil
4881 value when that element should be collected.
4883 Return a list of all elements found, in order of appearance."
4884 (org-element-map (plist-get info :parse-tree) type
4885 (lambda (element)
4886 (and (org-element-property :caption element)
4887 (or (not predicate) (funcall predicate element))
4888 element))
4889 info))
4891 (defun org-export-collect-tables (info)
4892 "Build a list of tables.
4893 INFO is a plist used as a communication channel.
4895 Return a list of table elements with a caption."
4896 (org-export-collect-elements 'table info))
4898 (defun org-export-collect-figures (info predicate)
4899 "Build a list of figures.
4901 INFO is a plist used as a communication channel. PREDICATE is
4902 a function which accepts one argument: a paragraph element and
4903 whose return value is non-nil when that element should be
4904 collected.
4906 A figure is a paragraph type element, with a caption, verifying
4907 PREDICATE. The latter has to be provided since a \"figure\" is
4908 a vague concept that may depend on back-end.
4910 Return a list of elements recognized as figures."
4911 (org-export-collect-elements 'paragraph info predicate))
4913 (defun org-export-collect-listings (info)
4914 "Build a list of src blocks.
4916 INFO is a plist used as a communication channel.
4918 Return a list of src-block elements with a caption."
4919 (org-export-collect-elements 'src-block info))
4922 ;;;; Smart Quotes
4924 ;; The main function for the smart quotes sub-system is
4925 ;; `org-export-activate-smart-quotes', which replaces every quote in
4926 ;; a given string from the parse tree with its "smart" counterpart.
4928 ;; Dictionary for smart quotes is stored in
4929 ;; `org-export-smart-quotes-alist'.
4931 ;; Internally, regexps matching potential smart quotes (checks at
4932 ;; string boundaries are also necessary) are defined in
4933 ;; `org-export-smart-quotes-regexps'.
4935 (defconst org-export-smart-quotes-alist
4936 '(("da"
4937 ;; one may use: »...«, "...", ›...‹, or '...'.
4938 ;; http://sproget.dk/raad-og-regler/retskrivningsregler/retskrivningsregler/a7-40-60/a7-58-anforselstegn/
4939 ;; LaTeX quotes require Babel!
4940 (opening-double-quote :utf-8 "»" :html "&raquo;" :latex ">>"
4941 :texinfo "@guillemetright{}")
4942 (closing-double-quote :utf-8 "«" :html "&laquo;" :latex "<<"
4943 :texinfo "@guillemetleft{}")
4944 (opening-single-quote :utf-8 "›" :html "&rsaquo;" :latex "\\frq{}"
4945 :texinfo "@guilsinglright{}")
4946 (closing-single-quote :utf-8 "‹" :html "&lsaquo;" :latex "\\flq{}"
4947 :texinfo "@guilsingleft{}")
4948 (apostrophe :utf-8 "’" :html "&rsquo;"))
4949 ("de"
4950 (opening-double-quote :utf-8 "„" :html "&bdquo;" :latex "\"`"
4951 :texinfo "@quotedblbase{}")
4952 (closing-double-quote :utf-8 "“" :html "&ldquo;" :latex "\"'"
4953 :texinfo "@quotedblleft{}")
4954 (opening-single-quote :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}"
4955 :texinfo "@quotesinglbase{}")
4956 (closing-single-quote :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}"
4957 :texinfo "@quoteleft{}")
4958 (apostrophe :utf-8 "’" :html "&rsquo;"))
4959 ("en"
4960 (opening-double-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
4961 (closing-double-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
4962 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
4963 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
4964 (apostrophe :utf-8 "’" :html "&rsquo;"))
4965 ("es"
4966 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
4967 :texinfo "@guillemetleft{}")
4968 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
4969 :texinfo "@guillemetright{}")
4970 (opening-single-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
4971 (closing-single-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
4972 (apostrophe :utf-8 "’" :html "&rsquo;"))
4973 ("fr"
4974 (opening-double-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
4975 :texinfo "@guillemetleft{}@tie{}")
4976 (closing-double-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
4977 :texinfo "@tie{}@guillemetright{}")
4978 (opening-single-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
4979 :texinfo "@guillemetleft{}@tie{}")
4980 (closing-single-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
4981 :texinfo "@tie{}@guillemetright{}")
4982 (apostrophe :utf-8 "’" :html "&rsquo;"))
4983 ("no"
4984 ;; https://nn.wikipedia.org/wiki/Sitatteikn
4985 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
4986 :texinfo "@guillemetleft{}")
4987 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
4988 :texinfo "@guillemetright{}")
4989 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
4990 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
4991 (apostrophe :utf-8 "’" :html "&rsquo;"))
4992 ("nb"
4993 ;; https://nn.wikipedia.org/wiki/Sitatteikn
4994 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
4995 :texinfo "@guillemetleft{}")
4996 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
4997 :texinfo "@guillemetright{}")
4998 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
4999 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5000 (apostrophe :utf-8 "’" :html "&rsquo;"))
5001 ("nn"
5002 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5003 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5004 :texinfo "@guillemetleft{}")
5005 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5006 :texinfo "@guillemetright{}")
5007 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5008 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5009 (apostrophe :utf-8 "’" :html "&rsquo;"))
5010 ("ru"
5011 ;; 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
5012 ;; http://www.artlebedev.ru/kovodstvo/sections/104/
5013 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "{}<<"
5014 :texinfo "@guillemetleft{}")
5015 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex ">>{}"
5016 :texinfo "@guillemetright{}")
5017 (opening-single-quote :utf-8 "„" :html "&bdquo;" :latex "\\glqq{}"
5018 :texinfo "@quotedblbase{}")
5019 (closing-single-quote :utf-8 "“" :html "&ldquo;" :latex "\\grqq{}"
5020 :texinfo "@quotedblleft{}")
5021 (apostrophe :utf-8 "’" :html: "&#39;"))
5022 ("sv"
5023 ;; based on https://sv.wikipedia.org/wiki/Citattecken
5024 (opening-double-quote :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
5025 (closing-double-quote :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
5026 (opening-single-quote :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "`")
5027 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "'")
5028 (apostrophe :utf-8 "’" :html "&rsquo;"))
5030 "Smart quotes translations.
5032 Alist whose CAR is a language string and CDR is an alist with
5033 quote type as key and a plist associating various encodings to
5034 their translation as value.
5036 A quote type can be any symbol among `opening-double-quote',
5037 `closing-double-quote', `opening-single-quote',
5038 `closing-single-quote' and `apostrophe'.
5040 Valid encodings include `:utf-8', `:html', `:latex' and
5041 `:texinfo'.
5043 If no translation is found, the quote character is left as-is.")
5045 (defconst org-export-smart-quotes-regexps
5046 (list
5047 ;; Possible opening quote at beginning of string.
5048 "\\`\\([\"']\\)\\(\\w\\|\\s.\\|\\s_\\|\\s(\\)"
5049 ;; Possible closing quote at beginning of string.
5050 "\\`\\([\"']\\)\\(\\s-\\|\\s)\\|\\s.\\)"
5051 ;; Possible apostrophe at beginning of string.
5052 "\\`\\('\\)\\S-"
5053 ;; Opening single and double quotes.
5054 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\(?:\\w\\|\\s.\\|\\s_\\)"
5055 ;; Closing single and double quotes.
5056 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\(?:\\s-\\|\\s)\\|\\s.\\)"
5057 ;; Apostrophe.
5058 "\\S-\\('\\)\\S-"
5059 ;; Possible opening quote at end of string.
5060 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\'"
5061 ;; Possible closing quote at end of string.
5062 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\'"
5063 ;; Possible apostrophe at end of string.
5064 "\\S-\\('\\)\\'")
5065 "List of regexps matching a quote or an apostrophe.
5066 In every regexp, quote or apostrophe matched is put in group 1.")
5068 (defun org-export-activate-smart-quotes (s encoding info &optional original)
5069 "Replace regular quotes with \"smart\" quotes in string S.
5071 ENCODING is a symbol among `:html', `:latex', `:texinfo' and
5072 `:utf-8'. INFO is a plist used as a communication channel.
5074 The function has to retrieve information about string
5075 surroundings in parse tree. It can only happen with an
5076 unmodified string. Thus, if S has already been through another
5077 process, a non-nil ORIGINAL optional argument will provide that
5078 original string.
5080 Return the new string."
5081 (if (equal s "") ""
5082 (let* ((prev (org-export-get-previous-element (or original s) info))
5083 ;; Try to be flexible when computing number of blanks
5084 ;; before object. The previous object may be a string
5085 ;; introduced by the back-end and not completely parsed.
5086 (pre-blank (and prev
5087 (or (org-element-property :post-blank prev)
5088 ;; A string with missing `:post-blank'
5089 ;; property.
5090 (and (stringp prev)
5091 (string-match " *\\'" prev)
5092 (length (match-string 0 prev)))
5093 ;; Fallback value.
5094 0)))
5095 (next (org-export-get-next-element (or original s) info))
5096 (get-smart-quote
5097 (lambda (q type)
5098 ;; Return smart quote associated to a give quote Q, as
5099 ;; a string. TYPE is a symbol among `open', `close' and
5100 ;; `apostrophe'.
5101 (let ((key (case type
5102 (apostrophe 'apostrophe)
5103 (open (if (equal "'" q) 'opening-single-quote
5104 'opening-double-quote))
5105 (otherwise (if (equal "'" q) 'closing-single-quote
5106 'closing-double-quote)))))
5107 (or (plist-get
5108 (cdr (assq key
5109 (cdr (assoc (plist-get info :language)
5110 org-export-smart-quotes-alist))))
5111 encoding)
5112 q)))))
5113 (if (or (equal "\"" s) (equal "'" s))
5114 ;; Only a quote: no regexp can match. We have to check both
5115 ;; sides and decide what to do.
5116 (cond ((and (not prev) (not next)) s)
5117 ((not prev) (funcall get-smart-quote s 'open))
5118 ((and (not next) (zerop pre-blank))
5119 (funcall get-smart-quote s 'close))
5120 ((not next) s)
5121 ((zerop pre-blank) (funcall get-smart-quote s 'apostrophe))
5122 (t (funcall get-smart-quote 'open)))
5123 ;; 1. Replace quote character at the beginning of S.
5124 (cond
5125 ;; Apostrophe?
5126 ((and prev (zerop pre-blank)
5127 (string-match (nth 2 org-export-smart-quotes-regexps) s))
5128 (setq s (replace-match
5129 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
5130 nil t s 1)))
5131 ;; Closing quote?
5132 ((and prev (zerop pre-blank)
5133 (string-match (nth 1 org-export-smart-quotes-regexps) s))
5134 (setq s (replace-match
5135 (funcall get-smart-quote (match-string 1 s) 'close)
5136 nil t s 1)))
5137 ;; Opening quote?
5138 ((and (or (not prev) (> pre-blank 0))
5139 (string-match (nth 0 org-export-smart-quotes-regexps) s))
5140 (setq s (replace-match
5141 (funcall get-smart-quote (match-string 1 s) 'open)
5142 nil t s 1))))
5143 ;; 2. Replace quotes in the middle of the string.
5144 (setq s (replace-regexp-in-string
5145 ;; Opening quotes.
5146 (nth 3 org-export-smart-quotes-regexps)
5147 (lambda (text)
5148 (funcall get-smart-quote (match-string 1 text) 'open))
5149 s nil t 1))
5150 (setq s (replace-regexp-in-string
5151 ;; Closing quotes.
5152 (nth 4 org-export-smart-quotes-regexps)
5153 (lambda (text)
5154 (funcall get-smart-quote (match-string 1 text) 'close))
5155 s nil t 1))
5156 (setq s (replace-regexp-in-string
5157 ;; Apostrophes.
5158 (nth 5 org-export-smart-quotes-regexps)
5159 (lambda (text)
5160 (funcall get-smart-quote (match-string 1 text) 'apostrophe))
5161 s nil t 1))
5162 ;; 3. Replace quote character at the end of S.
5163 (cond
5164 ;; Apostrophe?
5165 ((and next (string-match (nth 8 org-export-smart-quotes-regexps) s))
5166 (setq s (replace-match
5167 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
5168 nil t s 1)))
5169 ;; Closing quote?
5170 ((and (not next)
5171 (string-match (nth 7 org-export-smart-quotes-regexps) s))
5172 (setq s (replace-match
5173 (funcall get-smart-quote (match-string 1 s) 'close)
5174 nil t s 1)))
5175 ;; Opening quote?
5176 ((and next (string-match (nth 6 org-export-smart-quotes-regexps) s))
5177 (setq s (replace-match
5178 (funcall get-smart-quote (match-string 1 s) 'open)
5179 nil t s 1))))
5180 ;; Return string with smart quotes.
5181 s))))
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 ;; `org-export-get-genealogy' returns the full genealogy of a given
5195 ;; element or object, from closest parent to full parse tree.
5197 (defun org-export-get-genealogy (blob)
5198 "Return full genealogy relative to a given element or object.
5200 BLOB is the element or object being considered.
5202 Ancestors are returned from closest to farthest, the last one
5203 being the full parse tree."
5204 (let (genealogy (parent blob))
5205 (while (setq parent (org-element-property :parent parent))
5206 (push parent genealogy))
5207 (nreverse genealogy)))
5209 (defun org-export-get-parent-headline (blob)
5210 "Return BLOB parent headline or nil.
5211 BLOB is the element or object being considered."
5212 (let ((parent blob))
5213 (while (and (setq parent (org-element-property :parent parent))
5214 (not (eq (org-element-type parent) 'headline))))
5215 parent))
5217 (defun org-export-get-parent-element (object)
5218 "Return first element containing OBJECT or nil.
5219 OBJECT is the object to consider."
5220 (let ((parent object))
5221 (while (and (setq parent (org-element-property :parent parent))
5222 (memq (org-element-type parent) org-element-all-objects)))
5223 parent))
5225 (defun org-export-get-parent-table (object)
5226 "Return OBJECT parent table or nil.
5227 OBJECT is either a `table-cell' or `table-element' type object."
5228 (let ((parent object))
5229 (while (and (setq parent (org-element-property :parent parent))
5230 (not (eq (org-element-type parent) 'table))))
5231 parent))
5233 (defun org-export-get-previous-element (blob info &optional n)
5234 "Return previous element or object.
5236 BLOB is an element or object. INFO is a plist used as
5237 a communication channel. Return previous exportable element or
5238 object, a string, or nil.
5240 When optional argument N is a positive integer, return a list
5241 containing up to N siblings before BLOB, from farthest to
5242 closest. With any other non-nil value, return a list containing
5243 all of them."
5244 (let* ((secondary (org-element-secondary-p blob))
5245 (parent (org-export-get-parent blob))
5246 (siblings
5247 (if secondary (org-element-property secondary parent)
5248 (org-element-contents parent)))
5249 prev)
5250 (catch 'exit
5251 (dolist (obj (cdr (memq blob (reverse siblings))) prev)
5252 (cond ((memq obj (plist-get info :ignore-list)))
5253 ((null n) (throw 'exit obj))
5254 ((not (wholenump n)) (push obj prev))
5255 ((zerop n) (throw 'exit prev))
5256 (t (decf n) (push obj prev)))))))
5258 (defun org-export-get-next-element (blob info &optional n)
5259 "Return next element or object.
5261 BLOB is an element or object. INFO is a plist used as
5262 a communication channel. Return next exportable element or
5263 object, a string, or nil.
5265 When optional argument N is a positive integer, return a list
5266 containing up to N siblings after BLOB, from closest to farthest.
5267 With any other non-nil value, return a list containing all of
5268 them."
5269 (let* ((secondary (org-element-secondary-p blob))
5270 (parent (org-export-get-parent blob))
5271 (siblings
5272 (cdr (memq blob
5273 (if secondary (org-element-property secondary parent)
5274 (org-element-contents parent)))))
5275 next)
5276 (catch 'exit
5277 (dolist (obj siblings (nreverse next))
5278 (cond ((memq obj (plist-get info :ignore-list)))
5279 ((null n) (throw 'exit obj))
5280 ((not (wholenump n)) (push obj next))
5281 ((zerop n) (throw 'exit (nreverse next)))
5282 (t (decf n) (push obj next)))))))
5285 ;;;; Translation
5287 ;; `org-export-translate' translates a string according to the language
5288 ;; specified by the LANGUAGE keyword. `org-export-dictionary' contains
5289 ;; the dictionary used for the translation.
5291 (defconst org-export-dictionary
5292 '(("%e %n: %c"
5293 ("fr" :default "%e %n : %c" :html "%e&nbsp;%n&nbsp;: %c"))
5294 ("Author"
5295 ("ca" :default "Autor")
5296 ("cs" :default "Autor")
5297 ("da" :default "Forfatter")
5298 ("de" :default "Autor")
5299 ("eo" :html "A&#365;toro")
5300 ("es" :default "Autor")
5301 ("et" :default "Autor")
5302 ("fi" :html "Tekij&auml;")
5303 ("fr" :default "Auteur")
5304 ("hu" :default "Szerz&otilde;")
5305 ("is" :html "H&ouml;fundur")
5306 ("it" :default "Autore")
5307 ("ja" :default "著者" :html "&#33879;&#32773;")
5308 ("nl" :default "Auteur")
5309 ("no" :default "Forfatter")
5310 ("nb" :default "Forfatter")
5311 ("nn" :default "Forfattar")
5312 ("pl" :default "Autor")
5313 ("ru" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5314 ("sv" :html "F&ouml;rfattare")
5315 ("uk" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5316 ("zh-CN" :html "&#20316;&#32773;" :utf-8 "作者")
5317 ("zh-TW" :html "&#20316;&#32773;" :utf-8 "作者"))
5318 ("Continued from previous page"
5319 ("de" :default "Fortsetzung von vorheriger Seite")
5320 ("es" :default "Continúa de la página anterior")
5321 ("fr" :default "Suite de la page précédente")
5322 ("it" :default "Continua da pagina precedente")
5323 ("ja" :default "前ページからの続き")
5324 ("nl" :default "Vervolg van vorige pagina")
5325 ("pt" :default "Continuação da página anterior")
5326 ("ru" :html "(&#1055;&#1088;&#1086;&#1076;&#1086;&#1083;&#1078;&#1077;&#1085;&#1080;&#1077;)"
5327 :utf-8 "(Продолжение)"))
5328 ("Continued on next page"
5329 ("de" :default "Fortsetzung nächste Seite")
5330 ("es" :default "Continúa en la siguiente página")
5331 ("fr" :default "Suite page suivante")
5332 ("it" :default "Continua alla pagina successiva")
5333 ("ja" :default "次ページに続く")
5334 ("nl" :default "Vervolg op volgende pagina")
5335 ("pt" :default "Continua na página seguinte")
5336 ("ru" :html "(&#1055;&#1088;&#1086;&#1076;&#1086;&#1083;&#1078;&#1077;&#1085;&#1080;&#1077; &#1089;&#1083;&#1077;&#1076;&#1091;&#1077;&#1090;)"
5337 :utf-8 "(Продолжение следует)"))
5338 ("Date"
5339 ("ca" :default "Data")
5340 ("cs" :default "Datum")
5341 ("da" :default "Dato")
5342 ("de" :default "Datum")
5343 ("eo" :default "Dato")
5344 ("es" :default "Fecha")
5345 ("et" :html "Kuup&#228;ev" :utf-8 "Kuupäev")
5346 ("fi" :html "P&auml;iv&auml;m&auml;&auml;r&auml;")
5347 ("hu" :html "D&aacute;tum")
5348 ("is" :default "Dagsetning")
5349 ("it" :default "Data")
5350 ("ja" :default "日付" :html "&#26085;&#20184;")
5351 ("nl" :default "Datum")
5352 ("no" :default "Dato")
5353 ("nb" :default "Dato")
5354 ("nn" :default "Dato")
5355 ("pl" :default "Data")
5356 ("ru" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5357 ("sv" :default "Datum")
5358 ("uk" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5359 ("zh-CN" :html "&#26085;&#26399;" :utf-8 "日期")
5360 ("zh-TW" :html "&#26085;&#26399;" :utf-8 "日期"))
5361 ("Equation"
5362 ("da" :default "Ligning")
5363 ("de" :default "Gleichung")
5364 ("es" :html "Ecuaci&oacute;n" :default "Ecuación")
5365 ("et" :html "V&#245;rrand" :utf-8 "Võrrand")
5366 ("fr" :ascii "Equation" :default "Équation")
5367 ("ja" :default "方程式")
5368 ("no" :default "Ligning")
5369 ("nb" :default "Ligning")
5370 ("nn" :default "Likning")
5371 ("ru" :html "&#1059;&#1088;&#1072;&#1074;&#1085;&#1077;&#1085;&#1080;&#1077;"
5372 :utf-8 "Уравнение")
5373 ("sv" :default "Ekvation")
5374 ("zh-CN" :html "&#26041;&#31243;" :utf-8 "方程"))
5375 ("Figure"
5376 ("da" :default "Figur")
5377 ("de" :default "Abbildung")
5378 ("es" :default "Figura")
5379 ("et" :default "Joonis")
5380 ("ja" :default "図" :html "&#22259;")
5381 ("no" :default "Illustrasjon")
5382 ("nb" :default "Illustrasjon")
5383 ("nn" :default "Illustrasjon")
5384 ("ru" :html "&#1056;&#1080;&#1089;&#1091;&#1085;&#1086;&#1082;" :utf-8 "Рисунок")
5385 ("sv" :default "Illustration")
5386 ("zh-CN" :html "&#22270;" :utf-8 "图"))
5387 ("Figure %d:"
5388 ("da" :default "Figur %d")
5389 ("de" :default "Abbildung %d:")
5390 ("es" :default "Figura %d:")
5391 ("et" :default "Joonis %d:")
5392 ("fr" :default "Figure %d :" :html "Figure&nbsp;%d&nbsp;:")
5393 ("ja" :default "図%d: " :html "&#22259;%d: ")
5394 ("no" :default "Illustrasjon %d")
5395 ("nb" :default "Illustrasjon %d")
5396 ("nn" :default "Illustrasjon %d")
5397 ("ru" :html "&#1056;&#1080;&#1089;. %d.:" :utf-8 "Рис. %d.:")
5398 ("sv" :default "Illustration %d")
5399 ("zh-CN" :html "&#22270;%d&nbsp;" :utf-8 "图%d "))
5400 ("Footnotes"
5401 ("ca" :html "Peus de p&agrave;gina")
5402 ("cs" :default "Pozn\xe1mky pod carou")
5403 ("da" :default "Fodnoter")
5404 ("de" :html "Fu&szlig;noten" :default "Fußnoten")
5405 ("eo" :default "Piednotoj")
5406 ("es" :html "Nota al pie de p&aacute;gina" :default "Nota al pie de página")
5407 ("et" :html "Allm&#228;rkused" :utf-8 "Allmärkused")
5408 ("fi" :default "Alaviitteet")
5409 ("fr" :default "Notes de bas de page")
5410 ("hu" :html "L&aacute;bjegyzet")
5411 ("is" :html "Aftanm&aacute;lsgreinar")
5412 ("it" :html "Note a pi&egrave; di pagina")
5413 ("ja" :default "脚注" :html "&#33050;&#27880;")
5414 ("nl" :default "Voetnoten")
5415 ("no" :default "Fotnoter")
5416 ("nb" :default "Fotnoter")
5417 ("nn" :default "Fotnotar")
5418 ("pl" :default "Przypis")
5419 ("ru" :html "&#1057;&#1085;&#1086;&#1089;&#1082;&#1080;" :utf-8 "Сноски")
5420 ("sv" :default "Fotnoter")
5421 ("uk" :html "&#1055;&#1088;&#1080;&#1084;&#1110;&#1090;&#1082;&#1080;"
5422 :utf-8 "Примітки")
5423 ("zh-CN" :html "&#33050;&#27880;" :utf-8 "脚注")
5424 ("zh-TW" :html "&#33139;&#35387;" :utf-8 "腳註"))
5425 ("List of Listings"
5426 ("da" :default "Programmer")
5427 ("de" :default "Programmauflistungsverzeichnis")
5428 ("es" :default "Indice de Listados de programas")
5429 ("et" :default "Loendite nimekiri")
5430 ("fr" :default "Liste des programmes")
5431 ("ja" :default "ソースコード目次")
5432 ("no" :default "Dataprogrammer")
5433 ("nb" :default "Dataprogrammer")
5434 ("ru" :html "&#1057;&#1087;&#1080;&#1089;&#1086;&#1082; &#1088;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1086;&#1082;"
5435 :utf-8 "Список распечаток")
5436 ("zh-CN" :html "&#20195;&#30721;&#30446;&#24405;" :utf-8 "代码目录"))
5437 ("List of Tables"
5438 ("da" :default "Tabeller")
5439 ("de" :default "Tabellenverzeichnis")
5440 ("es" :default "Indice de tablas")
5441 ("et" :default "Tabelite nimekiri")
5442 ("fr" :default "Liste des tableaux")
5443 ("ja" :default "表目次")
5444 ("no" :default "Tabeller")
5445 ("nb" :default "Tabeller")
5446 ("nn" :default "Tabeller")
5447 ("ru" :html "&#1057;&#1087;&#1080;&#1089;&#1086;&#1082; &#1090;&#1072;&#1073;&#1083;&#1080;&#1094;"
5448 :utf-8 "Список таблиц")
5449 ("sv" :default "Tabeller")
5450 ("zh-CN" :html "&#34920;&#26684;&#30446;&#24405;" :utf-8 "表格目录"))
5451 ("Listing %d:"
5452 ("da" :default "Program %d")
5453 ("de" :default "Programmlisting %d")
5454 ("es" :default "Listado de programa %d")
5455 ("et" :default "Loend %d")
5456 ("fr" :default "Programme %d :" :html "Programme&nbsp;%d&nbsp;:")
5457 ("ja" :default "ソースコード%d:")
5458 ("no" :default "Dataprogram %d")
5459 ("nb" :default "Dataprogram %d")
5460 ("ru" :html "&#1056;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1082;&#1072; %d.:"
5461 :utf-8 "Распечатка %d.:")
5462 ("zh-CN" :html "&#20195;&#30721;%d&nbsp;" :utf-8 "代码%d "))
5463 ("See section %s"
5464 ("da" :default "jævnfør afsnit %s")
5465 ("de" :default "siehe Abschnitt %s")
5466 ("es" :default "vea seccion %s")
5467 ("et" :html "Vaata peat&#252;kki %s" :utf-8 "Vaata peatükki %s")
5468 ("fr" :default "cf. section %s")
5469 ("ja" :default "セクション %s を参照")
5470 ("ru" :html "&#1057;&#1084;. &#1088;&#1072;&#1079;&#1076;&#1077;&#1083; %s"
5471 :utf-8 "См. раздел %s")
5472 ("zh-CN" :html "&#21442;&#35265;&#31532;%s&#33410;" :utf-8 "参见第%s节"))
5473 ("Table"
5474 ("de" :default "Tabelle")
5475 ("es" :default "Tabla")
5476 ("et" :default "Tabel")
5477 ("fr" :default "Tableau")
5478 ("ja" :default "表" :html "&#34920;")
5479 ("ru" :html "&#1058;&#1072;&#1073;&#1083;&#1080;&#1094;&#1072;" :utf-8 "Таблица")
5480 ("zh-CN" :html "&#34920;" :utf-8 "表"))
5481 ("Table %d:"
5482 ("da" :default "Tabel %d")
5483 ("de" :default "Tabelle %d")
5484 ("es" :default "Tabla %d")
5485 ("et" :default "Tabel %d")
5486 ("fr" :default "Tableau %d :")
5487 ("ja" :default "表%d:" :html "&#34920;%d:")
5488 ("no" :default "Tabell %d")
5489 ("nb" :default "Tabell %d")
5490 ("nn" :default "Tabell %d")
5491 ("ru" :html "&#1058;&#1072;&#1073;&#1083;&#1080;&#1094;&#1072; %d.:"
5492 :utf-8 "Таблица %d.:")
5493 ("sv" :default "Tabell %d")
5494 ("zh-CN" :html "&#34920;%d&nbsp;" :utf-8 "表%d "))
5495 ("Table of Contents"
5496 ("ca" :html "&Iacute;ndex")
5497 ("cs" :default "Obsah")
5498 ("da" :default "Indhold")
5499 ("de" :default "Inhaltsverzeichnis")
5500 ("eo" :default "Enhavo")
5501 ("es" :html "&Iacute;ndice")
5502 ("et" :default "Sisukord")
5503 ("fi" :html "Sis&auml;llysluettelo")
5504 ("fr" :ascii "Sommaire" :default "Table des matières")
5505 ("hu" :html "Tartalomjegyz&eacute;k")
5506 ("is" :default "Efnisyfirlit")
5507 ("it" :default "Indice")
5508 ("ja" :default "目次" :html "&#30446;&#27425;")
5509 ("nl" :default "Inhoudsopgave")
5510 ("no" :default "Innhold")
5511 ("nb" :default "Innhold")
5512 ("nn" :default "Innhald")
5513 ("pl" :html "Spis tre&#x015b;ci")
5514 ("ru" :html "&#1057;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1077;"
5515 :utf-8 "Содержание")
5516 ("sv" :html "Inneh&aring;ll")
5517 ("uk" :html "&#1047;&#1084;&#1110;&#1089;&#1090;" :utf-8 "Зміст")
5518 ("zh-CN" :html "&#30446;&#24405;" :utf-8 "目录")
5519 ("zh-TW" :html "&#30446;&#37636;" :utf-8 "目錄"))
5520 ("Unknown reference"
5521 ("da" :default "ukendt reference")
5522 ("de" :default "Unbekannter Verweis")
5523 ("es" :default "referencia desconocida")
5524 ("et" :default "Tundmatu viide")
5525 ("fr" :ascii "Destination inconnue" :default "Référence inconnue")
5526 ("ja" :default "不明な参照先")
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 BODY evaluation happens in an asynchronous process, from a buffer
5590 which is an exact copy of the current one.
5592 Use `org-export-add-to-stack' in FUN in order to register results
5593 in the stack.
5595 This is a low level function. See also `org-export-to-buffer'
5596 and `org-export-to-file' for more specialized functions."
5597 (declare (indent 1) (debug t))
5598 (org-with-gensyms (process temp-file copy-fun proc-buffer coding)
5599 ;; Write the full sexp evaluating BODY in a copy of the current
5600 ;; buffer to a temporary file, as it may be too long for program
5601 ;; args in `start-process'.
5602 `(with-temp-message "Initializing asynchronous export process"
5603 (let ((,copy-fun (org-export--generate-copy-script (current-buffer)))
5604 (,temp-file (make-temp-file "org-export-process"))
5605 (,coding buffer-file-coding-system))
5606 (with-temp-file ,temp-file
5607 (insert
5608 ;; Null characters (from variable values) are inserted
5609 ;; within the file. As a consequence, coding system for
5610 ;; buffer contents will not be recognized properly. So,
5611 ;; we make sure it is the same as the one used to display
5612 ;; the original buffer.
5613 (format ";; -*- coding: %s; -*-\n%S"
5614 ,coding
5615 `(with-temp-buffer
5616 (when org-export-async-debug '(setq debug-on-error t))
5617 ;; Ignore `kill-emacs-hook' and code evaluation
5618 ;; queries from Babel as we need a truly
5619 ;; non-interactive process.
5620 (setq kill-emacs-hook nil
5621 org-babel-confirm-evaluate-answer-no t)
5622 ;; Initialize export framework.
5623 (require 'ox)
5624 ;; Re-create current buffer there.
5625 (funcall ,,copy-fun)
5626 (restore-buffer-modified-p nil)
5627 ;; Sexp to evaluate in the buffer.
5628 (print (progn ,,@body))))))
5629 ;; Start external process.
5630 (let* ((process-connection-type nil)
5631 (,proc-buffer (generate-new-buffer-name "*Org Export Process*"))
5632 (,process
5633 (apply
5634 #'start-process
5635 (append
5636 (list "org-export-process"
5637 ,proc-buffer
5638 (expand-file-name invocation-name invocation-directory)
5639 "--batch")
5640 (if org-export-async-init-file
5641 (list "-Q" "-l" org-export-async-init-file)
5642 (list "-l" user-init-file))
5643 (list "-l" ,temp-file)))))
5644 ;; Register running process in stack.
5645 (org-export-add-to-stack (get-buffer ,proc-buffer) nil ,process)
5646 ;; Set-up sentinel in order to catch results.
5647 (let ((handler ,fun))
5648 (set-process-sentinel
5649 ,process
5650 `(lambda (p status)
5651 (let ((proc-buffer (process-buffer p)))
5652 (when (eq (process-status p) 'exit)
5653 (unwind-protect
5654 (if (zerop (process-exit-status p))
5655 (unwind-protect
5656 (let ((results
5657 (with-current-buffer proc-buffer
5658 (goto-char (point-max))
5659 (backward-sexp)
5660 (read (current-buffer)))))
5661 (funcall ,handler results))
5662 (unless org-export-async-debug
5663 (and (get-buffer proc-buffer)
5664 (kill-buffer proc-buffer))))
5665 (org-export-add-to-stack proc-buffer nil p)
5666 (ding)
5667 (message "Process '%s' exited abnormally" p))
5668 (unless org-export-async-debug
5669 (delete-file ,,temp-file)))))))))))))
5671 ;;;###autoload
5672 (defun org-export-to-buffer
5673 (backend buffer
5674 &optional async subtreep visible-only body-only ext-plist
5675 post-process)
5676 "Call `org-export-as' with output to a specified buffer.
5678 BACKEND is either an export back-end, as returned by, e.g.,
5679 `org-export-create-backend', or a symbol referring to
5680 a registered back-end.
5682 BUFFER is the name of the output buffer. If it already exists,
5683 it will be erased first, otherwise, it will be created.
5685 A non-nil optional argument ASYNC means the process should happen
5686 asynchronously. The resulting buffer should then be accessible
5687 through the `org-export-stack' interface. When ASYNC is nil, the
5688 buffer is displayed if `org-export-show-temporary-export-buffer'
5689 is non-nil.
5691 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
5692 EXT-PLIST are similar to those used in `org-export-as', which
5693 see.
5695 Optional argument POST-PROCESS is a function which should accept
5696 no argument. It is always called within the current process,
5697 from BUFFER, with point at its beginning. Export back-ends can
5698 use it to set a major mode there, e.g,
5700 \(defun org-latex-export-as-latex
5701 \(&optional async subtreep visible-only body-only ext-plist)
5702 \(interactive)
5703 \(org-export-to-buffer 'latex \"*Org LATEX Export*\"
5704 async subtreep visible-only body-only ext-plist (lambda () (LaTeX-mode))))
5706 This function returns BUFFER."
5707 (declare (indent 2))
5708 (if async
5709 (org-export-async-start
5710 `(lambda (output)
5711 (with-current-buffer (get-buffer-create ,buffer)
5712 (erase-buffer)
5713 (setq buffer-file-coding-system ',buffer-file-coding-system)
5714 (insert output)
5715 (goto-char (point-min))
5716 (org-export-add-to-stack (current-buffer) ',backend)
5717 (ignore-errors (funcall ,post-process))))
5718 `(org-export-as
5719 ',backend ,subtreep ,visible-only ,body-only ',ext-plist))
5720 (let ((output
5721 (org-export-as backend subtreep visible-only body-only ext-plist))
5722 (buffer (get-buffer-create buffer))
5723 (encoding buffer-file-coding-system))
5724 (when (and (org-string-nw-p output) (org-export--copy-to-kill-ring-p))
5725 (org-kill-new output))
5726 (with-current-buffer buffer
5727 (erase-buffer)
5728 (setq buffer-file-coding-system encoding)
5729 (insert output)
5730 (goto-char (point-min))
5731 (and (functionp post-process) (funcall post-process)))
5732 (when org-export-show-temporary-export-buffer
5733 (switch-to-buffer-other-window buffer))
5734 buffer)))
5736 ;;;###autoload
5737 (defun org-export-to-file
5738 (backend file &optional async subtreep visible-only body-only ext-plist
5739 post-process)
5740 "Call `org-export-as' with output to a specified file.
5742 BACKEND is either an export back-end, as returned by, e.g.,
5743 `org-export-create-backend', or a symbol referring to
5744 a registered back-end. FILE is the name of the output file, as
5745 a string.
5747 A non-nil optional argument ASYNC means the process should happen
5748 asynchronously. The resulting buffer will then be accessible
5749 through the `org-export-stack' interface.
5751 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
5752 EXT-PLIST are similar to those used in `org-export-as', which
5753 see.
5755 Optional argument POST-PROCESS is called with FILE as its
5756 argument and happens asynchronously when ASYNC is non-nil. It
5757 has to return a file name, or nil. Export back-ends can use this
5758 to send the output file through additional processing, e.g,
5760 \(defun org-latex-export-to-latex
5761 \(&optional async subtreep visible-only body-only ext-plist)
5762 \(interactive)
5763 \(let ((outfile (org-export-output-file-name \".tex\" subtreep)))
5764 \(org-export-to-file 'latex outfile
5765 async subtreep visible-only body-only ext-plist
5766 \(lambda (file) (org-latex-compile file)))
5768 The function returns either a file name returned by POST-PROCESS,
5769 or FILE."
5770 (declare (indent 2))
5771 (if (not (file-writable-p file)) (error "Output file not writable")
5772 (let ((encoding (or org-export-coding-system buffer-file-coding-system)))
5773 (if async
5774 (org-export-async-start
5775 `(lambda (file)
5776 (org-export-add-to-stack (expand-file-name file) ',backend))
5777 `(let ((output
5778 (org-export-as
5779 ',backend ,subtreep ,visible-only ,body-only
5780 ',ext-plist)))
5781 (with-temp-buffer
5782 (insert output)
5783 (let ((coding-system-for-write ',encoding))
5784 (write-file ,file)))
5785 (or (ignore-errors (funcall ',post-process ,file)) ,file)))
5786 (let ((output (org-export-as
5787 backend subtreep visible-only body-only ext-plist)))
5788 (with-temp-buffer
5789 (insert output)
5790 (let ((coding-system-for-write encoding))
5791 (write-file file)))
5792 (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p output))
5793 (org-kill-new output))
5794 ;; Get proper return value.
5795 (or (and (functionp post-process) (funcall post-process file))
5796 file))))))
5798 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
5799 "Return output file's name according to buffer specifications.
5801 EXTENSION is a string representing the output file extension,
5802 with the leading dot.
5804 With a non-nil optional argument SUBTREEP, try to determine
5805 output file's name by looking for \"EXPORT_FILE_NAME\" property
5806 of subtree at point.
5808 When optional argument PUB-DIR is set, use it as the publishing
5809 directory.
5811 When optional argument VISIBLE-ONLY is non-nil, don't export
5812 contents of hidden elements.
5814 Return file name as a string."
5815 (let* ((visited-file (buffer-file-name (buffer-base-buffer)))
5816 (base-name
5817 ;; File name may come from EXPORT_FILE_NAME subtree
5818 ;; property, assuming point is at beginning of said
5819 ;; sub-tree.
5820 (file-name-sans-extension
5821 (or (and subtreep
5822 (org-entry-get
5823 (save-excursion
5824 (ignore-errors (org-back-to-heading) (point)))
5825 "EXPORT_FILE_NAME" t))
5826 ;; File name may be extracted from buffer's associated
5827 ;; file, if any.
5828 (and visited-file (file-name-nondirectory visited-file))
5829 ;; Can't determine file name on our own: Ask user.
5830 (let ((read-file-name-function
5831 (and org-completion-use-ido 'ido-read-file-name)))
5832 (read-file-name
5833 "Output file: " pub-dir nil nil nil
5834 (lambda (name)
5835 (string= (file-name-extension name t) extension)))))))
5836 (output-file
5837 ;; Build file name. Enforce EXTENSION over whatever user
5838 ;; may have come up with. PUB-DIR, if defined, always has
5839 ;; precedence over any provided path.
5840 (cond
5841 (pub-dir
5842 (concat (file-name-as-directory pub-dir)
5843 (file-name-nondirectory base-name)
5844 extension))
5845 ((file-name-absolute-p base-name) (concat base-name extension))
5846 (t (concat (file-name-as-directory ".") base-name extension)))))
5847 ;; If writing to OUTPUT-FILE would overwrite original file, append
5848 ;; EXTENSION another time to final name.
5849 (if (and visited-file (org-file-equal-p visited-file output-file))
5850 (concat output-file extension)
5851 output-file)))
5853 (defun org-export-add-to-stack (source backend &optional process)
5854 "Add a new result to export stack if not present already.
5856 SOURCE is a buffer or a file name containing export results.
5857 BACKEND is a symbol representing export back-end used to generate
5860 Entries already pointing to SOURCE and unavailable entries are
5861 removed beforehand. Return the new stack."
5862 (setq org-export-stack-contents
5863 (cons (list source backend (or process (current-time)))
5864 (org-export-stack-remove source))))
5866 (defun org-export-stack ()
5867 "Menu for asynchronous export results and running processes."
5868 (interactive)
5869 (let ((buffer (get-buffer-create "*Org Export Stack*")))
5870 (set-buffer buffer)
5871 (when (zerop (buffer-size)) (org-export-stack-mode))
5872 (org-export-stack-refresh)
5873 (pop-to-buffer buffer))
5874 (message "Type \"q\" to quit, \"?\" for help"))
5876 (defun org-export--stack-source-at-point ()
5877 "Return source from export results at point in stack."
5878 (let ((source (car (nth (1- (org-current-line)) org-export-stack-contents))))
5879 (if (not source) (error "Source unavailable, please refresh buffer")
5880 (let ((source-name (if (stringp source) source (buffer-name source))))
5881 (if (save-excursion
5882 (beginning-of-line)
5883 (looking-at (concat ".* +" (regexp-quote source-name) "$")))
5884 source
5885 ;; SOURCE is not consistent with current line. The stack
5886 ;; view is outdated.
5887 (error "Source unavailable; type `g' to update buffer"))))))
5889 (defun org-export-stack-clear ()
5890 "Remove all entries from export stack."
5891 (interactive)
5892 (setq org-export-stack-contents nil))
5894 (defun org-export-stack-refresh (&rest dummy)
5895 "Refresh the asynchronous export stack.
5896 DUMMY is ignored. Unavailable sources are removed from the list.
5897 Return the new stack."
5898 (let ((inhibit-read-only t))
5899 (org-preserve-lc
5900 (erase-buffer)
5901 (insert (concat
5902 (let ((counter 0))
5903 (mapconcat
5904 (lambda (entry)
5905 (let ((proc-p (processp (nth 2 entry))))
5906 (concat
5907 ;; Back-end.
5908 (format " %-12s " (or (nth 1 entry) ""))
5909 ;; Age.
5910 (let ((data (nth 2 entry)))
5911 (if proc-p (format " %6s " (process-status data))
5912 ;; Compute age of the results.
5913 (org-format-seconds
5914 "%4h:%.2m "
5915 (float-time (time-since data)))))
5916 ;; Source.
5917 (format " %s"
5918 (let ((source (car entry)))
5919 (if (stringp source) source
5920 (buffer-name source)))))))
5921 ;; Clear stack from exited processes, dead buffers or
5922 ;; non-existent files.
5923 (setq org-export-stack-contents
5924 (org-remove-if-not
5925 (lambda (el)
5926 (if (processp (nth 2 el))
5927 (buffer-live-p (process-buffer (nth 2 el)))
5928 (let ((source (car el)))
5929 (if (bufferp source) (buffer-live-p source)
5930 (file-exists-p source)))))
5931 org-export-stack-contents)) "\n")))))))
5933 (defun org-export-stack-remove (&optional source)
5934 "Remove export results at point from stack.
5935 If optional argument SOURCE is non-nil, remove it instead."
5936 (interactive)
5937 (let ((source (or source (org-export--stack-source-at-point))))
5938 (setq org-export-stack-contents
5939 (org-remove-if (lambda (el) (equal (car el) source))
5940 org-export-stack-contents))))
5942 (defun org-export-stack-view (&optional in-emacs)
5943 "View export results at point in stack.
5944 With an optional prefix argument IN-EMACS, force viewing files
5945 within Emacs."
5946 (interactive "P")
5947 (let ((source (org-export--stack-source-at-point)))
5948 (cond ((processp source)
5949 (org-switch-to-buffer-other-window (process-buffer source)))
5950 ((bufferp source) (org-switch-to-buffer-other-window source))
5951 (t (org-open-file source in-emacs)))))
5953 (defvar org-export-stack-mode-map
5954 (let ((km (make-sparse-keymap)))
5955 (define-key km " " 'next-line)
5956 (define-key km "n" 'next-line)
5957 (define-key km "\C-n" 'next-line)
5958 (define-key km [down] 'next-line)
5959 (define-key km "p" 'previous-line)
5960 (define-key km "\C-p" 'previous-line)
5961 (define-key km "\C-?" 'previous-line)
5962 (define-key km [up] 'previous-line)
5963 (define-key km "C" 'org-export-stack-clear)
5964 (define-key km "v" 'org-export-stack-view)
5965 (define-key km (kbd "RET") 'org-export-stack-view)
5966 (define-key km "d" 'org-export-stack-remove)
5968 "Keymap for Org Export Stack.")
5970 (define-derived-mode org-export-stack-mode special-mode "Org-Stack"
5971 "Mode for displaying asynchronous export stack.
5973 Type \\[org-export-stack] to visualize the asynchronous export
5974 stack.
5976 In an Org Export Stack buffer, use \\<org-export-stack-mode-map>\\[org-export-stack-view] to view export output
5977 on current line, \\[org-export-stack-remove] to remove it from the stack and \\[org-export-stack-clear] to clear
5978 stack completely.
5980 Removing entries in an Org Export Stack buffer doesn't affect
5981 files or buffers, only the display.
5983 \\{org-export-stack-mode-map}"
5984 (abbrev-mode 0)
5985 (auto-fill-mode 0)
5986 (setq buffer-read-only t
5987 buffer-undo-list t
5988 truncate-lines t
5989 header-line-format
5990 '(:eval
5991 (format " %-12s | %6s | %s" "Back-End" "Age" "Source")))
5992 (org-add-hook 'post-command-hook 'org-export-stack-refresh nil t)
5993 (set (make-local-variable 'revert-buffer-function)
5994 'org-export-stack-refresh))
5998 ;;; The Dispatcher
6000 ;; `org-export-dispatch' is the standard interactive way to start an
6001 ;; export process. It uses `org-export--dispatch-ui' as a subroutine
6002 ;; for its interface, which, in turn, delegates response to key
6003 ;; pressed to `org-export--dispatch-action'.
6005 ;;;###autoload
6006 (defun org-export-dispatch (&optional arg)
6007 "Export dispatcher for Org mode.
6009 It provides an access to common export related tasks in a buffer.
6010 Its interface comes in two flavors: standard and expert.
6012 While both share the same set of bindings, only the former
6013 displays the valid keys associations in a dedicated buffer.
6014 Scrolling (resp. line-wise motion) in this buffer is done with
6015 SPC and DEL (resp. C-n and C-p) keys.
6017 Set variable `org-export-dispatch-use-expert-ui' to switch to one
6018 flavor or the other.
6020 When ARG is \\[universal-argument], repeat the last export action, with the same set
6021 of options used back then, on the current buffer.
6023 When ARG is \\[universal-argument] \\[universal-argument], display the asynchronous export stack."
6024 (interactive "P")
6025 (let* ((input
6026 (cond ((equal arg '(16)) '(stack))
6027 ((and arg org-export-dispatch-last-action))
6028 (t (save-window-excursion
6029 (unwind-protect
6030 (progn
6031 ;; Remember where we are
6032 (move-marker org-export-dispatch-last-position
6033 (point)
6034 (org-base-buffer (current-buffer)))
6035 ;; Get and store an export command
6036 (setq org-export-dispatch-last-action
6037 (org-export--dispatch-ui
6038 (list org-export-initial-scope
6039 (and org-export-in-background 'async))
6041 org-export-dispatch-use-expert-ui)))
6042 (and (get-buffer "*Org Export Dispatcher*")
6043 (kill-buffer "*Org Export Dispatcher*")))))))
6044 (action (car input))
6045 (optns (cdr input)))
6046 (unless (memq 'subtree optns)
6047 (move-marker org-export-dispatch-last-position nil))
6048 (case action
6049 ;; First handle special hard-coded actions.
6050 (template (org-export-insert-default-template nil optns))
6051 (stack (org-export-stack))
6052 (publish-current-file
6053 (org-publish-current-file (memq 'force optns) (memq 'async optns)))
6054 (publish-current-project
6055 (org-publish-current-project (memq 'force optns) (memq 'async optns)))
6056 (publish-choose-project
6057 (org-publish (assoc (org-icompleting-read
6058 "Publish project: "
6059 org-publish-project-alist nil t)
6060 org-publish-project-alist)
6061 (memq 'force optns)
6062 (memq 'async optns)))
6063 (publish-all (org-publish-all (memq 'force optns) (memq 'async optns)))
6064 (otherwise
6065 (save-excursion
6066 (when arg
6067 ;; Repeating command, maybe move cursor to restore subtree
6068 ;; context.
6069 (if (eq (marker-buffer org-export-dispatch-last-position)
6070 (org-base-buffer (current-buffer)))
6071 (goto-char org-export-dispatch-last-position)
6072 ;; We are in a different buffer, forget position.
6073 (move-marker org-export-dispatch-last-position nil)))
6074 (funcall action
6075 ;; Return a symbol instead of a list to ease
6076 ;; asynchronous export macro use.
6077 (and (memq 'async optns) t)
6078 (and (memq 'subtree optns) t)
6079 (and (memq 'visible optns) t)
6080 (and (memq 'body optns) t)))))))
6082 (defun org-export--dispatch-ui (options first-key expertp)
6083 "Handle interface for `org-export-dispatch'.
6085 OPTIONS is a list containing current interactive options set for
6086 export. It can contain any of the following symbols:
6087 `body' toggles a body-only export
6088 `subtree' restricts export to current subtree
6089 `visible' restricts export to visible part of buffer.
6090 `force' force publishing files.
6091 `async' use asynchronous export process
6093 FIRST-KEY is the key pressed to select the first level menu. It
6094 is nil when this menu hasn't been selected yet.
6096 EXPERTP, when non-nil, triggers expert UI. In that case, no help
6097 buffer is provided, but indications about currently active
6098 options are given in the prompt. Moreover, \[?] allows to switch
6099 back to standard interface."
6100 (let* ((fontify-key
6101 (lambda (key &optional access-key)
6102 ;; Fontify KEY string. Optional argument ACCESS-KEY, when
6103 ;; non-nil is the required first-level key to activate
6104 ;; KEY. When its value is t, activate KEY independently
6105 ;; on the first key, if any. A nil value means KEY will
6106 ;; only be activated at first level.
6107 (if (or (eq access-key t) (eq access-key first-key))
6108 (org-propertize key 'face 'org-warning)
6109 key)))
6110 (fontify-value
6111 (lambda (value)
6112 ;; Fontify VALUE string.
6113 (org-propertize value 'face 'font-lock-variable-name-face)))
6114 ;; Prepare menu entries by extracting them from registered
6115 ;; back-ends and sorting them by access key and by ordinal,
6116 ;; if any.
6117 (entries
6118 (sort (sort (delq nil
6119 (mapcar 'org-export-backend-menu
6120 org-export--registered-backends))
6121 (lambda (a b)
6122 (let ((key-a (nth 1 a))
6123 (key-b (nth 1 b)))
6124 (cond ((and (numberp key-a) (numberp key-b))
6125 (< key-a key-b))
6126 ((numberp key-b) t)))))
6127 'car-less-than-car))
6128 ;; Compute a list of allowed keys based on the first key
6129 ;; pressed, if any. Some keys
6130 ;; (?^B, ?^V, ?^S, ?^F, ?^A, ?&, ?# and ?q) are always
6131 ;; available.
6132 (allowed-keys
6133 (nconc (list 2 22 19 6 1)
6134 (if (not first-key) (org-uniquify (mapcar 'car entries))
6135 (let (sub-menu)
6136 (dolist (entry entries (sort (mapcar 'car sub-menu) '<))
6137 (when (eq (car entry) first-key)
6138 (setq sub-menu (append (nth 2 entry) sub-menu))))))
6139 (cond ((eq first-key ?P) (list ?f ?p ?x ?a))
6140 ((not first-key) (list ?P)))
6141 (list ?& ?#)
6142 (when expertp (list ??))
6143 (list ?q)))
6144 ;; Build the help menu for standard UI.
6145 (help
6146 (unless expertp
6147 (concat
6148 ;; Options are hard-coded.
6149 (format "[%s] Body only: %s [%s] Visible only: %s
6150 \[%s] Export scope: %s [%s] Force publishing: %s
6151 \[%s] Async export: %s\n\n"
6152 (funcall fontify-key "C-b" t)
6153 (funcall fontify-value
6154 (if (memq 'body options) "On " "Off"))
6155 (funcall fontify-key "C-v" t)
6156 (funcall fontify-value
6157 (if (memq 'visible options) "On " "Off"))
6158 (funcall fontify-key "C-s" t)
6159 (funcall fontify-value
6160 (if (memq 'subtree options) "Subtree" "Buffer "))
6161 (funcall fontify-key "C-f" t)
6162 (funcall fontify-value
6163 (if (memq 'force options) "On " "Off"))
6164 (funcall fontify-key "C-a" t)
6165 (funcall fontify-value
6166 (if (memq 'async options) "On " "Off")))
6167 ;; Display registered back-end entries. When a key
6168 ;; appears for the second time, do not create another
6169 ;; entry, but append its sub-menu to existing menu.
6170 (let (last-key)
6171 (mapconcat
6172 (lambda (entry)
6173 (let ((top-key (car entry)))
6174 (concat
6175 (unless (eq top-key last-key)
6176 (setq last-key top-key)
6177 (format "\n[%s] %s\n"
6178 (funcall fontify-key (char-to-string top-key))
6179 (nth 1 entry)))
6180 (let ((sub-menu (nth 2 entry)))
6181 (unless (functionp sub-menu)
6182 ;; Split sub-menu into two columns.
6183 (let ((index -1))
6184 (concat
6185 (mapconcat
6186 (lambda (sub-entry)
6187 (incf index)
6188 (format
6189 (if (zerop (mod index 2)) " [%s] %-26s"
6190 "[%s] %s\n")
6191 (funcall fontify-key
6192 (char-to-string (car sub-entry))
6193 top-key)
6194 (nth 1 sub-entry)))
6195 sub-menu "")
6196 (when (zerop (mod index 2)) "\n"))))))))
6197 entries ""))
6198 ;; Publishing menu is hard-coded.
6199 (format "\n[%s] Publish
6200 [%s] Current file [%s] Current project
6201 [%s] Choose project [%s] All projects\n\n\n"
6202 (funcall fontify-key "P")
6203 (funcall fontify-key "f" ?P)
6204 (funcall fontify-key "p" ?P)
6205 (funcall fontify-key "x" ?P)
6206 (funcall fontify-key "a" ?P))
6207 (format "[%s] Export stack [%s] Insert template\n"
6208 (funcall fontify-key "&" t)
6209 (funcall fontify-key "#" t))
6210 (format "[%s] %s"
6211 (funcall fontify-key "q" t)
6212 (if first-key "Main menu" "Exit")))))
6213 ;; Build prompts for both standard and expert UI.
6214 (standard-prompt (unless expertp "Export command: "))
6215 (expert-prompt
6216 (when expertp
6217 (format
6218 "Export command (C-%s%s%s%s%s) [%s]: "
6219 (if (memq 'body options) (funcall fontify-key "b" t) "b")
6220 (if (memq 'visible options) (funcall fontify-key "v" t) "v")
6221 (if (memq 'subtree options) (funcall fontify-key "s" t) "s")
6222 (if (memq 'force options) (funcall fontify-key "f" t) "f")
6223 (if (memq 'async options) (funcall fontify-key "a" t) "a")
6224 (mapconcat (lambda (k)
6225 ;; Strip control characters.
6226 (unless (< k 27) (char-to-string k)))
6227 allowed-keys "")))))
6228 ;; With expert UI, just read key with a fancy prompt. In standard
6229 ;; UI, display an intrusive help buffer.
6230 (if expertp
6231 (org-export--dispatch-action
6232 expert-prompt allowed-keys entries options first-key expertp)
6233 ;; At first call, create frame layout in order to display menu.
6234 (unless (get-buffer "*Org Export Dispatcher*")
6235 (delete-other-windows)
6236 (org-switch-to-buffer-other-window
6237 (get-buffer-create "*Org Export Dispatcher*"))
6238 (setq cursor-type nil
6239 header-line-format "Use SPC, DEL, C-n or C-p to navigate.")
6240 ;; Make sure that invisible cursor will not highlight square
6241 ;; brackets.
6242 (set-syntax-table (copy-syntax-table))
6243 (modify-syntax-entry ?\[ "w"))
6244 ;; At this point, the buffer containing the menu exists and is
6245 ;; visible in the current window. So, refresh it.
6246 (with-current-buffer "*Org Export Dispatcher*"
6247 ;; Refresh help. Maintain display continuity by re-visiting
6248 ;; previous window position.
6249 (let ((pos (window-start)))
6250 (erase-buffer)
6251 (insert help)
6252 (set-window-start nil pos)))
6253 (org-fit-window-to-buffer)
6254 (org-export--dispatch-action
6255 standard-prompt allowed-keys entries options first-key expertp))))
6257 (defun org-export--dispatch-action
6258 (prompt allowed-keys entries options first-key expertp)
6259 "Read a character from command input and act accordingly.
6261 PROMPT is the displayed prompt, as a string. ALLOWED-KEYS is
6262 a list of characters available at a given step in the process.
6263 ENTRIES is a list of menu entries. OPTIONS, FIRST-KEY and
6264 EXPERTP are the same as defined in `org-export--dispatch-ui',
6265 which see.
6267 Toggle export options when required. Otherwise, return value is
6268 a list with action as CAR and a list of interactive export
6269 options as CDR."
6270 (let (key)
6271 ;; Scrolling: when in non-expert mode, act on motion keys (C-n,
6272 ;; C-p, SPC, DEL).
6273 (while (and (setq key (read-char-exclusive prompt))
6274 (not expertp)
6275 (memq key '(14 16 ?\s ?\d)))
6276 (case key
6277 (14 (if (not (pos-visible-in-window-p (point-max)))
6278 (ignore-errors (scroll-up 1))
6279 (message "End of buffer")
6280 (sit-for 1)))
6281 (16 (if (not (pos-visible-in-window-p (point-min)))
6282 (ignore-errors (scroll-down 1))
6283 (message "Beginning of buffer")
6284 (sit-for 1)))
6285 (?\s (if (not (pos-visible-in-window-p (point-max)))
6286 (scroll-up nil)
6287 (message "End of buffer")
6288 (sit-for 1)))
6289 (?\d (if (not (pos-visible-in-window-p (point-min)))
6290 (scroll-down nil)
6291 (message "Beginning of buffer")
6292 (sit-for 1)))))
6293 (cond
6294 ;; Ignore undefined associations.
6295 ((not (memq key allowed-keys))
6296 (ding)
6297 (unless expertp (message "Invalid key") (sit-for 1))
6298 (org-export--dispatch-ui options first-key expertp))
6299 ;; q key at first level aborts export. At second level, cancel
6300 ;; first key instead.
6301 ((eq key ?q) (if (not first-key) (error "Export aborted")
6302 (org-export--dispatch-ui options nil expertp)))
6303 ;; Help key: Switch back to standard interface if expert UI was
6304 ;; active.
6305 ((eq key ??) (org-export--dispatch-ui options first-key nil))
6306 ;; Send request for template insertion along with export scope.
6307 ((eq key ?#) (cons 'template (memq 'subtree options)))
6308 ;; Switch to asynchronous export stack.
6309 ((eq key ?&) '(stack))
6310 ;; Toggle options: C-b (2) C-v (22) C-s (19) C-f (6) C-a (1).
6311 ((memq key '(2 22 19 6 1))
6312 (org-export--dispatch-ui
6313 (let ((option (case key (2 'body) (22 'visible) (19 'subtree)
6314 (6 'force) (1 'async))))
6315 (if (memq option options) (remq option options)
6316 (cons option options)))
6317 first-key expertp))
6318 ;; Action selected: Send key and options back to
6319 ;; `org-export-dispatch'.
6320 ((or first-key (functionp (nth 2 (assq key entries))))
6321 (cons (cond
6322 ((not first-key) (nth 2 (assq key entries)))
6323 ;; Publishing actions are hard-coded. Send a special
6324 ;; signal to `org-export-dispatch'.
6325 ((eq first-key ?P)
6326 (case key
6327 (?f 'publish-current-file)
6328 (?p 'publish-current-project)
6329 (?x 'publish-choose-project)
6330 (?a 'publish-all)))
6331 ;; Return first action associated to FIRST-KEY + KEY
6332 ;; path. Indeed, derived backends can share the same
6333 ;; FIRST-KEY.
6334 (t (catch 'found
6335 (mapc (lambda (entry)
6336 (let ((match (assq key (nth 2 entry))))
6337 (when match (throw 'found (nth 2 match)))))
6338 (member (assq first-key entries) entries)))))
6339 options))
6340 ;; Otherwise, enter sub-menu.
6341 (t (org-export--dispatch-ui options key expertp)))))
6345 (provide 'ox)
6347 ;; Local variables:
6348 ;; generated-autoload-file: "org-loaddefs.el"
6349 ;; End:
6351 ;;; ox.el ends here