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