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