org.texi (Installation): Detail instructions when installing through ELPA
[org-mode.git] / lisp / ox.el
blob40c0617dab7e43c1f4f77234b1bcd71afa7b6b07
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 t
752 "Non-nil means exported stuff will also be pushed onto the kill ring."
753 :group 'org-export-general
754 :type 'boolean)
756 (defcustom org-export-initial-scope 'buffer
757 "The initial scope when exporting with `org-export-dispatch'.
758 This variable can be either set to `buffer' or `subtree'."
759 :group 'org-export-general
760 :type '(choice
761 (const :tag "Export current buffer" 'buffer)
762 (const :tag "Export current subtree" 'subtree)))
764 (defcustom org-export-show-temporary-export-buffer t
765 "Non-nil means show buffer after exporting to temp buffer.
766 When Org exports to a file, the buffer visiting that file is ever
767 shown, but remains buried. However, when exporting to
768 a temporary buffer, that buffer is popped up in a second window.
769 When this variable is nil, the buffer remains buried also in
770 these cases."
771 :group 'org-export-general
772 :type 'boolean)
774 (defcustom org-export-in-background nil
775 "Non-nil means export and publishing commands will run in background.
776 Results from an asynchronous export are never displayed
777 automatically. But you can retrieve them with \\[org-export-stack]."
778 :group 'org-export-general
779 :version "24.4"
780 :package-version '(Org . "8.0")
781 :type 'boolean)
783 (defcustom org-export-async-init-file user-init-file
784 "File used to initialize external export process.
785 Value must be an absolute file name. It defaults to user's
786 initialization file. Though, a specific configuration makes the
787 process faster and the export more portable."
788 :group 'org-export-general
789 :version "24.4"
790 :package-version '(Org . "8.0")
791 :type '(file :must-match t))
793 (defcustom org-export-invisible-backends nil
794 "List of back-ends that shouldn't appear in the dispatcher.
796 Any back-end belonging to this list or derived from a back-end
797 belonging to it will not appear in the dispatcher menu.
799 Indeed, Org may require some export back-ends without notice. If
800 these modules are never to be used interactively, adding them
801 here will avoid cluttering the dispatcher menu."
802 :group 'org-export-general
803 :version "24.4"
804 :package-version '(Org . "8.0")
805 :type '(repeat (symbol :tag "Back-End")))
807 (defcustom org-export-dispatch-use-expert-ui nil
808 "Non-nil means using a non-intrusive `org-export-dispatch'.
809 In that case, no help buffer is displayed. Though, an indicator
810 for current export scope is added to the prompt (\"b\" when
811 output is restricted to body only, \"s\" when it is restricted to
812 the current subtree, \"v\" when only visible elements are
813 considered for export, \"f\" when publishing functions should be
814 passed the FORCE argument and \"a\" when the export should be
815 asynchronous). Also, \[?] allows to switch back to standard
816 mode."
817 :group 'org-export-general
818 :version "24.4"
819 :package-version '(Org . "8.0")
820 :type 'boolean)
824 ;;; Defining Back-ends
826 ;; `org-export-define-backend' is the standard way to define an export
827 ;; back-end. It allows to specify translators, filters, buffer
828 ;; options and a menu entry. If the new back-end shares translators
829 ;; with another back-end, `org-export-define-derived-backend' may be
830 ;; used instead.
832 ;; Internally, a back-end is stored as a list, of which CAR is the
833 ;; name of the back-end, as a symbol, and CDR a plist. Accessors to
834 ;; properties of a given back-end are: `org-export-backend-filters',
835 ;; `org-export-backend-menu', `org-export-backend-options' and
836 ;; `org-export-backend-translate-table'.
838 ;; Eventually `org-export-barf-if-invalid-backend' returns an error
839 ;; when a given back-end hasn't been registered yet.
841 (defmacro org-export-define-backend (backend translators &rest body)
842 "Define a new back-end BACKEND.
844 TRANSLATORS is an alist between object or element types and
845 functions handling them.
847 These functions should return a string without any trailing
848 space, or nil. They must accept three arguments: the object or
849 element itself, its contents or nil when it isn't recursive and
850 the property list used as a communication channel.
852 Contents, when not nil, are stripped from any global indentation
853 \(although the relative one is preserved). They also always end
854 with a single newline character.
856 If, for a given type, no function is found, that element or
857 object type will simply be ignored, along with any blank line or
858 white space at its end. The same will happen if the function
859 returns the nil value. If that function returns the empty
860 string, the type will be ignored, but the blank lines or white
861 spaces will be kept.
863 In addition to element and object types, one function can be
864 associated to the `template' (or `inner-template') symbol and
865 another one to the `plain-text' symbol.
867 The former returns the final transcoded string, and can be used
868 to add a preamble and a postamble to document's body. It must
869 accept two arguments: the transcoded string and the property list
870 containing export options. A function associated to `template'
871 will not be applied if export has option \"body-only\".
872 A function associated to `inner-template' is always applied.
874 The latter, when defined, is to be called on every text not
875 recognized as an element or an object. It must accept two
876 arguments: the text string and the information channel. It is an
877 appropriate place to protect special chars relative to the
878 back-end.
880 BODY can start with pre-defined keyword arguments. The following
881 keywords are understood:
883 :export-block
885 String, or list of strings, representing block names that
886 will not be parsed. This is used to specify blocks that will
887 contain raw code specific to the back-end. These blocks
888 still have to be handled by the relative `export-block' type
889 translator.
891 :filters-alist
893 Alist between filters and function, or list of functions,
894 specific to the back-end. See `org-export-filters-alist' for
895 a list of all allowed filters. Filters defined here
896 shouldn't make a back-end test, as it may prevent back-ends
897 derived from this one to behave properly.
899 :menu-entry
901 Menu entry for the export dispatcher. It should be a list
902 like:
904 \(KEY DESCRIPTION-OR-ORDINAL ACTION-OR-MENU)
906 where :
908 KEY is a free character selecting the back-end.
910 DESCRIPTION-OR-ORDINAL is either a string or a number.
912 If it is a string, is will be used to name the back-end in
913 its menu entry. If it is a number, the following menu will
914 be displayed as a sub-menu of the back-end with the same
915 KEY. Also, the number will be used to determine in which
916 order such sub-menus will appear (lowest first).
918 ACTION-OR-MENU is either a function or an alist.
920 If it is an action, it will be called with four
921 arguments (booleans): ASYNC, SUBTREEP, VISIBLE-ONLY and
922 BODY-ONLY. See `org-export-as' for further explanations on
923 some of them.
925 If it is an alist, associations should follow the
926 pattern:
928 \(KEY DESCRIPTION ACTION)
930 where KEY, DESCRIPTION and ACTION are described above.
932 Valid values include:
934 \(?m \"My Special Back-end\" my-special-export-function)
938 \(?l \"Export to LaTeX\"
939 \(?p \"As PDF file\" org-latex-export-to-pdf)
940 \(?o \"As PDF file and open\"
941 \(lambda (a s v b)
942 \(if a (org-latex-export-to-pdf t s v b)
943 \(org-open-file
944 \(org-latex-export-to-pdf nil s v b)))))))
946 or the following, which will be added to the previous
947 sub-menu,
949 \(?l 1
950 \((?B \"As TEX buffer (Beamer)\" org-beamer-export-as-latex)
951 \(?P \"As PDF file (Beamer)\" org-beamer-export-to-pdf)))
953 :options-alist
955 Alist between back-end specific properties introduced in
956 communication channel and how their value are acquired. See
957 `org-export-options-alist' for more information about
958 structure of the values."
959 (declare (debug (&define name sexp [&rest [keywordp sexp]] defbody))
960 (indent 1))
961 (let (export-block filters menu-entry options contents)
962 (while (keywordp (car body))
963 (case (pop body)
964 (:export-block (let ((names (pop body)))
965 (setq export-block
966 (if (consp names) (mapcar 'upcase names)
967 (list (upcase names))))))
968 (:filters-alist (setq filters (pop body)))
969 (:menu-entry (setq menu-entry (pop body)))
970 (:options-alist (setq options (pop body)))
971 (t (pop body))))
972 (setq contents (append (list :translate-alist translators)
973 (and filters (list :filters-alist filters))
974 (and options (list :options-alist options))
975 (and menu-entry (list :menu-entry menu-entry))))
976 `(progn
977 ;; Register back-end.
978 (let ((registeredp (assq ',backend org-export-registered-backends)))
979 (if registeredp (setcdr registeredp ',contents)
980 (push (cons ',backend ',contents) org-export-registered-backends)))
981 ;; Tell parser to not parse EXPORT-BLOCK blocks.
982 ,(when export-block
983 `(mapc
984 (lambda (name)
985 (add-to-list 'org-element-block-name-alist
986 `(,name . org-element-export-block-parser)))
987 ',export-block))
988 ;; Splice in the body, if any.
989 ,@body)))
991 (defmacro 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 (debug (&define name sexp [&rest [keywordp sexp]] def-body))
1044 (indent 2))
1045 (let (export-block filters menu-entry options translators contents)
1046 (while (keywordp (car body))
1047 (case (pop body)
1048 (:export-block (let ((names (pop body)))
1049 (setq export-block
1050 (if (consp names) (mapcar 'upcase names)
1051 (list (upcase names))))))
1052 (:filters-alist (setq filters (pop body)))
1053 (:menu-entry (setq menu-entry (pop body)))
1054 (:options-alist (setq options (pop body)))
1055 (:translate-alist (setq translators (pop body)))
1056 (t (pop body))))
1057 (setq contents (append
1058 (list :parent parent)
1059 (let ((p-table (org-export-backend-translate-table parent)))
1060 (list :translate-alist (append translators p-table)))
1061 (let ((p-filters (org-export-backend-filters parent)))
1062 (list :filters-alist (append filters p-filters)))
1063 (let ((p-options (org-export-backend-options parent)))
1064 (list :options-alist (append options p-options)))
1065 (and menu-entry (list :menu-entry menu-entry))))
1066 `(progn
1067 (org-export-barf-if-invalid-backend ',parent)
1068 ;; Register back-end.
1069 (let ((registeredp (assq ',child org-export-registered-backends)))
1070 (if registeredp (setcdr registeredp ',contents)
1071 (push (cons ',child ',contents) org-export-registered-backends)))
1072 ;; Tell parser to not parse EXPORT-BLOCK blocks.
1073 ,(when export-block
1074 `(mapc
1075 (lambda (name)
1076 (add-to-list 'org-element-block-name-alist
1077 `(,name . org-element-export-block-parser)))
1078 ',export-block))
1079 ;; Splice in the body, if any.
1080 ,@body)))
1082 (defun org-export-backend-parent (backend)
1083 "Return back-end from which BACKEND is derived, or nil."
1084 (plist-get (cdr (assq backend org-export-registered-backends)) :parent))
1086 (defun org-export-backend-filters (backend)
1087 "Return filters for BACKEND."
1088 (plist-get (cdr (assq backend org-export-registered-backends))
1089 :filters-alist))
1091 (defun org-export-backend-menu (backend)
1092 "Return menu entry for BACKEND."
1093 (plist-get (cdr (assq backend org-export-registered-backends))
1094 :menu-entry))
1096 (defun org-export-backend-options (backend)
1097 "Return export options for BACKEND."
1098 (plist-get (cdr (assq backend org-export-registered-backends))
1099 :options-alist))
1101 (defun org-export-backend-translate-table (backend)
1102 "Return translate table for BACKEND."
1103 (plist-get (cdr (assq backend org-export-registered-backends))
1104 :translate-alist))
1106 (defun org-export-barf-if-invalid-backend (backend)
1107 "Signal an error if BACKEND isn't defined."
1108 (unless (org-export-backend-translate-table backend)
1109 (error "Unknown \"%s\" back-end: Aborting export" backend)))
1111 (defun org-export-derived-backend-p (backend &rest backends)
1112 "Non-nil if BACKEND is derived from one of BACKENDS."
1113 (let ((parent backend))
1114 (while (and (not (memq parent backends))
1115 (setq parent (org-export-backend-parent parent))))
1116 parent))
1120 ;;; The Communication Channel
1122 ;; During export process, every function has access to a number of
1123 ;; properties. They are of two types:
1125 ;; 1. Environment options are collected once at the very beginning of
1126 ;; the process, out of the original buffer and configuration.
1127 ;; Collecting them is handled by `org-export-get-environment'
1128 ;; function.
1130 ;; Most environment options are defined through the
1131 ;; `org-export-options-alist' variable.
1133 ;; 2. Tree properties are extracted directly from the parsed tree,
1134 ;; just before export, by `org-export-collect-tree-properties'.
1136 ;; Here is the full list of properties available during transcode
1137 ;; process, with their category and their value type.
1139 ;; + `:author' :: Author's name.
1140 ;; - category :: option
1141 ;; - type :: string
1143 ;; + `:back-end' :: Current back-end used for transcoding.
1144 ;; - category :: tree
1145 ;; - type :: symbol
1147 ;; + `:creator' :: String to write as creation information.
1148 ;; - category :: option
1149 ;; - type :: string
1151 ;; + `:date' :: String to use as date.
1152 ;; - category :: option
1153 ;; - type :: string
1155 ;; + `:description' :: Description text for the current data.
1156 ;; - category :: option
1157 ;; - type :: string
1159 ;; + `:email' :: Author's email.
1160 ;; - category :: option
1161 ;; - type :: string
1163 ;; + `:exclude-tags' :: Tags for exclusion of subtrees from export
1164 ;; process.
1165 ;; - category :: option
1166 ;; - type :: list of strings
1168 ;; + `:export-options' :: List of export options available for current
1169 ;; process.
1170 ;; - category :: none
1171 ;; - type :: list of symbols, among `subtree', `body-only' and
1172 ;; `visible-only'.
1174 ;; + `:exported-data' :: Hash table used for memoizing
1175 ;; `org-export-data'.
1176 ;; - category :: tree
1177 ;; - type :: hash table
1179 ;; + `:filetags' :: List of global tags for buffer. Used by
1180 ;; `org-export-get-tags' to get tags with inheritance.
1181 ;; - category :: option
1182 ;; - type :: list of strings
1184 ;; + `:footnote-definition-alist' :: Alist between footnote labels and
1185 ;; their definition, as parsed data. Only non-inlined footnotes
1186 ;; are represented in this alist. Also, every definition isn't
1187 ;; guaranteed to be referenced in the parse tree. The purpose of
1188 ;; this property is to preserve definitions from oblivion
1189 ;; (i.e. when the parse tree comes from a part of the original
1190 ;; buffer), it isn't meant for direct use in a back-end. To
1191 ;; retrieve a definition relative to a reference, use
1192 ;; `org-export-get-footnote-definition' instead.
1193 ;; - category :: option
1194 ;; - type :: alist (STRING . LIST)
1196 ;; + `:headline-levels' :: Maximum level being exported as an
1197 ;; headline. Comparison is done with the relative level of
1198 ;; headlines in the parse tree, not necessarily with their
1199 ;; actual level.
1200 ;; - category :: option
1201 ;; - type :: integer
1203 ;; + `:headline-offset' :: Difference between relative and real level
1204 ;; of headlines in the parse tree. For example, a value of -1
1205 ;; means a level 2 headline should be considered as level
1206 ;; 1 (cf. `org-export-get-relative-level').
1207 ;; - category :: tree
1208 ;; - type :: integer
1210 ;; + `:headline-numbering' :: Alist between headlines and their
1211 ;; numbering, as a list of numbers
1212 ;; (cf. `org-export-get-headline-number').
1213 ;; - category :: tree
1214 ;; - type :: alist (INTEGER . LIST)
1216 ;; + `:id-alist' :: Alist between ID strings and destination file's
1217 ;; path, relative to current directory. It is used by
1218 ;; `org-export-resolve-id-link' to resolve ID links targeting an
1219 ;; external file.
1220 ;; - category :: option
1221 ;; - type :: alist (STRING . STRING)
1223 ;; + `:ignore-list' :: List of elements and objects that should be
1224 ;; ignored during export.
1225 ;; - category :: tree
1226 ;; - type :: list of elements and objects
1228 ;; + `:input-file' :: Full path to input file, if any.
1229 ;; - category :: option
1230 ;; - type :: string or nil
1232 ;; + `:keywords' :: List of keywords attached to data.
1233 ;; - category :: option
1234 ;; - type :: string
1236 ;; + `:language' :: Default language used for translations.
1237 ;; - category :: option
1238 ;; - type :: string
1240 ;; + `:parse-tree' :: Whole parse tree, available at any time during
1241 ;; transcoding.
1242 ;; - category :: option
1243 ;; - type :: list (as returned by `org-element-parse-buffer')
1245 ;; + `:preserve-breaks' :: Non-nil means transcoding should preserve
1246 ;; all line breaks.
1247 ;; - category :: option
1248 ;; - type :: symbol (nil, t)
1250 ;; + `:section-numbers' :: Non-nil means transcoding should add
1251 ;; section numbers to headlines.
1252 ;; - category :: option
1253 ;; - type :: symbol (nil, t)
1255 ;; + `:select-tags' :: List of tags enforcing inclusion of sub-trees
1256 ;; in transcoding. When such a tag is present, subtrees without
1257 ;; it are de facto excluded from the process. See
1258 ;; `use-select-tags'.
1259 ;; - category :: option
1260 ;; - type :: list of strings
1262 ;; + `:time-stamp-file' :: Non-nil means transcoding should insert
1263 ;; a time stamp in the output.
1264 ;; - category :: option
1265 ;; - type :: symbol (nil, t)
1267 ;; + `:translate-alist' :: Alist between element and object types and
1268 ;; transcoding functions relative to the current back-end.
1269 ;; Special keys `inner-template', `template' and `plain-text' are
1270 ;; also possible.
1271 ;; - category :: option
1272 ;; - type :: alist (SYMBOL . FUNCTION)
1274 ;; + `:with-archived-trees' :: Non-nil when archived subtrees should
1275 ;; also be transcoded. If it is set to the `headline' symbol,
1276 ;; only the archived headline's name is retained.
1277 ;; - category :: option
1278 ;; - type :: symbol (nil, t, `headline')
1280 ;; + `:with-author' :: Non-nil means author's name should be included
1281 ;; in the output.
1282 ;; - category :: option
1283 ;; - type :: symbol (nil, t)
1285 ;; + `:with-clocks' :: Non-nil means clock keywords should be exported.
1286 ;; - category :: option
1287 ;; - type :: symbol (nil, t)
1289 ;; + `:with-creator' :: Non-nil means a creation sentence should be
1290 ;; inserted at the end of the transcoded string. If the value
1291 ;; is `comment', it should be commented.
1292 ;; - category :: option
1293 ;; - type :: symbol (`comment', nil, t)
1295 ;; + `:with-date' :: Non-nil means output should contain a date.
1296 ;; - category :: option
1297 ;; - type :. symbol (nil, t)
1299 ;; + `:with-drawers' :: Non-nil means drawers should be exported. If
1300 ;; its value is a list of names, only drawers with such names
1301 ;; will be transcoded. If that list starts with `not', drawer
1302 ;; with these names will be skipped.
1303 ;; - category :: option
1304 ;; - type :: symbol (nil, t) or list of strings
1306 ;; + `:with-email' :: Non-nil means output should contain author's
1307 ;; email.
1308 ;; - category :: option
1309 ;; - type :: symbol (nil, t)
1311 ;; + `:with-emphasize' :: Non-nil means emphasized text should be
1312 ;; interpreted.
1313 ;; - category :: option
1314 ;; - type :: symbol (nil, t)
1316 ;; + `:with-fixed-width' :: Non-nil if transcoder should interpret
1317 ;; strings starting with a colon as a fixed-with (verbatim) area.
1318 ;; - category :: option
1319 ;; - type :: symbol (nil, t)
1321 ;; + `:with-footnotes' :: Non-nil if transcoder should interpret
1322 ;; footnotes.
1323 ;; - category :: option
1324 ;; - type :: symbol (nil, t)
1326 ;; + `:with-latex' :: Non-nil means `latex-environment' elements and
1327 ;; `latex-fragment' objects should appear in export output. When
1328 ;; this property is set to `verbatim', they will be left as-is.
1329 ;; - category :: option
1330 ;; - type :: symbol (`verbatim', nil, t)
1332 ;; + `:with-plannings' :: Non-nil means transcoding should include
1333 ;; planning info.
1334 ;; - category :: option
1335 ;; - type :: symbol (nil, t)
1337 ;; + `:with-priority' :: Non-nil means transcoding should include
1338 ;; priority cookies.
1339 ;; - category :: option
1340 ;; - type :: symbol (nil, t)
1342 ;; + `:with-smart-quotes' :: Non-nil means activate smart quotes in
1343 ;; plain text.
1344 ;; - category :: option
1345 ;; - type :: symbol (nil, t)
1347 ;; + `:with-special-strings' :: Non-nil means transcoding should
1348 ;; interpret special strings in plain text.
1349 ;; - category :: option
1350 ;; - type :: symbol (nil, t)
1352 ;; + `:with-sub-superscript' :: Non-nil means transcoding should
1353 ;; interpret subscript and superscript. With a value of "{}",
1354 ;; only interpret those using curly brackets.
1355 ;; - category :: option
1356 ;; - type :: symbol (nil, {}, t)
1358 ;; + `:with-tables' :: Non-nil means transcoding should interpret
1359 ;; tables.
1360 ;; - category :: option
1361 ;; - type :: symbol (nil, t)
1363 ;; + `:with-tags' :: Non-nil means transcoding should keep tags in
1364 ;; headlines. A `not-in-toc' value will remove them from the
1365 ;; table of contents, if any, nonetheless.
1366 ;; - category :: option
1367 ;; - type :: symbol (nil, t, `not-in-toc')
1369 ;; + `:with-tasks' :: Non-nil means transcoding should include
1370 ;; headlines with a TODO keyword. A `todo' value will only
1371 ;; include headlines with a todo type keyword while a `done'
1372 ;; value will do the contrary. If a list of strings is provided,
1373 ;; only tasks with keywords belonging to that list will be kept.
1374 ;; - category :: option
1375 ;; - type :: symbol (t, todo, done, nil) or list of strings
1377 ;; + `:with-timestamps' :: Non-nil means transcoding should include
1378 ;; time stamps. Special value `active' (resp. `inactive') ask to
1379 ;; export only active (resp. inactive) timestamps. Otherwise,
1380 ;; completely remove them.
1381 ;; - category :: option
1382 ;; - type :: symbol: (`active', `inactive', t, nil)
1384 ;; + `:with-toc' :: Non-nil means that a table of contents has to be
1385 ;; added to the output. An integer value limits its depth.
1386 ;; - category :: option
1387 ;; - type :: symbol (nil, t or integer)
1389 ;; + `:with-todo-keywords' :: Non-nil means transcoding should
1390 ;; include TODO keywords.
1391 ;; - category :: option
1392 ;; - type :: symbol (nil, t)
1395 ;;;; Environment Options
1397 ;; Environment options encompass all parameters defined outside the
1398 ;; scope of the parsed data. They come from five sources, in
1399 ;; increasing precedence order:
1401 ;; - Global variables,
1402 ;; - Buffer's attributes,
1403 ;; - Options keyword symbols,
1404 ;; - Buffer keywords,
1405 ;; - Subtree properties.
1407 ;; The central internal function with regards to environment options
1408 ;; is `org-export-get-environment'. It updates global variables with
1409 ;; "#+BIND:" keywords, then retrieve and prioritize properties from
1410 ;; the different sources.
1412 ;; The internal functions doing the retrieval are:
1413 ;; `org-export--get-global-options',
1414 ;; `org-export--get-buffer-attributes',
1415 ;; `org-export--parse-option-keyword',
1416 ;; `org-export--get-subtree-options' and
1417 ;; `org-export--get-inbuffer-options'
1419 ;; Also, `org-export--install-letbind-maybe' takes care of the part
1420 ;; relative to "#+BIND:" keywords.
1422 (defun org-export-get-environment (&optional backend subtreep ext-plist)
1423 "Collect export options from the current buffer.
1425 Optional argument BACKEND is a symbol specifying which back-end
1426 specific options to read, if any.
1428 When optional argument SUBTREEP is non-nil, assume the export is
1429 done against the current sub-tree.
1431 Third optional argument EXT-PLIST is a property list with
1432 external parameters overriding Org default settings, but still
1433 inferior to file-local settings."
1434 ;; First install #+BIND variables.
1435 (org-export--install-letbind-maybe)
1436 ;; Get and prioritize export options...
1437 (org-combine-plists
1438 ;; ... from global variables...
1439 (org-export--get-global-options backend)
1440 ;; ... from an external property list...
1441 ext-plist
1442 ;; ... from in-buffer settings...
1443 (org-export--get-inbuffer-options backend)
1444 ;; ... and from subtree, when appropriate.
1445 (and subtreep (org-export--get-subtree-options backend))
1446 ;; Eventually add misc. properties.
1447 (list
1448 :back-end
1449 backend
1450 :translate-alist
1451 (org-export-backend-translate-table backend)
1452 :footnote-definition-alist
1453 ;; Footnotes definitions must be collected in the original
1454 ;; buffer, as there's no insurance that they will still be in
1455 ;; the parse tree, due to possible narrowing.
1456 (let (alist)
1457 (org-with-wide-buffer
1458 (goto-char (point-min))
1459 (while (re-search-forward org-footnote-definition-re nil t)
1460 (let ((def (save-match-data (org-element-at-point))))
1461 (when (eq (org-element-type def) 'footnote-definition)
1462 (push
1463 (cons (org-element-property :label def)
1464 (let ((cbeg (org-element-property :contents-begin def)))
1465 (when cbeg
1466 (org-element--parse-elements
1467 cbeg (org-element-property :contents-end def)
1468 nil nil nil nil (list 'org-data nil)))))
1469 alist))))
1470 alist))
1471 :id-alist
1472 ;; Collect id references.
1473 (let (alist)
1474 (org-with-wide-buffer
1475 (goto-char (point-min))
1476 (while (re-search-forward "\\[\\[id:\\S-+?\\]" nil t)
1477 (let ((link (org-element-context)))
1478 (when (eq (org-element-type link) 'link)
1479 (let* ((id (org-element-property :path link))
1480 (file (org-id-find-id-file id)))
1481 (when file
1482 (push (cons id (file-relative-name file)) alist)))))))
1483 alist))))
1485 (defun org-export--parse-option-keyword (options &optional backend)
1486 "Parse an OPTIONS line and return values as a plist.
1487 Optional argument BACKEND is a symbol specifying which back-end
1488 specific items to read, if any."
1489 (let* ((all
1490 ;; Priority is given to back-end specific options.
1491 (append (and backend (org-export-backend-options backend))
1492 org-export-options-alist))
1493 plist)
1494 (dolist (option all)
1495 (let ((property (car option))
1496 (item (nth 2 option)))
1497 (when (and item
1498 (not (plist-member plist property))
1499 (string-match (concat "\\(\\`\\|[ \t]\\)"
1500 (regexp-quote item)
1501 ":\\(([^)\n]+)\\|[^ \t\n\r;,.]*\\)")
1502 options))
1503 (setq plist (plist-put plist
1504 property
1505 (car (read-from-string
1506 (match-string 2 options))))))))
1507 plist))
1509 (defun org-export--get-subtree-options (&optional backend)
1510 "Get export options in subtree at point.
1511 Optional argument BACKEND is a symbol specifying back-end used
1512 for export. Return options as a plist."
1513 ;; For each buffer keyword, create a headline property setting the
1514 ;; same property in communication channel. The name for the property
1515 ;; is the keyword with "EXPORT_" appended to it.
1516 (org-with-wide-buffer
1517 (let (prop plist)
1518 ;; Make sure point is at an heading.
1519 (if (org-at-heading-p) (org-up-heading-safe) (org-back-to-heading t))
1520 ;; Take care of EXPORT_TITLE. If it isn't defined, use headline's
1521 ;; title as its fallback value.
1522 (when (setq prop (or (org-entry-get (point) "EXPORT_TITLE")
1523 (progn (looking-at org-todo-line-regexp)
1524 (org-match-string-no-properties 3))))
1525 (setq plist
1526 (plist-put
1527 plist :title
1528 (org-element-parse-secondary-string
1529 prop (org-element-restriction 'keyword)))))
1530 ;; EXPORT_OPTIONS are parsed in a non-standard way.
1531 (when (setq prop (org-entry-get (point) "EXPORT_OPTIONS"))
1532 (setq plist
1533 (nconc plist (org-export--parse-option-keyword prop backend))))
1534 ;; Handle other keywords. TITLE keyword is excluded as it has
1535 ;; been handled already.
1536 (let ((seen '("TITLE")))
1537 (mapc
1538 (lambda (option)
1539 (let ((property (car option))
1540 (keyword (nth 1 option)))
1541 (when (and keyword (not (member keyword seen)))
1542 (let* ((subtree-prop (concat "EXPORT_" keyword))
1543 ;; Export properties are not case-sensitive.
1544 (value (let ((case-fold-search t))
1545 (org-entry-get (point) subtree-prop))))
1546 (push keyword seen)
1547 (when (and value (not (plist-member plist property)))
1548 (setq plist
1549 (plist-put
1550 plist
1551 property
1552 (cond
1553 ;; Parse VALUE if required.
1554 ((member keyword org-element-document-properties)
1555 (org-element-parse-secondary-string
1556 value (org-element-restriction 'keyword)))
1557 ;; If BEHAVIOUR is `split' expected value is
1558 ;; a list of strings, not a string.
1559 ((eq (nth 4 option) 'split) (org-split-string value))
1560 (t value)))))))))
1561 ;; Look for both general keywords and back-end specific
1562 ;; options, with priority given to the latter.
1563 (append (and backend (org-export-backend-options backend))
1564 org-export-options-alist)))
1565 ;; Return value.
1566 plist)))
1568 (defun org-export--get-inbuffer-options (&optional backend)
1569 "Return current buffer export options, as a plist.
1571 Optional argument BACKEND, when non-nil, is a symbol specifying
1572 which back-end specific options should also be read in the
1573 process.
1575 Assume buffer is in Org mode. Narrowing, if any, is ignored."
1576 (let* (plist
1577 get-options ; For byte-compiler.
1578 (case-fold-search t)
1579 (options (append
1580 ;; Priority is given to back-end specific options.
1581 (and backend (org-export-backend-options backend))
1582 org-export-options-alist))
1583 (regexp (format "^[ \t]*#\\+%s:"
1584 (regexp-opt (nconc (delq nil (mapcar 'cadr options))
1585 org-export-special-keywords))))
1586 (find-opt
1587 (lambda (keyword)
1588 ;; Return property name associated to KEYWORD.
1589 (catch 'exit
1590 (mapc (lambda (option)
1591 (when (equal (nth 1 option) keyword)
1592 (throw 'exit (car option))))
1593 options))))
1594 (get-options
1595 (lambda (&optional files plist)
1596 ;; Recursively read keywords in buffer. FILES is a list
1597 ;; of files read so far. PLIST is the current property
1598 ;; list obtained.
1599 (org-with-wide-buffer
1600 (goto-char (point-min))
1601 (while (re-search-forward regexp nil t)
1602 (let ((element (org-element-at-point)))
1603 (when (eq (org-element-type element) 'keyword)
1604 (let ((key (org-element-property :key element))
1605 (val (org-element-property :value element)))
1606 (cond
1607 ;; Options in `org-export-special-keywords'.
1608 ((equal key "SETUPFILE")
1609 (let ((file (expand-file-name
1610 (org-remove-double-quotes (org-trim val)))))
1611 ;; Avoid circular dependencies.
1612 (unless (member file files)
1613 (with-temp-buffer
1614 (insert (org-file-contents file 'noerror))
1615 (org-mode)
1616 (setq plist (funcall get-options
1617 (cons file files) plist))))))
1618 ((equal key "OPTIONS")
1619 (setq plist
1620 (org-combine-plists
1621 plist
1622 (org-export--parse-option-keyword val backend))))
1623 ((equal key "FILETAGS")
1624 (setq plist
1625 (org-combine-plists
1626 plist
1627 (list :filetags
1628 (org-uniquify
1629 (append (org-split-string val ":")
1630 (plist-get plist :filetags)))))))
1632 ;; Options in `org-export-options-alist'.
1633 (let* ((prop (funcall find-opt key))
1634 (behaviour (nth 4 (assq prop options))))
1635 (setq plist
1636 (plist-put
1637 plist prop
1638 ;; Handle value depending on specified
1639 ;; BEHAVIOUR.
1640 (case behaviour
1641 (space
1642 (if (not (plist-get plist prop))
1643 (org-trim val)
1644 (concat (plist-get plist prop)
1646 (org-trim val))))
1647 (newline
1648 (org-trim (concat (plist-get plist prop)
1649 "\n"
1650 (org-trim val))))
1651 (split `(,@(plist-get plist prop)
1652 ,@(org-split-string val)))
1653 ('t val)
1654 (otherwise
1655 (if (not (plist-member plist prop)) val
1656 (plist-get plist prop)))))))))))))
1657 ;; Return final value.
1658 plist))))
1659 ;; Read options in the current buffer.
1660 (setq plist (funcall get-options buffer-file-name nil))
1661 ;; Parse keywords specified in `org-element-document-properties'.
1662 (mapc (lambda (keyword)
1663 ;; Find the property associated to the keyword.
1664 (let* ((prop (funcall find-opt keyword))
1665 (value (and prop (plist-get plist prop))))
1666 (when (stringp value)
1667 (setq plist
1668 (plist-put plist prop
1669 (org-element-parse-secondary-string
1670 value (org-element-restriction 'keyword)))))))
1671 org-element-document-properties)
1672 ;; Return value.
1673 plist))
1675 (defun org-export--get-buffer-attributes ()
1676 "Return properties related to buffer attributes, as a plist."
1677 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
1678 (list
1679 ;; Store full path of input file name, or nil. For internal use.
1680 :input-file visited-file
1681 :title (or (and visited-file
1682 (file-name-sans-extension
1683 (file-name-nondirectory visited-file)))
1684 (buffer-name (buffer-base-buffer))))))
1686 (defun org-export--get-global-options (&optional backend)
1687 "Return global export options as a plist.
1689 Optional argument BACKEND, if non-nil, is a symbol specifying
1690 which back-end specific export options should also be read in the
1691 process."
1692 (let ((all
1693 ;; Priority is given to back-end specific options.
1694 (append (and backend (org-export-backend-options backend))
1695 org-export-options-alist))
1696 plist)
1697 (mapc
1698 (lambda (cell)
1699 (let ((prop (car cell)))
1700 (unless (plist-member plist prop)
1701 (setq plist
1702 (plist-put
1703 plist
1704 prop
1705 ;; Eval default value provided. If keyword is a member
1706 ;; of `org-element-document-properties', parse it as
1707 ;; a secondary string before storing it.
1708 (let ((value (eval (nth 3 cell))))
1709 (if (not (stringp value)) value
1710 (let ((keyword (nth 1 cell)))
1711 (if (not (member keyword org-element-document-properties))
1712 value
1713 (org-element-parse-secondary-string
1714 value (org-element-restriction 'keyword)))))))))))
1715 all)
1716 ;; Return value.
1717 plist))
1719 (defun org-export--install-letbind-maybe ()
1720 "Install the values from #+BIND lines as local variables.
1721 Variables must be installed before in-buffer options are
1722 retrieved."
1723 (when org-export-allow-bind-keywords
1724 (let ((case-fold-search t) letbind)
1725 (org-with-wide-buffer
1726 (goto-char (point-min))
1727 (while (re-search-forward "^[ \t]*#\\+BIND:" nil t)
1728 (let* ((element (org-element-at-point))
1729 (value (org-element-property :value element)))
1730 (when (and (eq (org-element-type element) 'keyword)
1731 (not (equal value "")))
1732 (push (read (format "(%s)" value)) letbind)))))
1733 (dolist (pair (nreverse letbind))
1734 (org-set-local (car pair) (nth 1 pair))))))
1737 ;;;; Tree Properties
1739 ;; Tree properties are information extracted from parse tree. They
1740 ;; are initialized at the beginning of the transcoding process by
1741 ;; `org-export-collect-tree-properties'.
1743 ;; Dedicated functions focus on computing the value of specific tree
1744 ;; properties during initialization. Thus,
1745 ;; `org-export--populate-ignore-list' lists elements and objects that
1746 ;; should be skipped during export, `org-export--get-min-level' gets
1747 ;; the minimal exportable level, used as a basis to compute relative
1748 ;; level for headlines. Eventually
1749 ;; `org-export--collect-headline-numbering' builds an alist between
1750 ;; headlines and their numbering.
1752 (defun org-export-collect-tree-properties (data info)
1753 "Extract tree properties from parse tree.
1755 DATA is the parse tree from which information is retrieved. INFO
1756 is a list holding export options.
1758 Following tree properties are set or updated:
1760 `:exported-data' Hash table used to memoize results from
1761 `org-export-data'.
1763 `:footnote-definition-alist' List of footnotes definitions in
1764 original buffer and current parse tree.
1766 `:headline-offset' Offset between true level of headlines and
1767 local level. An offset of -1 means a headline
1768 of level 2 should be considered as a level
1769 1 headline in the context.
1771 `:headline-numbering' Alist of all headlines as key an the
1772 associated numbering as value.
1774 `:ignore-list' List of elements that should be ignored during
1775 export.
1777 Return updated plist."
1778 ;; Install the parse tree in the communication channel, in order to
1779 ;; use `org-export-get-genealogy' and al.
1780 (setq info (plist-put info :parse-tree data))
1781 ;; Get the list of elements and objects to ignore, and put it into
1782 ;; `:ignore-list'. Do not overwrite any user ignore that might have
1783 ;; been done during parse tree filtering.
1784 (setq info
1785 (plist-put info
1786 :ignore-list
1787 (append (org-export--populate-ignore-list data info)
1788 (plist-get info :ignore-list))))
1789 ;; Compute `:headline-offset' in order to be able to use
1790 ;; `org-export-get-relative-level'.
1791 (setq info
1792 (plist-put info
1793 :headline-offset
1794 (- 1 (org-export--get-min-level data info))))
1795 ;; Update footnotes definitions list with definitions in parse tree.
1796 ;; This is required since buffer expansion might have modified
1797 ;; boundaries of footnote definitions contained in the parse tree.
1798 ;; This way, definitions in `footnote-definition-alist' are bound to
1799 ;; match those in the parse tree.
1800 (let ((defs (plist-get info :footnote-definition-alist)))
1801 (org-element-map data 'footnote-definition
1802 (lambda (fn)
1803 (push (cons (org-element-property :label fn)
1804 `(org-data nil ,@(org-element-contents fn)))
1805 defs)))
1806 (setq info (plist-put info :footnote-definition-alist defs)))
1807 ;; Properties order doesn't matter: get the rest of the tree
1808 ;; properties.
1809 (nconc
1810 `(:headline-numbering ,(org-export--collect-headline-numbering data info)
1811 :exported-data ,(make-hash-table :test 'eq :size 4001))
1812 info))
1814 (defun org-export--get-min-level (data options)
1815 "Return minimum exportable headline's level in DATA.
1816 DATA is parsed tree as returned by `org-element-parse-buffer'.
1817 OPTIONS is a plist holding export options."
1818 (catch 'exit
1819 (let ((min-level 10000))
1820 (mapc
1821 (lambda (blob)
1822 (when (and (eq (org-element-type blob) 'headline)
1823 (not (org-element-property :footnote-section-p blob))
1824 (not (memq blob (plist-get options :ignore-list))))
1825 (setq min-level (min (org-element-property :level blob) min-level)))
1826 (when (= min-level 1) (throw 'exit 1)))
1827 (org-element-contents data))
1828 ;; If no headline was found, for the sake of consistency, set
1829 ;; minimum level to 1 nonetheless.
1830 (if (= min-level 10000) 1 min-level))))
1832 (defun org-export--collect-headline-numbering (data options)
1833 "Return numbering of all exportable headlines in a parse tree.
1835 DATA is the parse tree. OPTIONS is the plist holding export
1836 options.
1838 Return an alist whose key is a headline and value is its
1839 associated numbering \(in the shape of a list of numbers\) or nil
1840 for a footnotes section."
1841 (let ((numbering (make-vector org-export-max-depth 0)))
1842 (org-element-map data 'headline
1843 (lambda (headline)
1844 (unless (org-element-property :footnote-section-p headline)
1845 (let ((relative-level
1846 (1- (org-export-get-relative-level headline options))))
1847 (cons
1848 headline
1849 (loop for n across numbering
1850 for idx from 0 to org-export-max-depth
1851 when (< idx relative-level) collect n
1852 when (= idx relative-level) collect (aset numbering idx (1+ n))
1853 when (> idx relative-level) do (aset numbering idx 0))))))
1854 options)))
1856 (defun org-export--populate-ignore-list (data options)
1857 "Return list of elements and objects to ignore during export.
1858 DATA is the parse tree to traverse. OPTIONS is the plist holding
1859 export options."
1860 (let* (ignore
1861 walk-data
1862 ;; First find trees containing a select tag, if any.
1863 (selected (org-export--selected-trees data options))
1864 (walk-data
1865 (lambda (data)
1866 ;; Collect ignored elements or objects into IGNORE-LIST.
1867 (let ((type (org-element-type data)))
1868 (if (org-export--skip-p data options selected) (push data ignore)
1869 (if (and (eq type 'headline)
1870 (eq (plist-get options :with-archived-trees) 'headline)
1871 (org-element-property :archivedp data))
1872 ;; If headline is archived but tree below has
1873 ;; to be skipped, add it to ignore list.
1874 (mapc (lambda (e) (push e ignore))
1875 (org-element-contents data))
1876 ;; Move into secondary string, if any.
1877 (let ((sec-prop
1878 (cdr (assq type org-element-secondary-value-alist))))
1879 (when sec-prop
1880 (mapc walk-data (org-element-property sec-prop data))))
1881 ;; Move into recursive objects/elements.
1882 (mapc walk-data (org-element-contents data))))))))
1883 ;; Main call.
1884 (funcall walk-data data)
1885 ;; Return value.
1886 ignore))
1888 (defun org-export--selected-trees (data info)
1889 "Return list of headlines and inlinetasks with a select tag in their tree.
1890 DATA is parsed data as returned by `org-element-parse-buffer'.
1891 INFO is a plist holding export options."
1892 (let* (selected-trees
1893 walk-data ; For byte-compiler.
1894 (walk-data
1895 (function
1896 (lambda (data genealogy)
1897 (let ((type (org-element-type data)))
1898 (cond
1899 ((memq type '(headline inlinetask))
1900 (let ((tags (org-element-property :tags data)))
1901 (if (loop for tag in (plist-get info :select-tags)
1902 thereis (member tag tags))
1903 ;; When a select tag is found, mark full
1904 ;; genealogy and every headline within the tree
1905 ;; as acceptable.
1906 (setq selected-trees
1907 (append
1908 genealogy
1909 (org-element-map data '(headline inlinetask)
1910 'identity)
1911 selected-trees))
1912 ;; If at a headline, continue searching in tree,
1913 ;; recursively.
1914 (when (eq type 'headline)
1915 (mapc (lambda (el)
1916 (funcall walk-data el (cons data genealogy)))
1917 (org-element-contents data))))))
1918 ((or (eq type 'org-data)
1919 (memq type org-element-greater-elements))
1920 (mapc (lambda (el) (funcall walk-data el genealogy))
1921 (org-element-contents data)))))))))
1922 (funcall walk-data data nil)
1923 selected-trees))
1925 (defun org-export--skip-p (blob options selected)
1926 "Non-nil when element or object BLOB should be skipped during export.
1927 OPTIONS is the plist holding export options. SELECTED, when
1928 non-nil, is a list of headlines or inlinetasks belonging to
1929 a tree with a select tag."
1930 (case (org-element-type blob)
1931 (clock (not (plist-get options :with-clocks)))
1932 (drawer
1933 (let ((with-drawers-p (plist-get options :with-drawers)))
1934 (or (not with-drawers-p)
1935 (and (consp with-drawers-p)
1936 ;; If `:with-drawers' value starts with `not', ignore
1937 ;; every drawer whose name belong to that list.
1938 ;; Otherwise, ignore drawers whose name isn't in that
1939 ;; list.
1940 (let ((name (org-element-property :drawer-name blob)))
1941 (if (eq (car with-drawers-p) 'not)
1942 (member-ignore-case name (cdr with-drawers-p))
1943 (not (member-ignore-case name with-drawers-p))))))))
1944 ((headline inlinetask)
1945 (let ((with-tasks (plist-get options :with-tasks))
1946 (todo (org-element-property :todo-keyword blob))
1947 (todo-type (org-element-property :todo-type blob))
1948 (archived (plist-get options :with-archived-trees))
1949 (tags (org-element-property :tags blob)))
1951 (and (eq (org-element-type blob) 'inlinetask)
1952 (not (plist-get options :with-inlinetasks)))
1953 ;; Ignore subtrees with an exclude tag.
1954 (loop for k in (plist-get options :exclude-tags)
1955 thereis (member k tags))
1956 ;; When a select tag is present in the buffer, ignore any tree
1957 ;; without it.
1958 (and selected (not (memq blob selected)))
1959 ;; Ignore commented sub-trees.
1960 (org-element-property :commentedp blob)
1961 ;; Ignore archived subtrees if `:with-archived-trees' is nil.
1962 (and (not archived) (org-element-property :archivedp blob))
1963 ;; Ignore tasks, if specified by `:with-tasks' property.
1964 (and todo
1965 (or (not with-tasks)
1966 (and (memq with-tasks '(todo done))
1967 (not (eq todo-type with-tasks)))
1968 (and (consp with-tasks) (not (member todo with-tasks))))))))
1969 ((latex-environment latex-fragment) (not (plist-get options :with-latex)))
1970 (planning (not (plist-get options :with-plannings)))
1971 (statistics-cookie (not (plist-get options :with-statistics-cookies)))
1972 (table-cell
1973 (and (org-export-table-has-special-column-p
1974 (org-export-get-parent-table blob))
1975 (not (org-export-get-previous-element blob options))))
1976 (table-row (org-export-table-row-is-special-p blob options))
1977 (timestamp
1978 (case (plist-get options :with-timestamps)
1979 ;; No timestamp allowed.
1980 ('nil t)
1981 ;; Only active timestamps allowed and the current one isn't
1982 ;; active.
1983 (active
1984 (not (memq (org-element-property :type blob)
1985 '(active active-range))))
1986 ;; Only inactive timestamps allowed and the current one isn't
1987 ;; inactive.
1988 (inactive
1989 (not (memq (org-element-property :type blob)
1990 '(inactive inactive-range))))))))
1994 ;;; The Transcoder
1996 ;; `org-export-data' reads a parse tree (obtained with, i.e.
1997 ;; `org-element-parse-buffer') and transcodes it into a specified
1998 ;; back-end output. It takes care of filtering out elements or
1999 ;; objects according to export options and organizing the output blank
2000 ;; lines and white space are preserved. The function memoizes its
2001 ;; results, so it is cheap to call it within translators.
2003 ;; It is possible to modify locally the back-end used by
2004 ;; `org-export-data' or even use a temporary back-end by using
2005 ;; `org-export-data-with-translations' and
2006 ;; `org-export-data-with-backend'.
2008 ;; Internally, three functions handle the filtering of objects and
2009 ;; elements during the export. In particular,
2010 ;; `org-export-ignore-element' marks an element or object so future
2011 ;; parse tree traversals skip it, `org-export--interpret-p' tells which
2012 ;; elements or objects should be seen as real Org syntax and
2013 ;; `org-export-expand' transforms the others back into their original
2014 ;; shape
2016 ;; `org-export-transcoder' is an accessor returning appropriate
2017 ;; translator function for a given element or object.
2019 (defun org-export-transcoder (blob info)
2020 "Return appropriate transcoder for BLOB.
2021 INFO is a plist containing export directives."
2022 (let ((type (org-element-type blob)))
2023 ;; Return contents only for complete parse trees.
2024 (if (eq type 'org-data) (lambda (blob contents info) contents)
2025 (let ((transcoder (cdr (assq type (plist-get info :translate-alist)))))
2026 (and (functionp transcoder) transcoder)))))
2028 (defun org-export-data (data info)
2029 "Convert DATA into current back-end format.
2031 DATA is a parse tree, an element or an object or a secondary
2032 string. INFO is a plist holding export options.
2034 Return transcoded string."
2035 (let ((memo (gethash data (plist-get info :exported-data) 'no-memo)))
2036 (if (not (eq memo 'no-memo)) memo
2037 (let* ((type (org-element-type data))
2038 (results
2039 (cond
2040 ;; Ignored element/object.
2041 ((memq data (plist-get info :ignore-list)) nil)
2042 ;; Plain text.
2043 ((eq type 'plain-text)
2044 (org-export-filter-apply-functions
2045 (plist-get info :filter-plain-text)
2046 (let ((transcoder (org-export-transcoder data info)))
2047 (if transcoder (funcall transcoder data info) data))
2048 info))
2049 ;; Uninterpreted element/object: change it back to Org
2050 ;; syntax and export again resulting raw string.
2051 ((not (org-export--interpret-p data info))
2052 (org-export-data
2053 (org-export-expand
2054 data
2055 (mapconcat (lambda (blob) (org-export-data blob info))
2056 (org-element-contents data)
2057 ""))
2058 info))
2059 ;; Secondary string.
2060 ((not type)
2061 (mapconcat (lambda (obj) (org-export-data obj info)) data ""))
2062 ;; Element/Object without contents or, as a special case,
2063 ;; headline with archive tag and archived trees restricted
2064 ;; to title only.
2065 ((or (not (org-element-contents data))
2066 (and (eq type 'headline)
2067 (eq (plist-get info :with-archived-trees) 'headline)
2068 (org-element-property :archivedp data)))
2069 (let ((transcoder (org-export-transcoder data info)))
2070 (and (functionp transcoder)
2071 (funcall transcoder data nil info))))
2072 ;; Element/Object with contents.
2074 (let ((transcoder (org-export-transcoder data info)))
2075 (when transcoder
2076 (let* ((greaterp (memq type org-element-greater-elements))
2077 (objectp
2078 (and (not greaterp)
2079 (memq type org-element-recursive-objects)))
2080 (contents
2081 (mapconcat
2082 (lambda (element) (org-export-data element info))
2083 (org-element-contents
2084 (if (or greaterp objectp) data
2085 ;; Elements directly containing objects
2086 ;; must have their indentation normalized
2087 ;; first.
2088 (org-element-normalize-contents
2089 data
2090 ;; When normalizing contents of the first
2091 ;; paragraph in an item or a footnote
2092 ;; definition, ignore first line's
2093 ;; indentation: there is none and it
2094 ;; might be misleading.
2095 (when (eq type 'paragraph)
2096 (let ((parent (org-export-get-parent data)))
2097 (and
2098 (eq (car (org-element-contents parent))
2099 data)
2100 (memq (org-element-type parent)
2101 '(footnote-definition item))))))))
2102 "")))
2103 (funcall transcoder data
2104 (if (not greaterp) contents
2105 (org-element-normalize-string contents))
2106 info))))))))
2107 ;; Final result will be memoized before being returned.
2108 (puthash
2109 data
2110 (cond
2111 ((not results) nil)
2112 ((memq type '(org-data plain-text nil)) results)
2113 ;; Append the same white space between elements or objects as in
2114 ;; the original buffer, and call appropriate filters.
2116 (let ((results
2117 (org-export-filter-apply-functions
2118 (plist-get info (intern (format ":filter-%s" type)))
2119 (let ((post-blank (or (org-element-property :post-blank data)
2120 0)))
2121 (if (memq type org-element-all-elements)
2122 (concat (org-element-normalize-string results)
2123 (make-string post-blank ?\n))
2124 (concat results (make-string post-blank ? ))))
2125 info)))
2126 results)))
2127 (plist-get info :exported-data))))))
2129 (defun org-export-data-with-translations (data translations info)
2130 "Convert DATA into another format using a given translation table.
2131 DATA is an element, an object, a secondary string or a string.
2132 TRANSLATIONS is an alist between element or object types and
2133 a functions handling them. See `org-export-define-backend' for
2134 more information. INFO is a plist used as a communication
2135 channel."
2136 (org-export-data
2137 data
2138 ;; Set-up a new communication channel with TRANSLATIONS as the
2139 ;; translate table and a new hash table for memoization.
2140 (org-combine-plists
2141 info
2142 (list :translate-alist translations
2143 ;; Size of the hash table is reduced since this function
2144 ;; will probably be used on short trees.
2145 :exported-data (make-hash-table :test 'eq :size 401)))))
2147 (defun org-export-data-with-backend (data backend info)
2148 "Convert DATA into BACKEND format.
2150 DATA is an element, an object, a secondary string or a string.
2151 BACKEND is a symbol. INFO is a plist used as a communication
2152 channel.
2154 Unlike to `org-export-with-backend', this function will
2155 recursively convert DATA using BACKEND translation table."
2156 (org-export-barf-if-invalid-backend backend)
2157 (org-export-data-with-translations
2158 data (org-export-backend-translate-table backend) info))
2160 (defun org-export--interpret-p (blob info)
2161 "Non-nil if element or object BLOB should be interpreted during export.
2162 If nil, BLOB will appear as raw Org syntax. Check is done
2163 according to export options INFO, stored as a plist."
2164 (case (org-element-type blob)
2165 ;; ... entities...
2166 (entity (plist-get info :with-entities))
2167 ;; ... emphasis...
2168 ((bold italic strike-through underline)
2169 (plist-get info :with-emphasize))
2170 ;; ... fixed-width areas.
2171 (fixed-width (plist-get info :with-fixed-width))
2172 ;; ... footnotes...
2173 ((footnote-definition footnote-reference)
2174 (plist-get info :with-footnotes))
2175 ;; ... LaTeX environments and fragments...
2176 ((latex-environment latex-fragment)
2177 (let ((with-latex-p (plist-get info :with-latex)))
2178 (and with-latex-p (not (eq with-latex-p 'verbatim)))))
2179 ;; ... sub/superscripts...
2180 ((subscript superscript)
2181 (let ((sub/super-p (plist-get info :with-sub-superscript)))
2182 (if (eq sub/super-p '{})
2183 (org-element-property :use-brackets-p blob)
2184 sub/super-p)))
2185 ;; ... tables...
2186 (table (plist-get info :with-tables))
2187 (otherwise t)))
2189 (defun org-export-expand (blob contents)
2190 "Expand a parsed element or object to its original state.
2191 BLOB is either an element or an object. CONTENTS is its
2192 contents, as a string or nil."
2193 (funcall
2194 (intern (format "org-element-%s-interpreter" (org-element-type blob)))
2195 blob contents))
2197 (defun org-export-ignore-element (element info)
2198 "Add ELEMENT to `:ignore-list' in INFO.
2200 Any element in `:ignore-list' will be skipped when using
2201 `org-element-map'. INFO is modified by side effects."
2202 (plist-put info :ignore-list (cons element (plist-get info :ignore-list))))
2206 ;;; The Filter System
2208 ;; Filters allow end-users to tweak easily the transcoded output.
2209 ;; They are the functional counterpart of hooks, as every filter in
2210 ;; a set is applied to the return value of the previous one.
2212 ;; Every set is back-end agnostic. Although, a filter is always
2213 ;; called, in addition to the string it applies to, with the back-end
2214 ;; used as argument, so it's easy for the end-user to add back-end
2215 ;; specific filters in the set. The communication channel, as
2216 ;; a plist, is required as the third argument.
2218 ;; From the developer side, filters sets can be installed in the
2219 ;; process with the help of `org-export-define-backend', which
2220 ;; internally stores filters as an alist. Each association has a key
2221 ;; among the following symbols and a function or a list of functions
2222 ;; as value.
2224 ;; - `:filter-options' applies to the property list containing export
2225 ;; options. Unlike to other filters, functions in this list accept
2226 ;; two arguments instead of three: the property list containing
2227 ;; export options and the back-end. Users can set its value through
2228 ;; `org-export-filter-options-functions' variable.
2230 ;; - `:filter-parse-tree' applies directly to the complete parsed
2231 ;; tree. Users can set it through
2232 ;; `org-export-filter-parse-tree-functions' variable.
2234 ;; - `:filter-final-output' applies to the final transcoded string.
2235 ;; Users can set it with `org-export-filter-final-output-functions'
2236 ;; variable
2238 ;; - `:filter-plain-text' applies to any string not recognized as Org
2239 ;; syntax. `org-export-filter-plain-text-functions' allows users to
2240 ;; configure it.
2242 ;; - `:filter-TYPE' applies on the string returned after an element or
2243 ;; object of type TYPE has been transcoded. An user can modify
2244 ;; `org-export-filter-TYPE-functions'
2246 ;; All filters sets are applied with
2247 ;; `org-export-filter-apply-functions' function. Filters in a set are
2248 ;; applied in a LIFO fashion. It allows developers to be sure that
2249 ;; their filters will be applied first.
2251 ;; Filters properties are installed in communication channel with
2252 ;; `org-export-install-filters' function.
2254 ;; Eventually, two hooks (`org-export-before-processing-hook' and
2255 ;; `org-export-before-parsing-hook') are run at the beginning of the
2256 ;; export process and just before parsing to allow for heavy structure
2257 ;; modifications.
2260 ;;;; Hooks
2262 (defvar org-export-before-processing-hook nil
2263 "Hook run at the beginning of the export process.
2265 This is run before include keywords and macros are expanded and
2266 Babel code blocks executed, on a copy of the original buffer
2267 being exported. Visibility and narrowing are preserved. Point
2268 is at the beginning of the buffer.
2270 Every function in this hook will be called with one argument: the
2271 back-end currently used, as a symbol.")
2273 (defvar org-export-before-parsing-hook nil
2274 "Hook run before parsing an export buffer.
2276 This is run after include keywords and macros have been expanded
2277 and Babel code blocks executed, on a copy of the original buffer
2278 being exported. Visibility and narrowing are preserved. Point
2279 is at the beginning of the buffer.
2281 Every function in this hook will be called with one argument: the
2282 back-end currently used, as a symbol.")
2285 ;;;; Special Filters
2287 (defvar org-export-filter-options-functions nil
2288 "List of functions applied to the export options.
2289 Each filter is called with two arguments: the export options, as
2290 a plist, and the back-end, as a symbol. It must return
2291 a property list containing export options.")
2293 (defvar org-export-filter-parse-tree-functions nil
2294 "List of functions applied to the parsed tree.
2295 Each filter is called with three arguments: the parse tree, as
2296 returned by `org-element-parse-buffer', the back-end, as
2297 a symbol, and the communication channel, as a plist. It must
2298 return the modified parse tree to transcode.")
2300 (defvar org-export-filter-plain-text-functions nil
2301 "List of functions applied to plain text.
2302 Each filter is called with three arguments: a string which
2303 contains no Org syntax, the back-end, as a symbol, and the
2304 communication channel, as a plist. It must return a string or
2305 nil.")
2307 (defvar org-export-filter-final-output-functions nil
2308 "List of functions applied to the transcoded string.
2309 Each filter is called with three arguments: the full transcoded
2310 string, the back-end, as a symbol, and the communication channel,
2311 as a plist. It must return a string that will be used as the
2312 final export output.")
2315 ;;;; Elements Filters
2317 (defvar org-export-filter-babel-call-functions nil
2318 "List of functions applied to a transcoded babel-call.
2319 Each filter is called with three arguments: the transcoded data,
2320 as a string, the back-end, as a symbol, and the communication
2321 channel, as a plist. It must return a string or nil.")
2323 (defvar org-export-filter-center-block-functions nil
2324 "List of functions applied to a transcoded center block.
2325 Each filter is called with three arguments: the transcoded data,
2326 as a string, the back-end, as a symbol, and the communication
2327 channel, as a plist. It must return a string or nil.")
2329 (defvar org-export-filter-clock-functions nil
2330 "List of functions applied to a transcoded clock.
2331 Each filter is called with three arguments: the transcoded data,
2332 as a string, the back-end, as a symbol, and the communication
2333 channel, as a plist. It must return a string or nil.")
2335 (defvar org-export-filter-comment-functions nil
2336 "List of functions applied to a transcoded comment.
2337 Each filter is called with three arguments: the transcoded data,
2338 as a string, the back-end, as a symbol, and the communication
2339 channel, as a plist. It must return a string or nil.")
2341 (defvar org-export-filter-comment-block-functions nil
2342 "List of functions applied to a transcoded comment-block.
2343 Each filter is called with three arguments: the transcoded data,
2344 as a string, the back-end, as a symbol, and the communication
2345 channel, as a plist. It must return a string or nil.")
2347 (defvar org-export-filter-diary-sexp-functions nil
2348 "List of functions applied to a transcoded diary-sexp.
2349 Each filter is called with three arguments: the transcoded data,
2350 as a string, the back-end, as a symbol, and the communication
2351 channel, as a plist. It must return a string or nil.")
2353 (defvar org-export-filter-drawer-functions nil
2354 "List of functions applied to a transcoded drawer.
2355 Each filter is called with three arguments: the transcoded data,
2356 as a string, the back-end, as a symbol, and the communication
2357 channel, as a plist. It must return a string or nil.")
2359 (defvar org-export-filter-dynamic-block-functions nil
2360 "List of functions applied to a transcoded dynamic-block.
2361 Each filter is called with three arguments: the transcoded data,
2362 as a string, the back-end, as a symbol, and the communication
2363 channel, as a plist. It must return a string or nil.")
2365 (defvar org-export-filter-example-block-functions nil
2366 "List of functions applied to a transcoded example-block.
2367 Each filter is called with three arguments: the transcoded data,
2368 as a string, the back-end, as a symbol, and the communication
2369 channel, as a plist. It must return a string or nil.")
2371 (defvar org-export-filter-export-block-functions nil
2372 "List of functions applied to a transcoded export-block.
2373 Each filter is called with three arguments: the transcoded data,
2374 as a string, the back-end, as a symbol, and the communication
2375 channel, as a plist. It must return a string or nil.")
2377 (defvar org-export-filter-fixed-width-functions nil
2378 "List of functions applied to a transcoded fixed-width.
2379 Each filter is called with three arguments: the transcoded data,
2380 as a string, the back-end, as a symbol, and the communication
2381 channel, as a plist. It must return a string or nil.")
2383 (defvar org-export-filter-footnote-definition-functions nil
2384 "List of functions applied to a transcoded footnote-definition.
2385 Each filter is called with three arguments: the transcoded data,
2386 as a string, the back-end, as a symbol, and the communication
2387 channel, as a plist. It must return a string or nil.")
2389 (defvar org-export-filter-headline-functions nil
2390 "List of functions applied to a transcoded headline.
2391 Each filter is called with three arguments: the transcoded data,
2392 as a string, the back-end, as a symbol, and the communication
2393 channel, as a plist. It must return a string or nil.")
2395 (defvar org-export-filter-horizontal-rule-functions nil
2396 "List of functions applied to a transcoded horizontal-rule.
2397 Each filter is called with three arguments: the transcoded data,
2398 as a string, the back-end, as a symbol, and the communication
2399 channel, as a plist. It must return a string or nil.")
2401 (defvar org-export-filter-inlinetask-functions nil
2402 "List of functions applied to a transcoded inlinetask.
2403 Each filter is called with three arguments: the transcoded data,
2404 as a string, the back-end, as a symbol, and the communication
2405 channel, as a plist. It must return a string or nil.")
2407 (defvar org-export-filter-item-functions nil
2408 "List of functions applied to a transcoded item.
2409 Each filter is called with three arguments: the transcoded data,
2410 as a string, the back-end, as a symbol, and the communication
2411 channel, as a plist. It must return a string or nil.")
2413 (defvar org-export-filter-keyword-functions nil
2414 "List of functions applied to a transcoded keyword.
2415 Each filter is called with three arguments: the transcoded data,
2416 as a string, the back-end, as a symbol, and the communication
2417 channel, as a plist. It must return a string or nil.")
2419 (defvar org-export-filter-latex-environment-functions nil
2420 "List of functions applied to a transcoded latex-environment.
2421 Each filter is called with three arguments: the transcoded data,
2422 as a string, the back-end, as a symbol, and the communication
2423 channel, as a plist. It must return a string or nil.")
2425 (defvar org-export-filter-node-property-functions nil
2426 "List of functions applied to a transcoded node-property.
2427 Each filter is called with three arguments: the transcoded data,
2428 as a string, the back-end, as a symbol, and the communication
2429 channel, as a plist. It must return a string or nil.")
2431 (defvar org-export-filter-paragraph-functions nil
2432 "List of functions applied to a transcoded paragraph.
2433 Each filter is called with three arguments: the transcoded data,
2434 as a string, the back-end, as a symbol, and the communication
2435 channel, as a plist. It must return a string or nil.")
2437 (defvar org-export-filter-plain-list-functions nil
2438 "List of functions applied to a transcoded plain-list.
2439 Each filter is called with three arguments: the transcoded data,
2440 as a string, the back-end, as a symbol, and the communication
2441 channel, as a plist. It must return a string or nil.")
2443 (defvar org-export-filter-planning-functions nil
2444 "List of functions applied to a transcoded planning.
2445 Each filter is called with three arguments: the transcoded data,
2446 as a string, the back-end, as a symbol, and the communication
2447 channel, as a plist. It must return a string or nil.")
2449 (defvar org-export-filter-property-drawer-functions nil
2450 "List of functions applied to a transcoded property-drawer.
2451 Each filter is called with three arguments: the transcoded data,
2452 as a string, the back-end, as a symbol, and the communication
2453 channel, as a plist. It must return a string or nil.")
2455 (defvar org-export-filter-quote-block-functions nil
2456 "List of functions applied to a transcoded quote block.
2457 Each filter is called with three arguments: the transcoded quote
2458 data, as a string, the back-end, as a symbol, and the
2459 communication channel, as a plist. It must return a string or
2460 nil.")
2462 (defvar org-export-filter-quote-section-functions nil
2463 "List of functions applied to a transcoded quote-section.
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-section-functions nil
2469 "List of functions applied to a transcoded section.
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-special-block-functions nil
2475 "List of functions applied to a transcoded special block.
2476 Each filter is called with three arguments: the transcoded data,
2477 as a string, the back-end, as a symbol, and the communication
2478 channel, as a plist. It must return a string or nil.")
2480 (defvar org-export-filter-src-block-functions nil
2481 "List of functions applied to a transcoded src-block.
2482 Each filter is called with three arguments: the transcoded data,
2483 as a string, the back-end, as a symbol, and the communication
2484 channel, as a plist. It must return a string or nil.")
2486 (defvar org-export-filter-table-functions nil
2487 "List of functions applied to a transcoded table.
2488 Each filter is called with three arguments: the transcoded data,
2489 as a string, the back-end, as a symbol, and the communication
2490 channel, as a plist. It must return a string or nil.")
2492 (defvar org-export-filter-table-cell-functions nil
2493 "List of functions applied to a transcoded table-cell.
2494 Each filter is called with three arguments: the transcoded data,
2495 as a string, the back-end, as a symbol, and the communication
2496 channel, as a plist. It must return a string or nil.")
2498 (defvar org-export-filter-table-row-functions nil
2499 "List of functions applied to a transcoded table-row.
2500 Each filter is called with three arguments: the transcoded data,
2501 as a string, the back-end, as a symbol, and the communication
2502 channel, as a plist. It must return a string or nil.")
2504 (defvar org-export-filter-verse-block-functions nil
2505 "List of functions applied to a transcoded verse block.
2506 Each filter is called with three arguments: the transcoded data,
2507 as a string, the back-end, as a symbol, and the communication
2508 channel, as a plist. It must return a string or nil.")
2511 ;;;; Objects Filters
2513 (defvar org-export-filter-bold-functions nil
2514 "List of functions applied to transcoded bold text.
2515 Each filter is called with three arguments: the transcoded data,
2516 as a string, the back-end, as a symbol, and the communication
2517 channel, as a plist. It must return a string or nil.")
2519 (defvar org-export-filter-code-functions nil
2520 "List of functions applied to transcoded code text.
2521 Each filter is called with three arguments: the transcoded data,
2522 as a string, the back-end, as a symbol, and the communication
2523 channel, as a plist. It must return a string or nil.")
2525 (defvar org-export-filter-entity-functions nil
2526 "List of functions applied to a transcoded entity.
2527 Each filter is called with three arguments: the transcoded data,
2528 as a string, the back-end, as a symbol, and the communication
2529 channel, as a plist. It must return a string or nil.")
2531 (defvar org-export-filter-export-snippet-functions nil
2532 "List of functions applied to a transcoded export-snippet.
2533 Each filter is called with three arguments: the transcoded data,
2534 as a string, the back-end, as a symbol, and the communication
2535 channel, as a plist. It must return a string or nil.")
2537 (defvar org-export-filter-footnote-reference-functions nil
2538 "List of functions applied to a transcoded footnote-reference.
2539 Each filter is called with three arguments: the transcoded data,
2540 as a string, the back-end, as a symbol, and the communication
2541 channel, as a plist. It must return a string or nil.")
2543 (defvar org-export-filter-inline-babel-call-functions nil
2544 "List of functions applied to a transcoded inline-babel-call.
2545 Each filter is called with three arguments: the transcoded data,
2546 as a string, the back-end, as a symbol, and the communication
2547 channel, as a plist. It must return a string or nil.")
2549 (defvar org-export-filter-inline-src-block-functions nil
2550 "List of functions applied to a transcoded inline-src-block.
2551 Each filter is called with three arguments: the transcoded data,
2552 as a string, the back-end, as a symbol, and the communication
2553 channel, as a plist. It must return a string or nil.")
2555 (defvar org-export-filter-italic-functions nil
2556 "List of functions applied to transcoded italic text.
2557 Each filter is called with three arguments: the transcoded data,
2558 as a string, the back-end, as a symbol, and the communication
2559 channel, as a plist. It must return a string or nil.")
2561 (defvar org-export-filter-latex-fragment-functions nil
2562 "List of functions applied to a transcoded latex-fragment.
2563 Each filter is called with three arguments: the transcoded data,
2564 as a string, the back-end, as a symbol, and the communication
2565 channel, as a plist. It must return a string or nil.")
2567 (defvar org-export-filter-line-break-functions nil
2568 "List of functions applied to a transcoded line-break.
2569 Each filter is called with three arguments: the transcoded data,
2570 as a string, the back-end, as a symbol, and the communication
2571 channel, as a plist. It must return a string or nil.")
2573 (defvar org-export-filter-link-functions nil
2574 "List of functions applied to a transcoded link.
2575 Each filter is called with three arguments: the transcoded data,
2576 as a string, the back-end, as a symbol, and the communication
2577 channel, as a plist. It must return a string or nil.")
2579 (defvar org-export-filter-macro-functions nil
2580 "List of functions applied to a transcoded macro.
2581 Each filter is called with three arguments: the transcoded data,
2582 as a string, the back-end, as a symbol, and the communication
2583 channel, as a plist. It must return a string or nil.")
2585 (defvar org-export-filter-radio-target-functions nil
2586 "List of functions applied to a transcoded radio-target.
2587 Each filter is called with three arguments: the transcoded data,
2588 as a string, the back-end, as a symbol, and the communication
2589 channel, as a plist. It must return a string or nil.")
2591 (defvar org-export-filter-statistics-cookie-functions nil
2592 "List of functions applied to a transcoded statistics-cookie.
2593 Each filter is called with three arguments: the transcoded data,
2594 as a string, the back-end, as a symbol, and the communication
2595 channel, as a plist. It must return a string or nil.")
2597 (defvar org-export-filter-strike-through-functions nil
2598 "List of functions applied to transcoded strike-through text.
2599 Each filter is called with three arguments: the transcoded data,
2600 as a string, the back-end, as a symbol, and the communication
2601 channel, as a plist. It must return a string or nil.")
2603 (defvar org-export-filter-subscript-functions nil
2604 "List of functions applied to a transcoded subscript.
2605 Each filter is called with three arguments: the transcoded data,
2606 as a string, the back-end, as a symbol, and the communication
2607 channel, as a plist. It must return a string or nil.")
2609 (defvar org-export-filter-superscript-functions nil
2610 "List of functions applied to a transcoded superscript.
2611 Each filter is called with three arguments: the transcoded data,
2612 as a string, the back-end, as a symbol, and the communication
2613 channel, as a plist. It must return a string or nil.")
2615 (defvar org-export-filter-target-functions nil
2616 "List of functions applied to a transcoded target.
2617 Each filter is called with three arguments: the transcoded data,
2618 as a string, the back-end, as a symbol, and the communication
2619 channel, as a plist. It must return a string or nil.")
2621 (defvar org-export-filter-timestamp-functions nil
2622 "List of functions applied to a transcoded timestamp.
2623 Each filter is called with three arguments: the transcoded data,
2624 as a string, the back-end, as a symbol, and the communication
2625 channel, as a plist. It must return a string or nil.")
2627 (defvar org-export-filter-underline-functions nil
2628 "List of functions applied to transcoded underline text.
2629 Each filter is called with three arguments: the transcoded data,
2630 as a string, the back-end, as a symbol, and the communication
2631 channel, as a plist. It must return a string or nil.")
2633 (defvar org-export-filter-verbatim-functions nil
2634 "List of functions applied to transcoded verbatim text.
2635 Each filter is called with three arguments: the transcoded data,
2636 as a string, the back-end, as a symbol, and the communication
2637 channel, as a plist. It must return a string or nil.")
2640 ;;;; Filters Tools
2642 ;; Internal function `org-export-install-filters' installs filters
2643 ;; hard-coded in back-ends (developer filters) and filters from global
2644 ;; variables (user filters) in the communication channel.
2646 ;; Internal function `org-export-filter-apply-functions' takes care
2647 ;; about applying each filter in order to a given data. It ignores
2648 ;; filters returning a nil value but stops whenever a filter returns
2649 ;; an empty string.
2651 (defun org-export-filter-apply-functions (filters value info)
2652 "Call every function in FILTERS.
2654 Functions are called with arguments VALUE, current export
2655 back-end and INFO. A function returning a nil value will be
2656 skipped. If it returns the empty string, the process ends and
2657 VALUE is ignored.
2659 Call is done in a LIFO fashion, to be sure that developer
2660 specified filters, if any, are called first."
2661 (catch 'exit
2662 (dolist (filter filters value)
2663 (let ((result (funcall filter value (plist-get info :back-end) info)))
2664 (cond ((not result) value)
2665 ((equal value "") (throw 'exit nil))
2666 (t (setq value result)))))))
2668 (defun org-export-install-filters (info)
2669 "Install filters properties in communication channel.
2670 INFO is a plist containing the current communication channel.
2671 Return the updated communication channel."
2672 (let (plist)
2673 ;; Install user-defined filters with `org-export-filters-alist'
2674 ;; and filters already in INFO (through ext-plist mechanism).
2675 (mapc (lambda (p)
2676 (let* ((prop (car p))
2677 (info-value (plist-get info prop))
2678 (default-value (symbol-value (cdr p))))
2679 (setq plist
2680 (plist-put plist prop
2681 ;; Filters in INFO will be called
2682 ;; before those user provided.
2683 (append (if (listp info-value) info-value
2684 (list info-value))
2685 default-value)))))
2686 org-export-filters-alist)
2687 ;; Prepend back-end specific filters to that list.
2688 (mapc (lambda (p)
2689 ;; Single values get consed, lists are appended.
2690 (let ((key (car p)) (value (cdr p)))
2691 (when value
2692 (setq plist
2693 (plist-put
2694 plist key
2695 (if (atom value) (cons value (plist-get plist key))
2696 (append value (plist-get plist key))))))))
2697 (org-export-backend-filters (plist-get info :back-end)))
2698 ;; Return new communication channel.
2699 (org-combine-plists info plist)))
2703 ;;; Core functions
2705 ;; This is the room for the main function, `org-export-as', along with
2706 ;; its derivatives, `org-export-to-buffer', `org-export-to-file' and
2707 ;; `org-export-string-as'. They differ either by the way they output
2708 ;; the resulting code (for the first two) or by the input type (for
2709 ;; the latter).
2711 ;; `org-export-output-file-name' is an auxiliary function meant to be
2712 ;; used with `org-export-to-file'. With a given extension, it tries
2713 ;; to provide a canonical file name to write export output to.
2715 ;; Note that `org-export-as' doesn't really parse the current buffer,
2716 ;; but a copy of it (with the same buffer-local variables and
2717 ;; visibility), where macros and include keywords are expanded and
2718 ;; Babel blocks are executed, if appropriate.
2719 ;; `org-export-with-buffer-copy' macro prepares that copy.
2721 ;; File inclusion is taken care of by
2722 ;; `org-export-expand-include-keyword' and
2723 ;; `org-export--prepare-file-contents'. Structure wise, including
2724 ;; a whole Org file in a buffer often makes little sense. For
2725 ;; example, if the file contains a headline and the include keyword
2726 ;; was within an item, the item should contain the headline. That's
2727 ;; why file inclusion should be done before any structure can be
2728 ;; associated to the file, that is before parsing.
2730 (defun org-export-copy-buffer ()
2731 "Return a copy of the current buffer.
2732 The copy preserves Org buffer-local variables, visibility and
2733 narrowing."
2734 (let ((copy-buffer-fun (org-export--generate-copy-script (current-buffer)))
2735 (new-buf (generate-new-buffer (buffer-name))))
2736 (with-current-buffer new-buf
2737 (funcall copy-buffer-fun)
2738 (set-buffer-modified-p nil))
2739 new-buf))
2741 (defmacro org-export-with-buffer-copy (&rest body)
2742 "Apply BODY in a copy of the current buffer.
2743 The copy preserves local variables, visibility and contents of
2744 the original buffer. Point is at the beginning of the buffer
2745 when BODY is applied."
2746 (declare (debug t))
2747 (org-with-gensyms (buf-copy)
2748 `(let ((,buf-copy (org-export-copy-buffer)))
2749 (unwind-protect
2750 (with-current-buffer ,buf-copy
2751 (goto-char (point-min))
2752 (progn ,@body))
2753 (and (buffer-live-p ,buf-copy)
2754 ;; Kill copy without confirmation.
2755 (progn (with-current-buffer ,buf-copy
2756 (restore-buffer-modified-p nil))
2757 (kill-buffer ,buf-copy)))))))
2759 (defun org-export--generate-copy-script (buffer)
2760 "Generate a function duplicating BUFFER.
2762 The copy will preserve local variables, visibility, contents and
2763 narrowing of the original buffer. If a region was active in
2764 BUFFER, contents will be narrowed to that region instead.
2766 The resulting function can be evaled at a later time, from
2767 another buffer, effectively cloning the original buffer there.
2769 The function assumes BUFFER's major mode is `org-mode'."
2770 (with-current-buffer buffer
2771 `(lambda ()
2772 (let ((inhibit-modification-hooks t))
2773 ;; Set major mode. Ignore `org-mode-hook' as it has been run
2774 ;; already in BUFFER.
2775 (let ((org-mode-hook nil)) (org-mode))
2776 ;; Buffer local variables.
2777 ,@(let (local-vars)
2778 (mapc
2779 (lambda (entry)
2780 (when (consp entry)
2781 (let ((var (car entry))
2782 (val (cdr entry)))
2783 (and (not (eq var 'org-font-lock-keywords))
2784 (or (memq var
2785 '(default-directory
2786 buffer-file-name
2787 buffer-file-coding-system))
2788 (string-match "^\\(org-\\|orgtbl-\\)"
2789 (symbol-name var)))
2790 ;; Skip unreadable values, as they cannot be
2791 ;; sent to external process.
2792 (or (not val) (ignore-errors (read (format "%S" val))))
2793 (push `(set (make-local-variable (quote ,var))
2794 (quote ,val))
2795 local-vars)))))
2796 (buffer-local-variables (buffer-base-buffer)))
2797 local-vars)
2798 ;; Whole buffer contents.
2799 (insert
2800 ,(org-with-wide-buffer
2801 (buffer-substring-no-properties
2802 (point-min) (point-max))))
2803 ;; Narrowing.
2804 ,(if (org-region-active-p)
2805 `(narrow-to-region ,(region-beginning) ,(region-end))
2806 `(narrow-to-region ,(point-min) ,(point-max)))
2807 ;; Current position of point.
2808 (goto-char ,(point))
2809 ;; Overlays with invisible property.
2810 ,@(let (ov-set)
2811 (mapc
2812 (lambda (ov)
2813 (let ((invis-prop (overlay-get ov 'invisible)))
2814 (when invis-prop
2815 (push `(overlay-put
2816 (make-overlay ,(overlay-start ov)
2817 ,(overlay-end ov))
2818 'invisible (quote ,invis-prop))
2819 ov-set))))
2820 (overlays-in (point-min) (point-max)))
2821 ov-set)))))
2823 ;;;###autoload
2824 (defun org-export-as
2825 (backend &optional subtreep visible-only body-only ext-plist)
2826 "Transcode current Org buffer into BACKEND code.
2828 If narrowing is active in the current buffer, only transcode its
2829 narrowed part.
2831 If a region is active, transcode that region.
2833 When optional argument SUBTREEP is non-nil, transcode the
2834 sub-tree at point, extracting information from the headline
2835 properties first.
2837 When optional argument VISIBLE-ONLY is non-nil, don't export
2838 contents of hidden elements.
2840 When optional argument BODY-ONLY is non-nil, only return body
2841 code, without surrounding template.
2843 Optional argument EXT-PLIST, when provided, is a property list
2844 with external parameters overriding Org default settings, but
2845 still inferior to file-local settings.
2847 Return code as a string."
2848 (org-export-barf-if-invalid-backend backend)
2849 (save-excursion
2850 (save-restriction
2851 ;; Narrow buffer to an appropriate region or subtree for
2852 ;; parsing. If parsing subtree, be sure to remove main headline
2853 ;; too.
2854 (cond ((org-region-active-p)
2855 (narrow-to-region (region-beginning) (region-end)))
2856 (subtreep
2857 (org-narrow-to-subtree)
2858 (goto-char (point-min))
2859 (forward-line)
2860 (narrow-to-region (point) (point-max))))
2861 ;; Initialize communication channel with original buffer
2862 ;; attributes, unavailable in its copy.
2863 (let ((info (org-combine-plists
2864 (list :export-options
2865 (delq nil
2866 (list (and subtreep 'subtree)
2867 (and visible-only 'visible-only)
2868 (and body-only 'body-only))))
2869 (org-export--get-buffer-attributes)))
2870 tree)
2871 ;; Update communication channel and get parse tree. Buffer
2872 ;; isn't parsed directly. Instead, a temporary copy is
2873 ;; created, where include keywords, macros are expanded and
2874 ;; code blocks are evaluated.
2875 (org-export-with-buffer-copy
2876 ;; Run first hook with current back-end as argument.
2877 (run-hook-with-args 'org-export-before-processing-hook backend)
2878 (org-export-expand-include-keyword)
2879 ;; Update macro templates since #+INCLUDE keywords might have
2880 ;; added some new ones.
2881 (org-macro-initialize-templates)
2882 (org-macro-replace-all org-macro-templates)
2883 (org-export-execute-babel-code)
2884 ;; Update radio targets since keyword inclusion might have
2885 ;; added some more.
2886 (org-update-radio-target-regexp)
2887 ;; Run last hook with current back-end as argument.
2888 (goto-char (point-min))
2889 (run-hook-with-args 'org-export-before-parsing-hook backend)
2890 ;; Update communication channel with environment. Also
2891 ;; install user's and developer's filters.
2892 (setq info
2893 (org-export-install-filters
2894 (org-combine-plists
2895 info (org-export-get-environment backend subtreep ext-plist))))
2896 ;; Expand export-specific set of macros: {{{author}}},
2897 ;; {{{date}}}, {{{email}}} and {{{title}}}. It must be done
2898 ;; once regular macros have been expanded, since document
2899 ;; keywords may contain one of them.
2900 (org-macro-replace-all
2901 (list (cons "author"
2902 (org-element-interpret-data (plist-get info :author)))
2903 (cons "date"
2904 (org-element-interpret-data (plist-get info :date)))
2905 ;; EMAIL is not a parsed keyword: store it as-is.
2906 (cons "email" (or (plist-get info :email) ""))
2907 (cons "title"
2908 (org-element-interpret-data (plist-get info :title)))))
2909 ;; Call options filters and update export options. We do not
2910 ;; use `org-export-filter-apply-functions' here since the
2911 ;; arity of such filters is different.
2912 (dolist (filter (plist-get info :filter-options))
2913 (let ((result (funcall filter info backend)))
2914 (when result (setq info result))))
2915 ;; Parse buffer and call parse-tree filter on it.
2916 (setq tree
2917 (org-export-filter-apply-functions
2918 (plist-get info :filter-parse-tree)
2919 (org-element-parse-buffer nil visible-only) info))
2920 ;; Now tree is complete, compute its properties and add them
2921 ;; to communication channel.
2922 (setq info
2923 (org-combine-plists
2924 info (org-export-collect-tree-properties tree info)))
2925 ;; Eventually transcode TREE. Wrap the resulting string into
2926 ;; a template.
2927 (let* ((body (org-element-normalize-string
2928 (or (org-export-data tree info) "")))
2929 (inner-template (cdr (assq 'inner-template
2930 (plist-get info :translate-alist))))
2931 (full-body (if (not (functionp inner-template)) body
2932 (funcall inner-template body info)))
2933 (template (cdr (assq 'template
2934 (plist-get info :translate-alist)))))
2935 ;; Remove all text properties since they cannot be
2936 ;; retrieved from an external process. Finally call
2937 ;; final-output filter and return result.
2938 (org-no-properties
2939 (org-export-filter-apply-functions
2940 (plist-get info :filter-final-output)
2941 (if (or (not (functionp template)) body-only) full-body
2942 (funcall template full-body info))
2943 info))))))))
2945 ;;;###autoload
2946 (defun org-export-to-buffer
2947 (backend buffer &optional subtreep visible-only body-only ext-plist)
2948 "Call `org-export-as' with output to a specified buffer.
2950 BACKEND is the back-end used for transcoding, as a symbol.
2952 BUFFER is the output buffer. If it already exists, it will be
2953 erased first, otherwise, it will be created.
2955 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
2956 EXT-PLIST are similar to those used in `org-export-as', which
2957 see.
2959 If `org-export-copy-to-kill-ring' is non-nil, add buffer contents
2960 to kill ring. Return buffer."
2961 (let ((out (org-export-as backend subtreep visible-only body-only ext-plist))
2962 (buffer (get-buffer-create buffer)))
2963 (with-current-buffer buffer
2964 (erase-buffer)
2965 (insert out)
2966 (goto-char (point-min)))
2967 ;; Maybe add buffer contents to kill ring.
2968 (when (and org-export-copy-to-kill-ring (org-string-nw-p out))
2969 (org-kill-new out))
2970 ;; Return buffer.
2971 buffer))
2973 ;;;###autoload
2974 (defun org-export-to-file
2975 (backend file &optional subtreep visible-only body-only ext-plist)
2976 "Call `org-export-as' with output to a specified file.
2978 BACKEND is the back-end used for transcoding, as a symbol. FILE
2979 is the name of the output file, as a string.
2981 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
2982 EXT-PLIST are similar to those used in `org-export-as', which
2983 see.
2985 If `org-export-copy-to-kill-ring' is non-nil, add file contents
2986 to kill ring. Return output file's name."
2987 ;; Checks for FILE permissions. `write-file' would do the same, but
2988 ;; we'd rather avoid needless transcoding of parse tree.
2989 (unless (file-writable-p file) (error "Output file not writable"))
2990 ;; Insert contents to a temporary buffer and write it to FILE.
2991 (let ((out (org-export-as backend subtreep visible-only body-only ext-plist)))
2992 (with-temp-buffer
2993 (insert out)
2994 (let ((coding-system-for-write org-export-coding-system))
2995 (write-file file)))
2996 ;; Maybe add file contents to kill ring.
2997 (when (and org-export-copy-to-kill-ring (org-string-nw-p out))
2998 (org-kill-new out)))
2999 ;; Return full path.
3000 file)
3002 ;;;###autoload
3003 (defun org-export-string-as (string backend &optional body-only ext-plist)
3004 "Transcode STRING into BACKEND code.
3006 When optional argument BODY-ONLY is non-nil, only return body
3007 code, without preamble nor postamble.
3009 Optional argument EXT-PLIST, when provided, is a property list
3010 with external parameters overriding Org default settings, but
3011 still inferior to file-local settings.
3013 Return code as a string."
3014 (with-temp-buffer
3015 (insert string)
3016 (org-mode)
3017 (org-export-as backend nil nil body-only ext-plist)))
3019 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
3020 "Return output file's name according to buffer specifications.
3022 EXTENSION is a string representing the output file extension,
3023 with the leading dot.
3025 With a non-nil optional argument SUBTREEP, try to determine
3026 output file's name by looking for \"EXPORT_FILE_NAME\" property
3027 of subtree at point.
3029 When optional argument PUB-DIR is set, use it as the publishing
3030 directory.
3032 When optional argument VISIBLE-ONLY is non-nil, don't export
3033 contents of hidden elements.
3035 Return file name as a string."
3036 (let* ((visited-file (buffer-file-name (buffer-base-buffer)))
3037 (base-name
3038 ;; File name may come from EXPORT_FILE_NAME subtree
3039 ;; property, assuming point is at beginning of said
3040 ;; sub-tree.
3041 (file-name-sans-extension
3042 (or (and subtreep
3043 (org-entry-get
3044 (save-excursion
3045 (ignore-errors (org-back-to-heading) (point)))
3046 "EXPORT_FILE_NAME" t))
3047 ;; File name may be extracted from buffer's associated
3048 ;; file, if any.
3049 (and visited-file (file-name-nondirectory visited-file))
3050 ;; Can't determine file name on our own: Ask user.
3051 (let ((read-file-name-function
3052 (and org-completion-use-ido 'ido-read-file-name)))
3053 (read-file-name
3054 "Output file: " pub-dir nil nil nil
3055 (lambda (name)
3056 (string= (file-name-extension name t) extension)))))))
3057 (output-file
3058 ;; Build file name. Enforce EXTENSION over whatever user
3059 ;; may have come up with. PUB-DIR, if defined, always has
3060 ;; precedence over any provided path.
3061 (cond
3062 (pub-dir
3063 (concat (file-name-as-directory pub-dir)
3064 (file-name-nondirectory base-name)
3065 extension))
3066 ((file-name-absolute-p base-name) (concat base-name extension))
3067 (t (concat (file-name-as-directory ".") base-name extension)))))
3068 ;; If writing to OUTPUT-FILE would overwrite original file, append
3069 ;; EXTENSION another time to final name.
3070 (if (and visited-file (org-file-equal-p visited-file output-file))
3071 (concat output-file extension)
3072 output-file)))
3074 (defun org-export-expand-include-keyword (&optional included dir)
3075 "Expand every include keyword in buffer.
3076 Optional argument INCLUDED is a list of included file names along
3077 with their line restriction, when appropriate. It is used to
3078 avoid infinite recursion. Optional argument DIR is the current
3079 working directory. It is used to properly resolve relative
3080 paths."
3081 (let ((case-fold-search t))
3082 (goto-char (point-min))
3083 (while (re-search-forward "^[ \t]*#\\+INCLUDE: +\\(.*\\)[ \t]*$" nil t)
3084 (when (eq (org-element-type (save-match-data (org-element-at-point)))
3085 'keyword)
3086 (beginning-of-line)
3087 ;; Extract arguments from keyword's value.
3088 (let* ((value (match-string 1))
3089 (ind (org-get-indentation))
3090 (file (and (string-match "^\"\\(\\S-+\\)\"" value)
3091 (prog1 (expand-file-name (match-string 1 value) dir)
3092 (setq value (replace-match "" nil nil value)))))
3093 (lines
3094 (and (string-match
3095 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\"" value)
3096 (prog1 (match-string 1 value)
3097 (setq value (replace-match "" nil nil value)))))
3098 (env (cond ((string-match "\\<example\\>" value) 'example)
3099 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
3100 (match-string 1 value))))
3101 ;; Minimal level of included file defaults to the child
3102 ;; level of the current headline, if any, or one. It
3103 ;; only applies is the file is meant to be included as
3104 ;; an Org one.
3105 (minlevel
3106 (and (not env)
3107 (if (string-match ":minlevel +\\([0-9]+\\)" value)
3108 (prog1 (string-to-number (match-string 1 value))
3109 (setq value (replace-match "" nil nil value)))
3110 (let ((cur (org-current-level)))
3111 (if cur (1+ (org-reduced-level cur)) 1))))))
3112 ;; Remove keyword.
3113 (delete-region (point) (progn (forward-line) (point)))
3114 (cond
3115 ((not file) (error "Invalid syntax in INCLUDE keyword"))
3116 ((not (file-readable-p file)) (error "Cannot include file %s" file))
3117 ;; Check if files has already been parsed. Look after
3118 ;; inclusion lines too, as different parts of the same file
3119 ;; can be included too.
3120 ((member (list file lines) included)
3121 (error "Recursive file inclusion: %s" file))
3123 (cond
3124 ((eq env 'example)
3125 (insert
3126 (let ((ind-str (make-string ind ? ))
3127 (contents
3128 (org-escape-code-in-string
3129 (org-export--prepare-file-contents file lines))))
3130 (format "%s#+BEGIN_EXAMPLE\n%s%s#+END_EXAMPLE\n"
3131 ind-str contents ind-str))))
3132 ((stringp env)
3133 (insert
3134 (let ((ind-str (make-string ind ? ))
3135 (contents
3136 (org-escape-code-in-string
3137 (org-export--prepare-file-contents file lines))))
3138 (format "%s#+BEGIN_SRC %s\n%s%s#+END_SRC\n"
3139 ind-str env contents ind-str))))
3141 (insert
3142 (with-temp-buffer
3143 (org-mode)
3144 (insert
3145 (org-export--prepare-file-contents file lines ind minlevel))
3146 (org-export-expand-include-keyword
3147 (cons (list file lines) included)
3148 (file-name-directory file))
3149 (buffer-string))))))))))))
3151 (defun org-export--prepare-file-contents (file &optional lines ind minlevel)
3152 "Prepare the contents of FILE for inclusion and return them as a string.
3154 When optional argument LINES is a string specifying a range of
3155 lines, include only those lines.
3157 Optional argument IND, when non-nil, is an integer specifying the
3158 global indentation of returned contents. Since its purpose is to
3159 allow an included file to stay in the same environment it was
3160 created \(i.e. a list item), it doesn't apply past the first
3161 headline encountered.
3163 Optional argument MINLEVEL, when non-nil, is an integer
3164 specifying the level that any top-level headline in the included
3165 file should have."
3166 (with-temp-buffer
3167 (insert-file-contents file)
3168 (when lines
3169 (let* ((lines (split-string lines "-"))
3170 (lbeg (string-to-number (car lines)))
3171 (lend (string-to-number (cadr lines)))
3172 (beg (if (zerop lbeg) (point-min)
3173 (goto-char (point-min))
3174 (forward-line (1- lbeg))
3175 (point)))
3176 (end (if (zerop lend) (point-max)
3177 (goto-char (point-min))
3178 (forward-line (1- lend))
3179 (point))))
3180 (narrow-to-region beg end)))
3181 ;; Remove blank lines at beginning and end of contents. The logic
3182 ;; behind that removal is that blank lines around include keyword
3183 ;; override blank lines in included file.
3184 (goto-char (point-min))
3185 (org-skip-whitespace)
3186 (beginning-of-line)
3187 (delete-region (point-min) (point))
3188 (goto-char (point-max))
3189 (skip-chars-backward " \r\t\n")
3190 (forward-line)
3191 (delete-region (point) (point-max))
3192 ;; If IND is set, preserve indentation of include keyword until
3193 ;; the first headline encountered.
3194 (when ind
3195 (unless (eq major-mode 'org-mode) (org-mode))
3196 (goto-char (point-min))
3197 (let ((ind-str (make-string ind ? )))
3198 (while (not (or (eobp) (looking-at org-outline-regexp-bol)))
3199 ;; Do not move footnote definitions out of column 0.
3200 (unless (and (looking-at org-footnote-definition-re)
3201 (eq (org-element-type (org-element-at-point))
3202 'footnote-definition))
3203 (insert ind-str))
3204 (forward-line))))
3205 ;; When MINLEVEL is specified, compute minimal level for headlines
3206 ;; in the file (CUR-MIN), and remove stars to each headline so
3207 ;; that headlines with minimal level have a level of MINLEVEL.
3208 (when minlevel
3209 (unless (eq major-mode 'org-mode) (org-mode))
3210 (org-with-limited-levels
3211 (let ((levels (org-map-entries
3212 (lambda () (org-reduced-level (org-current-level))))))
3213 (when levels
3214 (let ((offset (- minlevel (apply 'min levels))))
3215 (unless (zerop offset)
3216 (when org-odd-levels-only (setq offset (* offset 2)))
3217 ;; Only change stars, don't bother moving whole
3218 ;; sections.
3219 (org-map-entries
3220 (lambda () (if (< offset 0) (delete-char (abs offset))
3221 (insert (make-string offset ?*)))))))))))
3222 (org-element-normalize-string (buffer-string))))
3224 (defun org-export-execute-babel-code ()
3225 "Execute every Babel code in the visible part of current buffer."
3226 ;; Get a pristine copy of current buffer so Babel references can be
3227 ;; properly resolved.
3228 (let ((reference (org-export-copy-buffer)))
3229 (unwind-protect (let ((org-current-export-file reference))
3230 (org-babel-exp-process-buffer))
3231 (kill-buffer reference))))
3235 ;;; Tools For Back-Ends
3237 ;; A whole set of tools is available to help build new exporters. Any
3238 ;; function general enough to have its use across many back-ends
3239 ;; should be added here.
3241 ;;;; For Affiliated Keywords
3243 ;; `org-export-read-attribute' reads a property from a given element
3244 ;; as a plist. It can be used to normalize affiliated keywords'
3245 ;; syntax.
3247 ;; Since captions can span over multiple lines and accept dual values,
3248 ;; their internal representation is a bit tricky. Therefore,
3249 ;; `org-export-get-caption' transparently returns a given element's
3250 ;; caption as a secondary string.
3252 (defun org-export-read-attribute (attribute element &optional property)
3253 "Turn ATTRIBUTE property from ELEMENT into a plist.
3255 When optional argument PROPERTY is non-nil, return the value of
3256 that property within attributes.
3258 This function assumes attributes are defined as \":keyword
3259 value\" pairs. It is appropriate for `:attr_html' like
3260 properties."
3261 (let ((attributes
3262 (let ((value (org-element-property attribute element)))
3263 (and value
3264 (read (format "(%s)" (mapconcat 'identity value " ")))))))
3265 (if property (plist-get attributes property) attributes)))
3267 (defun org-export-get-caption (element &optional shortp)
3268 "Return caption from ELEMENT as a secondary string.
3270 When optional argument SHORTP is non-nil, return short caption,
3271 as a secondary string, instead.
3273 Caption lines are separated by a white space."
3274 (let ((full-caption (org-element-property :caption element)) caption)
3275 (dolist (line full-caption (cdr caption))
3276 (let ((cap (funcall (if shortp 'cdr 'car) line)))
3277 (when cap
3278 (setq caption (nconc (list " ") (copy-sequence cap) caption)))))))
3281 ;;;; For Derived Back-ends
3283 ;; `org-export-with-backend' is a function allowing to locally use
3284 ;; another back-end to transcode some object or element. In a derived
3285 ;; back-end, it may be used as a fall-back function once all specific
3286 ;; cases have been treated.
3288 (defun org-export-with-backend (back-end data &optional contents info)
3289 "Call a transcoder from BACK-END on DATA.
3290 CONTENTS, when non-nil, is the transcoded contents of DATA
3291 element, as a string. INFO, when non-nil, is the communication
3292 channel used for export, as a plist.."
3293 (org-export-barf-if-invalid-backend back-end)
3294 (let ((type (org-element-type data)))
3295 (if (memq type '(nil org-data)) (error "No foreign transcoder available")
3296 (let ((transcoder
3297 (cdr (assq type (org-export-backend-translate-table back-end)))))
3298 (if (functionp transcoder) (funcall transcoder data contents info)
3299 (error "No foreign transcoder available"))))))
3302 ;;;; For Export Snippets
3304 ;; Every export snippet is transmitted to the back-end. Though, the
3305 ;; latter will only retain one type of export-snippet, ignoring
3306 ;; others, based on the former's target back-end. The function
3307 ;; `org-export-snippet-backend' returns that back-end for a given
3308 ;; export-snippet.
3310 (defun org-export-snippet-backend (export-snippet)
3311 "Return EXPORT-SNIPPET targeted back-end as a symbol.
3312 Translation, with `org-export-snippet-translation-alist', is
3313 applied."
3314 (let ((back-end (org-element-property :back-end export-snippet)))
3315 (intern
3316 (or (cdr (assoc back-end org-export-snippet-translation-alist))
3317 back-end))))
3320 ;;;; For Footnotes
3322 ;; `org-export-collect-footnote-definitions' is a tool to list
3323 ;; actually used footnotes definitions in the whole parse tree, or in
3324 ;; a headline, in order to add footnote listings throughout the
3325 ;; transcoded data.
3327 ;; `org-export-footnote-first-reference-p' is a predicate used by some
3328 ;; back-ends, when they need to attach the footnote definition only to
3329 ;; the first occurrence of the corresponding label.
3331 ;; `org-export-get-footnote-definition' and
3332 ;; `org-export-get-footnote-number' provide easier access to
3333 ;; additional information relative to a footnote reference.
3335 (defun org-export-collect-footnote-definitions (data info)
3336 "Return an alist between footnote numbers, labels and definitions.
3338 DATA is the parse tree from which definitions are collected.
3339 INFO is the plist used as a communication channel.
3341 Definitions are sorted by order of references. They either
3342 appear as Org data or as a secondary string for inlined
3343 footnotes. Unreferenced definitions are ignored."
3344 (let* (num-alist
3345 collect-fn ; for byte-compiler.
3346 (collect-fn
3347 (function
3348 (lambda (data)
3349 ;; Collect footnote number, label and definition in DATA.
3350 (org-element-map data 'footnote-reference
3351 (lambda (fn)
3352 (when (org-export-footnote-first-reference-p fn info)
3353 (let ((def (org-export-get-footnote-definition fn info)))
3354 (push
3355 (list (org-export-get-footnote-number fn info)
3356 (org-element-property :label fn)
3357 def)
3358 num-alist)
3359 ;; Also search in definition for nested footnotes.
3360 (when (eq (org-element-property :type fn) 'standard)
3361 (funcall collect-fn def)))))
3362 ;; Don't enter footnote definitions since it will happen
3363 ;; when their first reference is found.
3364 info nil 'footnote-definition)))))
3365 (funcall collect-fn (plist-get info :parse-tree))
3366 (reverse num-alist)))
3368 (defun org-export-footnote-first-reference-p (footnote-reference info)
3369 "Non-nil when a footnote reference is the first one for its label.
3371 FOOTNOTE-REFERENCE is the footnote reference being considered.
3372 INFO is the plist used as a communication channel."
3373 (let ((label (org-element-property :label footnote-reference)))
3374 ;; Anonymous footnotes are always a first reference.
3375 (if (not label) t
3376 ;; Otherwise, return the first footnote with the same LABEL and
3377 ;; test if it is equal to FOOTNOTE-REFERENCE.
3378 (let* (search-refs ; for byte-compiler.
3379 (search-refs
3380 (function
3381 (lambda (data)
3382 (org-element-map data 'footnote-reference
3383 (lambda (fn)
3384 (cond
3385 ((string= (org-element-property :label fn) label)
3386 (throw 'exit fn))
3387 ;; If FN isn't inlined, be sure to traverse its
3388 ;; definition before resuming search. See
3389 ;; comments in `org-export-get-footnote-number'
3390 ;; for more information.
3391 ((eq (org-element-property :type fn) 'standard)
3392 (funcall search-refs
3393 (org-export-get-footnote-definition fn info)))))
3394 ;; Don't enter footnote definitions since it will
3395 ;; happen when their first reference is found.
3396 info 'first-match 'footnote-definition)))))
3397 (eq (catch 'exit (funcall search-refs (plist-get info :parse-tree)))
3398 footnote-reference)))))
3400 (defun org-export-get-footnote-definition (footnote-reference info)
3401 "Return definition of FOOTNOTE-REFERENCE as parsed data.
3402 INFO is the plist used as a communication channel. If no such
3403 definition can be found, return the \"DEFINITION NOT FOUND\"
3404 string."
3405 (let ((label (org-element-property :label footnote-reference)))
3406 (or (org-element-property :inline-definition footnote-reference)
3407 (cdr (assoc label (plist-get info :footnote-definition-alist)))
3408 "DEFINITION NOT FOUND.")))
3410 (defun org-export-get-footnote-number (footnote info)
3411 "Return number associated to a footnote.
3413 FOOTNOTE is either a footnote reference or a footnote definition.
3414 INFO is the plist used as a communication channel."
3415 (let* ((label (org-element-property :label footnote))
3416 seen-refs
3417 search-ref ; For byte-compiler.
3418 (search-ref
3419 (function
3420 (lambda (data)
3421 ;; Search footnote references through DATA, filling
3422 ;; SEEN-REFS along the way.
3423 (org-element-map data 'footnote-reference
3424 (lambda (fn)
3425 (let ((fn-lbl (org-element-property :label fn)))
3426 (cond
3427 ;; Anonymous footnote match: return number.
3428 ((and (not fn-lbl) (eq fn footnote))
3429 (throw 'exit (1+ (length seen-refs))))
3430 ;; Labels match: return number.
3431 ((and label (string= label fn-lbl))
3432 (throw 'exit (1+ (length seen-refs))))
3433 ;; Anonymous footnote: it's always a new one.
3434 ;; Also, be sure to return nil from the `cond' so
3435 ;; `first-match' doesn't get us out of the loop.
3436 ((not fn-lbl) (push 'inline seen-refs) nil)
3437 ;; Label not seen so far: add it so SEEN-REFS.
3439 ;; Also search for subsequent references in
3440 ;; footnote definition so numbering follows
3441 ;; reading logic. Note that we don't have to care
3442 ;; about inline definitions, since
3443 ;; `org-element-map' already traverses them at the
3444 ;; right time.
3446 ;; Once again, return nil to stay in the loop.
3447 ((not (member fn-lbl seen-refs))
3448 (push fn-lbl seen-refs)
3449 (funcall search-ref
3450 (org-export-get-footnote-definition fn info))
3451 nil))))
3452 ;; Don't enter footnote definitions since it will
3453 ;; happen when their first reference is found.
3454 info 'first-match 'footnote-definition)))))
3455 (catch 'exit (funcall search-ref (plist-get info :parse-tree)))))
3458 ;;;; For Headlines
3460 ;; `org-export-get-relative-level' is a shortcut to get headline
3461 ;; level, relatively to the lower headline level in the parsed tree.
3463 ;; `org-export-get-headline-number' returns the section number of an
3464 ;; headline, while `org-export-number-to-roman' allows to convert it
3465 ;; to roman numbers.
3467 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
3468 ;; `org-export-last-sibling-p' are three useful predicates when it
3469 ;; comes to fulfill the `:headline-levels' property.
3471 ;; `org-export-get-tags', `org-export-get-category' and
3472 ;; `org-export-get-node-property' extract useful information from an
3473 ;; headline or a parent headline. They all handle inheritance.
3475 ;; `org-export-get-alt-title' tries to retrieve an alternative title,
3476 ;; as a secondary string, suitable for table of contents. It falls
3477 ;; back onto default title.
3479 (defun org-export-get-relative-level (headline info)
3480 "Return HEADLINE relative level within current parsed tree.
3481 INFO is a plist holding contextual information."
3482 (+ (org-element-property :level headline)
3483 (or (plist-get info :headline-offset) 0)))
3485 (defun org-export-low-level-p (headline info)
3486 "Non-nil when HEADLINE is considered as low level.
3488 INFO is a plist used as a communication channel.
3490 A low level headlines has a relative level greater than
3491 `:headline-levels' property value.
3493 Return value is the difference between HEADLINE relative level
3494 and the last level being considered as high enough, or nil."
3495 (let ((limit (plist-get info :headline-levels)))
3496 (when (wholenump limit)
3497 (let ((level (org-export-get-relative-level headline info)))
3498 (and (> level limit) (- level limit))))))
3500 (defun org-export-get-headline-number (headline info)
3501 "Return HEADLINE numbering as a list of numbers.
3502 INFO is a plist holding contextual information."
3503 (cdr (assoc headline (plist-get info :headline-numbering))))
3505 (defun org-export-numbered-headline-p (headline info)
3506 "Return a non-nil value if HEADLINE element should be numbered.
3507 INFO is a plist used as a communication channel."
3508 (let ((sec-num (plist-get info :section-numbers))
3509 (level (org-export-get-relative-level headline info)))
3510 (if (wholenump sec-num) (<= level sec-num) sec-num)))
3512 (defun org-export-number-to-roman (n)
3513 "Convert integer N into a roman numeral."
3514 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
3515 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
3516 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
3517 ( 1 . "I")))
3518 (res ""))
3519 (if (<= n 0)
3520 (number-to-string n)
3521 (while roman
3522 (if (>= n (caar roman))
3523 (setq n (- n (caar roman))
3524 res (concat res (cdar roman)))
3525 (pop roman)))
3526 res)))
3528 (defun org-export-get-tags (element info &optional tags inherited)
3529 "Return list of tags associated to ELEMENT.
3531 ELEMENT has either an `headline' or an `inlinetask' type. INFO
3532 is a plist used as a communication channel.
3534 Select tags (see `org-export-select-tags') and exclude tags (see
3535 `org-export-exclude-tags') are removed from the list.
3537 When non-nil, optional argument TAGS should be a list of strings.
3538 Any tag belonging to this list will also be removed.
3540 When optional argument INHERITED is non-nil, tags can also be
3541 inherited from parent headlines and FILETAGS keywords."
3542 (org-remove-if
3543 (lambda (tag) (or (member tag (plist-get info :select-tags))
3544 (member tag (plist-get info :exclude-tags))
3545 (member tag tags)))
3546 (if (not inherited) (org-element-property :tags element)
3547 ;; Build complete list of inherited tags.
3548 (let ((current-tag-list (org-element-property :tags element)))
3549 (mapc
3550 (lambda (parent)
3551 (mapc
3552 (lambda (tag)
3553 (when (and (memq (org-element-type parent) '(headline inlinetask))
3554 (not (member tag current-tag-list)))
3555 (push tag current-tag-list)))
3556 (org-element-property :tags parent)))
3557 (org-export-get-genealogy element))
3558 ;; Add FILETAGS keywords and return results.
3559 (org-uniquify (append (plist-get info :filetags) current-tag-list))))))
3561 (defun org-export-get-node-property (property blob &optional inherited)
3562 "Return node PROPERTY value for BLOB.
3564 PROPERTY is an upcase symbol (i.e. `:COOKIE_DATA'). BLOB is an
3565 element or object.
3567 If optional argument INHERITED is non-nil, the value can be
3568 inherited from a parent headline.
3570 Return value is a string or nil."
3571 (let ((headline (if (eq (org-element-type blob) 'headline) blob
3572 (org-export-get-parent-headline blob))))
3573 (if (not inherited) (org-element-property property blob)
3574 (let ((parent headline) value)
3575 (catch 'found
3576 (while parent
3577 (when (plist-member (nth 1 parent) property)
3578 (throw 'found (org-element-property property parent)))
3579 (setq parent (org-element-property :parent parent))))))))
3581 (defun org-export-get-category (blob info)
3582 "Return category for element or object BLOB.
3584 INFO is a plist used as a communication channel.
3586 CATEGORY is automatically inherited from a parent headline, from
3587 #+CATEGORY: keyword or created out of original file name. If all
3588 fail, the fall-back value is \"???\"."
3589 (or (let ((headline (if (eq (org-element-type blob) 'headline) blob
3590 (org-export-get-parent-headline blob))))
3591 ;; Almost like `org-export-node-property', but we cannot trust
3592 ;; `plist-member' as every headline has a `:CATEGORY'
3593 ;; property, would it be nil or equal to "???" (which has the
3594 ;; same meaning).
3595 (let ((parent headline) value)
3596 (catch 'found
3597 (while parent
3598 (let ((category (org-element-property :CATEGORY parent)))
3599 (and category (not (equal "???" category))
3600 (throw 'found category)))
3601 (setq parent (org-element-property :parent parent))))))
3602 (org-element-map (plist-get info :parse-tree) 'keyword
3603 (lambda (kwd)
3604 (when (equal (org-element-property :key kwd) "CATEGORY")
3605 (org-element-property :value kwd)))
3606 info 'first-match)
3607 (let ((file (plist-get info :input-file)))
3608 (and file (file-name-sans-extension (file-name-nondirectory file))))
3609 "???"))
3611 (defun org-export-get-alt-title (headline info)
3612 "Return alternative title for HEADLINE, as a secondary string.
3613 INFO is a plist used as a communication channel. If no optional
3614 title is defined, fall-back to the regular title."
3615 (or (org-element-property :alt-title headline)
3616 (org-element-property :title headline)))
3618 (defun org-export-first-sibling-p (headline info)
3619 "Non-nil when HEADLINE is the first sibling in its sub-tree.
3620 INFO is a plist used as a communication channel."
3621 (not (eq (org-element-type (org-export-get-previous-element headline info))
3622 'headline)))
3624 (defun org-export-last-sibling-p (headline info)
3625 "Non-nil when HEADLINE is the last sibling in its sub-tree.
3626 INFO is a plist used as a communication channel."
3627 (not (org-export-get-next-element headline info)))
3630 ;;;; For Links
3632 ;; `org-export-solidify-link-text' turns a string into a safer version
3633 ;; for links, replacing most non-standard characters with hyphens.
3635 ;; `org-export-get-coderef-format' returns an appropriate format
3636 ;; string for coderefs.
3638 ;; `org-export-inline-image-p' returns a non-nil value when the link
3639 ;; provided should be considered as an inline image.
3641 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
3642 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
3643 ;; returns an appropriate unique identifier when found, or nil.
3645 ;; `org-export-resolve-id-link' returns the first headline with
3646 ;; specified id or custom-id in parse tree, the path to the external
3647 ;; file with the id or nil when neither was found.
3649 ;; `org-export-resolve-coderef' associates a reference to a line
3650 ;; number in the element it belongs, or returns the reference itself
3651 ;; when the element isn't numbered.
3653 (defun org-export-solidify-link-text (s)
3654 "Take link text S and make a safe target out of it."
3655 (save-match-data
3656 (mapconcat 'identity (org-split-string s "[^a-zA-Z0-9_.-:]+") "-")))
3658 (defun org-export-get-coderef-format (path desc)
3659 "Return format string for code reference link.
3660 PATH is the link path. DESC is its description."
3661 (save-match-data
3662 (cond ((not desc) "%s")
3663 ((string-match (regexp-quote (concat "(" path ")")) desc)
3664 (replace-match "%s" t t desc))
3665 (t desc))))
3667 (defun org-export-inline-image-p (link &optional rules)
3668 "Non-nil if LINK object points to an inline image.
3670 Optional argument is a set of RULES defining inline images. It
3671 is an alist where associations have the following shape:
3673 \(TYPE . REGEXP)
3675 Applying a rule means apply REGEXP against LINK's path when its
3676 type is TYPE. The function will return a non-nil value if any of
3677 the provided rules is non-nil. The default rule is
3678 `org-export-default-inline-image-rule'.
3680 This only applies to links without a description."
3681 (and (not (org-element-contents link))
3682 (let ((case-fold-search t)
3683 (rules (or rules org-export-default-inline-image-rule)))
3684 (catch 'exit
3685 (mapc
3686 (lambda (rule)
3687 (and (string= (org-element-property :type link) (car rule))
3688 (string-match (cdr rule)
3689 (org-element-property :path link))
3690 (throw 'exit t)))
3691 rules)
3692 ;; Return nil if no rule matched.
3693 nil))))
3695 (defun org-export-resolve-coderef (ref info)
3696 "Resolve a code reference REF.
3698 INFO is a plist used as a communication channel.
3700 Return associated line number in source code, or REF itself,
3701 depending on src-block or example element's switches."
3702 (org-element-map (plist-get info :parse-tree) '(example-block src-block)
3703 (lambda (el)
3704 (with-temp-buffer
3705 (insert (org-trim (org-element-property :value el)))
3706 (let* ((label-fmt (regexp-quote
3707 (or (org-element-property :label-fmt el)
3708 org-coderef-label-format)))
3709 (ref-re
3710 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
3711 (replace-regexp-in-string "%s" ref label-fmt nil t))))
3712 ;; Element containing REF is found. Resolve it to either
3713 ;; a label or a line number, as needed.
3714 (when (re-search-backward ref-re nil t)
3715 (cond
3716 ((org-element-property :use-labels el) ref)
3717 ((eq (org-element-property :number-lines el) 'continued)
3718 (+ (org-export-get-loc el info) (line-number-at-pos)))
3719 (t (line-number-at-pos)))))))
3720 info 'first-match))
3722 (defun org-export-resolve-fuzzy-link (link info)
3723 "Return LINK destination.
3725 INFO is a plist holding contextual information.
3727 Return value can be an object, an element, or nil:
3729 - If LINK path matches a target object (i.e. <<path>>) or
3730 element (i.e. \"#+TARGET: path\"), return it.
3732 - If LINK path exactly matches the name affiliated keyword
3733 \(i.e. #+NAME: path) of an element, return that element.
3735 - If LINK path exactly matches any headline name, return that
3736 element. If more than one headline share that name, priority
3737 will be given to the one with the closest common ancestor, if
3738 any, or the first one in the parse tree otherwise.
3740 - Otherwise, return nil.
3742 Assume LINK type is \"fuzzy\". White spaces are not
3743 significant."
3744 (let* ((raw-path (org-element-property :path link))
3745 (match-title-p (eq (aref raw-path 0) ?*))
3746 ;; Split PATH at white spaces so matches are space
3747 ;; insensitive.
3748 (path (org-split-string
3749 (if match-title-p (substring raw-path 1) raw-path))))
3750 (cond
3751 ;; First try to find a matching "<<path>>" unless user specified
3752 ;; he was looking for a headline (path starts with a *
3753 ;; character).
3754 ((and (not match-title-p)
3755 (org-element-map (plist-get info :parse-tree) '(keyword target)
3756 (lambda (blob)
3757 (and (or (eq (org-element-type blob) 'target)
3758 (equal (org-element-property :key blob) "TARGET"))
3759 (equal (org-split-string (org-element-property :value blob))
3760 path)
3761 blob))
3762 info t)))
3763 ;; Then try to find an element with a matching "#+NAME: path"
3764 ;; affiliated keyword.
3765 ((and (not match-title-p)
3766 (org-element-map (plist-get info :parse-tree)
3767 org-element-all-elements
3768 (lambda (el)
3769 (let ((name (org-element-property :name el)))
3770 (when (and name (equal (org-split-string name) path)) el)))
3771 info 'first-match)))
3772 ;; Last case: link either points to a headline or to
3773 ;; nothingness. Try to find the source, with priority given to
3774 ;; headlines with the closest common ancestor. If such candidate
3775 ;; is found, return it, otherwise return nil.
3777 (let ((find-headline
3778 (function
3779 ;; Return first headline whose `:raw-value' property is
3780 ;; NAME in parse tree DATA, or nil. Statistics cookies
3781 ;; are ignored.
3782 (lambda (name data)
3783 (org-element-map data 'headline
3784 (lambda (headline)
3785 (when (equal (org-split-string
3786 (replace-regexp-in-string
3787 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
3788 (org-element-property :raw-value headline)))
3789 name)
3790 headline))
3791 info 'first-match)))))
3792 ;; Search among headlines sharing an ancestor with link, from
3793 ;; closest to farthest.
3794 (or (catch 'exit
3795 (mapc
3796 (lambda (parent)
3797 (when (eq (org-element-type parent) 'headline)
3798 (let ((foundp (funcall find-headline path parent)))
3799 (when foundp (throw 'exit foundp)))))
3800 (org-export-get-genealogy link)) nil)
3801 ;; No match with a common ancestor: try full parse-tree.
3802 (funcall find-headline path (plist-get info :parse-tree))))))))
3804 (defun org-export-resolve-id-link (link info)
3805 "Return headline referenced as LINK destination.
3807 INFO is a plist used as a communication channel.
3809 Return value can be the headline element matched in current parse
3810 tree, a file name or nil. Assume LINK type is either \"id\" or
3811 \"custom-id\"."
3812 (let ((id (org-element-property :path link)))
3813 ;; First check if id is within the current parse tree.
3814 (or (org-element-map (plist-get info :parse-tree) 'headline
3815 (lambda (headline)
3816 (when (or (string= (org-element-property :ID headline) id)
3817 (string= (org-element-property :CUSTOM_ID headline) id))
3818 headline))
3819 info 'first-match)
3820 ;; Otherwise, look for external files.
3821 (cdr (assoc id (plist-get info :id-alist))))))
3823 (defun org-export-resolve-radio-link (link info)
3824 "Return radio-target object referenced as LINK destination.
3826 INFO is a plist used as a communication channel.
3828 Return value can be a radio-target object or nil. Assume LINK
3829 has type \"radio\"."
3830 (let ((path (org-element-property :path link)))
3831 (org-element-map (plist-get info :parse-tree) 'radio-target
3832 (lambda (radio)
3833 (and (compare-strings
3834 (org-element-property :value radio) 0 nil path 0 nil t)
3835 radio))
3836 info 'first-match)))
3839 ;;;; For References
3841 ;; `org-export-get-ordinal' associates a sequence number to any object
3842 ;; or element.
3844 (defun org-export-get-ordinal (element info &optional types predicate)
3845 "Return ordinal number of an element or object.
3847 ELEMENT is the element or object considered. INFO is the plist
3848 used as a communication channel.
3850 Optional argument TYPES, when non-nil, is a list of element or
3851 object types, as symbols, that should also be counted in.
3852 Otherwise, only provided element's type is considered.
3854 Optional argument PREDICATE is a function returning a non-nil
3855 value if the current element or object should be counted in. It
3856 accepts two arguments: the element or object being considered and
3857 the plist used as a communication channel. This allows to count
3858 only a certain type of objects (i.e. inline images).
3860 Return value is a list of numbers if ELEMENT is a headline or an
3861 item. It is nil for keywords. It represents the footnote number
3862 for footnote definitions and footnote references. If ELEMENT is
3863 a target, return the same value as if ELEMENT was the closest
3864 table, item or headline containing the target. In any other
3865 case, return the sequence number of ELEMENT among elements or
3866 objects of the same type."
3867 ;; A target keyword, representing an invisible target, never has
3868 ;; a sequence number.
3869 (unless (eq (org-element-type element) 'keyword)
3870 ;; Ordinal of a target object refer to the ordinal of the closest
3871 ;; table, item, or headline containing the object.
3872 (when (eq (org-element-type element) 'target)
3873 (setq element
3874 (loop for parent in (org-export-get-genealogy element)
3875 when
3876 (memq
3877 (org-element-type parent)
3878 '(footnote-definition footnote-reference headline item
3879 table))
3880 return parent)))
3881 (case (org-element-type element)
3882 ;; Special case 1: A headline returns its number as a list.
3883 (headline (org-export-get-headline-number element info))
3884 ;; Special case 2: An item returns its number as a list.
3885 (item (let ((struct (org-element-property :structure element)))
3886 (org-list-get-item-number
3887 (org-element-property :begin element)
3888 struct
3889 (org-list-prevs-alist struct)
3890 (org-list-parents-alist struct))))
3891 ((footnote-definition footnote-reference)
3892 (org-export-get-footnote-number element info))
3893 (otherwise
3894 (let ((counter 0))
3895 ;; Increment counter until ELEMENT is found again.
3896 (org-element-map (plist-get info :parse-tree)
3897 (or types (org-element-type element))
3898 (lambda (el)
3899 (cond
3900 ((eq element el) (1+ counter))
3901 ((not predicate) (incf counter) nil)
3902 ((funcall predicate el info) (incf counter) nil)))
3903 info 'first-match))))))
3906 ;;;; For Src-Blocks
3908 ;; `org-export-get-loc' counts number of code lines accumulated in
3909 ;; src-block or example-block elements with a "+n" switch until
3910 ;; a given element, excluded. Note: "-n" switches reset that count.
3912 ;; `org-export-unravel-code' extracts source code (along with a code
3913 ;; references alist) from an `element-block' or `src-block' type
3914 ;; element.
3916 ;; `org-export-format-code' applies a formatting function to each line
3917 ;; of code, providing relative line number and code reference when
3918 ;; appropriate. Since it doesn't access the original element from
3919 ;; which the source code is coming, it expects from the code calling
3920 ;; it to know if lines should be numbered and if code references
3921 ;; should appear.
3923 ;; Eventually, `org-export-format-code-default' is a higher-level
3924 ;; function (it makes use of the two previous functions) which handles
3925 ;; line numbering and code references inclusion, and returns source
3926 ;; code in a format suitable for plain text or verbatim output.
3928 (defun org-export-get-loc (element info)
3929 "Return accumulated lines of code up to ELEMENT.
3931 INFO is the plist used as a communication channel.
3933 ELEMENT is excluded from count."
3934 (let ((loc 0))
3935 (org-element-map (plist-get info :parse-tree)
3936 `(src-block example-block ,(org-element-type element))
3937 (lambda (el)
3938 (cond
3939 ;; ELEMENT is reached: Quit the loop.
3940 ((eq el element))
3941 ;; Only count lines from src-block and example-block elements
3942 ;; with a "+n" or "-n" switch. A "-n" switch resets counter.
3943 ((not (memq (org-element-type el) '(src-block example-block))) nil)
3944 ((let ((linums (org-element-property :number-lines el)))
3945 (when linums
3946 ;; Accumulate locs or reset them.
3947 (let ((lines (org-count-lines
3948 (org-trim (org-element-property :value el)))))
3949 (setq loc (if (eq linums 'new) lines (+ loc lines))))))
3950 ;; Return nil to stay in the loop.
3951 nil)))
3952 info 'first-match)
3953 ;; Return value.
3954 loc))
3956 (defun org-export-unravel-code (element)
3957 "Clean source code and extract references out of it.
3959 ELEMENT has either a `src-block' an `example-block' type.
3961 Return a cons cell whose CAR is the source code, cleaned from any
3962 reference and protective comma and CDR is an alist between
3963 relative line number (integer) and name of code reference on that
3964 line (string)."
3965 (let* ((line 0) refs
3966 ;; Get code and clean it. Remove blank lines at its
3967 ;; beginning and end.
3968 (code (let ((c (replace-regexp-in-string
3969 "\\`\\([ \t]*\n\\)+" ""
3970 (replace-regexp-in-string
3971 "\\([ \t]*\n\\)*[ \t]*\\'" "\n"
3972 (org-element-property :value element)))))
3973 ;; If appropriate, remove global indentation.
3974 (if (or org-src-preserve-indentation
3975 (org-element-property :preserve-indent element))
3977 (org-remove-indentation c))))
3978 ;; Get format used for references.
3979 (label-fmt (regexp-quote
3980 (or (org-element-property :label-fmt element)
3981 org-coderef-label-format)))
3982 ;; Build a regexp matching a loc with a reference.
3983 (with-ref-re
3984 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)[ \t]*\\)$"
3985 (replace-regexp-in-string
3986 "%s" "\\([-a-zA-Z0-9_ ]+\\)" label-fmt nil t))))
3987 ;; Return value.
3988 (cons
3989 ;; Code with references removed.
3990 (org-element-normalize-string
3991 (mapconcat
3992 (lambda (loc)
3993 (incf line)
3994 (if (not (string-match with-ref-re loc)) loc
3995 ;; Ref line: remove ref, and signal its position in REFS.
3996 (push (cons line (match-string 3 loc)) refs)
3997 (replace-match "" nil nil loc 1)))
3998 (org-split-string code "\n") "\n"))
3999 ;; Reference alist.
4000 refs)))
4002 (defun org-export-format-code (code fun &optional num-lines ref-alist)
4003 "Format CODE by applying FUN line-wise and return it.
4005 CODE is a string representing the code to format. FUN is
4006 a function. It must accept three arguments: a line of
4007 code (string), the current line number (integer) or nil and the
4008 reference associated to the current line (string) or nil.
4010 Optional argument NUM-LINES can be an integer representing the
4011 number of code lines accumulated until the current code. Line
4012 numbers passed to FUN will take it into account. If it is nil,
4013 FUN's second argument will always be nil. This number can be
4014 obtained with `org-export-get-loc' function.
4016 Optional argument REF-ALIST can be an alist between relative line
4017 number (i.e. ignoring NUM-LINES) and the name of the code
4018 reference on it. If it is nil, FUN's third argument will always
4019 be nil. It can be obtained through the use of
4020 `org-export-unravel-code' function."
4021 (let ((--locs (org-split-string code "\n"))
4022 (--line 0))
4023 (org-element-normalize-string
4024 (mapconcat
4025 (lambda (--loc)
4026 (incf --line)
4027 (let ((--ref (cdr (assq --line ref-alist))))
4028 (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
4029 --locs "\n"))))
4031 (defun org-export-format-code-default (element info)
4032 "Return source code from ELEMENT, formatted in a standard way.
4034 ELEMENT is either a `src-block' or `example-block' element. INFO
4035 is a plist used as a communication channel.
4037 This function takes care of line numbering and code references
4038 inclusion. Line numbers, when applicable, appear at the
4039 beginning of the line, separated from the code by two white
4040 spaces. Code references, on the other hand, appear flushed to
4041 the right, separated by six white spaces from the widest line of
4042 code."
4043 ;; Extract code and references.
4044 (let* ((code-info (org-export-unravel-code element))
4045 (code (car code-info))
4046 (code-lines (org-split-string code "\n")))
4047 (if (null code-lines) ""
4048 (let* ((refs (and (org-element-property :retain-labels element)
4049 (cdr code-info)))
4050 ;; Handle line numbering.
4051 (num-start (case (org-element-property :number-lines element)
4052 (continued (org-export-get-loc element info))
4053 (new 0)))
4054 (num-fmt
4055 (and num-start
4056 (format "%%%ds "
4057 (length (number-to-string
4058 (+ (length code-lines) num-start))))))
4059 ;; Prepare references display, if required. Any reference
4060 ;; should start six columns after the widest line of code,
4061 ;; wrapped with parenthesis.
4062 (max-width
4063 (+ (apply 'max (mapcar 'length code-lines))
4064 (if (not num-start) 0 (length (format num-fmt num-start))))))
4065 (org-export-format-code
4066 code
4067 (lambda (loc line-num ref)
4068 (let ((number-str (and num-fmt (format num-fmt line-num))))
4069 (concat
4070 number-str
4072 (and ref
4073 (concat (make-string
4074 (- (+ 6 max-width)
4075 (+ (length loc) (length number-str))) ? )
4076 (format "(%s)" ref))))))
4077 num-start refs)))))
4080 ;;;; For Tables
4082 ;; `org-export-table-has-special-column-p' and and
4083 ;; `org-export-table-row-is-special-p' are predicates used to look for
4084 ;; meta-information about the table structure.
4086 ;; `org-table-has-header-p' tells when the rows before the first rule
4087 ;; should be considered as table's header.
4089 ;; `org-export-table-cell-width', `org-export-table-cell-alignment'
4090 ;; and `org-export-table-cell-borders' extract information from
4091 ;; a table-cell element.
4093 ;; `org-export-table-dimensions' gives the number on rows and columns
4094 ;; in the table, ignoring horizontal rules and special columns.
4095 ;; `org-export-table-cell-address', given a table-cell object, returns
4096 ;; the absolute address of a cell. On the other hand,
4097 ;; `org-export-get-table-cell-at' does the contrary.
4099 ;; `org-export-table-cell-starts-colgroup-p',
4100 ;; `org-export-table-cell-ends-colgroup-p',
4101 ;; `org-export-table-row-starts-rowgroup-p',
4102 ;; `org-export-table-row-ends-rowgroup-p',
4103 ;; `org-export-table-row-starts-header-p' and
4104 ;; `org-export-table-row-ends-header-p' indicate position of current
4105 ;; row or cell within the table.
4107 (defun org-export-table-has-special-column-p (table)
4108 "Non-nil when TABLE has a special column.
4109 All special columns will be ignored during export."
4110 ;; The table has a special column when every first cell of every row
4111 ;; has an empty value or contains a symbol among "/", "#", "!", "$",
4112 ;; "*" "_" and "^". Though, do not consider a first row containing
4113 ;; only empty cells as special.
4114 (let ((special-column-p 'empty))
4115 (catch 'exit
4116 (mapc
4117 (lambda (row)
4118 (when (eq (org-element-property :type row) 'standard)
4119 (let ((value (org-element-contents
4120 (car (org-element-contents row)))))
4121 (cond ((member value '(("/") ("#") ("!") ("$") ("*") ("_") ("^")))
4122 (setq special-column-p 'special))
4123 ((not value))
4124 (t (throw 'exit nil))))))
4125 (org-element-contents table))
4126 (eq special-column-p 'special))))
4128 (defun org-export-table-has-header-p (table info)
4129 "Non-nil when TABLE has an header.
4131 INFO is a plist used as a communication channel.
4133 A table has an header when it contains at least two row groups."
4134 (let ((rowgroup 1) row-flag)
4135 (org-element-map table 'table-row
4136 (lambda (row)
4137 (cond
4138 ((> rowgroup 1) t)
4139 ((and row-flag (eq (org-element-property :type row) 'rule))
4140 (incf rowgroup) (setq row-flag nil))
4141 ((and (not row-flag) (eq (org-element-property :type row) 'standard))
4142 (setq row-flag t) nil)))
4143 info)))
4145 (defun org-export-table-row-is-special-p (table-row info)
4146 "Non-nil if TABLE-ROW is considered special.
4148 INFO is a plist used as the communication channel.
4150 All special rows will be ignored during export."
4151 (when (eq (org-element-property :type table-row) 'standard)
4152 (let ((first-cell (org-element-contents
4153 (car (org-element-contents table-row)))))
4154 ;; A row is special either when...
4156 ;; ... it starts with a field only containing "/",
4157 (equal first-cell '("/"))
4158 ;; ... the table contains a special column and the row start
4159 ;; with a marking character among, "^", "_", "$" or "!",
4160 (and (org-export-table-has-special-column-p
4161 (org-export-get-parent table-row))
4162 (member first-cell '(("^") ("_") ("$") ("!"))))
4163 ;; ... it contains only alignment cookies and empty cells.
4164 (let ((special-row-p 'empty))
4165 (catch 'exit
4166 (mapc
4167 (lambda (cell)
4168 (let ((value (org-element-contents cell)))
4169 ;; Since VALUE is a secondary string, the following
4170 ;; checks avoid expanding it with `org-export-data'.
4171 (cond ((not value))
4172 ((and (not (cdr value))
4173 (stringp (car value))
4174 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'"
4175 (car value)))
4176 (setq special-row-p 'cookie))
4177 (t (throw 'exit nil)))))
4178 (org-element-contents table-row))
4179 (eq special-row-p 'cookie)))))))
4181 (defun org-export-table-row-group (table-row info)
4182 "Return TABLE-ROW's group.
4184 INFO is a plist used as the communication channel.
4186 Return value is the group number, as an integer, or nil special
4187 rows and table rules. Group 1 is also table's header."
4188 (unless (or (eq (org-element-property :type table-row) 'rule)
4189 (org-export-table-row-is-special-p table-row info))
4190 (let ((group 0) row-flag)
4191 (catch 'found
4192 (mapc
4193 (lambda (row)
4194 (cond
4195 ((and (eq (org-element-property :type row) 'standard)
4196 (not (org-export-table-row-is-special-p row info)))
4197 (unless row-flag (incf group) (setq row-flag t)))
4198 ((eq (org-element-property :type row) 'rule)
4199 (setq row-flag nil)))
4200 (when (eq table-row row) (throw 'found group)))
4201 (org-element-contents (org-export-get-parent table-row)))))))
4203 (defun org-export-table-cell-width (table-cell info)
4204 "Return TABLE-CELL contents width.
4206 INFO is a plist used as the communication channel.
4208 Return value is the width given by the last width cookie in the
4209 same column as TABLE-CELL, or nil."
4210 (let* ((row (org-export-get-parent table-cell))
4211 (column (let ((cells (org-element-contents row)))
4212 (- (length cells) (length (memq table-cell cells)))))
4213 (table (org-export-get-parent-table table-cell))
4214 cookie-width)
4215 (mapc
4216 (lambda (row)
4217 (cond
4218 ;; In a special row, try to find a width cookie at COLUMN.
4219 ((org-export-table-row-is-special-p row info)
4220 (let ((value (org-element-contents
4221 (elt (org-element-contents row) column))))
4222 ;; The following checks avoid expanding unnecessarily the
4223 ;; cell with `org-export-data'
4224 (when (and value
4225 (not (cdr value))
4226 (stringp (car value))
4227 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'" (car value))
4228 (match-string 1 (car value)))
4229 (setq cookie-width
4230 (string-to-number (match-string 1 (car value)))))))
4231 ;; Ignore table rules.
4232 ((eq (org-element-property :type row) 'rule))))
4233 (org-element-contents table))
4234 ;; Return value.
4235 cookie-width))
4237 (defun org-export-table-cell-alignment (table-cell info)
4238 "Return TABLE-CELL contents alignment.
4240 INFO is a plist used as the communication channel.
4242 Return alignment as specified by the last alignment cookie in the
4243 same column as TABLE-CELL. If no such cookie is found, a default
4244 alignment value will be deduced from fraction of numbers in the
4245 column (see `org-table-number-fraction' for more information).
4246 Possible values are `left', `right' and `center'."
4247 (let* ((row (org-export-get-parent table-cell))
4248 (column (let ((cells (org-element-contents row)))
4249 (- (length cells) (length (memq table-cell cells)))))
4250 (table (org-export-get-parent-table table-cell))
4251 (number-cells 0)
4252 (total-cells 0)
4253 cookie-align)
4254 (mapc
4255 (lambda (row)
4256 (cond
4257 ;; In a special row, try to find an alignment cookie at
4258 ;; COLUMN.
4259 ((org-export-table-row-is-special-p row info)
4260 (let ((value (org-element-contents
4261 (elt (org-element-contents row) column))))
4262 ;; Since VALUE is a secondary string, the following checks
4263 ;; avoid useless expansion through `org-export-data'.
4264 (when (and value
4265 (not (cdr value))
4266 (stringp (car value))
4267 (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'"
4268 (car value))
4269 (match-string 1 (car value)))
4270 (setq cookie-align (match-string 1 (car value))))))
4271 ;; Ignore table rules.
4272 ((eq (org-element-property :type row) 'rule))
4273 ;; In a standard row, check if cell's contents are expressing
4274 ;; some kind of number. Increase NUMBER-CELLS accordingly.
4275 ;; Though, don't bother if an alignment cookie has already
4276 ;; defined cell's alignment.
4277 ((not cookie-align)
4278 (let ((value (org-export-data
4279 (org-element-contents
4280 (elt (org-element-contents row) column))
4281 info)))
4282 (incf total-cells)
4283 (when (string-match org-table-number-regexp value)
4284 (incf number-cells))))))
4285 (org-element-contents table))
4286 ;; Return value. Alignment specified by cookies has precedence
4287 ;; over alignment deduced from cells contents.
4288 (cond ((equal cookie-align "l") 'left)
4289 ((equal cookie-align "r") 'right)
4290 ((equal cookie-align "c") 'center)
4291 ((>= (/ (float number-cells) total-cells) org-table-number-fraction)
4292 'right)
4293 (t 'left))))
4295 (defun org-export-table-cell-borders (table-cell info)
4296 "Return TABLE-CELL borders.
4298 INFO is a plist used as a communication channel.
4300 Return value is a list of symbols, or nil. Possible values are:
4301 `top', `bottom', `above', `below', `left' and `right'. Note:
4302 `top' (resp. `bottom') only happen for a cell in the first
4303 row (resp. last row) of the table, ignoring table rules, if any.
4305 Returned borders ignore special rows."
4306 (let* ((row (org-export-get-parent table-cell))
4307 (table (org-export-get-parent-table table-cell))
4308 borders)
4309 ;; Top/above border? TABLE-CELL has a border above when a rule
4310 ;; used to demarcate row groups can be found above. Hence,
4311 ;; finding a rule isn't sufficient to push `above' in BORDERS:
4312 ;; another regular row has to be found above that rule.
4313 (let (rule-flag)
4314 (catch 'exit
4315 (mapc (lambda (row)
4316 (cond ((eq (org-element-property :type row) 'rule)
4317 (setq rule-flag t))
4318 ((not (org-export-table-row-is-special-p row info))
4319 (if rule-flag (throw 'exit (push 'above borders))
4320 (throw 'exit nil)))))
4321 ;; Look at every row before the current one.
4322 (cdr (memq row (reverse (org-element-contents table)))))
4323 ;; No rule above, or rule found starts the table (ignoring any
4324 ;; special row): TABLE-CELL is at the top of the table.
4325 (when rule-flag (push 'above borders))
4326 (push 'top borders)))
4327 ;; Bottom/below border? TABLE-CELL has a border below when next
4328 ;; non-regular row below is a rule.
4329 (let (rule-flag)
4330 (catch 'exit
4331 (mapc (lambda (row)
4332 (cond ((eq (org-element-property :type row) 'rule)
4333 (setq rule-flag t))
4334 ((not (org-export-table-row-is-special-p row info))
4335 (if rule-flag (throw 'exit (push 'below borders))
4336 (throw 'exit nil)))))
4337 ;; Look at every row after the current one.
4338 (cdr (memq row (org-element-contents table))))
4339 ;; No rule below, or rule found ends the table (modulo some
4340 ;; special row): TABLE-CELL is at the bottom of the table.
4341 (when rule-flag (push 'below borders))
4342 (push 'bottom borders)))
4343 ;; Right/left borders? They can only be specified by column
4344 ;; groups. Column groups are defined in a row starting with "/".
4345 ;; Also a column groups row only contains "<", "<>", ">" or blank
4346 ;; cells.
4347 (catch 'exit
4348 (let ((column (let ((cells (org-element-contents row)))
4349 (- (length cells) (length (memq table-cell cells))))))
4350 (mapc
4351 (lambda (row)
4352 (unless (eq (org-element-property :type row) 'rule)
4353 (when (equal (org-element-contents
4354 (car (org-element-contents row)))
4355 '("/"))
4356 (let ((column-groups
4357 (mapcar
4358 (lambda (cell)
4359 (let ((value (org-element-contents cell)))
4360 (when (member value '(("<") ("<>") (">") nil))
4361 (car value))))
4362 (org-element-contents row))))
4363 ;; There's a left border when previous cell, if
4364 ;; any, ends a group, or current one starts one.
4365 (when (or (and (not (zerop column))
4366 (member (elt column-groups (1- column))
4367 '(">" "<>")))
4368 (member (elt column-groups column) '("<" "<>")))
4369 (push 'left borders))
4370 ;; There's a right border when next cell, if any,
4371 ;; starts a group, or current one ends one.
4372 (when (or (and (/= (1+ column) (length column-groups))
4373 (member (elt column-groups (1+ column))
4374 '("<" "<>")))
4375 (member (elt column-groups column) '(">" "<>")))
4376 (push 'right borders))
4377 (throw 'exit nil)))))
4378 ;; Table rows are read in reverse order so last column groups
4379 ;; row has precedence over any previous one.
4380 (reverse (org-element-contents table)))))
4381 ;; Return value.
4382 borders))
4384 (defun org-export-table-cell-starts-colgroup-p (table-cell info)
4385 "Non-nil when TABLE-CELL is at the beginning of a row group.
4386 INFO is a plist used as a communication channel."
4387 ;; A cell starts a column group either when it is at the beginning
4388 ;; of a row (or after the special column, if any) or when it has
4389 ;; a left border.
4390 (or (eq (org-element-map (org-export-get-parent table-cell) 'table-cell
4391 'identity info 'first-match)
4392 table-cell)
4393 (memq 'left (org-export-table-cell-borders table-cell info))))
4395 (defun org-export-table-cell-ends-colgroup-p (table-cell info)
4396 "Non-nil when TABLE-CELL is at the end of a row group.
4397 INFO is a plist used as a communication channel."
4398 ;; A cell ends a column group either when it is at the end of a row
4399 ;; or when it has a right border.
4400 (or (eq (car (last (org-element-contents
4401 (org-export-get-parent table-cell))))
4402 table-cell)
4403 (memq 'right (org-export-table-cell-borders table-cell info))))
4405 (defun org-export-table-row-starts-rowgroup-p (table-row info)
4406 "Non-nil when TABLE-ROW is at the beginning of a column group.
4407 INFO is a plist used as a communication channel."
4408 (unless (or (eq (org-element-property :type table-row) 'rule)
4409 (org-export-table-row-is-special-p table-row info))
4410 (let ((borders (org-export-table-cell-borders
4411 (car (org-element-contents table-row)) info)))
4412 (or (memq 'top borders) (memq 'above borders)))))
4414 (defun org-export-table-row-ends-rowgroup-p (table-row info)
4415 "Non-nil when TABLE-ROW is at the end of a column group.
4416 INFO is a plist used as a communication channel."
4417 (unless (or (eq (org-element-property :type table-row) 'rule)
4418 (org-export-table-row-is-special-p table-row info))
4419 (let ((borders (org-export-table-cell-borders
4420 (car (org-element-contents table-row)) info)))
4421 (or (memq 'bottom borders) (memq 'below borders)))))
4423 (defun org-export-table-row-starts-header-p (table-row info)
4424 "Non-nil when TABLE-ROW is the first table header's row.
4425 INFO is a plist used as a communication channel."
4426 (and (org-export-table-has-header-p
4427 (org-export-get-parent-table table-row) info)
4428 (org-export-table-row-starts-rowgroup-p table-row info)
4429 (= (org-export-table-row-group table-row info) 1)))
4431 (defun org-export-table-row-ends-header-p (table-row info)
4432 "Non-nil when TABLE-ROW is the last table header's row.
4433 INFO is a plist used as a communication channel."
4434 (and (org-export-table-has-header-p
4435 (org-export-get-parent-table table-row) info)
4436 (org-export-table-row-ends-rowgroup-p table-row info)
4437 (= (org-export-table-row-group table-row info) 1)))
4439 (defun org-export-table-dimensions (table info)
4440 "Return TABLE dimensions.
4442 INFO is a plist used as a communication channel.
4444 Return value is a CONS like (ROWS . COLUMNS) where
4445 ROWS (resp. COLUMNS) is the number of exportable
4446 rows (resp. columns)."
4447 (let (first-row (columns 0) (rows 0))
4448 ;; Set number of rows, and extract first one.
4449 (org-element-map table 'table-row
4450 (lambda (row)
4451 (when (eq (org-element-property :type row) 'standard)
4452 (incf rows)
4453 (unless first-row (setq first-row row)))) info)
4454 ;; Set number of columns.
4455 (org-element-map first-row 'table-cell (lambda (cell) (incf columns)) info)
4456 ;; Return value.
4457 (cons rows columns)))
4459 (defun org-export-table-cell-address (table-cell info)
4460 "Return address of a regular TABLE-CELL object.
4462 TABLE-CELL is the cell considered. INFO is a plist used as
4463 a communication channel.
4465 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4466 zero-based index. Only exportable cells are considered. The
4467 function returns nil for other cells."
4468 (let* ((table-row (org-export-get-parent table-cell))
4469 (table (org-export-get-parent-table table-cell)))
4470 ;; Ignore cells in special rows or in special column.
4471 (unless (or (org-export-table-row-is-special-p table-row info)
4472 (and (org-export-table-has-special-column-p table)
4473 (eq (car (org-element-contents table-row)) table-cell)))
4474 (cons
4475 ;; Row number.
4476 (let ((row-count 0))
4477 (org-element-map table 'table-row
4478 (lambda (row)
4479 (cond ((eq (org-element-property :type row) 'rule) nil)
4480 ((eq row table-row) row-count)
4481 (t (incf row-count) nil)))
4482 info 'first-match))
4483 ;; Column number.
4484 (let ((col-count 0))
4485 (org-element-map table-row 'table-cell
4486 (lambda (cell)
4487 (if (eq cell table-cell) col-count (incf col-count) nil))
4488 info 'first-match))))))
4490 (defun org-export-get-table-cell-at (address table info)
4491 "Return regular table-cell object at ADDRESS in TABLE.
4493 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4494 zero-based index. TABLE is a table type element. INFO is
4495 a plist used as a communication channel.
4497 If no table-cell, among exportable cells, is found at ADDRESS,
4498 return nil."
4499 (let ((column-pos (cdr address)) (column-count 0))
4500 (org-element-map
4501 ;; Row at (car address) or nil.
4502 (let ((row-pos (car address)) (row-count 0))
4503 (org-element-map table 'table-row
4504 (lambda (row)
4505 (cond ((eq (org-element-property :type row) 'rule) nil)
4506 ((= row-count row-pos) row)
4507 (t (incf row-count) nil)))
4508 info 'first-match))
4509 'table-cell
4510 (lambda (cell)
4511 (if (= column-count column-pos) cell
4512 (incf column-count) nil))
4513 info 'first-match)))
4516 ;;;; For Tables Of Contents
4518 ;; `org-export-collect-headlines' builds a list of all exportable
4519 ;; headline elements, maybe limited to a certain depth. One can then
4520 ;; easily parse it and transcode it.
4522 ;; Building lists of tables, figures or listings is quite similar.
4523 ;; Once the generic function `org-export-collect-elements' is defined,
4524 ;; `org-export-collect-tables', `org-export-collect-figures' and
4525 ;; `org-export-collect-listings' can be derived from it.
4527 (defun org-export-collect-headlines (info &optional n)
4528 "Collect headlines in order to build a table of contents.
4530 INFO is a plist used as a communication channel.
4532 When optional argument N is an integer, it specifies the depth of
4533 the table of contents. Otherwise, it is set to the value of the
4534 last headline level. See `org-export-headline-levels' for more
4535 information.
4537 Return a list of all exportable headlines as parsed elements.
4538 Footnote sections, if any, will be ignored."
4539 (unless (wholenump n) (setq n (plist-get info :headline-levels)))
4540 (org-element-map (plist-get info :parse-tree) 'headline
4541 (lambda (headline)
4542 (unless (org-element-property :footnote-section-p headline)
4543 ;; Strip contents from HEADLINE.
4544 (let ((relative-level (org-export-get-relative-level headline info)))
4545 (unless (> relative-level n) headline))))
4546 info))
4548 (defun org-export-collect-elements (type info &optional predicate)
4549 "Collect referenceable elements of a determined type.
4551 TYPE can be a symbol or a list of symbols specifying element
4552 types to search. Only elements with a caption are collected.
4554 INFO is a plist used as a communication channel.
4556 When non-nil, optional argument PREDICATE is a function accepting
4557 one argument, an element of type TYPE. It returns a non-nil
4558 value when that element should be collected.
4560 Return a list of all elements found, in order of appearance."
4561 (org-element-map (plist-get info :parse-tree) type
4562 (lambda (element)
4563 (and (org-element-property :caption element)
4564 (or (not predicate) (funcall predicate element))
4565 element))
4566 info))
4568 (defun org-export-collect-tables (info)
4569 "Build a list of tables.
4570 INFO is a plist used as a communication channel.
4572 Return a list of table elements with a caption."
4573 (org-export-collect-elements 'table info))
4575 (defun org-export-collect-figures (info predicate)
4576 "Build a list of figures.
4578 INFO is a plist used as a communication channel. PREDICATE is
4579 a function which accepts one argument: a paragraph element and
4580 whose return value is non-nil when that element should be
4581 collected.
4583 A figure is a paragraph type element, with a caption, verifying
4584 PREDICATE. The latter has to be provided since a \"figure\" is
4585 a vague concept that may depend on back-end.
4587 Return a list of elements recognized as figures."
4588 (org-export-collect-elements 'paragraph info predicate))
4590 (defun org-export-collect-listings (info)
4591 "Build a list of src blocks.
4593 INFO is a plist used as a communication channel.
4595 Return a list of src-block elements with a caption."
4596 (org-export-collect-elements 'src-block info))
4599 ;;;; Smart Quotes
4601 ;; The main function for the smart quotes sub-system is
4602 ;; `org-export-activate-smart-quotes', which replaces every quote in
4603 ;; a given string from the parse tree with its "smart" counterpart.
4605 ;; Dictionary for smart quotes is stored in
4606 ;; `org-export-smart-quotes-alist'.
4608 ;; Internally, regexps matching potential smart quotes (checks at
4609 ;; string boundaries are also necessary) are defined in
4610 ;; `org-export-smart-quotes-regexps'.
4612 (defconst org-export-smart-quotes-alist
4613 '(("de"
4614 (opening-double-quote :utf-8 "„" :html "&bdquo;" :latex "\"`"
4615 :texinfo "@quotedblbase{}")
4616 (closing-double-quote :utf-8 "“" :html "&ldquo;" :latex "\"'"
4617 :texinfo "@quotedblleft{}")
4618 (opening-single-quote :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}"
4619 :texinfo "@quotesinglbase{}")
4620 (closing-single-quote :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}"
4621 :texinfo "@quoteleft{}")
4622 (apostrophe :utf-8 "’" :html "&rsquo;"))
4623 ("en"
4624 (opening-double-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
4625 (closing-double-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
4626 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
4627 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
4628 (apostrophe :utf-8 "’" :html "&rsquo;"))
4629 ("es"
4630 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
4631 :texinfo "@guillemetleft{}")
4632 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
4633 :texinfo "@guillemetright{}")
4634 (opening-single-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
4635 (closing-single-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
4636 (apostrophe :utf-8 "’" :html "&rsquo;"))
4637 ("fr"
4638 (opening-double-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
4639 :texinfo "@guillemetleft{}@tie{}")
4640 (closing-double-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
4641 :texinfo "@tie{}@guillemetright{}")
4642 (opening-single-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
4643 :texinfo "@guillemetleft{}@tie{}")
4644 (closing-single-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
4645 :texinfo "@tie{}@guillemetright{}")
4646 (apostrophe :utf-8 "’" :html "&rsquo;")))
4647 "Smart quotes translations.
4649 Alist whose CAR is a language string and CDR is an alist with
4650 quote type as key and a plist associating various encodings to
4651 their translation as value.
4653 A quote type can be any symbol among `opening-double-quote',
4654 `closing-double-quote', `opening-single-quote',
4655 `closing-single-quote' and `apostrophe'.
4657 Valid encodings include `:utf-8', `:html', `:latex' and
4658 `:texinfo'.
4660 If no translation is found, the quote character is left as-is.")
4662 (defconst org-export-smart-quotes-regexps
4663 (list
4664 ;; Possible opening quote at beginning of string.
4665 "\\`\\([\"']\\)\\(\\w\\|\\s.\\|\\s_\\)"
4666 ;; Possible closing quote at beginning of string.
4667 "\\`\\([\"']\\)\\(\\s-\\|\\s)\\|\\s.\\)"
4668 ;; Possible apostrophe at beginning of string.
4669 "\\`\\('\\)\\S-"
4670 ;; Opening single and double quotes.
4671 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\(?:\\w\\|\\s.\\|\\s_\\)"
4672 ;; Closing single and double quotes.
4673 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\(?:\\s-\\|\\s)\\|\\s.\\)"
4674 ;; Apostrophe.
4675 "\\S-\\('\\)\\S-"
4676 ;; Possible opening quote at end of string.
4677 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\'"
4678 ;; Possible closing quote at end of string.
4679 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\'"
4680 ;; Possible apostrophe at end of string.
4681 "\\S-\\('\\)\\'")
4682 "List of regexps matching a quote or an apostrophe.
4683 In every regexp, quote or apostrophe matched is put in group 1.")
4685 (defun org-export-activate-smart-quotes (s encoding info &optional original)
4686 "Replace regular quotes with \"smart\" quotes in string S.
4688 ENCODING is a symbol among `:html', `:latex', `:texinfo' and
4689 `:utf-8'. INFO is a plist used as a communication channel.
4691 The function has to retrieve information about string
4692 surroundings in parse tree. It can only happen with an
4693 unmodified string. Thus, if S has already been through another
4694 process, a non-nil ORIGINAL optional argument will provide that
4695 original string.
4697 Return the new string."
4698 (if (equal s "") ""
4699 (let* ((prev (org-export-get-previous-element (or original s) info))
4700 ;; Try to be flexible when computing number of blanks
4701 ;; before object. The previous object may be a string
4702 ;; introduced by the back-end and not completely parsed.
4703 (pre-blank (and prev
4704 (or (org-element-property :post-blank prev)
4705 ;; A string with missing `:post-blank'
4706 ;; property.
4707 (and (stringp prev)
4708 (string-match " *\\'" prev)
4709 (length (match-string 0 prev)))
4710 ;; Fallback value.
4711 0)))
4712 (next (org-export-get-next-element (or original s) info))
4713 (get-smart-quote
4714 (lambda (q type)
4715 ;; Return smart quote associated to a give quote Q, as
4716 ;; a string. TYPE is a symbol among `open', `close' and
4717 ;; `apostrophe'.
4718 (let ((key (case type
4719 (apostrophe 'apostrophe)
4720 (open (if (equal "'" q) 'opening-single-quote
4721 'opening-double-quote))
4722 (otherwise (if (equal "'" q) 'closing-single-quote
4723 'closing-double-quote)))))
4724 (or (plist-get
4725 (cdr (assq key
4726 (cdr (assoc (plist-get info :language)
4727 org-export-smart-quotes-alist))))
4728 encoding)
4729 q)))))
4730 (if (or (equal "\"" s) (equal "'" s))
4731 ;; Only a quote: no regexp can match. We have to check both
4732 ;; sides and decide what to do.
4733 (cond ((and (not prev) (not next)) s)
4734 ((not prev) (funcall get-smart-quote s 'open))
4735 ((and (not next) (zerop pre-blank))
4736 (funcall get-smart-quote s 'close))
4737 ((not next) s)
4738 ((zerop pre-blank) (funcall get-smart-quote s 'apostrophe))
4739 (t (funcall get-smart-quote 'open)))
4740 ;; 1. Replace quote character at the beginning of S.
4741 (cond
4742 ;; Apostrophe?
4743 ((and prev (zerop pre-blank)
4744 (string-match (nth 2 org-export-smart-quotes-regexps) s))
4745 (setq s (replace-match
4746 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
4747 nil t s 1)))
4748 ;; Closing quote?
4749 ((and prev (zerop pre-blank)
4750 (string-match (nth 1 org-export-smart-quotes-regexps) s))
4751 (setq s (replace-match
4752 (funcall get-smart-quote (match-string 1 s) 'close)
4753 nil t s 1)))
4754 ;; Opening quote?
4755 ((and (or (not prev) (> pre-blank 0))
4756 (string-match (nth 0 org-export-smart-quotes-regexps) s))
4757 (setq s (replace-match
4758 (funcall get-smart-quote (match-string 1 s) 'open)
4759 nil t s 1))))
4760 ;; 2. Replace quotes in the middle of the string.
4761 (setq s (replace-regexp-in-string
4762 ;; Opening quotes.
4763 (nth 3 org-export-smart-quotes-regexps)
4764 (lambda (text)
4765 (funcall get-smart-quote (match-string 1 text) 'open))
4766 s nil t 1))
4767 (setq s (replace-regexp-in-string
4768 ;; Closing quotes.
4769 (nth 4 org-export-smart-quotes-regexps)
4770 (lambda (text)
4771 (funcall get-smart-quote (match-string 1 text) 'close))
4772 s nil t 1))
4773 (setq s (replace-regexp-in-string
4774 ;; Apostrophes.
4775 (nth 5 org-export-smart-quotes-regexps)
4776 (lambda (text)
4777 (funcall get-smart-quote (match-string 1 text) 'apostrophe))
4778 s nil t 1))
4779 ;; 3. Replace quote character at the end of S.
4780 (cond
4781 ;; Apostrophe?
4782 ((and next (string-match (nth 8 org-export-smart-quotes-regexps) s))
4783 (setq s (replace-match
4784 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
4785 nil t s 1)))
4786 ;; Closing quote?
4787 ((and (not next)
4788 (string-match (nth 7 org-export-smart-quotes-regexps) s))
4789 (setq s (replace-match
4790 (funcall get-smart-quote (match-string 1 s) 'close)
4791 nil t s 1)))
4792 ;; Opening quote?
4793 ((and next (string-match (nth 6 org-export-smart-quotes-regexps) s))
4794 (setq s (replace-match
4795 (funcall get-smart-quote (match-string 1 s) 'open)
4796 nil t s 1))))
4797 ;; Return string with smart quotes.
4798 s))))
4800 ;;;; Topology
4802 ;; Here are various functions to retrieve information about the
4803 ;; neighbourhood of a given element or object. Neighbours of interest
4804 ;; are direct parent (`org-export-get-parent'), parent headline
4805 ;; (`org-export-get-parent-headline'), first element containing an
4806 ;; object, (`org-export-get-parent-element'), parent table
4807 ;; (`org-export-get-parent-table'), previous element or object
4808 ;; (`org-export-get-previous-element') and next element or object
4809 ;; (`org-export-get-next-element').
4811 ;; `org-export-get-genealogy' returns the full genealogy of a given
4812 ;; element or object, from closest parent to full parse tree.
4814 (defun org-export-get-parent (blob)
4815 "Return BLOB parent or nil.
4816 BLOB is the element or object considered."
4817 (org-element-property :parent blob))
4819 (defun org-export-get-genealogy (blob)
4820 "Return full genealogy relative to a given element or object.
4822 BLOB is the element or object being considered.
4824 Ancestors are returned from closest to farthest, the last one
4825 being the full parse tree."
4826 (let (genealogy (parent blob))
4827 (while (setq parent (org-element-property :parent parent))
4828 (push parent genealogy))
4829 (nreverse genealogy)))
4831 (defun org-export-get-parent-headline (blob)
4832 "Return BLOB parent headline or nil.
4833 BLOB is the element or object being considered."
4834 (let ((parent blob))
4835 (while (and (setq parent (org-element-property :parent parent))
4836 (not (eq (org-element-type parent) 'headline))))
4837 parent))
4839 (defun org-export-get-parent-element (object)
4840 "Return first element containing OBJECT or nil.
4841 OBJECT is the object to consider."
4842 (let ((parent object))
4843 (while (and (setq parent (org-element-property :parent parent))
4844 (memq (org-element-type parent) org-element-all-objects)))
4845 parent))
4847 (defun org-export-get-parent-table (object)
4848 "Return OBJECT parent table or nil.
4849 OBJECT is either a `table-cell' or `table-element' type object."
4850 (let ((parent object))
4851 (while (and (setq parent (org-element-property :parent parent))
4852 (not (eq (org-element-type parent) 'table))))
4853 parent))
4855 (defun org-export-get-previous-element (blob info &optional n)
4856 "Return previous element or object.
4858 BLOB is an element or object. INFO is a plist used as
4859 a communication channel. Return previous exportable element or
4860 object, a string, or nil.
4862 When optional argument N is a positive integer, return a list
4863 containing up to N siblings before BLOB, from farthest to
4864 closest. With any other non-nil value, return a list containing
4865 all of them."
4866 (let ((siblings
4867 ;; An object can belong to the contents of its parent or
4868 ;; to a secondary string. We check the latter option
4869 ;; first.
4870 (let ((parent (org-export-get-parent blob)))
4871 (or (and (not (memq (org-element-type blob)
4872 org-element-all-elements))
4873 (let ((sec-value
4874 (org-element-property
4875 (cdr (assq (org-element-type parent)
4876 org-element-secondary-value-alist))
4877 parent)))
4878 (and (memq blob sec-value) sec-value)))
4879 (org-element-contents parent))))
4880 prev)
4881 (catch 'exit
4882 (mapc (lambda (obj)
4883 (cond ((memq obj (plist-get info :ignore-list)))
4884 ((null n) (throw 'exit obj))
4885 ((not (wholenump n)) (push obj prev))
4886 ((zerop n) (throw 'exit prev))
4887 (t (decf n) (push obj prev))))
4888 (cdr (memq blob (reverse siblings))))
4889 prev)))
4891 (defun org-export-get-next-element (blob info &optional n)
4892 "Return next element or object.
4894 BLOB is an element or object. INFO is a plist used as
4895 a communication channel. Return next exportable element or
4896 object, a string, or nil.
4898 When optional argument N is a positive integer, return a list
4899 containing up to N siblings after BLOB, from closest to farthest.
4900 With any other non-nil value, return a list containing all of
4901 them."
4902 (let ((siblings
4903 ;; An object can belong to the contents of its parent or to
4904 ;; a secondary string. We check the latter option first.
4905 (let ((parent (org-export-get-parent blob)))
4906 (or (and (not (memq (org-element-type blob)
4907 org-element-all-objects))
4908 (let ((sec-value
4909 (org-element-property
4910 (cdr (assq (org-element-type parent)
4911 org-element-secondary-value-alist))
4912 parent)))
4913 (cdr (memq blob sec-value))))
4914 (cdr (memq blob (org-element-contents parent))))))
4915 next)
4916 (catch 'exit
4917 (mapc (lambda (obj)
4918 (cond ((memq obj (plist-get info :ignore-list)))
4919 ((null n) (throw 'exit obj))
4920 ((not (wholenump n)) (push obj next))
4921 ((zerop n) (throw 'exit (nreverse next)))
4922 (t (decf n) (push obj next))))
4923 siblings)
4924 (nreverse next))))
4927 ;;;; Translation
4929 ;; `org-export-translate' translates a string according to language
4930 ;; specified by LANGUAGE keyword or `org-export-language-setup'
4931 ;; variable and a specified charset. `org-export-dictionary' contains
4932 ;; the dictionary used for the translation.
4934 (defconst org-export-dictionary
4935 '(("Author"
4936 ("ca" :default "Autor")
4937 ("cs" :default "Autor")
4938 ("da" :default "Ophavsmand")
4939 ("de" :default "Autor")
4940 ("eo" :html "A&#365;toro")
4941 ("es" :default "Autor")
4942 ("fi" :html "Tekij&auml;")
4943 ("fr" :default "Auteur")
4944 ("hu" :default "Szerz&otilde;")
4945 ("is" :html "H&ouml;fundur")
4946 ("it" :default "Autore")
4947 ("ja" :html "&#33879;&#32773;" :utf-8 "著者")
4948 ("nl" :default "Auteur")
4949 ("no" :default "Forfatter")
4950 ("nb" :default "Forfatter")
4951 ("nn" :default "Forfattar")
4952 ("pl" :default "Autor")
4953 ("ru" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
4954 ("sv" :html "F&ouml;rfattare")
4955 ("uk" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
4956 ("zh-CN" :html "&#20316;&#32773;" :utf-8 "作者")
4957 ("zh-TW" :html "&#20316;&#32773;" :utf-8 "作者"))
4958 ("Date"
4959 ("ca" :default "Data")
4960 ("cs" :default "Datum")
4961 ("da" :default "Dato")
4962 ("de" :default "Datum")
4963 ("eo" :default "Dato")
4964 ("es" :default "Fecha")
4965 ("fi" :html "P&auml;iv&auml;m&auml;&auml;r&auml;")
4966 ("hu" :html "D&aacute;tum")
4967 ("is" :default "Dagsetning")
4968 ("it" :default "Data")
4969 ("ja" :html "&#26085;&#20184;" :utf-8 "日付")
4970 ("nl" :default "Datum")
4971 ("no" :default "Dato")
4972 ("nb" :default "Dato")
4973 ("nn" :default "Dato")
4974 ("pl" :default "Data")
4975 ("ru" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
4976 ("sv" :default "Datum")
4977 ("uk" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
4978 ("zh-CN" :html "&#26085;&#26399;" :utf-8 "日期")
4979 ("zh-TW" :html "&#26085;&#26399;" :utf-8 "日期"))
4980 ("Equation"
4981 ("fr" :ascii "Equation" :default "Équation"))
4982 ("Figure")
4983 ("Footnotes"
4984 ("ca" :html "Peus de p&agrave;gina")
4985 ("cs" :default "Pozn\xe1mky pod carou")
4986 ("da" :default "Fodnoter")
4987 ("de" :html "Fu&szlig;noten")
4988 ("eo" :default "Piednotoj")
4989 ("es" :html "Pies de p&aacute;gina")
4990 ("fi" :default "Alaviitteet")
4991 ("fr" :default "Notes de bas de page")
4992 ("hu" :html "L&aacute;bjegyzet")
4993 ("is" :html "Aftanm&aacute;lsgreinar")
4994 ("it" :html "Note a pi&egrave; di pagina")
4995 ("ja" :html "&#33050;&#27880;" :utf-8 "脚注")
4996 ("nl" :default "Voetnoten")
4997 ("no" :default "Fotnoter")
4998 ("nb" :default "Fotnoter")
4999 ("nn" :default "Fotnotar")
5000 ("pl" :default "Przypis")
5001 ("ru" :html "&#1057;&#1085;&#1086;&#1089;&#1082;&#1080;" :utf-8 "Сноски")
5002 ("sv" :default "Fotnoter")
5003 ("uk" :html "&#1055;&#1088;&#1080;&#1084;&#1110;&#1090;&#1082;&#1080;"
5004 :utf-8 "Примітки")
5005 ("zh-CN" :html "&#33050;&#27880;" :utf-8 "脚注")
5006 ("zh-TW" :html "&#33139;&#35387;" :utf-8 "腳註"))
5007 ("List of Listings"
5008 ("fr" :default "Liste des programmes"))
5009 ("List of Tables"
5010 ("fr" :default "Liste des tableaux"))
5011 ("Listing %d:"
5012 ("fr"
5013 :ascii "Programme %d :" :default "Programme nº %d :"
5014 :latin1 "Programme %d :"))
5015 ("Listing %d: %s"
5016 ("fr"
5017 :ascii "Programme %d : %s" :default "Programme nº %d : %s"
5018 :latin1 "Programme %d : %s"))
5019 ("See section %s"
5020 ("fr" :default "cf. section %s"))
5021 ("Table %d:"
5022 ("fr"
5023 :ascii "Tableau %d :" :default "Tableau nº %d :" :latin1 "Tableau %d :"))
5024 ("Table %d: %s"
5025 ("fr"
5026 :ascii "Tableau %d : %s" :default "Tableau nº %d : %s"
5027 :latin1 "Tableau %d : %s"))
5028 ("Table of Contents"
5029 ("ca" :html "&Iacute;ndex")
5030 ("cs" :default "Obsah")
5031 ("da" :default "Indhold")
5032 ("de" :default "Inhaltsverzeichnis")
5033 ("eo" :default "Enhavo")
5034 ("es" :html "&Iacute;ndice")
5035 ("fi" :html "Sis&auml;llysluettelo")
5036 ("fr" :ascii "Sommaire" :default "Table des matières")
5037 ("hu" :html "Tartalomjegyz&eacute;k")
5038 ("is" :default "Efnisyfirlit")
5039 ("it" :default "Indice")
5040 ("ja" :html "&#30446;&#27425;" :utf-8 "目次")
5041 ("nl" :default "Inhoudsopgave")
5042 ("no" :default "Innhold")
5043 ("nb" :default "Innhold")
5044 ("nn" :default "Innhald")
5045 ("pl" :html "Spis tre&#x015b;ci")
5046 ("ru" :html "&#1057;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1077;"
5047 :utf-8 "Содержание")
5048 ("sv" :html "Inneh&aring;ll")
5049 ("uk" :html "&#1047;&#1084;&#1110;&#1089;&#1090;" :utf-8 "Зміст")
5050 ("zh-CN" :html "&#30446;&#24405;" :utf-8 "目录")
5051 ("zh-TW" :html "&#30446;&#37636;" :utf-8 "目錄"))
5052 ("Unknown reference"
5053 ("fr" :ascii "Destination inconnue" :default "Référence inconnue")))
5054 "Dictionary for export engine.
5056 Alist whose CAR is the string to translate and CDR is an alist
5057 whose CAR is the language string and CDR is a plist whose
5058 properties are possible charsets and values translated terms.
5060 It is used as a database for `org-export-translate'. Since this
5061 function returns the string as-is if no translation was found,
5062 the variable only needs to record values different from the
5063 entry.")
5065 (defun org-export-translate (s encoding info)
5066 "Translate string S according to language specification.
5068 ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1'
5069 and `:utf-8'. INFO is a plist used as a communication channel.
5071 Translation depends on `:language' property. Return the
5072 translated string. If no translation is found, try to fall back
5073 to `:default' encoding. If it fails, return S."
5074 (let* ((lang (plist-get info :language))
5075 (translations (cdr (assoc lang
5076 (cdr (assoc s org-export-dictionary))))))
5077 (or (plist-get translations encoding)
5078 (plist-get translations :default)
5079 s)))
5083 ;;; Asynchronous Export
5085 ;; `org-export-async-start' is the entry point for asynchronous
5086 ;; export. It recreates current buffer (including visibility,
5087 ;; narrowing and visited file) in an external Emacs process, and
5088 ;; evaluates a command there. It then applies a function on the
5089 ;; returned results in the current process.
5091 ;; Asynchronously generated results are never displayed directly.
5092 ;; Instead, they are stored in `org-export-stack-contents'. They can
5093 ;; then be retrieved by calling `org-export-stack'.
5095 ;; Export Stack is viewed through a dedicated major mode
5096 ;;`org-export-stack-mode' and tools: `org-export-stack-refresh',
5097 ;;`org-export-stack-delete', `org-export-stack-view' and
5098 ;;`org-export-stack-clear'.
5100 ;; For back-ends, `org-export-add-to-stack' add a new source to stack.
5101 ;; It should used whenever `org-export-async-start' is called.
5103 (defmacro org-export-async-start (fun &rest body)
5104 "Call function FUN on the results returned by BODY evaluation.
5106 BODY evaluation happens in an asynchronous process, from a buffer
5107 which is an exact copy of the current one.
5109 Use `org-export-add-to-stack' in FUN in order to register results
5110 in the stack. Examples for, respectively a temporary buffer and
5111 a file are:
5113 \(org-export-async-start
5114 \(lambda (output)
5115 \(with-current-buffer (get-buffer-create \"*Org BACKEND Export*\")
5116 \(erase-buffer)
5117 \(insert output)
5118 \(goto-char (point-min))
5119 \(org-export-add-to-stack (current-buffer) 'backend)))
5120 `(org-export-as 'backend ,subtreep ,visible-only ,body-only ',ext-plist))
5124 \(org-export-async-start
5125 \(lambda (f) (org-export-add-to-stack f 'backend))
5126 `(expand-file-name
5127 \(org-export-to-file
5128 'backend ,outfile ,subtreep ,visible-only ,body-only ',ext-plist)))"
5129 (declare (indent 1) (debug t))
5130 (org-with-gensyms (process temp-file copy-fun proc-buffer handler)
5131 ;; Write the full sexp evaluating BODY in a copy of the current
5132 ;; buffer to a temporary file, as it may be too long for program
5133 ;; args in `start-process'.
5134 `(with-temp-message "Initializing asynchronous export process"
5135 (let ((,copy-fun (org-export--generate-copy-script (current-buffer)))
5136 (,temp-file (make-temp-file "org-export-process")))
5137 (with-temp-file ,temp-file
5138 (insert
5139 (format
5140 "%S"
5141 `(with-temp-buffer
5142 ,(when org-export-async-debug '(setq debug-on-error t))
5143 ;; Ignore `kill-emacs-hook' as we need a truly
5144 ;; non-interactive process.
5145 (setq kill-emacs-hook nil)
5146 ;; Initialize export framework in external process.
5147 (require 'ox)
5148 ;; Re-create current buffer there.
5149 (funcall ,,copy-fun)
5150 (restore-buffer-modified-p nil)
5151 ;; Sexp to evaluate in the buffer.
5152 (print (progn ,,@body))))))
5153 ;; Start external process.
5154 (let* ((process-connection-type nil)
5155 (,proc-buffer (generate-new-buffer-name "*Org Export Process*"))
5156 (,process
5157 (start-process
5158 "org-export-process" ,proc-buffer
5159 (expand-file-name invocation-name invocation-directory)
5160 "-Q" "--batch"
5161 "-l" org-export-async-init-file
5162 "-l" ,temp-file)))
5163 ;; Register running process in stack.
5164 (org-export-add-to-stack (get-buffer ,proc-buffer) nil ,process)
5165 ;; Set-up sentinel in order to catch results.
5166 (set-process-sentinel
5167 ,process
5168 (let ((handler ',fun))
5169 `(lambda (p status)
5170 (let ((proc-buffer (process-buffer p)))
5171 (when (eq (process-status p) 'exit)
5172 (unwind-protect
5173 (if (zerop (process-exit-status p))
5174 (unwind-protect
5175 (let ((results
5176 (with-current-buffer proc-buffer
5177 (goto-char (point-max))
5178 (backward-sexp)
5179 (read (current-buffer)))))
5180 (funcall ,handler results))
5181 (unless org-export-async-debug
5182 (and (get-buffer proc-buffer)
5183 (kill-buffer proc-buffer))))
5184 (org-export-add-to-stack proc-buffer nil p)
5185 (ding)
5186 (message "Process '%s' exited abnormally" p))
5187 (unless org-export-async-debug
5188 (delete-file ,,temp-file)))))))))))))
5190 (defun org-export-add-to-stack (source backend &optional process)
5191 "Add a new result to export stack if not present already.
5193 SOURCE is a buffer or a file name containing export results.
5194 BACKEND is a symbol representing export back-end used to generate
5197 Entries already pointing to SOURCE and unavailable entries are
5198 removed beforehand. Return the new stack."
5199 (setq org-export-stack-contents
5200 (cons (list source backend (or process (current-time)))
5201 (org-export-stack-remove source))))
5203 (defun org-export-stack ()
5204 "Menu for asynchronous export results and running processes."
5205 (interactive)
5206 (let ((buffer (get-buffer-create "*Org Export Stack*")))
5207 (set-buffer buffer)
5208 (when (zerop (buffer-size)) (org-export-stack-mode))
5209 (org-export-stack-refresh)
5210 (pop-to-buffer buffer))
5211 (message "Type \"q\" to quit, \"?\" for help"))
5213 (defun org-export--stack-source-at-point ()
5214 "Return source from export results at point in stack."
5215 (let ((source (car (nth (1- (org-current-line)) org-export-stack-contents))))
5216 (if (not source) (error "Source unavailable, please refresh buffer")
5217 (let ((source-name (if (stringp source) source (buffer-name source))))
5218 (if (save-excursion
5219 (beginning-of-line)
5220 (looking-at (concat ".* +" (regexp-quote source-name) "$")))
5221 source
5222 ;; SOURCE is not consistent with current line. The stack
5223 ;; view is outdated.
5224 (error "Source unavailable; type `g' to update buffer"))))))
5226 (defun org-export-stack-clear ()
5227 "Remove all entries from export stack."
5228 (interactive)
5229 (setq org-export-stack-contents nil))
5231 (defun org-export-stack-refresh (&rest dummy)
5232 "Refresh the asynchronous export stack.
5233 DUMMY is ignored. Unavailable sources are removed from the list.
5234 Return the new stack."
5235 (let ((inhibit-read-only t))
5236 (org-preserve-lc
5237 (erase-buffer)
5238 (insert (concat
5239 (let ((counter 0))
5240 (mapconcat
5241 (lambda (entry)
5242 (let ((proc-p (processp (nth 2 entry))))
5243 (concat
5244 ;; Back-end.
5245 (format " %-12s " (or (nth 1 entry) ""))
5246 ;; Age.
5247 (let ((data (nth 2 entry)))
5248 (if proc-p (format " %6s " (process-status data))
5249 ;; Compute age of the results.
5250 (org-format-seconds
5251 "%4h:%.2m "
5252 (float-time (time-since data)))))
5253 ;; Source.
5254 (format " %s"
5255 (let ((source (car entry)))
5256 (if (stringp source) source
5257 (buffer-name source)))))))
5258 ;; Clear stack from exited processes, dead buffers or
5259 ;; non-existent files.
5260 (setq org-export-stack-contents
5261 (org-remove-if-not
5262 (lambda (el)
5263 (if (processp (nth 2 el))
5264 (buffer-live-p (process-buffer (nth 2 el)))
5265 (let ((source (car el)))
5266 (if (bufferp source) (buffer-live-p source)
5267 (file-exists-p source)))))
5268 org-export-stack-contents)) "\n")))))))
5270 (defun org-export-stack-remove (&optional source)
5271 "Remove export results at point from stack.
5272 If optional argument SOURCE is non-nil, remove it instead."
5273 (interactive)
5274 (let ((source (or source (org-export--stack-source-at-point))))
5275 (setq org-export-stack-contents
5276 (org-remove-if (lambda (el) (equal (car el) source))
5277 org-export-stack-contents))))
5279 (defun org-export-stack-view (&optional in-emacs)
5280 "View export results at point in stack.
5281 With an optional prefix argument IN-EMACS, force viewing files
5282 within Emacs."
5283 (interactive "P")
5284 (let ((source (org-export--stack-source-at-point)))
5285 (cond ((processp source)
5286 (org-switch-to-buffer-other-window (process-buffer source)))
5287 ((bufferp source) (org-switch-to-buffer-other-window source))
5288 (t (org-open-file source in-emacs)))))
5290 (defconst org-export-stack-mode-map
5291 (let ((km (make-sparse-keymap)))
5292 (define-key km " " 'next-line)
5293 (define-key km "n" 'next-line)
5294 (define-key km "\C-n" 'next-line)
5295 (define-key km [down] 'next-line)
5296 (define-key km "p" 'previous-line)
5297 (define-key km "\C-p" 'previous-line)
5298 (define-key km "\C-?" 'previous-line)
5299 (define-key km [up] 'previous-line)
5300 (define-key km "C" 'org-export-stack-clear)
5301 (define-key km "v" 'org-export-stack-view)
5302 (define-key km (kbd "RET") 'org-export-stack-view)
5303 (define-key km "d" 'org-export-stack-remove)
5305 "Keymap for Org Export Stack.")
5307 (define-derived-mode org-export-stack-mode special-mode "Org-Stack"
5308 "Mode for displaying asynchronous export stack.
5310 Type \\[org-export-stack] to visualize the asynchronous export
5311 stack.
5313 In an Org Export Stack buffer, use \\<org-export-stack-mode-map>\\[org-export-stack-view] to view export output
5314 on current line, \\[org-export-stack-remove] to remove it from the stack and \\[org-export-stack-clear] to clear
5315 stack completely.
5317 Removing entries in an Org Export Stack buffer doesn't affect
5318 files or buffers, only the display.
5320 \\{org-export-stack-mode-map}"
5321 (abbrev-mode 0)
5322 (auto-fill-mode 0)
5323 (setq buffer-read-only t
5324 buffer-undo-list t
5325 truncate-lines t
5326 header-line-format
5327 '(:eval
5328 (format " %-12s | %6s | %s" "Back-End" "Age" "Source")))
5329 (add-hook 'post-command-hook 'org-export-stack-refresh nil t)
5330 (set (make-local-variable 'revert-buffer-function)
5331 'org-export-stack-refresh))
5335 ;;; The Dispatcher
5337 ;; `org-export-dispatch' is the standard interactive way to start an
5338 ;; export process. It uses `org-export--dispatch-ui' as a subroutine
5339 ;; for its interface, which, in turn, delegates response to key
5340 ;; pressed to `org-export--dispatch-action'.
5342 ;;;###autoload
5343 (defun org-export-dispatch (&optional arg)
5344 "Export dispatcher for Org mode.
5346 It provides an access to common export related tasks in a buffer.
5347 Its interface comes in two flavours: standard and expert.
5349 While both share the same set of bindings, only the former
5350 displays the valid keys associations in a dedicated buffer.
5351 Scrolling (resp. line-wise motion) in this buffer is done with
5352 SPC and DEL (resp. C-n and C-p) keys.
5354 Set variable `org-export-dispatch-use-expert-ui' to switch to one
5355 flavour or the other.
5357 When ARG is \\[universal-argument], repeat the last export action, with the same set
5358 of options used back then, on the current buffer.
5360 When ARG is \\[universal-argument] \\[universal-argument], display the asynchronous export stack."
5361 (interactive "P")
5362 (let* ((input
5363 (cond ((equal arg '(16)) '(stack))
5364 ((and arg org-export-dispatch-last-action))
5365 (t (save-window-excursion
5366 (unwind-protect
5367 (progn
5368 ;; Remember where we are
5369 (move-marker org-export-dispatch-last-position
5370 (point)
5371 (org-base-buffer (current-buffer)))
5372 ;; Get and store an export command
5373 (setq org-export-dispatch-last-action
5374 (org-export--dispatch-ui
5375 (list org-export-initial-scope
5376 (and org-export-in-background 'async))
5378 org-export-dispatch-use-expert-ui)))
5379 (and (get-buffer "*Org Export Dispatcher*")
5380 (kill-buffer "*Org Export Dispatcher*")))))))
5381 (action (car input))
5382 (optns (cdr input)))
5383 (unless (memq 'subtree optns)
5384 (move-marker org-export-dispatch-last-position nil))
5385 (case action
5386 ;; First handle special hard-coded actions.
5387 (stack (org-export-stack))
5388 (publish-current-file
5389 (org-publish-current-file (memq 'force optns) (memq 'async optns)))
5390 (publish-current-project
5391 (org-publish-current-project (memq 'force optns) (memq 'async optns)))
5392 (publish-choose-project
5393 (org-publish (assoc (org-icompleting-read
5394 "Publish project: "
5395 org-publish-project-alist nil t)
5396 org-publish-project-alist)
5397 (memq 'force optns)
5398 (memq 'async optns)))
5399 (publish-all (org-publish-all (memq 'force optns) (memq 'async optns)))
5400 (otherwise
5401 (save-excursion
5402 (when arg
5403 ;; Repeating command, maybe move cursor
5404 ;; to restore subtree context
5405 (if (eq (marker-buffer org-export-dispatch-last-position)
5406 (org-base-buffer (current-buffer)))
5407 (goto-char org-export-dispatch-last-position)
5408 ;; We are in a differnet buffer, forget position
5409 (move-marker org-export-dispatch-last-position nil)))
5410 (funcall action
5411 ;; Return a symbol instead of a list to ease
5412 ;; asynchronous export macro use.
5413 (and (memq 'async optns) t)
5414 (and (memq 'subtree optns) t)
5415 (and (memq 'visible optns) t)
5416 (and (memq 'body optns) t)))))))
5418 (defun org-export--dispatch-ui (options first-key expertp)
5419 "Handle interface for `org-export-dispatch'.
5421 OPTIONS is a list containing current interactive options set for
5422 export. It can contain any of the following symbols:
5423 `body' toggles a body-only export
5424 `subtree' restricts export to current subtree
5425 `visible' restricts export to visible part of buffer.
5426 `force' force publishing files.
5427 `async' use asynchronous export process
5429 FIRST-KEY is the key pressed to select the first level menu. It
5430 is nil when this menu hasn't been selected yet.
5432 EXPERTP, when non-nil, triggers expert UI. In that case, no help
5433 buffer is provided, but indications about currently active
5434 options are given in the prompt. Moreover, \[?] allows to switch
5435 back to standard interface."
5436 (let* ((fontify-key
5437 (lambda (key &optional access-key)
5438 ;; Fontify KEY string. Optional argument ACCESS-KEY, when
5439 ;; non-nil is the required first-level key to activate
5440 ;; KEY. When its value is t, activate KEY independently
5441 ;; on the first key, if any. A nil value means KEY will
5442 ;; only be activated at first level.
5443 (if (or (eq access-key t) (eq access-key first-key))
5444 (org-propertize key 'face 'org-warning)
5445 key)))
5446 (fontify-value
5447 (lambda (value)
5448 ;; Fontify VALUE string.
5449 (org-propertize value 'face 'font-lock-variable-name-face)))
5450 ;; Prepare menu entries by extracting them from
5451 ;; `org-export-registered-backends', and sorting them by
5452 ;; access key and by ordinal, if any.
5453 (backends
5454 (sort
5455 (sort
5456 (delq nil
5457 (mapcar
5458 (lambda (b)
5459 (let ((name (car b)))
5460 (catch 'ignored
5461 ;; Ignore any back-end belonging to
5462 ;; `org-export-invisible-backends' or derived
5463 ;; from one of them.
5464 (dolist (ignored org-export-invisible-backends)
5465 (when (org-export-derived-backend-p name ignored)
5466 (throw 'ignored nil)))
5467 (org-export-backend-menu name))))
5468 org-export-registered-backends))
5469 (lambda (a b)
5470 (let ((key-a (nth 1 a))
5471 (key-b (nth 1 b)))
5472 (cond ((and (numberp key-a) (numberp key-b))
5473 (< key-a key-b))
5474 ((numberp key-b) t)))))
5475 (lambda (a b) (< (car a) (car b)))))
5476 ;; Compute a list of allowed keys based on the first key
5477 ;; pressed, if any. Some keys (?^B, ?^V, ?^S, ?^F, ?^A
5478 ;; and ?q) are always available.
5479 (allowed-keys
5480 (nconc (list 2 22 19 6 1)
5481 (if (not first-key) (org-uniquify (mapcar 'car backends))
5482 (let (sub-menu)
5483 (dolist (backend backends (sort (mapcar 'car sub-menu) '<))
5484 (when (eq (car backend) first-key)
5485 (setq sub-menu (append (nth 2 backend) sub-menu))))))
5486 (cond ((eq first-key ?P) (list ?f ?p ?x ?a))
5487 ((not first-key) (list ?P)))
5488 (list ?&)
5489 (when expertp (list ??))
5490 (list ?q)))
5491 ;; Build the help menu for standard UI.
5492 (help
5493 (unless expertp
5494 (concat
5495 ;; Options are hard-coded.
5496 (format "Options
5497 [%s] Body only: %s [%s] Visible only: %s
5498 [%s] Export scope: %s [%s] Force publishing: %s
5499 [%s] Async export: %s\n"
5500 (funcall fontify-key "C-b" t)
5501 (funcall fontify-value
5502 (if (memq 'body options) "On " "Off"))
5503 (funcall fontify-key "C-v" t)
5504 (funcall fontify-value
5505 (if (memq 'visible options) "On " "Off"))
5506 (funcall fontify-key "C-s" t)
5507 (funcall fontify-value
5508 (if (memq 'subtree options) "Subtree" "Buffer "))
5509 (funcall fontify-key "C-f" t)
5510 (funcall fontify-value
5511 (if (memq 'force options) "On " "Off"))
5512 (funcall fontify-key "C-a" t)
5513 (funcall fontify-value
5514 (if (memq 'async options) "On " "Off")))
5515 ;; Display registered back-end entries. When a key
5516 ;; appears for the second time, do not create another
5517 ;; entry, but append its sub-menu to existing menu.
5518 (let (last-key)
5519 (mapconcat
5520 (lambda (entry)
5521 (let ((top-key (car entry)))
5522 (concat
5523 (unless (eq top-key last-key)
5524 (setq last-key top-key)
5525 (format "\n[%s] %s\n"
5526 (funcall fontify-key (char-to-string top-key))
5527 (nth 1 entry)))
5528 (let ((sub-menu (nth 2 entry)))
5529 (unless (functionp sub-menu)
5530 ;; Split sub-menu into two columns.
5531 (let ((index -1))
5532 (concat
5533 (mapconcat
5534 (lambda (sub-entry)
5535 (incf index)
5536 (format
5537 (if (zerop (mod index 2)) " [%s] %-26s"
5538 "[%s] %s\n")
5539 (funcall fontify-key
5540 (char-to-string (car sub-entry))
5541 top-key)
5542 (nth 1 sub-entry)))
5543 sub-menu "")
5544 (when (zerop (mod index 2)) "\n"))))))))
5545 backends ""))
5546 ;; Publishing menu is hard-coded.
5547 (format "\n[%s] Publish
5548 [%s] Current file [%s] Current project
5549 [%s] Choose project [%s] All projects\n\n"
5550 (funcall fontify-key "P")
5551 (funcall fontify-key "f" ?P)
5552 (funcall fontify-key "p" ?P)
5553 (funcall fontify-key "x" ?P)
5554 (funcall fontify-key "a" ?P))
5555 (format "\[%s] Export stack\n" (funcall fontify-key "&" t))
5556 (format "\[%s] %s"
5557 (funcall fontify-key "q" t)
5558 (if first-key "Main menu" "Exit")))))
5559 ;; Build prompts for both standard and expert UI.
5560 (standard-prompt (unless expertp "Export command: "))
5561 (expert-prompt
5562 (when expertp
5563 (format
5564 "Export command (C-%s%s%s%s%s) [%s]: "
5565 (if (memq 'body options) (funcall fontify-key "b" t) "b")
5566 (if (memq 'visible options) (funcall fontify-key "v" t) "v")
5567 (if (memq 'subtree options) (funcall fontify-key "s" t) "s")
5568 (if (memq 'force options) (funcall fontify-key "f" t) "f")
5569 (if (memq 'async options) (funcall fontify-key "a" t) "a")
5570 (mapconcat (lambda (k)
5571 ;; Strip control characters.
5572 (unless (< k 27) (char-to-string k)))
5573 allowed-keys "")))))
5574 ;; With expert UI, just read key with a fancy prompt. In standard
5575 ;; UI, display an intrusive help buffer.
5576 (if expertp
5577 (org-export--dispatch-action
5578 expert-prompt allowed-keys backends options first-key expertp)
5579 ;; At first call, create frame layout in order to display menu.
5580 (unless (get-buffer "*Org Export Dispatcher*")
5581 (delete-other-windows)
5582 (org-switch-to-buffer-other-window
5583 (get-buffer-create "*Org Export Dispatcher*"))
5584 (setq cursor-type nil
5585 header-line-format "Use SPC, DEL, C-n or C-p to navigate.")
5586 ;; Make sure that invisible cursor will not highlight square
5587 ;; brackets.
5588 (set-syntax-table (copy-syntax-table))
5589 (modify-syntax-entry ?\[ "w"))
5590 ;; At this point, the buffer containing the menu exists and is
5591 ;; visible in the current window. So, refresh it.
5592 (with-current-buffer "*Org Export Dispatcher*"
5593 ;; Refresh help. Maintain display continuity by re-visiting
5594 ;; previous window position.
5595 (let ((pos (window-start)))
5596 (erase-buffer)
5597 (insert help)
5598 (set-window-start nil pos)))
5599 (org-fit-window-to-buffer)
5600 (org-export--dispatch-action
5601 standard-prompt allowed-keys backends options first-key expertp))))
5603 (defun org-export--dispatch-action
5604 (prompt allowed-keys backends options first-key expertp)
5605 "Read a character from command input and act accordingly.
5607 PROMPT is the displayed prompt, as a string. ALLOWED-KEYS is
5608 a list of characters available at a given step in the process.
5609 BACKENDS is a list of menu entries. OPTIONS, FIRST-KEY and
5610 EXPERTP are the same as defined in `org-export--dispatch-ui',
5611 which see.
5613 Toggle export options when required. Otherwise, return value is
5614 a list with action as CAR and a list of interactive export
5615 options as CDR."
5616 (let (key)
5617 ;; Scrolling: when in non-expert mode, act on motion keys (C-n,
5618 ;; C-p, SPC, DEL).
5619 (while (and (setq key (read-char-exclusive prompt))
5620 (not expertp)
5621 (memq key '(14 16 ?\s ?\d)))
5622 (case key
5623 (14 (if (not (pos-visible-in-window-p (point-max)))
5624 (ignore-errors (scroll-up-line))
5625 (message "End of buffer")
5626 (sit-for 1)))
5627 (16 (if (not (pos-visible-in-window-p (point-min)))
5628 (ignore-errors (scroll-down-line))
5629 (message "Beginning of buffer")
5630 (sit-for 1)))
5631 (?\s (if (not (pos-visible-in-window-p (point-max)))
5632 (scroll-up nil)
5633 (message "End of buffer")
5634 (sit-for 1)))
5635 (?\d (if (not (pos-visible-in-window-p (point-min)))
5636 (scroll-down nil)
5637 (message "Beginning of buffer")
5638 (sit-for 1)))))
5639 (cond
5640 ;; Ignore undefined associations.
5641 ((not (memq key allowed-keys))
5642 (ding)
5643 (unless expertp (message "Invalid key") (sit-for 1))
5644 (org-export--dispatch-ui options first-key expertp))
5645 ;; q key at first level aborts export. At second
5646 ;; level, cancel first key instead.
5647 ((eq key ?q) (if (not first-key) (error "Export aborted")
5648 (org-export--dispatch-ui options nil expertp)))
5649 ;; Help key: Switch back to standard interface if
5650 ;; expert UI was active.
5651 ((eq key ??) (org-export--dispatch-ui options first-key nil))
5652 ;; Switch to asynchronous export stack.
5653 ((eq key ?&) '(stack))
5654 ;; Toggle export options
5655 ;; C-b (2) C-v (22) C-s (19) C-f (6) C-a (1)
5656 ((memq key '(2 22 19 6 1))
5657 (org-export--dispatch-ui
5658 (let ((option (case key (2 'body) (22 'visible) (19 'subtree)
5659 (6 'force) (1 'async))))
5660 (if (memq option options) (remq option options)
5661 (cons option options)))
5662 first-key expertp))
5663 ;; Action selected: Send key and options back to
5664 ;; `org-export-dispatch'.
5665 ((or first-key (functionp (nth 2 (assq key backends))))
5666 (cons (cond
5667 ((not first-key) (nth 2 (assq key backends)))
5668 ;; Publishing actions are hard-coded. Send a special
5669 ;; signal to `org-export-dispatch'.
5670 ((eq first-key ?P)
5671 (case key
5672 (?f 'publish-current-file)
5673 (?p 'publish-current-project)
5674 (?x 'publish-choose-project)
5675 (?a 'publish-all)))
5676 ;; Return first action associated to FIRST-KEY + KEY
5677 ;; path. Indeed, derived backends can share the same
5678 ;; FIRST-KEY.
5679 (t (catch 'found
5680 (mapc (lambda (backend)
5681 (let ((match (assq key (nth 2 backend))))
5682 (when match (throw 'found (nth 2 match)))))
5683 (member (assq first-key backends) backends)))))
5684 options))
5685 ;; Otherwise, enter sub-menu.
5686 (t (org-export--dispatch-ui options key expertp)))))
5690 (provide 'ox)
5692 ;; Local variables:
5693 ;; generated-autoload-file: "org-loaddefs.el"
5694 ;; End:
5696 ;;; ox.el ends here