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