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