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