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