Extended org-export-default-language docstring
[org-mode.git] / lisp / ox.el
blob6531fa345bef546fbbccf4b5b01b545a9612f2a8
1 ;;; ox.el --- Generic Export Engine for Org Mode
3 ;; Copyright (C) 2012, 2013 Free Software Foundation, Inc.
5 ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
6 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; GNU Emacs is free software: you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation, either version 3 of the License, or
11 ;; (at your option) any later version.
13 ;; GNU Emacs is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 ;; GNU General Public License for more details.
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
21 ;;; Commentary:
23 ;; This library implements a generic export engine for Org, built on
24 ;; its syntactical parser: Org Elements.
26 ;; Besides that parser, the generic exporter is made of three distinct
27 ;; parts:
29 ;; - The communication channel consists in a property list, which is
30 ;; created and updated during the process. Its use is to offer
31 ;; every piece of information, would it be about initial environment
32 ;; or contextual data, all in a single place. The exhaustive list
33 ;; of properties is given in "The Communication Channel" section of
34 ;; this file.
36 ;; - The transcoder walks the parse tree, ignores or treat as plain
37 ;; text elements and objects according to export options, and
38 ;; eventually calls back-end specific functions to do the real
39 ;; transcoding, concatenating their return value along the way.
41 ;; - The filter system is activated at the very beginning and the very
42 ;; end of the export process, and each time an element or an object
43 ;; has been converted. It is the entry point to fine-tune standard
44 ;; output from back-end transcoders. See "The Filter System"
45 ;; section for more information.
47 ;; The core function is `org-export-as'. It returns the transcoded
48 ;; buffer as a string.
50 ;; An export back-end is defined with `org-export-define-backend',
51 ;; which defines one mandatory information: his translation table.
52 ;; Its value is an alist whose keys are elements and objects types and
53 ;; values translator functions. See function's docstring for more
54 ;; information about translators.
56 ;; Optionally, `org-export-define-backend' can also support specific
57 ;; buffer keywords, OPTION keyword's items and filters. Also refer to
58 ;; function documentation for more information.
60 ;; If the new back-end shares most properties with another one,
61 ;; `org-export-define-derived-backend' can be used to simplify the
62 ;; process.
64 ;; Any back-end can define its own variables. Among them, those
65 ;; customizable should belong to the `org-export-BACKEND' group.
67 ;; Tools for common tasks across back-ends are implemented in the
68 ;; following part of the file.
70 ;; Then, a wrapper macro for asynchronous export,
71 ;; `org-export-async-start', along with tools to display results. are
72 ;; given in the penultimate part.
74 ;; Eventually, a dispatcher (`org-export-dispatch') for standard
75 ;; back-ends is provided in the last one.
77 ;;; Code:
79 (eval-when-compile (require 'cl))
80 (require 'org-element)
81 (require 'org-macro)
82 (require 'ob-exp)
84 (declare-function org-publish "ox-publish" (project &optional force async))
85 (declare-function org-publish-all "ox-publish" (&optional force async))
86 (declare-function
87 org-publish-current-file "ox-publish" (&optional force async))
88 (declare-function org-publish-current-project "ox-publish"
89 (&optional force async))
91 (defvar org-publish-project-alist)
92 (defvar org-table-number-fraction)
93 (defvar org-table-number-regexp)
97 ;;; Internal Variables
99 ;; Among internal variables, the most important is
100 ;; `org-export-options-alist'. This variable define the global export
101 ;; options, shared between every exporter, and how they are acquired.
103 (defconst org-export-max-depth 19
104 "Maximum nesting depth for headlines, counting from 0.")
106 (defconst org-export-options-alist
107 '((:author "AUTHOR" nil user-full-name t)
108 (:creator "CREATOR" nil org-export-creator-string)
109 (:date "DATE" nil nil t)
110 (:description "DESCRIPTION" nil nil newline)
111 (:email "EMAIL" nil user-mail-address t)
112 (:exclude-tags "EXCLUDE_TAGS" nil org-export-exclude-tags split)
113 (:headline-levels nil "H" org-export-headline-levels)
114 (:keywords "KEYWORDS" nil nil space)
115 (:language "LANGUAGE" nil org-export-default-language t)
116 (:preserve-breaks nil "\\n" org-export-preserve-breaks)
117 (:section-numbers nil "num" org-export-with-section-numbers)
118 (:select-tags "SELECT_TAGS" nil org-export-select-tags split)
119 (:time-stamp-file nil "timestamp" org-export-time-stamp-file)
120 (:title "TITLE" nil org-export--default-title space)
121 (:with-archived-trees nil "arch" org-export-with-archived-trees)
122 (:with-author nil "author" org-export-with-author)
123 (:with-clocks nil "c" org-export-with-clocks)
124 (:with-creator nil "creator" org-export-with-creator)
125 (:with-date nil "date" org-export-with-date)
126 (:with-drawers nil "d" org-export-with-drawers)
127 (:with-email nil "email" org-export-with-email)
128 (:with-emphasize nil "*" org-export-with-emphasize)
129 (:with-entities nil "e" org-export-with-entities)
130 (:with-fixed-width nil ":" org-export-with-fixed-width)
131 (:with-footnotes nil "f" org-export-with-footnotes)
132 (:with-inlinetasks nil "inline" org-export-with-inlinetasks)
133 (:with-latex nil "tex" org-export-with-latex)
134 (:with-planning nil "p" org-export-with-planning)
135 (:with-priority nil "pri" org-export-with-priority)
136 (:with-smart-quotes nil "'" org-export-with-smart-quotes)
137 (:with-special-strings nil "-" org-export-with-special-strings)
138 (:with-statistics-cookies nil "stat" org-export-with-statistics-cookies)
139 (:with-sub-superscript nil "^" org-export-with-sub-superscripts)
140 (:with-toc nil "toc" org-export-with-toc)
141 (:with-tables nil "|" org-export-with-tables)
142 (:with-tags nil "tags" org-export-with-tags)
143 (:with-tasks nil "tasks" org-export-with-tasks)
144 (:with-timestamps nil "<" org-export-with-timestamps)
145 (:with-todo-keywords nil "todo" org-export-with-todo-keywords))
146 "Alist between export properties and ways to set them.
148 The CAR of the alist is the property name, and the CDR is a list
149 like (KEYWORD OPTION DEFAULT BEHAVIOUR) where:
151 KEYWORD is a string representing a buffer keyword, or nil. Each
152 property defined this way can also be set, during subtree
153 export, through a headline property named after the keyword
154 with the \"EXPORT_\" prefix (i.e. DATE keyword and EXPORT_DATE
155 property).
156 OPTION is a string that could be found in an #+OPTIONS: line.
157 DEFAULT is the default value for the property.
158 BEHAVIOUR determines how Org should handle multiple keywords for
159 the same property. It is a symbol among:
160 nil Keep old value and discard the new one.
161 t Replace old value with the new one.
162 `space' Concatenate the values, separating them with a space.
163 `newline' Concatenate the values, separating them with
164 a newline.
165 `split' Split values at white spaces, and cons them to the
166 previous list.
168 Values set through KEYWORD and OPTION have precedence over
169 DEFAULT.
171 All these properties should be back-end agnostic. Back-end
172 specific properties are set through `org-export-define-backend'.
173 Properties redefined there have precedence over these.")
175 (defconst org-export-special-keywords '("FILETAGS" "SETUPFILE" "OPTIONS")
176 "List of in-buffer keywords that require special treatment.
177 These keywords are not directly associated to a property. The
178 way they are handled must be hard-coded into
179 `org-export--get-inbuffer-options' function.")
181 (defconst org-export-filters-alist
182 '((:filter-bold . org-export-filter-bold-functions)
183 (:filter-babel-call . org-export-filter-babel-call-functions)
184 (:filter-center-block . org-export-filter-center-block-functions)
185 (:filter-clock . org-export-filter-clock-functions)
186 (:filter-code . org-export-filter-code-functions)
187 (:filter-comment . org-export-filter-comment-functions)
188 (:filter-comment-block . org-export-filter-comment-block-functions)
189 (:filter-diary-sexp . org-export-filter-diary-sexp-functions)
190 (:filter-drawer . org-export-filter-drawer-functions)
191 (:filter-dynamic-block . org-export-filter-dynamic-block-functions)
192 (:filter-entity . org-export-filter-entity-functions)
193 (:filter-example-block . org-export-filter-example-block-functions)
194 (:filter-export-block . org-export-filter-export-block-functions)
195 (:filter-export-snippet . org-export-filter-export-snippet-functions)
196 (:filter-final-output . org-export-filter-final-output-functions)
197 (:filter-fixed-width . org-export-filter-fixed-width-functions)
198 (:filter-footnote-definition . org-export-filter-footnote-definition-functions)
199 (:filter-footnote-reference . org-export-filter-footnote-reference-functions)
200 (:filter-headline . org-export-filter-headline-functions)
201 (:filter-horizontal-rule . org-export-filter-horizontal-rule-functions)
202 (:filter-inline-babel-call . org-export-filter-inline-babel-call-functions)
203 (:filter-inline-src-block . org-export-filter-inline-src-block-functions)
204 (:filter-inlinetask . org-export-filter-inlinetask-functions)
205 (:filter-italic . org-export-filter-italic-functions)
206 (:filter-item . org-export-filter-item-functions)
207 (:filter-keyword . org-export-filter-keyword-functions)
208 (:filter-latex-environment . org-export-filter-latex-environment-functions)
209 (:filter-latex-fragment . org-export-filter-latex-fragment-functions)
210 (:filter-line-break . org-export-filter-line-break-functions)
211 (:filter-link . org-export-filter-link-functions)
212 (:filter-node-property . org-export-filter-node-property-functions)
213 (:filter-options . org-export-filter-options-functions)
214 (:filter-paragraph . org-export-filter-paragraph-functions)
215 (:filter-parse-tree . org-export-filter-parse-tree-functions)
216 (:filter-plain-list . org-export-filter-plain-list-functions)
217 (:filter-plain-text . org-export-filter-plain-text-functions)
218 (:filter-planning . org-export-filter-planning-functions)
219 (:filter-property-drawer . org-export-filter-property-drawer-functions)
220 (:filter-quote-block . org-export-filter-quote-block-functions)
221 (:filter-quote-section . org-export-filter-quote-section-functions)
222 (:filter-radio-target . org-export-filter-radio-target-functions)
223 (:filter-section . org-export-filter-section-functions)
224 (:filter-special-block . org-export-filter-special-block-functions)
225 (:filter-src-block . org-export-filter-src-block-functions)
226 (:filter-statistics-cookie . org-export-filter-statistics-cookie-functions)
227 (:filter-strike-through . org-export-filter-strike-through-functions)
228 (:filter-subscript . org-export-filter-subscript-functions)
229 (:filter-superscript . org-export-filter-superscript-functions)
230 (:filter-table . org-export-filter-table-functions)
231 (:filter-table-cell . org-export-filter-table-cell-functions)
232 (:filter-table-row . org-export-filter-table-row-functions)
233 (:filter-target . org-export-filter-target-functions)
234 (:filter-timestamp . org-export-filter-timestamp-functions)
235 (:filter-underline . org-export-filter-underline-functions)
236 (:filter-verbatim . org-export-filter-verbatim-functions)
237 (:filter-verse-block . org-export-filter-verse-block-functions))
238 "Alist between filters properties and initial values.
240 The key of each association is a property name accessible through
241 the communication channel. Its value is a configurable global
242 variable defining initial filters.
244 This list is meant to install user specified filters. Back-end
245 developers may install their own filters using
246 `org-export-define-backend'. Filters defined there will always
247 be prepended to the current list, so they always get applied
248 first.")
250 (defconst org-export-default-inline-image-rule
251 `(("file" .
252 ,(format "\\.%s\\'"
253 (regexp-opt
254 '("png" "jpeg" "jpg" "gif" "tiff" "tif" "xbm"
255 "xpm" "pbm" "pgm" "ppm") t))))
256 "Default rule for link matching an inline image.
257 This rule applies to links with no description. By default, it
258 will be considered as an inline image if it targets a local file
259 whose extension is either \"png\", \"jpeg\", \"jpg\", \"gif\",
260 \"tiff\", \"tif\", \"xbm\", \"xpm\", \"pbm\", \"pgm\" or \"ppm\".
261 See `org-export-inline-image-p' for more information about
262 rules.")
264 (defvar org-export-async-debug nil
265 "Non-nil means asynchronous export process should leave data behind.
267 This data is found in the appropriate \"*Org Export Process*\"
268 buffer, and in files prefixed with \"org-export-process\" and
269 located in `temporary-file-directory'.
271 When non-nil, it will also set `debug-on-error' to a non-nil
272 value in the external process.")
274 (defvar org-export-stack-contents nil
275 "Record asynchronously generated export results and processes.
276 This is an alist: its CAR is the source of the
277 result (destination file or buffer for a finished process,
278 original buffer for a running one) and its CDR is a list
279 containing the back-end used, as a symbol, and either a process
280 or the time at which it finished. It is used to build the menu
281 from `org-export-stack'.")
283 (defvar org-export-registered-backends nil
284 "List of backends currently available in the exporter.
286 A backend is stored as a list where CAR is its name, as a symbol,
287 and CDR is a plist with the following properties:
288 `:filters-alist', `:menu-entry', `:options-alist' and
289 `:translate-alist'.
291 This variable is set with `org-export-define-backend' and
292 `org-export-define-derived-backend' functions.")
294 (defvar org-export-dispatch-last-action nil
295 "Last command called from the dispatcher.
296 The value should be a list. Its CAR is the action, as a symbol,
297 and its CDR is a list of export options.")
299 (defvar org-export-dispatch-last-position (make-marker)
300 "The position where the last export command was created using the dispatcher.
301 This marker will be used with `C-u C-c C-e' to make sure export repetition
302 uses the same subtree if the previous command was restricted to a subtree.")
305 ;;; User-configurable Variables
307 ;; Configuration for the masses.
309 ;; They should never be accessed directly, as their value is to be
310 ;; stored in a property list (cf. `org-export-options-alist').
311 ;; Back-ends will read their value from there instead.
313 (defgroup org-export nil
314 "Options for exporting Org mode files."
315 :tag "Org Export"
316 :group 'org)
318 (defgroup org-export-general nil
319 "General options for export engine."
320 :tag "Org Export General"
321 :group 'org-export)
323 (defcustom org-export-with-archived-trees 'headline
324 "Whether sub-trees with the ARCHIVE tag should be exported.
326 This can have three different values:
327 nil Do not export, pretend this tree is not present.
328 t Do export the entire tree.
329 `headline' Only export the headline, but skip the tree below it.
331 This option can also be set with the OPTIONS keyword,
332 e.g. \"arch:nil\"."
333 :group 'org-export-general
334 :type '(choice
335 (const :tag "Not at all" nil)
336 (const :tag "Headline only" headline)
337 (const :tag "Entirely" t)))
339 (defcustom org-export-with-author t
340 "Non-nil means insert author name into the exported file.
341 This option can also be set with the OPTIONS keyword,
342 e.g. \"author:nil\"."
343 :group 'org-export-general
344 :type 'boolean)
346 (defcustom org-export-with-clocks nil
347 "Non-nil means export CLOCK keywords.
348 This option can also be set with the OPTIONS keyword,
349 e.g. \"c:t\"."
350 :group 'org-export-general
351 :type 'boolean)
353 (defcustom org-export-with-creator 'comment
354 "Non-nil means the postamble should contain a creator sentence.
356 The sentence can be set in `org-export-creator-string' and
357 defaults to \"Generated by Org mode XX in Emacs XXX.\".
359 If the value is `comment' insert it as a comment."
360 :group 'org-export-general
361 :type '(choice
362 (const :tag "No creator sentence" nil)
363 (const :tag "Sentence as a comment" 'comment)
364 (const :tag "Insert the sentence" t)))
366 (defcustom org-export-with-date t
367 "Non-nil means insert date in the exported document.
368 This option can also be set with the OPTIONS keyword,
369 e.g. \"date:nil\"."
370 :group 'org-export-general
371 :type 'boolean)
373 (defcustom org-export-date-timestamp-format nil
374 "Time-stamp format string to use for DATE keyword.
376 The format string, when specified, only applies if date consists
377 in a single time-stamp. Otherwise its value will be ignored.
379 See `format-time-string' for details on how to build this
380 string."
381 :group 'org-export-general
382 :type '(choice
383 (string :tag "Time-stamp format string")
384 (const :tag "No format string" nil)))
386 (defcustom org-export-creator-string
387 (format "Emacs %s (Org mode %s)"
388 emacs-version
389 (if (fboundp 'org-version) (org-version) "unknown version"))
390 "Information about the creator of the document.
391 This option can also be set on with the CREATOR keyword."
392 :group 'org-export-general
393 :type '(string :tag "Creator string"))
395 (defcustom org-export-with-drawers '(not "LOGBOOK")
396 "Non-nil means export contents of standard drawers.
398 When t, all drawers are exported. This may also be a list of
399 drawer names to export. If that list starts with `not', only
400 drawers with such names will be ignored.
402 This variable doesn't apply to properties drawers.
404 This option can also be set with the OPTIONS keyword,
405 e.g. \"d:nil\"."
406 :group 'org-export-general
407 :version "24.4"
408 :package-version '(Org . "8.0")
409 :type '(choice
410 (const :tag "All drawers" t)
411 (const :tag "None" nil)
412 (repeat :tag "Selected drawers"
413 (string :tag "Drawer name"))
414 (list :tag "Ignored drawers"
415 (const :format "" not)
416 (repeat :tag "Specify names of drawers to ignore during export"
417 :inline t
418 (string :tag "Drawer name")))))
420 (defcustom org-export-with-email nil
421 "Non-nil means insert author email into the exported file.
422 This option can also be set with the OPTIONS keyword,
423 e.g. \"email:t\"."
424 :group 'org-export-general
425 :type 'boolean)
427 (defcustom org-export-with-emphasize t
428 "Non-nil means interpret *word*, /word/, _word_ and +word+.
430 If the export target supports emphasizing text, the word will be
431 typeset in bold, italic, with an underline or strike-through,
432 respectively.
434 This option can also be set with the OPTIONS keyword,
435 e.g. \"*:nil\"."
436 :group 'org-export-general
437 :type 'boolean)
439 (defcustom org-export-exclude-tags '("noexport")
440 "Tags that exclude a tree from export.
442 All trees carrying any of these tags will be excluded from
443 export. This is without condition, so even subtrees inside that
444 carry one of the `org-export-select-tags' will be removed.
446 This option can also be set with the EXCLUDE_TAGS keyword."
447 :group 'org-export-general
448 :type '(repeat (string :tag "Tag")))
450 (defcustom org-export-with-fixed-width t
451 "Non-nil means lines starting with \":\" will be in fixed width font.
453 This can be used to have pre-formatted text, fragments of code
454 etc. For example:
455 : ;; Some Lisp examples
456 : (while (defc cnt)
457 : (ding))
458 will be looking just like this in also HTML. See also the QUOTE
459 keyword. Not all export backends support this.
461 This option can also be set with the OPTIONS keyword,
462 e.g. \"::nil\"."
463 :group 'org-export-general
464 :type 'boolean)
466 (defcustom org-export-with-footnotes t
467 "Non-nil means Org footnotes should be exported.
468 This option can also be set with the OPTIONS keyword,
469 e.g. \"f:nil\"."
470 :group 'org-export-general
471 :type 'boolean)
473 (defcustom org-export-with-latex t
474 "Non-nil means process LaTeX environments and fragments.
476 This option can also be set with the OPTIONS line,
477 e.g. \"tex:verbatim\". Allowed values are:
479 nil Ignore math snippets.
480 `verbatim' Keep everything in verbatim.
481 t Allow export of math snippets."
482 :group 'org-export-general
483 :version "24.4"
484 :package-version '(Org . "8.0")
485 :type '(choice
486 (const :tag "Do not process math in any way" nil)
487 (const :tag "Interpret math snippets" t)
488 (const :tag "Leave math verbatim" verbatim)))
490 (defcustom org-export-headline-levels 3
491 "The last level which is still exported as a headline.
493 Inferior levels will usually produce itemize or enumerate lists
494 when exported, but back-end behaviour may differ.
496 This option can also be set with the OPTIONS keyword,
497 e.g. \"H:2\"."
498 :group 'org-export-general
499 :type 'integer)
501 (defcustom org-export-default-language "en"
502 "The default language for export and clocktable translations, as a string.
503 This may have an association in
504 `org-clock-clocktable-language-setup',
505 `org-export-smart-quotes-alist' and `org-export-dictionary'.
506 This option can also be set with the LANGUAGE keyword."
507 :group 'org-export-general
508 :type '(string :tag "Language"))
510 (defcustom org-export-preserve-breaks nil
511 "Non-nil means preserve all line breaks when exporting.
512 This option can also be set with the OPTIONS keyword,
513 e.g. \"\\n:t\"."
514 :group 'org-export-general
515 :type 'boolean)
517 (defcustom org-export-with-entities t
518 "Non-nil means interpret entities when exporting.
520 For example, HTML export converts \\alpha to &alpha; and \\AA to
521 &Aring;.
523 For a list of supported names, see the constant `org-entities'
524 and the user option `org-entities-user'.
526 This option can also be set with the OPTIONS keyword,
527 e.g. \"e:nil\"."
528 :group 'org-export-general
529 :type 'boolean)
531 (defcustom org-export-with-inlinetasks t
532 "Non-nil means inlinetasks should be exported.
533 This option can also be set with the OPTIONS keyword,
534 e.g. \"inline:nil\"."
535 :group 'org-export-general
536 :version "24.4"
537 :package-version '(Org . "8.0")
538 :type 'boolean)
540 (defcustom org-export-with-planning nil
541 "Non-nil means include planning info in export.
543 Planning info is the line containing either SCHEDULED:,
544 DEADLINE:, CLOSED: time-stamps, or a combination of them.
546 This option can also be set with the OPTIONS keyword,
547 e.g. \"p:t\"."
548 :group 'org-export-general
549 :version "24.4"
550 :package-version '(Org . "8.0")
551 :type 'boolean)
553 (defcustom org-export-with-priority nil
554 "Non-nil means include priority cookies in export.
555 This option can also be set with the OPTIONS keyword,
556 e.g. \"pri:t\"."
557 :group 'org-export-general
558 :type 'boolean)
560 (defcustom org-export-with-section-numbers t
561 "Non-nil means add section numbers to headlines when exporting.
563 When set to an integer n, numbering will only happen for
564 headlines whose relative level is higher or equal to n.
566 This option can also be set with the OPTIONS keyword,
567 e.g. \"num:t\"."
568 :group 'org-export-general
569 :type 'boolean)
571 (defcustom org-export-select-tags '("export")
572 "Tags that select a tree for export.
574 If any such tag is found in a buffer, all trees that do not carry
575 one of these tags will be ignored during export. Inside trees
576 that are selected like this, you can still deselect a subtree by
577 tagging it with one of the `org-export-exclude-tags'.
579 This option can also be set with the SELECT_TAGS keyword."
580 :group 'org-export-general
581 :type '(repeat (string :tag "Tag")))
583 (defcustom org-export-with-smart-quotes nil
584 "Non-nil means activate smart quotes during export.
585 This option can also be set with the OPTIONS keyword,
586 e.g., \"':t\".
588 When setting this to non-nil, you need to take care of
589 using the correct Babel package when exporting to LaTeX.
590 E.g., you can load Babel for french like this:
592 #+LATEX_HEADER: \\usepackage[french]{babel}"
593 :group 'org-export-general
594 :version "24.4"
595 :package-version '(Org . "8.0")
596 :type 'boolean)
598 (defcustom org-export-with-special-strings t
599 "Non-nil means interpret \"\\-\", \"--\" and \"---\" for export.
601 When this option is turned on, these strings will be exported as:
603 Org HTML LaTeX UTF-8
604 -----+----------+--------+-------
605 \\- &shy; \\-
606 -- &ndash; -- –
607 --- &mdash; --- —
608 ... &hellip; \\ldots …
610 This option can also be set with the OPTIONS keyword,
611 e.g. \"-:nil\"."
612 :group 'org-export-general
613 :type 'boolean)
615 (defcustom org-export-with-statistics-cookies t
616 "Non-nil means include statistics cookies in export.
617 This option can also be set with the OPTIONS keyword,
618 e.g. \"stat:nil\""
619 :group 'org-export-general
620 :version "24.4"
621 :package-version '(Org . "8.0")
622 :type 'boolean)
624 (defcustom org-export-with-sub-superscripts t
625 "Non-nil means interpret \"_\" and \"^\" for export.
627 When this option is turned on, you can use TeX-like syntax for
628 sub- and superscripts. Several characters after \"_\" or \"^\"
629 will be considered as a single item - so grouping with {} is
630 normally not needed. For example, the following things will be
631 parsed as single sub- or superscripts.
633 10^24 or 10^tau several digits will be considered 1 item.
634 10^-12 or 10^-tau a leading sign with digits or a word
635 x^2-y^3 will be read as x^2 - y^3, because items are
636 terminated by almost any nonword/nondigit char.
637 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
639 Still, ambiguity is possible - so when in doubt use {} to enclose
640 the sub/superscript. If you set this variable to the symbol
641 `{}', the braces are *required* in order to trigger
642 interpretations as sub/superscript. This can be helpful in
643 documents that need \"_\" frequently in plain text.
645 This option can also be set with the OPTIONS keyword,
646 e.g. \"^:nil\"."
647 :group 'org-export-general
648 :type '(choice
649 (const :tag "Interpret them" t)
650 (const :tag "Curly brackets only" {})
651 (const :tag "Do not interpret them" nil)))
653 (defcustom org-export-with-toc t
654 "Non-nil means create a table of contents in exported files.
656 The TOC contains headlines with levels up
657 to`org-export-headline-levels'. When an integer, include levels
658 up to N in the toc, this may then be different from
659 `org-export-headline-levels', but it will not be allowed to be
660 larger than the number of headline levels. When nil, no table of
661 contents is made.
663 This option can also be set with the OPTIONS keyword,
664 e.g. \"toc:nil\" or \"toc:3\"."
665 :group 'org-export-general
666 :type '(choice
667 (const :tag "No Table of Contents" nil)
668 (const :tag "Full Table of Contents" t)
669 (integer :tag "TOC to level")))
671 (defcustom org-export-with-tables t
672 "If non-nil, lines starting with \"|\" define a table.
673 For example:
675 | Name | Address | Birthday |
676 |-------------+----------+-----------|
677 | Arthur Dent | England | 29.2.2100 |
679 This option can also be set with the OPTIONS keyword,
680 e.g. \"|:nil\"."
681 :group 'org-export-general
682 :type 'boolean)
684 (defcustom org-export-with-tags t
685 "If nil, do not export tags, just remove them from headlines.
687 If this is the symbol `not-in-toc', tags will be removed from
688 table of contents entries, but still be shown in the headlines of
689 the document.
691 This option can also be set with the OPTIONS keyword,
692 e.g. \"tags:nil\"."
693 :group 'org-export-general
694 :type '(choice
695 (const :tag "Off" nil)
696 (const :tag "Not in TOC" not-in-toc)
697 (const :tag "On" t)))
699 (defcustom org-export-with-tasks t
700 "Non-nil means include TODO items for export.
702 This may have the following values:
703 t include tasks independent of state.
704 `todo' include only tasks that are not yet done.
705 `done' include only tasks that are already done.
706 nil ignore all tasks.
707 list of keywords include tasks with these keywords.
709 This option can also be set with the OPTIONS keyword,
710 e.g. \"tasks:nil\"."
711 :group 'org-export-general
712 :type '(choice
713 (const :tag "All tasks" t)
714 (const :tag "No tasks" nil)
715 (const :tag "Not-done tasks" todo)
716 (const :tag "Only done tasks" done)
717 (repeat :tag "Specific TODO keywords"
718 (string :tag "Keyword"))))
720 (defcustom org-export-time-stamp-file t
721 "Non-nil means insert a time stamp into the exported file.
722 The time stamp shows when the file was created. This option can
723 also be set with the OPTIONS keyword, e.g. \"timestamp:nil\"."
724 :group 'org-export-general
725 :type 'boolean)
727 (defcustom org-export-with-timestamps t
728 "Non nil means allow timestamps in export.
730 It can be set to any of the following values:
731 t export all timestamps.
732 `active' export active timestamps only.
733 `inactive' export inactive timestamps only.
734 nil do not export timestamps
736 This only applies to timestamps isolated in a paragraph
737 containing only timestamps. Other timestamps are always
738 exported.
740 This option can also be set with the OPTIONS keyword, e.g.
741 \"<:nil\"."
742 :group 'org-export-general
743 :type '(choice
744 (const :tag "All timestamps" t)
745 (const :tag "Only active timestamps" active)
746 (const :tag "Only inactive timestamps" inactive)
747 (const :tag "No timestamp" nil)))
749 (defcustom org-export-with-todo-keywords t
750 "Non-nil means include TODO keywords in export.
751 When nil, remove all these keywords from the export. This option
752 can also be set with the OPTIONS keyword, e.g. \"todo:nil\"."
753 :group 'org-export-general
754 :type 'boolean)
756 (defcustom org-export-allow-bind-keywords nil
757 "Non-nil means BIND keywords can define local variable values.
758 This is a potential security risk, which is why the default value
759 is nil. You can also allow them through local buffer variables."
760 :group 'org-export-general
761 :version "24.4"
762 :package-version '(Org . "8.0")
763 :type 'boolean)
765 (defcustom org-export-snippet-translation-alist nil
766 "Alist between export snippets back-ends and exporter back-ends.
768 This variable allows to provide shortcuts for export snippets.
770 For example, with a value of '\(\(\"h\" . \"html\"\)\), the
771 HTML back-end will recognize the contents of \"@@h:<b>@@\" as
772 HTML code while every other back-end will ignore it."
773 :group 'org-export-general
774 :version "24.4"
775 :package-version '(Org . "8.0")
776 :type '(repeat
777 (cons (string :tag "Shortcut")
778 (string :tag "Back-end"))))
780 (defcustom org-export-coding-system nil
781 "Coding system for the exported file."
782 :group 'org-export-general
783 :version "24.4"
784 :package-version '(Org . "8.0")
785 :type 'coding-system)
787 (defcustom org-export-copy-to-kill-ring 'if-interactive
788 "Should we push exported content to the kill ring?"
789 :group 'org-export-general
790 :version "24.3"
791 :type '(choice
792 (const :tag "Always" t)
793 (const :tag "When export is done interactively" if-interactive)
794 (const :tag "Never" nil)))
796 (defcustom org-export-initial-scope 'buffer
797 "The initial scope when exporting with `org-export-dispatch'.
798 This variable can be either set to `buffer' or `subtree'."
799 :group 'org-export-general
800 :type '(choice
801 (const :tag "Export current buffer" buffer)
802 (const :tag "Export current subtree" subtree)))
804 (defcustom org-export-show-temporary-export-buffer t
805 "Non-nil means show buffer after exporting to temp buffer.
806 When Org exports to a file, the buffer visiting that file is ever
807 shown, but remains buried. However, when exporting to
808 a temporary buffer, that buffer is popped up in a second window.
809 When this variable is nil, the buffer remains buried also in
810 these cases."
811 :group 'org-export-general
812 :type 'boolean)
814 (defcustom org-export-in-background nil
815 "Non-nil means export and publishing commands will run in background.
816 Results from an asynchronous export are never displayed
817 automatically. But you can retrieve them with \\[org-export-stack]."
818 :group 'org-export-general
819 :version "24.4"
820 :package-version '(Org . "8.0")
821 :type 'boolean)
823 (defcustom org-export-async-init-file user-init-file
824 "File used to initialize external export process.
825 Value must be an absolute file name. It defaults to user's
826 initialization file. Though, a specific configuration makes the
827 process faster and the export more portable."
828 :group 'org-export-general
829 :version "24.4"
830 :package-version '(Org . "8.0")
831 :type '(file :must-match t))
833 (defcustom org-export-invisible-backends nil
834 "List of back-ends that shouldn't appear in the dispatcher.
836 Any back-end belonging to this list or derived from a back-end
837 belonging to it will not appear in the dispatcher menu.
839 Indeed, Org may require some export back-ends without notice. If
840 these modules are never to be used interactively, adding them
841 here will avoid cluttering the dispatcher menu."
842 :group 'org-export-general
843 :version "24.4"
844 :package-version '(Org . "8.0")
845 :type '(repeat (symbol :tag "Back-End")))
847 (defcustom org-export-dispatch-use-expert-ui nil
848 "Non-nil means using a non-intrusive `org-export-dispatch'.
849 In that case, no help buffer is displayed. Though, an indicator
850 for current export scope is added to the prompt (\"b\" when
851 output is restricted to body only, \"s\" when it is restricted to
852 the current subtree, \"v\" when only visible elements are
853 considered for export, \"f\" when publishing functions should be
854 passed the FORCE argument and \"a\" when the export should be
855 asynchronous). Also, \[?] allows to switch back to standard
856 mode."
857 :group 'org-export-general
858 :version "24.4"
859 :package-version '(Org . "8.0")
860 :type 'boolean)
864 ;;; Defining Back-ends
866 ;; `org-export-define-backend' is the standard way to define an export
867 ;; back-end. It allows to specify translators, filters, buffer
868 ;; options and a menu entry. If the new back-end shares translators
869 ;; with another back-end, `org-export-define-derived-backend' may be
870 ;; used instead.
872 ;; Internally, a back-end is stored as a list, of which CAR is the
873 ;; name of the back-end, as a symbol, and CDR a plist. Accessors to
874 ;; properties of a given back-end are: `org-export-backend-filters',
875 ;; `org-export-backend-menu', `org-export-backend-options' and
876 ;; `org-export-backend-translate-table'.
878 ;; Eventually `org-export-barf-if-invalid-backend' returns an error
879 ;; when a given back-end hasn't been registered yet.
881 (defun org-export-define-backend (backend translators &rest body)
882 "Define a new back-end BACKEND.
884 TRANSLATORS is an alist between object or element types and
885 functions handling them.
887 These functions should return a string without any trailing
888 space, or nil. They must accept three arguments: the object or
889 element itself, its contents or nil when it isn't recursive and
890 the property list used as a communication channel.
892 Contents, when not nil, are stripped from any global indentation
893 \(although the relative one is preserved). They also always end
894 with a single newline character.
896 If, for a given type, no function is found, that element or
897 object type will simply be ignored, along with any blank line or
898 white space at its end. The same will happen if the function
899 returns the nil value. If that function returns the empty
900 string, the type will be ignored, but the blank lines or white
901 spaces will be kept.
903 In addition to element and object types, one function can be
904 associated to the `template' (or `inner-template') symbol and
905 another one to the `plain-text' symbol.
907 The former returns the final transcoded string, and can be used
908 to add a preamble and a postamble to document's body. It must
909 accept two arguments: the transcoded string and the property list
910 containing export options. A function associated to `template'
911 will not be applied if export has option \"body-only\".
912 A function associated to `inner-template' is always applied.
914 The latter, when defined, is to be called on every text not
915 recognized as an element or an object. It must accept two
916 arguments: the text string and the information channel. It is an
917 appropriate place to protect special chars relative to the
918 back-end.
920 BODY can start with pre-defined keyword arguments. The following
921 keywords are understood:
923 :export-block
925 String, or list of strings, representing block names that
926 will not be parsed. This is used to specify blocks that will
927 contain raw code specific to the back-end. These blocks
928 still have to be handled by the relative `export-block' type
929 translator.
931 :filters-alist
933 Alist between filters and function, or list of functions,
934 specific to the back-end. See `org-export-filters-alist' for
935 a list of all allowed filters. Filters defined here
936 shouldn't make a back-end test, as it may prevent back-ends
937 derived from this one to behave properly.
939 :menu-entry
941 Menu entry for the export dispatcher. It should be a list
942 like:
944 '(KEY DESCRIPTION-OR-ORDINAL ACTION-OR-MENU)
946 where :
948 KEY is a free character selecting the back-end.
950 DESCRIPTION-OR-ORDINAL is either a string or a number.
952 If it is a string, is will be used to name the back-end in
953 its menu entry. If it is a number, the following menu will
954 be displayed as a sub-menu of the back-end with the same
955 KEY. Also, the number will be used to determine in which
956 order such sub-menus will appear (lowest first).
958 ACTION-OR-MENU is either a function or an alist.
960 If it is an action, it will be called with four
961 arguments (booleans): ASYNC, SUBTREEP, VISIBLE-ONLY and
962 BODY-ONLY. See `org-export-as' for further explanations on
963 some of them.
965 If it is an alist, associations should follow the
966 pattern:
968 '(KEY DESCRIPTION ACTION)
970 where KEY, DESCRIPTION and ACTION are described above.
972 Valid values include:
974 '(?m \"My Special Back-end\" my-special-export-function)
978 '(?l \"Export to LaTeX\"
979 \(?p \"As PDF file\" org-latex-export-to-pdf)
980 \(?o \"As PDF file and open\"
981 \(lambda (a s v b)
982 \(if a (org-latex-export-to-pdf t s v b)
983 \(org-open-file
984 \(org-latex-export-to-pdf nil s v b)))))))
986 or the following, which will be added to the previous
987 sub-menu,
989 '(?l 1
990 \((?B \"As TEX buffer (Beamer)\" org-beamer-export-as-latex)
991 \(?P \"As PDF file (Beamer)\" org-beamer-export-to-pdf)))
993 :options-alist
995 Alist between back-end specific properties introduced in
996 communication channel and how their value are acquired. See
997 `org-export-options-alist' for more information about
998 structure of the values."
999 (declare (indent 1))
1000 (let (export-block filters menu-entry options contents)
1001 (while (keywordp (car body))
1002 (case (pop body)
1003 (:export-block (let ((names (pop body)))
1004 (setq export-block
1005 (if (consp names) (mapcar 'upcase names)
1006 (list (upcase names))))))
1007 (:filters-alist (setq filters (pop body)))
1008 (:menu-entry (setq menu-entry (pop body)))
1009 (:options-alist (setq options (pop body)))
1010 (t (pop body))))
1011 (setq contents (append (list :translate-alist translators)
1012 (and filters (list :filters-alist filters))
1013 (and options (list :options-alist options))
1014 (and menu-entry (list :menu-entry menu-entry))))
1015 ;; Register back-end.
1016 (let ((registeredp (assq backend org-export-registered-backends)))
1017 (if registeredp (setcdr registeredp contents)
1018 (push (cons backend contents) org-export-registered-backends)))
1019 ;; Tell parser to not parse EXPORT-BLOCK blocks.
1020 (when export-block
1021 (mapc
1022 (lambda (name)
1023 (add-to-list 'org-element-block-name-alist
1024 `(,name . org-element-export-block-parser)))
1025 export-block))))
1027 (defun org-export-define-derived-backend (child parent &rest body)
1028 "Create a new back-end as a variant of an existing one.
1030 CHILD is the name of the derived back-end. PARENT is the name of
1031 the parent back-end.
1033 BODY can start with pre-defined keyword arguments. The following
1034 keywords are understood:
1036 :export-block
1038 String, or list of strings, representing block names that
1039 will not be parsed. This is used to specify blocks that will
1040 contain raw code specific to the back-end. These blocks
1041 still have to be handled by the relative `export-block' type
1042 translator.
1044 :filters-alist
1046 Alist of filters that will overwrite or complete filters
1047 defined in PARENT back-end. See `org-export-filters-alist'
1048 for a list of allowed filters.
1050 :menu-entry
1052 Menu entry for the export dispatcher. See
1053 `org-export-define-backend' for more information about the
1054 expected value.
1056 :options-alist
1058 Alist of back-end specific properties that will overwrite or
1059 complete those defined in PARENT back-end. Refer to
1060 `org-export-options-alist' for more information about
1061 structure of the values.
1063 :translate-alist
1065 Alist of element and object types and transcoders that will
1066 overwrite or complete transcode table from PARENT back-end.
1067 Refer to `org-export-define-backend' for detailed information
1068 about transcoders.
1070 As an example, here is how one could define \"my-latex\" back-end
1071 as a variant of `latex' back-end with a custom template function:
1073 \(org-export-define-derived-backend 'my-latex 'latex
1074 :translate-alist '((template . my-latex-template-fun)))
1076 The back-end could then be called with, for example:
1078 \(org-export-to-buffer 'my-latex \"*Test my-latex*\")"
1079 (declare (indent 2))
1080 (let (export-block filters menu-entry options translators contents)
1081 (while (keywordp (car body))
1082 (case (pop body)
1083 (:export-block (let ((names (pop body)))
1084 (setq export-block
1085 (if (consp names) (mapcar 'upcase names)
1086 (list (upcase names))))))
1087 (:filters-alist (setq filters (pop body)))
1088 (:menu-entry (setq menu-entry (pop body)))
1089 (:options-alist (setq options (pop body)))
1090 (:translate-alist (setq translators (pop body)))
1091 (t (pop body))))
1092 (setq contents (append
1093 (list :parent parent)
1094 (let ((p-table (org-export-backend-translate-table parent)))
1095 (list :translate-alist (append translators p-table)))
1096 (let ((p-filters (org-export-backend-filters parent)))
1097 (list :filters-alist (append filters p-filters)))
1098 (let ((p-options (org-export-backend-options parent)))
1099 (list :options-alist (append options p-options)))
1100 (and menu-entry (list :menu-entry menu-entry))))
1101 (org-export-barf-if-invalid-backend parent)
1102 ;; Register back-end.
1103 (let ((registeredp (assq child org-export-registered-backends)))
1104 (if registeredp (setcdr registeredp contents)
1105 (push (cons child contents) org-export-registered-backends)))
1106 ;; Tell parser to not parse EXPORT-BLOCK blocks.
1107 (when export-block
1108 (mapc
1109 (lambda (name)
1110 (add-to-list 'org-element-block-name-alist
1111 `(,name . org-element-export-block-parser)))
1112 export-block))))
1114 (defun org-export-backend-parent (backend)
1115 "Return back-end from which BACKEND is derived, or nil."
1116 (plist-get (cdr (assq backend org-export-registered-backends)) :parent))
1118 (defun org-export-backend-filters (backend)
1119 "Return filters for BACKEND."
1120 (plist-get (cdr (assq backend org-export-registered-backends))
1121 :filters-alist))
1123 (defun org-export-backend-menu (backend)
1124 "Return menu entry for BACKEND."
1125 (plist-get (cdr (assq backend org-export-registered-backends))
1126 :menu-entry))
1128 (defun org-export-backend-options (backend)
1129 "Return export options for BACKEND."
1130 (plist-get (cdr (assq backend org-export-registered-backends))
1131 :options-alist))
1133 (defun org-export-backend-translate-table (backend)
1134 "Return translate table for BACKEND."
1135 (plist-get (cdr (assq backend org-export-registered-backends))
1136 :translate-alist))
1138 (defun org-export-barf-if-invalid-backend (backend)
1139 "Signal an error if BACKEND isn't defined."
1140 (unless (org-export-backend-translate-table backend)
1141 (error "Unknown \"%s\" back-end: Aborting export" backend)))
1143 (defun org-export-derived-backend-p (backend &rest backends)
1144 "Non-nil if BACKEND is derived from one of BACKENDS."
1145 (let ((parent backend))
1146 (while (and (not (memq parent backends))
1147 (setq parent (org-export-backend-parent parent))))
1148 parent))
1152 ;;; The Communication Channel
1154 ;; During export process, every function has access to a number of
1155 ;; properties. They are of two types:
1157 ;; 1. Environment options are collected once at the very beginning of
1158 ;; the process, out of the original buffer and configuration.
1159 ;; Collecting them is handled by `org-export-get-environment'
1160 ;; function.
1162 ;; Most environment options are defined through the
1163 ;; `org-export-options-alist' variable.
1165 ;; 2. Tree properties are extracted directly from the parsed tree,
1166 ;; just before export, by `org-export-collect-tree-properties'.
1168 ;; Here is the full list of properties available during transcode
1169 ;; process, with their category and their value type.
1171 ;; + `:author' :: Author's name.
1172 ;; - category :: option
1173 ;; - type :: string
1175 ;; + `:back-end' :: Current back-end used for transcoding.
1176 ;; - category :: tree
1177 ;; - type :: symbol
1179 ;; + `:creator' :: String to write as creation information.
1180 ;; - category :: option
1181 ;; - type :: string
1183 ;; + `:date' :: String to use as date.
1184 ;; - category :: option
1185 ;; - type :: string
1187 ;; + `:description' :: Description text for the current data.
1188 ;; - category :: option
1189 ;; - type :: string
1191 ;; + `:email' :: Author's email.
1192 ;; - category :: option
1193 ;; - type :: string
1195 ;; + `:exclude-tags' :: Tags for exclusion of subtrees from export
1196 ;; process.
1197 ;; - category :: option
1198 ;; - type :: list of strings
1200 ;; + `:export-options' :: List of export options available for current
1201 ;; process.
1202 ;; - category :: none
1203 ;; - type :: list of symbols, among `subtree', `body-only' and
1204 ;; `visible-only'.
1206 ;; + `:exported-data' :: Hash table used for memoizing
1207 ;; `org-export-data'.
1208 ;; - category :: tree
1209 ;; - type :: hash table
1211 ;; + `:filetags' :: List of global tags for buffer. Used by
1212 ;; `org-export-get-tags' to get tags with inheritance.
1213 ;; - category :: option
1214 ;; - type :: list of strings
1216 ;; + `:footnote-definition-alist' :: Alist between footnote labels and
1217 ;; their definition, as parsed data. Only non-inlined footnotes
1218 ;; are represented in this alist. Also, every definition isn't
1219 ;; guaranteed to be referenced in the parse tree. The purpose of
1220 ;; this property is to preserve definitions from oblivion
1221 ;; (i.e. when the parse tree comes from a part of the original
1222 ;; buffer), it isn't meant for direct use in a back-end. To
1223 ;; retrieve a definition relative to a reference, use
1224 ;; `org-export-get-footnote-definition' instead.
1225 ;; - category :: option
1226 ;; - type :: alist (STRING . LIST)
1228 ;; + `:headline-levels' :: Maximum level being exported as an
1229 ;; headline. Comparison is done with the relative level of
1230 ;; headlines in the parse tree, not necessarily with their
1231 ;; actual level.
1232 ;; - category :: option
1233 ;; - type :: integer
1235 ;; + `:headline-offset' :: Difference between relative and real level
1236 ;; of headlines in the parse tree. For example, a value of -1
1237 ;; means a level 2 headline should be considered as level
1238 ;; 1 (cf. `org-export-get-relative-level').
1239 ;; - category :: tree
1240 ;; - type :: integer
1242 ;; + `:headline-numbering' :: Alist between headlines and their
1243 ;; numbering, as a list of numbers
1244 ;; (cf. `org-export-get-headline-number').
1245 ;; - category :: tree
1246 ;; - type :: alist (INTEGER . LIST)
1248 ;; + `:id-alist' :: Alist between ID strings and destination file's
1249 ;; path, relative to current directory. It is used by
1250 ;; `org-export-resolve-id-link' to resolve ID links targeting an
1251 ;; external file.
1252 ;; - category :: option
1253 ;; - type :: alist (STRING . STRING)
1255 ;; + `:ignore-list' :: List of elements and objects that should be
1256 ;; ignored during export.
1257 ;; - category :: tree
1258 ;; - type :: list of elements and objects
1260 ;; + `:input-file' :: Full path to input file, if any.
1261 ;; - category :: option
1262 ;; - type :: string or nil
1264 ;; + `:keywords' :: List of keywords attached to data.
1265 ;; - category :: option
1266 ;; - type :: string
1268 ;; + `:language' :: Default language used for translations.
1269 ;; - category :: option
1270 ;; - type :: string
1272 ;; + `:parse-tree' :: Whole parse tree, available at any time during
1273 ;; transcoding.
1274 ;; - category :: option
1275 ;; - type :: list (as returned by `org-element-parse-buffer')
1277 ;; + `:preserve-breaks' :: Non-nil means transcoding should preserve
1278 ;; all line breaks.
1279 ;; - category :: option
1280 ;; - type :: symbol (nil, t)
1282 ;; + `:section-numbers' :: Non-nil means transcoding should add
1283 ;; section numbers to headlines.
1284 ;; - category :: option
1285 ;; - type :: symbol (nil, t)
1287 ;; + `:select-tags' :: List of tags enforcing inclusion of sub-trees
1288 ;; in transcoding. When such a tag is present, subtrees without
1289 ;; it are de facto excluded from the process. See
1290 ;; `use-select-tags'.
1291 ;; - category :: option
1292 ;; - type :: list of strings
1294 ;; + `:time-stamp-file' :: Non-nil means transcoding should insert
1295 ;; a time stamp in the output.
1296 ;; - category :: option
1297 ;; - type :: symbol (nil, t)
1299 ;; + `:translate-alist' :: Alist between element and object types and
1300 ;; transcoding functions relative to the current back-end.
1301 ;; Special keys `inner-template', `template' and `plain-text' are
1302 ;; also possible.
1303 ;; - category :: option
1304 ;; - type :: alist (SYMBOL . FUNCTION)
1306 ;; + `:with-archived-trees' :: Non-nil when archived subtrees should
1307 ;; also be transcoded. If it is set to the `headline' symbol,
1308 ;; only the archived headline's name is retained.
1309 ;; - category :: option
1310 ;; - type :: symbol (nil, t, `headline')
1312 ;; + `:with-author' :: Non-nil means author's name should be included
1313 ;; in the output.
1314 ;; - category :: option
1315 ;; - type :: symbol (nil, t)
1317 ;; + `:with-clocks' :: Non-nil means clock keywords should be exported.
1318 ;; - category :: option
1319 ;; - type :: symbol (nil, t)
1321 ;; + `:with-creator' :: Non-nil means a creation sentence should be
1322 ;; inserted at the end of the transcoded string. If the value
1323 ;; is `comment', it should be commented.
1324 ;; - category :: option
1325 ;; - type :: symbol (`comment', nil, t)
1327 ;; + `:with-date' :: Non-nil means output should contain a date.
1328 ;; - category :: option
1329 ;; - type :. symbol (nil, t)
1331 ;; + `:with-drawers' :: Non-nil means drawers should be exported. If
1332 ;; its value is a list of names, only drawers with such names
1333 ;; will be transcoded. If that list starts with `not', drawer
1334 ;; with these names will be skipped.
1335 ;; - category :: option
1336 ;; - type :: symbol (nil, t) or list of strings
1338 ;; + `:with-email' :: Non-nil means output should contain author's
1339 ;; email.
1340 ;; - category :: option
1341 ;; - type :: symbol (nil, t)
1343 ;; + `:with-emphasize' :: Non-nil means emphasized text should be
1344 ;; interpreted.
1345 ;; - category :: option
1346 ;; - type :: symbol (nil, t)
1348 ;; + `:with-fixed-width' :: Non-nil if transcoder should interpret
1349 ;; strings starting with a colon as a fixed-with (verbatim) area.
1350 ;; - category :: option
1351 ;; - type :: symbol (nil, t)
1353 ;; + `:with-footnotes' :: Non-nil if transcoder should interpret
1354 ;; footnotes.
1355 ;; - category :: option
1356 ;; - type :: symbol (nil, t)
1358 ;; + `:with-latex' :: Non-nil means `latex-environment' elements and
1359 ;; `latex-fragment' objects should appear in export output. When
1360 ;; this property is set to `verbatim', they will be left as-is.
1361 ;; - category :: option
1362 ;; - type :: symbol (`verbatim', nil, t)
1364 ;; + `:with-planning' :: Non-nil means transcoding should include
1365 ;; planning info.
1366 ;; - category :: option
1367 ;; - type :: symbol (nil, t)
1369 ;; + `:with-priority' :: Non-nil means transcoding should include
1370 ;; priority cookies.
1371 ;; - category :: option
1372 ;; - type :: symbol (nil, t)
1374 ;; + `:with-smart-quotes' :: Non-nil means activate smart quotes in
1375 ;; plain text.
1376 ;; - category :: option
1377 ;; - type :: symbol (nil, t)
1379 ;; + `:with-special-strings' :: Non-nil means transcoding should
1380 ;; interpret special strings in plain text.
1381 ;; - category :: option
1382 ;; - type :: symbol (nil, t)
1384 ;; + `:with-sub-superscript' :: Non-nil means transcoding should
1385 ;; interpret subscript and superscript. With a value of "{}",
1386 ;; only interpret those using curly brackets.
1387 ;; - category :: option
1388 ;; - type :: symbol (nil, {}, t)
1390 ;; + `:with-tables' :: Non-nil means transcoding should interpret
1391 ;; tables.
1392 ;; - category :: option
1393 ;; - type :: symbol (nil, t)
1395 ;; + `:with-tags' :: Non-nil means transcoding should keep tags in
1396 ;; headlines. A `not-in-toc' value will remove them from the
1397 ;; table of contents, if any, nonetheless.
1398 ;; - category :: option
1399 ;; - type :: symbol (nil, t, `not-in-toc')
1401 ;; + `:with-tasks' :: Non-nil means transcoding should include
1402 ;; headlines with a TODO keyword. A `todo' value will only
1403 ;; include headlines with a todo type keyword while a `done'
1404 ;; value will do the contrary. If a list of strings is provided,
1405 ;; only tasks with keywords belonging to that list will be kept.
1406 ;; - category :: option
1407 ;; - type :: symbol (t, todo, done, nil) or list of strings
1409 ;; + `:with-timestamps' :: Non-nil means transcoding should include
1410 ;; time stamps. Special value `active' (resp. `inactive') ask to
1411 ;; export only active (resp. inactive) timestamps. Otherwise,
1412 ;; completely remove them.
1413 ;; - category :: option
1414 ;; - type :: symbol: (`active', `inactive', t, nil)
1416 ;; + `:with-toc' :: Non-nil means that a table of contents has to be
1417 ;; added to the output. An integer value limits its depth.
1418 ;; - category :: option
1419 ;; - type :: symbol (nil, t or integer)
1421 ;; + `:with-todo-keywords' :: Non-nil means transcoding should
1422 ;; include TODO keywords.
1423 ;; - category :: option
1424 ;; - type :: symbol (nil, t)
1427 ;;;; Environment Options
1429 ;; Environment options encompass all parameters defined outside the
1430 ;; scope of the parsed data. They come from five sources, in
1431 ;; increasing precedence order:
1433 ;; - Global variables,
1434 ;; - Buffer's attributes,
1435 ;; - Options keyword symbols,
1436 ;; - Buffer keywords,
1437 ;; - Subtree properties.
1439 ;; The central internal function with regards to environment options
1440 ;; is `org-export-get-environment'. It updates global variables with
1441 ;; "#+BIND:" keywords, then retrieve and prioritize properties from
1442 ;; the different sources.
1444 ;; The internal functions doing the retrieval are:
1445 ;; `org-export--get-global-options',
1446 ;; `org-export--get-buffer-attributes',
1447 ;; `org-export--parse-option-keyword',
1448 ;; `org-export--get-subtree-options' and
1449 ;; `org-export--get-inbuffer-options'
1451 ;; Also, `org-export--install-letbind-maybe' takes care of the part
1452 ;; relative to "#+BIND:" keywords.
1454 (defun org-export-get-environment (&optional backend subtreep ext-plist)
1455 "Collect export options from the current buffer.
1457 Optional argument BACKEND is a symbol specifying which back-end
1458 specific options to read, if any.
1460 When optional argument SUBTREEP is non-nil, assume the export is
1461 done against the current sub-tree.
1463 Third optional argument EXT-PLIST is a property list with
1464 external parameters overriding Org default settings, but still
1465 inferior to file-local settings."
1466 ;; First install #+BIND variables since these must be set before
1467 ;; global options are read.
1468 (dolist (pair (org-export--list-bound-variables))
1469 (org-set-local (car pair) (nth 1 pair)))
1470 ;; Get and prioritize export options...
1471 (org-combine-plists
1472 ;; ... from global variables...
1473 (org-export--get-global-options backend)
1474 ;; ... from an external property list...
1475 ext-plist
1476 ;; ... from in-buffer settings...
1477 (org-export--get-inbuffer-options backend)
1478 ;; ... and from subtree, when appropriate.
1479 (and subtreep (org-export--get-subtree-options backend))
1480 ;; Eventually add misc. properties.
1481 (list
1482 :back-end
1483 backend
1484 :translate-alist
1485 (org-export-backend-translate-table backend)
1486 :footnote-definition-alist
1487 ;; Footnotes definitions must be collected in the original
1488 ;; buffer, as there's no insurance that they will still be in
1489 ;; the parse tree, due to possible narrowing.
1490 (let (alist)
1491 (org-with-wide-buffer
1492 (goto-char (point-min))
1493 (while (re-search-forward org-footnote-definition-re nil t)
1494 (let ((def (save-match-data (org-element-at-point))))
1495 (when (eq (org-element-type def) 'footnote-definition)
1496 (push
1497 (cons (org-element-property :label def)
1498 (let ((cbeg (org-element-property :contents-begin def)))
1499 (when cbeg
1500 (org-element--parse-elements
1501 cbeg (org-element-property :contents-end def)
1502 nil nil nil nil (list 'org-data nil)))))
1503 alist))))
1504 alist))
1505 :id-alist
1506 ;; Collect id references.
1507 (let (alist)
1508 (org-with-wide-buffer
1509 (goto-char (point-min))
1510 (while (re-search-forward "\\[\\[id:\\S-+?\\]" nil t)
1511 (let ((link (org-element-context)))
1512 (when (eq (org-element-type link) 'link)
1513 (let* ((id (org-element-property :path link))
1514 (file (org-id-find-id-file id)))
1515 (when file
1516 (push (cons id (file-relative-name file)) alist)))))))
1517 alist))))
1519 (defun org-export--parse-option-keyword (options &optional backend)
1520 "Parse an OPTIONS line and return values as a plist.
1521 Optional argument BACKEND is a symbol specifying which back-end
1522 specific items to read, if any."
1523 (let* ((all
1524 ;; Priority is given to back-end specific options.
1525 (append (and backend (org-export-backend-options backend))
1526 org-export-options-alist))
1527 plist)
1528 (dolist (option all)
1529 (let ((property (car option))
1530 (item (nth 2 option)))
1531 (when (and item
1532 (not (plist-member plist property))
1533 (string-match (concat "\\(\\`\\|[ \t]\\)"
1534 (regexp-quote item)
1535 ":\\(([^)\n]+)\\|[^ \t\n\r;,.]*\\)")
1536 options))
1537 (setq plist (plist-put plist
1538 property
1539 (car (read-from-string
1540 (match-string 2 options))))))))
1541 plist))
1543 (defun org-export--get-subtree-options (&optional backend)
1544 "Get export options in subtree at point.
1545 Optional argument BACKEND is a symbol specifying back-end used
1546 for export. Return options as a plist."
1547 ;; For each buffer keyword, create a headline property setting the
1548 ;; same property in communication channel. The name for the property
1549 ;; is the keyword with "EXPORT_" appended to it.
1550 (org-with-wide-buffer
1551 (let (prop plist)
1552 ;; Make sure point is at a heading.
1553 (if (org-at-heading-p) (org-up-heading-safe) (org-back-to-heading t))
1554 ;; Take care of EXPORT_TITLE. If it isn't defined, use headline's
1555 ;; title as its fallback value.
1556 (when (setq prop (or (org-entry-get (point) "EXPORT_TITLE")
1557 (progn (looking-at org-todo-line-regexp)
1558 (org-match-string-no-properties 3))))
1559 (setq plist
1560 (plist-put
1561 plist :title
1562 (org-element-parse-secondary-string
1563 prop (org-element-restriction 'keyword)))))
1564 ;; EXPORT_OPTIONS are parsed in a non-standard way.
1565 (when (setq prop (org-entry-get (point) "EXPORT_OPTIONS"))
1566 (setq plist
1567 (nconc plist (org-export--parse-option-keyword prop backend))))
1568 ;; Handle other keywords. TITLE keyword is excluded as it has
1569 ;; been handled already.
1570 (let ((seen '("TITLE")))
1571 (mapc
1572 (lambda (option)
1573 (let ((property (car option))
1574 (keyword (nth 1 option)))
1575 (when (and keyword (not (member keyword seen)))
1576 (let* ((subtree-prop (concat "EXPORT_" keyword))
1577 ;; Export properties are not case-sensitive.
1578 (value (let ((case-fold-search t))
1579 (org-entry-get (point) subtree-prop))))
1580 (push keyword seen)
1581 (when (and value (not (plist-member plist property)))
1582 (setq plist
1583 (plist-put
1584 plist
1585 property
1586 (cond
1587 ;; Parse VALUE if required.
1588 ((member keyword org-element-document-properties)
1589 (org-element-parse-secondary-string
1590 value (org-element-restriction 'keyword)))
1591 ;; If BEHAVIOUR is `split' expected value is
1592 ;; a list of strings, not a string.
1593 ((eq (nth 4 option) 'split) (org-split-string value))
1594 (t value)))))))))
1595 ;; Look for both general keywords and back-end specific
1596 ;; options, with priority given to the latter.
1597 (append (and backend (org-export-backend-options backend))
1598 org-export-options-alist)))
1599 ;; Return value.
1600 plist)))
1602 (defun org-export--get-inbuffer-options (&optional backend)
1603 "Return current buffer export options, as a plist.
1605 Optional argument BACKEND, when non-nil, is a symbol specifying
1606 which back-end specific options should also be read in the
1607 process.
1609 Assume buffer is in Org mode. Narrowing, if any, is ignored."
1610 (let* (plist
1611 get-options ; For byte-compiler.
1612 (case-fold-search t)
1613 (options (append
1614 ;; Priority is given to back-end specific options.
1615 (and backend (org-export-backend-options backend))
1616 org-export-options-alist))
1617 (regexp (format "^[ \t]*#\\+%s:"
1618 (regexp-opt (nconc (delq nil (mapcar 'cadr options))
1619 org-export-special-keywords))))
1620 (find-opt
1621 (lambda (keyword)
1622 ;; Return property name associated to KEYWORD.
1623 (catch 'exit
1624 (mapc (lambda (option)
1625 (when (equal (nth 1 option) keyword)
1626 (throw 'exit (car option))))
1627 options))))
1628 (get-options
1629 (lambda (&optional files plist)
1630 ;; Recursively read keywords in buffer. FILES is a list
1631 ;; of files read so far. PLIST is the current property
1632 ;; list obtained.
1633 (org-with-wide-buffer
1634 (goto-char (point-min))
1635 (while (re-search-forward regexp nil t)
1636 (let ((element (org-element-at-point)))
1637 (when (eq (org-element-type element) 'keyword)
1638 (let ((key (org-element-property :key element))
1639 (val (org-element-property :value element)))
1640 (cond
1641 ;; Options in `org-export-special-keywords'.
1642 ((equal key "SETUPFILE")
1643 (let ((file (expand-file-name
1644 (org-remove-double-quotes (org-trim val)))))
1645 ;; Avoid circular dependencies.
1646 (unless (member file files)
1647 (with-temp-buffer
1648 (insert (org-file-contents file 'noerror))
1649 (let ((org-inhibit-startup t)) (org-mode))
1650 (setq plist (funcall get-options
1651 (cons file files) plist))))))
1652 ((equal key "OPTIONS")
1653 (setq plist
1654 (org-combine-plists
1655 plist
1656 (org-export--parse-option-keyword val backend))))
1657 ((equal key "FILETAGS")
1658 (setq plist
1659 (org-combine-plists
1660 plist
1661 (list :filetags
1662 (org-uniquify
1663 (append (org-split-string val ":")
1664 (plist-get plist :filetags)))))))
1666 ;; Options in `org-export-options-alist'.
1667 (let* ((prop (funcall find-opt key))
1668 (behaviour (nth 4 (assq prop options))))
1669 (setq plist
1670 (plist-put
1671 plist prop
1672 ;; Handle value depending on specified
1673 ;; BEHAVIOUR.
1674 (case behaviour
1675 (space
1676 (if (not (plist-get plist prop))
1677 (org-trim val)
1678 (concat (plist-get plist prop)
1680 (org-trim val))))
1681 (newline
1682 (org-trim (concat (plist-get plist prop)
1683 "\n"
1684 (org-trim val))))
1685 (split `(,@(plist-get plist prop)
1686 ,@(org-split-string val)))
1687 ('t val)
1688 (otherwise
1689 (if (not (plist-member plist prop)) val
1690 (plist-get plist prop)))))))))))))
1691 ;; Return final value.
1692 plist))))
1693 ;; Read options in the current buffer.
1694 (setq plist (funcall get-options buffer-file-name nil))
1695 ;; Parse keywords specified in `org-element-document-properties'.
1696 (mapc (lambda (keyword)
1697 ;; Find the property associated to the keyword.
1698 (let* ((prop (funcall find-opt keyword))
1699 (value (and prop (plist-get plist prop))))
1700 (when (stringp value)
1701 (setq plist
1702 (plist-put plist prop
1703 (org-element-parse-secondary-string
1704 value (org-element-restriction 'keyword)))))))
1705 org-element-document-properties)
1706 ;; Return value.
1707 plist))
1709 (defun org-export--get-buffer-attributes ()
1710 "Return properties related to buffer attributes, as a plist."
1711 ;; Store full path of input file name, or nil. For internal use.
1712 (list :input-file (buffer-file-name (buffer-base-buffer))))
1714 (defvar org-export--default-title nil) ; Dynamically scoped.
1715 (defun org-export-store-default-title ()
1716 "Return default title for current document, as a string.
1717 Title is extracted from associated file name, if any, or buffer's
1718 name."
1719 (setq org-export--default-title
1720 (or (let ((visited-file (buffer-file-name (buffer-base-buffer))))
1721 (and visited-file
1722 (file-name-sans-extension
1723 (file-name-nondirectory visited-file))))
1724 (buffer-name (buffer-base-buffer)))))
1726 (defun org-export--get-global-options (&optional backend)
1727 "Return global export options as a plist.
1728 Optional argument BACKEND, if non-nil, is a symbol specifying
1729 which back-end specific export options should also be read in the
1730 process."
1731 (let (plist
1732 ;; Priority is given to back-end specific options.
1733 (all (append (and backend (org-export-backend-options backend))
1734 org-export-options-alist)))
1735 (dolist (cell all plist)
1736 (let ((prop (car cell)))
1737 (unless (plist-member plist prop)
1738 (setq plist
1739 (plist-put
1740 plist
1741 prop
1742 ;; Eval default value provided. If keyword is
1743 ;; a member of `org-element-document-properties',
1744 ;; parse it as a secondary string before storing it.
1745 (let ((value (eval (nth 3 cell))))
1746 (if (not (stringp value)) value
1747 (let ((keyword (nth 1 cell)))
1748 (if (member keyword org-element-document-properties)
1749 (org-element-parse-secondary-string
1750 value (org-element-restriction 'keyword))
1751 value)))))))))))
1753 (defun org-export--list-bound-variables ()
1754 "Return variables bound from BIND keywords in current buffer.
1755 Also look for BIND keywords in setup files. The return value is
1756 an alist where associations are (VARIABLE-NAME VALUE)."
1757 (when org-export-allow-bind-keywords
1758 (let* (collect-bind ; For byte-compiler.
1759 (collect-bind
1760 (lambda (files alist)
1761 ;; Return an alist between variable names and their
1762 ;; value. FILES is a list of setup files names read so
1763 ;; far, used to avoid circular dependencies. ALIST is
1764 ;; the alist collected so far.
1765 (let ((case-fold-search t))
1766 (org-with-wide-buffer
1767 (goto-char (point-min))
1768 (while (re-search-forward
1769 "^[ \t]*#\\+\\(BIND\\|SETUPFILE\\):" nil t)
1770 (let ((element (org-element-at-point)))
1771 (when (eq (org-element-type element) 'keyword)
1772 (let ((val (org-element-property :value element)))
1773 (if (equal (org-element-property :key element) "BIND")
1774 (push (read (format "(%s)" val)) alist)
1775 ;; Enter setup file.
1776 (let ((file (expand-file-name
1777 (org-remove-double-quotes val))))
1778 (unless (member file files)
1779 (with-temp-buffer
1780 (let ((org-inhibit-startup t)) (org-mode))
1781 (insert (org-file-contents file 'noerror))
1782 (setq alist
1783 (funcall collect-bind
1784 (cons file files)
1785 alist))))))))))
1786 alist)))))
1787 ;; Return value in appropriate order of appearance.
1788 (nreverse (funcall collect-bind nil nil)))))
1791 ;;;; Tree Properties
1793 ;; Tree properties are information extracted from parse tree. They
1794 ;; are initialized at the beginning of the transcoding process by
1795 ;; `org-export-collect-tree-properties'.
1797 ;; Dedicated functions focus on computing the value of specific tree
1798 ;; properties during initialization. Thus,
1799 ;; `org-export--populate-ignore-list' lists elements and objects that
1800 ;; should be skipped during export, `org-export--get-min-level' gets
1801 ;; the minimal exportable level, used as a basis to compute relative
1802 ;; level for headlines. Eventually
1803 ;; `org-export--collect-headline-numbering' builds an alist between
1804 ;; headlines and their numbering.
1806 (defun org-export-collect-tree-properties (data info)
1807 "Extract tree properties from parse tree.
1809 DATA is the parse tree from which information is retrieved. INFO
1810 is a list holding export options.
1812 Following tree properties are set or updated:
1814 `:exported-data' Hash table used to memoize results from
1815 `org-export-data'.
1817 `:footnote-definition-alist' List of footnotes definitions in
1818 original buffer and current parse tree.
1820 `:headline-offset' Offset between true level of headlines and
1821 local level. An offset of -1 means a headline
1822 of level 2 should be considered as a level
1823 1 headline in the context.
1825 `:headline-numbering' Alist of all headlines as key an the
1826 associated numbering as value.
1828 `:ignore-list' List of elements that should be ignored during
1829 export.
1831 Return updated plist."
1832 ;; Install the parse tree in the communication channel, in order to
1833 ;; use `org-export-get-genealogy' and al.
1834 (setq info (plist-put info :parse-tree data))
1835 ;; Get the list of elements and objects to ignore, and put it into
1836 ;; `:ignore-list'. Do not overwrite any user ignore that might have
1837 ;; been done during parse tree filtering.
1838 (setq info
1839 (plist-put info
1840 :ignore-list
1841 (append (org-export--populate-ignore-list data info)
1842 (plist-get info :ignore-list))))
1843 ;; Compute `:headline-offset' in order to be able to use
1844 ;; `org-export-get-relative-level'.
1845 (setq info
1846 (plist-put info
1847 :headline-offset
1848 (- 1 (org-export--get-min-level data info))))
1849 ;; Update footnotes definitions list with definitions in parse tree.
1850 ;; This is required since buffer expansion might have modified
1851 ;; boundaries of footnote definitions contained in the parse tree.
1852 ;; This way, definitions in `footnote-definition-alist' are bound to
1853 ;; match those in the parse tree.
1854 (let ((defs (plist-get info :footnote-definition-alist)))
1855 (org-element-map data 'footnote-definition
1856 (lambda (fn)
1857 (push (cons (org-element-property :label fn)
1858 `(org-data nil ,@(org-element-contents fn)))
1859 defs)))
1860 (setq info (plist-put info :footnote-definition-alist defs)))
1861 ;; Properties order doesn't matter: get the rest of the tree
1862 ;; properties.
1863 (nconc
1864 `(:headline-numbering ,(org-export--collect-headline-numbering data info)
1865 :exported-data ,(make-hash-table :test 'eq :size 4001))
1866 info))
1868 (defun org-export--get-min-level (data options)
1869 "Return minimum exportable headline's level in DATA.
1870 DATA is parsed tree as returned by `org-element-parse-buffer'.
1871 OPTIONS is a plist holding export options."
1872 (catch 'exit
1873 (let ((min-level 10000))
1874 (mapc
1875 (lambda (blob)
1876 (when (and (eq (org-element-type blob) 'headline)
1877 (not (org-element-property :footnote-section-p blob))
1878 (not (memq blob (plist-get options :ignore-list))))
1879 (setq min-level (min (org-element-property :level blob) min-level)))
1880 (when (= min-level 1) (throw 'exit 1)))
1881 (org-element-contents data))
1882 ;; If no headline was found, for the sake of consistency, set
1883 ;; minimum level to 1 nonetheless.
1884 (if (= min-level 10000) 1 min-level))))
1886 (defun org-export--collect-headline-numbering (data options)
1887 "Return numbering of all exportable headlines in a parse tree.
1889 DATA is the parse tree. OPTIONS is the plist holding export
1890 options.
1892 Return an alist whose key is a headline and value is its
1893 associated numbering \(in the shape of a list of numbers\) or nil
1894 for a footnotes section."
1895 (let ((numbering (make-vector org-export-max-depth 0)))
1896 (org-element-map data 'headline
1897 (lambda (headline)
1898 (unless (org-element-property :footnote-section-p headline)
1899 (let ((relative-level
1900 (1- (org-export-get-relative-level headline options))))
1901 (cons
1902 headline
1903 (loop for n across numbering
1904 for idx from 0 to org-export-max-depth
1905 when (< idx relative-level) collect n
1906 when (= idx relative-level) collect (aset numbering idx (1+ n))
1907 when (> idx relative-level) do (aset numbering idx 0))))))
1908 options)))
1910 (defun org-export--populate-ignore-list (data options)
1911 "Return list of elements and objects to ignore during export.
1912 DATA is the parse tree to traverse. OPTIONS is the plist holding
1913 export options."
1914 (let* (ignore
1915 walk-data
1916 ;; First find trees containing a select tag, if any.
1917 (selected (org-export--selected-trees data options))
1918 (walk-data
1919 (lambda (data)
1920 ;; Collect ignored elements or objects into IGNORE-LIST.
1921 (let ((type (org-element-type data)))
1922 (if (org-export--skip-p data options selected) (push data ignore)
1923 (if (and (eq type 'headline)
1924 (eq (plist-get options :with-archived-trees) 'headline)
1925 (org-element-property :archivedp data))
1926 ;; If headline is archived but tree below has
1927 ;; to be skipped, add it to ignore list.
1928 (mapc (lambda (e) (push e ignore))
1929 (org-element-contents data))
1930 ;; Move into secondary string, if any.
1931 (let ((sec-prop
1932 (cdr (assq type org-element-secondary-value-alist))))
1933 (when sec-prop
1934 (mapc walk-data (org-element-property sec-prop data))))
1935 ;; Move into recursive objects/elements.
1936 (mapc walk-data (org-element-contents data))))))))
1937 ;; Main call.
1938 (funcall walk-data data)
1939 ;; Return value.
1940 ignore))
1942 (defun org-export--selected-trees (data info)
1943 "Return list of headlines and inlinetasks with a select tag in their tree.
1944 DATA is parsed data as returned by `org-element-parse-buffer'.
1945 INFO is a plist holding export options."
1946 (let* (selected-trees
1947 walk-data ; For byte-compiler.
1948 (walk-data
1949 (function
1950 (lambda (data genealogy)
1951 (let ((type (org-element-type data)))
1952 (cond
1953 ((memq type '(headline inlinetask))
1954 (let ((tags (org-element-property :tags data)))
1955 (if (loop for tag in (plist-get info :select-tags)
1956 thereis (member tag tags))
1957 ;; When a select tag is found, mark full
1958 ;; genealogy and every headline within the tree
1959 ;; as acceptable.
1960 (setq selected-trees
1961 (append
1962 genealogy
1963 (org-element-map data '(headline inlinetask)
1964 'identity)
1965 selected-trees))
1966 ;; If at a headline, continue searching in tree,
1967 ;; recursively.
1968 (when (eq type 'headline)
1969 (mapc (lambda (el)
1970 (funcall walk-data el (cons data genealogy)))
1971 (org-element-contents data))))))
1972 ((or (eq type 'org-data)
1973 (memq type org-element-greater-elements))
1974 (mapc (lambda (el) (funcall walk-data el genealogy))
1975 (org-element-contents data)))))))))
1976 (funcall walk-data data nil)
1977 selected-trees))
1979 (defun org-export--skip-p (blob options selected)
1980 "Non-nil when element or object BLOB should be skipped during export.
1981 OPTIONS is the plist holding export options. SELECTED, when
1982 non-nil, is a list of headlines or inlinetasks belonging to
1983 a tree with a select tag."
1984 (case (org-element-type blob)
1985 (clock (not (plist-get options :with-clocks)))
1986 (drawer
1987 (let ((with-drawers-p (plist-get options :with-drawers)))
1988 (or (not with-drawers-p)
1989 (and (consp with-drawers-p)
1990 ;; If `:with-drawers' value starts with `not', ignore
1991 ;; every drawer whose name belong to that list.
1992 ;; Otherwise, ignore drawers whose name isn't in that
1993 ;; list.
1994 (let ((name (org-element-property :drawer-name blob)))
1995 (if (eq (car with-drawers-p) 'not)
1996 (member-ignore-case name (cdr with-drawers-p))
1997 (not (member-ignore-case name with-drawers-p))))))))
1998 ((footnote-definition footnote-reference)
1999 (not (plist-get options :with-footnotes)))
2000 ((headline inlinetask)
2001 (let ((with-tasks (plist-get options :with-tasks))
2002 (todo (org-element-property :todo-keyword blob))
2003 (todo-type (org-element-property :todo-type blob))
2004 (archived (plist-get options :with-archived-trees))
2005 (tags (org-element-property :tags blob)))
2007 (and (eq (org-element-type blob) 'inlinetask)
2008 (not (plist-get options :with-inlinetasks)))
2009 ;; Ignore subtrees with an exclude tag.
2010 (loop for k in (plist-get options :exclude-tags)
2011 thereis (member k tags))
2012 ;; When a select tag is present in the buffer, ignore any tree
2013 ;; without it.
2014 (and selected (not (memq blob selected)))
2015 ;; Ignore commented sub-trees.
2016 (org-element-property :commentedp blob)
2017 ;; Ignore archived subtrees if `:with-archived-trees' is nil.
2018 (and (not archived) (org-element-property :archivedp blob))
2019 ;; Ignore tasks, if specified by `:with-tasks' property.
2020 (and todo
2021 (or (not with-tasks)
2022 (and (memq with-tasks '(todo done))
2023 (not (eq todo-type with-tasks)))
2024 (and (consp with-tasks) (not (member todo with-tasks))))))))
2025 ((latex-environment latex-fragment) (not (plist-get options :with-latex)))
2026 (planning (not (plist-get options :with-planning)))
2027 (statistics-cookie (not (plist-get options :with-statistics-cookies)))
2028 (table-cell
2029 (and (org-export-table-has-special-column-p
2030 (org-export-get-parent-table blob))
2031 (not (org-export-get-previous-element blob options))))
2032 (table-row (org-export-table-row-is-special-p blob options))
2033 (timestamp
2034 ;; `:with-timestamps' only applies to isolated timestamps
2035 ;; objects, i.e. timestamp objects in a paragraph containing only
2036 ;; timestamps and whitespaces.
2037 (when (let ((parent (org-export-get-parent-element blob)))
2038 (and (memq (org-element-type parent) '(paragraph verse-block))
2039 (not (org-element-map parent
2040 (cons 'plain-text
2041 (remq 'timestamp org-element-all-objects))
2042 (lambda (obj)
2043 (or (not (stringp obj)) (org-string-nw-p obj)))
2044 options t))))
2045 (case (plist-get options :with-timestamps)
2046 ('nil t)
2047 (active
2048 (not (memq (org-element-property :type blob) '(active active-range))))
2049 (inactive
2050 (not (memq (org-element-property :type blob)
2051 '(inactive inactive-range)))))))))
2054 ;;; The Transcoder
2056 ;; `org-export-data' reads a parse tree (obtained with, i.e.
2057 ;; `org-element-parse-buffer') and transcodes it into a specified
2058 ;; back-end output. It takes care of filtering out elements or
2059 ;; objects according to export options and organizing the output blank
2060 ;; lines and white space are preserved. The function memoizes its
2061 ;; results, so it is cheap to call it within translators.
2063 ;; It is possible to modify locally the back-end used by
2064 ;; `org-export-data' or even use a temporary back-end by using
2065 ;; `org-export-data-with-translations' and
2066 ;; `org-export-data-with-backend'.
2068 ;; Internally, three functions handle the filtering of objects and
2069 ;; elements during the export. In particular,
2070 ;; `org-export-ignore-element' marks an element or object so future
2071 ;; parse tree traversals skip it, `org-export--interpret-p' tells which
2072 ;; elements or objects should be seen as real Org syntax and
2073 ;; `org-export-expand' transforms the others back into their original
2074 ;; shape
2076 ;; `org-export-transcoder' is an accessor returning appropriate
2077 ;; translator function for a given element or object.
2079 (defun org-export-transcoder (blob info)
2080 "Return appropriate transcoder for BLOB.
2081 INFO is a plist containing export directives."
2082 (let ((type (org-element-type blob)))
2083 ;; Return contents only for complete parse trees.
2084 (if (eq type 'org-data) (lambda (blob contents info) contents)
2085 (let ((transcoder (cdr (assq type (plist-get info :translate-alist)))))
2086 (and (functionp transcoder) transcoder)))))
2088 (defun org-export-data (data info)
2089 "Convert DATA into current back-end format.
2091 DATA is a parse tree, an element or an object or a secondary
2092 string. INFO is a plist holding export options.
2094 Return transcoded string."
2095 (let ((memo (gethash data (plist-get info :exported-data) 'no-memo)))
2096 (if (not (eq memo 'no-memo)) memo
2097 (let* ((type (org-element-type data))
2098 (results
2099 (cond
2100 ;; Ignored element/object.
2101 ((memq data (plist-get info :ignore-list)) nil)
2102 ;; Plain text.
2103 ((eq type 'plain-text)
2104 (org-export-filter-apply-functions
2105 (plist-get info :filter-plain-text)
2106 (let ((transcoder (org-export-transcoder data info)))
2107 (if transcoder (funcall transcoder data info) data))
2108 info))
2109 ;; Uninterpreted element/object: change it back to Org
2110 ;; syntax and export again resulting raw string.
2111 ((not (org-export--interpret-p data info))
2112 (org-export-data
2113 (org-export-expand
2114 data
2115 (mapconcat (lambda (blob) (org-export-data blob info))
2116 (org-element-contents data)
2117 ""))
2118 info))
2119 ;; Secondary string.
2120 ((not type)
2121 (mapconcat (lambda (obj) (org-export-data obj info)) data ""))
2122 ;; Element/Object without contents or, as a special case,
2123 ;; headline with archive tag and archived trees restricted
2124 ;; to title only.
2125 ((or (not (org-element-contents data))
2126 (and (eq type 'headline)
2127 (eq (plist-get info :with-archived-trees) 'headline)
2128 (org-element-property :archivedp data)))
2129 (let ((transcoder (org-export-transcoder data info)))
2130 (or (and (functionp transcoder)
2131 (funcall transcoder data nil info))
2132 ;; Export snippets never return a nil value so
2133 ;; that white spaces following them are never
2134 ;; ignored.
2135 (and (eq type 'export-snippet) ""))))
2136 ;; Element/Object with contents.
2138 (let ((transcoder (org-export-transcoder data info)))
2139 (when transcoder
2140 (let* ((greaterp (memq type org-element-greater-elements))
2141 (objectp
2142 (and (not greaterp)
2143 (memq type org-element-recursive-objects)))
2144 (contents
2145 (mapconcat
2146 (lambda (element) (org-export-data element info))
2147 (org-element-contents
2148 (if (or greaterp objectp) data
2149 ;; Elements directly containing objects
2150 ;; must have their indentation normalized
2151 ;; first.
2152 (org-element-normalize-contents
2153 data
2154 ;; When normalizing contents of the first
2155 ;; paragraph in an item or a footnote
2156 ;; definition, ignore first line's
2157 ;; indentation: there is none and it
2158 ;; might be misleading.
2159 (when (eq type 'paragraph)
2160 (let ((parent (org-export-get-parent data)))
2161 (and
2162 (eq (car (org-element-contents parent))
2163 data)
2164 (memq (org-element-type parent)
2165 '(footnote-definition item))))))))
2166 "")))
2167 (funcall transcoder data
2168 (if (not greaterp) contents
2169 (org-element-normalize-string contents))
2170 info))))))))
2171 ;; Final result will be memoized before being returned.
2172 (puthash
2173 data
2174 (cond
2175 ((not results) nil)
2176 ((memq type '(org-data plain-text nil)) results)
2177 ;; Append the same white space between elements or objects as in
2178 ;; the original buffer, and call appropriate filters.
2180 (let ((results
2181 (org-export-filter-apply-functions
2182 (plist-get info (intern (format ":filter-%s" type)))
2183 (let ((post-blank (or (org-element-property :post-blank data)
2184 0)))
2185 (if (memq type org-element-all-elements)
2186 (concat (org-element-normalize-string results)
2187 (make-string post-blank ?\n))
2188 (concat results (make-string post-blank ? ))))
2189 info)))
2190 results)))
2191 (plist-get info :exported-data))))))
2193 (defun org-export-data-with-translations (data translations info)
2194 "Convert DATA into another format using a given translation table.
2195 DATA is an element, an object, a secondary string or a string.
2196 TRANSLATIONS is an alist between element or object types and
2197 a functions handling them. See `org-export-define-backend' for
2198 more information. INFO is a plist used as a communication
2199 channel."
2200 (org-export-data
2201 data
2202 ;; Set-up a new communication channel with TRANSLATIONS as the
2203 ;; translate table and a new hash table for memoization.
2204 (org-combine-plists
2205 info
2206 (list :translate-alist translations
2207 ;; Size of the hash table is reduced since this function
2208 ;; will probably be used on short trees.
2209 :exported-data (make-hash-table :test 'eq :size 401)))))
2211 (defun org-export-data-with-backend (data backend info)
2212 "Convert DATA into BACKEND format.
2214 DATA is an element, an object, a secondary string or a string.
2215 BACKEND is a symbol. INFO is a plist used as a communication
2216 channel.
2218 Unlike to `org-export-with-backend', this function will
2219 recursively convert DATA using BACKEND translation table."
2220 (org-export-barf-if-invalid-backend backend)
2221 (org-export-data-with-translations
2222 data (org-export-backend-translate-table backend) info))
2224 (defun org-export--interpret-p (blob info)
2225 "Non-nil if element or object BLOB should be interpreted during export.
2226 If nil, BLOB will appear as raw Org syntax. Check is done
2227 according to export options INFO, stored as a plist."
2228 (case (org-element-type blob)
2229 ;; ... entities...
2230 (entity (plist-get info :with-entities))
2231 ;; ... emphasis...
2232 ((bold italic strike-through underline)
2233 (plist-get info :with-emphasize))
2234 ;; ... fixed-width areas.
2235 (fixed-width (plist-get info :with-fixed-width))
2236 ;; ... LaTeX environments and fragments...
2237 ((latex-environment latex-fragment)
2238 (let ((with-latex-p (plist-get info :with-latex)))
2239 (and with-latex-p (not (eq with-latex-p 'verbatim)))))
2240 ;; ... sub/superscripts...
2241 ((subscript superscript)
2242 (let ((sub/super-p (plist-get info :with-sub-superscript)))
2243 (if (eq sub/super-p '{})
2244 (org-element-property :use-brackets-p blob)
2245 sub/super-p)))
2246 ;; ... tables...
2247 (table (plist-get info :with-tables))
2248 (otherwise t)))
2250 (defun org-export-expand (blob contents &optional with-affiliated)
2251 "Expand a parsed element or object to its original state.
2253 BLOB is either an element or an object. CONTENTS is its
2254 contents, as a string or nil.
2256 When optional argument WITH-AFFILIATED is non-nil, add affiliated
2257 keywords before output."
2258 (let ((type (org-element-type blob)))
2259 (concat (and with-affiliated (memq type org-element-all-elements)
2260 (org-element--interpret-affiliated-keywords blob))
2261 (funcall (intern (format "org-element-%s-interpreter" type))
2262 blob contents))))
2264 (defun org-export-ignore-element (element info)
2265 "Add ELEMENT to `:ignore-list' in INFO.
2267 Any element in `:ignore-list' will be skipped when using
2268 `org-element-map'. INFO is modified by side effects."
2269 (plist-put info :ignore-list (cons element (plist-get info :ignore-list))))
2273 ;;; The Filter System
2275 ;; Filters allow end-users to tweak easily the transcoded output.
2276 ;; They are the functional counterpart of hooks, as every filter in
2277 ;; a set is applied to the return value of the previous one.
2279 ;; Every set is back-end agnostic. Although, a filter is always
2280 ;; called, in addition to the string it applies to, with the back-end
2281 ;; used as argument, so it's easy for the end-user to add back-end
2282 ;; specific filters in the set. The communication channel, as
2283 ;; a plist, is required as the third argument.
2285 ;; From the developer side, filters sets can be installed in the
2286 ;; process with the help of `org-export-define-backend', which
2287 ;; internally stores filters as an alist. Each association has a key
2288 ;; among the following symbols and a function or a list of functions
2289 ;; as value.
2291 ;; - `:filter-options' applies to the property list containing export
2292 ;; options. Unlike to other filters, functions in this list accept
2293 ;; two arguments instead of three: the property list containing
2294 ;; export options and the back-end. Users can set its value through
2295 ;; `org-export-filter-options-functions' variable.
2297 ;; - `:filter-parse-tree' applies directly to the complete parsed
2298 ;; tree. Users can set it through
2299 ;; `org-export-filter-parse-tree-functions' variable.
2301 ;; - `:filter-final-output' applies to the final transcoded string.
2302 ;; Users can set it with `org-export-filter-final-output-functions'
2303 ;; variable
2305 ;; - `:filter-plain-text' applies to any string not recognized as Org
2306 ;; syntax. `org-export-filter-plain-text-functions' allows users to
2307 ;; configure it.
2309 ;; - `:filter-TYPE' applies on the string returned after an element or
2310 ;; object of type TYPE has been transcoded. A user can modify
2311 ;; `org-export-filter-TYPE-functions'
2313 ;; All filters sets are applied with
2314 ;; `org-export-filter-apply-functions' function. Filters in a set are
2315 ;; applied in a LIFO fashion. It allows developers to be sure that
2316 ;; their filters will be applied first.
2318 ;; Filters properties are installed in communication channel with
2319 ;; `org-export-install-filters' function.
2321 ;; Eventually, two hooks (`org-export-before-processing-hook' and
2322 ;; `org-export-before-parsing-hook') are run at the beginning of the
2323 ;; export process and just before parsing to allow for heavy structure
2324 ;; modifications.
2327 ;;;; Hooks
2329 (defvar org-export-before-processing-hook nil
2330 "Hook run at the beginning of the export process.
2332 This is run before include keywords and macros are expanded and
2333 Babel code blocks executed, on a copy of the original buffer
2334 being exported. Visibility and narrowing are preserved. Point
2335 is at the beginning of the buffer.
2337 Every function in this hook will be called with one argument: the
2338 back-end currently used, as a symbol.")
2340 (defvar org-export-before-parsing-hook nil
2341 "Hook run before parsing an export buffer.
2343 This is run after include keywords and macros have been expanded
2344 and Babel code blocks executed, on a copy of the original buffer
2345 being exported. Visibility and narrowing are preserved. Point
2346 is at the beginning of the buffer.
2348 Every function in this hook will be called with one argument: the
2349 back-end currently used, as a symbol.")
2352 ;;;; Special Filters
2354 (defvar org-export-filter-options-functions nil
2355 "List of functions applied to the export options.
2356 Each filter is called with two arguments: the export options, as
2357 a plist, and the back-end, as a symbol. It must return
2358 a property list containing export options.")
2360 (defvar org-export-filter-parse-tree-functions nil
2361 "List of functions applied to the parsed tree.
2362 Each filter is called with three arguments: the parse tree, as
2363 returned by `org-element-parse-buffer', the back-end, as
2364 a symbol, and the communication channel, as a plist. It must
2365 return the modified parse tree to transcode.")
2367 (defvar org-export-filter-plain-text-functions nil
2368 "List of functions applied to plain text.
2369 Each filter is called with three arguments: a string which
2370 contains no Org syntax, the back-end, as a symbol, and the
2371 communication channel, as a plist. It must return a string or
2372 nil.")
2374 (defvar org-export-filter-final-output-functions nil
2375 "List of functions applied to the transcoded string.
2376 Each filter is called with three arguments: the full transcoded
2377 string, the back-end, as a symbol, and the communication channel,
2378 as a plist. It must return a string that will be used as the
2379 final export output.")
2382 ;;;; Elements Filters
2384 (defvar org-export-filter-babel-call-functions nil
2385 "List of functions applied to a transcoded babel-call.
2386 Each filter is called with three arguments: the transcoded data,
2387 as a string, the back-end, as a symbol, and the communication
2388 channel, as a plist. It must return a string or nil.")
2390 (defvar org-export-filter-center-block-functions nil
2391 "List of functions applied to a transcoded center block.
2392 Each filter is called with three arguments: the transcoded data,
2393 as a string, the back-end, as a symbol, and the communication
2394 channel, as a plist. It must return a string or nil.")
2396 (defvar org-export-filter-clock-functions nil
2397 "List of functions applied to a transcoded clock.
2398 Each filter is called with three arguments: the transcoded data,
2399 as a string, the back-end, as a symbol, and the communication
2400 channel, as a plist. It must return a string or nil.")
2402 (defvar org-export-filter-comment-functions nil
2403 "List of functions applied to a transcoded comment.
2404 Each filter is called with three arguments: the transcoded data,
2405 as a string, the back-end, as a symbol, and the communication
2406 channel, as a plist. It must return a string or nil.")
2408 (defvar org-export-filter-comment-block-functions nil
2409 "List of functions applied to a transcoded comment-block.
2410 Each filter is called with three arguments: the transcoded data,
2411 as a string, the back-end, as a symbol, and the communication
2412 channel, as a plist. It must return a string or nil.")
2414 (defvar org-export-filter-diary-sexp-functions nil
2415 "List of functions applied to a transcoded diary-sexp.
2416 Each filter is called with three arguments: the transcoded data,
2417 as a string, the back-end, as a symbol, and the communication
2418 channel, as a plist. It must return a string or nil.")
2420 (defvar org-export-filter-drawer-functions nil
2421 "List of functions applied to a transcoded drawer.
2422 Each filter is called with three arguments: the transcoded data,
2423 as a string, the back-end, as a symbol, and the communication
2424 channel, as a plist. It must return a string or nil.")
2426 (defvar org-export-filter-dynamic-block-functions nil
2427 "List of functions applied to a transcoded dynamic-block.
2428 Each filter is called with three arguments: the transcoded data,
2429 as a string, the back-end, as a symbol, and the communication
2430 channel, as a plist. It must return a string or nil.")
2432 (defvar org-export-filter-example-block-functions nil
2433 "List of functions applied to a transcoded example-block.
2434 Each filter is called with three arguments: the transcoded data,
2435 as a string, the back-end, as a symbol, and the communication
2436 channel, as a plist. It must return a string or nil.")
2438 (defvar org-export-filter-export-block-functions nil
2439 "List of functions applied to a transcoded export-block.
2440 Each filter is called with three arguments: the transcoded data,
2441 as a string, the back-end, as a symbol, and the communication
2442 channel, as a plist. It must return a string or nil.")
2444 (defvar org-export-filter-fixed-width-functions nil
2445 "List of functions applied to a transcoded fixed-width.
2446 Each filter is called with three arguments: the transcoded data,
2447 as a string, the back-end, as a symbol, and the communication
2448 channel, as a plist. It must return a string or nil.")
2450 (defvar org-export-filter-footnote-definition-functions nil
2451 "List of functions applied to a transcoded footnote-definition.
2452 Each filter is called with three arguments: the transcoded data,
2453 as a string, the back-end, as a symbol, and the communication
2454 channel, as a plist. It must return a string or nil.")
2456 (defvar org-export-filter-headline-functions nil
2457 "List of functions applied to a transcoded headline.
2458 Each filter is called with three arguments: the transcoded data,
2459 as a string, the back-end, as a symbol, and the communication
2460 channel, as a plist. It must return a string or nil.")
2462 (defvar org-export-filter-horizontal-rule-functions nil
2463 "List of functions applied to a transcoded horizontal-rule.
2464 Each filter is called with three arguments: the transcoded data,
2465 as a string, the back-end, as a symbol, and the communication
2466 channel, as a plist. It must return a string or nil.")
2468 (defvar org-export-filter-inlinetask-functions nil
2469 "List of functions applied to a transcoded inlinetask.
2470 Each filter is called with three arguments: the transcoded data,
2471 as a string, the back-end, as a symbol, and the communication
2472 channel, as a plist. It must return a string or nil.")
2474 (defvar org-export-filter-item-functions nil
2475 "List of functions applied to a transcoded item.
2476 Each filter is called with three arguments: the transcoded data,
2477 as a string, the back-end, as a symbol, and the communication
2478 channel, as a plist. It must return a string or nil.")
2480 (defvar org-export-filter-keyword-functions nil
2481 "List of functions applied to a transcoded keyword.
2482 Each filter is called with three arguments: the transcoded data,
2483 as a string, the back-end, as a symbol, and the communication
2484 channel, as a plist. It must return a string or nil.")
2486 (defvar org-export-filter-latex-environment-functions nil
2487 "List of functions applied to a transcoded latex-environment.
2488 Each filter is called with three arguments: the transcoded data,
2489 as a string, the back-end, as a symbol, and the communication
2490 channel, as a plist. It must return a string or nil.")
2492 (defvar org-export-filter-node-property-functions nil
2493 "List of functions applied to a transcoded node-property.
2494 Each filter is called with three arguments: the transcoded data,
2495 as a string, the back-end, as a symbol, and the communication
2496 channel, as a plist. It must return a string or nil.")
2498 (defvar org-export-filter-paragraph-functions nil
2499 "List of functions applied to a transcoded paragraph.
2500 Each filter is called with three arguments: the transcoded data,
2501 as a string, the back-end, as a symbol, and the communication
2502 channel, as a plist. It must return a string or nil.")
2504 (defvar org-export-filter-plain-list-functions nil
2505 "List of functions applied to a transcoded plain-list.
2506 Each filter is called with three arguments: the transcoded data,
2507 as a string, the back-end, as a symbol, and the communication
2508 channel, as a plist. It must return a string or nil.")
2510 (defvar org-export-filter-planning-functions nil
2511 "List of functions applied to a transcoded planning.
2512 Each filter is called with three arguments: the transcoded data,
2513 as a string, the back-end, as a symbol, and the communication
2514 channel, as a plist. It must return a string or nil.")
2516 (defvar org-export-filter-property-drawer-functions nil
2517 "List of functions applied to a transcoded property-drawer.
2518 Each filter is called with three arguments: the transcoded data,
2519 as a string, the back-end, as a symbol, and the communication
2520 channel, as a plist. It must return a string or nil.")
2522 (defvar org-export-filter-quote-block-functions nil
2523 "List of functions applied to a transcoded quote block.
2524 Each filter is called with three arguments: the transcoded quote
2525 data, as a string, the back-end, as a symbol, and the
2526 communication channel, as a plist. It must return a string or
2527 nil.")
2529 (defvar org-export-filter-quote-section-functions nil
2530 "List of functions applied to a transcoded quote-section.
2531 Each filter is called with three arguments: the transcoded data,
2532 as a string, the back-end, as a symbol, and the communication
2533 channel, as a plist. It must return a string or nil.")
2535 (defvar org-export-filter-section-functions nil
2536 "List of functions applied to a transcoded section.
2537 Each filter is called with three arguments: the transcoded data,
2538 as a string, the back-end, as a symbol, and the communication
2539 channel, as a plist. It must return a string or nil.")
2541 (defvar org-export-filter-special-block-functions nil
2542 "List of functions applied to a transcoded special block.
2543 Each filter is called with three arguments: the transcoded data,
2544 as a string, the back-end, as a symbol, and the communication
2545 channel, as a plist. It must return a string or nil.")
2547 (defvar org-export-filter-src-block-functions nil
2548 "List of functions applied to a transcoded src-block.
2549 Each filter is called with three arguments: the transcoded data,
2550 as a string, the back-end, as a symbol, and the communication
2551 channel, as a plist. It must return a string or nil.")
2553 (defvar org-export-filter-table-functions nil
2554 "List of functions applied to a transcoded table.
2555 Each filter is called with three arguments: the transcoded data,
2556 as a string, the back-end, as a symbol, and the communication
2557 channel, as a plist. It must return a string or nil.")
2559 (defvar org-export-filter-table-cell-functions nil
2560 "List of functions applied to a transcoded table-cell.
2561 Each filter is called with three arguments: the transcoded data,
2562 as a string, the back-end, as a symbol, and the communication
2563 channel, as a plist. It must return a string or nil.")
2565 (defvar org-export-filter-table-row-functions nil
2566 "List of functions applied to a transcoded table-row.
2567 Each filter is called with three arguments: the transcoded data,
2568 as a string, the back-end, as a symbol, and the communication
2569 channel, as a plist. It must return a string or nil.")
2571 (defvar org-export-filter-verse-block-functions nil
2572 "List of functions applied to a transcoded verse block.
2573 Each filter is called with three arguments: the transcoded data,
2574 as a string, the back-end, as a symbol, and the communication
2575 channel, as a plist. It must return a string or nil.")
2578 ;;;; Objects Filters
2580 (defvar org-export-filter-bold-functions nil
2581 "List of functions applied to transcoded bold text.
2582 Each filter is called with three arguments: the transcoded data,
2583 as a string, the back-end, as a symbol, and the communication
2584 channel, as a plist. It must return a string or nil.")
2586 (defvar org-export-filter-code-functions nil
2587 "List of functions applied to transcoded code text.
2588 Each filter is called with three arguments: the transcoded data,
2589 as a string, the back-end, as a symbol, and the communication
2590 channel, as a plist. It must return a string or nil.")
2592 (defvar org-export-filter-entity-functions nil
2593 "List of functions applied to a transcoded entity.
2594 Each filter is called with three arguments: the transcoded data,
2595 as a string, the back-end, as a symbol, and the communication
2596 channel, as a plist. It must return a string or nil.")
2598 (defvar org-export-filter-export-snippet-functions nil
2599 "List of functions applied to a transcoded export-snippet.
2600 Each filter is called with three arguments: the transcoded data,
2601 as a string, the back-end, as a symbol, and the communication
2602 channel, as a plist. It must return a string or nil.")
2604 (defvar org-export-filter-footnote-reference-functions nil
2605 "List of functions applied to a transcoded footnote-reference.
2606 Each filter is called with three arguments: the transcoded data,
2607 as a string, the back-end, as a symbol, and the communication
2608 channel, as a plist. It must return a string or nil.")
2610 (defvar org-export-filter-inline-babel-call-functions nil
2611 "List of functions applied to a transcoded inline-babel-call.
2612 Each filter is called with three arguments: the transcoded data,
2613 as a string, the back-end, as a symbol, and the communication
2614 channel, as a plist. It must return a string or nil.")
2616 (defvar org-export-filter-inline-src-block-functions nil
2617 "List of functions applied to a transcoded inline-src-block.
2618 Each filter is called with three arguments: the transcoded data,
2619 as a string, the back-end, as a symbol, and the communication
2620 channel, as a plist. It must return a string or nil.")
2622 (defvar org-export-filter-italic-functions nil
2623 "List of functions applied to transcoded italic text.
2624 Each filter is called with three arguments: the transcoded data,
2625 as a string, the back-end, as a symbol, and the communication
2626 channel, as a plist. It must return a string or nil.")
2628 (defvar org-export-filter-latex-fragment-functions nil
2629 "List of functions applied to a transcoded latex-fragment.
2630 Each filter is called with three arguments: the transcoded data,
2631 as a string, the back-end, as a symbol, and the communication
2632 channel, as a plist. It must return a string or nil.")
2634 (defvar org-export-filter-line-break-functions nil
2635 "List of functions applied to a transcoded line-break.
2636 Each filter is called with three arguments: the transcoded data,
2637 as a string, the back-end, as a symbol, and the communication
2638 channel, as a plist. It must return a string or nil.")
2640 (defvar org-export-filter-link-functions nil
2641 "List of functions applied to a transcoded link.
2642 Each filter is called with three arguments: the transcoded data,
2643 as a string, the back-end, as a symbol, and the communication
2644 channel, as a plist. It must return a string or nil.")
2646 (defvar org-export-filter-radio-target-functions nil
2647 "List of functions applied to a transcoded radio-target.
2648 Each filter is called with three arguments: the transcoded data,
2649 as a string, the back-end, as a symbol, and the communication
2650 channel, as a plist. It must return a string or nil.")
2652 (defvar org-export-filter-statistics-cookie-functions nil
2653 "List of functions applied to a transcoded statistics-cookie.
2654 Each filter is called with three arguments: the transcoded data,
2655 as a string, the back-end, as a symbol, and the communication
2656 channel, as a plist. It must return a string or nil.")
2658 (defvar org-export-filter-strike-through-functions nil
2659 "List of functions applied to transcoded strike-through text.
2660 Each filter is called with three arguments: the transcoded data,
2661 as a string, the back-end, as a symbol, and the communication
2662 channel, as a plist. It must return a string or nil.")
2664 (defvar org-export-filter-subscript-functions nil
2665 "List of functions applied to a transcoded subscript.
2666 Each filter is called with three arguments: the transcoded data,
2667 as a string, the back-end, as a symbol, and the communication
2668 channel, as a plist. It must return a string or nil.")
2670 (defvar org-export-filter-superscript-functions nil
2671 "List of functions applied to a transcoded superscript.
2672 Each filter is called with three arguments: the transcoded data,
2673 as a string, the back-end, as a symbol, and the communication
2674 channel, as a plist. It must return a string or nil.")
2676 (defvar org-export-filter-target-functions nil
2677 "List of functions applied to a transcoded target.
2678 Each filter is called with three arguments: the transcoded data,
2679 as a string, the back-end, as a symbol, and the communication
2680 channel, as a plist. It must return a string or nil.")
2682 (defvar org-export-filter-timestamp-functions nil
2683 "List of functions applied to a transcoded timestamp.
2684 Each filter is called with three arguments: the transcoded data,
2685 as a string, the back-end, as a symbol, and the communication
2686 channel, as a plist. It must return a string or nil.")
2688 (defvar org-export-filter-underline-functions nil
2689 "List of functions applied to transcoded underline text.
2690 Each filter is called with three arguments: the transcoded data,
2691 as a string, the back-end, as a symbol, and the communication
2692 channel, as a plist. It must return a string or nil.")
2694 (defvar org-export-filter-verbatim-functions nil
2695 "List of functions applied to transcoded verbatim text.
2696 Each filter is called with three arguments: the transcoded data,
2697 as a string, the back-end, as a symbol, and the communication
2698 channel, as a plist. It must return a string or nil.")
2701 ;;;; Filters Tools
2703 ;; Internal function `org-export-install-filters' installs filters
2704 ;; hard-coded in back-ends (developer filters) and filters from global
2705 ;; variables (user filters) in the communication channel.
2707 ;; Internal function `org-export-filter-apply-functions' takes care
2708 ;; about applying each filter in order to a given data. It ignores
2709 ;; filters returning a nil value but stops whenever a filter returns
2710 ;; an empty string.
2712 (defun org-export-filter-apply-functions (filters value info)
2713 "Call every function in FILTERS.
2715 Functions are called with arguments VALUE, current export
2716 back-end and INFO. A function returning a nil value will be
2717 skipped. If it returns the empty string, the process ends and
2718 VALUE is ignored.
2720 Call is done in a LIFO fashion, to be sure that developer
2721 specified filters, if any, are called first."
2722 (catch 'exit
2723 (dolist (filter filters value)
2724 (let ((result (funcall filter value (plist-get info :back-end) info)))
2725 (cond ((not result) value)
2726 ((equal value "") (throw 'exit nil))
2727 (t (setq value result)))))))
2729 (defun org-export-install-filters (info)
2730 "Install filters properties in communication channel.
2731 INFO is a plist containing the current communication channel.
2732 Return the updated communication channel."
2733 (let (plist)
2734 ;; Install user-defined filters with `org-export-filters-alist'
2735 ;; and filters already in INFO (through ext-plist mechanism).
2736 (mapc (lambda (p)
2737 (let* ((prop (car p))
2738 (info-value (plist-get info prop))
2739 (default-value (symbol-value (cdr p))))
2740 (setq plist
2741 (plist-put plist prop
2742 ;; Filters in INFO will be called
2743 ;; before those user provided.
2744 (append (if (listp info-value) info-value
2745 (list info-value))
2746 default-value)))))
2747 org-export-filters-alist)
2748 ;; Prepend back-end specific filters to that list.
2749 (mapc (lambda (p)
2750 ;; Single values get consed, lists are appended.
2751 (let ((key (car p)) (value (cdr p)))
2752 (when value
2753 (setq plist
2754 (plist-put
2755 plist key
2756 (if (atom value) (cons value (plist-get plist key))
2757 (append value (plist-get plist key))))))))
2758 (org-export-backend-filters (plist-get info :back-end)))
2759 ;; Return new communication channel.
2760 (org-combine-plists info plist)))
2764 ;;; Core functions
2766 ;; This is the room for the main function, `org-export-as', along with
2767 ;; its derivatives, `org-export-to-buffer', `org-export-to-file' and
2768 ;; `org-export-string-as'. They differ either by the way they output
2769 ;; the resulting code (for the first two) or by the input type (for
2770 ;; the latter). `org-export--copy-to-kill-ring-p' determines if
2771 ;; output of these function should be added to kill ring.
2773 ;; `org-export-output-file-name' is an auxiliary function meant to be
2774 ;; used with `org-export-to-file'. With a given extension, it tries
2775 ;; to provide a canonical file name to write export output to.
2777 ;; Note that `org-export-as' doesn't really parse the current buffer,
2778 ;; but a copy of it (with the same buffer-local variables and
2779 ;; visibility), where macros and include keywords are expanded and
2780 ;; Babel blocks are executed, if appropriate.
2781 ;; `org-export-with-buffer-copy' macro prepares that copy.
2783 ;; File inclusion is taken care of by
2784 ;; `org-export-expand-include-keyword' and
2785 ;; `org-export--prepare-file-contents'. Structure wise, including
2786 ;; a whole Org file in a buffer often makes little sense. For
2787 ;; example, if the file contains a headline and the include keyword
2788 ;; was within an item, the item should contain the headline. That's
2789 ;; why file inclusion should be done before any structure can be
2790 ;; associated to the file, that is before parsing.
2792 ;; `org-export-insert-default-template' is a command to insert
2793 ;; a default template (or a back-end specific template) at point or in
2794 ;; current subtree.
2796 (defun org-export-copy-buffer ()
2797 "Return a copy of the current buffer.
2798 The copy preserves Org buffer-local variables, visibility and
2799 narrowing."
2800 (let ((copy-buffer-fun (org-export--generate-copy-script (current-buffer)))
2801 (new-buf (generate-new-buffer (buffer-name))))
2802 (with-current-buffer new-buf
2803 (funcall copy-buffer-fun)
2804 (set-buffer-modified-p nil))
2805 new-buf))
2807 (defmacro org-export-with-buffer-copy (&rest body)
2808 "Apply BODY in a copy of the current buffer.
2809 The copy preserves local variables, visibility and contents of
2810 the original buffer. Point is at the beginning of the buffer
2811 when BODY is applied."
2812 (declare (debug t))
2813 (org-with-gensyms (buf-copy)
2814 `(let ((,buf-copy (org-export-copy-buffer)))
2815 (unwind-protect
2816 (with-current-buffer ,buf-copy
2817 (goto-char (point-min))
2818 (progn ,@body))
2819 (and (buffer-live-p ,buf-copy)
2820 ;; Kill copy without confirmation.
2821 (progn (with-current-buffer ,buf-copy
2822 (restore-buffer-modified-p nil))
2823 (kill-buffer ,buf-copy)))))))
2825 (defun org-export--generate-copy-script (buffer)
2826 "Generate a function duplicating BUFFER.
2828 The copy will preserve local variables, visibility, contents and
2829 narrowing of the original buffer. If a region was active in
2830 BUFFER, contents will be narrowed to that region instead.
2832 The resulting function can be evaled at a later time, from
2833 another buffer, effectively cloning the original buffer there.
2835 The function assumes BUFFER's major mode is `org-mode'."
2836 (with-current-buffer buffer
2837 `(lambda ()
2838 (let ((inhibit-modification-hooks t))
2839 ;; Set major mode. Ignore `org-mode-hook' as it has been run
2840 ;; already in BUFFER.
2841 (let ((org-mode-hook nil) (org-inhibit-startup t)) (org-mode))
2842 ;; Copy specific buffer local variables and variables set
2843 ;; through BIND keywords.
2844 ,@(let ((bound-variables (org-export--list-bound-variables))
2845 vars)
2846 (dolist (entry (buffer-local-variables (buffer-base-buffer)) vars)
2847 (when (consp entry)
2848 (let ((var (car entry))
2849 (val (cdr entry)))
2850 (and (not (eq var 'org-font-lock-keywords))
2851 (or (memq var
2852 '(default-directory
2853 buffer-file-name
2854 buffer-file-coding-system))
2855 (assq var bound-variables)
2856 (string-match "^\\(org-\\|orgtbl-\\)"
2857 (symbol-name var)))
2858 ;; Skip unreadable values, as they cannot be
2859 ;; sent to external process.
2860 (or (not val) (ignore-errors (read (format "%S" val))))
2861 (push `(set (make-local-variable (quote ,var))
2862 (quote ,val))
2863 vars))))))
2864 ;; Whole buffer contents.
2865 (insert
2866 ,(org-with-wide-buffer
2867 (buffer-substring-no-properties
2868 (point-min) (point-max))))
2869 ;; Narrowing.
2870 ,(if (org-region-active-p)
2871 `(narrow-to-region ,(region-beginning) ,(region-end))
2872 `(narrow-to-region ,(point-min) ,(point-max)))
2873 ;; Current position of point.
2874 (goto-char ,(point))
2875 ;; Overlays with invisible property.
2876 ,@(let (ov-set)
2877 (mapc
2878 (lambda (ov)
2879 (let ((invis-prop (overlay-get ov 'invisible)))
2880 (when invis-prop
2881 (push `(overlay-put
2882 (make-overlay ,(overlay-start ov)
2883 ,(overlay-end ov))
2884 'invisible (quote ,invis-prop))
2885 ov-set))))
2886 (overlays-in (point-min) (point-max)))
2887 ov-set)))))
2889 ;;;###autoload
2890 (defun org-export-as
2891 (backend &optional subtreep visible-only body-only ext-plist)
2892 "Transcode current Org buffer into BACKEND code.
2894 If narrowing is active in the current buffer, only transcode its
2895 narrowed part.
2897 If a region is active, transcode that region.
2899 When optional argument SUBTREEP is non-nil, transcode the
2900 sub-tree at point, extracting information from the headline
2901 properties first.
2903 When optional argument VISIBLE-ONLY is non-nil, don't export
2904 contents of hidden elements.
2906 When optional argument BODY-ONLY is non-nil, only return body
2907 code, without surrounding template.
2909 Optional argument EXT-PLIST, when provided, is a property list
2910 with external parameters overriding Org default settings, but
2911 still inferior to file-local settings.
2913 Return code as a string."
2914 (org-export-barf-if-invalid-backend backend)
2915 (save-excursion
2916 (save-restriction
2917 ;; Narrow buffer to an appropriate region or subtree for
2918 ;; parsing. If parsing subtree, be sure to remove main headline
2919 ;; too.
2920 (cond ((org-region-active-p)
2921 (narrow-to-region (region-beginning) (region-end)))
2922 (subtreep
2923 (org-narrow-to-subtree)
2924 (goto-char (point-min))
2925 (forward-line)
2926 (narrow-to-region (point) (point-max))))
2927 ;; Initialize communication channel with original buffer
2928 ;; attributes, unavailable in its copy.
2929 (let* ((info (org-combine-plists
2930 (list :export-options
2931 (delq nil
2932 (list (and subtreep 'subtree)
2933 (and visible-only 'visible-only)
2934 (and body-only 'body-only))))
2935 (org-export--get-buffer-attributes)))
2936 tree)
2937 ;; Store default title in `org-export--default-title' so that
2938 ;; `org-export-get-environment' can access it from buffer's
2939 ;; copy and then add it properly to communication channel.
2940 (org-export-store-default-title)
2941 ;; Update communication channel and get parse tree. Buffer
2942 ;; isn't parsed directly. Instead, a temporary copy is
2943 ;; created, where include keywords, macros are expanded and
2944 ;; code blocks are evaluated.
2945 (org-export-with-buffer-copy
2946 ;; Run first hook with current back-end as argument.
2947 (run-hook-with-args 'org-export-before-processing-hook backend)
2948 (org-export-expand-include-keyword)
2949 ;; Update macro templates since #+INCLUDE keywords might have
2950 ;; added some new ones.
2951 (org-macro-initialize-templates)
2952 (org-macro-replace-all org-macro-templates)
2953 (org-export-execute-babel-code)
2954 ;; Update radio targets since keyword inclusion might have
2955 ;; added some more.
2956 (org-update-radio-target-regexp)
2957 ;; Run last hook with current back-end as argument.
2958 (goto-char (point-min))
2959 (save-excursion
2960 (run-hook-with-args 'org-export-before-parsing-hook backend))
2961 ;; Update communication channel with environment. Also
2962 ;; install user's and developer's filters.
2963 (setq info
2964 (org-export-install-filters
2965 (org-combine-plists
2966 info (org-export-get-environment backend subtreep ext-plist))))
2967 ;; Expand export-specific set of macros: {{{author}}},
2968 ;; {{{date}}}, {{{email}}} and {{{title}}}. It must be done
2969 ;; once regular macros have been expanded, since document
2970 ;; keywords may contain one of them.
2971 (org-macro-replace-all
2972 (list (cons "author"
2973 (org-element-interpret-data (plist-get info :author)))
2974 (cons "date"
2975 (org-element-interpret-data (plist-get info :date)))
2976 ;; EMAIL is not a parsed keyword: store it as-is.
2977 (cons "email" (or (plist-get info :email) ""))
2978 (cons "title"
2979 (org-element-interpret-data (plist-get info :title)))))
2980 ;; Call options filters and update export options. We do not
2981 ;; use `org-export-filter-apply-functions' here since the
2982 ;; arity of such filters is different.
2983 (dolist (filter (plist-get info :filter-options))
2984 (let ((result (funcall filter info backend)))
2985 (when result (setq info result))))
2986 ;; Parse buffer and call parse-tree filter on it.
2987 (setq tree
2988 (org-export-filter-apply-functions
2989 (plist-get info :filter-parse-tree)
2990 (org-element-parse-buffer nil visible-only) info))
2991 ;; Now tree is complete, compute its properties and add them
2992 ;; to communication channel.
2993 (setq info
2994 (org-combine-plists
2995 info (org-export-collect-tree-properties tree info)))
2996 ;; Eventually transcode TREE. Wrap the resulting string into
2997 ;; a template.
2998 (let* ((body (org-element-normalize-string
2999 (or (org-export-data tree info) "")))
3000 (inner-template (cdr (assq 'inner-template
3001 (plist-get info :translate-alist))))
3002 (full-body (if (not (functionp inner-template)) body
3003 (funcall inner-template body info)))
3004 (template (cdr (assq 'template
3005 (plist-get info :translate-alist)))))
3006 ;; Remove all text properties since they cannot be
3007 ;; retrieved from an external process. Finally call
3008 ;; final-output filter and return result.
3009 (org-no-properties
3010 (org-export-filter-apply-functions
3011 (plist-get info :filter-final-output)
3012 (if (or (not (functionp template)) body-only) full-body
3013 (funcall template full-body info))
3014 info))))))))
3016 ;;;###autoload
3017 (defun org-export-to-buffer
3018 (backend buffer &optional subtreep visible-only body-only ext-plist)
3019 "Call `org-export-as' with output to a specified buffer.
3021 BACKEND is the back-end used for transcoding, as a symbol.
3023 BUFFER is the output buffer. If it already exists, it will be
3024 erased first, otherwise, it will be created.
3026 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
3027 EXT-PLIST are similar to those used in `org-export-as', which
3028 see.
3030 Depending on `org-export-copy-to-kill-ring', add buffer contents
3031 to kill ring. Return buffer."
3032 (let ((out (org-export-as backend subtreep visible-only body-only ext-plist))
3033 (buffer (get-buffer-create buffer)))
3034 (with-current-buffer buffer
3035 (erase-buffer)
3036 (insert out)
3037 (goto-char (point-min)))
3038 ;; Maybe add buffer contents to kill ring.
3039 (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p out))
3040 (org-kill-new out))
3041 ;; Return buffer.
3042 buffer))
3044 ;;;###autoload
3045 (defun org-export-to-file
3046 (backend file &optional subtreep visible-only body-only ext-plist)
3047 "Call `org-export-as' with output to a specified file.
3049 BACKEND is the back-end used for transcoding, as a symbol. FILE
3050 is the name of the output file, as a string.
3052 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
3053 EXT-PLIST are similar to those used in `org-export-as', which
3054 see.
3056 Depending on `org-export-copy-to-kill-ring', add file contents
3057 to kill ring. Return output file's name."
3058 ;; Checks for FILE permissions. `write-file' would do the same, but
3059 ;; we'd rather avoid needless transcoding of parse tree.
3060 (unless (file-writable-p file) (error "Output file not writable"))
3061 ;; Insert contents to a temporary buffer and write it to FILE.
3062 (let ((out (org-export-as backend subtreep visible-only body-only ext-plist)))
3063 (with-temp-buffer
3064 (insert out)
3065 (let ((coding-system-for-write org-export-coding-system))
3066 (write-file file)))
3067 ;; Maybe add file contents to kill ring.
3068 (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p out))
3069 (org-kill-new out)))
3070 ;; Return full path.
3071 file)
3073 ;;;###autoload
3074 (defun org-export-string-as (string backend &optional body-only ext-plist)
3075 "Transcode STRING into BACKEND code.
3077 When optional argument BODY-ONLY is non-nil, only return body
3078 code, without preamble nor postamble.
3080 Optional argument EXT-PLIST, when provided, is a property list
3081 with external parameters overriding Org default settings, but
3082 still inferior to file-local settings.
3084 Return code as a string."
3085 (with-temp-buffer
3086 (insert string)
3087 (let ((org-inhibit-startup t)) (org-mode))
3088 (org-export-as backend nil nil body-only ext-plist)))
3090 ;;;###autoload
3091 (defun org-export-replace-region-by (backend)
3092 "Replace the active region by its export to BACKEND."
3093 (if (not (org-region-active-p))
3094 (user-error "No active region to replace")
3095 (let* ((beg (region-beginning))
3096 (end (region-end))
3097 (str (buffer-substring beg end)) rpl)
3098 (setq rpl (org-export-string-as str backend t))
3099 (delete-region beg end)
3100 (insert rpl))))
3102 ;;;###autoload
3103 (defun org-export-insert-default-template (&optional backend subtreep)
3104 "Insert all export keywords with default values at beginning of line.
3106 BACKEND is a symbol representing the export back-end for which
3107 specific export options should be added to the template, or
3108 `default' for default template. When it is nil, the user will be
3109 prompted for a category.
3111 If SUBTREEP is non-nil, export configuration will be set up
3112 locally for the subtree through node properties."
3113 (interactive)
3114 (unless (derived-mode-p 'org-mode) (user-error "Not in an Org mode buffer"))
3115 (when (and subtreep (org-before-first-heading-p))
3116 (user-error "No subtree to set export options for"))
3117 (let ((node (and subtreep (save-excursion (org-back-to-heading t) (point))))
3118 (backend (or backend
3119 (intern
3120 (org-completing-read
3121 "Options category: "
3122 (cons "default"
3123 (mapcar (lambda (b) (symbol-name (car b)))
3124 org-export-registered-backends))))))
3125 options keywords)
3126 ;; Populate OPTIONS and KEYWORDS.
3127 (dolist (entry (if (eq backend 'default) org-export-options-alist
3128 (org-export-backend-options backend)))
3129 (let ((keyword (nth 1 entry))
3130 (option (nth 2 entry)))
3131 (cond
3132 (keyword (unless (assoc keyword keywords)
3133 (let ((value
3134 (if (eq (nth 4 entry) 'split)
3135 (mapconcat 'identity (eval (nth 3 entry)) " ")
3136 (eval (nth 3 entry)))))
3137 (push (cons keyword value) keywords))))
3138 (option (unless (assoc option options)
3139 (push (cons option (eval (nth 3 entry))) options))))))
3140 ;; Move to an appropriate location in order to insert options.
3141 (unless subtreep (beginning-of-line))
3142 ;; First get TITLE, DATE, AUTHOR and EMAIL if they belong to the
3143 ;; list of available keywords.
3144 (when (assoc "TITLE" keywords)
3145 (let ((title
3146 (or (let ((visited-file (buffer-file-name (buffer-base-buffer))))
3147 (and visited-file
3148 (file-name-sans-extension
3149 (file-name-nondirectory visited-file))))
3150 (buffer-name (buffer-base-buffer)))))
3151 (if (not subtreep) (insert (format "#+TITLE: %s\n" title))
3152 (org-entry-put node "EXPORT_TITLE" title))))
3153 (when (assoc "DATE" keywords)
3154 (let ((date (with-temp-buffer (org-insert-time-stamp (current-time)))))
3155 (if (not subtreep) (insert "#+DATE: " date "\n")
3156 (org-entry-put node "EXPORT_DATE" date))))
3157 (when (assoc "AUTHOR" keywords)
3158 (let ((author (cdr (assoc "AUTHOR" keywords))))
3159 (if subtreep (org-entry-put node "EXPORT_AUTHOR" author)
3160 (insert
3161 (format "#+AUTHOR:%s\n"
3162 (if (not (org-string-nw-p author)) ""
3163 (concat " " author)))))))
3164 (when (assoc "EMAIL" keywords)
3165 (let ((email (cdr (assoc "EMAIL" keywords))))
3166 (if subtreep (org-entry-put node "EXPORT_EMAIL" email)
3167 (insert
3168 (format "#+EMAIL:%s\n"
3169 (if (not (org-string-nw-p email)) ""
3170 (concat " " email)))))))
3171 ;; Then (multiple) OPTIONS lines. Never go past fill-column.
3172 (when options
3173 (let ((items
3174 (mapcar
3175 (lambda (opt)
3176 (format "%s:%s" (car opt) (format "%s" (cdr opt))))
3177 (sort options (lambda (k1 k2) (string< (car k1) (car k2)))))))
3178 (if subtreep
3179 (org-entry-put
3180 node "EXPORT_OPTIONS" (mapconcat 'identity items " "))
3181 (while items
3182 (insert "#+OPTIONS:")
3183 (let ((width 10))
3184 (while (and items
3185 (< (+ width (length (car items)) 1) fill-column))
3186 (let ((item (pop items)))
3187 (insert " " item)
3188 (incf width (1+ (length item))))))
3189 (insert "\n")))))
3190 ;; And the rest of keywords.
3191 (dolist (key (sort keywords (lambda (k1 k2) (string< (car k1) (car k2)))))
3192 (unless (member (car key) '("TITLE" "DATE" "AUTHOR" "EMAIL"))
3193 (let ((val (cdr key)))
3194 (if subtreep (org-entry-put node (concat "EXPORT_" (car key)) val)
3195 (insert
3196 (format "#+%s:%s\n"
3197 (car key)
3198 (if (org-string-nw-p val) (format " %s" val) "")))))))))
3200 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
3201 "Return output file's name according to buffer specifications.
3203 EXTENSION is a string representing the output file extension,
3204 with the leading dot.
3206 With a non-nil optional argument SUBTREEP, try to determine
3207 output file's name by looking for \"EXPORT_FILE_NAME\" property
3208 of subtree at point.
3210 When optional argument PUB-DIR is set, use it as the publishing
3211 directory.
3213 When optional argument VISIBLE-ONLY is non-nil, don't export
3214 contents of hidden elements.
3216 Return file name as a string."
3217 (let* ((visited-file (buffer-file-name (buffer-base-buffer)))
3218 (base-name
3219 ;; File name may come from EXPORT_FILE_NAME subtree
3220 ;; property, assuming point is at beginning of said
3221 ;; sub-tree.
3222 (file-name-sans-extension
3223 (or (and subtreep
3224 (org-entry-get
3225 (save-excursion
3226 (ignore-errors (org-back-to-heading) (point)))
3227 "EXPORT_FILE_NAME" t))
3228 ;; File name may be extracted from buffer's associated
3229 ;; file, if any.
3230 (and visited-file (file-name-nondirectory visited-file))
3231 ;; Can't determine file name on our own: Ask user.
3232 (let ((read-file-name-function
3233 (and org-completion-use-ido 'ido-read-file-name)))
3234 (read-file-name
3235 "Output file: " pub-dir nil nil nil
3236 (lambda (name)
3237 (string= (file-name-extension name t) extension)))))))
3238 (output-file
3239 ;; Build file name. Enforce EXTENSION over whatever user
3240 ;; may have come up with. PUB-DIR, if defined, always has
3241 ;; precedence over any provided path.
3242 (cond
3243 (pub-dir
3244 (concat (file-name-as-directory pub-dir)
3245 (file-name-nondirectory base-name)
3246 extension))
3247 ((file-name-absolute-p base-name) (concat base-name extension))
3248 (t (concat (file-name-as-directory ".") base-name extension)))))
3249 ;; If writing to OUTPUT-FILE would overwrite original file, append
3250 ;; EXTENSION another time to final name.
3251 (if (and visited-file (org-file-equal-p visited-file output-file))
3252 (concat output-file extension)
3253 output-file)))
3255 (defun org-export-expand-include-keyword (&optional included dir)
3256 "Expand every include keyword in buffer.
3257 Optional argument INCLUDED is a list of included file names along
3258 with their line restriction, when appropriate. It is used to
3259 avoid infinite recursion. Optional argument DIR is the current
3260 working directory. It is used to properly resolve relative
3261 paths."
3262 (let ((case-fold-search t))
3263 (goto-char (point-min))
3264 (while (re-search-forward "^[ \t]*#\\+INCLUDE:" nil t)
3265 (let ((element (save-match-data (org-element-at-point))))
3266 (when (eq (org-element-type element) 'keyword)
3267 (beginning-of-line)
3268 ;; Extract arguments from keyword's value.
3269 (let* ((value (org-element-property :value element))
3270 (ind (org-get-indentation))
3271 (file (and (string-match
3272 "^\\(\".+?\"\\|\\S-+\\)\\(?:\\s-+\\|$\\)" value)
3273 (prog1 (expand-file-name
3274 (org-remove-double-quotes
3275 (match-string 1 value))
3276 dir)
3277 (setq value (replace-match "" nil nil value)))))
3278 (lines
3279 (and (string-match
3280 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\""
3281 value)
3282 (prog1 (match-string 1 value)
3283 (setq value (replace-match "" nil nil value)))))
3284 (env (cond ((string-match "\\<example\\>" value) 'example)
3285 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
3286 (match-string 1 value))))
3287 ;; Minimal level of included file defaults to the child
3288 ;; level of the current headline, if any, or one. It
3289 ;; only applies is the file is meant to be included as
3290 ;; an Org one.
3291 (minlevel
3292 (and (not env)
3293 (if (string-match ":minlevel +\\([0-9]+\\)" value)
3294 (prog1 (string-to-number (match-string 1 value))
3295 (setq value (replace-match "" nil nil value)))
3296 (let ((cur (org-current-level)))
3297 (if cur (1+ (org-reduced-level cur)) 1))))))
3298 ;; Remove keyword.
3299 (delete-region (point) (progn (forward-line) (point)))
3300 (cond
3301 ((not file) nil)
3302 ((not (file-readable-p file))
3303 (error "Cannot include file %s" file))
3304 ;; Check if files has already been parsed. Look after
3305 ;; inclusion lines too, as different parts of the same file
3306 ;; can be included too.
3307 ((member (list file lines) included)
3308 (error "Recursive file inclusion: %s" file))
3310 (cond
3311 ((eq env 'example)
3312 (insert
3313 (let ((ind-str (make-string ind ? ))
3314 (contents
3315 (org-escape-code-in-string
3316 (org-export--prepare-file-contents file lines))))
3317 (format "%s#+BEGIN_EXAMPLE\n%s%s#+END_EXAMPLE\n"
3318 ind-str contents ind-str))))
3319 ((stringp env)
3320 (insert
3321 (let ((ind-str (make-string ind ? ))
3322 (contents
3323 (org-escape-code-in-string
3324 (org-export--prepare-file-contents file lines))))
3325 (format "%s#+BEGIN_SRC %s\n%s%s#+END_SRC\n"
3326 ind-str env contents ind-str))))
3328 (insert
3329 (with-temp-buffer
3330 (let ((org-inhibit-startup t)) (org-mode))
3331 (insert
3332 (org-export--prepare-file-contents file lines ind minlevel))
3333 (org-export-expand-include-keyword
3334 (cons (list file lines) included)
3335 (file-name-directory file))
3336 (buffer-string)))))))))))))
3338 (defun org-export--prepare-file-contents (file &optional lines ind minlevel)
3339 "Prepare the contents of FILE for inclusion and return them as a string.
3341 When optional argument LINES is a string specifying a range of
3342 lines, include only those lines.
3344 Optional argument IND, when non-nil, is an integer specifying the
3345 global indentation of returned contents. Since its purpose is to
3346 allow an included file to stay in the same environment it was
3347 created \(i.e. a list item), it doesn't apply past the first
3348 headline encountered.
3350 Optional argument MINLEVEL, when non-nil, is an integer
3351 specifying the level that any top-level headline in the included
3352 file should have."
3353 (with-temp-buffer
3354 (insert-file-contents file)
3355 (when lines
3356 (let* ((lines (split-string lines "-"))
3357 (lbeg (string-to-number (car lines)))
3358 (lend (string-to-number (cadr lines)))
3359 (beg (if (zerop lbeg) (point-min)
3360 (goto-char (point-min))
3361 (forward-line (1- lbeg))
3362 (point)))
3363 (end (if (zerop lend) (point-max)
3364 (goto-char (point-min))
3365 (forward-line (1- lend))
3366 (point))))
3367 (narrow-to-region beg end)))
3368 ;; Remove blank lines at beginning and end of contents. The logic
3369 ;; behind that removal is that blank lines around include keyword
3370 ;; override blank lines in included file.
3371 (goto-char (point-min))
3372 (org-skip-whitespace)
3373 (beginning-of-line)
3374 (delete-region (point-min) (point))
3375 (goto-char (point-max))
3376 (skip-chars-backward " \r\t\n")
3377 (forward-line)
3378 (delete-region (point) (point-max))
3379 ;; If IND is set, preserve indentation of include keyword until
3380 ;; the first headline encountered.
3381 (when ind
3382 (unless (eq major-mode 'org-mode)
3383 (let ((org-inhibit-startup t)) (org-mode)))
3384 (goto-char (point-min))
3385 (let ((ind-str (make-string ind ? )))
3386 (while (not (or (eobp) (looking-at org-outline-regexp-bol)))
3387 ;; Do not move footnote definitions out of column 0.
3388 (unless (and (looking-at org-footnote-definition-re)
3389 (eq (org-element-type (org-element-at-point))
3390 'footnote-definition))
3391 (insert ind-str))
3392 (forward-line))))
3393 ;; When MINLEVEL is specified, compute minimal level for headlines
3394 ;; in the file (CUR-MIN), and remove stars to each headline so
3395 ;; that headlines with minimal level have a level of MINLEVEL.
3396 (when minlevel
3397 (unless (eq major-mode 'org-mode)
3398 (let ((org-inhibit-startup t)) (org-mode)))
3399 (org-with-limited-levels
3400 (let ((levels (org-map-entries
3401 (lambda () (org-reduced-level (org-current-level))))))
3402 (when levels
3403 (let ((offset (- minlevel (apply 'min levels))))
3404 (unless (zerop offset)
3405 (when org-odd-levels-only (setq offset (* offset 2)))
3406 ;; Only change stars, don't bother moving whole
3407 ;; sections.
3408 (org-map-entries
3409 (lambda () (if (< offset 0) (delete-char (abs offset))
3410 (insert (make-string offset ?*)))))))))))
3411 (org-element-normalize-string (buffer-string))))
3413 (defun org-export-execute-babel-code ()
3414 "Execute every Babel code in the visible part of current buffer."
3415 ;; Get a pristine copy of current buffer so Babel references can be
3416 ;; properly resolved.
3417 (let ((reference (org-export-copy-buffer)))
3418 (unwind-protect (let ((org-current-export-file reference))
3419 (org-babel-exp-process-buffer))
3420 (kill-buffer reference))))
3422 (defun org-export--copy-to-kill-ring-p ()
3423 "Return a non-nil value when output should be added to the kill ring.
3424 See also `org-export-copy-to-kill-ring'."
3425 (if (eq org-export-copy-to-kill-ring 'if-interactive)
3426 (not (or executing-kbd-macro noninteractive))
3427 (eq org-export-copy-to-kill-ring t)))
3431 ;;; Tools For Back-Ends
3433 ;; A whole set of tools is available to help build new exporters. Any
3434 ;; function general enough to have its use across many back-ends
3435 ;; should be added here.
3437 ;;;; For Affiliated Keywords
3439 ;; `org-export-read-attribute' reads a property from a given element
3440 ;; as a plist. It can be used to normalize affiliated keywords'
3441 ;; syntax.
3443 ;; Since captions can span over multiple lines and accept dual values,
3444 ;; their internal representation is a bit tricky. Therefore,
3445 ;; `org-export-get-caption' transparently returns a given element's
3446 ;; caption as a secondary string.
3448 (defun org-export-read-attribute (attribute element &optional property)
3449 "Turn ATTRIBUTE property from ELEMENT into a plist.
3451 When optional argument PROPERTY is non-nil, return the value of
3452 that property within attributes.
3454 This function assumes attributes are defined as \":keyword
3455 value\" pairs. It is appropriate for `:attr_html' like
3456 properties.
3458 All values will become strings except the empty string and
3459 \"nil\", which will become nil. Also, values containing only
3460 double quotes will be read as-is, which means that \"\" value
3461 will become the empty string."
3462 (let* ((prepare-value
3463 (lambda (str)
3464 (save-match-data
3465 (cond ((member str '(nil "" "nil")) nil)
3466 ((string-match "^\"\\(\"+\\)?\"$" str)
3467 (or (match-string 1 str) ""))
3468 (t str)))))
3469 (attributes
3470 (let ((value (org-element-property attribute element)))
3471 (when value
3472 (let ((s (mapconcat 'identity value " ")) result)
3473 (while (string-match
3474 "\\(?:^\\|[ \t]+\\)\\(:[-a-zA-Z0-9_]+\\)\\([ \t]+\\|$\\)"
3476 (let ((value (substring s 0 (match-beginning 0))))
3477 (push (funcall prepare-value value) result))
3478 (push (intern (match-string 1 s)) result)
3479 (setq s (substring s (match-end 0))))
3480 ;; Ignore any string before first property with `cdr'.
3481 (cdr (nreverse (cons (funcall prepare-value s) result))))))))
3482 (if property (plist-get attributes property) attributes)))
3484 (defun org-export-get-caption (element &optional shortp)
3485 "Return caption from ELEMENT as a secondary string.
3487 When optional argument SHORTP is non-nil, return short caption,
3488 as a secondary string, instead.
3490 Caption lines are separated by a white space."
3491 (let ((full-caption (org-element-property :caption element)) caption)
3492 (dolist (line full-caption (cdr caption))
3493 (let ((cap (funcall (if shortp 'cdr 'car) line)))
3494 (when cap
3495 (setq caption (nconc (list " ") (copy-sequence cap) caption)))))))
3498 ;;;; For Derived Back-ends
3500 ;; `org-export-with-backend' is a function allowing to locally use
3501 ;; another back-end to transcode some object or element. In a derived
3502 ;; back-end, it may be used as a fall-back function once all specific
3503 ;; cases have been treated.
3505 (defun org-export-with-backend (back-end data &optional contents info)
3506 "Call a transcoder from BACK-END on DATA.
3507 CONTENTS, when non-nil, is the transcoded contents of DATA
3508 element, as a string. INFO, when non-nil, is the communication
3509 channel used for export, as a plist.."
3510 (org-export-barf-if-invalid-backend back-end)
3511 (let ((type (org-element-type data)))
3512 (if (memq type '(nil org-data)) (error "No foreign transcoder available")
3513 (let ((transcoder
3514 (cdr (assq type (org-export-backend-translate-table back-end)))))
3515 (if (functionp transcoder) (funcall transcoder data contents info)
3516 (error "No foreign transcoder available"))))))
3519 ;;;; For Export Snippets
3521 ;; Every export snippet is transmitted to the back-end. Though, the
3522 ;; latter will only retain one type of export-snippet, ignoring
3523 ;; others, based on the former's target back-end. The function
3524 ;; `org-export-snippet-backend' returns that back-end for a given
3525 ;; export-snippet.
3527 (defun org-export-snippet-backend (export-snippet)
3528 "Return EXPORT-SNIPPET targeted back-end as a symbol.
3529 Translation, with `org-export-snippet-translation-alist', is
3530 applied."
3531 (let ((back-end (org-element-property :back-end export-snippet)))
3532 (intern
3533 (or (cdr (assoc back-end org-export-snippet-translation-alist))
3534 back-end))))
3537 ;;;; For Footnotes
3539 ;; `org-export-collect-footnote-definitions' is a tool to list
3540 ;; actually used footnotes definitions in the whole parse tree, or in
3541 ;; a headline, in order to add footnote listings throughout the
3542 ;; transcoded data.
3544 ;; `org-export-footnote-first-reference-p' is a predicate used by some
3545 ;; back-ends, when they need to attach the footnote definition only to
3546 ;; the first occurrence of the corresponding label.
3548 ;; `org-export-get-footnote-definition' and
3549 ;; `org-export-get-footnote-number' provide easier access to
3550 ;; additional information relative to a footnote reference.
3552 (defun org-export-collect-footnote-definitions (data info)
3553 "Return an alist between footnote numbers, labels and definitions.
3555 DATA is the parse tree from which definitions are collected.
3556 INFO is the plist used as a communication channel.
3558 Definitions are sorted by order of references. They either
3559 appear as Org data or as a secondary string for inlined
3560 footnotes. Unreferenced definitions are ignored."
3561 (let* (num-alist
3562 collect-fn ; for byte-compiler.
3563 (collect-fn
3564 (function
3565 (lambda (data)
3566 ;; Collect footnote number, label and definition in DATA.
3567 (org-element-map data 'footnote-reference
3568 (lambda (fn)
3569 (when (org-export-footnote-first-reference-p fn info)
3570 (let ((def (org-export-get-footnote-definition fn info)))
3571 (push
3572 (list (org-export-get-footnote-number fn info)
3573 (org-element-property :label fn)
3574 def)
3575 num-alist)
3576 ;; Also search in definition for nested footnotes.
3577 (when (eq (org-element-property :type fn) 'standard)
3578 (funcall collect-fn def)))))
3579 ;; Don't enter footnote definitions since it will happen
3580 ;; when their first reference is found.
3581 info nil 'footnote-definition)))))
3582 (funcall collect-fn (plist-get info :parse-tree))
3583 (reverse num-alist)))
3585 (defun org-export-footnote-first-reference-p (footnote-reference info)
3586 "Non-nil when a footnote reference is the first one for its label.
3588 FOOTNOTE-REFERENCE is the footnote reference being considered.
3589 INFO is the plist used as a communication channel."
3590 (let ((label (org-element-property :label footnote-reference)))
3591 ;; Anonymous footnotes are always a first reference.
3592 (if (not label) t
3593 ;; Otherwise, return the first footnote with the same LABEL and
3594 ;; test if it is equal to FOOTNOTE-REFERENCE.
3595 (let* (search-refs ; for byte-compiler.
3596 (search-refs
3597 (function
3598 (lambda (data)
3599 (org-element-map data 'footnote-reference
3600 (lambda (fn)
3601 (cond
3602 ((string= (org-element-property :label fn) label)
3603 (throw 'exit fn))
3604 ;; If FN isn't inlined, be sure to traverse its
3605 ;; definition before resuming search. See
3606 ;; comments in `org-export-get-footnote-number'
3607 ;; for more information.
3608 ((eq (org-element-property :type fn) 'standard)
3609 (funcall search-refs
3610 (org-export-get-footnote-definition fn info)))))
3611 ;; Don't enter footnote definitions since it will
3612 ;; happen when their first reference is found.
3613 info 'first-match 'footnote-definition)))))
3614 (eq (catch 'exit (funcall search-refs (plist-get info :parse-tree)))
3615 footnote-reference)))))
3617 (defun org-export-get-footnote-definition (footnote-reference info)
3618 "Return definition of FOOTNOTE-REFERENCE as parsed data.
3619 INFO is the plist used as a communication channel. If no such
3620 definition can be found, return the \"DEFINITION NOT FOUND\"
3621 string."
3622 (let ((label (org-element-property :label footnote-reference)))
3623 (or (org-element-property :inline-definition footnote-reference)
3624 (cdr (assoc label (plist-get info :footnote-definition-alist)))
3625 "DEFINITION NOT FOUND.")))
3627 (defun org-export-get-footnote-number (footnote info)
3628 "Return number associated to a footnote.
3630 FOOTNOTE is either a footnote reference or a footnote definition.
3631 INFO is the plist used as a communication channel."
3632 (let* ((label (org-element-property :label footnote))
3633 seen-refs
3634 search-ref ; For byte-compiler.
3635 (search-ref
3636 (function
3637 (lambda (data)
3638 ;; Search footnote references through DATA, filling
3639 ;; SEEN-REFS along the way.
3640 (org-element-map data 'footnote-reference
3641 (lambda (fn)
3642 (let ((fn-lbl (org-element-property :label fn)))
3643 (cond
3644 ;; Anonymous footnote match: return number.
3645 ((and (not fn-lbl) (eq fn footnote))
3646 (throw 'exit (1+ (length seen-refs))))
3647 ;; Labels match: return number.
3648 ((and label (string= label fn-lbl))
3649 (throw 'exit (1+ (length seen-refs))))
3650 ;; Anonymous footnote: it's always a new one.
3651 ;; Also, be sure to return nil from the `cond' so
3652 ;; `first-match' doesn't get us out of the loop.
3653 ((not fn-lbl) (push 'inline seen-refs) nil)
3654 ;; Label not seen so far: add it so SEEN-REFS.
3656 ;; Also search for subsequent references in
3657 ;; footnote definition so numbering follows
3658 ;; reading logic. Note that we don't have to care
3659 ;; about inline definitions, since
3660 ;; `org-element-map' already traverses them at the
3661 ;; right time.
3663 ;; Once again, return nil to stay in the loop.
3664 ((not (member fn-lbl seen-refs))
3665 (push fn-lbl seen-refs)
3666 (funcall search-ref
3667 (org-export-get-footnote-definition fn info))
3668 nil))))
3669 ;; Don't enter footnote definitions since it will
3670 ;; happen when their first reference is found.
3671 info 'first-match 'footnote-definition)))))
3672 (catch 'exit (funcall search-ref (plist-get info :parse-tree)))))
3675 ;;;; For Headlines
3677 ;; `org-export-get-relative-level' is a shortcut to get headline
3678 ;; level, relatively to the lower headline level in the parsed tree.
3680 ;; `org-export-get-headline-number' returns the section number of an
3681 ;; headline, while `org-export-number-to-roman' allows to convert it
3682 ;; to roman numbers.
3684 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
3685 ;; `org-export-last-sibling-p' are three useful predicates when it
3686 ;; comes to fulfill the `:headline-levels' property.
3688 ;; `org-export-get-tags', `org-export-get-category' and
3689 ;; `org-export-get-node-property' extract useful information from an
3690 ;; headline or a parent headline. They all handle inheritance.
3692 ;; `org-export-get-alt-title' tries to retrieve an alternative title,
3693 ;; as a secondary string, suitable for table of contents. It falls
3694 ;; back onto default title.
3696 (defun org-export-get-relative-level (headline info)
3697 "Return HEADLINE relative level within current parsed tree.
3698 INFO is a plist holding contextual information."
3699 (+ (org-element-property :level headline)
3700 (or (plist-get info :headline-offset) 0)))
3702 (defun org-export-low-level-p (headline info)
3703 "Non-nil when HEADLINE is considered as low level.
3705 INFO is a plist used as a communication channel.
3707 A low level headlines has a relative level greater than
3708 `:headline-levels' property value.
3710 Return value is the difference between HEADLINE relative level
3711 and the last level being considered as high enough, or nil."
3712 (let ((limit (plist-get info :headline-levels)))
3713 (when (wholenump limit)
3714 (let ((level (org-export-get-relative-level headline info)))
3715 (and (> level limit) (- level limit))))))
3717 (defun org-export-get-headline-number (headline info)
3718 "Return HEADLINE numbering as a list of numbers.
3719 INFO is a plist holding contextual information."
3720 (cdr (assoc headline (plist-get info :headline-numbering))))
3722 (defun org-export-numbered-headline-p (headline info)
3723 "Return a non-nil value if HEADLINE element should be numbered.
3724 INFO is a plist used as a communication channel."
3725 (let ((sec-num (plist-get info :section-numbers))
3726 (level (org-export-get-relative-level headline info)))
3727 (if (wholenump sec-num) (<= level sec-num) sec-num)))
3729 (defun org-export-number-to-roman (n)
3730 "Convert integer N into a roman numeral."
3731 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
3732 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
3733 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
3734 ( 1 . "I")))
3735 (res ""))
3736 (if (<= n 0)
3737 (number-to-string n)
3738 (while roman
3739 (if (>= n (caar roman))
3740 (setq n (- n (caar roman))
3741 res (concat res (cdar roman)))
3742 (pop roman)))
3743 res)))
3745 (defun org-export-get-tags (element info &optional tags inherited)
3746 "Return list of tags associated to ELEMENT.
3748 ELEMENT has either an `headline' or an `inlinetask' type. INFO
3749 is a plist used as a communication channel.
3751 Select tags (see `org-export-select-tags') and exclude tags (see
3752 `org-export-exclude-tags') are removed from the list.
3754 When non-nil, optional argument TAGS should be a list of strings.
3755 Any tag belonging to this list will also be removed.
3757 When optional argument INHERITED is non-nil, tags can also be
3758 inherited from parent headlines and FILETAGS keywords."
3759 (org-remove-if
3760 (lambda (tag) (or (member tag (plist-get info :select-tags))
3761 (member tag (plist-get info :exclude-tags))
3762 (member tag tags)))
3763 (if (not inherited) (org-element-property :tags element)
3764 ;; Build complete list of inherited tags.
3765 (let ((current-tag-list (org-element-property :tags element)))
3766 (mapc
3767 (lambda (parent)
3768 (mapc
3769 (lambda (tag)
3770 (when (and (memq (org-element-type parent) '(headline inlinetask))
3771 (not (member tag current-tag-list)))
3772 (push tag current-tag-list)))
3773 (org-element-property :tags parent)))
3774 (org-export-get-genealogy element))
3775 ;; Add FILETAGS keywords and return results.
3776 (org-uniquify (append (plist-get info :filetags) current-tag-list))))))
3778 (defun org-export-get-node-property (property blob &optional inherited)
3779 "Return node PROPERTY value for BLOB.
3781 PROPERTY is an upcase symbol (i.e. `:COOKIE_DATA'). BLOB is an
3782 element or object.
3784 If optional argument INHERITED is non-nil, the value can be
3785 inherited from a parent headline.
3787 Return value is a string or nil."
3788 (let ((headline (if (eq (org-element-type blob) 'headline) blob
3789 (org-export-get-parent-headline blob))))
3790 (if (not inherited) (org-element-property property blob)
3791 (let ((parent headline) value)
3792 (catch 'found
3793 (while parent
3794 (when (plist-member (nth 1 parent) property)
3795 (throw 'found (org-element-property property parent)))
3796 (setq parent (org-element-property :parent parent))))))))
3798 (defun org-export-get-category (blob info)
3799 "Return category for element or object BLOB.
3801 INFO is a plist used as a communication channel.
3803 CATEGORY is automatically inherited from a parent headline, from
3804 #+CATEGORY: keyword or created out of original file name. If all
3805 fail, the fall-back value is \"???\"."
3806 (or (let ((headline (if (eq (org-element-type blob) 'headline) blob
3807 (org-export-get-parent-headline blob))))
3808 ;; Almost like `org-export-node-property', but we cannot trust
3809 ;; `plist-member' as every headline has a `:CATEGORY'
3810 ;; property, would it be nil or equal to "???" (which has the
3811 ;; same meaning).
3812 (let ((parent headline) value)
3813 (catch 'found
3814 (while parent
3815 (let ((category (org-element-property :CATEGORY parent)))
3816 (and category (not (equal "???" category))
3817 (throw 'found category)))
3818 (setq parent (org-element-property :parent parent))))))
3819 (org-element-map (plist-get info :parse-tree) 'keyword
3820 (lambda (kwd)
3821 (when (equal (org-element-property :key kwd) "CATEGORY")
3822 (org-element-property :value kwd)))
3823 info 'first-match)
3824 (let ((file (plist-get info :input-file)))
3825 (and file (file-name-sans-extension (file-name-nondirectory file))))
3826 "???"))
3828 (defun org-export-get-alt-title (headline info)
3829 "Return alternative title for HEADLINE, as a secondary string.
3830 INFO is a plist used as a communication channel. If no optional
3831 title is defined, fall-back to the regular title."
3832 (or (org-element-property :alt-title headline)
3833 (org-element-property :title headline)))
3835 (defun org-export-first-sibling-p (headline info)
3836 "Non-nil when HEADLINE is the first sibling in its sub-tree.
3837 INFO is a plist used as a communication channel."
3838 (not (eq (org-element-type (org-export-get-previous-element headline info))
3839 'headline)))
3841 (defun org-export-last-sibling-p (headline info)
3842 "Non-nil when HEADLINE is the last sibling in its sub-tree.
3843 INFO is a plist used as a communication channel."
3844 (not (org-export-get-next-element headline info)))
3847 ;;;; For Keywords
3849 ;; `org-export-get-date' returns a date appropriate for the document
3850 ;; to about to be exported. In particular, it takes care of
3851 ;; `org-export-date-timestamp-format'.
3853 (defun org-export-get-date (info &optional fmt)
3854 "Return date value for the current document.
3856 INFO is a plist used as a communication channel. FMT, when
3857 non-nil, is a time format string that will be applied on the date
3858 if it consists in a single timestamp object. It defaults to
3859 `org-export-date-timestamp-format' when nil.
3861 A proper date can be a secondary string, a string or nil. It is
3862 meant to be translated with `org-export-data' or alike."
3863 (let ((date (plist-get info :date))
3864 (fmt (or fmt org-export-date-timestamp-format)))
3865 (cond ((not date) nil)
3866 ((and fmt
3867 (not (cdr date))
3868 (eq (org-element-type (car date)) 'timestamp))
3869 (org-timestamp-format (car date) fmt))
3870 (t date))))
3873 ;;;; For Links
3875 ;; `org-export-solidify-link-text' turns a string into a safer version
3876 ;; for links, replacing most non-standard characters with hyphens.
3878 ;; `org-export-get-coderef-format' returns an appropriate format
3879 ;; string for coderefs.
3881 ;; `org-export-inline-image-p' returns a non-nil value when the link
3882 ;; provided should be considered as an inline image.
3884 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
3885 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
3886 ;; returns an appropriate unique identifier when found, or nil.
3888 ;; `org-export-resolve-id-link' returns the first headline with
3889 ;; specified id or custom-id in parse tree, the path to the external
3890 ;; file with the id or nil when neither was found.
3892 ;; `org-export-resolve-coderef' associates a reference to a line
3893 ;; number in the element it belongs, or returns the reference itself
3894 ;; when the element isn't numbered.
3896 (defun org-export-solidify-link-text (s)
3897 "Take link text S and make a safe target out of it."
3898 (save-match-data
3899 (mapconcat 'identity (org-split-string s "[^a-zA-Z0-9_.-:]+") "-")))
3901 (defun org-export-get-coderef-format (path desc)
3902 "Return format string for code reference link.
3903 PATH is the link path. DESC is its description."
3904 (save-match-data
3905 (cond ((not desc) "%s")
3906 ((string-match (regexp-quote (concat "(" path ")")) desc)
3907 (replace-match "%s" t t desc))
3908 (t desc))))
3910 (defun org-export-inline-image-p (link &optional rules)
3911 "Non-nil if LINK object points to an inline image.
3913 Optional argument is a set of RULES defining inline images. It
3914 is an alist where associations have the following shape:
3916 \(TYPE . REGEXP)
3918 Applying a rule means apply REGEXP against LINK's path when its
3919 type is TYPE. The function will return a non-nil value if any of
3920 the provided rules is non-nil. The default rule is
3921 `org-export-default-inline-image-rule'.
3923 This only applies to links without a description."
3924 (and (not (org-element-contents link))
3925 (let ((case-fold-search t)
3926 (rules (or rules org-export-default-inline-image-rule)))
3927 (catch 'exit
3928 (mapc
3929 (lambda (rule)
3930 (and (string= (org-element-property :type link) (car rule))
3931 (string-match (cdr rule)
3932 (org-element-property :path link))
3933 (throw 'exit t)))
3934 rules)
3935 ;; Return nil if no rule matched.
3936 nil))))
3938 (defun org-export-resolve-coderef (ref info)
3939 "Resolve a code reference REF.
3941 INFO is a plist used as a communication channel.
3943 Return associated line number in source code, or REF itself,
3944 depending on src-block or example element's switches."
3945 (org-element-map (plist-get info :parse-tree) '(example-block src-block)
3946 (lambda (el)
3947 (with-temp-buffer
3948 (insert (org-trim (org-element-property :value el)))
3949 (let* ((label-fmt (regexp-quote
3950 (or (org-element-property :label-fmt el)
3951 org-coderef-label-format)))
3952 (ref-re
3953 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
3954 (replace-regexp-in-string "%s" ref label-fmt nil t))))
3955 ;; Element containing REF is found. Resolve it to either
3956 ;; a label or a line number, as needed.
3957 (when (re-search-backward ref-re nil t)
3958 (cond
3959 ((org-element-property :use-labels el) ref)
3960 ((eq (org-element-property :number-lines el) 'continued)
3961 (+ (org-export-get-loc el info) (line-number-at-pos)))
3962 (t (line-number-at-pos)))))))
3963 info 'first-match))
3965 (defun org-export-resolve-fuzzy-link (link info)
3966 "Return LINK destination.
3968 INFO is a plist holding contextual information.
3970 Return value can be an object, an element, or nil:
3972 - If LINK path matches a target object (i.e. <<path>>) return it.
3974 - If LINK path exactly matches the name affiliated keyword
3975 \(i.e. #+NAME: path) of an element, return that element.
3977 - If LINK path exactly matches any headline name, return that
3978 element. If more than one headline share that name, priority
3979 will be given to the one with the closest common ancestor, if
3980 any, or the first one in the parse tree otherwise.
3982 - Otherwise, return nil.
3984 Assume LINK type is \"fuzzy\". White spaces are not
3985 significant."
3986 (let* ((raw-path (org-element-property :path link))
3987 (match-title-p (eq (aref raw-path 0) ?*))
3988 ;; Split PATH at white spaces so matches are space
3989 ;; insensitive.
3990 (path (org-split-string
3991 (if match-title-p (substring raw-path 1) raw-path)))
3992 ;; Cache for destinations that are not position dependent.
3993 (link-cache
3994 (or (plist-get info :resolve-fuzzy-link-cache)
3995 (plist-get (setq info (plist-put info :resolve-fuzzy-link-cache
3996 (make-hash-table :test 'equal)))
3997 :resolve-fuzzy-link-cache)))
3998 (cached (gethash path link-cache 'not-found)))
3999 (cond
4000 ;; Destination is not position dependent: use cached value.
4001 ((and (not match-title-p) (not (eq cached 'not-found))) cached)
4002 ;; First try to find a matching "<<path>>" unless user specified
4003 ;; he was looking for a headline (path starts with a "*"
4004 ;; character).
4005 ((and (not match-title-p)
4006 (let ((match (org-element-map (plist-get info :parse-tree) 'target
4007 (lambda (blob)
4008 (and (equal (org-split-string
4009 (org-element-property :value blob))
4010 path)
4011 blob))
4012 info 'first-match)))
4013 (and match (puthash path match link-cache)))))
4014 ;; Then try to find an element with a matching "#+NAME: path"
4015 ;; affiliated keyword.
4016 ((and (not match-title-p)
4017 (let ((match (org-element-map (plist-get info :parse-tree)
4018 org-element-all-elements
4019 (lambda (el)
4020 (let ((name (org-element-property :name el)))
4021 (when (and name
4022 (equal (org-split-string name) path))
4023 el)))
4024 info 'first-match)))
4025 (and match (puthash path match link-cache)))))
4026 ;; Last case: link either points to a headline or to nothingness.
4027 ;; Try to find the source, with priority given to headlines with
4028 ;; the closest common ancestor. If such candidate is found,
4029 ;; return it, otherwise return nil.
4031 (let ((find-headline
4032 (function
4033 ;; Return first headline whose `:raw-value' property is
4034 ;; NAME in parse tree DATA, or nil. Statistics cookies
4035 ;; are ignored.
4036 (lambda (name data)
4037 (org-element-map data 'headline
4038 (lambda (headline)
4039 (when (equal (org-split-string
4040 (replace-regexp-in-string
4041 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
4042 (org-element-property :raw-value headline)))
4043 name)
4044 headline))
4045 info 'first-match)))))
4046 ;; Search among headlines sharing an ancestor with link, from
4047 ;; closest to farthest.
4048 (catch 'exit
4049 (mapc
4050 (lambda (parent)
4051 (let ((foundp (funcall find-headline path parent)))
4052 (when foundp (throw 'exit foundp))))
4053 (let ((parent-hl (org-export-get-parent-headline link)))
4054 (if (not parent-hl) (list (plist-get info :parse-tree))
4055 (cons parent-hl (org-export-get-genealogy parent-hl)))))
4056 ;; No destination found: return nil.
4057 (and (not match-title-p) (puthash path nil link-cache))))))))
4059 (defun org-export-resolve-id-link (link info)
4060 "Return headline referenced as LINK destination.
4062 INFO is a plist used as a communication channel.
4064 Return value can be the headline element matched in current parse
4065 tree, a file name or nil. Assume LINK type is either \"id\" or
4066 \"custom-id\"."
4067 (let ((id (org-element-property :path link)))
4068 ;; First check if id is within the current parse tree.
4069 (or (org-element-map (plist-get info :parse-tree) 'headline
4070 (lambda (headline)
4071 (when (or (string= (org-element-property :ID headline) id)
4072 (string= (org-element-property :CUSTOM_ID headline) id))
4073 headline))
4074 info 'first-match)
4075 ;; Otherwise, look for external files.
4076 (cdr (assoc id (plist-get info :id-alist))))))
4078 (defun org-export-resolve-radio-link (link info)
4079 "Return radio-target object referenced as LINK destination.
4081 INFO is a plist used as a communication channel.
4083 Return value can be a radio-target object or nil. Assume LINK
4084 has type \"radio\"."
4085 (let ((path (replace-regexp-in-string
4086 "[ \r\t\n]+" " " (org-element-property :path link))))
4087 (org-element-map (plist-get info :parse-tree) 'radio-target
4088 (lambda (radio)
4089 (and (eq (compare-strings
4090 (replace-regexp-in-string
4091 "[ \r\t\n]+" " " (org-element-property :value radio))
4092 nil nil path nil nil t)
4094 radio))
4095 info 'first-match)))
4098 ;;;; For References
4100 ;; `org-export-get-ordinal' associates a sequence number to any object
4101 ;; or element.
4103 (defun org-export-get-ordinal (element info &optional types predicate)
4104 "Return ordinal number of an element or object.
4106 ELEMENT is the element or object considered. INFO is the plist
4107 used as a communication channel.
4109 Optional argument TYPES, when non-nil, is a list of element or
4110 object types, as symbols, that should also be counted in.
4111 Otherwise, only provided element's type is considered.
4113 Optional argument PREDICATE is a function returning a non-nil
4114 value if the current element or object should be counted in. It
4115 accepts two arguments: the element or object being considered and
4116 the plist used as a communication channel. This allows to count
4117 only a certain type of objects (i.e. inline images).
4119 Return value is a list of numbers if ELEMENT is a headline or an
4120 item. It is nil for keywords. It represents the footnote number
4121 for footnote definitions and footnote references. If ELEMENT is
4122 a target, return the same value as if ELEMENT was the closest
4123 table, item or headline containing the target. In any other
4124 case, return the sequence number of ELEMENT among elements or
4125 objects of the same type."
4126 ;; Ordinal of a target object refer to the ordinal of the closest
4127 ;; table, item, or headline containing the object.
4128 (when (eq (org-element-type element) 'target)
4129 (setq element
4130 (loop for parent in (org-export-get-genealogy element)
4131 when
4132 (memq
4133 (org-element-type parent)
4134 '(footnote-definition footnote-reference headline item
4135 table))
4136 return parent)))
4137 (case (org-element-type element)
4138 ;; Special case 1: A headline returns its number as a list.
4139 (headline (org-export-get-headline-number element info))
4140 ;; Special case 2: An item returns its number as a list.
4141 (item (let ((struct (org-element-property :structure element)))
4142 (org-list-get-item-number
4143 (org-element-property :begin element)
4144 struct
4145 (org-list-prevs-alist struct)
4146 (org-list-parents-alist struct))))
4147 ((footnote-definition footnote-reference)
4148 (org-export-get-footnote-number element info))
4149 (otherwise
4150 (let ((counter 0))
4151 ;; Increment counter until ELEMENT is found again.
4152 (org-element-map (plist-get info :parse-tree)
4153 (or types (org-element-type element))
4154 (lambda (el)
4155 (cond
4156 ((eq element el) (1+ counter))
4157 ((not predicate) (incf counter) nil)
4158 ((funcall predicate el info) (incf counter) nil)))
4159 info 'first-match)))))
4162 ;;;; For Src-Blocks
4164 ;; `org-export-get-loc' counts number of code lines accumulated in
4165 ;; src-block or example-block elements with a "+n" switch until
4166 ;; a given element, excluded. Note: "-n" switches reset that count.
4168 ;; `org-export-unravel-code' extracts source code (along with a code
4169 ;; references alist) from an `element-block' or `src-block' type
4170 ;; element.
4172 ;; `org-export-format-code' applies a formatting function to each line
4173 ;; of code, providing relative line number and code reference when
4174 ;; appropriate. Since it doesn't access the original element from
4175 ;; which the source code is coming, it expects from the code calling
4176 ;; it to know if lines should be numbered and if code references
4177 ;; should appear.
4179 ;; Eventually, `org-export-format-code-default' is a higher-level
4180 ;; function (it makes use of the two previous functions) which handles
4181 ;; line numbering and code references inclusion, and returns source
4182 ;; code in a format suitable for plain text or verbatim output.
4184 (defun org-export-get-loc (element info)
4185 "Return accumulated lines of code up to ELEMENT.
4187 INFO is the plist used as a communication channel.
4189 ELEMENT is excluded from count."
4190 (let ((loc 0))
4191 (org-element-map (plist-get info :parse-tree)
4192 `(src-block example-block ,(org-element-type element))
4193 (lambda (el)
4194 (cond
4195 ;; ELEMENT is reached: Quit the loop.
4196 ((eq el element))
4197 ;; Only count lines from src-block and example-block elements
4198 ;; with a "+n" or "-n" switch. A "-n" switch resets counter.
4199 ((not (memq (org-element-type el) '(src-block example-block))) nil)
4200 ((let ((linums (org-element-property :number-lines el)))
4201 (when linums
4202 ;; Accumulate locs or reset them.
4203 (let ((lines (org-count-lines
4204 (org-trim (org-element-property :value el)))))
4205 (setq loc (if (eq linums 'new) lines (+ loc lines))))))
4206 ;; Return nil to stay in the loop.
4207 nil)))
4208 info 'first-match)
4209 ;; Return value.
4210 loc))
4212 (defun org-export-unravel-code (element)
4213 "Clean source code and extract references out of it.
4215 ELEMENT has either a `src-block' an `example-block' type.
4217 Return a cons cell whose CAR is the source code, cleaned from any
4218 reference and protective comma and CDR is an alist between
4219 relative line number (integer) and name of code reference on that
4220 line (string)."
4221 (let* ((line 0) refs
4222 ;; Get code and clean it. Remove blank lines at its
4223 ;; beginning and end.
4224 (code (replace-regexp-in-string
4225 "\\`\\([ \t]*\n\\)+" ""
4226 (replace-regexp-in-string
4227 "\\([ \t]*\n\\)*[ \t]*\\'" "\n"
4228 (org-element-property :value element))))
4229 ;; Get format used for references.
4230 (label-fmt (regexp-quote
4231 (or (org-element-property :label-fmt element)
4232 org-coderef-label-format)))
4233 ;; Build a regexp matching a loc with a reference.
4234 (with-ref-re
4235 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)[ \t]*\\)$"
4236 (replace-regexp-in-string
4237 "%s" "\\([-a-zA-Z0-9_ ]+\\)" label-fmt nil t))))
4238 ;; Return value.
4239 (cons
4240 ;; Code with references removed.
4241 (org-element-normalize-string
4242 (mapconcat
4243 (lambda (loc)
4244 (incf line)
4245 (if (not (string-match with-ref-re loc)) loc
4246 ;; Ref line: remove ref, and signal its position in REFS.
4247 (push (cons line (match-string 3 loc)) refs)
4248 (replace-match "" nil nil loc 1)))
4249 (org-split-string code "\n") "\n"))
4250 ;; Reference alist.
4251 refs)))
4253 (defun org-export-format-code (code fun &optional num-lines ref-alist)
4254 "Format CODE by applying FUN line-wise and return it.
4256 CODE is a string representing the code to format. FUN is
4257 a function. It must accept three arguments: a line of
4258 code (string), the current line number (integer) or nil and the
4259 reference associated to the current line (string) or nil.
4261 Optional argument NUM-LINES can be an integer representing the
4262 number of code lines accumulated until the current code. Line
4263 numbers passed to FUN will take it into account. If it is nil,
4264 FUN's second argument will always be nil. This number can be
4265 obtained with `org-export-get-loc' function.
4267 Optional argument REF-ALIST can be an alist between relative line
4268 number (i.e. ignoring NUM-LINES) and the name of the code
4269 reference on it. If it is nil, FUN's third argument will always
4270 be nil. It can be obtained through the use of
4271 `org-export-unravel-code' function."
4272 (let ((--locs (org-split-string code "\n"))
4273 (--line 0))
4274 (org-element-normalize-string
4275 (mapconcat
4276 (lambda (--loc)
4277 (incf --line)
4278 (let ((--ref (cdr (assq --line ref-alist))))
4279 (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
4280 --locs "\n"))))
4282 (defun org-export-format-code-default (element info)
4283 "Return source code from ELEMENT, formatted in a standard way.
4285 ELEMENT is either a `src-block' or `example-block' element. INFO
4286 is a plist used as a communication channel.
4288 This function takes care of line numbering and code references
4289 inclusion. Line numbers, when applicable, appear at the
4290 beginning of the line, separated from the code by two white
4291 spaces. Code references, on the other hand, appear flushed to
4292 the right, separated by six white spaces from the widest line of
4293 code."
4294 ;; Extract code and references.
4295 (let* ((code-info (org-export-unravel-code element))
4296 (code (car code-info))
4297 (code-lines (org-split-string code "\n")))
4298 (if (null code-lines) ""
4299 (let* ((refs (and (org-element-property :retain-labels element)
4300 (cdr code-info)))
4301 ;; Handle line numbering.
4302 (num-start (case (org-element-property :number-lines element)
4303 (continued (org-export-get-loc element info))
4304 (new 0)))
4305 (num-fmt
4306 (and num-start
4307 (format "%%%ds "
4308 (length (number-to-string
4309 (+ (length code-lines) num-start))))))
4310 ;; Prepare references display, if required. Any reference
4311 ;; should start six columns after the widest line of code,
4312 ;; wrapped with parenthesis.
4313 (max-width
4314 (+ (apply 'max (mapcar 'length code-lines))
4315 (if (not num-start) 0 (length (format num-fmt num-start))))))
4316 (org-export-format-code
4317 code
4318 (lambda (loc line-num ref)
4319 (let ((number-str (and num-fmt (format num-fmt line-num))))
4320 (concat
4321 number-str
4323 (and ref
4324 (concat (make-string
4325 (- (+ 6 max-width)
4326 (+ (length loc) (length number-str))) ? )
4327 (format "(%s)" ref))))))
4328 num-start refs)))))
4331 ;;;; For Tables
4333 ;; `org-export-table-has-special-column-p' and and
4334 ;; `org-export-table-row-is-special-p' are predicates used to look for
4335 ;; meta-information about the table structure.
4337 ;; `org-table-has-header-p' tells when the rows before the first rule
4338 ;; should be considered as table's header.
4340 ;; `org-export-table-cell-width', `org-export-table-cell-alignment'
4341 ;; and `org-export-table-cell-borders' extract information from
4342 ;; a table-cell element.
4344 ;; `org-export-table-dimensions' gives the number on rows and columns
4345 ;; in the table, ignoring horizontal rules and special columns.
4346 ;; `org-export-table-cell-address', given a table-cell object, returns
4347 ;; the absolute address of a cell. On the other hand,
4348 ;; `org-export-get-table-cell-at' does the contrary.
4350 ;; `org-export-table-cell-starts-colgroup-p',
4351 ;; `org-export-table-cell-ends-colgroup-p',
4352 ;; `org-export-table-row-starts-rowgroup-p',
4353 ;; `org-export-table-row-ends-rowgroup-p',
4354 ;; `org-export-table-row-starts-header-p' and
4355 ;; `org-export-table-row-ends-header-p' indicate position of current
4356 ;; row or cell within the table.
4358 (defun org-export-table-has-special-column-p (table)
4359 "Non-nil when TABLE has a special column.
4360 All special columns will be ignored during export."
4361 ;; The table has a special column when every first cell of every row
4362 ;; has an empty value or contains a symbol among "/", "#", "!", "$",
4363 ;; "*" "_" and "^". Though, do not consider a first row containing
4364 ;; only empty cells as special.
4365 (let ((special-column-p 'empty))
4366 (catch 'exit
4367 (mapc
4368 (lambda (row)
4369 (when (eq (org-element-property :type row) 'standard)
4370 (let ((value (org-element-contents
4371 (car (org-element-contents row)))))
4372 (cond ((member value '(("/") ("#") ("!") ("$") ("*") ("_") ("^")))
4373 (setq special-column-p 'special))
4374 ((not value))
4375 (t (throw 'exit nil))))))
4376 (org-element-contents table))
4377 (eq special-column-p 'special))))
4379 (defun org-export-table-has-header-p (table info)
4380 "Non-nil when TABLE has a header.
4382 INFO is a plist used as a communication channel.
4384 A table has a header when it contains at least two row groups."
4385 (let ((cache (or (plist-get info :table-header-cache)
4386 (plist-get (setq info
4387 (plist-put info :table-header-cache
4388 (make-hash-table :test 'eq)))
4389 :table-header-cache))))
4390 (or (gethash table cache)
4391 (let ((rowgroup 1) row-flag)
4392 (puthash
4393 table
4394 (org-element-map table 'table-row
4395 (lambda (row)
4396 (cond
4397 ((> rowgroup 1) t)
4398 ((and row-flag (eq (org-element-property :type row) 'rule))
4399 (incf rowgroup) (setq row-flag nil))
4400 ((and (not row-flag) (eq (org-element-property :type row)
4401 'standard))
4402 (setq row-flag t) nil)))
4403 info 'first-match)
4404 cache)))))
4406 (defun org-export-table-row-is-special-p (table-row info)
4407 "Non-nil if TABLE-ROW is considered special.
4409 INFO is a plist used as the communication channel.
4411 All special rows will be ignored during export."
4412 (when (eq (org-element-property :type table-row) 'standard)
4413 (let ((first-cell (org-element-contents
4414 (car (org-element-contents table-row)))))
4415 ;; A row is special either when...
4417 ;; ... it starts with a field only containing "/",
4418 (equal first-cell '("/"))
4419 ;; ... the table contains a special column and the row start
4420 ;; with a marking character among, "^", "_", "$" or "!",
4421 (and (org-export-table-has-special-column-p
4422 (org-export-get-parent table-row))
4423 (member first-cell '(("^") ("_") ("$") ("!"))))
4424 ;; ... it contains only alignment cookies and empty cells.
4425 (let ((special-row-p 'empty))
4426 (catch 'exit
4427 (mapc
4428 (lambda (cell)
4429 (let ((value (org-element-contents cell)))
4430 ;; Since VALUE is a secondary string, the following
4431 ;; checks avoid expanding it with `org-export-data'.
4432 (cond ((not value))
4433 ((and (not (cdr value))
4434 (stringp (car value))
4435 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'"
4436 (car value)))
4437 (setq special-row-p 'cookie))
4438 (t (throw 'exit nil)))))
4439 (org-element-contents table-row))
4440 (eq special-row-p 'cookie)))))))
4442 (defun org-export-table-row-group (table-row info)
4443 "Return TABLE-ROW's group number, as an integer.
4445 INFO is a plist used as the communication channel.
4447 Return value is the group number, as an integer, or nil for
4448 special rows and rows separators. First group is also table's
4449 header."
4450 (let ((cache (or (plist-get info :table-row-group-cache)
4451 (plist-get (setq info
4452 (plist-put info :table-row-group-cache
4453 (make-hash-table :test 'eq)))
4454 :table-row-group-cache))))
4455 (cond ((gethash table-row cache))
4456 ((eq (org-element-property :type table-row) 'rule) nil)
4457 (t (let ((group 0) row-flag)
4458 (org-element-map (org-export-get-parent table-row) 'table-row
4459 (lambda (row)
4460 (if (eq (org-element-property :type row) 'rule)
4461 (setq row-flag nil)
4462 (unless row-flag (incf group) (setq row-flag t)))
4463 (when (eq table-row row) (puthash table-row group cache)))
4464 info 'first-match))))))
4466 (defun org-export-table-cell-width (table-cell info)
4467 "Return TABLE-CELL contents width.
4469 INFO is a plist used as the communication channel.
4471 Return value is the width given by the last width cookie in the
4472 same column as TABLE-CELL, or nil."
4473 (let* ((row (org-export-get-parent table-cell))
4474 (table (org-export-get-parent row))
4475 (column (let ((cells (org-element-contents row)))
4476 (- (length cells) (length (memq table-cell cells)))))
4477 (cache (or (plist-get info :table-cell-width-cache)
4478 (plist-get (setq info
4479 (plist-put info :table-cell-width-cache
4480 (make-hash-table :test 'equal)))
4481 :table-cell-width-cache)))
4482 (key (cons table column))
4483 (value (gethash key cache 'no-result)))
4484 (if (not (eq value 'no-result)) value
4485 (let (cookie-width)
4486 (dolist (row (org-element-contents table)
4487 (puthash key cookie-width cache))
4488 (when (org-export-table-row-is-special-p row info)
4489 ;; In a special row, try to find a width cookie at COLUMN.
4490 (let* ((value (org-element-contents
4491 (elt (org-element-contents row) column)))
4492 (cookie (car value)))
4493 ;; The following checks avoid expanding unnecessarily
4494 ;; the cell with `org-export-data'.
4495 (when (and value
4496 (not (cdr value))
4497 (stringp cookie)
4498 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'" cookie)
4499 (match-string 1 cookie))
4500 (setq cookie-width
4501 (string-to-number (match-string 1 cookie)))))))))))
4503 (defun org-export-table-cell-alignment (table-cell info)
4504 "Return TABLE-CELL contents alignment.
4506 INFO is a plist used as the communication channel.
4508 Return alignment as specified by the last alignment cookie in the
4509 same column as TABLE-CELL. If no such cookie is found, a default
4510 alignment value will be deduced from fraction of numbers in the
4511 column (see `org-table-number-fraction' for more information).
4512 Possible values are `left', `right' and `center'."
4513 (let* ((row (org-export-get-parent table-cell))
4514 (table (org-export-get-parent row))
4515 (column (let ((cells (org-element-contents row)))
4516 (- (length cells) (length (memq table-cell cells)))))
4517 (cache (or (plist-get info :table-cell-alignment-cache)
4518 (plist-get (setq info
4519 (plist-put info :table-cell-alignment-cache
4520 (make-hash-table :test 'equal)))
4521 :table-cell-alignment-cache))))
4522 (or (gethash (cons table column) cache)
4523 (let ((number-cells 0)
4524 (total-cells 0)
4525 cookie-align
4526 previous-cell-number-p)
4527 (dolist (row (org-element-contents (org-export-get-parent row)))
4528 (cond
4529 ;; In a special row, try to find an alignment cookie at
4530 ;; COLUMN.
4531 ((org-export-table-row-is-special-p row info)
4532 (let ((value (org-element-contents
4533 (elt (org-element-contents row) column))))
4534 ;; Since VALUE is a secondary string, the following
4535 ;; checks avoid useless expansion through
4536 ;; `org-export-data'.
4537 (when (and value
4538 (not (cdr value))
4539 (stringp (car value))
4540 (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'"
4541 (car value))
4542 (match-string 1 (car value)))
4543 (setq cookie-align (match-string 1 (car value))))))
4544 ;; Ignore table rules.
4545 ((eq (org-element-property :type row) 'rule))
4546 ;; In a standard row, check if cell's contents are
4547 ;; expressing some kind of number. Increase NUMBER-CELLS
4548 ;; accordingly. Though, don't bother if an alignment
4549 ;; cookie has already defined cell's alignment.
4550 ((not cookie-align)
4551 (let ((value (org-export-data
4552 (org-element-contents
4553 (elt (org-element-contents row) column))
4554 info)))
4555 (incf total-cells)
4556 ;; Treat an empty cell as a number if it follows
4557 ;; a number.
4558 (if (not (or (string-match org-table-number-regexp value)
4559 (and (string= value "") previous-cell-number-p)))
4560 (setq previous-cell-number-p nil)
4561 (setq previous-cell-number-p t)
4562 (incf number-cells))))))
4563 ;; Return value. Alignment specified by cookies has
4564 ;; precedence over alignment deduced from cell's contents.
4565 (puthash (cons table column)
4566 (cond ((equal cookie-align "l") 'left)
4567 ((equal cookie-align "r") 'right)
4568 ((equal cookie-align "c") 'center)
4569 ((>= (/ (float number-cells) total-cells)
4570 org-table-number-fraction)
4571 'right)
4572 (t 'left))
4573 cache)))))
4575 (defun org-export-table-cell-borders (table-cell info)
4576 "Return TABLE-CELL borders.
4578 INFO is a plist used as a communication channel.
4580 Return value is a list of symbols, or nil. Possible values are:
4581 `top', `bottom', `above', `below', `left' and `right'. Note:
4582 `top' (resp. `bottom') only happen for a cell in the first
4583 row (resp. last row) of the table, ignoring table rules, if any.
4585 Returned borders ignore special rows."
4586 (let* ((row (org-export-get-parent table-cell))
4587 (table (org-export-get-parent-table table-cell))
4588 borders)
4589 ;; Top/above border? TABLE-CELL has a border above when a rule
4590 ;; used to demarcate row groups can be found above. Hence,
4591 ;; finding a rule isn't sufficient to push `above' in BORDERS:
4592 ;; another regular row has to be found above that rule.
4593 (let (rule-flag)
4594 (catch 'exit
4595 (mapc (lambda (row)
4596 (cond ((eq (org-element-property :type row) 'rule)
4597 (setq rule-flag t))
4598 ((not (org-export-table-row-is-special-p row info))
4599 (if rule-flag (throw 'exit (push 'above borders))
4600 (throw 'exit nil)))))
4601 ;; Look at every row before the current one.
4602 (cdr (memq row (reverse (org-element-contents table)))))
4603 ;; No rule above, or rule found starts the table (ignoring any
4604 ;; special row): TABLE-CELL is at the top of the table.
4605 (when rule-flag (push 'above borders))
4606 (push 'top borders)))
4607 ;; Bottom/below border? TABLE-CELL has a border below when next
4608 ;; non-regular row below is a rule.
4609 (let (rule-flag)
4610 (catch 'exit
4611 (mapc (lambda (row)
4612 (cond ((eq (org-element-property :type row) 'rule)
4613 (setq rule-flag t))
4614 ((not (org-export-table-row-is-special-p row info))
4615 (if rule-flag (throw 'exit (push 'below borders))
4616 (throw 'exit nil)))))
4617 ;; Look at every row after the current one.
4618 (cdr (memq row (org-element-contents table))))
4619 ;; No rule below, or rule found ends the table (modulo some
4620 ;; special row): TABLE-CELL is at the bottom of the table.
4621 (when rule-flag (push 'below borders))
4622 (push 'bottom borders)))
4623 ;; Right/left borders? They can only be specified by column
4624 ;; groups. Column groups are defined in a row starting with "/".
4625 ;; Also a column groups row only contains "<", "<>", ">" or blank
4626 ;; cells.
4627 (catch 'exit
4628 (let ((column (let ((cells (org-element-contents row)))
4629 (- (length cells) (length (memq table-cell cells))))))
4630 (mapc
4631 (lambda (row)
4632 (unless (eq (org-element-property :type row) 'rule)
4633 (when (equal (org-element-contents
4634 (car (org-element-contents row)))
4635 '("/"))
4636 (let ((column-groups
4637 (mapcar
4638 (lambda (cell)
4639 (let ((value (org-element-contents cell)))
4640 (when (member value '(("<") ("<>") (">") nil))
4641 (car value))))
4642 (org-element-contents row))))
4643 ;; There's a left border when previous cell, if
4644 ;; any, ends a group, or current one starts one.
4645 (when (or (and (not (zerop column))
4646 (member (elt column-groups (1- column))
4647 '(">" "<>")))
4648 (member (elt column-groups column) '("<" "<>")))
4649 (push 'left borders))
4650 ;; There's a right border when next cell, if any,
4651 ;; starts a group, or current one ends one.
4652 (when (or (and (/= (1+ column) (length column-groups))
4653 (member (elt column-groups (1+ column))
4654 '("<" "<>")))
4655 (member (elt column-groups column) '(">" "<>")))
4656 (push 'right borders))
4657 (throw 'exit nil)))))
4658 ;; Table rows are read in reverse order so last column groups
4659 ;; row has precedence over any previous one.
4660 (reverse (org-element-contents table)))))
4661 ;; Return value.
4662 borders))
4664 (defun org-export-table-cell-starts-colgroup-p (table-cell info)
4665 "Non-nil when TABLE-CELL is at the beginning of a row group.
4666 INFO is a plist used as a communication channel."
4667 ;; A cell starts a column group either when it is at the beginning
4668 ;; of a row (or after the special column, if any) or when it has
4669 ;; a left border.
4670 (or (eq (org-element-map (org-export-get-parent table-cell) 'table-cell
4671 'identity info 'first-match)
4672 table-cell)
4673 (memq 'left (org-export-table-cell-borders table-cell info))))
4675 (defun org-export-table-cell-ends-colgroup-p (table-cell info)
4676 "Non-nil when TABLE-CELL is at the end of a row group.
4677 INFO is a plist used as a communication channel."
4678 ;; A cell ends a column group either when it is at the end of a row
4679 ;; or when it has a right border.
4680 (or (eq (car (last (org-element-contents
4681 (org-export-get-parent table-cell))))
4682 table-cell)
4683 (memq 'right (org-export-table-cell-borders table-cell info))))
4685 (defun org-export-table-row-starts-rowgroup-p (table-row info)
4686 "Non-nil when TABLE-ROW is at the beginning of a column group.
4687 INFO is a plist used as a communication channel."
4688 (unless (or (eq (org-element-property :type table-row) 'rule)
4689 (org-export-table-row-is-special-p table-row info))
4690 (let ((borders (org-export-table-cell-borders
4691 (car (org-element-contents table-row)) info)))
4692 (or (memq 'top borders) (memq 'above borders)))))
4694 (defun org-export-table-row-ends-rowgroup-p (table-row info)
4695 "Non-nil when TABLE-ROW is at the end of a column group.
4696 INFO is a plist used as a communication channel."
4697 (unless (or (eq (org-element-property :type table-row) 'rule)
4698 (org-export-table-row-is-special-p table-row info))
4699 (let ((borders (org-export-table-cell-borders
4700 (car (org-element-contents table-row)) info)))
4701 (or (memq 'bottom borders) (memq 'below borders)))))
4703 (defun org-export-table-row-starts-header-p (table-row info)
4704 "Non-nil when TABLE-ROW is the first table header's row.
4705 INFO is a plist used as a communication channel."
4706 (and (org-export-table-has-header-p
4707 (org-export-get-parent-table table-row) info)
4708 (org-export-table-row-starts-rowgroup-p table-row info)
4709 (= (org-export-table-row-group table-row info) 1)))
4711 (defun org-export-table-row-ends-header-p (table-row info)
4712 "Non-nil when TABLE-ROW is the last 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-ends-rowgroup-p table-row info)
4717 (= (org-export-table-row-group table-row info) 1)))
4719 (defun org-export-table-row-number (table-row info)
4720 "Return TABLE-ROW number.
4721 INFO is a plist used as a communication channel. Return value is
4722 zero-based and ignores separators. The function returns nil for
4723 special colums and separators."
4724 (when (and (eq (org-element-property :type table-row) 'standard)
4725 (not (org-export-table-row-is-special-p table-row info)))
4726 (let ((number 0))
4727 (org-element-map (org-export-get-parent-table table-row) 'table-row
4728 (lambda (row)
4729 (cond ((eq row table-row) number)
4730 ((eq (org-element-property :type row) 'standard)
4731 (incf number) nil)))
4732 info 'first-match))))
4734 (defun org-export-table-dimensions (table info)
4735 "Return TABLE dimensions.
4737 INFO is a plist used as a communication channel.
4739 Return value is a CONS like (ROWS . COLUMNS) where
4740 ROWS (resp. COLUMNS) is the number of exportable
4741 rows (resp. columns)."
4742 (let (first-row (columns 0) (rows 0))
4743 ;; Set number of rows, and extract first one.
4744 (org-element-map table 'table-row
4745 (lambda (row)
4746 (when (eq (org-element-property :type row) 'standard)
4747 (incf rows)
4748 (unless first-row (setq first-row row)))) info)
4749 ;; Set number of columns.
4750 (org-element-map first-row 'table-cell (lambda (cell) (incf columns)) info)
4751 ;; Return value.
4752 (cons rows columns)))
4754 (defun org-export-table-cell-address (table-cell info)
4755 "Return address of a regular TABLE-CELL object.
4757 TABLE-CELL is the cell considered. INFO is a plist used as
4758 a communication channel.
4760 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4761 zero-based index. Only exportable cells are considered. The
4762 function returns nil for other cells."
4763 (let* ((table-row (org-export-get-parent table-cell))
4764 (row-number (org-export-table-row-number table-row info)))
4765 (when row-number
4766 (cons row-number
4767 (let ((col-count 0))
4768 (org-element-map table-row 'table-cell
4769 (lambda (cell)
4770 (if (eq cell table-cell) col-count (incf col-count) nil))
4771 info 'first-match))))))
4773 (defun org-export-get-table-cell-at (address table info)
4774 "Return regular table-cell object at ADDRESS in TABLE.
4776 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4777 zero-based index. TABLE is a table type element. INFO is
4778 a plist used as a communication channel.
4780 If no table-cell, among exportable cells, is found at ADDRESS,
4781 return nil."
4782 (let ((column-pos (cdr address)) (column-count 0))
4783 (org-element-map
4784 ;; Row at (car address) or nil.
4785 (let ((row-pos (car address)) (row-count 0))
4786 (org-element-map table 'table-row
4787 (lambda (row)
4788 (cond ((eq (org-element-property :type row) 'rule) nil)
4789 ((= row-count row-pos) row)
4790 (t (incf row-count) nil)))
4791 info 'first-match))
4792 'table-cell
4793 (lambda (cell)
4794 (if (= column-count column-pos) cell
4795 (incf column-count) nil))
4796 info 'first-match)))
4799 ;;;; For Tables Of Contents
4801 ;; `org-export-collect-headlines' builds a list of all exportable
4802 ;; headline elements, maybe limited to a certain depth. One can then
4803 ;; easily parse it and transcode it.
4805 ;; Building lists of tables, figures or listings is quite similar.
4806 ;; Once the generic function `org-export-collect-elements' is defined,
4807 ;; `org-export-collect-tables', `org-export-collect-figures' and
4808 ;; `org-export-collect-listings' can be derived from it.
4810 (defun org-export-collect-headlines (info &optional n)
4811 "Collect headlines in order to build a table of contents.
4813 INFO is a plist used as a communication channel.
4815 When optional argument N is an integer, it specifies the depth of
4816 the table of contents. Otherwise, it is set to the value of the
4817 last headline level. See `org-export-headline-levels' for more
4818 information.
4820 Return a list of all exportable headlines as parsed elements.
4821 Footnote sections, if any, will be ignored."
4822 (unless (wholenump n) (setq n (plist-get info :headline-levels)))
4823 (org-element-map (plist-get info :parse-tree) 'headline
4824 (lambda (headline)
4825 (unless (org-element-property :footnote-section-p headline)
4826 ;; Strip contents from HEADLINE.
4827 (let ((relative-level (org-export-get-relative-level headline info)))
4828 (unless (> relative-level n) headline))))
4829 info))
4831 (defun org-export-collect-elements (type info &optional predicate)
4832 "Collect referenceable elements of a determined type.
4834 TYPE can be a symbol or a list of symbols specifying element
4835 types to search. Only elements with a caption are collected.
4837 INFO is a plist used as a communication channel.
4839 When non-nil, optional argument PREDICATE is a function accepting
4840 one argument, an element of type TYPE. It returns a non-nil
4841 value when that element should be collected.
4843 Return a list of all elements found, in order of appearance."
4844 (org-element-map (plist-get info :parse-tree) type
4845 (lambda (element)
4846 (and (org-element-property :caption element)
4847 (or (not predicate) (funcall predicate element))
4848 element))
4849 info))
4851 (defun org-export-collect-tables (info)
4852 "Build a list of tables.
4853 INFO is a plist used as a communication channel.
4855 Return a list of table elements with a caption."
4856 (org-export-collect-elements 'table info))
4858 (defun org-export-collect-figures (info predicate)
4859 "Build a list of figures.
4861 INFO is a plist used as a communication channel. PREDICATE is
4862 a function which accepts one argument: a paragraph element and
4863 whose return value is non-nil when that element should be
4864 collected.
4866 A figure is a paragraph type element, with a caption, verifying
4867 PREDICATE. The latter has to be provided since a \"figure\" is
4868 a vague concept that may depend on back-end.
4870 Return a list of elements recognized as figures."
4871 (org-export-collect-elements 'paragraph info predicate))
4873 (defun org-export-collect-listings (info)
4874 "Build a list of src blocks.
4876 INFO is a plist used as a communication channel.
4878 Return a list of src-block elements with a caption."
4879 (org-export-collect-elements 'src-block info))
4882 ;;;; Smart Quotes
4884 ;; The main function for the smart quotes sub-system is
4885 ;; `org-export-activate-smart-quotes', which replaces every quote in
4886 ;; a given string from the parse tree with its "smart" counterpart.
4888 ;; Dictionary for smart quotes is stored in
4889 ;; `org-export-smart-quotes-alist'.
4891 ;; Internally, regexps matching potential smart quotes (checks at
4892 ;; string boundaries are also necessary) are defined in
4893 ;; `org-export-smart-quotes-regexps'.
4895 (defconst org-export-smart-quotes-alist
4896 '(("de"
4897 (opening-double-quote :utf-8 "„" :html "&bdquo;" :latex "\"`"
4898 :texinfo "@quotedblbase{}")
4899 (closing-double-quote :utf-8 "“" :html "&ldquo;" :latex "\"'"
4900 :texinfo "@quotedblleft{}")
4901 (opening-single-quote :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}"
4902 :texinfo "@quotesinglbase{}")
4903 (closing-single-quote :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}"
4904 :texinfo "@quoteleft{}")
4905 (apostrophe :utf-8 "’" :html "&rsquo;"))
4906 ("en"
4907 (opening-double-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
4908 (closing-double-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
4909 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
4910 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
4911 (apostrophe :utf-8 "’" :html "&rsquo;"))
4912 ("es"
4913 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
4914 :texinfo "@guillemetleft{}")
4915 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
4916 :texinfo "@guillemetright{}")
4917 (opening-single-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
4918 (closing-single-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
4919 (apostrophe :utf-8 "’" :html "&rsquo;"))
4920 ("fr"
4921 (opening-double-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
4922 :texinfo "@guillemetleft{}@tie{}")
4923 (closing-double-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
4924 :texinfo "@tie{}@guillemetright{}")
4925 (opening-single-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
4926 :texinfo "@guillemetleft{}@tie{}")
4927 (closing-single-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
4928 :texinfo "@tie{}@guillemetright{}")
4929 (apostrophe :utf-8 "’" :html "&rsquo;")))
4930 "Smart quotes translations.
4932 Alist whose CAR is a language string and CDR is an alist with
4933 quote type as key and a plist associating various encodings to
4934 their translation as value.
4936 A quote type can be any symbol among `opening-double-quote',
4937 `closing-double-quote', `opening-single-quote',
4938 `closing-single-quote' and `apostrophe'.
4940 Valid encodings include `:utf-8', `:html', `:latex' and
4941 `:texinfo'.
4943 If no translation is found, the quote character is left as-is.")
4945 (defconst org-export-smart-quotes-regexps
4946 (list
4947 ;; Possible opening quote at beginning of string.
4948 "\\`\\([\"']\\)\\(\\w\\|\\s.\\|\\s_\\)"
4949 ;; Possible closing quote at beginning of string.
4950 "\\`\\([\"']\\)\\(\\s-\\|\\s)\\|\\s.\\)"
4951 ;; Possible apostrophe at beginning of string.
4952 "\\`\\('\\)\\S-"
4953 ;; Opening single and double quotes.
4954 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\(?:\\w\\|\\s.\\|\\s_\\)"
4955 ;; Closing single and double quotes.
4956 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\(?:\\s-\\|\\s)\\|\\s.\\)"
4957 ;; Apostrophe.
4958 "\\S-\\('\\)\\S-"
4959 ;; Possible opening quote at end of string.
4960 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\'"
4961 ;; Possible closing quote at end of string.
4962 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\'"
4963 ;; Possible apostrophe at end of string.
4964 "\\S-\\('\\)\\'")
4965 "List of regexps matching a quote or an apostrophe.
4966 In every regexp, quote or apostrophe matched is put in group 1.")
4968 (defun org-export-activate-smart-quotes (s encoding info &optional original)
4969 "Replace regular quotes with \"smart\" quotes in string S.
4971 ENCODING is a symbol among `:html', `:latex', `:texinfo' and
4972 `:utf-8'. INFO is a plist used as a communication channel.
4974 The function has to retrieve information about string
4975 surroundings in parse tree. It can only happen with an
4976 unmodified string. Thus, if S has already been through another
4977 process, a non-nil ORIGINAL optional argument will provide that
4978 original string.
4980 Return the new string."
4981 (if (equal s "") ""
4982 (let* ((prev (org-export-get-previous-element (or original s) info))
4983 ;; Try to be flexible when computing number of blanks
4984 ;; before object. The previous object may be a string
4985 ;; introduced by the back-end and not completely parsed.
4986 (pre-blank (and prev
4987 (or (org-element-property :post-blank prev)
4988 ;; A string with missing `:post-blank'
4989 ;; property.
4990 (and (stringp prev)
4991 (string-match " *\\'" prev)
4992 (length (match-string 0 prev)))
4993 ;; Fallback value.
4994 0)))
4995 (next (org-export-get-next-element (or original s) info))
4996 (get-smart-quote
4997 (lambda (q type)
4998 ;; Return smart quote associated to a give quote Q, as
4999 ;; a string. TYPE is a symbol among `open', `close' and
5000 ;; `apostrophe'.
5001 (let ((key (case type
5002 (apostrophe 'apostrophe)
5003 (open (if (equal "'" q) 'opening-single-quote
5004 'opening-double-quote))
5005 (otherwise (if (equal "'" q) 'closing-single-quote
5006 'closing-double-quote)))))
5007 (or (plist-get
5008 (cdr (assq key
5009 (cdr (assoc (plist-get info :language)
5010 org-export-smart-quotes-alist))))
5011 encoding)
5012 q)))))
5013 (if (or (equal "\"" s) (equal "'" s))
5014 ;; Only a quote: no regexp can match. We have to check both
5015 ;; sides and decide what to do.
5016 (cond ((and (not prev) (not next)) s)
5017 ((not prev) (funcall get-smart-quote s 'open))
5018 ((and (not next) (zerop pre-blank))
5019 (funcall get-smart-quote s 'close))
5020 ((not next) s)
5021 ((zerop pre-blank) (funcall get-smart-quote s 'apostrophe))
5022 (t (funcall get-smart-quote 'open)))
5023 ;; 1. Replace quote character at the beginning of S.
5024 (cond
5025 ;; Apostrophe?
5026 ((and prev (zerop pre-blank)
5027 (string-match (nth 2 org-export-smart-quotes-regexps) s))
5028 (setq s (replace-match
5029 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
5030 nil t s 1)))
5031 ;; Closing quote?
5032 ((and prev (zerop pre-blank)
5033 (string-match (nth 1 org-export-smart-quotes-regexps) s))
5034 (setq s (replace-match
5035 (funcall get-smart-quote (match-string 1 s) 'close)
5036 nil t s 1)))
5037 ;; Opening quote?
5038 ((and (or (not prev) (> pre-blank 0))
5039 (string-match (nth 0 org-export-smart-quotes-regexps) s))
5040 (setq s (replace-match
5041 (funcall get-smart-quote (match-string 1 s) 'open)
5042 nil t s 1))))
5043 ;; 2. Replace quotes in the middle of the string.
5044 (setq s (replace-regexp-in-string
5045 ;; Opening quotes.
5046 (nth 3 org-export-smart-quotes-regexps)
5047 (lambda (text)
5048 (funcall get-smart-quote (match-string 1 text) 'open))
5049 s nil t 1))
5050 (setq s (replace-regexp-in-string
5051 ;; Closing quotes.
5052 (nth 4 org-export-smart-quotes-regexps)
5053 (lambda (text)
5054 (funcall get-smart-quote (match-string 1 text) 'close))
5055 s nil t 1))
5056 (setq s (replace-regexp-in-string
5057 ;; Apostrophes.
5058 (nth 5 org-export-smart-quotes-regexps)
5059 (lambda (text)
5060 (funcall get-smart-quote (match-string 1 text) 'apostrophe))
5061 s nil t 1))
5062 ;; 3. Replace quote character at the end of S.
5063 (cond
5064 ;; Apostrophe?
5065 ((and next (string-match (nth 8 org-export-smart-quotes-regexps) s))
5066 (setq s (replace-match
5067 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
5068 nil t s 1)))
5069 ;; Closing quote?
5070 ((and (not next)
5071 (string-match (nth 7 org-export-smart-quotes-regexps) s))
5072 (setq s (replace-match
5073 (funcall get-smart-quote (match-string 1 s) 'close)
5074 nil t s 1)))
5075 ;; Opening quote?
5076 ((and next (string-match (nth 6 org-export-smart-quotes-regexps) s))
5077 (setq s (replace-match
5078 (funcall get-smart-quote (match-string 1 s) 'open)
5079 nil t s 1))))
5080 ;; Return string with smart quotes.
5081 s))))
5083 ;;;; Topology
5085 ;; Here are various functions to retrieve information about the
5086 ;; neighbourhood of a given element or object. Neighbours of interest
5087 ;; are direct parent (`org-export-get-parent'), parent headline
5088 ;; (`org-export-get-parent-headline'), first element containing an
5089 ;; object, (`org-export-get-parent-element'), parent table
5090 ;; (`org-export-get-parent-table'), previous element or object
5091 ;; (`org-export-get-previous-element') and next element or object
5092 ;; (`org-export-get-next-element').
5094 ;; `org-export-get-genealogy' returns the full genealogy of a given
5095 ;; element or object, from closest parent to full parse tree.
5097 (defsubst org-export-get-parent (blob)
5098 "Return BLOB parent or nil.
5099 BLOB is the element or object considered."
5100 (org-element-property :parent blob))
5102 (defun org-export-get-genealogy (blob)
5103 "Return full genealogy relative to a given element or object.
5105 BLOB is the element or object being considered.
5107 Ancestors are returned from closest to farthest, the last one
5108 being the full parse tree."
5109 (let (genealogy (parent blob))
5110 (while (setq parent (org-element-property :parent parent))
5111 (push parent genealogy))
5112 (nreverse genealogy)))
5114 (defun org-export-get-parent-headline (blob)
5115 "Return BLOB parent headline or nil.
5116 BLOB is the element or object being considered."
5117 (let ((parent blob))
5118 (while (and (setq parent (org-element-property :parent parent))
5119 (not (eq (org-element-type parent) 'headline))))
5120 parent))
5122 (defun org-export-get-parent-element (object)
5123 "Return first element containing OBJECT or nil.
5124 OBJECT is the object to consider."
5125 (let ((parent object))
5126 (while (and (setq parent (org-element-property :parent parent))
5127 (memq (org-element-type parent) org-element-all-objects)))
5128 parent))
5130 (defun org-export-get-parent-table (object)
5131 "Return OBJECT parent table or nil.
5132 OBJECT is either a `table-cell' or `table-element' type object."
5133 (let ((parent object))
5134 (while (and (setq parent (org-element-property :parent parent))
5135 (not (eq (org-element-type parent) 'table))))
5136 parent))
5138 (defun org-export-get-previous-element (blob info &optional n)
5139 "Return previous element or object.
5141 BLOB is an element or object. INFO is a plist used as
5142 a communication channel. Return previous exportable element or
5143 object, a string, or nil.
5145 When optional argument N is a positive integer, return a list
5146 containing up to N siblings before BLOB, from farthest to
5147 closest. With any other non-nil value, return a list containing
5148 all of them."
5149 (let ((siblings
5150 ;; An object can belong to the contents of its parent or
5151 ;; to a secondary string. We check the latter option
5152 ;; first.
5153 (let ((parent (org-export-get-parent blob)))
5154 (or (and (not (memq (org-element-type blob)
5155 org-element-all-elements))
5156 (let ((sec-value
5157 (org-element-property
5158 (cdr (assq (org-element-type parent)
5159 org-element-secondary-value-alist))
5160 parent)))
5161 (and (memq blob sec-value) sec-value)))
5162 (org-element-contents parent))))
5163 prev)
5164 (catch 'exit
5165 (mapc (lambda (obj)
5166 (cond ((memq obj (plist-get info :ignore-list)))
5167 ((null n) (throw 'exit obj))
5168 ((not (wholenump n)) (push obj prev))
5169 ((zerop n) (throw 'exit prev))
5170 (t (decf n) (push obj prev))))
5171 (cdr (memq blob (reverse siblings))))
5172 prev)))
5174 (defun org-export-get-next-element (blob info &optional n)
5175 "Return next element or object.
5177 BLOB is an element or object. INFO is a plist used as
5178 a communication channel. Return next exportable element or
5179 object, a string, or nil.
5181 When optional argument N is a positive integer, return a list
5182 containing up to N siblings after BLOB, from closest to farthest.
5183 With any other non-nil value, return a list containing all of
5184 them."
5185 (let ((siblings
5186 ;; An object can belong to the contents of its parent or to
5187 ;; a secondary string. We check the latter option first.
5188 (let ((parent (org-export-get-parent blob)))
5189 (or (and (not (memq (org-element-type blob)
5190 org-element-all-objects))
5191 (let ((sec-value
5192 (org-element-property
5193 (cdr (assq (org-element-type parent)
5194 org-element-secondary-value-alist))
5195 parent)))
5196 (cdr (memq blob sec-value))))
5197 (cdr (memq blob (org-element-contents parent))))))
5198 next)
5199 (catch 'exit
5200 (mapc (lambda (obj)
5201 (cond ((memq obj (plist-get info :ignore-list)))
5202 ((null n) (throw 'exit obj))
5203 ((not (wholenump n)) (push obj next))
5204 ((zerop n) (throw 'exit (nreverse next)))
5205 (t (decf n) (push obj next))))
5206 siblings)
5207 (nreverse next))))
5210 ;;;; Translation
5212 ;; `org-export-translate' translates a string according to language
5213 ;; specified by LANGUAGE keyword or `org-export-language-setup'
5214 ;; variable and a specified charset. `org-export-dictionary' contains
5215 ;; the dictionary used for the translation.
5217 (defconst org-export-dictionary
5218 '(("%e %n: %c"
5219 ("fr" :default "%e %n : %c" :html "%e&nbsp;%n&nbsp;: %c"))
5220 ("Author"
5221 ("ca" :default "Autor")
5222 ("cs" :default "Autor")
5223 ("da" :default "Ophavsmand")
5224 ("de" :default "Autor")
5225 ("eo" :html "A&#365;toro")
5226 ("es" :default "Autor")
5227 ("fi" :html "Tekij&auml;")
5228 ("fr" :default "Auteur")
5229 ("hu" :default "Szerz&otilde;")
5230 ("is" :html "H&ouml;fundur")
5231 ("it" :default "Autore")
5232 ("ja" :html "&#33879;&#32773;" :utf-8 "著者")
5233 ("nl" :default "Auteur")
5234 ("no" :default "Forfatter")
5235 ("nb" :default "Forfatter")
5236 ("nn" :default "Forfattar")
5237 ("pl" :default "Autor")
5238 ("ru" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5239 ("sv" :html "F&ouml;rfattare")
5240 ("uk" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5241 ("zh-CN" :html "&#20316;&#32773;" :utf-8 "作者")
5242 ("zh-TW" :html "&#20316;&#32773;" :utf-8 "作者"))
5243 ("Date"
5244 ("ca" :default "Data")
5245 ("cs" :default "Datum")
5246 ("da" :default "Dato")
5247 ("de" :default "Datum")
5248 ("eo" :default "Dato")
5249 ("es" :default "Fecha")
5250 ("fi" :html "P&auml;iv&auml;m&auml;&auml;r&auml;")
5251 ("hu" :html "D&aacute;tum")
5252 ("is" :default "Dagsetning")
5253 ("it" :default "Data")
5254 ("ja" :html "&#26085;&#20184;" :utf-8 "日付")
5255 ("nl" :default "Datum")
5256 ("no" :default "Dato")
5257 ("nb" :default "Dato")
5258 ("nn" :default "Dato")
5259 ("pl" :default "Data")
5260 ("ru" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5261 ("sv" :default "Datum")
5262 ("uk" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5263 ("zh-CN" :html "&#26085;&#26399;" :utf-8 "日期")
5264 ("zh-TW" :html "&#26085;&#26399;" :utf-8 "日期"))
5265 ("Equation"
5266 ("de" :default "Gleichung")
5267 ("es" :html "Ecuaci&oacute;n" :default "Ecuación")
5268 ("fr" :ascii "Equation" :default "Équation")
5269 ("zh-CN" :html "&#26041;&#31243;" :utf-8 "方程"))
5270 ("Figure"
5271 ("de" :default "Abbildung")
5272 ("es" :default "Figura")
5273 ("ja" :html "&#22259;" :utf-8 "図")
5274 ("zh-CN" :html "&#22270;" :utf-8 "图"))
5275 ("Figure %d:"
5276 ("de" :default "Abbildung %d:")
5277 ("es" :default "Figura %d:")
5278 ("fr" :default "Figure %d :" :html "Figure&nbsp;%d&nbsp;:")
5279 ("ja" :html "&#22259;%d: " :utf-8 "図%d: ")
5280 ("zh-CN" :html "&#22270;%d&nbsp;" :utf-8 "图%d "))
5281 ("Footnotes"
5282 ("ca" :html "Peus de p&agrave;gina")
5283 ("cs" :default "Pozn\xe1mky pod carou")
5284 ("da" :default "Fodnoter")
5285 ("de" :html "Fu&szlig;noten" :default "Fußnoten")
5286 ("eo" :default "Piednotoj")
5287 ("es" :html "Nota al pie de p&aacute;gina" :default "Nota al pie de página")
5288 ("fi" :default "Alaviitteet")
5289 ("fr" :default "Notes de bas de page")
5290 ("hu" :html "L&aacute;bjegyzet")
5291 ("is" :html "Aftanm&aacute;lsgreinar")
5292 ("it" :html "Note a pi&egrave; di pagina")
5293 ("ja" :html "&#33050;&#27880;" :utf-8 "脚注")
5294 ("nl" :default "Voetnoten")
5295 ("no" :default "Fotnoter")
5296 ("nb" :default "Fotnoter")
5297 ("nn" :default "Fotnotar")
5298 ("pl" :default "Przypis")
5299 ("ru" :html "&#1057;&#1085;&#1086;&#1089;&#1082;&#1080;" :utf-8 "Сноски")
5300 ("sv" :default "Fotnoter")
5301 ("uk" :html "&#1055;&#1088;&#1080;&#1084;&#1110;&#1090;&#1082;&#1080;"
5302 :utf-8 "Примітки")
5303 ("zh-CN" :html "&#33050;&#27880;" :utf-8 "脚注")
5304 ("zh-TW" :html "&#33139;&#35387;" :utf-8 "腳註"))
5305 ("List of Listings"
5306 ("de" :default "Programmauflistungsverzeichnis")
5307 ("es" :default "Indice de Listados de programas")
5308 ("fr" :default "Liste des programmes")
5309 ("zh-CN" :html "&#20195;&#30721;&#30446;&#24405;" :utf-8 "代码目录"))
5310 ("List of Tables"
5311 ("de" :default "Tabellenverzeichnis")
5312 ("es" :default "Indice de tablas")
5313 ("fr" :default "Liste des tableaux")
5314 ("zh-CN" :html "&#34920;&#26684;&#30446;&#24405;" :utf-8 "表格目录"))
5315 ("Listing %d:"
5316 ("de" :default "Programmlisting %d")
5317 ("es" :default "Listado de programa %d")
5318 ("fr" :default "Programme %d :" :html "Programme&nbsp;%d&nbsp;:")
5319 ("zh-CN" :html "&#20195;&#30721;%d&nbsp;" :utf-8 "代码%d "))
5320 ("See section %s"
5321 ("de" :default "siehe Abschnitt %s")
5322 ("es" :default "vea seccion %s")
5323 ("fr" :default "cf. section %s")
5324 ("zh-CN" :html "&#21442;&#35265;&#31532;%d&#33410;" :utf-8 "参见第%s节"))
5325 ("Table"
5326 ("de" :default "Tabelle")
5327 ("es" :default "Tabla")
5328 ("fr" :default "Tableau")
5329 ("ja" :html "&#34920;" :utf-8 "表")
5330 ("zh-CN" :html "&#34920;" :utf-8 "表"))
5331 ("Table %d:"
5332 ("de" :default "Tabelle %d")
5333 ("es" :default "Tabla %d")
5334 ("fr" :default "Tableau %d :")
5335 ("ja" :html "&#34920;%d:" :utf-8 "表%d:")
5336 ("zh-CN" :html "&#34920;%d&nbsp;" :utf-8 "表%d "))
5337 ("Table of Contents"
5338 ("ca" :html "&Iacute;ndex")
5339 ("cs" :default "Obsah")
5340 ("da" :default "Indhold")
5341 ("de" :default "Inhaltsverzeichnis")
5342 ("eo" :default "Enhavo")
5343 ("es" :html "&Iacute;ndice")
5344 ("fi" :html "Sis&auml;llysluettelo")
5345 ("fr" :ascii "Sommaire" :default "Table des matières")
5346 ("hu" :html "Tartalomjegyz&eacute;k")
5347 ("is" :default "Efnisyfirlit")
5348 ("it" :default "Indice")
5349 ("ja" :html "&#30446;&#27425;" :utf-8 "目次")
5350 ("nl" :default "Inhoudsopgave")
5351 ("no" :default "Innhold")
5352 ("nb" :default "Innhold")
5353 ("nn" :default "Innhald")
5354 ("pl" :html "Spis tre&#x015b;ci")
5355 ("ru" :html "&#1057;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1077;"
5356 :utf-8 "Содержание")
5357 ("sv" :html "Inneh&aring;ll")
5358 ("uk" :html "&#1047;&#1084;&#1110;&#1089;&#1090;" :utf-8 "Зміст")
5359 ("zh-CN" :html "&#30446;&#24405;" :utf-8 "目录")
5360 ("zh-TW" :html "&#30446;&#37636;" :utf-8 "目錄"))
5361 ("Unknown reference"
5362 ("de" :default "Unbekannter Verweis")
5363 ("es" :default "referencia desconocida")
5364 ("fr" :ascii "Destination inconnue" :default "Référence inconnue")
5365 ("zh-CN" :html "&#26410;&#30693;&#24341;&#29992;" :utf-8 "未知引用")))
5366 "Dictionary for export engine.
5368 Alist whose CAR is the string to translate and CDR is an alist
5369 whose CAR is the language string and CDR is a plist whose
5370 properties are possible charsets and values translated terms.
5372 It is used as a database for `org-export-translate'. Since this
5373 function returns the string as-is if no translation was found,
5374 the variable only needs to record values different from the
5375 entry.")
5377 (defun org-export-translate (s encoding info)
5378 "Translate string S according to language specification.
5380 ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1'
5381 and `:utf-8'. INFO is a plist used as a communication channel.
5383 Translation depends on `:language' property. Return the
5384 translated string. If no translation is found, try to fall back
5385 to `:default' encoding. If it fails, return S."
5386 (let* ((lang (plist-get info :language))
5387 (translations (cdr (assoc lang
5388 (cdr (assoc s org-export-dictionary))))))
5389 (or (plist-get translations encoding)
5390 (plist-get translations :default)
5391 s)))
5395 ;;; Asynchronous Export
5397 ;; `org-export-async-start' is the entry point for asynchronous
5398 ;; export. It recreates current buffer (including visibility,
5399 ;; narrowing and visited file) in an external Emacs process, and
5400 ;; evaluates a command there. It then applies a function on the
5401 ;; returned results in the current process.
5403 ;; Asynchronously generated results are never displayed directly.
5404 ;; Instead, they are stored in `org-export-stack-contents'. They can
5405 ;; then be retrieved by calling `org-export-stack'.
5407 ;; Export Stack is viewed through a dedicated major mode
5408 ;;`org-export-stack-mode' and tools: `org-export-stack-refresh',
5409 ;;`org-export-stack-delete', `org-export-stack-view' and
5410 ;;`org-export-stack-clear'.
5412 ;; For back-ends, `org-export-add-to-stack' add a new source to stack.
5413 ;; It should used whenever `org-export-async-start' is called.
5415 (defmacro org-export-async-start (fun &rest body)
5416 "Call function FUN on the results returned by BODY evaluation.
5418 BODY evaluation happens in an asynchronous process, from a buffer
5419 which is an exact copy of the current one.
5421 Use `org-export-add-to-stack' in FUN in order to register results
5422 in the stack. Examples for, respectively a temporary buffer and
5423 a file are:
5425 \(org-export-async-start
5426 \(lambda (output)
5427 \(with-current-buffer (get-buffer-create \"*Org BACKEND Export*\")
5428 \(erase-buffer)
5429 \(insert output)
5430 \(goto-char (point-min))
5431 \(org-export-add-to-stack (current-buffer) 'backend)))
5432 `(org-export-as 'backend ,subtreep ,visible-only ,body-only ',ext-plist))
5436 \(org-export-async-start
5437 \(lambda (f) (org-export-add-to-stack f 'backend))
5438 `(expand-file-name
5439 \(org-export-to-file
5440 'backend ,outfile ,subtreep ,visible-only ,body-only ',ext-plist)))"
5441 (declare (indent 1) (debug t))
5442 (org-with-gensyms (process temp-file copy-fun proc-buffer handler coding)
5443 ;; Write the full sexp evaluating BODY in a copy of the current
5444 ;; buffer to a temporary file, as it may be too long for program
5445 ;; args in `start-process'.
5446 `(with-temp-message "Initializing asynchronous export process"
5447 (let ((,copy-fun (org-export--generate-copy-script (current-buffer)))
5448 (,temp-file (make-temp-file "org-export-process"))
5449 (,coding buffer-file-coding-system))
5450 (with-temp-file ,temp-file
5451 (insert
5452 ;; Null characters (from variable values) are inserted
5453 ;; within the file. As a consequence, coding system for
5454 ;; buffer contents will not be recognized properly. So,
5455 ;; we make sure it is the same as the one used to display
5456 ;; the original buffer.
5457 (format ";; -*- coding: %s; -*-\n%S"
5458 ,coding
5459 `(with-temp-buffer
5460 ,(when org-export-async-debug '(setq debug-on-error t))
5461 ;; Ignore `kill-emacs-hook' and code evaluation
5462 ;; queries from Babel as we need a truly
5463 ;; non-interactive process.
5464 (setq kill-emacs-hook nil
5465 org-babel-confirm-evaluate-answer-no t)
5466 ;; Initialize export framework.
5467 (require 'ox)
5468 ;; Re-create current buffer there.
5469 (funcall ,,copy-fun)
5470 (restore-buffer-modified-p nil)
5471 ;; Sexp to evaluate in the buffer.
5472 (print (progn ,,@body))))))
5473 ;; Start external process.
5474 (let* ((process-connection-type nil)
5475 (,proc-buffer (generate-new-buffer-name "*Org Export Process*"))
5476 (,process
5477 (start-process
5478 "org-export-process" ,proc-buffer
5479 (expand-file-name invocation-name invocation-directory)
5480 "-Q" "--batch"
5481 "-l" org-export-async-init-file
5482 "-l" ,temp-file)))
5483 ;; Register running process in stack.
5484 (org-export-add-to-stack (get-buffer ,proc-buffer) nil ,process)
5485 ;; Set-up sentinel in order to catch results.
5486 (set-process-sentinel
5487 ,process
5488 (let ((handler ',fun))
5489 `(lambda (p status)
5490 (let ((proc-buffer (process-buffer p)))
5491 (when (eq (process-status p) 'exit)
5492 (unwind-protect
5493 (if (zerop (process-exit-status p))
5494 (unwind-protect
5495 (let ((results
5496 (with-current-buffer proc-buffer
5497 (goto-char (point-max))
5498 (backward-sexp)
5499 (read (current-buffer)))))
5500 (funcall ,handler results))
5501 (unless org-export-async-debug
5502 (and (get-buffer proc-buffer)
5503 (kill-buffer proc-buffer))))
5504 (org-export-add-to-stack proc-buffer nil p)
5505 (ding)
5506 (message "Process '%s' exited abnormally" p))
5507 (unless org-export-async-debug
5508 (delete-file ,,temp-file)))))))))))))
5510 (defun org-export-add-to-stack (source backend &optional process)
5511 "Add a new result to export stack if not present already.
5513 SOURCE is a buffer or a file name containing export results.
5514 BACKEND is a symbol representing export back-end used to generate
5517 Entries already pointing to SOURCE and unavailable entries are
5518 removed beforehand. Return the new stack."
5519 (setq org-export-stack-contents
5520 (cons (list source backend (or process (current-time)))
5521 (org-export-stack-remove source))))
5523 (defun org-export-stack ()
5524 "Menu for asynchronous export results and running processes."
5525 (interactive)
5526 (let ((buffer (get-buffer-create "*Org Export Stack*")))
5527 (set-buffer buffer)
5528 (when (zerop (buffer-size)) (org-export-stack-mode))
5529 (org-export-stack-refresh)
5530 (pop-to-buffer buffer))
5531 (message "Type \"q\" to quit, \"?\" for help"))
5533 (defun org-export--stack-source-at-point ()
5534 "Return source from export results at point in stack."
5535 (let ((source (car (nth (1- (org-current-line)) org-export-stack-contents))))
5536 (if (not source) (error "Source unavailable, please refresh buffer")
5537 (let ((source-name (if (stringp source) source (buffer-name source))))
5538 (if (save-excursion
5539 (beginning-of-line)
5540 (looking-at (concat ".* +" (regexp-quote source-name) "$")))
5541 source
5542 ;; SOURCE is not consistent with current line. The stack
5543 ;; view is outdated.
5544 (error "Source unavailable; type `g' to update buffer"))))))
5546 (defun org-export-stack-clear ()
5547 "Remove all entries from export stack."
5548 (interactive)
5549 (setq org-export-stack-contents nil))
5551 (defun org-export-stack-refresh (&rest dummy)
5552 "Refresh the asynchronous export stack.
5553 DUMMY is ignored. Unavailable sources are removed from the list.
5554 Return the new stack."
5555 (let ((inhibit-read-only t))
5556 (org-preserve-lc
5557 (erase-buffer)
5558 (insert (concat
5559 (let ((counter 0))
5560 (mapconcat
5561 (lambda (entry)
5562 (let ((proc-p (processp (nth 2 entry))))
5563 (concat
5564 ;; Back-end.
5565 (format " %-12s " (or (nth 1 entry) ""))
5566 ;; Age.
5567 (let ((data (nth 2 entry)))
5568 (if proc-p (format " %6s " (process-status data))
5569 ;; Compute age of the results.
5570 (org-format-seconds
5571 "%4h:%.2m "
5572 (float-time (time-since data)))))
5573 ;; Source.
5574 (format " %s"
5575 (let ((source (car entry)))
5576 (if (stringp source) source
5577 (buffer-name source)))))))
5578 ;; Clear stack from exited processes, dead buffers or
5579 ;; non-existent files.
5580 (setq org-export-stack-contents
5581 (org-remove-if-not
5582 (lambda (el)
5583 (if (processp (nth 2 el))
5584 (buffer-live-p (process-buffer (nth 2 el)))
5585 (let ((source (car el)))
5586 (if (bufferp source) (buffer-live-p source)
5587 (file-exists-p source)))))
5588 org-export-stack-contents)) "\n")))))))
5590 (defun org-export-stack-remove (&optional source)
5591 "Remove export results at point from stack.
5592 If optional argument SOURCE is non-nil, remove it instead."
5593 (interactive)
5594 (let ((source (or source (org-export--stack-source-at-point))))
5595 (setq org-export-stack-contents
5596 (org-remove-if (lambda (el) (equal (car el) source))
5597 org-export-stack-contents))))
5599 (defun org-export-stack-view (&optional in-emacs)
5600 "View export results at point in stack.
5601 With an optional prefix argument IN-EMACS, force viewing files
5602 within Emacs."
5603 (interactive "P")
5604 (let ((source (org-export--stack-source-at-point)))
5605 (cond ((processp source)
5606 (org-switch-to-buffer-other-window (process-buffer source)))
5607 ((bufferp source) (org-switch-to-buffer-other-window source))
5608 (t (org-open-file source in-emacs)))))
5610 (defconst org-export-stack-mode-map
5611 (let ((km (make-sparse-keymap)))
5612 (define-key km " " 'next-line)
5613 (define-key km "n" 'next-line)
5614 (define-key km "\C-n" 'next-line)
5615 (define-key km [down] 'next-line)
5616 (define-key km "p" 'previous-line)
5617 (define-key km "\C-p" 'previous-line)
5618 (define-key km "\C-?" 'previous-line)
5619 (define-key km [up] 'previous-line)
5620 (define-key km "C" 'org-export-stack-clear)
5621 (define-key km "v" 'org-export-stack-view)
5622 (define-key km (kbd "RET") 'org-export-stack-view)
5623 (define-key km "d" 'org-export-stack-remove)
5625 "Keymap for Org Export Stack.")
5627 (define-derived-mode org-export-stack-mode special-mode "Org-Stack"
5628 "Mode for displaying asynchronous export stack.
5630 Type \\[org-export-stack] to visualize the asynchronous export
5631 stack.
5633 In an Org Export Stack buffer, use \\<org-export-stack-mode-map>\\[org-export-stack-view] to view export output
5634 on current line, \\[org-export-stack-remove] to remove it from the stack and \\[org-export-stack-clear] to clear
5635 stack completely.
5637 Removing entries in an Org Export Stack buffer doesn't affect
5638 files or buffers, only the display.
5640 \\{org-export-stack-mode-map}"
5641 (abbrev-mode 0)
5642 (auto-fill-mode 0)
5643 (setq buffer-read-only t
5644 buffer-undo-list t
5645 truncate-lines t
5646 header-line-format
5647 '(:eval
5648 (format " %-12s | %6s | %s" "Back-End" "Age" "Source")))
5649 (org-add-hook 'post-command-hook 'org-export-stack-refresh nil t)
5650 (set (make-local-variable 'revert-buffer-function)
5651 'org-export-stack-refresh))
5655 ;;; The Dispatcher
5657 ;; `org-export-dispatch' is the standard interactive way to start an
5658 ;; export process. It uses `org-export--dispatch-ui' as a subroutine
5659 ;; for its interface, which, in turn, delegates response to key
5660 ;; pressed to `org-export--dispatch-action'.
5662 ;;;###autoload
5663 (defun org-export-dispatch (&optional arg)
5664 "Export dispatcher for Org mode.
5666 It provides an access to common export related tasks in a buffer.
5667 Its interface comes in two flavours: standard and expert.
5669 While both share the same set of bindings, only the former
5670 displays the valid keys associations in a dedicated buffer.
5671 Scrolling (resp. line-wise motion) in this buffer is done with
5672 SPC and DEL (resp. C-n and C-p) keys.
5674 Set variable `org-export-dispatch-use-expert-ui' to switch to one
5675 flavour or the other.
5677 When ARG is \\[universal-argument], repeat the last export action, with the same set
5678 of options used back then, on the current buffer.
5680 When ARG is \\[universal-argument] \\[universal-argument], display the asynchronous export stack."
5681 (interactive "P")
5682 (let* ((input
5683 (cond ((equal arg '(16)) '(stack))
5684 ((and arg org-export-dispatch-last-action))
5685 (t (save-window-excursion
5686 (unwind-protect
5687 (progn
5688 ;; Remember where we are
5689 (move-marker org-export-dispatch-last-position
5690 (point)
5691 (org-base-buffer (current-buffer)))
5692 ;; Get and store an export command
5693 (setq org-export-dispatch-last-action
5694 (org-export--dispatch-ui
5695 (list org-export-initial-scope
5696 (and org-export-in-background 'async))
5698 org-export-dispatch-use-expert-ui)))
5699 (and (get-buffer "*Org Export Dispatcher*")
5700 (kill-buffer "*Org Export Dispatcher*")))))))
5701 (action (car input))
5702 (optns (cdr input)))
5703 (unless (memq 'subtree optns)
5704 (move-marker org-export-dispatch-last-position nil))
5705 (case action
5706 ;; First handle special hard-coded actions.
5707 (template (org-export-insert-default-template nil optns))
5708 (stack (org-export-stack))
5709 (publish-current-file
5710 (org-publish-current-file (memq 'force optns) (memq 'async optns)))
5711 (publish-current-project
5712 (org-publish-current-project (memq 'force optns) (memq 'async optns)))
5713 (publish-choose-project
5714 (org-publish (assoc (org-icompleting-read
5715 "Publish project: "
5716 org-publish-project-alist nil t)
5717 org-publish-project-alist)
5718 (memq 'force optns)
5719 (memq 'async optns)))
5720 (publish-all (org-publish-all (memq 'force optns) (memq 'async optns)))
5721 (otherwise
5722 (save-excursion
5723 (when arg
5724 ;; Repeating command, maybe move cursor to restore subtree
5725 ;; context.
5726 (if (eq (marker-buffer org-export-dispatch-last-position)
5727 (org-base-buffer (current-buffer)))
5728 (goto-char org-export-dispatch-last-position)
5729 ;; We are in a different buffer, forget position.
5730 (move-marker org-export-dispatch-last-position nil)))
5731 (funcall action
5732 ;; Return a symbol instead of a list to ease
5733 ;; asynchronous export macro use.
5734 (and (memq 'async optns) t)
5735 (and (memq 'subtree optns) t)
5736 (and (memq 'visible optns) t)
5737 (and (memq 'body optns) t)))))))
5739 (defun org-export--dispatch-ui (options first-key expertp)
5740 "Handle interface for `org-export-dispatch'.
5742 OPTIONS is a list containing current interactive options set for
5743 export. It can contain any of the following symbols:
5744 `body' toggles a body-only export
5745 `subtree' restricts export to current subtree
5746 `visible' restricts export to visible part of buffer.
5747 `force' force publishing files.
5748 `async' use asynchronous export process
5750 FIRST-KEY is the key pressed to select the first level menu. It
5751 is nil when this menu hasn't been selected yet.
5753 EXPERTP, when non-nil, triggers expert UI. In that case, no help
5754 buffer is provided, but indications about currently active
5755 options are given in the prompt. Moreover, \[?] allows to switch
5756 back to standard interface."
5757 (let* ((fontify-key
5758 (lambda (key &optional access-key)
5759 ;; Fontify KEY string. Optional argument ACCESS-KEY, when
5760 ;; non-nil is the required first-level key to activate
5761 ;; KEY. When its value is t, activate KEY independently
5762 ;; on the first key, if any. A nil value means KEY will
5763 ;; only be activated at first level.
5764 (if (or (eq access-key t) (eq access-key first-key))
5765 (org-propertize key 'face 'org-warning)
5766 key)))
5767 (fontify-value
5768 (lambda (value)
5769 ;; Fontify VALUE string.
5770 (org-propertize value 'face 'font-lock-variable-name-face)))
5771 ;; Prepare menu entries by extracting them from
5772 ;; `org-export-registered-backends', and sorting them by
5773 ;; access key and by ordinal, if any.
5774 (backends
5775 (sort
5776 (sort
5777 (delq nil
5778 (mapcar
5779 (lambda (b)
5780 (let ((name (car b)))
5781 (catch 'ignored
5782 ;; Ignore any back-end belonging to
5783 ;; `org-export-invisible-backends' or derived
5784 ;; from one of them.
5785 (dolist (ignored org-export-invisible-backends)
5786 (when (org-export-derived-backend-p name ignored)
5787 (throw 'ignored nil)))
5788 (org-export-backend-menu name))))
5789 org-export-registered-backends))
5790 (lambda (a b)
5791 (let ((key-a (nth 1 a))
5792 (key-b (nth 1 b)))
5793 (cond ((and (numberp key-a) (numberp key-b))
5794 (< key-a key-b))
5795 ((numberp key-b) t)))))
5796 (lambda (a b) (< (car a) (car b)))))
5797 ;; Compute a list of allowed keys based on the first key
5798 ;; pressed, if any. Some keys
5799 ;; (?^B, ?^V, ?^S, ?^F, ?^A, ?&, ?# and ?q) are always
5800 ;; available.
5801 (allowed-keys
5802 (nconc (list 2 22 19 6 1)
5803 (if (not first-key) (org-uniquify (mapcar 'car backends))
5804 (let (sub-menu)
5805 (dolist (backend backends (sort (mapcar 'car sub-menu) '<))
5806 (when (eq (car backend) first-key)
5807 (setq sub-menu (append (nth 2 backend) sub-menu))))))
5808 (cond ((eq first-key ?P) (list ?f ?p ?x ?a))
5809 ((not first-key) (list ?P)))
5810 (list ?& ?#)
5811 (when expertp (list ??))
5812 (list ?q)))
5813 ;; Build the help menu for standard UI.
5814 (help
5815 (unless expertp
5816 (concat
5817 ;; Options are hard-coded.
5818 (format "[%s] Body only: %s [%s] Visible only: %s
5819 \[%s] Export scope: %s [%s] Force publishing: %s
5820 \[%s] Async export: %s\n\n"
5821 (funcall fontify-key "C-b" t)
5822 (funcall fontify-value
5823 (if (memq 'body options) "On " "Off"))
5824 (funcall fontify-key "C-v" t)
5825 (funcall fontify-value
5826 (if (memq 'visible options) "On " "Off"))
5827 (funcall fontify-key "C-s" t)
5828 (funcall fontify-value
5829 (if (memq 'subtree options) "Subtree" "Buffer "))
5830 (funcall fontify-key "C-f" t)
5831 (funcall fontify-value
5832 (if (memq 'force options) "On " "Off"))
5833 (funcall fontify-key "C-a" t)
5834 (funcall fontify-value
5835 (if (memq 'async options) "On " "Off")))
5836 ;; Display registered back-end entries. When a key
5837 ;; appears for the second time, do not create another
5838 ;; entry, but append its sub-menu to existing menu.
5839 (let (last-key)
5840 (mapconcat
5841 (lambda (entry)
5842 (let ((top-key (car entry)))
5843 (concat
5844 (unless (eq top-key last-key)
5845 (setq last-key top-key)
5846 (format "\n[%s] %s\n"
5847 (funcall fontify-key (char-to-string top-key))
5848 (nth 1 entry)))
5849 (let ((sub-menu (nth 2 entry)))
5850 (unless (functionp sub-menu)
5851 ;; Split sub-menu into two columns.
5852 (let ((index -1))
5853 (concat
5854 (mapconcat
5855 (lambda (sub-entry)
5856 (incf index)
5857 (format
5858 (if (zerop (mod index 2)) " [%s] %-26s"
5859 "[%s] %s\n")
5860 (funcall fontify-key
5861 (char-to-string (car sub-entry))
5862 top-key)
5863 (nth 1 sub-entry)))
5864 sub-menu "")
5865 (when (zerop (mod index 2)) "\n"))))))))
5866 backends ""))
5867 ;; Publishing menu is hard-coded.
5868 (format "\n[%s] Publish
5869 [%s] Current file [%s] Current project
5870 [%s] Choose project [%s] All projects\n\n\n"
5871 (funcall fontify-key "P")
5872 (funcall fontify-key "f" ?P)
5873 (funcall fontify-key "p" ?P)
5874 (funcall fontify-key "x" ?P)
5875 (funcall fontify-key "a" ?P))
5876 (format "[%s] Export stack [%s] Insert template\n"
5877 (funcall fontify-key "&" t)
5878 (funcall fontify-key "#" t))
5879 (format "[%s] %s"
5880 (funcall fontify-key "q" t)
5881 (if first-key "Main menu" "Exit")))))
5882 ;; Build prompts for both standard and expert UI.
5883 (standard-prompt (unless expertp "Export command: "))
5884 (expert-prompt
5885 (when expertp
5886 (format
5887 "Export command (C-%s%s%s%s%s) [%s]: "
5888 (if (memq 'body options) (funcall fontify-key "b" t) "b")
5889 (if (memq 'visible options) (funcall fontify-key "v" t) "v")
5890 (if (memq 'subtree options) (funcall fontify-key "s" t) "s")
5891 (if (memq 'force options) (funcall fontify-key "f" t) "f")
5892 (if (memq 'async options) (funcall fontify-key "a" t) "a")
5893 (mapconcat (lambda (k)
5894 ;; Strip control characters.
5895 (unless (< k 27) (char-to-string k)))
5896 allowed-keys "")))))
5897 ;; With expert UI, just read key with a fancy prompt. In standard
5898 ;; UI, display an intrusive help buffer.
5899 (if expertp
5900 (org-export--dispatch-action
5901 expert-prompt allowed-keys backends options first-key expertp)
5902 ;; At first call, create frame layout in order to display menu.
5903 (unless (get-buffer "*Org Export Dispatcher*")
5904 (delete-other-windows)
5905 (org-switch-to-buffer-other-window
5906 (get-buffer-create "*Org Export Dispatcher*"))
5907 (setq cursor-type nil
5908 header-line-format "Use SPC, DEL, C-n or C-p to navigate.")
5909 ;; Make sure that invisible cursor will not highlight square
5910 ;; brackets.
5911 (set-syntax-table (copy-syntax-table))
5912 (modify-syntax-entry ?\[ "w"))
5913 ;; At this point, the buffer containing the menu exists and is
5914 ;; visible in the current window. So, refresh it.
5915 (with-current-buffer "*Org Export Dispatcher*"
5916 ;; Refresh help. Maintain display continuity by re-visiting
5917 ;; previous window position.
5918 (let ((pos (window-start)))
5919 (erase-buffer)
5920 (insert help)
5921 (set-window-start nil pos)))
5922 (org-fit-window-to-buffer)
5923 (org-export--dispatch-action
5924 standard-prompt allowed-keys backends options first-key expertp))))
5926 (defun org-export--dispatch-action
5927 (prompt allowed-keys backends options first-key expertp)
5928 "Read a character from command input and act accordingly.
5930 PROMPT is the displayed prompt, as a string. ALLOWED-KEYS is
5931 a list of characters available at a given step in the process.
5932 BACKENDS is a list of menu entries. OPTIONS, FIRST-KEY and
5933 EXPERTP are the same as defined in `org-export--dispatch-ui',
5934 which see.
5936 Toggle export options when required. Otherwise, return value is
5937 a list with action as CAR and a list of interactive export
5938 options as CDR."
5939 (let (key)
5940 ;; Scrolling: when in non-expert mode, act on motion keys (C-n,
5941 ;; C-p, SPC, DEL).
5942 (while (and (setq key (read-char-exclusive prompt))
5943 (not expertp)
5944 (memq key '(14 16 ?\s ?\d)))
5945 (case key
5946 (14 (if (not (pos-visible-in-window-p (point-max)))
5947 (ignore-errors (scroll-up-line))
5948 (message "End of buffer")
5949 (sit-for 1)))
5950 (16 (if (not (pos-visible-in-window-p (point-min)))
5951 (ignore-errors (scroll-down-line))
5952 (message "Beginning of buffer")
5953 (sit-for 1)))
5954 (?\s (if (not (pos-visible-in-window-p (point-max)))
5955 (scroll-up nil)
5956 (message "End of buffer")
5957 (sit-for 1)))
5958 (?\d (if (not (pos-visible-in-window-p (point-min)))
5959 (scroll-down nil)
5960 (message "Beginning of buffer")
5961 (sit-for 1)))))
5962 (cond
5963 ;; Ignore undefined associations.
5964 ((not (memq key allowed-keys))
5965 (ding)
5966 (unless expertp (message "Invalid key") (sit-for 1))
5967 (org-export--dispatch-ui options first-key expertp))
5968 ;; q key at first level aborts export. At second level, cancel
5969 ;; first key instead.
5970 ((eq key ?q) (if (not first-key) (error "Export aborted")
5971 (org-export--dispatch-ui options nil expertp)))
5972 ;; Help key: Switch back to standard interface if expert UI was
5973 ;; active.
5974 ((eq key ??) (org-export--dispatch-ui options first-key nil))
5975 ;; Send request for template insertion along with export scope.
5976 ((eq key ?#) (cons 'template (memq 'subtree options)))
5977 ;; Switch to asynchronous export stack.
5978 ((eq key ?&) '(stack))
5979 ;; Toggle options: C-b (2) C-v (22) C-s (19) C-f (6) C-a (1).
5980 ((memq key '(2 22 19 6 1))
5981 (org-export--dispatch-ui
5982 (let ((option (case key (2 'body) (22 'visible) (19 'subtree)
5983 (6 'force) (1 'async))))
5984 (if (memq option options) (remq option options)
5985 (cons option options)))
5986 first-key expertp))
5987 ;; Action selected: Send key and options back to
5988 ;; `org-export-dispatch'.
5989 ((or first-key (functionp (nth 2 (assq key backends))))
5990 (cons (cond
5991 ((not first-key) (nth 2 (assq key backends)))
5992 ;; Publishing actions are hard-coded. Send a special
5993 ;; signal to `org-export-dispatch'.
5994 ((eq first-key ?P)
5995 (case key
5996 (?f 'publish-current-file)
5997 (?p 'publish-current-project)
5998 (?x 'publish-choose-project)
5999 (?a 'publish-all)))
6000 ;; Return first action associated to FIRST-KEY + KEY
6001 ;; path. Indeed, derived backends can share the same
6002 ;; FIRST-KEY.
6003 (t (catch 'found
6004 (mapc (lambda (backend)
6005 (let ((match (assq key (nth 2 backend))))
6006 (when match (throw 'found (nth 2 match)))))
6007 (member (assq first-key backends) backends)))))
6008 options))
6009 ;; Otherwise, enter sub-menu.
6010 (t (org-export--dispatch-ui options key expertp)))))
6014 (provide 'ox)
6016 ;; Local variables:
6017 ;; generated-autoload-file: "org-loaddefs.el"
6018 ;; End:
6020 ;;; ox.el ends here