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