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