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