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