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