org.el: Tiny cosmetic change.
[org-mode.git] / lisp / ox.el
blob21e5c231d149bb848ea02107fe9d4fe9322a8e75
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 nil 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-macro . org-export-filter-macro-functions)
213 (:filter-node-property . org-export-filter-node-property-functions)
214 (:filter-options . org-export-filter-options-functions)
215 (:filter-paragraph . org-export-filter-paragraph-functions)
216 (:filter-parse-tree . org-export-filter-parse-tree-functions)
217 (:filter-plain-list . org-export-filter-plain-list-functions)
218 (:filter-plain-text . org-export-filter-plain-text-functions)
219 (:filter-planning . org-export-filter-planning-functions)
220 (:filter-property-drawer . org-export-filter-property-drawer-functions)
221 (:filter-quote-block . org-export-filter-quote-block-functions)
222 (:filter-quote-section . org-export-filter-quote-section-functions)
223 (:filter-radio-target . org-export-filter-radio-target-functions)
224 (:filter-section . org-export-filter-section-functions)
225 (:filter-special-block . org-export-filter-special-block-functions)
226 (:filter-src-block . org-export-filter-src-block-functions)
227 (:filter-statistics-cookie . org-export-filter-statistics-cookie-functions)
228 (:filter-strike-through . org-export-filter-strike-through-functions)
229 (:filter-subscript . org-export-filter-subscript-functions)
230 (:filter-superscript . org-export-filter-superscript-functions)
231 (:filter-table . org-export-filter-table-functions)
232 (:filter-table-cell . org-export-filter-table-cell-functions)
233 (:filter-table-row . org-export-filter-table-row-functions)
234 (:filter-target . org-export-filter-target-functions)
235 (:filter-timestamp . org-export-filter-timestamp-functions)
236 (:filter-underline . org-export-filter-underline-functions)
237 (:filter-verbatim . org-export-filter-verbatim-functions)
238 (:filter-verse-block . org-export-filter-verse-block-functions))
239 "Alist between filters properties and initial values.
241 The key of each association is a property name accessible through
242 the communication channel. Its value is a configurable global
243 variable defining initial filters.
245 This list is meant to install user specified filters. Back-end
246 developers may install their own filters using
247 `org-export-define-backend'. Filters defined there will always
248 be prepended to the current list, so they always get applied
249 first.")
251 (defconst org-export-default-inline-image-rule
252 `(("file" .
253 ,(format "\\.%s\\'"
254 (regexp-opt
255 '("png" "jpeg" "jpg" "gif" "tiff" "tif" "xbm"
256 "xpm" "pbm" "pgm" "ppm") t))))
257 "Default rule for link matching an inline image.
258 This rule applies to links with no description. By default, it
259 will be considered as an inline image if it targets a local file
260 whose extension is either \"png\", \"jpeg\", \"jpg\", \"gif\",
261 \"tiff\", \"tif\", \"xbm\", \"xpm\", \"pbm\", \"pgm\" or \"ppm\".
262 See `org-export-inline-image-p' for more information about
263 rules.")
265 (defvar org-export-async-debug nil
266 "Non-nil means asynchronous export process should leave data behind.
268 This data is found in the appropriate \"*Org Export Process*\"
269 buffer, and in files prefixed with \"org-export-process\" and
270 located in `temporary-file-directory'.
272 When non-nil, it will also set `debug-on-error' to a non-nil
273 value in the external process.")
275 (defvar org-export-stack-contents nil
276 "Record asynchronously generated export results and processes.
277 This is an alist: its CAR is the source of the
278 result (destination file or buffer for a finished process,
279 original buffer for a running one) and its CDR is a list
280 containing the back-end used, as a symbol, and either a process
281 or the time at which it finished. It is used to build the menu
282 from `org-export-stack'.")
284 (defvar org-export-registered-backends nil
285 "List of backends currently available in the exporter.
287 A backend is stored as a list where CAR is its name, as a symbol,
288 and CDR is a plist with the following properties:
289 `:filters-alist', `:menu-entry', `:options-alist' and
290 `:translate-alist'.
292 This variable is set with `org-export-define-backend' and
293 `org-export-define-derived-backend' functions.")
295 (defvar org-export-dispatch-last-action nil
296 "Last command called from the dispatcher.
297 The value should be a list. Its CAR is the action, as a symbol,
298 and its CDR is a list of export options.")
300 (defvar org-export-dispatch-last-position (make-marker)
301 "The position where the last export command was created using the dispatcher.
302 This marker will be used with `C-u C-c C-e' to make sure export repetition
303 uses the same subtree if the previous command was restricted to a subtree.")
306 ;;; User-configurable Variables
308 ;; Configuration for the masses.
310 ;; They should never be accessed directly, as their value is to be
311 ;; stored in a property list (cf. `org-export-options-alist').
312 ;; Back-ends will read their value from there instead.
314 (defgroup org-export nil
315 "Options for exporting Org mode files."
316 :tag "Org Export"
317 :group 'org)
319 (defgroup org-export-general nil
320 "General options for export engine."
321 :tag "Org Export General"
322 :group 'org-export)
324 (defcustom org-export-with-archived-trees 'headline
325 "Whether sub-trees with the ARCHIVE tag should be exported.
327 This can have three different values:
328 nil Do not export, pretend this tree is not present.
329 t Do export the entire tree.
330 `headline' Only export the headline, but skip the tree below it.
332 This option can also be set with the OPTIONS keyword,
333 e.g. \"arch:nil\"."
334 :group 'org-export-general
335 :type '(choice
336 (const :tag "Not at all" nil)
337 (const :tag "Headline only" 'headline)
338 (const :tag "Entirely" t)))
340 (defcustom org-export-with-author t
341 "Non-nil means insert author name into the exported file.
342 This option can also be set with the OPTIONS keyword,
343 e.g. \"author:nil\"."
344 :group 'org-export-general
345 :type 'boolean)
347 (defcustom org-export-with-clocks nil
348 "Non-nil means export CLOCK keywords.
349 This option can also be set with the OPTIONS keyword,
350 e.g. \"c:t\"."
351 :group 'org-export-general
352 :type 'boolean)
354 (defcustom org-export-with-creator 'comment
355 "Non-nil means the postamble should contain a creator sentence.
357 The sentence can be set in `org-export-creator-string' and
358 defaults to \"Generated by Org mode XX in Emacs XXX.\".
360 If the value is `comment' insert it as a comment."
361 :group 'org-export-general
362 :type '(choice
363 (const :tag "No creator sentence" nil)
364 (const :tag "Sentence as a comment" 'comment)
365 (const :tag "Insert the sentence" t)))
367 (defcustom org-export-with-date t
368 "Non-nil means insert date in the exported document.
369 This option can also be set with the OPTIONS keyword,
370 e.g. \"date:nil\"."
371 :group 'org-export-general
372 :type 'boolean)
374 (defcustom org-export-date-timestamp-format nil
375 "Time-stamp format string to use for DATE keyword.
377 The format string, when specified, only applies if date consists
378 in a single time-stamp. Otherwise its value will be ignored.
380 See `format-time-string' for details on how to build this
381 string."
382 :group 'org-export-general
383 :type '(choice
384 (string :tag "Time-stamp format string")
385 (const :tag "No format string" nil)))
387 (defcustom org-export-creator-string
388 (format "Emacs %s (Org mode %s)"
389 emacs-version
390 (if (fboundp 'org-version) (org-version) "unknown version"))
391 "Information about the creator of the document.
392 This option can also be set on with the CREATOR keyword."
393 :group 'org-export-general
394 :type '(string :tag "Creator string"))
396 (defcustom org-export-with-drawers '(not "LOGBOOK")
397 "Non-nil means export contents of standard drawers.
399 When t, all drawers are exported. This may also be a list of
400 drawer names to export. If that list starts with `not', only
401 drawers with such names will be ignored.
403 This variable doesn't apply to properties drawers.
405 This option can also be set with the OPTIONS keyword,
406 e.g. \"d:nil\"."
407 :group 'org-export-general
408 :version "24.4"
409 :package-version '(Org . "8.0")
410 :type '(choice
411 (const :tag "All drawers" t)
412 (const :tag "None" nil)
413 (repeat :tag "Selected drawers"
414 (string :tag "Drawer name"))
415 (list :tag "Ignored drawers"
416 (const :format "" not)
417 (repeat :tag "Specify names of drawers to ignore during export"
418 :inline t
419 (string :tag "Drawer name")))))
421 (defcustom org-export-with-email nil
422 "Non-nil means insert author email into the exported file.
423 This option can also be set with the OPTIONS keyword,
424 e.g. \"email:t\"."
425 :group 'org-export-general
426 :type 'boolean)
428 (defcustom org-export-with-emphasize t
429 "Non-nil means interpret *word*, /word/, _word_ and +word+.
431 If the export target supports emphasizing text, the word will be
432 typeset in bold, italic, with an underline or strike-through,
433 respectively.
435 This option can also be set with the OPTIONS keyword,
436 e.g. \"*:nil\"."
437 :group 'org-export-general
438 :type 'boolean)
440 (defcustom org-export-exclude-tags '("noexport")
441 "Tags that exclude a tree from export.
443 All trees carrying any of these tags will be excluded from
444 export. This is without condition, so even subtrees inside that
445 carry one of the `org-export-select-tags' will be removed.
447 This option can also be set with the EXCLUDE_TAGS keyword."
448 :group 'org-export-general
449 :type '(repeat (string :tag "Tag")))
451 (defcustom org-export-with-fixed-width t
452 "Non-nil means lines starting with \":\" will be in fixed width font.
454 This can be used to have pre-formatted text, fragments of code
455 etc. For example:
456 : ;; Some Lisp examples
457 : (while (defc cnt)
458 : (ding))
459 will be looking just like this in also HTML. See also the QUOTE
460 keyword. Not all export backends support this.
462 This option can also be set with the OPTIONS keyword,
463 e.g. \"::nil\"."
464 :group 'org-export-general
465 :type 'boolean)
467 (defcustom org-export-with-footnotes t
468 "Non-nil means Org footnotes should be exported.
469 This option can also be set with the OPTIONS keyword,
470 e.g. \"f:nil\"."
471 :group 'org-export-general
472 :type 'boolean)
474 (defcustom org-export-with-latex t
475 "Non-nil means process LaTeX environments and fragments.
477 This option can also be set with the OPTIONS line,
478 e.g. \"tex:verbatim\". Allowed values are:
480 nil Ignore math snippets.
481 `verbatim' Keep everything in verbatim.
482 t Allow export of math snippets."
483 :group 'org-export-general
484 :version "24.4"
485 :package-version '(Org . "8.0")
486 :type '(choice
487 (const :tag "Do not process math in any way" nil)
488 (const :tag "Interpret math snippets" t)
489 (const :tag "Leave math verbatim" verbatim)))
491 (defcustom org-export-headline-levels 3
492 "The last level which is still exported as a headline.
494 Inferior levels will usually produce itemize or enumerate lists
495 when exported, but back-end behaviour may differ.
497 This option can also be set with the OPTIONS keyword,
498 e.g. \"H:2\"."
499 :group 'org-export-general
500 :type 'integer)
502 (defcustom org-export-default-language "en"
503 "The default language for export and clocktable translations, as a string.
504 This may have an association in
505 `org-clock-clocktable-language-setup'. This option can also be
506 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\"."
587 :group 'org-export-general
588 :version "24.4"
589 :package-version '(Org . "8.0")
590 :type 'boolean)
592 (defcustom org-export-with-special-strings t
593 "Non-nil means interpret \"\\-\", \"--\" and \"---\" for export.
595 When this option is turned on, these strings will be exported as:
597 Org HTML LaTeX UTF-8
598 -----+----------+--------+-------
599 \\- &shy; \\-
600 -- &ndash; -- –
601 --- &mdash; --- —
602 ... &hellip; \\ldots …
604 This option can also be set with the OPTIONS keyword,
605 e.g. \"-:nil\"."
606 :group 'org-export-general
607 :type 'boolean)
609 (defcustom org-export-with-statistics-cookies t
610 "Non-nil means include statistics cookies in export.
611 This option can also be set with the OPTIONS keyword,
612 e.g. \"stat:nil\""
613 :group 'org-export-general
614 :version "24.4"
615 :package-version '(Org . "8.0")
616 :type 'boolean)
618 (defcustom org-export-with-sub-superscripts t
619 "Non-nil means interpret \"_\" and \"^\" for export.
621 When this option is turned on, you can use TeX-like syntax for
622 sub- and superscripts. Several characters after \"_\" or \"^\"
623 will be considered as a single item - so grouping with {} is
624 normally not needed. For example, the following things will be
625 parsed as single sub- or superscripts.
627 10^24 or 10^tau several digits will be considered 1 item.
628 10^-12 or 10^-tau a leading sign with digits or a word
629 x^2-y^3 will be read as x^2 - y^3, because items are
630 terminated by almost any nonword/nondigit char.
631 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
633 Still, ambiguity is possible - so when in doubt use {} to enclose
634 the sub/superscript. If you set this variable to the symbol
635 `{}', the braces are *required* in order to trigger
636 interpretations as sub/superscript. This can be helpful in
637 documents that need \"_\" frequently in plain text.
639 This option can also be set with the OPTIONS keyword,
640 e.g. \"^:nil\"."
641 :group 'org-export-general
642 :type '(choice
643 (const :tag "Interpret them" t)
644 (const :tag "Curly brackets only" {})
645 (const :tag "Do not interpret them" nil)))
647 (defcustom org-export-with-toc t
648 "Non-nil means create a table of contents in exported files.
650 The TOC contains headlines with levels up
651 to`org-export-headline-levels'. When an integer, include levels
652 up to N in the toc, this may then be different from
653 `org-export-headline-levels', but it will not be allowed to be
654 larger than the number of headline levels. When nil, no table of
655 contents is made.
657 This option can also be set with the OPTIONS keyword,
658 e.g. \"toc:nil\" or \"toc:3\"."
659 :group 'org-export-general
660 :type '(choice
661 (const :tag "No Table of Contents" nil)
662 (const :tag "Full Table of Contents" t)
663 (integer :tag "TOC to level")))
665 (defcustom org-export-with-tables t
666 "If non-nil, lines starting with \"|\" define a table.
667 For example:
669 | Name | Address | Birthday |
670 |-------------+----------+-----------|
671 | Arthur Dent | England | 29.2.2100 |
673 This option can also be set with the OPTIONS keyword,
674 e.g. \"|:nil\"."
675 :group 'org-export-general
676 :type 'boolean)
678 (defcustom org-export-with-tags t
679 "If nil, do not export tags, just remove them from headlines.
681 If this is the symbol `not-in-toc', tags will be removed from
682 table of contents entries, but still be shown in the headlines of
683 the document.
685 This option can also be set with the OPTIONS keyword,
686 e.g. \"tags:nil\"."
687 :group 'org-export-general
688 :type '(choice
689 (const :tag "Off" nil)
690 (const :tag "Not in TOC" not-in-toc)
691 (const :tag "On" t)))
693 (defcustom org-export-with-tasks t
694 "Non-nil means include TODO items for export.
696 This may have the following values:
697 t include tasks independent of state.
698 `todo' include only tasks that are not yet done.
699 `done' include only tasks that are already done.
700 nil ignore all tasks.
701 list of keywords include tasks with these keywords.
703 This option can also be set with the OPTIONS keyword,
704 e.g. \"tasks:nil\"."
705 :group 'org-export-general
706 :type '(choice
707 (const :tag "All tasks" t)
708 (const :tag "No tasks" nil)
709 (const :tag "Not-done tasks" todo)
710 (const :tag "Only done tasks" done)
711 (repeat :tag "Specific TODO keywords"
712 (string :tag "Keyword"))))
714 (defcustom org-export-time-stamp-file t
715 "Non-nil means insert a time stamp into the exported file.
716 The time stamp shows when the file was created. This option can
717 also be set with the OPTIONS keyword, e.g. \"timestamp:nil\"."
718 :group 'org-export-general
719 :type 'boolean)
721 (defcustom org-export-with-timestamps t
722 "Non nil means allow timestamps in export.
724 It can be set to `active', `inactive', t or nil, in order to
725 export, respectively, only active timestamps, only inactive ones,
726 all of them or none.
728 This option can also be set with the OPTIONS keyword, e.g.
729 \"<:nil\"."
730 :group 'org-export-general
731 :type '(choice
732 (const :tag "All timestamps" t)
733 (const :tag "Only active timestamps" active)
734 (const :tag "Only inactive timestamps" inactive)
735 (const :tag "No timestamp" nil)))
737 (defcustom org-export-with-todo-keywords t
738 "Non-nil means include TODO keywords in export.
739 When nil, remove all these keywords from the export. This option
740 can also be set with the OPTIONS keyword, e.g. \"todo:nil\"."
741 :group 'org-export-general
742 :type 'boolean)
744 (defcustom org-export-allow-bind-keywords nil
745 "Non-nil means BIND keywords can define local variable values.
746 This is a potential security risk, which is why the default value
747 is nil. You can also allow them through local buffer variables."
748 :group 'org-export-general
749 :version "24.4"
750 :package-version '(Org . "8.0")
751 :type 'boolean)
753 (defcustom org-export-snippet-translation-alist nil
754 "Alist between export snippets back-ends and exporter back-ends.
756 This variable allows to provide shortcuts for export snippets.
758 For example, with a value of '\(\(\"h\" . \"html\"\)\), the
759 HTML back-end will recognize the contents of \"@@h:<b>@@\" as
760 HTML code while every other back-end will ignore it."
761 :group 'org-export-general
762 :version "24.4"
763 :package-version '(Org . "8.0")
764 :type '(repeat
765 (cons (string :tag "Shortcut")
766 (string :tag "Back-end"))))
768 (defcustom org-export-coding-system nil
769 "Coding system for the exported file."
770 :group 'org-export-general
771 :version "24.4"
772 :package-version '(Org . "8.0")
773 :type 'coding-system)
775 (defcustom org-export-copy-to-kill-ring 'if-interactive
776 "Should we push exported content to the kill ring?"
777 :group 'org-export-general
778 :version "24.3"
779 :type '(choice
780 (const :tag "Always" t)
781 (const :tag "When export is done interactively" if-interactive)
782 (const :tag "Never" nil)))
784 (defcustom org-export-initial-scope 'buffer
785 "The initial scope when exporting with `org-export-dispatch'.
786 This variable can be either set to `buffer' or `subtree'."
787 :group 'org-export-general
788 :type '(choice
789 (const :tag "Export current buffer" 'buffer)
790 (const :tag "Export current subtree" 'subtree)))
792 (defcustom org-export-show-temporary-export-buffer t
793 "Non-nil means show buffer after exporting to temp buffer.
794 When Org exports to a file, the buffer visiting that file is ever
795 shown, but remains buried. However, when exporting to
796 a temporary buffer, that buffer is popped up in a second window.
797 When this variable is nil, the buffer remains buried also in
798 these cases."
799 :group 'org-export-general
800 :type 'boolean)
802 (defcustom org-export-in-background nil
803 "Non-nil means export and publishing commands will run in background.
804 Results from an asynchronous export are never displayed
805 automatically. But you can retrieve them with \\[org-export-stack]."
806 :group 'org-export-general
807 :version "24.4"
808 :package-version '(Org . "8.0")
809 :type 'boolean)
811 (defcustom org-export-async-init-file user-init-file
812 "File used to initialize external export process.
813 Value must be an absolute file name. It defaults to user's
814 initialization file. Though, a specific configuration makes the
815 process faster and the export more portable."
816 :group 'org-export-general
817 :version "24.4"
818 :package-version '(Org . "8.0")
819 :type '(file :must-match t))
821 (defcustom org-export-invisible-backends nil
822 "List of back-ends that shouldn't appear in the dispatcher.
824 Any back-end belonging to this list or derived from a back-end
825 belonging to it will not appear in the dispatcher menu.
827 Indeed, Org may require some export back-ends without notice. If
828 these modules are never to be used interactively, adding them
829 here will avoid cluttering the dispatcher menu."
830 :group 'org-export-general
831 :version "24.4"
832 :package-version '(Org . "8.0")
833 :type '(repeat (symbol :tag "Back-End")))
835 (defcustom org-export-dispatch-use-expert-ui nil
836 "Non-nil means using a non-intrusive `org-export-dispatch'.
837 In that case, no help buffer is displayed. Though, an indicator
838 for current export scope is added to the prompt (\"b\" when
839 output is restricted to body only, \"s\" when it is restricted to
840 the current subtree, \"v\" when only visible elements are
841 considered for export, \"f\" when publishing functions should be
842 passed the FORCE argument and \"a\" when the export should be
843 asynchronous). Also, \[?] allows to switch back to standard
844 mode."
845 :group 'org-export-general
846 :version "24.4"
847 :package-version '(Org . "8.0")
848 :type 'boolean)
852 ;;; Defining Back-ends
854 ;; `org-export-define-backend' is the standard way to define an export
855 ;; back-end. It allows to specify translators, filters, buffer
856 ;; options and a menu entry. If the new back-end shares translators
857 ;; with another back-end, `org-export-define-derived-backend' may be
858 ;; used instead.
860 ;; Internally, a back-end is stored as a list, of which CAR is the
861 ;; name of the back-end, as a symbol, and CDR a plist. Accessors to
862 ;; properties of a given back-end are: `org-export-backend-filters',
863 ;; `org-export-backend-menu', `org-export-backend-options' and
864 ;; `org-export-backend-translate-table'.
866 ;; Eventually `org-export-barf-if-invalid-backend' returns an error
867 ;; when a given back-end hasn't been registered yet.
869 (defun org-export-define-backend (backend translators &rest body)
870 "Define a new back-end BACKEND.
872 TRANSLATORS is an alist between object or element types and
873 functions handling them.
875 These functions should return a string without any trailing
876 space, or nil. They must accept three arguments: the object or
877 element itself, its contents or nil when it isn't recursive and
878 the property list used as a communication channel.
880 Contents, when not nil, are stripped from any global indentation
881 \(although the relative one is preserved). They also always end
882 with a single newline character.
884 If, for a given type, no function is found, that element or
885 object type will simply be ignored, along with any blank line or
886 white space at its end. The same will happen if the function
887 returns the nil value. If that function returns the empty
888 string, the type will be ignored, but the blank lines or white
889 spaces will be kept.
891 In addition to element and object types, one function can be
892 associated to the `template' (or `inner-template') symbol and
893 another one to the `plain-text' symbol.
895 The former returns the final transcoded string, and can be used
896 to add a preamble and a postamble to document's body. It must
897 accept two arguments: the transcoded string and the property list
898 containing export options. A function associated to `template'
899 will not be applied if export has option \"body-only\".
900 A function associated to `inner-template' is always applied.
902 The latter, when defined, is to be called on every text not
903 recognized as an element or an object. It must accept two
904 arguments: the text string and the information channel. It is an
905 appropriate place to protect special chars relative to the
906 back-end.
908 BODY can start with pre-defined keyword arguments. The following
909 keywords are understood:
911 :export-block
913 String, or list of strings, representing block names that
914 will not be parsed. This is used to specify blocks that will
915 contain raw code specific to the back-end. These blocks
916 still have to be handled by the relative `export-block' type
917 translator.
919 :filters-alist
921 Alist between filters and function, or list of functions,
922 specific to the back-end. See `org-export-filters-alist' for
923 a list of all allowed filters. Filters defined here
924 shouldn't make a back-end test, as it may prevent back-ends
925 derived from this one to behave properly.
927 :menu-entry
929 Menu entry for the export dispatcher. It should be a list
930 like:
932 '(KEY DESCRIPTION-OR-ORDINAL ACTION-OR-MENU)
934 where :
936 KEY is a free character selecting the back-end.
938 DESCRIPTION-OR-ORDINAL is either a string or a number.
940 If it is a string, is will be used to name the back-end in
941 its menu entry. If it is a number, the following menu will
942 be displayed as a sub-menu of the back-end with the same
943 KEY. Also, the number will be used to determine in which
944 order such sub-menus will appear (lowest first).
946 ACTION-OR-MENU is either a function or an alist.
948 If it is an action, it will be called with four
949 arguments (booleans): ASYNC, SUBTREEP, VISIBLE-ONLY and
950 BODY-ONLY. See `org-export-as' for further explanations on
951 some of them.
953 If it is an alist, associations should follow the
954 pattern:
956 '(KEY DESCRIPTION ACTION)
958 where KEY, DESCRIPTION and ACTION are described above.
960 Valid values include:
962 '(?m \"My Special Back-end\" my-special-export-function)
966 '(?l \"Export to LaTeX\"
967 \(?p \"As PDF file\" org-latex-export-to-pdf)
968 \(?o \"As PDF file and open\"
969 \(lambda (a s v b)
970 \(if a (org-latex-export-to-pdf t s v b)
971 \(org-open-file
972 \(org-latex-export-to-pdf nil s v b)))))))
974 or the following, which will be added to the previous
975 sub-menu,
977 '(?l 1
978 \((?B \"As TEX buffer (Beamer)\" org-beamer-export-as-latex)
979 \(?P \"As PDF file (Beamer)\" org-beamer-export-to-pdf)))
981 :options-alist
983 Alist between back-end specific properties introduced in
984 communication channel and how their value are acquired. See
985 `org-export-options-alist' for more information about
986 structure of the values."
987 (declare (indent 1))
988 (let (export-block filters menu-entry options contents)
989 (while (keywordp (car body))
990 (case (pop body)
991 (:export-block (let ((names (pop body)))
992 (setq export-block
993 (if (consp names) (mapcar 'upcase names)
994 (list (upcase names))))))
995 (:filters-alist (setq filters (pop body)))
996 (:menu-entry (setq menu-entry (pop body)))
997 (:options-alist (setq options (pop body)))
998 (t (pop body))))
999 (setq contents (append (list :translate-alist translators)
1000 (and filters (list :filters-alist filters))
1001 (and options (list :options-alist options))
1002 (and menu-entry (list :menu-entry menu-entry))))
1003 ;; Register back-end.
1004 (let ((registeredp (assq backend org-export-registered-backends)))
1005 (if registeredp (setcdr registeredp contents)
1006 (push (cons backend contents) org-export-registered-backends)))
1007 ;; Tell parser to not parse EXPORT-BLOCK blocks.
1008 (when export-block
1009 (mapc
1010 (lambda (name)
1011 (add-to-list 'org-element-block-name-alist
1012 `(,name . org-element-export-block-parser)))
1013 export-block))))
1015 (defun org-export-define-derived-backend (child parent &rest body)
1016 "Create a new back-end as a variant of an existing one.
1018 CHILD is the name of the derived back-end. PARENT is the name of
1019 the parent back-end.
1021 BODY can start with pre-defined keyword arguments. The following
1022 keywords are understood:
1024 :export-block
1026 String, or list of strings, representing block names that
1027 will not be parsed. This is used to specify blocks that will
1028 contain raw code specific to the back-end. These blocks
1029 still have to be handled by the relative `export-block' type
1030 translator.
1032 :filters-alist
1034 Alist of filters that will overwrite or complete filters
1035 defined in PARENT back-end. See `org-export-filters-alist'
1036 for a list of allowed filters.
1038 :menu-entry
1040 Menu entry for the export dispatcher. See
1041 `org-export-define-backend' for more information about the
1042 expected value.
1044 :options-alist
1046 Alist of back-end specific properties that will overwrite or
1047 complete those defined in PARENT back-end. Refer to
1048 `org-export-options-alist' for more information about
1049 structure of the values.
1051 :translate-alist
1053 Alist of element and object types and transcoders that will
1054 overwrite or complete transcode table from PARENT back-end.
1055 Refer to `org-export-define-backend' for detailed information
1056 about transcoders.
1058 As an example, here is how one could define \"my-latex\" back-end
1059 as a variant of `latex' back-end with a custom template function:
1061 \(org-export-define-derived-backend 'my-latex 'latex
1062 :translate-alist '((template . my-latex-template-fun)))
1064 The back-end could then be called with, for example:
1066 \(org-export-to-buffer 'my-latex \"*Test my-latex*\")"
1067 (declare (indent 2))
1068 (let (export-block filters menu-entry options translators contents)
1069 (while (keywordp (car body))
1070 (case (pop body)
1071 (:export-block (let ((names (pop body)))
1072 (setq export-block
1073 (if (consp names) (mapcar 'upcase names)
1074 (list (upcase names))))))
1075 (:filters-alist (setq filters (pop body)))
1076 (:menu-entry (setq menu-entry (pop body)))
1077 (:options-alist (setq options (pop body)))
1078 (:translate-alist (setq translators (pop body)))
1079 (t (pop body))))
1080 (setq contents (append
1081 (list :parent parent)
1082 (let ((p-table (org-export-backend-translate-table parent)))
1083 (list :translate-alist (append translators p-table)))
1084 (let ((p-filters (org-export-backend-filters parent)))
1085 (list :filters-alist (append filters p-filters)))
1086 (let ((p-options (org-export-backend-options parent)))
1087 (list :options-alist (append options p-options)))
1088 (and menu-entry (list :menu-entry menu-entry))))
1089 (org-export-barf-if-invalid-backend parent)
1090 ;; Register back-end.
1091 (let ((registeredp (assq child org-export-registered-backends)))
1092 (if registeredp (setcdr registeredp contents)
1093 (push (cons child contents) org-export-registered-backends)))
1094 ;; Tell parser to not parse EXPORT-BLOCK blocks.
1095 (when export-block
1096 (mapc
1097 (lambda (name)
1098 (add-to-list 'org-element-block-name-alist
1099 `(,name . org-element-export-block-parser)))
1100 export-block))))
1102 (defun org-export-backend-parent (backend)
1103 "Return back-end from which BACKEND is derived, or nil."
1104 (plist-get (cdr (assq backend org-export-registered-backends)) :parent))
1106 (defun org-export-backend-filters (backend)
1107 "Return filters for BACKEND."
1108 (plist-get (cdr (assq backend org-export-registered-backends))
1109 :filters-alist))
1111 (defun org-export-backend-menu (backend)
1112 "Return menu entry for BACKEND."
1113 (plist-get (cdr (assq backend org-export-registered-backends))
1114 :menu-entry))
1116 (defun org-export-backend-options (backend)
1117 "Return export options for BACKEND."
1118 (plist-get (cdr (assq backend org-export-registered-backends))
1119 :options-alist))
1121 (defun org-export-backend-translate-table (backend)
1122 "Return translate table for BACKEND."
1123 (plist-get (cdr (assq backend org-export-registered-backends))
1124 :translate-alist))
1126 (defun org-export-barf-if-invalid-backend (backend)
1127 "Signal an error if BACKEND isn't defined."
1128 (unless (org-export-backend-translate-table backend)
1129 (error "Unknown \"%s\" back-end: Aborting export" backend)))
1131 (defun org-export-derived-backend-p (backend &rest backends)
1132 "Non-nil if BACKEND is derived from one of BACKENDS."
1133 (let ((parent backend))
1134 (while (and (not (memq parent backends))
1135 (setq parent (org-export-backend-parent parent))))
1136 parent))
1140 ;;; The Communication Channel
1142 ;; During export process, every function has access to a number of
1143 ;; properties. They are of two types:
1145 ;; 1. Environment options are collected once at the very beginning of
1146 ;; the process, out of the original buffer and configuration.
1147 ;; Collecting them is handled by `org-export-get-environment'
1148 ;; function.
1150 ;; Most environment options are defined through the
1151 ;; `org-export-options-alist' variable.
1153 ;; 2. Tree properties are extracted directly from the parsed tree,
1154 ;; just before export, by `org-export-collect-tree-properties'.
1156 ;; Here is the full list of properties available during transcode
1157 ;; process, with their category and their value type.
1159 ;; + `:author' :: Author's name.
1160 ;; - category :: option
1161 ;; - type :: string
1163 ;; + `:back-end' :: Current back-end used for transcoding.
1164 ;; - category :: tree
1165 ;; - type :: symbol
1167 ;; + `:creator' :: String to write as creation information.
1168 ;; - category :: option
1169 ;; - type :: string
1171 ;; + `:date' :: String to use as date.
1172 ;; - category :: option
1173 ;; - type :: string
1175 ;; + `:description' :: Description text for the current data.
1176 ;; - category :: option
1177 ;; - type :: string
1179 ;; + `:email' :: Author's email.
1180 ;; - category :: option
1181 ;; - type :: string
1183 ;; + `:exclude-tags' :: Tags for exclusion of subtrees from export
1184 ;; process.
1185 ;; - category :: option
1186 ;; - type :: list of strings
1188 ;; + `:export-options' :: List of export options available for current
1189 ;; process.
1190 ;; - category :: none
1191 ;; - type :: list of symbols, among `subtree', `body-only' and
1192 ;; `visible-only'.
1194 ;; + `:exported-data' :: Hash table used for memoizing
1195 ;; `org-export-data'.
1196 ;; - category :: tree
1197 ;; - type :: hash table
1199 ;; + `:filetags' :: List of global tags for buffer. Used by
1200 ;; `org-export-get-tags' to get tags with inheritance.
1201 ;; - category :: option
1202 ;; - type :: list of strings
1204 ;; + `:footnote-definition-alist' :: Alist between footnote labels and
1205 ;; their definition, as parsed data. Only non-inlined footnotes
1206 ;; are represented in this alist. Also, every definition isn't
1207 ;; guaranteed to be referenced in the parse tree. The purpose of
1208 ;; this property is to preserve definitions from oblivion
1209 ;; (i.e. when the parse tree comes from a part of the original
1210 ;; buffer), it isn't meant for direct use in a back-end. To
1211 ;; retrieve a definition relative to a reference, use
1212 ;; `org-export-get-footnote-definition' instead.
1213 ;; - category :: option
1214 ;; - type :: alist (STRING . LIST)
1216 ;; + `:headline-levels' :: Maximum level being exported as an
1217 ;; headline. Comparison is done with the relative level of
1218 ;; headlines in the parse tree, not necessarily with their
1219 ;; actual level.
1220 ;; - category :: option
1221 ;; - type :: integer
1223 ;; + `:headline-offset' :: Difference between relative and real level
1224 ;; of headlines in the parse tree. For example, a value of -1
1225 ;; means a level 2 headline should be considered as level
1226 ;; 1 (cf. `org-export-get-relative-level').
1227 ;; - category :: tree
1228 ;; - type :: integer
1230 ;; + `:headline-numbering' :: Alist between headlines and their
1231 ;; numbering, as a list of numbers
1232 ;; (cf. `org-export-get-headline-number').
1233 ;; - category :: tree
1234 ;; - type :: alist (INTEGER . LIST)
1236 ;; + `:id-alist' :: Alist between ID strings and destination file's
1237 ;; path, relative to current directory. It is used by
1238 ;; `org-export-resolve-id-link' to resolve ID links targeting an
1239 ;; external file.
1240 ;; - category :: option
1241 ;; - type :: alist (STRING . STRING)
1243 ;; + `:ignore-list' :: List of elements and objects that should be
1244 ;; ignored during export.
1245 ;; - category :: tree
1246 ;; - type :: list of elements and objects
1248 ;; + `:input-file' :: Full path to input file, if any.
1249 ;; - category :: option
1250 ;; - type :: string or nil
1252 ;; + `:keywords' :: List of keywords attached to data.
1253 ;; - category :: option
1254 ;; - type :: string
1256 ;; + `:language' :: Default language used for translations.
1257 ;; - category :: option
1258 ;; - type :: string
1260 ;; + `:parse-tree' :: Whole parse tree, available at any time during
1261 ;; transcoding.
1262 ;; - category :: option
1263 ;; - type :: list (as returned by `org-element-parse-buffer')
1265 ;; + `:preserve-breaks' :: Non-nil means transcoding should preserve
1266 ;; all line breaks.
1267 ;; - category :: option
1268 ;; - type :: symbol (nil, t)
1270 ;; + `:section-numbers' :: Non-nil means transcoding should add
1271 ;; section numbers to headlines.
1272 ;; - category :: option
1273 ;; - type :: symbol (nil, t)
1275 ;; + `:select-tags' :: List of tags enforcing inclusion of sub-trees
1276 ;; in transcoding. When such a tag is present, subtrees without
1277 ;; it are de facto excluded from the process. See
1278 ;; `use-select-tags'.
1279 ;; - category :: option
1280 ;; - type :: list of strings
1282 ;; + `:time-stamp-file' :: Non-nil means transcoding should insert
1283 ;; a time stamp in the output.
1284 ;; - category :: option
1285 ;; - type :: symbol (nil, t)
1287 ;; + `:translate-alist' :: Alist between element and object types and
1288 ;; transcoding functions relative to the current back-end.
1289 ;; Special keys `inner-template', `template' and `plain-text' are
1290 ;; also possible.
1291 ;; - category :: option
1292 ;; - type :: alist (SYMBOL . FUNCTION)
1294 ;; + `:with-archived-trees' :: Non-nil when archived subtrees should
1295 ;; also be transcoded. If it is set to the `headline' symbol,
1296 ;; only the archived headline's name is retained.
1297 ;; - category :: option
1298 ;; - type :: symbol (nil, t, `headline')
1300 ;; + `:with-author' :: Non-nil means author's name should be included
1301 ;; in the output.
1302 ;; - category :: option
1303 ;; - type :: symbol (nil, t)
1305 ;; + `:with-clocks' :: Non-nil means clock keywords should be exported.
1306 ;; - category :: option
1307 ;; - type :: symbol (nil, t)
1309 ;; + `:with-creator' :: Non-nil means a creation sentence should be
1310 ;; inserted at the end of the transcoded string. If the value
1311 ;; is `comment', it should be commented.
1312 ;; - category :: option
1313 ;; - type :: symbol (`comment', nil, t)
1315 ;; + `:with-date' :: Non-nil means output should contain a date.
1316 ;; - category :: option
1317 ;; - type :. symbol (nil, t)
1319 ;; + `:with-drawers' :: Non-nil means drawers should be exported. If
1320 ;; its value is a list of names, only drawers with such names
1321 ;; will be transcoded. If that list starts with `not', drawer
1322 ;; with these names will be skipped.
1323 ;; - category :: option
1324 ;; - type :: symbol (nil, t) or list of strings
1326 ;; + `:with-email' :: Non-nil means output should contain author's
1327 ;; email.
1328 ;; - category :: option
1329 ;; - type :: symbol (nil, t)
1331 ;; + `:with-emphasize' :: Non-nil means emphasized text should be
1332 ;; interpreted.
1333 ;; - category :: option
1334 ;; - type :: symbol (nil, t)
1336 ;; + `:with-fixed-width' :: Non-nil if transcoder should interpret
1337 ;; strings starting with a colon as a fixed-with (verbatim) area.
1338 ;; - category :: option
1339 ;; - type :: symbol (nil, t)
1341 ;; + `:with-footnotes' :: Non-nil if transcoder should interpret
1342 ;; footnotes.
1343 ;; - category :: option
1344 ;; - type :: symbol (nil, t)
1346 ;; + `:with-latex' :: Non-nil means `latex-environment' elements and
1347 ;; `latex-fragment' objects should appear in export output. When
1348 ;; this property is set to `verbatim', they will be left as-is.
1349 ;; - category :: option
1350 ;; - type :: symbol (`verbatim', nil, t)
1352 ;; + `:with-planning' :: Non-nil means transcoding should include
1353 ;; planning info.
1354 ;; - category :: option
1355 ;; - type :: symbol (nil, t)
1357 ;; + `:with-priority' :: Non-nil means transcoding should include
1358 ;; priority cookies.
1359 ;; - category :: option
1360 ;; - type :: symbol (nil, t)
1362 ;; + `:with-smart-quotes' :: Non-nil means activate smart quotes in
1363 ;; plain text.
1364 ;; - category :: option
1365 ;; - type :: symbol (nil, t)
1367 ;; + `:with-special-strings' :: Non-nil means transcoding should
1368 ;; interpret special strings in plain text.
1369 ;; - category :: option
1370 ;; - type :: symbol (nil, t)
1372 ;; + `:with-sub-superscript' :: Non-nil means transcoding should
1373 ;; interpret subscript and superscript. With a value of "{}",
1374 ;; only interpret those using curly brackets.
1375 ;; - category :: option
1376 ;; - type :: symbol (nil, {}, t)
1378 ;; + `:with-tables' :: Non-nil means transcoding should interpret
1379 ;; tables.
1380 ;; - category :: option
1381 ;; - type :: symbol (nil, t)
1383 ;; + `:with-tags' :: Non-nil means transcoding should keep tags in
1384 ;; headlines. A `not-in-toc' value will remove them from the
1385 ;; table of contents, if any, nonetheless.
1386 ;; - category :: option
1387 ;; - type :: symbol (nil, t, `not-in-toc')
1389 ;; + `:with-tasks' :: Non-nil means transcoding should include
1390 ;; headlines with a TODO keyword. A `todo' value will only
1391 ;; include headlines with a todo type keyword while a `done'
1392 ;; value will do the contrary. If a list of strings is provided,
1393 ;; only tasks with keywords belonging to that list will be kept.
1394 ;; - category :: option
1395 ;; - type :: symbol (t, todo, done, nil) or list of strings
1397 ;; + `:with-timestamps' :: Non-nil means transcoding should include
1398 ;; time stamps. Special value `active' (resp. `inactive') ask to
1399 ;; export only active (resp. inactive) timestamps. Otherwise,
1400 ;; completely remove them.
1401 ;; - category :: option
1402 ;; - type :: symbol: (`active', `inactive', t, nil)
1404 ;; + `:with-toc' :: Non-nil means that a table of contents has to be
1405 ;; added to the output. An integer value limits its depth.
1406 ;; - category :: option
1407 ;; - type :: symbol (nil, t or integer)
1409 ;; + `:with-todo-keywords' :: Non-nil means transcoding should
1410 ;; include TODO keywords.
1411 ;; - category :: option
1412 ;; - type :: symbol (nil, t)
1415 ;;;; Environment Options
1417 ;; Environment options encompass all parameters defined outside the
1418 ;; scope of the parsed data. They come from five sources, in
1419 ;; increasing precedence order:
1421 ;; - Global variables,
1422 ;; - Buffer's attributes,
1423 ;; - Options keyword symbols,
1424 ;; - Buffer keywords,
1425 ;; - Subtree properties.
1427 ;; The central internal function with regards to environment options
1428 ;; is `org-export-get-environment'. It updates global variables with
1429 ;; "#+BIND:" keywords, then retrieve and prioritize properties from
1430 ;; the different sources.
1432 ;; The internal functions doing the retrieval are:
1433 ;; `org-export--get-global-options',
1434 ;; `org-export--get-buffer-attributes',
1435 ;; `org-export--parse-option-keyword',
1436 ;; `org-export--get-subtree-options' and
1437 ;; `org-export--get-inbuffer-options'
1439 ;; Also, `org-export--install-letbind-maybe' takes care of the part
1440 ;; relative to "#+BIND:" keywords.
1442 (defun org-export-get-environment (&optional backend subtreep ext-plist)
1443 "Collect export options from the current buffer.
1445 Optional argument BACKEND is a symbol specifying which back-end
1446 specific options to read, if any.
1448 When optional argument SUBTREEP is non-nil, assume the export is
1449 done against the current sub-tree.
1451 Third optional argument EXT-PLIST is a property list with
1452 external parameters overriding Org default settings, but still
1453 inferior to file-local settings."
1454 ;; First install #+BIND variables since these must be set before
1455 ;; global options are read.
1456 (dolist (pair (org-export--list-bound-variables))
1457 (org-set-local (car pair) (nth 1 pair)))
1458 ;; Get and prioritize export options...
1459 (org-combine-plists
1460 ;; ... from global variables...
1461 (org-export--get-global-options backend)
1462 ;; ... from an external property list...
1463 ext-plist
1464 ;; ... from in-buffer settings...
1465 (org-export--get-inbuffer-options backend)
1466 ;; ... and from subtree, when appropriate.
1467 (and subtreep (org-export--get-subtree-options backend))
1468 ;; Eventually add misc. properties.
1469 (list
1470 :back-end
1471 backend
1472 :translate-alist
1473 (org-export-backend-translate-table backend)
1474 :footnote-definition-alist
1475 ;; Footnotes definitions must be collected in the original
1476 ;; buffer, as there's no insurance that they will still be in
1477 ;; the parse tree, due to possible narrowing.
1478 (let (alist)
1479 (org-with-wide-buffer
1480 (goto-char (point-min))
1481 (while (re-search-forward org-footnote-definition-re nil t)
1482 (let ((def (save-match-data (org-element-at-point))))
1483 (when (eq (org-element-type def) 'footnote-definition)
1484 (push
1485 (cons (org-element-property :label def)
1486 (let ((cbeg (org-element-property :contents-begin def)))
1487 (when cbeg
1488 (org-element--parse-elements
1489 cbeg (org-element-property :contents-end def)
1490 nil nil nil nil (list 'org-data nil)))))
1491 alist))))
1492 alist))
1493 :id-alist
1494 ;; Collect id references.
1495 (let (alist)
1496 (org-with-wide-buffer
1497 (goto-char (point-min))
1498 (while (re-search-forward "\\[\\[id:\\S-+?\\]" nil t)
1499 (let ((link (org-element-context)))
1500 (when (eq (org-element-type link) 'link)
1501 (let* ((id (org-element-property :path link))
1502 (file (org-id-find-id-file id)))
1503 (when file
1504 (push (cons id (file-relative-name file)) alist)))))))
1505 alist))))
1507 (defun org-export--parse-option-keyword (options &optional backend)
1508 "Parse an OPTIONS line and return values as a plist.
1509 Optional argument BACKEND is a symbol specifying which back-end
1510 specific items to read, if any."
1511 (let* ((all
1512 ;; Priority is given to back-end specific options.
1513 (append (and backend (org-export-backend-options backend))
1514 org-export-options-alist))
1515 plist)
1516 (dolist (option all)
1517 (let ((property (car option))
1518 (item (nth 2 option)))
1519 (when (and item
1520 (not (plist-member plist property))
1521 (string-match (concat "\\(\\`\\|[ \t]\\)"
1522 (regexp-quote item)
1523 ":\\(([^)\n]+)\\|[^ \t\n\r;,.]*\\)")
1524 options))
1525 (setq plist (plist-put plist
1526 property
1527 (car (read-from-string
1528 (match-string 2 options))))))))
1529 plist))
1531 (defun org-export--get-subtree-options (&optional backend)
1532 "Get export options in subtree at point.
1533 Optional argument BACKEND is a symbol specifying back-end used
1534 for export. Return options as a plist."
1535 ;; For each buffer keyword, create a headline property setting the
1536 ;; same property in communication channel. The name for the property
1537 ;; is the keyword with "EXPORT_" appended to it.
1538 (org-with-wide-buffer
1539 (let (prop plist)
1540 ;; Make sure point is at a heading.
1541 (if (org-at-heading-p) (org-up-heading-safe) (org-back-to-heading t))
1542 ;; Take care of EXPORT_TITLE. If it isn't defined, use headline's
1543 ;; title as its fallback value.
1544 (when (setq prop (or (org-entry-get (point) "EXPORT_TITLE")
1545 (progn (looking-at org-todo-line-regexp)
1546 (org-match-string-no-properties 3))))
1547 (setq plist
1548 (plist-put
1549 plist :title
1550 (org-element-parse-secondary-string
1551 prop (org-element-restriction 'keyword)))))
1552 ;; EXPORT_OPTIONS are parsed in a non-standard way.
1553 (when (setq prop (org-entry-get (point) "EXPORT_OPTIONS"))
1554 (setq plist
1555 (nconc plist (org-export--parse-option-keyword prop backend))))
1556 ;; Handle other keywords. TITLE keyword is excluded as it has
1557 ;; been handled already.
1558 (let ((seen '("TITLE")))
1559 (mapc
1560 (lambda (option)
1561 (let ((property (car option))
1562 (keyword (nth 1 option)))
1563 (when (and keyword (not (member keyword seen)))
1564 (let* ((subtree-prop (concat "EXPORT_" keyword))
1565 ;; Export properties are not case-sensitive.
1566 (value (let ((case-fold-search t))
1567 (org-entry-get (point) subtree-prop))))
1568 (push keyword seen)
1569 (when (and value (not (plist-member plist property)))
1570 (setq plist
1571 (plist-put
1572 plist
1573 property
1574 (cond
1575 ;; Parse VALUE if required.
1576 ((member keyword org-element-document-properties)
1577 (org-element-parse-secondary-string
1578 value (org-element-restriction 'keyword)))
1579 ;; If BEHAVIOUR is `split' expected value is
1580 ;; a list of strings, not a string.
1581 ((eq (nth 4 option) 'split) (org-split-string value))
1582 (t value)))))))))
1583 ;; Look for both general keywords and back-end specific
1584 ;; options, with priority given to the latter.
1585 (append (and backend (org-export-backend-options backend))
1586 org-export-options-alist)))
1587 ;; Return value.
1588 plist)))
1590 (defun org-export--get-inbuffer-options (&optional backend)
1591 "Return current buffer export options, as a plist.
1593 Optional argument BACKEND, when non-nil, is a symbol specifying
1594 which back-end specific options should also be read in the
1595 process.
1597 Assume buffer is in Org mode. Narrowing, if any, is ignored."
1598 (let* (plist
1599 get-options ; For byte-compiler.
1600 (case-fold-search t)
1601 (options (append
1602 ;; Priority is given to back-end specific options.
1603 (and backend (org-export-backend-options backend))
1604 org-export-options-alist))
1605 (regexp (format "^[ \t]*#\\+%s:"
1606 (regexp-opt (nconc (delq nil (mapcar 'cadr options))
1607 org-export-special-keywords))))
1608 (find-opt
1609 (lambda (keyword)
1610 ;; Return property name associated to KEYWORD.
1611 (catch 'exit
1612 (mapc (lambda (option)
1613 (when (equal (nth 1 option) keyword)
1614 (throw 'exit (car option))))
1615 options))))
1616 (get-options
1617 (lambda (&optional files plist)
1618 ;; Recursively read keywords in buffer. FILES is a list
1619 ;; of files read so far. PLIST is the current property
1620 ;; list obtained.
1621 (org-with-wide-buffer
1622 (goto-char (point-min))
1623 (while (re-search-forward regexp nil t)
1624 (let ((element (org-element-at-point)))
1625 (when (eq (org-element-type element) 'keyword)
1626 (let ((key (org-element-property :key element))
1627 (val (org-element-property :value element)))
1628 (cond
1629 ;; Options in `org-export-special-keywords'.
1630 ((equal key "SETUPFILE")
1631 (let ((file (expand-file-name
1632 (org-remove-double-quotes (org-trim val)))))
1633 ;; Avoid circular dependencies.
1634 (unless (member file files)
1635 (with-temp-buffer
1636 (insert (org-file-contents file 'noerror))
1637 (let ((org-inhibit-startup t)) (org-mode))
1638 (setq plist (funcall get-options
1639 (cons file files) plist))))))
1640 ((equal key "OPTIONS")
1641 (setq plist
1642 (org-combine-plists
1643 plist
1644 (org-export--parse-option-keyword val backend))))
1645 ((equal key "FILETAGS")
1646 (setq plist
1647 (org-combine-plists
1648 plist
1649 (list :filetags
1650 (org-uniquify
1651 (append (org-split-string val ":")
1652 (plist-get plist :filetags)))))))
1654 ;; Options in `org-export-options-alist'.
1655 (let* ((prop (funcall find-opt key))
1656 (behaviour (nth 4 (assq prop options))))
1657 (setq plist
1658 (plist-put
1659 plist prop
1660 ;; Handle value depending on specified
1661 ;; BEHAVIOUR.
1662 (case behaviour
1663 (space
1664 (if (not (plist-get plist prop))
1665 (org-trim val)
1666 (concat (plist-get plist prop)
1668 (org-trim val))))
1669 (newline
1670 (org-trim (concat (plist-get plist prop)
1671 "\n"
1672 (org-trim val))))
1673 (split `(,@(plist-get plist prop)
1674 ,@(org-split-string val)))
1675 ('t val)
1676 (otherwise
1677 (if (not (plist-member plist prop)) val
1678 (plist-get plist prop)))))))))))))
1679 ;; Return final value.
1680 plist))))
1681 ;; Read options in the current buffer.
1682 (setq plist (funcall get-options buffer-file-name nil))
1683 ;; Parse keywords specified in `org-element-document-properties'.
1684 (mapc (lambda (keyword)
1685 ;; Find the property associated to the keyword.
1686 (let* ((prop (funcall find-opt keyword))
1687 (value (and prop (plist-get plist prop))))
1688 (when (stringp value)
1689 (setq plist
1690 (plist-put plist prop
1691 (org-element-parse-secondary-string
1692 value (org-element-restriction 'keyword)))))))
1693 org-element-document-properties)
1694 ;; Return value.
1695 plist))
1697 (defun org-export--get-buffer-attributes ()
1698 "Return properties related to buffer attributes, as a plist."
1699 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
1700 (list
1701 ;; Store full path of input file name, or nil. For internal use.
1702 :input-file visited-file
1703 :title (or (and visited-file
1704 (file-name-sans-extension
1705 (file-name-nondirectory visited-file)))
1706 (buffer-name (buffer-base-buffer))))))
1708 (defun org-export--get-global-options (&optional backend)
1709 "Return global export options as a plist.
1711 Optional argument BACKEND, if non-nil, is a symbol specifying
1712 which back-end specific export options should also be read in the
1713 process."
1714 (let ((all
1715 ;; Priority is given to back-end specific options.
1716 (append (and backend (org-export-backend-options backend))
1717 org-export-options-alist))
1718 plist)
1719 (mapc
1720 (lambda (cell)
1721 (let ((prop (car cell)))
1722 (unless (plist-member plist prop)
1723 (setq plist
1724 (plist-put
1725 plist
1726 prop
1727 ;; Eval default value provided. If keyword is a member
1728 ;; of `org-element-document-properties', parse it as
1729 ;; a secondary string before storing it.
1730 (let ((value (eval (nth 3 cell))))
1731 (if (not (stringp value)) value
1732 (let ((keyword (nth 1 cell)))
1733 (if (not (member keyword org-element-document-properties))
1734 value
1735 (org-element-parse-secondary-string
1736 value (org-element-restriction 'keyword)))))))))))
1737 all)
1738 ;; Return value.
1739 plist))
1741 (defun org-export--list-bound-variables ()
1742 "Return variables bound from BIND keywords in current buffer.
1743 Also look for BIND keywords in setup files. The return value is
1744 an alist where associations are (VARIABLE-NAME VALUE)."
1745 (when org-export-allow-bind-keywords
1746 (let* (collect-bind ; For byte-compiler.
1747 (collect-bind
1748 (lambda (files alist)
1749 ;; Return an alist between variable names and their
1750 ;; value. FILES is a list of setup files names read so
1751 ;; far, used to avoid circular dependencies. ALIST is
1752 ;; the alist collected so far.
1753 (let ((case-fold-search t))
1754 (org-with-wide-buffer
1755 (goto-char (point-min))
1756 (while (re-search-forward
1757 "^[ \t]*#\\+\\(BIND\\|SETUPFILE\\):" nil t)
1758 (let ((element (org-element-at-point)))
1759 (when (eq (org-element-type element) 'keyword)
1760 (let ((val (org-element-property :value element)))
1761 (if (equal (org-element-property :key element) "BIND")
1762 (push (read (format "(%s)" val)) alist)
1763 ;; Enter setup file.
1764 (let ((file (expand-file-name
1765 (org-remove-double-quotes val))))
1766 (unless (member file files)
1767 (with-temp-buffer
1768 (let ((org-inhibit-startup t)) (org-mode))
1769 (insert (org-file-contents file 'noerror))
1770 (setq alist
1771 (funcall collect-bind
1772 (cons file files)
1773 alist))))))))))
1774 alist)))))
1775 ;; Return value in appropriate order of appearance.
1776 (nreverse (funcall collect-bind nil nil)))))
1779 ;;;; Tree Properties
1781 ;; Tree properties are information extracted from parse tree. They
1782 ;; are initialized at the beginning of the transcoding process by
1783 ;; `org-export-collect-tree-properties'.
1785 ;; Dedicated functions focus on computing the value of specific tree
1786 ;; properties during initialization. Thus,
1787 ;; `org-export--populate-ignore-list' lists elements and objects that
1788 ;; should be skipped during export, `org-export--get-min-level' gets
1789 ;; the minimal exportable level, used as a basis to compute relative
1790 ;; level for headlines. Eventually
1791 ;; `org-export--collect-headline-numbering' builds an alist between
1792 ;; headlines and their numbering.
1794 (defun org-export-collect-tree-properties (data info)
1795 "Extract tree properties from parse tree.
1797 DATA is the parse tree from which information is retrieved. INFO
1798 is a list holding export options.
1800 Following tree properties are set or updated:
1802 `:exported-data' Hash table used to memoize results from
1803 `org-export-data'.
1805 `:footnote-definition-alist' List of footnotes definitions in
1806 original buffer and current parse tree.
1808 `:headline-offset' Offset between true level of headlines and
1809 local level. An offset of -1 means a headline
1810 of level 2 should be considered as a level
1811 1 headline in the context.
1813 `:headline-numbering' Alist of all headlines as key an the
1814 associated numbering as value.
1816 `:ignore-list' List of elements that should be ignored during
1817 export.
1819 Return updated plist."
1820 ;; Install the parse tree in the communication channel, in order to
1821 ;; use `org-export-get-genealogy' and al.
1822 (setq info (plist-put info :parse-tree data))
1823 ;; Get the list of elements and objects to ignore, and put it into
1824 ;; `:ignore-list'. Do not overwrite any user ignore that might have
1825 ;; been done during parse tree filtering.
1826 (setq info
1827 (plist-put info
1828 :ignore-list
1829 (append (org-export--populate-ignore-list data info)
1830 (plist-get info :ignore-list))))
1831 ;; Compute `:headline-offset' in order to be able to use
1832 ;; `org-export-get-relative-level'.
1833 (setq info
1834 (plist-put info
1835 :headline-offset
1836 (- 1 (org-export--get-min-level data info))))
1837 ;; Update footnotes definitions list with definitions in parse tree.
1838 ;; This is required since buffer expansion might have modified
1839 ;; boundaries of footnote definitions contained in the parse tree.
1840 ;; This way, definitions in `footnote-definition-alist' are bound to
1841 ;; match those in the parse tree.
1842 (let ((defs (plist-get info :footnote-definition-alist)))
1843 (org-element-map data 'footnote-definition
1844 (lambda (fn)
1845 (push (cons (org-element-property :label fn)
1846 `(org-data nil ,@(org-element-contents fn)))
1847 defs)))
1848 (setq info (plist-put info :footnote-definition-alist defs)))
1849 ;; Properties order doesn't matter: get the rest of the tree
1850 ;; properties.
1851 (nconc
1852 `(:headline-numbering ,(org-export--collect-headline-numbering data info)
1853 :exported-data ,(make-hash-table :test 'eq :size 4001))
1854 info))
1856 (defun org-export--get-min-level (data options)
1857 "Return minimum exportable headline's level in DATA.
1858 DATA is parsed tree as returned by `org-element-parse-buffer'.
1859 OPTIONS is a plist holding export options."
1860 (catch 'exit
1861 (let ((min-level 10000))
1862 (mapc
1863 (lambda (blob)
1864 (when (and (eq (org-element-type blob) 'headline)
1865 (not (org-element-property :footnote-section-p blob))
1866 (not (memq blob (plist-get options :ignore-list))))
1867 (setq min-level (min (org-element-property :level blob) min-level)))
1868 (when (= min-level 1) (throw 'exit 1)))
1869 (org-element-contents data))
1870 ;; If no headline was found, for the sake of consistency, set
1871 ;; minimum level to 1 nonetheless.
1872 (if (= min-level 10000) 1 min-level))))
1874 (defun org-export--collect-headline-numbering (data options)
1875 "Return numbering of all exportable headlines in a parse tree.
1877 DATA is the parse tree. OPTIONS is the plist holding export
1878 options.
1880 Return an alist whose key is a headline and value is its
1881 associated numbering \(in the shape of a list of numbers\) or nil
1882 for a footnotes section."
1883 (let ((numbering (make-vector org-export-max-depth 0)))
1884 (org-element-map data 'headline
1885 (lambda (headline)
1886 (unless (org-element-property :footnote-section-p headline)
1887 (let ((relative-level
1888 (1- (org-export-get-relative-level headline options))))
1889 (cons
1890 headline
1891 (loop for n across numbering
1892 for idx from 0 to org-export-max-depth
1893 when (< idx relative-level) collect n
1894 when (= idx relative-level) collect (aset numbering idx (1+ n))
1895 when (> idx relative-level) do (aset numbering idx 0))))))
1896 options)))
1898 (defun org-export--populate-ignore-list (data options)
1899 "Return list of elements and objects to ignore during export.
1900 DATA is the parse tree to traverse. OPTIONS is the plist holding
1901 export options."
1902 (let* (ignore
1903 walk-data
1904 ;; First find trees containing a select tag, if any.
1905 (selected (org-export--selected-trees data options))
1906 (walk-data
1907 (lambda (data)
1908 ;; Collect ignored elements or objects into IGNORE-LIST.
1909 (let ((type (org-element-type data)))
1910 (if (org-export--skip-p data options selected) (push data ignore)
1911 (if (and (eq type 'headline)
1912 (eq (plist-get options :with-archived-trees) 'headline)
1913 (org-element-property :archivedp data))
1914 ;; If headline is archived but tree below has
1915 ;; to be skipped, add it to ignore list.
1916 (mapc (lambda (e) (push e ignore))
1917 (org-element-contents data))
1918 ;; Move into secondary string, if any.
1919 (let ((sec-prop
1920 (cdr (assq type org-element-secondary-value-alist))))
1921 (when sec-prop
1922 (mapc walk-data (org-element-property sec-prop data))))
1923 ;; Move into recursive objects/elements.
1924 (mapc walk-data (org-element-contents data))))))))
1925 ;; Main call.
1926 (funcall walk-data data)
1927 ;; Return value.
1928 ignore))
1930 (defun org-export--selected-trees (data info)
1931 "Return list of headlines and inlinetasks with a select tag in their tree.
1932 DATA is parsed data as returned by `org-element-parse-buffer'.
1933 INFO is a plist holding export options."
1934 (let* (selected-trees
1935 walk-data ; For byte-compiler.
1936 (walk-data
1937 (function
1938 (lambda (data genealogy)
1939 (let ((type (org-element-type data)))
1940 (cond
1941 ((memq type '(headline inlinetask))
1942 (let ((tags (org-element-property :tags data)))
1943 (if (loop for tag in (plist-get info :select-tags)
1944 thereis (member tag tags))
1945 ;; When a select tag is found, mark full
1946 ;; genealogy and every headline within the tree
1947 ;; as acceptable.
1948 (setq selected-trees
1949 (append
1950 genealogy
1951 (org-element-map data '(headline inlinetask)
1952 'identity)
1953 selected-trees))
1954 ;; If at a headline, continue searching in tree,
1955 ;; recursively.
1956 (when (eq type 'headline)
1957 (mapc (lambda (el)
1958 (funcall walk-data el (cons data genealogy)))
1959 (org-element-contents data))))))
1960 ((or (eq type 'org-data)
1961 (memq type org-element-greater-elements))
1962 (mapc (lambda (el) (funcall walk-data el genealogy))
1963 (org-element-contents data)))))))))
1964 (funcall walk-data data nil)
1965 selected-trees))
1967 (defun org-export--skip-p (blob options selected)
1968 "Non-nil when element or object BLOB should be skipped during export.
1969 OPTIONS is the plist holding export options. SELECTED, when
1970 non-nil, is a list of headlines or inlinetasks belonging to
1971 a tree with a select tag."
1972 (case (org-element-type blob)
1973 (clock (not (plist-get options :with-clocks)))
1974 (drawer
1975 (let ((with-drawers-p (plist-get options :with-drawers)))
1976 (or (not with-drawers-p)
1977 (and (consp with-drawers-p)
1978 ;; If `:with-drawers' value starts with `not', ignore
1979 ;; every drawer whose name belong to that list.
1980 ;; Otherwise, ignore drawers whose name isn't in that
1981 ;; list.
1982 (let ((name (org-element-property :drawer-name blob)))
1983 (if (eq (car with-drawers-p) 'not)
1984 (member-ignore-case name (cdr with-drawers-p))
1985 (not (member-ignore-case name with-drawers-p))))))))
1986 ((headline inlinetask)
1987 (let ((with-tasks (plist-get options :with-tasks))
1988 (todo (org-element-property :todo-keyword blob))
1989 (todo-type (org-element-property :todo-type blob))
1990 (archived (plist-get options :with-archived-trees))
1991 (tags (org-element-property :tags blob)))
1993 (and (eq (org-element-type blob) 'inlinetask)
1994 (not (plist-get options :with-inlinetasks)))
1995 ;; Ignore subtrees with an exclude tag.
1996 (loop for k in (plist-get options :exclude-tags)
1997 thereis (member k tags))
1998 ;; When a select tag is present in the buffer, ignore any tree
1999 ;; without it.
2000 (and selected (not (memq blob selected)))
2001 ;; Ignore commented sub-trees.
2002 (org-element-property :commentedp blob)
2003 ;; Ignore archived subtrees if `:with-archived-trees' is nil.
2004 (and (not archived) (org-element-property :archivedp blob))
2005 ;; Ignore tasks, if specified by `:with-tasks' property.
2006 (and todo
2007 (or (not with-tasks)
2008 (and (memq with-tasks '(todo done))
2009 (not (eq todo-type with-tasks)))
2010 (and (consp with-tasks) (not (member todo with-tasks))))))))
2011 ((latex-environment latex-fragment) (not (plist-get options :with-latex)))
2012 (planning (not (plist-get options :with-planning)))
2013 (statistics-cookie (not (plist-get options :with-statistics-cookies)))
2014 (table-cell
2015 (and (org-export-table-has-special-column-p
2016 (org-export-get-parent-table blob))
2017 (not (org-export-get-previous-element blob options))))
2018 (table-row (org-export-table-row-is-special-p blob options))
2019 (timestamp
2020 (case (plist-get options :with-timestamps)
2021 ;; No timestamp allowed.
2022 ('nil t)
2023 ;; Only active timestamps allowed and the current one isn't
2024 ;; active.
2025 (active
2026 (not (memq (org-element-property :type blob)
2027 '(active active-range))))
2028 ;; Only inactive timestamps allowed and the current one isn't
2029 ;; inactive.
2030 (inactive
2031 (not (memq (org-element-property :type blob)
2032 '(inactive inactive-range))))))))
2035 ;;; The Transcoder
2037 ;; `org-export-data' reads a parse tree (obtained with, i.e.
2038 ;; `org-element-parse-buffer') and transcodes it into a specified
2039 ;; back-end output. It takes care of filtering out elements or
2040 ;; objects according to export options and organizing the output blank
2041 ;; lines and white space are preserved. The function memoizes its
2042 ;; results, so it is cheap to call it within translators.
2044 ;; It is possible to modify locally the back-end used by
2045 ;; `org-export-data' or even use a temporary back-end by using
2046 ;; `org-export-data-with-translations' and
2047 ;; `org-export-data-with-backend'.
2049 ;; Internally, three functions handle the filtering of objects and
2050 ;; elements during the export. In particular,
2051 ;; `org-export-ignore-element' marks an element or object so future
2052 ;; parse tree traversals skip it, `org-export--interpret-p' tells which
2053 ;; elements or objects should be seen as real Org syntax and
2054 ;; `org-export-expand' transforms the others back into their original
2055 ;; shape
2057 ;; `org-export-transcoder' is an accessor returning appropriate
2058 ;; translator function for a given element or object.
2060 (defun org-export-transcoder (blob info)
2061 "Return appropriate transcoder for BLOB.
2062 INFO is a plist containing export directives."
2063 (let ((type (org-element-type blob)))
2064 ;; Return contents only for complete parse trees.
2065 (if (eq type 'org-data) (lambda (blob contents info) contents)
2066 (let ((transcoder (cdr (assq type (plist-get info :translate-alist)))))
2067 (and (functionp transcoder) transcoder)))))
2069 (defun org-export-data (data info)
2070 "Convert DATA into current back-end format.
2072 DATA is a parse tree, an element or an object or a secondary
2073 string. INFO is a plist holding export options.
2075 Return transcoded string."
2076 (let ((memo (gethash data (plist-get info :exported-data) 'no-memo)))
2077 (if (not (eq memo 'no-memo)) memo
2078 (let* ((type (org-element-type data))
2079 (results
2080 (cond
2081 ;; Ignored element/object.
2082 ((memq data (plist-get info :ignore-list)) nil)
2083 ;; Plain text.
2084 ((eq type 'plain-text)
2085 (org-export-filter-apply-functions
2086 (plist-get info :filter-plain-text)
2087 (let ((transcoder (org-export-transcoder data info)))
2088 (if transcoder (funcall transcoder data info) data))
2089 info))
2090 ;; Uninterpreted element/object: change it back to Org
2091 ;; syntax and export again resulting raw string.
2092 ((not (org-export--interpret-p data info))
2093 (org-export-data
2094 (org-export-expand
2095 data
2096 (mapconcat (lambda (blob) (org-export-data blob info))
2097 (org-element-contents data)
2098 ""))
2099 info))
2100 ;; Secondary string.
2101 ((not type)
2102 (mapconcat (lambda (obj) (org-export-data obj info)) data ""))
2103 ;; Element/Object without contents or, as a special case,
2104 ;; headline with archive tag and archived trees restricted
2105 ;; to title only.
2106 ((or (not (org-element-contents data))
2107 (and (eq type 'headline)
2108 (eq (plist-get info :with-archived-trees) 'headline)
2109 (org-element-property :archivedp data)))
2110 (let ((transcoder (org-export-transcoder data info)))
2111 (or (and (functionp transcoder)
2112 (funcall transcoder data nil info))
2113 ;; Export snippets never return a nil value so
2114 ;; that white spaces following them are never
2115 ;; ignored.
2116 (and (eq type 'export-snippet) ""))))
2117 ;; Element/Object with contents.
2119 (let ((transcoder (org-export-transcoder data info)))
2120 (when transcoder
2121 (let* ((greaterp (memq type org-element-greater-elements))
2122 (objectp
2123 (and (not greaterp)
2124 (memq type org-element-recursive-objects)))
2125 (contents
2126 (mapconcat
2127 (lambda (element) (org-export-data element info))
2128 (org-element-contents
2129 (if (or greaterp objectp) data
2130 ;; Elements directly containing objects
2131 ;; must have their indentation normalized
2132 ;; first.
2133 (org-element-normalize-contents
2134 data
2135 ;; When normalizing contents of the first
2136 ;; paragraph in an item or a footnote
2137 ;; definition, ignore first line's
2138 ;; indentation: there is none and it
2139 ;; might be misleading.
2140 (when (eq type 'paragraph)
2141 (let ((parent (org-export-get-parent data)))
2142 (and
2143 (eq (car (org-element-contents parent))
2144 data)
2145 (memq (org-element-type parent)
2146 '(footnote-definition item))))))))
2147 "")))
2148 (funcall transcoder data
2149 (if (not greaterp) contents
2150 (org-element-normalize-string contents))
2151 info))))))))
2152 ;; Final result will be memoized before being returned.
2153 (puthash
2154 data
2155 (cond
2156 ((not results) nil)
2157 ((memq type '(org-data plain-text nil)) results)
2158 ;; Append the same white space between elements or objects as in
2159 ;; the original buffer, and call appropriate filters.
2161 (let ((results
2162 (org-export-filter-apply-functions
2163 (plist-get info (intern (format ":filter-%s" type)))
2164 (let ((post-blank (or (org-element-property :post-blank data)
2165 0)))
2166 (if (memq type org-element-all-elements)
2167 (concat (org-element-normalize-string results)
2168 (make-string post-blank ?\n))
2169 (concat results (make-string post-blank ? ))))
2170 info)))
2171 results)))
2172 (plist-get info :exported-data))))))
2174 (defun org-export-data-with-translations (data translations info)
2175 "Convert DATA into another format using a given translation table.
2176 DATA is an element, an object, a secondary string or a string.
2177 TRANSLATIONS is an alist between element or object types and
2178 a functions handling them. See `org-export-define-backend' for
2179 more information. INFO is a plist used as a communication
2180 channel."
2181 (org-export-data
2182 data
2183 ;; Set-up a new communication channel with TRANSLATIONS as the
2184 ;; translate table and a new hash table for memoization.
2185 (org-combine-plists
2186 info
2187 (list :translate-alist translations
2188 ;; Size of the hash table is reduced since this function
2189 ;; will probably be used on short trees.
2190 :exported-data (make-hash-table :test 'eq :size 401)))))
2192 (defun org-export-data-with-backend (data backend info)
2193 "Convert DATA into BACKEND format.
2195 DATA is an element, an object, a secondary string or a string.
2196 BACKEND is a symbol. INFO is a plist used as a communication
2197 channel.
2199 Unlike to `org-export-with-backend', this function will
2200 recursively convert DATA using BACKEND translation table."
2201 (org-export-barf-if-invalid-backend backend)
2202 (org-export-data-with-translations
2203 data (org-export-backend-translate-table backend) info))
2205 (defun org-export--interpret-p (blob info)
2206 "Non-nil if element or object BLOB should be interpreted during export.
2207 If nil, BLOB will appear as raw Org syntax. Check is done
2208 according to export options INFO, stored as a plist."
2209 (case (org-element-type blob)
2210 ;; ... entities...
2211 (entity (plist-get info :with-entities))
2212 ;; ... emphasis...
2213 ((bold italic strike-through underline)
2214 (plist-get info :with-emphasize))
2215 ;; ... fixed-width areas.
2216 (fixed-width (plist-get info :with-fixed-width))
2217 ;; ... footnotes...
2218 ((footnote-definition footnote-reference)
2219 (plist-get info :with-footnotes))
2220 ;; ... LaTeX environments and fragments...
2221 ((latex-environment latex-fragment)
2222 (let ((with-latex-p (plist-get info :with-latex)))
2223 (and with-latex-p (not (eq with-latex-p 'verbatim)))))
2224 ;; ... sub/superscripts...
2225 ((subscript superscript)
2226 (let ((sub/super-p (plist-get info :with-sub-superscript)))
2227 (if (eq sub/super-p '{})
2228 (org-element-property :use-brackets-p blob)
2229 sub/super-p)))
2230 ;; ... tables...
2231 (table (plist-get info :with-tables))
2232 (otherwise t)))
2234 (defun org-export-expand (blob contents)
2235 "Expand a parsed element or object to its original state.
2236 BLOB is either an element or an object. CONTENTS is its
2237 contents, as a string or nil."
2238 (funcall
2239 (intern (format "org-element-%s-interpreter" (org-element-type blob)))
2240 blob contents))
2242 (defun org-export-ignore-element (element info)
2243 "Add ELEMENT to `:ignore-list' in INFO.
2245 Any element in `:ignore-list' will be skipped when using
2246 `org-element-map'. INFO is modified by side effects."
2247 (plist-put info :ignore-list (cons element (plist-get info :ignore-list))))
2251 ;;; The Filter System
2253 ;; Filters allow end-users to tweak easily the transcoded output.
2254 ;; They are the functional counterpart of hooks, as every filter in
2255 ;; a set is applied to the return value of the previous one.
2257 ;; Every set is back-end agnostic. Although, a filter is always
2258 ;; called, in addition to the string it applies to, with the back-end
2259 ;; used as argument, so it's easy for the end-user to add back-end
2260 ;; specific filters in the set. The communication channel, as
2261 ;; a plist, is required as the third argument.
2263 ;; From the developer side, filters sets can be installed in the
2264 ;; process with the help of `org-export-define-backend', which
2265 ;; internally stores filters as an alist. Each association has a key
2266 ;; among the following symbols and a function or a list of functions
2267 ;; as value.
2269 ;; - `:filter-options' applies to the property list containing export
2270 ;; options. Unlike to other filters, functions in this list accept
2271 ;; two arguments instead of three: the property list containing
2272 ;; export options and the back-end. Users can set its value through
2273 ;; `org-export-filter-options-functions' variable.
2275 ;; - `:filter-parse-tree' applies directly to the complete parsed
2276 ;; tree. Users can set it through
2277 ;; `org-export-filter-parse-tree-functions' variable.
2279 ;; - `:filter-final-output' applies to the final transcoded string.
2280 ;; Users can set it with `org-export-filter-final-output-functions'
2281 ;; variable
2283 ;; - `:filter-plain-text' applies to any string not recognized as Org
2284 ;; syntax. `org-export-filter-plain-text-functions' allows users to
2285 ;; configure it.
2287 ;; - `:filter-TYPE' applies on the string returned after an element or
2288 ;; object of type TYPE has been transcoded. A user can modify
2289 ;; `org-export-filter-TYPE-functions'
2291 ;; All filters sets are applied with
2292 ;; `org-export-filter-apply-functions' function. Filters in a set are
2293 ;; applied in a LIFO fashion. It allows developers to be sure that
2294 ;; their filters will be applied first.
2296 ;; Filters properties are installed in communication channel with
2297 ;; `org-export-install-filters' function.
2299 ;; Eventually, two hooks (`org-export-before-processing-hook' and
2300 ;; `org-export-before-parsing-hook') are run at the beginning of the
2301 ;; export process and just before parsing to allow for heavy structure
2302 ;; modifications.
2305 ;;;; Hooks
2307 (defvar org-export-before-processing-hook nil
2308 "Hook run at the beginning of the export process.
2310 This is run before include keywords and macros are expanded and
2311 Babel code blocks executed, on a copy of the original buffer
2312 being exported. Visibility and narrowing are preserved. Point
2313 is at the beginning of the buffer.
2315 Every function in this hook will be called with one argument: the
2316 back-end currently used, as a symbol.")
2318 (defvar org-export-before-parsing-hook nil
2319 "Hook run before parsing an export buffer.
2321 This is run after include keywords and macros have been expanded
2322 and Babel code blocks executed, on a copy of the original buffer
2323 being exported. Visibility and narrowing are preserved. Point
2324 is at the beginning of the buffer.
2326 Every function in this hook will be called with one argument: the
2327 back-end currently used, as a symbol.")
2330 ;;;; Special Filters
2332 (defvar org-export-filter-options-functions nil
2333 "List of functions applied to the export options.
2334 Each filter is called with two arguments: the export options, as
2335 a plist, and the back-end, as a symbol. It must return
2336 a property list containing export options.")
2338 (defvar org-export-filter-parse-tree-functions nil
2339 "List of functions applied to the parsed tree.
2340 Each filter is called with three arguments: the parse tree, as
2341 returned by `org-element-parse-buffer', the back-end, as
2342 a symbol, and the communication channel, as a plist. It must
2343 return the modified parse tree to transcode.")
2345 (defvar org-export-filter-plain-text-functions nil
2346 "List of functions applied to plain text.
2347 Each filter is called with three arguments: a string which
2348 contains no Org syntax, the back-end, as a symbol, and the
2349 communication channel, as a plist. It must return a string or
2350 nil.")
2352 (defvar org-export-filter-final-output-functions nil
2353 "List of functions applied to the transcoded string.
2354 Each filter is called with three arguments: the full transcoded
2355 string, the back-end, as a symbol, and the communication channel,
2356 as a plist. It must return a string that will be used as the
2357 final export output.")
2360 ;;;; Elements Filters
2362 (defvar org-export-filter-babel-call-functions nil
2363 "List of functions applied to a transcoded babel-call.
2364 Each filter is called with three arguments: the transcoded data,
2365 as a string, the back-end, as a symbol, and the communication
2366 channel, as a plist. It must return a string or nil.")
2368 (defvar org-export-filter-center-block-functions nil
2369 "List of functions applied to a transcoded center block.
2370 Each filter is called with three arguments: the transcoded data,
2371 as a string, the back-end, as a symbol, and the communication
2372 channel, as a plist. It must return a string or nil.")
2374 (defvar org-export-filter-clock-functions nil
2375 "List of functions applied to a transcoded clock.
2376 Each filter is called with three arguments: the transcoded data,
2377 as a string, the back-end, as a symbol, and the communication
2378 channel, as a plist. It must return a string or nil.")
2380 (defvar org-export-filter-comment-functions nil
2381 "List of functions applied to a transcoded comment.
2382 Each filter is called with three arguments: the transcoded data,
2383 as a string, the back-end, as a symbol, and the communication
2384 channel, as a plist. It must return a string or nil.")
2386 (defvar org-export-filter-comment-block-functions nil
2387 "List of functions applied to a transcoded comment-block.
2388 Each filter is called with three arguments: the transcoded data,
2389 as a string, the back-end, as a symbol, and the communication
2390 channel, as a plist. It must return a string or nil.")
2392 (defvar org-export-filter-diary-sexp-functions nil
2393 "List of functions applied to a transcoded diary-sexp.
2394 Each filter is called with three arguments: the transcoded data,
2395 as a string, the back-end, as a symbol, and the communication
2396 channel, as a plist. It must return a string or nil.")
2398 (defvar org-export-filter-drawer-functions nil
2399 "List of functions applied to a transcoded drawer.
2400 Each filter is called with three arguments: the transcoded data,
2401 as a string, the back-end, as a symbol, and the communication
2402 channel, as a plist. It must return a string or nil.")
2404 (defvar org-export-filter-dynamic-block-functions nil
2405 "List of functions applied to a transcoded dynamic-block.
2406 Each filter is called with three arguments: the transcoded data,
2407 as a string, the back-end, as a symbol, and the communication
2408 channel, as a plist. It must return a string or nil.")
2410 (defvar org-export-filter-example-block-functions nil
2411 "List of functions applied to a transcoded example-block.
2412 Each filter is called with three arguments: the transcoded data,
2413 as a string, the back-end, as a symbol, and the communication
2414 channel, as a plist. It must return a string or nil.")
2416 (defvar org-export-filter-export-block-functions nil
2417 "List of functions applied to a transcoded export-block.
2418 Each filter is called with three arguments: the transcoded data,
2419 as a string, the back-end, as a symbol, and the communication
2420 channel, as a plist. It must return a string or nil.")
2422 (defvar org-export-filter-fixed-width-functions nil
2423 "List of functions applied to a transcoded fixed-width.
2424 Each filter is called with three arguments: the transcoded data,
2425 as a string, the back-end, as a symbol, and the communication
2426 channel, as a plist. It must return a string or nil.")
2428 (defvar org-export-filter-footnote-definition-functions nil
2429 "List of functions applied to a transcoded footnote-definition.
2430 Each filter is called with three arguments: the transcoded data,
2431 as a string, the back-end, as a symbol, and the communication
2432 channel, as a plist. It must return a string or nil.")
2434 (defvar org-export-filter-headline-functions nil
2435 "List of functions applied to a transcoded headline.
2436 Each filter is called with three arguments: the transcoded data,
2437 as a string, the back-end, as a symbol, and the communication
2438 channel, as a plist. It must return a string or nil.")
2440 (defvar org-export-filter-horizontal-rule-functions nil
2441 "List of functions applied to a transcoded horizontal-rule.
2442 Each filter is called with three arguments: the transcoded data,
2443 as a string, the back-end, as a symbol, and the communication
2444 channel, as a plist. It must return a string or nil.")
2446 (defvar org-export-filter-inlinetask-functions nil
2447 "List of functions applied to a transcoded inlinetask.
2448 Each filter is called with three arguments: the transcoded data,
2449 as a string, the back-end, as a symbol, and the communication
2450 channel, as a plist. It must return a string or nil.")
2452 (defvar org-export-filter-item-functions nil
2453 "List of functions applied to a transcoded item.
2454 Each filter is called with three arguments: the transcoded data,
2455 as a string, the back-end, as a symbol, and the communication
2456 channel, as a plist. It must return a string or nil.")
2458 (defvar org-export-filter-keyword-functions nil
2459 "List of functions applied to a transcoded keyword.
2460 Each filter is called with three arguments: the transcoded data,
2461 as a string, the back-end, as a symbol, and the communication
2462 channel, as a plist. It must return a string or nil.")
2464 (defvar org-export-filter-latex-environment-functions nil
2465 "List of functions applied to a transcoded latex-environment.
2466 Each filter is called with three arguments: the transcoded data,
2467 as a string, the back-end, as a symbol, and the communication
2468 channel, as a plist. It must return a string or nil.")
2470 (defvar org-export-filter-node-property-functions nil
2471 "List of functions applied to a transcoded node-property.
2472 Each filter is called with three arguments: the transcoded data,
2473 as a string, the back-end, as a symbol, and the communication
2474 channel, as a plist. It must return a string or nil.")
2476 (defvar org-export-filter-paragraph-functions nil
2477 "List of functions applied to a transcoded paragraph.
2478 Each filter is called with three arguments: the transcoded data,
2479 as a string, the back-end, as a symbol, and the communication
2480 channel, as a plist. It must return a string or nil.")
2482 (defvar org-export-filter-plain-list-functions nil
2483 "List of functions applied to a transcoded plain-list.
2484 Each filter is called with three arguments: the transcoded data,
2485 as a string, the back-end, as a symbol, and the communication
2486 channel, as a plist. It must return a string or nil.")
2488 (defvar org-export-filter-planning-functions nil
2489 "List of functions applied to a transcoded planning.
2490 Each filter is called with three arguments: the transcoded data,
2491 as a string, the back-end, as a symbol, and the communication
2492 channel, as a plist. It must return a string or nil.")
2494 (defvar org-export-filter-property-drawer-functions nil
2495 "List of functions applied to a transcoded property-drawer.
2496 Each filter is called with three arguments: the transcoded data,
2497 as a string, the back-end, as a symbol, and the communication
2498 channel, as a plist. It must return a string or nil.")
2500 (defvar org-export-filter-quote-block-functions nil
2501 "List of functions applied to a transcoded quote block.
2502 Each filter is called with three arguments: the transcoded quote
2503 data, as a string, the back-end, as a symbol, and the
2504 communication channel, as a plist. It must return a string or
2505 nil.")
2507 (defvar org-export-filter-quote-section-functions nil
2508 "List of functions applied to a transcoded quote-section.
2509 Each filter is called with three arguments: the transcoded data,
2510 as a string, the back-end, as a symbol, and the communication
2511 channel, as a plist. It must return a string or nil.")
2513 (defvar org-export-filter-section-functions nil
2514 "List of functions applied to a transcoded section.
2515 Each filter is called with three arguments: the transcoded data,
2516 as a string, the back-end, as a symbol, and the communication
2517 channel, as a plist. It must return a string or nil.")
2519 (defvar org-export-filter-special-block-functions nil
2520 "List of functions applied to a transcoded special block.
2521 Each filter is called with three arguments: the transcoded data,
2522 as a string, the back-end, as a symbol, and the communication
2523 channel, as a plist. It must return a string or nil.")
2525 (defvar org-export-filter-src-block-functions nil
2526 "List of functions applied to a transcoded src-block.
2527 Each filter is called with three arguments: the transcoded data,
2528 as a string, the back-end, as a symbol, and the communication
2529 channel, as a plist. It must return a string or nil.")
2531 (defvar org-export-filter-table-functions nil
2532 "List of functions applied to a transcoded table.
2533 Each filter is called with three arguments: the transcoded data,
2534 as a string, the back-end, as a symbol, and the communication
2535 channel, as a plist. It must return a string or nil.")
2537 (defvar org-export-filter-table-cell-functions nil
2538 "List of functions applied to a transcoded table-cell.
2539 Each filter is called with three arguments: the transcoded data,
2540 as a string, the back-end, as a symbol, and the communication
2541 channel, as a plist. It must return a string or nil.")
2543 (defvar org-export-filter-table-row-functions nil
2544 "List of functions applied to a transcoded table-row.
2545 Each filter is called with three arguments: the transcoded data,
2546 as a string, the back-end, as a symbol, and the communication
2547 channel, as a plist. It must return a string or nil.")
2549 (defvar org-export-filter-verse-block-functions nil
2550 "List of functions applied to a transcoded verse block.
2551 Each filter is called with three arguments: the transcoded data,
2552 as a string, the back-end, as a symbol, and the communication
2553 channel, as a plist. It must return a string or nil.")
2556 ;;;; Objects Filters
2558 (defvar org-export-filter-bold-functions nil
2559 "List of functions applied to transcoded bold text.
2560 Each filter is called with three arguments: the transcoded data,
2561 as a string, the back-end, as a symbol, and the communication
2562 channel, as a plist. It must return a string or nil.")
2564 (defvar org-export-filter-code-functions nil
2565 "List of functions applied to transcoded code text.
2566 Each filter is called with three arguments: the transcoded data,
2567 as a string, the back-end, as a symbol, and the communication
2568 channel, as a plist. It must return a string or nil.")
2570 (defvar org-export-filter-entity-functions nil
2571 "List of functions applied to a transcoded entity.
2572 Each filter is called with three arguments: the transcoded data,
2573 as a string, the back-end, as a symbol, and the communication
2574 channel, as a plist. It must return a string or nil.")
2576 (defvar org-export-filter-export-snippet-functions nil
2577 "List of functions applied to a transcoded export-snippet.
2578 Each filter is called with three arguments: the transcoded data,
2579 as a string, the back-end, as a symbol, and the communication
2580 channel, as a plist. It must return a string or nil.")
2582 (defvar org-export-filter-footnote-reference-functions nil
2583 "List of functions applied to a transcoded footnote-reference.
2584 Each filter is called with three arguments: the transcoded data,
2585 as a string, the back-end, as a symbol, and the communication
2586 channel, as a plist. It must return a string or nil.")
2588 (defvar org-export-filter-inline-babel-call-functions nil
2589 "List of functions applied to a transcoded inline-babel-call.
2590 Each filter is called with three arguments: the transcoded data,
2591 as a string, the back-end, as a symbol, and the communication
2592 channel, as a plist. It must return a string or nil.")
2594 (defvar org-export-filter-inline-src-block-functions nil
2595 "List of functions applied to a transcoded inline-src-block.
2596 Each filter is called with three arguments: the transcoded data,
2597 as a string, the back-end, as a symbol, and the communication
2598 channel, as a plist. It must return a string or nil.")
2600 (defvar org-export-filter-italic-functions nil
2601 "List of functions applied to transcoded italic text.
2602 Each filter is called with three arguments: the transcoded data,
2603 as a string, the back-end, as a symbol, and the communication
2604 channel, as a plist. It must return a string or nil.")
2606 (defvar org-export-filter-latex-fragment-functions nil
2607 "List of functions applied to a transcoded latex-fragment.
2608 Each filter is called with three arguments: the transcoded data,
2609 as a string, the back-end, as a symbol, and the communication
2610 channel, as a plist. It must return a string or nil.")
2612 (defvar org-export-filter-line-break-functions nil
2613 "List of functions applied to a transcoded line-break.
2614 Each filter is called with three arguments: the transcoded data,
2615 as a string, the back-end, as a symbol, and the communication
2616 channel, as a plist. It must return a string or nil.")
2618 (defvar org-export-filter-link-functions nil
2619 "List of functions applied to a transcoded link.
2620 Each filter is called with three arguments: the transcoded data,
2621 as a string, the back-end, as a symbol, and the communication
2622 channel, as a plist. It must return a string or nil.")
2624 (defvar org-export-filter-macro-functions nil
2625 "List of functions applied to a transcoded macro.
2626 Each filter is called with three arguments: the transcoded data,
2627 as a string, the back-end, as a symbol, and the communication
2628 channel, as a plist. It must return a string or nil.")
2630 (defvar org-export-filter-radio-target-functions nil
2631 "List of functions applied to a transcoded radio-target.
2632 Each filter is called with three arguments: the transcoded data,
2633 as a string, the back-end, as a symbol, and the communication
2634 channel, as a plist. It must return a string or nil.")
2636 (defvar org-export-filter-statistics-cookie-functions nil
2637 "List of functions applied to a transcoded statistics-cookie.
2638 Each filter is called with three arguments: the transcoded data,
2639 as a string, the back-end, as a symbol, and the communication
2640 channel, as a plist. It must return a string or nil.")
2642 (defvar org-export-filter-strike-through-functions nil
2643 "List of functions applied to transcoded strike-through text.
2644 Each filter is called with three arguments: the transcoded data,
2645 as a string, the back-end, as a symbol, and the communication
2646 channel, as a plist. It must return a string or nil.")
2648 (defvar org-export-filter-subscript-functions nil
2649 "List of functions applied to a transcoded subscript.
2650 Each filter is called with three arguments: the transcoded data,
2651 as a string, the back-end, as a symbol, and the communication
2652 channel, as a plist. It must return a string or nil.")
2654 (defvar org-export-filter-superscript-functions nil
2655 "List of functions applied to a transcoded superscript.
2656 Each filter is called with three arguments: the transcoded data,
2657 as a string, the back-end, as a symbol, and the communication
2658 channel, as a plist. It must return a string or nil.")
2660 (defvar org-export-filter-target-functions nil
2661 "List of functions applied to a transcoded target.
2662 Each filter is called with three arguments: the transcoded data,
2663 as a string, the back-end, as a symbol, and the communication
2664 channel, as a plist. It must return a string or nil.")
2666 (defvar org-export-filter-timestamp-functions nil
2667 "List of functions applied to a transcoded timestamp.
2668 Each filter is called with three arguments: the transcoded data,
2669 as a string, the back-end, as a symbol, and the communication
2670 channel, as a plist. It must return a string or nil.")
2672 (defvar org-export-filter-underline-functions nil
2673 "List of functions applied to transcoded underline text.
2674 Each filter is called with three arguments: the transcoded data,
2675 as a string, the back-end, as a symbol, and the communication
2676 channel, as a plist. It must return a string or nil.")
2678 (defvar org-export-filter-verbatim-functions nil
2679 "List of functions applied to transcoded verbatim text.
2680 Each filter is called with three arguments: the transcoded data,
2681 as a string, the back-end, as a symbol, and the communication
2682 channel, as a plist. It must return a string or nil.")
2685 ;;;; Filters Tools
2687 ;; Internal function `org-export-install-filters' installs filters
2688 ;; hard-coded in back-ends (developer filters) and filters from global
2689 ;; variables (user filters) in the communication channel.
2691 ;; Internal function `org-export-filter-apply-functions' takes care
2692 ;; about applying each filter in order to a given data. It ignores
2693 ;; filters returning a nil value but stops whenever a filter returns
2694 ;; an empty string.
2696 (defun org-export-filter-apply-functions (filters value info)
2697 "Call every function in FILTERS.
2699 Functions are called with arguments VALUE, current export
2700 back-end and INFO. A function returning a nil value will be
2701 skipped. If it returns the empty string, the process ends and
2702 VALUE is ignored.
2704 Call is done in a LIFO fashion, to be sure that developer
2705 specified filters, if any, are called first."
2706 (catch 'exit
2707 (dolist (filter filters value)
2708 (let ((result (funcall filter value (plist-get info :back-end) info)))
2709 (cond ((not result) value)
2710 ((equal value "") (throw 'exit nil))
2711 (t (setq value result)))))))
2713 (defun org-export-install-filters (info)
2714 "Install filters properties in communication channel.
2715 INFO is a plist containing the current communication channel.
2716 Return the updated communication channel."
2717 (let (plist)
2718 ;; Install user-defined filters with `org-export-filters-alist'
2719 ;; and filters already in INFO (through ext-plist mechanism).
2720 (mapc (lambda (p)
2721 (let* ((prop (car p))
2722 (info-value (plist-get info prop))
2723 (default-value (symbol-value (cdr p))))
2724 (setq plist
2725 (plist-put plist prop
2726 ;; Filters in INFO will be called
2727 ;; before those user provided.
2728 (append (if (listp info-value) info-value
2729 (list info-value))
2730 default-value)))))
2731 org-export-filters-alist)
2732 ;; Prepend back-end specific filters to that list.
2733 (mapc (lambda (p)
2734 ;; Single values get consed, lists are appended.
2735 (let ((key (car p)) (value (cdr p)))
2736 (when value
2737 (setq plist
2738 (plist-put
2739 plist key
2740 (if (atom value) (cons value (plist-get plist key))
2741 (append value (plist-get plist key))))))))
2742 (org-export-backend-filters (plist-get info :back-end)))
2743 ;; Return new communication channel.
2744 (org-combine-plists info plist)))
2748 ;;; Core functions
2750 ;; This is the room for the main function, `org-export-as', along with
2751 ;; its derivatives, `org-export-to-buffer', `org-export-to-file' and
2752 ;; `org-export-string-as'. They differ either by the way they output
2753 ;; the resulting code (for the first two) or by the input type (for
2754 ;; the latter). `org-export--copy-to-kill-ring-p' determines if
2755 ;; output of these function should be added to kill ring.
2757 ;; `org-export-output-file-name' is an auxiliary function meant to be
2758 ;; used with `org-export-to-file'. With a given extension, it tries
2759 ;; to provide a canonical file name to write export output to.
2761 ;; Note that `org-export-as' doesn't really parse the current buffer,
2762 ;; but a copy of it (with the same buffer-local variables and
2763 ;; visibility), where macros and include keywords are expanded and
2764 ;; Babel blocks are executed, if appropriate.
2765 ;; `org-export-with-buffer-copy' macro prepares that copy.
2767 ;; File inclusion is taken care of by
2768 ;; `org-export-expand-include-keyword' and
2769 ;; `org-export--prepare-file-contents'. Structure wise, including
2770 ;; a whole Org file in a buffer often makes little sense. For
2771 ;; example, if the file contains a headline and the include keyword
2772 ;; was within an item, the item should contain the headline. That's
2773 ;; why file inclusion should be done before any structure can be
2774 ;; associated to the file, that is before parsing.
2776 ;; `org-export-insert-default-template' is a command to insert
2777 ;; a default template (or a back-end specific template) at point or in
2778 ;; current subtree.
2780 (defun org-export-copy-buffer ()
2781 "Return a copy of the current buffer.
2782 The copy preserves Org buffer-local variables, visibility and
2783 narrowing."
2784 (let ((copy-buffer-fun (org-export--generate-copy-script (current-buffer)))
2785 (new-buf (generate-new-buffer (buffer-name))))
2786 (with-current-buffer new-buf
2787 (funcall copy-buffer-fun)
2788 (set-buffer-modified-p nil))
2789 new-buf))
2791 (defmacro org-export-with-buffer-copy (&rest body)
2792 "Apply BODY in a copy of the current buffer.
2793 The copy preserves local variables, visibility and contents of
2794 the original buffer. Point is at the beginning of the buffer
2795 when BODY is applied."
2796 (declare (debug t))
2797 (org-with-gensyms (buf-copy)
2798 `(let ((,buf-copy (org-export-copy-buffer)))
2799 (unwind-protect
2800 (with-current-buffer ,buf-copy
2801 (goto-char (point-min))
2802 (progn ,@body))
2803 (and (buffer-live-p ,buf-copy)
2804 ;; Kill copy without confirmation.
2805 (progn (with-current-buffer ,buf-copy
2806 (restore-buffer-modified-p nil))
2807 (kill-buffer ,buf-copy)))))))
2809 (defun org-export--generate-copy-script (buffer)
2810 "Generate a function duplicating BUFFER.
2812 The copy will preserve local variables, visibility, contents and
2813 narrowing of the original buffer. If a region was active in
2814 BUFFER, contents will be narrowed to that region instead.
2816 The resulting function can be evaled at a later time, from
2817 another buffer, effectively cloning the original buffer there.
2819 The function assumes BUFFER's major mode is `org-mode'."
2820 (with-current-buffer buffer
2821 `(lambda ()
2822 (let ((inhibit-modification-hooks t))
2823 ;; Set major mode. Ignore `org-mode-hook' as it has been run
2824 ;; already in BUFFER.
2825 (let ((org-mode-hook nil) (org-inhibit-startup t)) (org-mode))
2826 ;; Copy specific buffer local variables and variables set
2827 ;; through BIND keywords.
2828 ,@(let ((bound-variables (org-export--list-bound-variables))
2829 vars)
2830 (dolist (entry (buffer-local-variables (buffer-base-buffer)) vars)
2831 (when (consp entry)
2832 (let ((var (car entry))
2833 (val (cdr entry)))
2834 (and (not (eq var 'org-font-lock-keywords))
2835 (or (memq var
2836 '(default-directory
2837 buffer-file-name
2838 buffer-file-coding-system))
2839 (assq var bound-variables)
2840 (string-match "^\\(org-\\|orgtbl-\\)"
2841 (symbol-name var)))
2842 ;; Skip unreadable values, as they cannot be
2843 ;; sent to external process.
2844 (or (not val) (ignore-errors (read (format "%S" val))))
2845 (push `(set (make-local-variable (quote ,var))
2846 (quote ,val))
2847 vars))))))
2848 ;; Whole buffer contents.
2849 (insert
2850 ,(org-with-wide-buffer
2851 (buffer-substring-no-properties
2852 (point-min) (point-max))))
2853 ;; Narrowing.
2854 ,(if (org-region-active-p)
2855 `(narrow-to-region ,(region-beginning) ,(region-end))
2856 `(narrow-to-region ,(point-min) ,(point-max)))
2857 ;; Current position of point.
2858 (goto-char ,(point))
2859 ;; Overlays with invisible property.
2860 ,@(let (ov-set)
2861 (mapc
2862 (lambda (ov)
2863 (let ((invis-prop (overlay-get ov 'invisible)))
2864 (when invis-prop
2865 (push `(overlay-put
2866 (make-overlay ,(overlay-start ov)
2867 ,(overlay-end ov))
2868 'invisible (quote ,invis-prop))
2869 ov-set))))
2870 (overlays-in (point-min) (point-max)))
2871 ov-set)))))
2873 ;;;###autoload
2874 (defun org-export-as
2875 (backend &optional subtreep visible-only body-only ext-plist)
2876 "Transcode current Org buffer into BACKEND code.
2878 If narrowing is active in the current buffer, only transcode its
2879 narrowed part.
2881 If a region is active, transcode that region.
2883 When optional argument SUBTREEP is non-nil, transcode the
2884 sub-tree at point, extracting information from the headline
2885 properties first.
2887 When optional argument VISIBLE-ONLY is non-nil, don't export
2888 contents of hidden elements.
2890 When optional argument BODY-ONLY is non-nil, only return body
2891 code, without surrounding template.
2893 Optional argument EXT-PLIST, when provided, is a property list
2894 with external parameters overriding Org default settings, but
2895 still inferior to file-local settings.
2897 Return code as a string."
2898 (org-export-barf-if-invalid-backend backend)
2899 (save-excursion
2900 (save-restriction
2901 ;; Narrow buffer to an appropriate region or subtree for
2902 ;; parsing. If parsing subtree, be sure to remove main headline
2903 ;; too.
2904 (cond ((org-region-active-p)
2905 (narrow-to-region (region-beginning) (region-end)))
2906 (subtreep
2907 (org-narrow-to-subtree)
2908 (goto-char (point-min))
2909 (forward-line)
2910 (narrow-to-region (point) (point-max))))
2911 ;; Initialize communication channel with original buffer
2912 ;; attributes, unavailable in its copy.
2913 (let ((info (org-combine-plists
2914 (list :export-options
2915 (delq nil
2916 (list (and subtreep 'subtree)
2917 (and visible-only 'visible-only)
2918 (and body-only 'body-only))))
2919 (org-export--get-buffer-attributes)))
2920 tree)
2921 ;; Update communication channel and get parse tree. Buffer
2922 ;; isn't parsed directly. Instead, a temporary copy is
2923 ;; created, where include keywords, macros are expanded and
2924 ;; code blocks are evaluated.
2925 (org-export-with-buffer-copy
2926 ;; Run first hook with current back-end as argument.
2927 (run-hook-with-args 'org-export-before-processing-hook backend)
2928 (org-export-expand-include-keyword)
2929 ;; Update macro templates since #+INCLUDE keywords might have
2930 ;; added some new ones.
2931 (org-macro-initialize-templates)
2932 (org-macro-replace-all org-macro-templates)
2933 (org-export-execute-babel-code)
2934 ;; Update radio targets since keyword inclusion might have
2935 ;; added some more.
2936 (org-update-radio-target-regexp)
2937 ;; Run last hook with current back-end as argument.
2938 (goto-char (point-min))
2939 (save-excursion
2940 (run-hook-with-args 'org-export-before-parsing-hook backend))
2941 ;; Update communication channel with environment. Also
2942 ;; install user's and developer's filters.
2943 (setq info
2944 (org-export-install-filters
2945 (org-combine-plists
2946 info (org-export-get-environment backend subtreep ext-plist))))
2947 ;; Expand export-specific set of macros: {{{author}}},
2948 ;; {{{date}}}, {{{email}}} and {{{title}}}. It must be done
2949 ;; once regular macros have been expanded, since document
2950 ;; keywords may contain one of them.
2951 (org-macro-replace-all
2952 (list (cons "author"
2953 (org-element-interpret-data (plist-get info :author)))
2954 (cons "date"
2955 (org-element-interpret-data (plist-get info :date)))
2956 ;; EMAIL is not a parsed keyword: store it as-is.
2957 (cons "email" (or (plist-get info :email) ""))
2958 (cons "title"
2959 (org-element-interpret-data (plist-get info :title)))))
2960 ;; Call options filters and update export options. We do not
2961 ;; use `org-export-filter-apply-functions' here since the
2962 ;; arity of such filters is different.
2963 (dolist (filter (plist-get info :filter-options))
2964 (let ((result (funcall filter info backend)))
2965 (when result (setq info result))))
2966 ;; Parse buffer and call parse-tree filter on it.
2967 (setq tree
2968 (org-export-filter-apply-functions
2969 (plist-get info :filter-parse-tree)
2970 (org-element-parse-buffer nil visible-only) info))
2971 ;; Now tree is complete, compute its properties and add them
2972 ;; to communication channel.
2973 (setq info
2974 (org-combine-plists
2975 info (org-export-collect-tree-properties tree info)))
2976 ;; Eventually transcode TREE. Wrap the resulting string into
2977 ;; a template.
2978 (let* ((body (org-element-normalize-string
2979 (or (org-export-data tree info) "")))
2980 (inner-template (cdr (assq 'inner-template
2981 (plist-get info :translate-alist))))
2982 (full-body (if (not (functionp inner-template)) body
2983 (funcall inner-template body info)))
2984 (template (cdr (assq 'template
2985 (plist-get info :translate-alist)))))
2986 ;; Remove all text properties since they cannot be
2987 ;; retrieved from an external process. Finally call
2988 ;; final-output filter and return result.
2989 (org-no-properties
2990 (org-export-filter-apply-functions
2991 (plist-get info :filter-final-output)
2992 (if (or (not (functionp template)) body-only) full-body
2993 (funcall template full-body info))
2994 info))))))))
2996 ;;;###autoload
2997 (defun org-export-to-buffer
2998 (backend buffer &optional subtreep visible-only body-only ext-plist)
2999 "Call `org-export-as' with output to a specified buffer.
3001 BACKEND is the back-end used for transcoding, as a symbol.
3003 BUFFER is the output buffer. If it already exists, it will be
3004 erased first, otherwise, it will be created.
3006 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
3007 EXT-PLIST are similar to those used in `org-export-as', which
3008 see.
3010 Depending on `org-export-copy-to-kill-ring', add buffer contents
3011 to kill ring. Return buffer."
3012 (let ((out (org-export-as backend subtreep visible-only body-only ext-plist))
3013 (buffer (get-buffer-create buffer)))
3014 (with-current-buffer buffer
3015 (erase-buffer)
3016 (insert out)
3017 (goto-char (point-min)))
3018 ;; Maybe add buffer contents to kill ring.
3019 (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p out))
3020 (org-kill-new out))
3021 ;; Return buffer.
3022 buffer))
3024 ;;;###autoload
3025 (defun org-export-to-file
3026 (backend file &optional subtreep visible-only body-only ext-plist)
3027 "Call `org-export-as' with output to a specified file.
3029 BACKEND is the back-end used for transcoding, as a symbol. FILE
3030 is the name of the output file, as a string.
3032 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
3033 EXT-PLIST are similar to those used in `org-export-as', which
3034 see.
3036 Depending on `org-export-copy-to-kill-ring', add file contents
3037 to kill ring. Return output file's name."
3038 ;; Checks for FILE permissions. `write-file' would do the same, but
3039 ;; we'd rather avoid needless transcoding of parse tree.
3040 (unless (file-writable-p file) (error "Output file not writable"))
3041 ;; Insert contents to a temporary buffer and write it to FILE.
3042 (let ((out (org-export-as backend subtreep visible-only body-only ext-plist)))
3043 (with-temp-buffer
3044 (insert out)
3045 (let ((coding-system-for-write org-export-coding-system))
3046 (write-file file)))
3047 ;; Maybe add file contents to kill ring.
3048 (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p out))
3049 (org-kill-new out)))
3050 ;; Return full path.
3051 file)
3053 ;;;###autoload
3054 (defun org-export-string-as (string backend &optional body-only ext-plist)
3055 "Transcode STRING into BACKEND code.
3057 When optional argument BODY-ONLY is non-nil, only return body
3058 code, without preamble nor postamble.
3060 Optional argument EXT-PLIST, when provided, is a property list
3061 with external parameters overriding Org default settings, but
3062 still inferior to file-local settings.
3064 Return code as a string."
3065 (with-temp-buffer
3066 (insert string)
3067 (let ((org-inhibit-startup t)) (org-mode))
3068 (org-export-as backend nil nil body-only ext-plist)))
3070 ;;;###autoload
3071 (defun org-export-replace-region-by (backend)
3072 "Replace the active region by its export to BACKEND."
3073 (if (not (org-region-active-p))
3074 (user-error "No active region to replace")
3075 (let* ((beg (region-beginning))
3076 (end (region-end))
3077 (str (buffer-substring beg end)) rpl)
3078 (setq rpl (org-export-string-as str backend t))
3079 (delete-region beg end)
3080 (insert rpl))))
3082 ;;;###autoload
3083 (defun org-export-insert-default-template (&optional backend subtreep)
3084 "Insert all export keywords with default values at beginning of line.
3086 BACKEND is a symbol representing the export back-end for which
3087 specific export options should be added to the template, or
3088 `default' for default template. When it is nil, the user will be
3089 prompted for a category.
3091 If SUBTREEP is non-nil, export configuration will be set up
3092 locally for the subtree through node properties."
3093 (interactive)
3094 (unless (derived-mode-p 'org-mode) (user-error "Not in an Org mode buffer"))
3095 (when (and subtreep (org-before-first-heading-p))
3096 (user-error "No subtree to set export options for"))
3097 (let ((node (and subtreep (save-excursion (org-back-to-heading t) (point))))
3098 (backend (or backend
3099 (intern
3100 (org-completing-read
3101 "Options category: "
3102 (cons "default"
3103 (mapcar (lambda (b) (symbol-name (car b)))
3104 org-export-registered-backends))))))
3105 options keywords)
3106 ;; Populate OPTIONS and KEYWORDS.
3107 (dolist (entry (if (eq backend 'default) org-export-options-alist
3108 (org-export-backend-options backend)))
3109 (let ((keyword (nth 1 entry))
3110 (option (nth 2 entry)))
3111 (cond
3112 (keyword (unless (assoc keyword keywords)
3113 (let ((value
3114 (if (eq (nth 4 entry) 'split)
3115 (mapconcat 'identity (eval (nth 3 entry)) " ")
3116 (eval (nth 3 entry)))))
3117 (push (cons keyword value) keywords))))
3118 (option (unless (assoc option options)
3119 (push (cons option (eval (nth 3 entry))) options))))))
3120 ;; Move to an appropriate location in order to insert options.
3121 (unless subtreep (beginning-of-line))
3122 ;; First get TITLE, DATE, AUTHOR and EMAIL if they belong to the
3123 ;; list of available keywords.
3124 (when (assoc "TITLE" keywords)
3125 (let ((title
3126 (or (let ((visited-file (buffer-file-name (buffer-base-buffer))))
3127 (and visited-file
3128 (file-name-sans-extension
3129 (file-name-nondirectory visited-file))))
3130 (buffer-name (buffer-base-buffer)))))
3131 (if (not subtreep) (insert (format "#+TITLE: %s\n" title))
3132 (org-entry-put node "EXPORT_TITLE" title))))
3133 (when (assoc "DATE" keywords)
3134 (let ((date (with-temp-buffer (org-insert-time-stamp (current-time)))))
3135 (if (not subtreep) (insert "#+DATE: " date "\n")
3136 (org-entry-put node "EXPORT_DATE" date))))
3137 (when (assoc "AUTHOR" keywords)
3138 (let ((author (cdr (assoc "AUTHOR" keywords))))
3139 (if subtreep (org-entry-put node "EXPORT_AUTHOR" author)
3140 (insert
3141 (format "#+AUTHOR:%s\n"
3142 (if (not (org-string-nw-p author)) ""
3143 (concat " " author)))))))
3144 (when (assoc "EMAIL" keywords)
3145 (let ((email (cdr (assoc "EMAIL" keywords))))
3146 (if subtreep (org-entry-put node "EXPORT_EMAIL" email)
3147 (insert
3148 (format "#+EMAIL:%s\n"
3149 (if (not (org-string-nw-p email)) ""
3150 (concat " " email)))))))
3151 ;; Then (multiple) OPTIONS lines. Never go past fill-column.
3152 (when options
3153 (let ((items
3154 (mapcar
3155 (lambda (opt)
3156 (format "%s:%s" (car opt) (format "%s" (cdr opt))))
3157 (sort options (lambda (k1 k2) (string< (car k1) (car k2)))))))
3158 (if subtreep
3159 (org-entry-put
3160 node "EXPORT_OPTIONS" (mapconcat 'identity items " "))
3161 (while items
3162 (insert "#+OPTIONS:")
3163 (let ((width 10))
3164 (while (and items
3165 (< (+ width (length (car items)) 1) fill-column))
3166 (let ((item (pop items)))
3167 (insert " " item)
3168 (incf width (1+ (length item))))))
3169 (insert "\n")))))
3170 ;; And the rest of keywords.
3171 (dolist (key (sort keywords (lambda (k1 k2) (string< (car k1) (car k2)))))
3172 (unless (member (car key) '("TITLE" "DATE" "AUTHOR" "EMAIL"))
3173 (let ((val (cdr key)))
3174 (if subtreep (org-entry-put node (concat "EXPORT_" (car key)) val)
3175 (insert
3176 (format "#+%s:%s\n"
3177 (car key)
3178 (if (org-string-nw-p val) (format " %s" val) "")))))))))
3180 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
3181 "Return output file's name according to buffer specifications.
3183 EXTENSION is a string representing the output file extension,
3184 with the leading dot.
3186 With a non-nil optional argument SUBTREEP, try to determine
3187 output file's name by looking for \"EXPORT_FILE_NAME\" property
3188 of subtree at point.
3190 When optional argument PUB-DIR is set, use it as the publishing
3191 directory.
3193 When optional argument VISIBLE-ONLY is non-nil, don't export
3194 contents of hidden elements.
3196 Return file name as a string."
3197 (let* ((visited-file (buffer-file-name (buffer-base-buffer)))
3198 (base-name
3199 ;; File name may come from EXPORT_FILE_NAME subtree
3200 ;; property, assuming point is at beginning of said
3201 ;; sub-tree.
3202 (file-name-sans-extension
3203 (or (and subtreep
3204 (org-entry-get
3205 (save-excursion
3206 (ignore-errors (org-back-to-heading) (point)))
3207 "EXPORT_FILE_NAME" t))
3208 ;; File name may be extracted from buffer's associated
3209 ;; file, if any.
3210 (and visited-file (file-name-nondirectory visited-file))
3211 ;; Can't determine file name on our own: Ask user.
3212 (let ((read-file-name-function
3213 (and org-completion-use-ido 'ido-read-file-name)))
3214 (read-file-name
3215 "Output file: " pub-dir nil nil nil
3216 (lambda (name)
3217 (string= (file-name-extension name t) extension)))))))
3218 (output-file
3219 ;; Build file name. Enforce EXTENSION over whatever user
3220 ;; may have come up with. PUB-DIR, if defined, always has
3221 ;; precedence over any provided path.
3222 (cond
3223 (pub-dir
3224 (concat (file-name-as-directory pub-dir)
3225 (file-name-nondirectory base-name)
3226 extension))
3227 ((file-name-absolute-p base-name) (concat base-name extension))
3228 (t (concat (file-name-as-directory ".") base-name extension)))))
3229 ;; If writing to OUTPUT-FILE would overwrite original file, append
3230 ;; EXTENSION another time to final name.
3231 (if (and visited-file (org-file-equal-p visited-file output-file))
3232 (concat output-file extension)
3233 output-file)))
3235 (defun org-export-expand-include-keyword (&optional included dir)
3236 "Expand every include keyword in buffer.
3237 Optional argument INCLUDED is a list of included file names along
3238 with their line restriction, when appropriate. It is used to
3239 avoid infinite recursion. Optional argument DIR is the current
3240 working directory. It is used to properly resolve relative
3241 paths."
3242 (let ((case-fold-search t))
3243 (goto-char (point-min))
3244 (while (re-search-forward "^[ \t]*#\\+INCLUDE: +\\(.*\\)[ \t]*$" nil t)
3245 (when (eq (org-element-type (save-match-data (org-element-at-point)))
3246 'keyword)
3247 (beginning-of-line)
3248 ;; Extract arguments from keyword's value.
3249 (let* ((value (match-string 1))
3250 (ind (org-get-indentation))
3251 (file (and (string-match "^\"\\(\\S-+\\)\"" value)
3252 (prog1 (expand-file-name (match-string 1 value) dir)
3253 (setq value (replace-match "" nil nil value)))))
3254 (lines
3255 (and (string-match
3256 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\"" value)
3257 (prog1 (match-string 1 value)
3258 (setq value (replace-match "" nil nil value)))))
3259 (env (cond ((string-match "\\<example\\>" value) 'example)
3260 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
3261 (match-string 1 value))))
3262 ;; Minimal level of included file defaults to the child
3263 ;; level of the current headline, if any, or one. It
3264 ;; only applies is the file is meant to be included as
3265 ;; an Org one.
3266 (minlevel
3267 (and (not env)
3268 (if (string-match ":minlevel +\\([0-9]+\\)" value)
3269 (prog1 (string-to-number (match-string 1 value))
3270 (setq value (replace-match "" nil nil value)))
3271 (let ((cur (org-current-level)))
3272 (if cur (1+ (org-reduced-level cur)) 1))))))
3273 ;; Remove keyword.
3274 (delete-region (point) (progn (forward-line) (point)))
3275 (cond
3276 ((not file) (error "Invalid syntax in INCLUDE keyword"))
3277 ((not (file-readable-p file)) (error "Cannot include file %s" file))
3278 ;; Check if files has already been parsed. Look after
3279 ;; inclusion lines too, as different parts of the same file
3280 ;; can be included too.
3281 ((member (list file lines) included)
3282 (error "Recursive file inclusion: %s" file))
3284 (cond
3285 ((eq env 'example)
3286 (insert
3287 (let ((ind-str (make-string ind ? ))
3288 (contents
3289 (org-escape-code-in-string
3290 (org-export--prepare-file-contents file lines))))
3291 (format "%s#+BEGIN_EXAMPLE\n%s%s#+END_EXAMPLE\n"
3292 ind-str contents ind-str))))
3293 ((stringp env)
3294 (insert
3295 (let ((ind-str (make-string ind ? ))
3296 (contents
3297 (org-escape-code-in-string
3298 (org-export--prepare-file-contents file lines))))
3299 (format "%s#+BEGIN_SRC %s\n%s%s#+END_SRC\n"
3300 ind-str env contents ind-str))))
3302 (insert
3303 (with-temp-buffer
3304 (let ((org-inhibit-startup t)) (org-mode))
3305 (insert
3306 (org-export--prepare-file-contents file lines ind minlevel))
3307 (org-export-expand-include-keyword
3308 (cons (list file lines) included)
3309 (file-name-directory file))
3310 (buffer-string))))))))))))
3312 (defun org-export--prepare-file-contents (file &optional lines ind minlevel)
3313 "Prepare the contents of FILE for inclusion and return them as a string.
3315 When optional argument LINES is a string specifying a range of
3316 lines, include only those lines.
3318 Optional argument IND, when non-nil, is an integer specifying the
3319 global indentation of returned contents. Since its purpose is to
3320 allow an included file to stay in the same environment it was
3321 created \(i.e. a list item), it doesn't apply past the first
3322 headline encountered.
3324 Optional argument MINLEVEL, when non-nil, is an integer
3325 specifying the level that any top-level headline in the included
3326 file should have."
3327 (with-temp-buffer
3328 (insert-file-contents file)
3329 (when lines
3330 (let* ((lines (split-string lines "-"))
3331 (lbeg (string-to-number (car lines)))
3332 (lend (string-to-number (cadr lines)))
3333 (beg (if (zerop lbeg) (point-min)
3334 (goto-char (point-min))
3335 (forward-line (1- lbeg))
3336 (point)))
3337 (end (if (zerop lend) (point-max)
3338 (goto-char (point-min))
3339 (forward-line (1- lend))
3340 (point))))
3341 (narrow-to-region beg end)))
3342 ;; Remove blank lines at beginning and end of contents. The logic
3343 ;; behind that removal is that blank lines around include keyword
3344 ;; override blank lines in included file.
3345 (goto-char (point-min))
3346 (org-skip-whitespace)
3347 (beginning-of-line)
3348 (delete-region (point-min) (point))
3349 (goto-char (point-max))
3350 (skip-chars-backward " \r\t\n")
3351 (forward-line)
3352 (delete-region (point) (point-max))
3353 ;; If IND is set, preserve indentation of include keyword until
3354 ;; the first headline encountered.
3355 (when ind
3356 (unless (eq major-mode 'org-mode)
3357 (let ((org-inhibit-startup t)) (org-mode)))
3358 (goto-char (point-min))
3359 (let ((ind-str (make-string ind ? )))
3360 (while (not (or (eobp) (looking-at org-outline-regexp-bol)))
3361 ;; Do not move footnote definitions out of column 0.
3362 (unless (and (looking-at org-footnote-definition-re)
3363 (eq (org-element-type (org-element-at-point))
3364 'footnote-definition))
3365 (insert ind-str))
3366 (forward-line))))
3367 ;; When MINLEVEL is specified, compute minimal level for headlines
3368 ;; in the file (CUR-MIN), and remove stars to each headline so
3369 ;; that headlines with minimal level have a level of MINLEVEL.
3370 (when minlevel
3371 (unless (eq major-mode 'org-mode)
3372 (let ((org-inhibit-startup t)) (org-mode)))
3373 (org-with-limited-levels
3374 (let ((levels (org-map-entries
3375 (lambda () (org-reduced-level (org-current-level))))))
3376 (when levels
3377 (let ((offset (- minlevel (apply 'min levels))))
3378 (unless (zerop offset)
3379 (when org-odd-levels-only (setq offset (* offset 2)))
3380 ;; Only change stars, don't bother moving whole
3381 ;; sections.
3382 (org-map-entries
3383 (lambda () (if (< offset 0) (delete-char (abs offset))
3384 (insert (make-string offset ?*)))))))))))
3385 (org-element-normalize-string (buffer-string))))
3387 (defun org-export-execute-babel-code ()
3388 "Execute every Babel code in the visible part of current buffer."
3389 ;; Get a pristine copy of current buffer so Babel references can be
3390 ;; properly resolved.
3391 (let ((reference (org-export-copy-buffer)))
3392 (unwind-protect (let ((org-current-export-file reference))
3393 (org-babel-exp-process-buffer))
3394 (kill-buffer reference))))
3396 (defun org-export--copy-to-kill-ring-p ()
3397 "Return a non-nil value when output should be added to the kill ring.
3398 See also `org-export-copy-to-kill-ring'."
3399 (if (eq org-export-copy-to-kill-ring 'if-interactive)
3400 (not (or executing-kbd-macro noninteractive))
3401 (eq org-export-copy-to-kill-ring t)))
3405 ;;; Tools For Back-Ends
3407 ;; A whole set of tools is available to help build new exporters. Any
3408 ;; function general enough to have its use across many back-ends
3409 ;; should be added here.
3411 ;;;; For Affiliated Keywords
3413 ;; `org-export-read-attribute' reads a property from a given element
3414 ;; as a plist. It can be used to normalize affiliated keywords'
3415 ;; syntax.
3417 ;; Since captions can span over multiple lines and accept dual values,
3418 ;; their internal representation is a bit tricky. Therefore,
3419 ;; `org-export-get-caption' transparently returns a given element's
3420 ;; caption as a secondary string.
3422 (defun org-export-read-attribute (attribute element &optional property)
3423 "Turn ATTRIBUTE property from ELEMENT into a plist.
3425 When optional argument PROPERTY is non-nil, return the value of
3426 that property within attributes.
3428 This function assumes attributes are defined as \":keyword
3429 value\" pairs. It is appropriate for `:attr_html' like
3430 properties.
3432 All values will become strings except the empty string and
3433 \"nil\", which will become nil. Also, values containing only
3434 double quotes will be read as-is, which means that \"\" value
3435 will become the empty string."
3436 (let* ((prepare-value
3437 (lambda (str)
3438 (cond ((member str '(nil "" "nil")) nil)
3439 ((string-match "^\"\\(\"+\\)?\"$" str)
3440 (or (match-string 1 str) ""))
3441 (t str))))
3442 (attributes
3443 (let ((value (org-element-property attribute element)))
3444 (when value
3445 (let ((s (mapconcat 'identity value " ")) result)
3446 (while (string-match
3447 "\\(?:^\\|[ \t]+\\)\\(:[-a-zA-Z0-9_]+\\)\\([ \t]+\\|$\\)"
3449 (let ((value (substring s 0 (match-beginning 0))))
3450 (push (funcall prepare-value value) result))
3451 (push (intern (match-string 1 s)) result)
3452 (setq s (substring s (match-end 0))))
3453 ;; Ignore any string before first property with `cdr'.
3454 (cdr (nreverse (cons (funcall prepare-value s) result))))))))
3455 (if property (plist-get attributes property) attributes)))
3457 (defun org-export-get-caption (element &optional shortp)
3458 "Return caption from ELEMENT as a secondary string.
3460 When optional argument SHORTP is non-nil, return short caption,
3461 as a secondary string, instead.
3463 Caption lines are separated by a white space."
3464 (let ((full-caption (org-element-property :caption element)) caption)
3465 (dolist (line full-caption (cdr caption))
3466 (let ((cap (funcall (if shortp 'cdr 'car) line)))
3467 (when cap
3468 (setq caption (nconc (list " ") (copy-sequence cap) caption)))))))
3471 ;;;; For Derived Back-ends
3473 ;; `org-export-with-backend' is a function allowing to locally use
3474 ;; another back-end to transcode some object or element. In a derived
3475 ;; back-end, it may be used as a fall-back function once all specific
3476 ;; cases have been treated.
3478 (defun org-export-with-backend (back-end data &optional contents info)
3479 "Call a transcoder from BACK-END on DATA.
3480 CONTENTS, when non-nil, is the transcoded contents of DATA
3481 element, as a string. INFO, when non-nil, is the communication
3482 channel used for export, as a plist.."
3483 (org-export-barf-if-invalid-backend back-end)
3484 (let ((type (org-element-type data)))
3485 (if (memq type '(nil org-data)) (error "No foreign transcoder available")
3486 (let ((transcoder
3487 (cdr (assq type (org-export-backend-translate-table back-end)))))
3488 (if (functionp transcoder) (funcall transcoder data contents info)
3489 (error "No foreign transcoder available"))))))
3492 ;;;; For Export Snippets
3494 ;; Every export snippet is transmitted to the back-end. Though, the
3495 ;; latter will only retain one type of export-snippet, ignoring
3496 ;; others, based on the former's target back-end. The function
3497 ;; `org-export-snippet-backend' returns that back-end for a given
3498 ;; export-snippet.
3500 (defun org-export-snippet-backend (export-snippet)
3501 "Return EXPORT-SNIPPET targeted back-end as a symbol.
3502 Translation, with `org-export-snippet-translation-alist', is
3503 applied."
3504 (let ((back-end (org-element-property :back-end export-snippet)))
3505 (intern
3506 (or (cdr (assoc back-end org-export-snippet-translation-alist))
3507 back-end))))
3510 ;;;; For Footnotes
3512 ;; `org-export-collect-footnote-definitions' is a tool to list
3513 ;; actually used footnotes definitions in the whole parse tree, or in
3514 ;; a headline, in order to add footnote listings throughout the
3515 ;; transcoded data.
3517 ;; `org-export-footnote-first-reference-p' is a predicate used by some
3518 ;; back-ends, when they need to attach the footnote definition only to
3519 ;; the first occurrence of the corresponding label.
3521 ;; `org-export-get-footnote-definition' and
3522 ;; `org-export-get-footnote-number' provide easier access to
3523 ;; additional information relative to a footnote reference.
3525 (defun org-export-collect-footnote-definitions (data info)
3526 "Return an alist between footnote numbers, labels and definitions.
3528 DATA is the parse tree from which definitions are collected.
3529 INFO is the plist used as a communication channel.
3531 Definitions are sorted by order of references. They either
3532 appear as Org data or as a secondary string for inlined
3533 footnotes. Unreferenced definitions are ignored."
3534 (let* (num-alist
3535 collect-fn ; for byte-compiler.
3536 (collect-fn
3537 (function
3538 (lambda (data)
3539 ;; Collect footnote number, label and definition in DATA.
3540 (org-element-map data 'footnote-reference
3541 (lambda (fn)
3542 (when (org-export-footnote-first-reference-p fn info)
3543 (let ((def (org-export-get-footnote-definition fn info)))
3544 (push
3545 (list (org-export-get-footnote-number fn info)
3546 (org-element-property :label fn)
3547 def)
3548 num-alist)
3549 ;; Also search in definition for nested footnotes.
3550 (when (eq (org-element-property :type fn) 'standard)
3551 (funcall collect-fn def)))))
3552 ;; Don't enter footnote definitions since it will happen
3553 ;; when their first reference is found.
3554 info nil 'footnote-definition)))))
3555 (funcall collect-fn (plist-get info :parse-tree))
3556 (reverse num-alist)))
3558 (defun org-export-footnote-first-reference-p (footnote-reference info)
3559 "Non-nil when a footnote reference is the first one for its label.
3561 FOOTNOTE-REFERENCE is the footnote reference being considered.
3562 INFO is the plist used as a communication channel."
3563 (let ((label (org-element-property :label footnote-reference)))
3564 ;; Anonymous footnotes are always a first reference.
3565 (if (not label) t
3566 ;; Otherwise, return the first footnote with the same LABEL and
3567 ;; test if it is equal to FOOTNOTE-REFERENCE.
3568 (let* (search-refs ; for byte-compiler.
3569 (search-refs
3570 (function
3571 (lambda (data)
3572 (org-element-map data 'footnote-reference
3573 (lambda (fn)
3574 (cond
3575 ((string= (org-element-property :label fn) label)
3576 (throw 'exit fn))
3577 ;; If FN isn't inlined, be sure to traverse its
3578 ;; definition before resuming search. See
3579 ;; comments in `org-export-get-footnote-number'
3580 ;; for more information.
3581 ((eq (org-element-property :type fn) 'standard)
3582 (funcall search-refs
3583 (org-export-get-footnote-definition fn info)))))
3584 ;; Don't enter footnote definitions since it will
3585 ;; happen when their first reference is found.
3586 info 'first-match 'footnote-definition)))))
3587 (eq (catch 'exit (funcall search-refs (plist-get info :parse-tree)))
3588 footnote-reference)))))
3590 (defun org-export-get-footnote-definition (footnote-reference info)
3591 "Return definition of FOOTNOTE-REFERENCE as parsed data.
3592 INFO is the plist used as a communication channel. If no such
3593 definition can be found, return the \"DEFINITION NOT FOUND\"
3594 string."
3595 (let ((label (org-element-property :label footnote-reference)))
3596 (or (org-element-property :inline-definition footnote-reference)
3597 (cdr (assoc label (plist-get info :footnote-definition-alist)))
3598 "DEFINITION NOT FOUND.")))
3600 (defun org-export-get-footnote-number (footnote info)
3601 "Return number associated to a footnote.
3603 FOOTNOTE is either a footnote reference or a footnote definition.
3604 INFO is the plist used as a communication channel."
3605 (let* ((label (org-element-property :label footnote))
3606 seen-refs
3607 search-ref ; For byte-compiler.
3608 (search-ref
3609 (function
3610 (lambda (data)
3611 ;; Search footnote references through DATA, filling
3612 ;; SEEN-REFS along the way.
3613 (org-element-map data 'footnote-reference
3614 (lambda (fn)
3615 (let ((fn-lbl (org-element-property :label fn)))
3616 (cond
3617 ;; Anonymous footnote match: return number.
3618 ((and (not fn-lbl) (eq fn footnote))
3619 (throw 'exit (1+ (length seen-refs))))
3620 ;; Labels match: return number.
3621 ((and label (string= label fn-lbl))
3622 (throw 'exit (1+ (length seen-refs))))
3623 ;; Anonymous footnote: it's always a new one.
3624 ;; Also, be sure to return nil from the `cond' so
3625 ;; `first-match' doesn't get us out of the loop.
3626 ((not fn-lbl) (push 'inline seen-refs) nil)
3627 ;; Label not seen so far: add it so SEEN-REFS.
3629 ;; Also search for subsequent references in
3630 ;; footnote definition so numbering follows
3631 ;; reading logic. Note that we don't have to care
3632 ;; about inline definitions, since
3633 ;; `org-element-map' already traverses them at the
3634 ;; right time.
3636 ;; Once again, return nil to stay in the loop.
3637 ((not (member fn-lbl seen-refs))
3638 (push fn-lbl seen-refs)
3639 (funcall search-ref
3640 (org-export-get-footnote-definition fn info))
3641 nil))))
3642 ;; Don't enter footnote definitions since it will
3643 ;; happen when their first reference is found.
3644 info 'first-match 'footnote-definition)))))
3645 (catch 'exit (funcall search-ref (plist-get info :parse-tree)))))
3648 ;;;; For Headlines
3650 ;; `org-export-get-relative-level' is a shortcut to get headline
3651 ;; level, relatively to the lower headline level in the parsed tree.
3653 ;; `org-export-get-headline-number' returns the section number of an
3654 ;; headline, while `org-export-number-to-roman' allows to convert it
3655 ;; to roman numbers.
3657 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
3658 ;; `org-export-last-sibling-p' are three useful predicates when it
3659 ;; comes to fulfill the `:headline-levels' property.
3661 ;; `org-export-get-tags', `org-export-get-category' and
3662 ;; `org-export-get-node-property' extract useful information from an
3663 ;; headline or a parent headline. They all handle inheritance.
3665 ;; `org-export-get-alt-title' tries to retrieve an alternative title,
3666 ;; as a secondary string, suitable for table of contents. It falls
3667 ;; back onto default title.
3669 (defun org-export-get-relative-level (headline info)
3670 "Return HEADLINE relative level within current parsed tree.
3671 INFO is a plist holding contextual information."
3672 (+ (org-element-property :level headline)
3673 (or (plist-get info :headline-offset) 0)))
3675 (defun org-export-low-level-p (headline info)
3676 "Non-nil when HEADLINE is considered as low level.
3678 INFO is a plist used as a communication channel.
3680 A low level headlines has a relative level greater than
3681 `:headline-levels' property value.
3683 Return value is the difference between HEADLINE relative level
3684 and the last level being considered as high enough, or nil."
3685 (let ((limit (plist-get info :headline-levels)))
3686 (when (wholenump limit)
3687 (let ((level (org-export-get-relative-level headline info)))
3688 (and (> level limit) (- level limit))))))
3690 (defun org-export-get-headline-number (headline info)
3691 "Return HEADLINE numbering as a list of numbers.
3692 INFO is a plist holding contextual information."
3693 (cdr (assoc headline (plist-get info :headline-numbering))))
3695 (defun org-export-numbered-headline-p (headline info)
3696 "Return a non-nil value if HEADLINE element should be numbered.
3697 INFO is a plist used as a communication channel."
3698 (let ((sec-num (plist-get info :section-numbers))
3699 (level (org-export-get-relative-level headline info)))
3700 (if (wholenump sec-num) (<= level sec-num) sec-num)))
3702 (defun org-export-number-to-roman (n)
3703 "Convert integer N into a roman numeral."
3704 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
3705 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
3706 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
3707 ( 1 . "I")))
3708 (res ""))
3709 (if (<= n 0)
3710 (number-to-string n)
3711 (while roman
3712 (if (>= n (caar roman))
3713 (setq n (- n (caar roman))
3714 res (concat res (cdar roman)))
3715 (pop roman)))
3716 res)))
3718 (defun org-export-get-tags (element info &optional tags inherited)
3719 "Return list of tags associated to ELEMENT.
3721 ELEMENT has either an `headline' or an `inlinetask' type. INFO
3722 is a plist used as a communication channel.
3724 Select tags (see `org-export-select-tags') and exclude tags (see
3725 `org-export-exclude-tags') are removed from the list.
3727 When non-nil, optional argument TAGS should be a list of strings.
3728 Any tag belonging to this list will also be removed.
3730 When optional argument INHERITED is non-nil, tags can also be
3731 inherited from parent headlines and FILETAGS keywords."
3732 (org-remove-if
3733 (lambda (tag) (or (member tag (plist-get info :select-tags))
3734 (member tag (plist-get info :exclude-tags))
3735 (member tag tags)))
3736 (if (not inherited) (org-element-property :tags element)
3737 ;; Build complete list of inherited tags.
3738 (let ((current-tag-list (org-element-property :tags element)))
3739 (mapc
3740 (lambda (parent)
3741 (mapc
3742 (lambda (tag)
3743 (when (and (memq (org-element-type parent) '(headline inlinetask))
3744 (not (member tag current-tag-list)))
3745 (push tag current-tag-list)))
3746 (org-element-property :tags parent)))
3747 (org-export-get-genealogy element))
3748 ;; Add FILETAGS keywords and return results.
3749 (org-uniquify (append (plist-get info :filetags) current-tag-list))))))
3751 (defun org-export-get-node-property (property blob &optional inherited)
3752 "Return node PROPERTY value for BLOB.
3754 PROPERTY is an upcase symbol (i.e. `:COOKIE_DATA'). BLOB is an
3755 element or object.
3757 If optional argument INHERITED is non-nil, the value can be
3758 inherited from a parent headline.
3760 Return value is a string or nil."
3761 (let ((headline (if (eq (org-element-type blob) 'headline) blob
3762 (org-export-get-parent-headline blob))))
3763 (if (not inherited) (org-element-property property blob)
3764 (let ((parent headline) value)
3765 (catch 'found
3766 (while parent
3767 (when (plist-member (nth 1 parent) property)
3768 (throw 'found (org-element-property property parent)))
3769 (setq parent (org-element-property :parent parent))))))))
3771 (defun org-export-get-category (blob info)
3772 "Return category for element or object BLOB.
3774 INFO is a plist used as a communication channel.
3776 CATEGORY is automatically inherited from a parent headline, from
3777 #+CATEGORY: keyword or created out of original file name. If all
3778 fail, the fall-back value is \"???\"."
3779 (or (let ((headline (if (eq (org-element-type blob) 'headline) blob
3780 (org-export-get-parent-headline blob))))
3781 ;; Almost like `org-export-node-property', but we cannot trust
3782 ;; `plist-member' as every headline has a `:CATEGORY'
3783 ;; property, would it be nil or equal to "???" (which has the
3784 ;; same meaning).
3785 (let ((parent headline) value)
3786 (catch 'found
3787 (while parent
3788 (let ((category (org-element-property :CATEGORY parent)))
3789 (and category (not (equal "???" category))
3790 (throw 'found category)))
3791 (setq parent (org-element-property :parent parent))))))
3792 (org-element-map (plist-get info :parse-tree) 'keyword
3793 (lambda (kwd)
3794 (when (equal (org-element-property :key kwd) "CATEGORY")
3795 (org-element-property :value kwd)))
3796 info 'first-match)
3797 (let ((file (plist-get info :input-file)))
3798 (and file (file-name-sans-extension (file-name-nondirectory file))))
3799 "???"))
3801 (defun org-export-get-alt-title (headline info)
3802 "Return alternative title for HEADLINE, as a secondary string.
3803 INFO is a plist used as a communication channel. If no optional
3804 title is defined, fall-back to the regular title."
3805 (or (org-element-property :alt-title headline)
3806 (org-element-property :title headline)))
3808 (defun org-export-first-sibling-p (headline info)
3809 "Non-nil when HEADLINE is the first sibling in its sub-tree.
3810 INFO is a plist used as a communication channel."
3811 (not (eq (org-element-type (org-export-get-previous-element headline info))
3812 'headline)))
3814 (defun org-export-last-sibling-p (headline info)
3815 "Non-nil when HEADLINE is the last sibling in its sub-tree.
3816 INFO is a plist used as a communication channel."
3817 (not (org-export-get-next-element headline info)))
3820 ;;;; For Keywords
3822 ;; `org-export-get-date' returns a date appropriate for the document
3823 ;; to about to be exported. In particular, it takes care of
3824 ;; `org-export-date-timestamp-format'.
3826 (defun org-export-get-date (info &optional fmt)
3827 "Return date value for the current document.
3829 INFO is a plist used as a communication channel. FMT, when
3830 non-nil, is a time format string that will be applied on the date
3831 if it consists in a single timestamp object. It defaults to
3832 `org-export-date-timestamp-format' when nil.
3834 A proper date can be a secondary string, a string or nil. It is
3835 meant to be translated with `org-export-data' or alike."
3836 (let ((date (plist-get info :date))
3837 (fmt (or fmt org-export-date-timestamp-format)))
3838 (cond ((not date) nil)
3839 ((and fmt
3840 (not (cdr date))
3841 (eq (org-element-type (car date)) 'timestamp))
3842 (org-timestamp-format (car date) fmt))
3843 (t date))))
3846 ;;;; For Links
3848 ;; `org-export-solidify-link-text' turns a string into a safer version
3849 ;; for links, replacing most non-standard characters with hyphens.
3851 ;; `org-export-get-coderef-format' returns an appropriate format
3852 ;; string for coderefs.
3854 ;; `org-export-inline-image-p' returns a non-nil value when the link
3855 ;; provided should be considered as an inline image.
3857 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
3858 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
3859 ;; returns an appropriate unique identifier when found, or nil.
3861 ;; `org-export-resolve-id-link' returns the first headline with
3862 ;; specified id or custom-id in parse tree, the path to the external
3863 ;; file with the id or nil when neither was found.
3865 ;; `org-export-resolve-coderef' associates a reference to a line
3866 ;; number in the element it belongs, or returns the reference itself
3867 ;; when the element isn't numbered.
3869 (defun org-export-solidify-link-text (s)
3870 "Take link text S and make a safe target out of it."
3871 (save-match-data
3872 (mapconcat 'identity (org-split-string s "[^a-zA-Z0-9_.-:]+") "-")))
3874 (defun org-export-get-coderef-format (path desc)
3875 "Return format string for code reference link.
3876 PATH is the link path. DESC is its description."
3877 (save-match-data
3878 (cond ((not desc) "%s")
3879 ((string-match (regexp-quote (concat "(" path ")")) desc)
3880 (replace-match "%s" t t desc))
3881 (t desc))))
3883 (defun org-export-inline-image-p (link &optional rules)
3884 "Non-nil if LINK object points to an inline image.
3886 Optional argument is a set of RULES defining inline images. It
3887 is an alist where associations have the following shape:
3889 \(TYPE . REGEXP)
3891 Applying a rule means apply REGEXP against LINK's path when its
3892 type is TYPE. The function will return a non-nil value if any of
3893 the provided rules is non-nil. The default rule is
3894 `org-export-default-inline-image-rule'.
3896 This only applies to links without a description."
3897 (and (not (org-element-contents link))
3898 (let ((case-fold-search t)
3899 (rules (or rules org-export-default-inline-image-rule)))
3900 (catch 'exit
3901 (mapc
3902 (lambda (rule)
3903 (and (string= (org-element-property :type link) (car rule))
3904 (string-match (cdr rule)
3905 (org-element-property :path link))
3906 (throw 'exit t)))
3907 rules)
3908 ;; Return nil if no rule matched.
3909 nil))))
3911 (defun org-export-resolve-coderef (ref info)
3912 "Resolve a code reference REF.
3914 INFO is a plist used as a communication channel.
3916 Return associated line number in source code, or REF itself,
3917 depending on src-block or example element's switches."
3918 (org-element-map (plist-get info :parse-tree) '(example-block src-block)
3919 (lambda (el)
3920 (with-temp-buffer
3921 (insert (org-trim (org-element-property :value el)))
3922 (let* ((label-fmt (regexp-quote
3923 (or (org-element-property :label-fmt el)
3924 org-coderef-label-format)))
3925 (ref-re
3926 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
3927 (replace-regexp-in-string "%s" ref label-fmt nil t))))
3928 ;; Element containing REF is found. Resolve it to either
3929 ;; a label or a line number, as needed.
3930 (when (re-search-backward ref-re nil t)
3931 (cond
3932 ((org-element-property :use-labels el) ref)
3933 ((eq (org-element-property :number-lines el) 'continued)
3934 (+ (org-export-get-loc el info) (line-number-at-pos)))
3935 (t (line-number-at-pos)))))))
3936 info 'first-match))
3938 (defun org-export-resolve-fuzzy-link (link info)
3939 "Return LINK destination.
3941 INFO is a plist holding contextual information.
3943 Return value can be an object, an element, or nil:
3945 - If LINK path matches a target object (i.e. <<path>>) return it.
3947 - If LINK path exactly matches the name affiliated keyword
3948 \(i.e. #+NAME: path) of an element, return that element.
3950 - If LINK path exactly matches any headline name, return that
3951 element. If more than one headline share that name, priority
3952 will be given to the one with the closest common ancestor, if
3953 any, or the first one in the parse tree otherwise.
3955 - Otherwise, return nil.
3957 Assume LINK type is \"fuzzy\". White spaces are not
3958 significant."
3959 (let* ((raw-path (org-element-property :path link))
3960 (match-title-p (eq (aref raw-path 0) ?*))
3961 ;; Split PATH at white spaces so matches are space
3962 ;; insensitive.
3963 (path (org-split-string
3964 (if match-title-p (substring raw-path 1) raw-path))))
3965 (cond
3966 ;; First try to find a matching "<<path>>" unless user specified
3967 ;; he was looking for a headline (path starts with a "*"
3968 ;; character).
3969 ((and (not match-title-p)
3970 (org-element-map (plist-get info :parse-tree) 'target
3971 (lambda (blob)
3972 (and (equal (org-split-string (org-element-property :value blob))
3973 path)
3974 blob))
3975 info t)))
3976 ;; Then try to find an element with a matching "#+NAME: path"
3977 ;; affiliated keyword.
3978 ((and (not match-title-p)
3979 (org-element-map (plist-get info :parse-tree)
3980 org-element-all-elements
3981 (lambda (el)
3982 (let ((name (org-element-property :name el)))
3983 (when (and name (equal (org-split-string name) path)) el)))
3984 info 'first-match)))
3985 ;; Last case: link either points to a headline or to nothingness.
3986 ;; Try to find the source, with priority given to headlines with
3987 ;; the closest common ancestor. If such candidate is found,
3988 ;; return it, otherwise return nil.
3990 (let ((find-headline
3991 (function
3992 ;; Return first headline whose `:raw-value' property is
3993 ;; NAME in parse tree DATA, or nil. Statistics cookies
3994 ;; are ignored.
3995 (lambda (name data)
3996 (org-element-map data 'headline
3997 (lambda (headline)
3998 (when (equal (org-split-string
3999 (replace-regexp-in-string
4000 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
4001 (org-element-property :raw-value headline)))
4002 name)
4003 headline))
4004 info 'first-match)))))
4005 ;; Search among headlines sharing an ancestor with link, from
4006 ;; closest to farthest.
4007 (or (catch 'exit
4008 (mapc
4009 (lambda (parent)
4010 (when (eq (org-element-type parent) 'headline)
4011 (let ((foundp (funcall find-headline path parent)))
4012 (when foundp (throw 'exit foundp)))))
4013 (org-export-get-genealogy link)) nil)
4014 ;; No match with a common ancestor: try full parse-tree.
4015 (funcall find-headline path (plist-get info :parse-tree))))))))
4017 (defun org-export-resolve-id-link (link info)
4018 "Return headline referenced as LINK destination.
4020 INFO is a plist used as a communication channel.
4022 Return value can be the headline element matched in current parse
4023 tree, a file name or nil. Assume LINK type is either \"id\" or
4024 \"custom-id\"."
4025 (let ((id (org-element-property :path link)))
4026 ;; First check if id is within the current parse tree.
4027 (or (org-element-map (plist-get info :parse-tree) 'headline
4028 (lambda (headline)
4029 (when (or (string= (org-element-property :ID headline) id)
4030 (string= (org-element-property :CUSTOM_ID headline) id))
4031 headline))
4032 info 'first-match)
4033 ;; Otherwise, look for external files.
4034 (cdr (assoc id (plist-get info :id-alist))))))
4036 (defun org-export-resolve-radio-link (link info)
4037 "Return radio-target object referenced as LINK destination.
4039 INFO is a plist used as a communication channel.
4041 Return value can be a radio-target object or nil. Assume LINK
4042 has type \"radio\"."
4043 (let ((path (org-element-property :path link)))
4044 (org-element-map (plist-get info :parse-tree) 'radio-target
4045 (lambda (radio)
4046 (and (compare-strings
4047 (org-element-property :value radio) 0 nil path 0 nil t)
4048 radio))
4049 info 'first-match)))
4052 ;;;; For References
4054 ;; `org-export-get-ordinal' associates a sequence number to any object
4055 ;; or element.
4057 (defun org-export-get-ordinal (element info &optional types predicate)
4058 "Return ordinal number of an element or object.
4060 ELEMENT is the element or object considered. INFO is the plist
4061 used as a communication channel.
4063 Optional argument TYPES, when non-nil, is a list of element or
4064 object types, as symbols, that should also be counted in.
4065 Otherwise, only provided element's type is considered.
4067 Optional argument PREDICATE is a function returning a non-nil
4068 value if the current element or object should be counted in. It
4069 accepts two arguments: the element or object being considered and
4070 the plist used as a communication channel. This allows to count
4071 only a certain type of objects (i.e. inline images).
4073 Return value is a list of numbers if ELEMENT is a headline or an
4074 item. It is nil for keywords. It represents the footnote number
4075 for footnote definitions and footnote references. If ELEMENT is
4076 a target, return the same value as if ELEMENT was the closest
4077 table, item or headline containing the target. In any other
4078 case, return the sequence number of ELEMENT among elements or
4079 objects of the same type."
4080 ;; Ordinal of a target object refer to the ordinal of the closest
4081 ;; table, item, or headline containing the object.
4082 (when (eq (org-element-type element) 'target)
4083 (setq element
4084 (loop for parent in (org-export-get-genealogy element)
4085 when
4086 (memq
4087 (org-element-type parent)
4088 '(footnote-definition footnote-reference headline item
4089 table))
4090 return parent)))
4091 (case (org-element-type element)
4092 ;; Special case 1: A headline returns its number as a list.
4093 (headline (org-export-get-headline-number element info))
4094 ;; Special case 2: An item returns its number as a list.
4095 (item (let ((struct (org-element-property :structure element)))
4096 (org-list-get-item-number
4097 (org-element-property :begin element)
4098 struct
4099 (org-list-prevs-alist struct)
4100 (org-list-parents-alist struct))))
4101 ((footnote-definition footnote-reference)
4102 (org-export-get-footnote-number element info))
4103 (otherwise
4104 (let ((counter 0))
4105 ;; Increment counter until ELEMENT is found again.
4106 (org-element-map (plist-get info :parse-tree)
4107 (or types (org-element-type element))
4108 (lambda (el)
4109 (cond
4110 ((eq element el) (1+ counter))
4111 ((not predicate) (incf counter) nil)
4112 ((funcall predicate el info) (incf counter) nil)))
4113 info 'first-match)))))
4116 ;;;; For Src-Blocks
4118 ;; `org-export-get-loc' counts number of code lines accumulated in
4119 ;; src-block or example-block elements with a "+n" switch until
4120 ;; a given element, excluded. Note: "-n" switches reset that count.
4122 ;; `org-export-unravel-code' extracts source code (along with a code
4123 ;; references alist) from an `element-block' or `src-block' type
4124 ;; element.
4126 ;; `org-export-format-code' applies a formatting function to each line
4127 ;; of code, providing relative line number and code reference when
4128 ;; appropriate. Since it doesn't access the original element from
4129 ;; which the source code is coming, it expects from the code calling
4130 ;; it to know if lines should be numbered and if code references
4131 ;; should appear.
4133 ;; Eventually, `org-export-format-code-default' is a higher-level
4134 ;; function (it makes use of the two previous functions) which handles
4135 ;; line numbering and code references inclusion, and returns source
4136 ;; code in a format suitable for plain text or verbatim output.
4138 (defun org-export-get-loc (element info)
4139 "Return accumulated lines of code up to ELEMENT.
4141 INFO is the plist used as a communication channel.
4143 ELEMENT is excluded from count."
4144 (let ((loc 0))
4145 (org-element-map (plist-get info :parse-tree)
4146 `(src-block example-block ,(org-element-type element))
4147 (lambda (el)
4148 (cond
4149 ;; ELEMENT is reached: Quit the loop.
4150 ((eq el element))
4151 ;; Only count lines from src-block and example-block elements
4152 ;; with a "+n" or "-n" switch. A "-n" switch resets counter.
4153 ((not (memq (org-element-type el) '(src-block example-block))) nil)
4154 ((let ((linums (org-element-property :number-lines el)))
4155 (when linums
4156 ;; Accumulate locs or reset them.
4157 (let ((lines (org-count-lines
4158 (org-trim (org-element-property :value el)))))
4159 (setq loc (if (eq linums 'new) lines (+ loc lines))))))
4160 ;; Return nil to stay in the loop.
4161 nil)))
4162 info 'first-match)
4163 ;; Return value.
4164 loc))
4166 (defun org-export-unravel-code (element)
4167 "Clean source code and extract references out of it.
4169 ELEMENT has either a `src-block' an `example-block' type.
4171 Return a cons cell whose CAR is the source code, cleaned from any
4172 reference and protective comma and CDR is an alist between
4173 relative line number (integer) and name of code reference on that
4174 line (string)."
4175 (let* ((line 0) refs
4176 ;; Get code and clean it. Remove blank lines at its
4177 ;; beginning and end.
4178 (code (let ((c (replace-regexp-in-string
4179 "\\`\\([ \t]*\n\\)+" ""
4180 (replace-regexp-in-string
4181 "\\([ \t]*\n\\)*[ \t]*\\'" "\n"
4182 (org-element-property :value element)))))
4183 ;; If appropriate, remove global indentation.
4184 (if (or org-src-preserve-indentation
4185 (org-element-property :preserve-indent element))
4187 (org-remove-indentation c))))
4188 ;; Get format used for references.
4189 (label-fmt (regexp-quote
4190 (or (org-element-property :label-fmt element)
4191 org-coderef-label-format)))
4192 ;; Build a regexp matching a loc with a reference.
4193 (with-ref-re
4194 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)[ \t]*\\)$"
4195 (replace-regexp-in-string
4196 "%s" "\\([-a-zA-Z0-9_ ]+\\)" label-fmt nil t))))
4197 ;; Return value.
4198 (cons
4199 ;; Code with references removed.
4200 (org-element-normalize-string
4201 (mapconcat
4202 (lambda (loc)
4203 (incf line)
4204 (if (not (string-match with-ref-re loc)) loc
4205 ;; Ref line: remove ref, and signal its position in REFS.
4206 (push (cons line (match-string 3 loc)) refs)
4207 (replace-match "" nil nil loc 1)))
4208 (org-split-string code "\n") "\n"))
4209 ;; Reference alist.
4210 refs)))
4212 (defun org-export-format-code (code fun &optional num-lines ref-alist)
4213 "Format CODE by applying FUN line-wise and return it.
4215 CODE is a string representing the code to format. FUN is
4216 a function. It must accept three arguments: a line of
4217 code (string), the current line number (integer) or nil and the
4218 reference associated to the current line (string) or nil.
4220 Optional argument NUM-LINES can be an integer representing the
4221 number of code lines accumulated until the current code. Line
4222 numbers passed to FUN will take it into account. If it is nil,
4223 FUN's second argument will always be nil. This number can be
4224 obtained with `org-export-get-loc' function.
4226 Optional argument REF-ALIST can be an alist between relative line
4227 number (i.e. ignoring NUM-LINES) and the name of the code
4228 reference on it. If it is nil, FUN's third argument will always
4229 be nil. It can be obtained through the use of
4230 `org-export-unravel-code' function."
4231 (let ((--locs (org-split-string code "\n"))
4232 (--line 0))
4233 (org-element-normalize-string
4234 (mapconcat
4235 (lambda (--loc)
4236 (incf --line)
4237 (let ((--ref (cdr (assq --line ref-alist))))
4238 (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
4239 --locs "\n"))))
4241 (defun org-export-format-code-default (element info)
4242 "Return source code from ELEMENT, formatted in a standard way.
4244 ELEMENT is either a `src-block' or `example-block' element. INFO
4245 is a plist used as a communication channel.
4247 This function takes care of line numbering and code references
4248 inclusion. Line numbers, when applicable, appear at the
4249 beginning of the line, separated from the code by two white
4250 spaces. Code references, on the other hand, appear flushed to
4251 the right, separated by six white spaces from the widest line of
4252 code."
4253 ;; Extract code and references.
4254 (let* ((code-info (org-export-unravel-code element))
4255 (code (car code-info))
4256 (code-lines (org-split-string code "\n")))
4257 (if (null code-lines) ""
4258 (let* ((refs (and (org-element-property :retain-labels element)
4259 (cdr code-info)))
4260 ;; Handle line numbering.
4261 (num-start (case (org-element-property :number-lines element)
4262 (continued (org-export-get-loc element info))
4263 (new 0)))
4264 (num-fmt
4265 (and num-start
4266 (format "%%%ds "
4267 (length (number-to-string
4268 (+ (length code-lines) num-start))))))
4269 ;; Prepare references display, if required. Any reference
4270 ;; should start six columns after the widest line of code,
4271 ;; wrapped with parenthesis.
4272 (max-width
4273 (+ (apply 'max (mapcar 'length code-lines))
4274 (if (not num-start) 0 (length (format num-fmt num-start))))))
4275 (org-export-format-code
4276 code
4277 (lambda (loc line-num ref)
4278 (let ((number-str (and num-fmt (format num-fmt line-num))))
4279 (concat
4280 number-str
4282 (and ref
4283 (concat (make-string
4284 (- (+ 6 max-width)
4285 (+ (length loc) (length number-str))) ? )
4286 (format "(%s)" ref))))))
4287 num-start refs)))))
4290 ;;;; For Tables
4292 ;; `org-export-table-has-special-column-p' and and
4293 ;; `org-export-table-row-is-special-p' are predicates used to look for
4294 ;; meta-information about the table structure.
4296 ;; `org-table-has-header-p' tells when the rows before the first rule
4297 ;; should be considered as table's header.
4299 ;; `org-export-table-cell-width', `org-export-table-cell-alignment'
4300 ;; and `org-export-table-cell-borders' extract information from
4301 ;; a table-cell element.
4303 ;; `org-export-table-dimensions' gives the number on rows and columns
4304 ;; in the table, ignoring horizontal rules and special columns.
4305 ;; `org-export-table-cell-address', given a table-cell object, returns
4306 ;; the absolute address of a cell. On the other hand,
4307 ;; `org-export-get-table-cell-at' does the contrary.
4309 ;; `org-export-table-cell-starts-colgroup-p',
4310 ;; `org-export-table-cell-ends-colgroup-p',
4311 ;; `org-export-table-row-starts-rowgroup-p',
4312 ;; `org-export-table-row-ends-rowgroup-p',
4313 ;; `org-export-table-row-starts-header-p' and
4314 ;; `org-export-table-row-ends-header-p' indicate position of current
4315 ;; row or cell within the table.
4317 (defun org-export-table-has-special-column-p (table)
4318 "Non-nil when TABLE has a special column.
4319 All special columns will be ignored during export."
4320 ;; The table has a special column when every first cell of every row
4321 ;; has an empty value or contains a symbol among "/", "#", "!", "$",
4322 ;; "*" "_" and "^". Though, do not consider a first row containing
4323 ;; only empty cells as special.
4324 (let ((special-column-p 'empty))
4325 (catch 'exit
4326 (mapc
4327 (lambda (row)
4328 (when (eq (org-element-property :type row) 'standard)
4329 (let ((value (org-element-contents
4330 (car (org-element-contents row)))))
4331 (cond ((member value '(("/") ("#") ("!") ("$") ("*") ("_") ("^")))
4332 (setq special-column-p 'special))
4333 ((not value))
4334 (t (throw 'exit nil))))))
4335 (org-element-contents table))
4336 (eq special-column-p 'special))))
4338 (defun org-export-table-has-header-p (table info)
4339 "Non-nil when TABLE has a header.
4341 INFO is a plist used as a communication channel.
4343 A table has a header when it contains at least two row groups."
4344 (let ((rowgroup 1) row-flag)
4345 (org-element-map table 'table-row
4346 (lambda (row)
4347 (cond
4348 ((> rowgroup 1) t)
4349 ((and row-flag (eq (org-element-property :type row) 'rule))
4350 (incf rowgroup) (setq row-flag nil))
4351 ((and (not row-flag) (eq (org-element-property :type row) 'standard))
4352 (setq row-flag t) nil)))
4353 info)))
4355 (defun org-export-table-row-is-special-p (table-row info)
4356 "Non-nil if TABLE-ROW is considered special.
4358 INFO is a plist used as the communication channel.
4360 All special rows will be ignored during export."
4361 (when (eq (org-element-property :type table-row) 'standard)
4362 (let ((first-cell (org-element-contents
4363 (car (org-element-contents table-row)))))
4364 ;; A row is special either when...
4366 ;; ... it starts with a field only containing "/",
4367 (equal first-cell '("/"))
4368 ;; ... the table contains a special column and the row start
4369 ;; with a marking character among, "^", "_", "$" or "!",
4370 (and (org-export-table-has-special-column-p
4371 (org-export-get-parent table-row))
4372 (member first-cell '(("^") ("_") ("$") ("!"))))
4373 ;; ... it contains only alignment cookies and empty cells.
4374 (let ((special-row-p 'empty))
4375 (catch 'exit
4376 (mapc
4377 (lambda (cell)
4378 (let ((value (org-element-contents cell)))
4379 ;; Since VALUE is a secondary string, the following
4380 ;; checks avoid expanding it with `org-export-data'.
4381 (cond ((not value))
4382 ((and (not (cdr value))
4383 (stringp (car value))
4384 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'"
4385 (car value)))
4386 (setq special-row-p 'cookie))
4387 (t (throw 'exit nil)))))
4388 (org-element-contents table-row))
4389 (eq special-row-p 'cookie)))))))
4391 (defun org-export-table-row-group (table-row info)
4392 "Return TABLE-ROW's group.
4394 INFO is a plist used as the communication channel.
4396 Return value is the group number, as an integer, or nil for
4397 special rows and table rules. Group 1 is also table's header."
4398 (unless (or (eq (org-element-property :type table-row) 'rule)
4399 (org-export-table-row-is-special-p table-row info))
4400 (let ((group 0) row-flag)
4401 (catch 'found
4402 (mapc
4403 (lambda (row)
4404 (cond
4405 ((and (eq (org-element-property :type row) 'standard)
4406 (not (org-export-table-row-is-special-p row info)))
4407 (unless row-flag (incf group) (setq row-flag t)))
4408 ((eq (org-element-property :type row) 'rule)
4409 (setq row-flag nil)))
4410 (when (eq table-row row) (throw 'found group)))
4411 (org-element-contents (org-export-get-parent table-row)))))))
4413 (defun org-export-table-cell-width (table-cell info)
4414 "Return TABLE-CELL contents width.
4416 INFO is a plist used as the communication channel.
4418 Return value is the width given by the last width cookie in the
4419 same column as TABLE-CELL, or nil."
4420 (let* ((row (org-export-get-parent table-cell))
4421 (column (let ((cells (org-element-contents row)))
4422 (- (length cells) (length (memq table-cell cells)))))
4423 (table (org-export-get-parent-table table-cell))
4424 cookie-width)
4425 (mapc
4426 (lambda (row)
4427 (cond
4428 ;; In a special row, try to find a width cookie at COLUMN.
4429 ((org-export-table-row-is-special-p row info)
4430 (let ((value (org-element-contents
4431 (elt (org-element-contents row) column))))
4432 ;; The following checks avoid expanding unnecessarily the
4433 ;; cell with `org-export-data'
4434 (when (and value
4435 (not (cdr value))
4436 (stringp (car value))
4437 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'" (car value))
4438 (match-string 1 (car value)))
4439 (setq cookie-width
4440 (string-to-number (match-string 1 (car value)))))))
4441 ;; Ignore table rules.
4442 ((eq (org-element-property :type row) 'rule))))
4443 (org-element-contents table))
4444 ;; Return value.
4445 cookie-width))
4447 (defun org-export-table-cell-alignment (table-cell info)
4448 "Return TABLE-CELL contents alignment.
4450 INFO is a plist used as the communication channel.
4452 Return alignment as specified by the last alignment cookie in the
4453 same column as TABLE-CELL. If no such cookie is found, a default
4454 alignment value will be deduced from fraction of numbers in the
4455 column (see `org-table-number-fraction' for more information).
4456 Possible values are `left', `right' and `center'."
4457 (let* ((row (org-export-get-parent table-cell))
4458 (column (let ((cells (org-element-contents row)))
4459 (- (length cells) (length (memq table-cell cells)))))
4460 (table (org-export-get-parent-table table-cell))
4461 (number-cells 0)
4462 (total-cells 0)
4463 cookie-align
4464 previous-cell-number-p)
4465 (mapc
4466 (lambda (row)
4467 (cond
4468 ;; In a special row, try to find an alignment cookie at
4469 ;; COLUMN.
4470 ((org-export-table-row-is-special-p row info)
4471 (let ((value (org-element-contents
4472 (elt (org-element-contents row) column))))
4473 ;; Since VALUE is a secondary string, the following checks
4474 ;; avoid useless expansion through `org-export-data'.
4475 (when (and value
4476 (not (cdr value))
4477 (stringp (car value))
4478 (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'"
4479 (car value))
4480 (match-string 1 (car value)))
4481 (setq cookie-align (match-string 1 (car value))))))
4482 ;; Ignore table rules.
4483 ((eq (org-element-property :type row) 'rule))
4484 ;; In a standard row, check if cell's contents are expressing
4485 ;; some kind of number. Increase NUMBER-CELLS accordingly.
4486 ;; Though, don't bother if an alignment cookie has already
4487 ;; defined cell's alignment.
4488 ((not cookie-align)
4489 (let ((value (org-export-data
4490 (org-element-contents
4491 (elt (org-element-contents row) column))
4492 info)))
4493 (incf total-cells)
4494 ;; Treat an empty cell as a number if it follows a number
4495 (if (not (or (string-match org-table-number-regexp value)
4496 (and (string= value "") previous-cell-number-p)))
4497 (setq previous-cell-number-p nil)
4498 (setq previous-cell-number-p t)
4499 (incf number-cells))))))
4500 (org-element-contents table))
4501 ;; Return value. Alignment specified by cookies has precedence
4502 ;; over alignment deduced from cells contents.
4503 (cond ((equal cookie-align "l") 'left)
4504 ((equal cookie-align "r") 'right)
4505 ((equal cookie-align "c") 'center)
4506 ((>= (/ (float number-cells) total-cells) org-table-number-fraction)
4507 'right)
4508 (t 'left))))
4510 (defun org-export-table-cell-borders (table-cell info)
4511 "Return TABLE-CELL borders.
4513 INFO is a plist used as a communication channel.
4515 Return value is a list of symbols, or nil. Possible values are:
4516 `top', `bottom', `above', `below', `left' and `right'. Note:
4517 `top' (resp. `bottom') only happen for a cell in the first
4518 row (resp. last row) of the table, ignoring table rules, if any.
4520 Returned borders ignore special rows."
4521 (let* ((row (org-export-get-parent table-cell))
4522 (table (org-export-get-parent-table table-cell))
4523 borders)
4524 ;; Top/above border? TABLE-CELL has a border above when a rule
4525 ;; used to demarcate row groups can be found above. Hence,
4526 ;; finding a rule isn't sufficient to push `above' in BORDERS:
4527 ;; another regular row has to be found above that rule.
4528 (let (rule-flag)
4529 (catch 'exit
4530 (mapc (lambda (row)
4531 (cond ((eq (org-element-property :type row) 'rule)
4532 (setq rule-flag t))
4533 ((not (org-export-table-row-is-special-p row info))
4534 (if rule-flag (throw 'exit (push 'above borders))
4535 (throw 'exit nil)))))
4536 ;; Look at every row before the current one.
4537 (cdr (memq row (reverse (org-element-contents table)))))
4538 ;; No rule above, or rule found starts the table (ignoring any
4539 ;; special row): TABLE-CELL is at the top of the table.
4540 (when rule-flag (push 'above borders))
4541 (push 'top borders)))
4542 ;; Bottom/below border? TABLE-CELL has a border below when next
4543 ;; non-regular row below is a rule.
4544 (let (rule-flag)
4545 (catch 'exit
4546 (mapc (lambda (row)
4547 (cond ((eq (org-element-property :type row) 'rule)
4548 (setq rule-flag t))
4549 ((not (org-export-table-row-is-special-p row info))
4550 (if rule-flag (throw 'exit (push 'below borders))
4551 (throw 'exit nil)))))
4552 ;; Look at every row after the current one.
4553 (cdr (memq row (org-element-contents table))))
4554 ;; No rule below, or rule found ends the table (modulo some
4555 ;; special row): TABLE-CELL is at the bottom of the table.
4556 (when rule-flag (push 'below borders))
4557 (push 'bottom borders)))
4558 ;; Right/left borders? They can only be specified by column
4559 ;; groups. Column groups are defined in a row starting with "/".
4560 ;; Also a column groups row only contains "<", "<>", ">" or blank
4561 ;; cells.
4562 (catch 'exit
4563 (let ((column (let ((cells (org-element-contents row)))
4564 (- (length cells) (length (memq table-cell cells))))))
4565 (mapc
4566 (lambda (row)
4567 (unless (eq (org-element-property :type row) 'rule)
4568 (when (equal (org-element-contents
4569 (car (org-element-contents row)))
4570 '("/"))
4571 (let ((column-groups
4572 (mapcar
4573 (lambda (cell)
4574 (let ((value (org-element-contents cell)))
4575 (when (member value '(("<") ("<>") (">") nil))
4576 (car value))))
4577 (org-element-contents row))))
4578 ;; There's a left border when previous cell, if
4579 ;; any, ends a group, or current one starts one.
4580 (when (or (and (not (zerop column))
4581 (member (elt column-groups (1- column))
4582 '(">" "<>")))
4583 (member (elt column-groups column) '("<" "<>")))
4584 (push 'left borders))
4585 ;; There's a right border when next cell, if any,
4586 ;; starts a group, or current one ends one.
4587 (when (or (and (/= (1+ column) (length column-groups))
4588 (member (elt column-groups (1+ column))
4589 '("<" "<>")))
4590 (member (elt column-groups column) '(">" "<>")))
4591 (push 'right borders))
4592 (throw 'exit nil)))))
4593 ;; Table rows are read in reverse order so last column groups
4594 ;; row has precedence over any previous one.
4595 (reverse (org-element-contents table)))))
4596 ;; Return value.
4597 borders))
4599 (defun org-export-table-cell-starts-colgroup-p (table-cell info)
4600 "Non-nil when TABLE-CELL is at the beginning of a row group.
4601 INFO is a plist used as a communication channel."
4602 ;; A cell starts a column group either when it is at the beginning
4603 ;; of a row (or after the special column, if any) or when it has
4604 ;; a left border.
4605 (or (eq (org-element-map (org-export-get-parent table-cell) 'table-cell
4606 'identity info 'first-match)
4607 table-cell)
4608 (memq 'left (org-export-table-cell-borders table-cell info))))
4610 (defun org-export-table-cell-ends-colgroup-p (table-cell info)
4611 "Non-nil when TABLE-CELL is at the end of a row group.
4612 INFO is a plist used as a communication channel."
4613 ;; A cell ends a column group either when it is at the end of a row
4614 ;; or when it has a right border.
4615 (or (eq (car (last (org-element-contents
4616 (org-export-get-parent table-cell))))
4617 table-cell)
4618 (memq 'right (org-export-table-cell-borders table-cell info))))
4620 (defun org-export-table-row-starts-rowgroup-p (table-row info)
4621 "Non-nil when TABLE-ROW is at the beginning of a column group.
4622 INFO is a plist used as a communication channel."
4623 (unless (or (eq (org-element-property :type table-row) 'rule)
4624 (org-export-table-row-is-special-p table-row info))
4625 (let ((borders (org-export-table-cell-borders
4626 (car (org-element-contents table-row)) info)))
4627 (or (memq 'top borders) (memq 'above borders)))))
4629 (defun org-export-table-row-ends-rowgroup-p (table-row info)
4630 "Non-nil when TABLE-ROW is at the end of a column group.
4631 INFO is a plist used as a communication channel."
4632 (unless (or (eq (org-element-property :type table-row) 'rule)
4633 (org-export-table-row-is-special-p table-row info))
4634 (let ((borders (org-export-table-cell-borders
4635 (car (org-element-contents table-row)) info)))
4636 (or (memq 'bottom borders) (memq 'below borders)))))
4638 (defun org-export-table-row-starts-header-p (table-row info)
4639 "Non-nil when TABLE-ROW is the first table header's row.
4640 INFO is a plist used as a communication channel."
4641 (and (org-export-table-has-header-p
4642 (org-export-get-parent-table table-row) info)
4643 (org-export-table-row-starts-rowgroup-p table-row info)
4644 (= (org-export-table-row-group table-row info) 1)))
4646 (defun org-export-table-row-ends-header-p (table-row info)
4647 "Non-nil when TABLE-ROW is the last table header's row.
4648 INFO is a plist used as a communication channel."
4649 (and (org-export-table-has-header-p
4650 (org-export-get-parent-table table-row) info)
4651 (org-export-table-row-ends-rowgroup-p table-row info)
4652 (= (org-export-table-row-group table-row info) 1)))
4654 (defun org-export-table-row-number (table-row info)
4655 "Return TABLE-ROW number.
4656 INFO is a plist used as a communication channel. Return value is
4657 zero-based and ignores separators. The function returns nil for
4658 special colums and separators."
4659 (when (and (eq (org-element-property :type table-row) 'standard)
4660 (not (org-export-table-row-is-special-p table-row info)))
4661 (let ((number 0))
4662 (org-element-map (org-export-get-parent-table table-row) 'table-row
4663 (lambda (row)
4664 (cond ((eq row table-row) number)
4665 ((eq (org-element-property :type row) 'standard)
4666 (incf number) nil)))
4667 info 'first-match))))
4669 (defun org-export-table-dimensions (table info)
4670 "Return TABLE dimensions.
4672 INFO is a plist used as a communication channel.
4674 Return value is a CONS like (ROWS . COLUMNS) where
4675 ROWS (resp. COLUMNS) is the number of exportable
4676 rows (resp. columns)."
4677 (let (first-row (columns 0) (rows 0))
4678 ;; Set number of rows, and extract first one.
4679 (org-element-map table 'table-row
4680 (lambda (row)
4681 (when (eq (org-element-property :type row) 'standard)
4682 (incf rows)
4683 (unless first-row (setq first-row row)))) info)
4684 ;; Set number of columns.
4685 (org-element-map first-row 'table-cell (lambda (cell) (incf columns)) info)
4686 ;; Return value.
4687 (cons rows columns)))
4689 (defun org-export-table-cell-address (table-cell info)
4690 "Return address of a regular TABLE-CELL object.
4692 TABLE-CELL is the cell considered. INFO is a plist used as
4693 a communication channel.
4695 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4696 zero-based index. Only exportable cells are considered. The
4697 function returns nil for other cells."
4698 (let* ((table-row (org-export-get-parent table-cell))
4699 (table (org-export-get-parent-table table-cell)))
4700 ;; Ignore cells in special rows or in special column.
4701 (unless (or (org-export-table-row-is-special-p table-row info)
4702 (and (org-export-table-has-special-column-p table)
4703 (eq (car (org-element-contents table-row)) table-cell)))
4704 (cons
4705 ;; Row number.
4706 (org-export-table-row-number (org-export-get-parent table-cell) info)
4707 ;; Column number.
4708 (let ((col-count 0))
4709 (org-element-map table-row 'table-cell
4710 (lambda (cell)
4711 (if (eq cell table-cell) col-count (incf col-count) nil))
4712 info 'first-match))))))
4714 (defun org-export-get-table-cell-at (address table info)
4715 "Return regular table-cell object at ADDRESS in TABLE.
4717 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4718 zero-based index. TABLE is a table type element. INFO is
4719 a plist used as a communication channel.
4721 If no table-cell, among exportable cells, is found at ADDRESS,
4722 return nil."
4723 (let ((column-pos (cdr address)) (column-count 0))
4724 (org-element-map
4725 ;; Row at (car address) or nil.
4726 (let ((row-pos (car address)) (row-count 0))
4727 (org-element-map table 'table-row
4728 (lambda (row)
4729 (cond ((eq (org-element-property :type row) 'rule) nil)
4730 ((= row-count row-pos) row)
4731 (t (incf row-count) nil)))
4732 info 'first-match))
4733 'table-cell
4734 (lambda (cell)
4735 (if (= column-count column-pos) cell
4736 (incf column-count) nil))
4737 info 'first-match)))
4740 ;;;; For Tables Of Contents
4742 ;; `org-export-collect-headlines' builds a list of all exportable
4743 ;; headline elements, maybe limited to a certain depth. One can then
4744 ;; easily parse it and transcode it.
4746 ;; Building lists of tables, figures or listings is quite similar.
4747 ;; Once the generic function `org-export-collect-elements' is defined,
4748 ;; `org-export-collect-tables', `org-export-collect-figures' and
4749 ;; `org-export-collect-listings' can be derived from it.
4751 (defun org-export-collect-headlines (info &optional n)
4752 "Collect headlines in order to build a table of contents.
4754 INFO is a plist used as a communication channel.
4756 When optional argument N is an integer, it specifies the depth of
4757 the table of contents. Otherwise, it is set to the value of the
4758 last headline level. See `org-export-headline-levels' for more
4759 information.
4761 Return a list of all exportable headlines as parsed elements.
4762 Footnote sections, if any, will be ignored."
4763 (unless (wholenump n) (setq n (plist-get info :headline-levels)))
4764 (org-element-map (plist-get info :parse-tree) 'headline
4765 (lambda (headline)
4766 (unless (org-element-property :footnote-section-p headline)
4767 ;; Strip contents from HEADLINE.
4768 (let ((relative-level (org-export-get-relative-level headline info)))
4769 (unless (> relative-level n) headline))))
4770 info))
4772 (defun org-export-collect-elements (type info &optional predicate)
4773 "Collect referenceable elements of a determined type.
4775 TYPE can be a symbol or a list of symbols specifying element
4776 types to search. Only elements with a caption are collected.
4778 INFO is a plist used as a communication channel.
4780 When non-nil, optional argument PREDICATE is a function accepting
4781 one argument, an element of type TYPE. It returns a non-nil
4782 value when that element should be collected.
4784 Return a list of all elements found, in order of appearance."
4785 (org-element-map (plist-get info :parse-tree) type
4786 (lambda (element)
4787 (and (org-element-property :caption element)
4788 (or (not predicate) (funcall predicate element))
4789 element))
4790 info))
4792 (defun org-export-collect-tables (info)
4793 "Build a list of tables.
4794 INFO is a plist used as a communication channel.
4796 Return a list of table elements with a caption."
4797 (org-export-collect-elements 'table info))
4799 (defun org-export-collect-figures (info predicate)
4800 "Build a list of figures.
4802 INFO is a plist used as a communication channel. PREDICATE is
4803 a function which accepts one argument: a paragraph element and
4804 whose return value is non-nil when that element should be
4805 collected.
4807 A figure is a paragraph type element, with a caption, verifying
4808 PREDICATE. The latter has to be provided since a \"figure\" is
4809 a vague concept that may depend on back-end.
4811 Return a list of elements recognized as figures."
4812 (org-export-collect-elements 'paragraph info predicate))
4814 (defun org-export-collect-listings (info)
4815 "Build a list of src blocks.
4817 INFO is a plist used as a communication channel.
4819 Return a list of src-block elements with a caption."
4820 (org-export-collect-elements 'src-block info))
4823 ;;;; Smart Quotes
4825 ;; The main function for the smart quotes sub-system is
4826 ;; `org-export-activate-smart-quotes', which replaces every quote in
4827 ;; a given string from the parse tree with its "smart" counterpart.
4829 ;; Dictionary for smart quotes is stored in
4830 ;; `org-export-smart-quotes-alist'.
4832 ;; Internally, regexps matching potential smart quotes (checks at
4833 ;; string boundaries are also necessary) are defined in
4834 ;; `org-export-smart-quotes-regexps'.
4836 (defconst org-export-smart-quotes-alist
4837 '(("de"
4838 (opening-double-quote :utf-8 "„" :html "&bdquo;" :latex "\"`"
4839 :texinfo "@quotedblbase{}")
4840 (closing-double-quote :utf-8 "“" :html "&ldquo;" :latex "\"'"
4841 :texinfo "@quotedblleft{}")
4842 (opening-single-quote :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}"
4843 :texinfo "@quotesinglbase{}")
4844 (closing-single-quote :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}"
4845 :texinfo "@quoteleft{}")
4846 (apostrophe :utf-8 "’" :html "&rsquo;"))
4847 ("en"
4848 (opening-double-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
4849 (closing-double-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
4850 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
4851 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
4852 (apostrophe :utf-8 "’" :html "&rsquo;"))
4853 ("es"
4854 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
4855 :texinfo "@guillemetleft{}")
4856 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
4857 :texinfo "@guillemetright{}")
4858 (opening-single-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
4859 (closing-single-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
4860 (apostrophe :utf-8 "’" :html "&rsquo;"))
4861 ("fr"
4862 (opening-double-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
4863 :texinfo "@guillemetleft{}@tie{}")
4864 (closing-double-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
4865 :texinfo "@tie{}@guillemetright{}")
4866 (opening-single-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
4867 :texinfo "@guillemetleft{}@tie{}")
4868 (closing-single-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
4869 :texinfo "@tie{}@guillemetright{}")
4870 (apostrophe :utf-8 "’" :html "&rsquo;")))
4871 "Smart quotes translations.
4873 Alist whose CAR is a language string and CDR is an alist with
4874 quote type as key and a plist associating various encodings to
4875 their translation as value.
4877 A quote type can be any symbol among `opening-double-quote',
4878 `closing-double-quote', `opening-single-quote',
4879 `closing-single-quote' and `apostrophe'.
4881 Valid encodings include `:utf-8', `:html', `:latex' and
4882 `:texinfo'.
4884 If no translation is found, the quote character is left as-is.")
4886 (defconst org-export-smart-quotes-regexps
4887 (list
4888 ;; Possible opening quote at beginning of string.
4889 "\\`\\([\"']\\)\\(\\w\\|\\s.\\|\\s_\\)"
4890 ;; Possible closing quote at beginning of string.
4891 "\\`\\([\"']\\)\\(\\s-\\|\\s)\\|\\s.\\)"
4892 ;; Possible apostrophe at beginning of string.
4893 "\\`\\('\\)\\S-"
4894 ;; Opening single and double quotes.
4895 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\(?:\\w\\|\\s.\\|\\s_\\)"
4896 ;; Closing single and double quotes.
4897 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\(?:\\s-\\|\\s)\\|\\s.\\)"
4898 ;; Apostrophe.
4899 "\\S-\\('\\)\\S-"
4900 ;; Possible opening quote at end of string.
4901 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\'"
4902 ;; Possible closing quote at end of string.
4903 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\'"
4904 ;; Possible apostrophe at end of string.
4905 "\\S-\\('\\)\\'")
4906 "List of regexps matching a quote or an apostrophe.
4907 In every regexp, quote or apostrophe matched is put in group 1.")
4909 (defun org-export-activate-smart-quotes (s encoding info &optional original)
4910 "Replace regular quotes with \"smart\" quotes in string S.
4912 ENCODING is a symbol among `:html', `:latex', `:texinfo' and
4913 `:utf-8'. INFO is a plist used as a communication channel.
4915 The function has to retrieve information about string
4916 surroundings in parse tree. It can only happen with an
4917 unmodified string. Thus, if S has already been through another
4918 process, a non-nil ORIGINAL optional argument will provide that
4919 original string.
4921 Return the new string."
4922 (if (equal s "") ""
4923 (let* ((prev (org-export-get-previous-element (or original s) info))
4924 ;; Try to be flexible when computing number of blanks
4925 ;; before object. The previous object may be a string
4926 ;; introduced by the back-end and not completely parsed.
4927 (pre-blank (and prev
4928 (or (org-element-property :post-blank prev)
4929 ;; A string with missing `:post-blank'
4930 ;; property.
4931 (and (stringp prev)
4932 (string-match " *\\'" prev)
4933 (length (match-string 0 prev)))
4934 ;; Fallback value.
4935 0)))
4936 (next (org-export-get-next-element (or original s) info))
4937 (get-smart-quote
4938 (lambda (q type)
4939 ;; Return smart quote associated to a give quote Q, as
4940 ;; a string. TYPE is a symbol among `open', `close' and
4941 ;; `apostrophe'.
4942 (let ((key (case type
4943 (apostrophe 'apostrophe)
4944 (open (if (equal "'" q) 'opening-single-quote
4945 'opening-double-quote))
4946 (otherwise (if (equal "'" q) 'closing-single-quote
4947 'closing-double-quote)))))
4948 (or (plist-get
4949 (cdr (assq key
4950 (cdr (assoc (plist-get info :language)
4951 org-export-smart-quotes-alist))))
4952 encoding)
4953 q)))))
4954 (if (or (equal "\"" s) (equal "'" s))
4955 ;; Only a quote: no regexp can match. We have to check both
4956 ;; sides and decide what to do.
4957 (cond ((and (not prev) (not next)) s)
4958 ((not prev) (funcall get-smart-quote s 'open))
4959 ((and (not next) (zerop pre-blank))
4960 (funcall get-smart-quote s 'close))
4961 ((not next) s)
4962 ((zerop pre-blank) (funcall get-smart-quote s 'apostrophe))
4963 (t (funcall get-smart-quote 'open)))
4964 ;; 1. Replace quote character at the beginning of S.
4965 (cond
4966 ;; Apostrophe?
4967 ((and prev (zerop pre-blank)
4968 (string-match (nth 2 org-export-smart-quotes-regexps) s))
4969 (setq s (replace-match
4970 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
4971 nil t s 1)))
4972 ;; Closing quote?
4973 ((and prev (zerop pre-blank)
4974 (string-match (nth 1 org-export-smart-quotes-regexps) s))
4975 (setq s (replace-match
4976 (funcall get-smart-quote (match-string 1 s) 'close)
4977 nil t s 1)))
4978 ;; Opening quote?
4979 ((and (or (not prev) (> pre-blank 0))
4980 (string-match (nth 0 org-export-smart-quotes-regexps) s))
4981 (setq s (replace-match
4982 (funcall get-smart-quote (match-string 1 s) 'open)
4983 nil t s 1))))
4984 ;; 2. Replace quotes in the middle of the string.
4985 (setq s (replace-regexp-in-string
4986 ;; Opening quotes.
4987 (nth 3 org-export-smart-quotes-regexps)
4988 (lambda (text)
4989 (funcall get-smart-quote (match-string 1 text) 'open))
4990 s nil t 1))
4991 (setq s (replace-regexp-in-string
4992 ;; Closing quotes.
4993 (nth 4 org-export-smart-quotes-regexps)
4994 (lambda (text)
4995 (funcall get-smart-quote (match-string 1 text) 'close))
4996 s nil t 1))
4997 (setq s (replace-regexp-in-string
4998 ;; Apostrophes.
4999 (nth 5 org-export-smart-quotes-regexps)
5000 (lambda (text)
5001 (funcall get-smart-quote (match-string 1 text) 'apostrophe))
5002 s nil t 1))
5003 ;; 3. Replace quote character at the end of S.
5004 (cond
5005 ;; Apostrophe?
5006 ((and next (string-match (nth 8 org-export-smart-quotes-regexps) s))
5007 (setq s (replace-match
5008 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
5009 nil t s 1)))
5010 ;; Closing quote?
5011 ((and (not next)
5012 (string-match (nth 7 org-export-smart-quotes-regexps) s))
5013 (setq s (replace-match
5014 (funcall get-smart-quote (match-string 1 s) 'close)
5015 nil t s 1)))
5016 ;; Opening quote?
5017 ((and next (string-match (nth 6 org-export-smart-quotes-regexps) s))
5018 (setq s (replace-match
5019 (funcall get-smart-quote (match-string 1 s) 'open)
5020 nil t s 1))))
5021 ;; Return string with smart quotes.
5022 s))))
5024 ;;;; Topology
5026 ;; Here are various functions to retrieve information about the
5027 ;; neighbourhood of a given element or object. Neighbours of interest
5028 ;; are direct parent (`org-export-get-parent'), parent headline
5029 ;; (`org-export-get-parent-headline'), first element containing an
5030 ;; object, (`org-export-get-parent-element'), parent table
5031 ;; (`org-export-get-parent-table'), previous element or object
5032 ;; (`org-export-get-previous-element') and next element or object
5033 ;; (`org-export-get-next-element').
5035 ;; `org-export-get-genealogy' returns the full genealogy of a given
5036 ;; element or object, from closest parent to full parse tree.
5038 (defun org-export-get-parent (blob)
5039 "Return BLOB parent or nil.
5040 BLOB is the element or object considered."
5041 (org-element-property :parent blob))
5043 (defun org-export-get-genealogy (blob)
5044 "Return full genealogy relative to a given element or object.
5046 BLOB is the element or object being considered.
5048 Ancestors are returned from closest to farthest, the last one
5049 being the full parse tree."
5050 (let (genealogy (parent blob))
5051 (while (setq parent (org-element-property :parent parent))
5052 (push parent genealogy))
5053 (nreverse genealogy)))
5055 (defun org-export-get-parent-headline (blob)
5056 "Return BLOB parent headline or nil.
5057 BLOB is the element or object being considered."
5058 (let ((parent blob))
5059 (while (and (setq parent (org-element-property :parent parent))
5060 (not (eq (org-element-type parent) 'headline))))
5061 parent))
5063 (defun org-export-get-parent-element (object)
5064 "Return first element containing OBJECT or nil.
5065 OBJECT is the object to consider."
5066 (let ((parent object))
5067 (while (and (setq parent (org-element-property :parent parent))
5068 (memq (org-element-type parent) org-element-all-objects)))
5069 parent))
5071 (defun org-export-get-parent-table (object)
5072 "Return OBJECT parent table or nil.
5073 OBJECT is either a `table-cell' or `table-element' type object."
5074 (let ((parent object))
5075 (while (and (setq parent (org-element-property :parent parent))
5076 (not (eq (org-element-type parent) 'table))))
5077 parent))
5079 (defun org-export-get-previous-element (blob info &optional n)
5080 "Return previous element or object.
5082 BLOB is an element or object. INFO is a plist used as
5083 a communication channel. Return previous exportable element or
5084 object, a string, or nil.
5086 When optional argument N is a positive integer, return a list
5087 containing up to N siblings before BLOB, from farthest to
5088 closest. With any other non-nil value, return a list containing
5089 all of them."
5090 (let ((siblings
5091 ;; An object can belong to the contents of its parent or
5092 ;; to a secondary string. We check the latter option
5093 ;; first.
5094 (let ((parent (org-export-get-parent blob)))
5095 (or (and (not (memq (org-element-type blob)
5096 org-element-all-elements))
5097 (let ((sec-value
5098 (org-element-property
5099 (cdr (assq (org-element-type parent)
5100 org-element-secondary-value-alist))
5101 parent)))
5102 (and (memq blob sec-value) sec-value)))
5103 (org-element-contents parent))))
5104 prev)
5105 (catch 'exit
5106 (mapc (lambda (obj)
5107 (cond ((memq obj (plist-get info :ignore-list)))
5108 ((null n) (throw 'exit obj))
5109 ((not (wholenump n)) (push obj prev))
5110 ((zerop n) (throw 'exit prev))
5111 (t (decf n) (push obj prev))))
5112 (cdr (memq blob (reverse siblings))))
5113 prev)))
5115 (defun org-export-get-next-element (blob info &optional n)
5116 "Return next element or object.
5118 BLOB is an element or object. INFO is a plist used as
5119 a communication channel. Return next exportable element or
5120 object, a string, or nil.
5122 When optional argument N is a positive integer, return a list
5123 containing up to N siblings after BLOB, from closest to farthest.
5124 With any other non-nil value, return a list containing all of
5125 them."
5126 (let ((siblings
5127 ;; An object can belong to the contents of its parent or to
5128 ;; a secondary string. We check the latter option first.
5129 (let ((parent (org-export-get-parent blob)))
5130 (or (and (not (memq (org-element-type blob)
5131 org-element-all-objects))
5132 (let ((sec-value
5133 (org-element-property
5134 (cdr (assq (org-element-type parent)
5135 org-element-secondary-value-alist))
5136 parent)))
5137 (cdr (memq blob sec-value))))
5138 (cdr (memq blob (org-element-contents parent))))))
5139 next)
5140 (catch 'exit
5141 (mapc (lambda (obj)
5142 (cond ((memq obj (plist-get info :ignore-list)))
5143 ((null n) (throw 'exit obj))
5144 ((not (wholenump n)) (push obj next))
5145 ((zerop n) (throw 'exit (nreverse next)))
5146 (t (decf n) (push obj next))))
5147 siblings)
5148 (nreverse next))))
5151 ;;;; Translation
5153 ;; `org-export-translate' translates a string according to language
5154 ;; specified by LANGUAGE keyword or `org-export-language-setup'
5155 ;; variable and a specified charset. `org-export-dictionary' contains
5156 ;; the dictionary used for the translation.
5158 (defconst org-export-dictionary
5159 '(("Author"
5160 ("ca" :default "Autor")
5161 ("cs" :default "Autor")
5162 ("da" :default "Ophavsmand")
5163 ("de" :default "Autor")
5164 ("eo" :html "A&#365;toro")
5165 ("es" :default "Autor")
5166 ("fi" :html "Tekij&auml;")
5167 ("fr" :default "Auteur")
5168 ("hu" :default "Szerz&otilde;")
5169 ("is" :html "H&ouml;fundur")
5170 ("it" :default "Autore")
5171 ("ja" :html "&#33879;&#32773;" :utf-8 "著者")
5172 ("nl" :default "Auteur")
5173 ("no" :default "Forfatter")
5174 ("nb" :default "Forfatter")
5175 ("nn" :default "Forfattar")
5176 ("pl" :default "Autor")
5177 ("ru" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5178 ("sv" :html "F&ouml;rfattare")
5179 ("uk" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5180 ("zh-CN" :html "&#20316;&#32773;" :utf-8 "作者")
5181 ("zh-TW" :html "&#20316;&#32773;" :utf-8 "作者"))
5182 ("Date"
5183 ("ca" :default "Data")
5184 ("cs" :default "Datum")
5185 ("da" :default "Dato")
5186 ("de" :default "Datum")
5187 ("eo" :default "Dato")
5188 ("es" :default "Fecha")
5189 ("fi" :html "P&auml;iv&auml;m&auml;&auml;r&auml;")
5190 ("hu" :html "D&aacute;tum")
5191 ("is" :default "Dagsetning")
5192 ("it" :default "Data")
5193 ("ja" :html "&#26085;&#20184;" :utf-8 "日付")
5194 ("nl" :default "Datum")
5195 ("no" :default "Dato")
5196 ("nb" :default "Dato")
5197 ("nn" :default "Dato")
5198 ("pl" :default "Data")
5199 ("ru" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5200 ("sv" :default "Datum")
5201 ("uk" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5202 ("zh-CN" :html "&#26085;&#26399;" :utf-8 "日期")
5203 ("zh-TW" :html "&#26085;&#26399;" :utf-8 "日期"))
5204 ("Equation"
5205 ("fr" :ascii "Equation" :default "Équation"))
5206 ("Figure")
5207 ("Footnotes"
5208 ("ca" :html "Peus de p&agrave;gina")
5209 ("cs" :default "Pozn\xe1mky pod carou")
5210 ("da" :default "Fodnoter")
5211 ("de" :html "Fu&szlig;noten")
5212 ("eo" :default "Piednotoj")
5213 ("es" :html "Pies de p&aacute;gina")
5214 ("fi" :default "Alaviitteet")
5215 ("fr" :default "Notes de bas de page")
5216 ("hu" :html "L&aacute;bjegyzet")
5217 ("is" :html "Aftanm&aacute;lsgreinar")
5218 ("it" :html "Note a pi&egrave; di pagina")
5219 ("ja" :html "&#33050;&#27880;" :utf-8 "脚注")
5220 ("nl" :default "Voetnoten")
5221 ("no" :default "Fotnoter")
5222 ("nb" :default "Fotnoter")
5223 ("nn" :default "Fotnotar")
5224 ("pl" :default "Przypis")
5225 ("ru" :html "&#1057;&#1085;&#1086;&#1089;&#1082;&#1080;" :utf-8 "Сноски")
5226 ("sv" :default "Fotnoter")
5227 ("uk" :html "&#1055;&#1088;&#1080;&#1084;&#1110;&#1090;&#1082;&#1080;"
5228 :utf-8 "Примітки")
5229 ("zh-CN" :html "&#33050;&#27880;" :utf-8 "脚注")
5230 ("zh-TW" :html "&#33139;&#35387;" :utf-8 "腳註"))
5231 ("List of Listings"
5232 ("fr" :default "Liste des programmes"))
5233 ("List of Tables"
5234 ("fr" :default "Liste des tableaux"))
5235 ("Listing %d:"
5236 ("fr"
5237 :ascii "Programme %d :" :default "Programme nº %d :"
5238 :latin1 "Programme %d :"))
5239 ("Listing %d: %s"
5240 ("fr"
5241 :ascii "Programme %d : %s" :default "Programme nº %d : %s"
5242 :latin1 "Programme %d : %s"))
5243 ("See section %s"
5244 ("fr" :default "cf. section %s"))
5245 ("Table %d:"
5246 ("fr"
5247 :ascii "Tableau %d :" :default "Tableau nº %d :" :latin1 "Tableau %d :"))
5248 ("Table %d: %s"
5249 ("fr"
5250 :ascii "Tableau %d : %s" :default "Tableau nº %d : %s"
5251 :latin1 "Tableau %d : %s"))
5252 ("Table of Contents"
5253 ("ca" :html "&Iacute;ndex")
5254 ("cs" :default "Obsah")
5255 ("da" :default "Indhold")
5256 ("de" :default "Inhaltsverzeichnis")
5257 ("eo" :default "Enhavo")
5258 ("es" :html "&Iacute;ndice")
5259 ("fi" :html "Sis&auml;llysluettelo")
5260 ("fr" :ascii "Sommaire" :default "Table des matières")
5261 ("hu" :html "Tartalomjegyz&eacute;k")
5262 ("is" :default "Efnisyfirlit")
5263 ("it" :default "Indice")
5264 ("ja" :html "&#30446;&#27425;" :utf-8 "目次")
5265 ("nl" :default "Inhoudsopgave")
5266 ("no" :default "Innhold")
5267 ("nb" :default "Innhold")
5268 ("nn" :default "Innhald")
5269 ("pl" :html "Spis tre&#x015b;ci")
5270 ("ru" :html "&#1057;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1077;"
5271 :utf-8 "Содержание")
5272 ("sv" :html "Inneh&aring;ll")
5273 ("uk" :html "&#1047;&#1084;&#1110;&#1089;&#1090;" :utf-8 "Зміст")
5274 ("zh-CN" :html "&#30446;&#24405;" :utf-8 "目录")
5275 ("zh-TW" :html "&#30446;&#37636;" :utf-8 "目錄"))
5276 ("Unknown reference"
5277 ("fr" :ascii "Destination inconnue" :default "Référence inconnue")))
5278 "Dictionary for export engine.
5280 Alist whose CAR is the string to translate and CDR is an alist
5281 whose CAR is the language string and CDR is a plist whose
5282 properties are possible charsets and values translated terms.
5284 It is used as a database for `org-export-translate'. Since this
5285 function returns the string as-is if no translation was found,
5286 the variable only needs to record values different from the
5287 entry.")
5289 (defun org-export-translate (s encoding info)
5290 "Translate string S according to language specification.
5292 ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1'
5293 and `:utf-8'. INFO is a plist used as a communication channel.
5295 Translation depends on `:language' property. Return the
5296 translated string. If no translation is found, try to fall back
5297 to `:default' encoding. If it fails, return S."
5298 (let* ((lang (plist-get info :language))
5299 (translations (cdr (assoc lang
5300 (cdr (assoc s org-export-dictionary))))))
5301 (or (plist-get translations encoding)
5302 (plist-get translations :default)
5303 s)))
5307 ;;; Asynchronous Export
5309 ;; `org-export-async-start' is the entry point for asynchronous
5310 ;; export. It recreates current buffer (including visibility,
5311 ;; narrowing and visited file) in an external Emacs process, and
5312 ;; evaluates a command there. It then applies a function on the
5313 ;; returned results in the current process.
5315 ;; Asynchronously generated results are never displayed directly.
5316 ;; Instead, they are stored in `org-export-stack-contents'. They can
5317 ;; then be retrieved by calling `org-export-stack'.
5319 ;; Export Stack is viewed through a dedicated major mode
5320 ;;`org-export-stack-mode' and tools: `org-export-stack-refresh',
5321 ;;`org-export-stack-delete', `org-export-stack-view' and
5322 ;;`org-export-stack-clear'.
5324 ;; For back-ends, `org-export-add-to-stack' add a new source to stack.
5325 ;; It should used whenever `org-export-async-start' is called.
5327 (defmacro org-export-async-start (fun &rest body)
5328 "Call function FUN on the results returned by BODY evaluation.
5330 BODY evaluation happens in an asynchronous process, from a buffer
5331 which is an exact copy of the current one.
5333 Use `org-export-add-to-stack' in FUN in order to register results
5334 in the stack. Examples for, respectively a temporary buffer and
5335 a file are:
5337 \(org-export-async-start
5338 \(lambda (output)
5339 \(with-current-buffer (get-buffer-create \"*Org BACKEND Export*\")
5340 \(erase-buffer)
5341 \(insert output)
5342 \(goto-char (point-min))
5343 \(org-export-add-to-stack (current-buffer) 'backend)))
5344 `(org-export-as 'backend ,subtreep ,visible-only ,body-only ',ext-plist))
5348 \(org-export-async-start
5349 \(lambda (f) (org-export-add-to-stack f 'backend))
5350 `(expand-file-name
5351 \(org-export-to-file
5352 'backend ,outfile ,subtreep ,visible-only ,body-only ',ext-plist)))"
5353 (declare (indent 1) (debug t))
5354 (org-with-gensyms (process temp-file copy-fun proc-buffer handler coding)
5355 ;; Write the full sexp evaluating BODY in a copy of the current
5356 ;; buffer to a temporary file, as it may be too long for program
5357 ;; args in `start-process'.
5358 `(with-temp-message "Initializing asynchronous export process"
5359 (let ((,copy-fun (org-export--generate-copy-script (current-buffer)))
5360 (,temp-file (make-temp-file "org-export-process"))
5361 (,coding buffer-file-coding-system))
5362 (with-temp-file ,temp-file
5363 (insert
5364 ;; Null characters (from variable values) are inserted
5365 ;; within the file. As a consequence, coding system for
5366 ;; buffer contents will not be recognized properly. So,
5367 ;; we make sure it is the same as the one used to display
5368 ;; the original buffer.
5369 (format ";; -*- coding: %s; -*-\n%S"
5370 ,coding
5371 `(with-temp-buffer
5372 ,(when org-export-async-debug '(setq debug-on-error t))
5373 ;; Ignore `kill-emacs-hook' and code evaluation
5374 ;; queries from Babel as we need a truly
5375 ;; non-interactive process.
5376 (setq kill-emacs-hook nil
5377 org-babel-confirm-evaluate-answer-no t)
5378 ;; Initialize export framework.
5379 (require 'ox)
5380 ;; Re-create current buffer there.
5381 (funcall ,,copy-fun)
5382 (restore-buffer-modified-p nil)
5383 ;; Sexp to evaluate in the buffer.
5384 (print (progn ,,@body))))))
5385 ;; Start external process.
5386 (let* ((process-connection-type nil)
5387 (,proc-buffer (generate-new-buffer-name "*Org Export Process*"))
5388 (,process
5389 (start-process
5390 "org-export-process" ,proc-buffer
5391 (expand-file-name invocation-name invocation-directory)
5392 "-Q" "--batch"
5393 "-l" org-export-async-init-file
5394 "-l" ,temp-file)))
5395 ;; Register running process in stack.
5396 (org-export-add-to-stack (get-buffer ,proc-buffer) nil ,process)
5397 ;; Set-up sentinel in order to catch results.
5398 (set-process-sentinel
5399 ,process
5400 (let ((handler ',fun))
5401 `(lambda (p status)
5402 (let ((proc-buffer (process-buffer p)))
5403 (when (eq (process-status p) 'exit)
5404 (unwind-protect
5405 (if (zerop (process-exit-status p))
5406 (unwind-protect
5407 (let ((results
5408 (with-current-buffer proc-buffer
5409 (goto-char (point-max))
5410 (backward-sexp)
5411 (read (current-buffer)))))
5412 (funcall ,handler results))
5413 (unless org-export-async-debug
5414 (and (get-buffer proc-buffer)
5415 (kill-buffer proc-buffer))))
5416 (org-export-add-to-stack proc-buffer nil p)
5417 (ding)
5418 (message "Process '%s' exited abnormally" p))
5419 (unless org-export-async-debug
5420 (delete-file ,,temp-file)))))))))))))
5422 (defun org-export-add-to-stack (source backend &optional process)
5423 "Add a new result to export stack if not present already.
5425 SOURCE is a buffer or a file name containing export results.
5426 BACKEND is a symbol representing export back-end used to generate
5429 Entries already pointing to SOURCE and unavailable entries are
5430 removed beforehand. Return the new stack."
5431 (setq org-export-stack-contents
5432 (cons (list source backend (or process (current-time)))
5433 (org-export-stack-remove source))))
5435 (defun org-export-stack ()
5436 "Menu for asynchronous export results and running processes."
5437 (interactive)
5438 (let ((buffer (get-buffer-create "*Org Export Stack*")))
5439 (set-buffer buffer)
5440 (when (zerop (buffer-size)) (org-export-stack-mode))
5441 (org-export-stack-refresh)
5442 (pop-to-buffer buffer))
5443 (message "Type \"q\" to quit, \"?\" for help"))
5445 (defun org-export--stack-source-at-point ()
5446 "Return source from export results at point in stack."
5447 (let ((source (car (nth (1- (org-current-line)) org-export-stack-contents))))
5448 (if (not source) (error "Source unavailable, please refresh buffer")
5449 (let ((source-name (if (stringp source) source (buffer-name source))))
5450 (if (save-excursion
5451 (beginning-of-line)
5452 (looking-at (concat ".* +" (regexp-quote source-name) "$")))
5453 source
5454 ;; SOURCE is not consistent with current line. The stack
5455 ;; view is outdated.
5456 (error "Source unavailable; type `g' to update buffer"))))))
5458 (defun org-export-stack-clear ()
5459 "Remove all entries from export stack."
5460 (interactive)
5461 (setq org-export-stack-contents nil))
5463 (defun org-export-stack-refresh (&rest dummy)
5464 "Refresh the asynchronous export stack.
5465 DUMMY is ignored. Unavailable sources are removed from the list.
5466 Return the new stack."
5467 (let ((inhibit-read-only t))
5468 (org-preserve-lc
5469 (erase-buffer)
5470 (insert (concat
5471 (let ((counter 0))
5472 (mapconcat
5473 (lambda (entry)
5474 (let ((proc-p (processp (nth 2 entry))))
5475 (concat
5476 ;; Back-end.
5477 (format " %-12s " (or (nth 1 entry) ""))
5478 ;; Age.
5479 (let ((data (nth 2 entry)))
5480 (if proc-p (format " %6s " (process-status data))
5481 ;; Compute age of the results.
5482 (org-format-seconds
5483 "%4h:%.2m "
5484 (float-time (time-since data)))))
5485 ;; Source.
5486 (format " %s"
5487 (let ((source (car entry)))
5488 (if (stringp source) source
5489 (buffer-name source)))))))
5490 ;; Clear stack from exited processes, dead buffers or
5491 ;; non-existent files.
5492 (setq org-export-stack-contents
5493 (org-remove-if-not
5494 (lambda (el)
5495 (if (processp (nth 2 el))
5496 (buffer-live-p (process-buffer (nth 2 el)))
5497 (let ((source (car el)))
5498 (if (bufferp source) (buffer-live-p source)
5499 (file-exists-p source)))))
5500 org-export-stack-contents)) "\n")))))))
5502 (defun org-export-stack-remove (&optional source)
5503 "Remove export results at point from stack.
5504 If optional argument SOURCE is non-nil, remove it instead."
5505 (interactive)
5506 (let ((source (or source (org-export--stack-source-at-point))))
5507 (setq org-export-stack-contents
5508 (org-remove-if (lambda (el) (equal (car el) source))
5509 org-export-stack-contents))))
5511 (defun org-export-stack-view (&optional in-emacs)
5512 "View export results at point in stack.
5513 With an optional prefix argument IN-EMACS, force viewing files
5514 within Emacs."
5515 (interactive "P")
5516 (let ((source (org-export--stack-source-at-point)))
5517 (cond ((processp source)
5518 (org-switch-to-buffer-other-window (process-buffer source)))
5519 ((bufferp source) (org-switch-to-buffer-other-window source))
5520 (t (org-open-file source in-emacs)))))
5522 (defconst org-export-stack-mode-map
5523 (let ((km (make-sparse-keymap)))
5524 (define-key km " " 'next-line)
5525 (define-key km "n" 'next-line)
5526 (define-key km "\C-n" 'next-line)
5527 (define-key km [down] 'next-line)
5528 (define-key km "p" 'previous-line)
5529 (define-key km "\C-p" 'previous-line)
5530 (define-key km "\C-?" 'previous-line)
5531 (define-key km [up] 'previous-line)
5532 (define-key km "C" 'org-export-stack-clear)
5533 (define-key km "v" 'org-export-stack-view)
5534 (define-key km (kbd "RET") 'org-export-stack-view)
5535 (define-key km "d" 'org-export-stack-remove)
5537 "Keymap for Org Export Stack.")
5539 (define-derived-mode org-export-stack-mode special-mode "Org-Stack"
5540 "Mode for displaying asynchronous export stack.
5542 Type \\[org-export-stack] to visualize the asynchronous export
5543 stack.
5545 In an Org Export Stack buffer, use \\<org-export-stack-mode-map>\\[org-export-stack-view] to view export output
5546 on current line, \\[org-export-stack-remove] to remove it from the stack and \\[org-export-stack-clear] to clear
5547 stack completely.
5549 Removing entries in an Org Export Stack buffer doesn't affect
5550 files or buffers, only the display.
5552 \\{org-export-stack-mode-map}"
5553 (abbrev-mode 0)
5554 (auto-fill-mode 0)
5555 (setq buffer-read-only t
5556 buffer-undo-list t
5557 truncate-lines t
5558 header-line-format
5559 '(:eval
5560 (format " %-12s | %6s | %s" "Back-End" "Age" "Source")))
5561 (add-hook 'post-command-hook 'org-export-stack-refresh nil t)
5562 (set (make-local-variable 'revert-buffer-function)
5563 'org-export-stack-refresh))
5567 ;;; The Dispatcher
5569 ;; `org-export-dispatch' is the standard interactive way to start an
5570 ;; export process. It uses `org-export--dispatch-ui' as a subroutine
5571 ;; for its interface, which, in turn, delegates response to key
5572 ;; pressed to `org-export--dispatch-action'.
5574 ;;;###autoload
5575 (defun org-export-dispatch (&optional arg)
5576 "Export dispatcher for Org mode.
5578 It provides an access to common export related tasks in a buffer.
5579 Its interface comes in two flavours: standard and expert.
5581 While both share the same set of bindings, only the former
5582 displays the valid keys associations in a dedicated buffer.
5583 Scrolling (resp. line-wise motion) in this buffer is done with
5584 SPC and DEL (resp. C-n and C-p) keys.
5586 Set variable `org-export-dispatch-use-expert-ui' to switch to one
5587 flavour or the other.
5589 When ARG is \\[universal-argument], repeat the last export action, with the same set
5590 of options used back then, on the current buffer.
5592 When ARG is \\[universal-argument] \\[universal-argument], display the asynchronous export stack."
5593 (interactive "P")
5594 (let* ((input
5595 (cond ((equal arg '(16)) '(stack))
5596 ((and arg org-export-dispatch-last-action))
5597 (t (save-window-excursion
5598 (unwind-protect
5599 (progn
5600 ;; Remember where we are
5601 (move-marker org-export-dispatch-last-position
5602 (point)
5603 (org-base-buffer (current-buffer)))
5604 ;; Get and store an export command
5605 (setq org-export-dispatch-last-action
5606 (org-export--dispatch-ui
5607 (list org-export-initial-scope
5608 (and org-export-in-background 'async))
5610 org-export-dispatch-use-expert-ui)))
5611 (and (get-buffer "*Org Export Dispatcher*")
5612 (kill-buffer "*Org Export Dispatcher*")))))))
5613 (action (car input))
5614 (optns (cdr input)))
5615 (unless (memq 'subtree optns)
5616 (move-marker org-export-dispatch-last-position nil))
5617 (case action
5618 ;; First handle special hard-coded actions.
5619 (template (org-export-insert-default-template nil optns))
5620 (stack (org-export-stack))
5621 (publish-current-file
5622 (org-publish-current-file (memq 'force optns) (memq 'async optns)))
5623 (publish-current-project
5624 (org-publish-current-project (memq 'force optns) (memq 'async optns)))
5625 (publish-choose-project
5626 (org-publish (assoc (org-icompleting-read
5627 "Publish project: "
5628 org-publish-project-alist nil t)
5629 org-publish-project-alist)
5630 (memq 'force optns)
5631 (memq 'async optns)))
5632 (publish-all (org-publish-all (memq 'force optns) (memq 'async optns)))
5633 (otherwise
5634 (save-excursion
5635 (when arg
5636 ;; Repeating command, maybe move cursor to restore subtree
5637 ;; context.
5638 (if (eq (marker-buffer org-export-dispatch-last-position)
5639 (org-base-buffer (current-buffer)))
5640 (goto-char org-export-dispatch-last-position)
5641 ;; We are in a different buffer, forget position.
5642 (move-marker org-export-dispatch-last-position nil)))
5643 (funcall action
5644 ;; Return a symbol instead of a list to ease
5645 ;; asynchronous export macro use.
5646 (and (memq 'async optns) t)
5647 (and (memq 'subtree optns) t)
5648 (and (memq 'visible optns) t)
5649 (and (memq 'body optns) t)))))))
5651 (defun org-export--dispatch-ui (options first-key expertp)
5652 "Handle interface for `org-export-dispatch'.
5654 OPTIONS is a list containing current interactive options set for
5655 export. It can contain any of the following symbols:
5656 `body' toggles a body-only export
5657 `subtree' restricts export to current subtree
5658 `visible' restricts export to visible part of buffer.
5659 `force' force publishing files.
5660 `async' use asynchronous export process
5662 FIRST-KEY is the key pressed to select the first level menu. It
5663 is nil when this menu hasn't been selected yet.
5665 EXPERTP, when non-nil, triggers expert UI. In that case, no help
5666 buffer is provided, but indications about currently active
5667 options are given in the prompt. Moreover, \[?] allows to switch
5668 back to standard interface."
5669 (let* ((fontify-key
5670 (lambda (key &optional access-key)
5671 ;; Fontify KEY string. Optional argument ACCESS-KEY, when
5672 ;; non-nil is the required first-level key to activate
5673 ;; KEY. When its value is t, activate KEY independently
5674 ;; on the first key, if any. A nil value means KEY will
5675 ;; only be activated at first level.
5676 (if (or (eq access-key t) (eq access-key first-key))
5677 (org-propertize key 'face 'org-warning)
5678 key)))
5679 (fontify-value
5680 (lambda (value)
5681 ;; Fontify VALUE string.
5682 (org-propertize value 'face 'font-lock-variable-name-face)))
5683 ;; Prepare menu entries by extracting them from
5684 ;; `org-export-registered-backends', and sorting them by
5685 ;; access key and by ordinal, if any.
5686 (backends
5687 (sort
5688 (sort
5689 (delq nil
5690 (mapcar
5691 (lambda (b)
5692 (let ((name (car b)))
5693 (catch 'ignored
5694 ;; Ignore any back-end belonging to
5695 ;; `org-export-invisible-backends' or derived
5696 ;; from one of them.
5697 (dolist (ignored org-export-invisible-backends)
5698 (when (org-export-derived-backend-p name ignored)
5699 (throw 'ignored nil)))
5700 (org-export-backend-menu name))))
5701 org-export-registered-backends))
5702 (lambda (a b)
5703 (let ((key-a (nth 1 a))
5704 (key-b (nth 1 b)))
5705 (cond ((and (numberp key-a) (numberp key-b))
5706 (< key-a key-b))
5707 ((numberp key-b) t)))))
5708 (lambda (a b) (< (car a) (car b)))))
5709 ;; Compute a list of allowed keys based on the first key
5710 ;; pressed, if any. Some keys
5711 ;; (?^B, ?^V, ?^S, ?^F, ?^A, ?&, ?# and ?q) are always
5712 ;; available.
5713 (allowed-keys
5714 (nconc (list 2 22 19 6 1)
5715 (if (not first-key) (org-uniquify (mapcar 'car backends))
5716 (let (sub-menu)
5717 (dolist (backend backends (sort (mapcar 'car sub-menu) '<))
5718 (when (eq (car backend) first-key)
5719 (setq sub-menu (append (nth 2 backend) sub-menu))))))
5720 (cond ((eq first-key ?P) (list ?f ?p ?x ?a))
5721 ((not first-key) (list ?P)))
5722 (list ?& ?#)
5723 (when expertp (list ??))
5724 (list ?q)))
5725 ;; Build the help menu for standard UI.
5726 (help
5727 (unless expertp
5728 (concat
5729 ;; Options are hard-coded.
5730 (format "[%s] Body only: %s [%s] Visible only: %s
5731 \[%s] Export scope: %s [%s] Force publishing: %s
5732 \[%s] Async export: %s\n\n"
5733 (funcall fontify-key "C-b" t)
5734 (funcall fontify-value
5735 (if (memq 'body options) "On " "Off"))
5736 (funcall fontify-key "C-v" t)
5737 (funcall fontify-value
5738 (if (memq 'visible options) "On " "Off"))
5739 (funcall fontify-key "C-s" t)
5740 (funcall fontify-value
5741 (if (memq 'subtree options) "Subtree" "Buffer "))
5742 (funcall fontify-key "C-f" t)
5743 (funcall fontify-value
5744 (if (memq 'force options) "On " "Off"))
5745 (funcall fontify-key "C-a" t)
5746 (funcall fontify-value
5747 (if (memq 'async options) "On " "Off")))
5748 ;; Display registered back-end entries. When a key
5749 ;; appears for the second time, do not create another
5750 ;; entry, but append its sub-menu to existing menu.
5751 (let (last-key)
5752 (mapconcat
5753 (lambda (entry)
5754 (let ((top-key (car entry)))
5755 (concat
5756 (unless (eq top-key last-key)
5757 (setq last-key top-key)
5758 (format "\n[%s] %s\n"
5759 (funcall fontify-key (char-to-string top-key))
5760 (nth 1 entry)))
5761 (let ((sub-menu (nth 2 entry)))
5762 (unless (functionp sub-menu)
5763 ;; Split sub-menu into two columns.
5764 (let ((index -1))
5765 (concat
5766 (mapconcat
5767 (lambda (sub-entry)
5768 (incf index)
5769 (format
5770 (if (zerop (mod index 2)) " [%s] %-26s"
5771 "[%s] %s\n")
5772 (funcall fontify-key
5773 (char-to-string (car sub-entry))
5774 top-key)
5775 (nth 1 sub-entry)))
5776 sub-menu "")
5777 (when (zerop (mod index 2)) "\n"))))))))
5778 backends ""))
5779 ;; Publishing menu is hard-coded.
5780 (format "\n[%s] Publish
5781 [%s] Current file [%s] Current project
5782 [%s] Choose project [%s] All projects\n\n\n"
5783 (funcall fontify-key "P")
5784 (funcall fontify-key "f" ?P)
5785 (funcall fontify-key "p" ?P)
5786 (funcall fontify-key "x" ?P)
5787 (funcall fontify-key "a" ?P))
5788 (format "[%s] Export stack [%s] Insert template\n"
5789 (funcall fontify-key "&" t)
5790 (funcall fontify-key "#" t))
5791 (format "[%s] %s"
5792 (funcall fontify-key "q" t)
5793 (if first-key "Main menu" "Exit")))))
5794 ;; Build prompts for both standard and expert UI.
5795 (standard-prompt (unless expertp "Export command: "))
5796 (expert-prompt
5797 (when expertp
5798 (format
5799 "Export command (C-%s%s%s%s%s) [%s]: "
5800 (if (memq 'body options) (funcall fontify-key "b" t) "b")
5801 (if (memq 'visible options) (funcall fontify-key "v" t) "v")
5802 (if (memq 'subtree options) (funcall fontify-key "s" t) "s")
5803 (if (memq 'force options) (funcall fontify-key "f" t) "f")
5804 (if (memq 'async options) (funcall fontify-key "a" t) "a")
5805 (mapconcat (lambda (k)
5806 ;; Strip control characters.
5807 (unless (< k 27) (char-to-string k)))
5808 allowed-keys "")))))
5809 ;; With expert UI, just read key with a fancy prompt. In standard
5810 ;; UI, display an intrusive help buffer.
5811 (if expertp
5812 (org-export--dispatch-action
5813 expert-prompt allowed-keys backends options first-key expertp)
5814 ;; At first call, create frame layout in order to display menu.
5815 (unless (get-buffer "*Org Export Dispatcher*")
5816 (delete-other-windows)
5817 (org-switch-to-buffer-other-window
5818 (get-buffer-create "*Org Export Dispatcher*"))
5819 (setq cursor-type nil
5820 header-line-format "Use SPC, DEL, C-n or C-p to navigate.")
5821 ;; Make sure that invisible cursor will not highlight square
5822 ;; brackets.
5823 (set-syntax-table (copy-syntax-table))
5824 (modify-syntax-entry ?\[ "w"))
5825 ;; At this point, the buffer containing the menu exists and is
5826 ;; visible in the current window. So, refresh it.
5827 (with-current-buffer "*Org Export Dispatcher*"
5828 ;; Refresh help. Maintain display continuity by re-visiting
5829 ;; previous window position.
5830 (let ((pos (window-start)))
5831 (erase-buffer)
5832 (insert help)
5833 (set-window-start nil pos)))
5834 (org-fit-window-to-buffer)
5835 (org-export--dispatch-action
5836 standard-prompt allowed-keys backends options first-key expertp))))
5838 (defun org-export--dispatch-action
5839 (prompt allowed-keys backends options first-key expertp)
5840 "Read a character from command input and act accordingly.
5842 PROMPT is the displayed prompt, as a string. ALLOWED-KEYS is
5843 a list of characters available at a given step in the process.
5844 BACKENDS is a list of menu entries. OPTIONS, FIRST-KEY and
5845 EXPERTP are the same as defined in `org-export--dispatch-ui',
5846 which see.
5848 Toggle export options when required. Otherwise, return value is
5849 a list with action as CAR and a list of interactive export
5850 options as CDR."
5851 (let (key)
5852 ;; Scrolling: when in non-expert mode, act on motion keys (C-n,
5853 ;; C-p, SPC, DEL).
5854 (while (and (setq key (read-char-exclusive prompt))
5855 (not expertp)
5856 (memq key '(14 16 ?\s ?\d)))
5857 (case key
5858 (14 (if (not (pos-visible-in-window-p (point-max)))
5859 (ignore-errors (scroll-up-line))
5860 (message "End of buffer")
5861 (sit-for 1)))
5862 (16 (if (not (pos-visible-in-window-p (point-min)))
5863 (ignore-errors (scroll-down-line))
5864 (message "Beginning of buffer")
5865 (sit-for 1)))
5866 (?\s (if (not (pos-visible-in-window-p (point-max)))
5867 (scroll-up nil)
5868 (message "End of buffer")
5869 (sit-for 1)))
5870 (?\d (if (not (pos-visible-in-window-p (point-min)))
5871 (scroll-down nil)
5872 (message "Beginning of buffer")
5873 (sit-for 1)))))
5874 (cond
5875 ;; Ignore undefined associations.
5876 ((not (memq key allowed-keys))
5877 (ding)
5878 (unless expertp (message "Invalid key") (sit-for 1))
5879 (org-export--dispatch-ui options first-key expertp))
5880 ;; q key at first level aborts export. At second level, cancel
5881 ;; first key instead.
5882 ((eq key ?q) (if (not first-key) (error "Export aborted")
5883 (org-export--dispatch-ui options nil expertp)))
5884 ;; Help key: Switch back to standard interface if expert UI was
5885 ;; active.
5886 ((eq key ??) (org-export--dispatch-ui options first-key nil))
5887 ;; Send request for template insertion along with export scope.
5888 ((eq key ?#) (cons 'template (memq 'subtree options)))
5889 ;; Switch to asynchronous export stack.
5890 ((eq key ?&) '(stack))
5891 ;; Toggle options: C-b (2) C-v (22) C-s (19) C-f (6) C-a (1).
5892 ((memq key '(2 22 19 6 1))
5893 (org-export--dispatch-ui
5894 (let ((option (case key (2 'body) (22 'visible) (19 'subtree)
5895 (6 'force) (1 'async))))
5896 (if (memq option options) (remq option options)
5897 (cons option options)))
5898 first-key expertp))
5899 ;; Action selected: Send key and options back to
5900 ;; `org-export-dispatch'.
5901 ((or first-key (functionp (nth 2 (assq key backends))))
5902 (cons (cond
5903 ((not first-key) (nth 2 (assq key backends)))
5904 ;; Publishing actions are hard-coded. Send a special
5905 ;; signal to `org-export-dispatch'.
5906 ((eq first-key ?P)
5907 (case key
5908 (?f 'publish-current-file)
5909 (?p 'publish-current-project)
5910 (?x 'publish-choose-project)
5911 (?a 'publish-all)))
5912 ;; Return first action associated to FIRST-KEY + KEY
5913 ;; path. Indeed, derived backends can share the same
5914 ;; FIRST-KEY.
5915 (t (catch 'found
5916 (mapc (lambda (backend)
5917 (let ((match (assq key (nth 2 backend))))
5918 (when match (throw 'found (nth 2 match)))))
5919 (member (assq first-key backends) backends)))))
5920 options))
5921 ;; Otherwise, enter sub-menu.
5922 (t (org-export--dispatch-ui options key expertp)))))
5926 (provide 'ox)
5928 ;; Local variables:
5929 ;; generated-autoload-file: "org-loaddefs.el"
5930 ;; End:
5932 ;;; ox.el ends here