Merge branch 'master' of orgmode.org:org-mode
[org-mode.git] / lisp / ox.el
bloba3694b656f87a66897e20985396af8e8852d1351
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 (and (functionp transcoder)
2066 (funcall transcoder data nil info))))
2067 ;; Element/Object with contents.
2069 (let ((transcoder (org-export-transcoder data info)))
2070 (when transcoder
2071 (let* ((greaterp (memq type org-element-greater-elements))
2072 (objectp
2073 (and (not greaterp)
2074 (memq type org-element-recursive-objects)))
2075 (contents
2076 (mapconcat
2077 (lambda (element) (org-export-data element info))
2078 (org-element-contents
2079 (if (or greaterp objectp) data
2080 ;; Elements directly containing objects
2081 ;; must have their indentation normalized
2082 ;; first.
2083 (org-element-normalize-contents
2084 data
2085 ;; When normalizing contents of the first
2086 ;; paragraph in an item or a footnote
2087 ;; definition, ignore first line's
2088 ;; indentation: there is none and it
2089 ;; might be misleading.
2090 (when (eq type 'paragraph)
2091 (let ((parent (org-export-get-parent data)))
2092 (and
2093 (eq (car (org-element-contents parent))
2094 data)
2095 (memq (org-element-type parent)
2096 '(footnote-definition item))))))))
2097 "")))
2098 (funcall transcoder data
2099 (if (not greaterp) contents
2100 (org-element-normalize-string contents))
2101 info))))))))
2102 ;; Final result will be memoized before being returned.
2103 (puthash
2104 data
2105 (cond
2106 ((not results) nil)
2107 ((memq type '(org-data plain-text nil)) results)
2108 ;; Append the same white space between elements or objects as in
2109 ;; the original buffer, and call appropriate filters.
2111 (let ((results
2112 (org-export-filter-apply-functions
2113 (plist-get info (intern (format ":filter-%s" type)))
2114 (let ((post-blank (or (org-element-property :post-blank data)
2115 0)))
2116 (if (memq type org-element-all-elements)
2117 (concat (org-element-normalize-string results)
2118 (make-string post-blank ?\n))
2119 (concat results (make-string post-blank ? ))))
2120 info)))
2121 results)))
2122 (plist-get info :exported-data))))))
2124 (defun org-export-data-with-translations (data translations info)
2125 "Convert DATA into another format using a given translation table.
2126 DATA is an element, an object, a secondary string or a string.
2127 TRANSLATIONS is an alist between element or object types and
2128 a functions handling them. See `org-export-define-backend' for
2129 more information. INFO is a plist used as a communication
2130 channel."
2131 (org-export-data
2132 data
2133 ;; Set-up a new communication channel with TRANSLATIONS as the
2134 ;; translate table and a new hash table for memoization.
2135 (org-combine-plists
2136 info
2137 (list :translate-alist translations
2138 ;; Size of the hash table is reduced since this function
2139 ;; will probably be used on short trees.
2140 :exported-data (make-hash-table :test 'eq :size 401)))))
2142 (defun org-export-data-with-backend (data backend info)
2143 "Convert DATA into BACKEND format.
2145 DATA is an element, an object, a secondary string or a string.
2146 BACKEND is a symbol. INFO is a plist used as a communication
2147 channel.
2149 Unlike to `org-export-with-backend', this function will
2150 recursively convert DATA using BACKEND translation table."
2151 (org-export-barf-if-invalid-backend backend)
2152 (org-export-data-with-translations
2153 data (org-export-backend-translate-table backend) info))
2155 (defun org-export--interpret-p (blob info)
2156 "Non-nil if element or object BLOB should be interpreted during export.
2157 If nil, BLOB will appear as raw Org syntax. Check is done
2158 according to export options INFO, stored as a plist."
2159 (case (org-element-type blob)
2160 ;; ... entities...
2161 (entity (plist-get info :with-entities))
2162 ;; ... emphasis...
2163 ((bold italic strike-through underline)
2164 (plist-get info :with-emphasize))
2165 ;; ... fixed-width areas.
2166 (fixed-width (plist-get info :with-fixed-width))
2167 ;; ... footnotes...
2168 ((footnote-definition footnote-reference)
2169 (plist-get info :with-footnotes))
2170 ;; ... LaTeX environments and fragments...
2171 ((latex-environment latex-fragment)
2172 (let ((with-latex-p (plist-get info :with-latex)))
2173 (and with-latex-p (not (eq with-latex-p 'verbatim)))))
2174 ;; ... sub/superscripts...
2175 ((subscript superscript)
2176 (let ((sub/super-p (plist-get info :with-sub-superscript)))
2177 (if (eq sub/super-p '{})
2178 (org-element-property :use-brackets-p blob)
2179 sub/super-p)))
2180 ;; ... tables...
2181 (table (plist-get info :with-tables))
2182 (otherwise t)))
2184 (defun org-export-expand (blob contents)
2185 "Expand a parsed element or object to its original state.
2186 BLOB is either an element or an object. CONTENTS is its
2187 contents, as a string or nil."
2188 (funcall
2189 (intern (format "org-element-%s-interpreter" (org-element-type blob)))
2190 blob contents))
2192 (defun org-export-ignore-element (element info)
2193 "Add ELEMENT to `:ignore-list' in INFO.
2195 Any element in `:ignore-list' will be skipped when using
2196 `org-element-map'. INFO is modified by side effects."
2197 (plist-put info :ignore-list (cons element (plist-get info :ignore-list))))
2201 ;;; The Filter System
2203 ;; Filters allow end-users to tweak easily the transcoded output.
2204 ;; They are the functional counterpart of hooks, as every filter in
2205 ;; a set is applied to the return value of the previous one.
2207 ;; Every set is back-end agnostic. Although, a filter is always
2208 ;; called, in addition to the string it applies to, with the back-end
2209 ;; used as argument, so it's easy for the end-user to add back-end
2210 ;; specific filters in the set. The communication channel, as
2211 ;; a plist, is required as the third argument.
2213 ;; From the developer side, filters sets can be installed in the
2214 ;; process with the help of `org-export-define-backend', which
2215 ;; internally stores filters as an alist. Each association has a key
2216 ;; among the following symbols and a function or a list of functions
2217 ;; as value.
2219 ;; - `:filter-options' applies to the property list containing export
2220 ;; options. Unlike to other filters, functions in this list accept
2221 ;; two arguments instead of three: the property list containing
2222 ;; export options and the back-end. Users can set its value through
2223 ;; `org-export-filter-options-functions' variable.
2225 ;; - `:filter-parse-tree' applies directly to the complete parsed
2226 ;; tree. Users can set it through
2227 ;; `org-export-filter-parse-tree-functions' variable.
2229 ;; - `:filter-final-output' applies to the final transcoded string.
2230 ;; Users can set it with `org-export-filter-final-output-functions'
2231 ;; variable
2233 ;; - `:filter-plain-text' applies to any string not recognized as Org
2234 ;; syntax. `org-export-filter-plain-text-functions' allows users to
2235 ;; configure it.
2237 ;; - `:filter-TYPE' applies on the string returned after an element or
2238 ;; object of type TYPE has been transcoded. An user can modify
2239 ;; `org-export-filter-TYPE-functions'
2241 ;; All filters sets are applied with
2242 ;; `org-export-filter-apply-functions' function. Filters in a set are
2243 ;; applied in a LIFO fashion. It allows developers to be sure that
2244 ;; their filters will be applied first.
2246 ;; Filters properties are installed in communication channel with
2247 ;; `org-export-install-filters' function.
2249 ;; Eventually, two hooks (`org-export-before-processing-hook' and
2250 ;; `org-export-before-parsing-hook') are run at the beginning of the
2251 ;; export process and just before parsing to allow for heavy structure
2252 ;; modifications.
2255 ;;;; Hooks
2257 (defvar org-export-before-processing-hook nil
2258 "Hook run at the beginning of the export process.
2260 This is run before include keywords and macros are expanded and
2261 Babel code blocks executed, on a copy of the original buffer
2262 being exported. Visibility and narrowing are preserved. Point
2263 is at the beginning of the buffer.
2265 Every function in this hook will be called with one argument: the
2266 back-end currently used, as a symbol.")
2268 (defvar org-export-before-parsing-hook nil
2269 "Hook run before parsing an export buffer.
2271 This is run after include keywords and macros have been expanded
2272 and Babel code blocks executed, on a copy of the original buffer
2273 being exported. Visibility and narrowing are preserved. Point
2274 is at the beginning of the buffer.
2276 Every function in this hook will be called with one argument: the
2277 back-end currently used, as a symbol.")
2280 ;;;; Special Filters
2282 (defvar org-export-filter-options-functions nil
2283 "List of functions applied to the export options.
2284 Each filter is called with two arguments: the export options, as
2285 a plist, and the back-end, as a symbol. It must return
2286 a property list containing export options.")
2288 (defvar org-export-filter-parse-tree-functions nil
2289 "List of functions applied to the parsed tree.
2290 Each filter is called with three arguments: the parse tree, as
2291 returned by `org-element-parse-buffer', the back-end, as
2292 a symbol, and the communication channel, as a plist. It must
2293 return the modified parse tree to transcode.")
2295 (defvar org-export-filter-plain-text-functions nil
2296 "List of functions applied to plain text.
2297 Each filter is called with three arguments: a string which
2298 contains no Org syntax, the back-end, as a symbol, and the
2299 communication channel, as a plist. It must return a string or
2300 nil.")
2302 (defvar org-export-filter-final-output-functions nil
2303 "List of functions applied to the transcoded string.
2304 Each filter is called with three arguments: the full transcoded
2305 string, the back-end, as a symbol, and the communication channel,
2306 as a plist. It must return a string that will be used as the
2307 final export output.")
2310 ;;;; Elements Filters
2312 (defvar org-export-filter-babel-call-functions nil
2313 "List of functions applied to a transcoded babel-call.
2314 Each filter is called with three arguments: the transcoded data,
2315 as a string, the back-end, as a symbol, and the communication
2316 channel, as a plist. It must return a string or nil.")
2318 (defvar org-export-filter-center-block-functions nil
2319 "List of functions applied to a transcoded center block.
2320 Each filter is called with three arguments: the transcoded data,
2321 as a string, the back-end, as a symbol, and the communication
2322 channel, as a plist. It must return a string or nil.")
2324 (defvar org-export-filter-clock-functions nil
2325 "List of functions applied to a transcoded clock.
2326 Each filter is called with three arguments: the transcoded data,
2327 as a string, the back-end, as a symbol, and the communication
2328 channel, as a plist. It must return a string or nil.")
2330 (defvar org-export-filter-comment-functions nil
2331 "List of functions applied to a transcoded comment.
2332 Each filter is called with three arguments: the transcoded data,
2333 as a string, the back-end, as a symbol, and the communication
2334 channel, as a plist. It must return a string or nil.")
2336 (defvar org-export-filter-comment-block-functions nil
2337 "List of functions applied to a transcoded comment-block.
2338 Each filter is called with three arguments: the transcoded data,
2339 as a string, the back-end, as a symbol, and the communication
2340 channel, as a plist. It must return a string or nil.")
2342 (defvar org-export-filter-diary-sexp-functions nil
2343 "List of functions applied to a transcoded diary-sexp.
2344 Each filter is called with three arguments: the transcoded data,
2345 as a string, the back-end, as a symbol, and the communication
2346 channel, as a plist. It must return a string or nil.")
2348 (defvar org-export-filter-drawer-functions nil
2349 "List of functions applied to a transcoded drawer.
2350 Each filter is called with three arguments: the transcoded data,
2351 as a string, the back-end, as a symbol, and the communication
2352 channel, as a plist. It must return a string or nil.")
2354 (defvar org-export-filter-dynamic-block-functions nil
2355 "List of functions applied to a transcoded dynamic-block.
2356 Each filter is called with three arguments: the transcoded data,
2357 as a string, the back-end, as a symbol, and the communication
2358 channel, as a plist. It must return a string or nil.")
2360 (defvar org-export-filter-example-block-functions nil
2361 "List of functions applied to a transcoded example-block.
2362 Each filter is called with three arguments: the transcoded data,
2363 as a string, the back-end, as a symbol, and the communication
2364 channel, as a plist. It must return a string or nil.")
2366 (defvar org-export-filter-export-block-functions nil
2367 "List of functions applied to a transcoded export-block.
2368 Each filter is called with three arguments: the transcoded data,
2369 as a string, the back-end, as a symbol, and the communication
2370 channel, as a plist. It must return a string or nil.")
2372 (defvar org-export-filter-fixed-width-functions nil
2373 "List of functions applied to a transcoded fixed-width.
2374 Each filter is called with three arguments: the transcoded data,
2375 as a string, the back-end, as a symbol, and the communication
2376 channel, as a plist. It must return a string or nil.")
2378 (defvar org-export-filter-footnote-definition-functions nil
2379 "List of functions applied to a transcoded footnote-definition.
2380 Each filter is called with three arguments: the transcoded data,
2381 as a string, the back-end, as a symbol, and the communication
2382 channel, as a plist. It must return a string or nil.")
2384 (defvar org-export-filter-headline-functions nil
2385 "List of functions applied to a transcoded headline.
2386 Each filter is called with three arguments: the transcoded data,
2387 as a string, the back-end, as a symbol, and the communication
2388 channel, as a plist. It must return a string or nil.")
2390 (defvar org-export-filter-horizontal-rule-functions nil
2391 "List of functions applied to a transcoded horizontal-rule.
2392 Each filter is called with three arguments: the transcoded data,
2393 as a string, the back-end, as a symbol, and the communication
2394 channel, as a plist. It must return a string or nil.")
2396 (defvar org-export-filter-inlinetask-functions nil
2397 "List of functions applied to a transcoded inlinetask.
2398 Each filter is called with three arguments: the transcoded data,
2399 as a string, the back-end, as a symbol, and the communication
2400 channel, as a plist. It must return a string or nil.")
2402 (defvar org-export-filter-item-functions nil
2403 "List of functions applied to a transcoded item.
2404 Each filter is called with three arguments: the transcoded data,
2405 as a string, the back-end, as a symbol, and the communication
2406 channel, as a plist. It must return a string or nil.")
2408 (defvar org-export-filter-keyword-functions nil
2409 "List of functions applied to a transcoded keyword.
2410 Each filter is called with three arguments: the transcoded data,
2411 as a string, the back-end, as a symbol, and the communication
2412 channel, as a plist. It must return a string or nil.")
2414 (defvar org-export-filter-latex-environment-functions nil
2415 "List of functions applied to a transcoded latex-environment.
2416 Each filter is called with three arguments: the transcoded data,
2417 as a string, the back-end, as a symbol, and the communication
2418 channel, as a plist. It must return a string or nil.")
2420 (defvar org-export-filter-node-property-functions nil
2421 "List of functions applied to a transcoded node-property.
2422 Each filter is called with three arguments: the transcoded data,
2423 as a string, the back-end, as a symbol, and the communication
2424 channel, as a plist. It must return a string or nil.")
2426 (defvar org-export-filter-paragraph-functions nil
2427 "List of functions applied to a transcoded paragraph.
2428 Each filter is called with three arguments: the transcoded data,
2429 as a string, the back-end, as a symbol, and the communication
2430 channel, as a plist. It must return a string or nil.")
2432 (defvar org-export-filter-plain-list-functions nil
2433 "List of functions applied to a transcoded plain-list.
2434 Each filter is called with three arguments: the transcoded data,
2435 as a string, the back-end, as a symbol, and the communication
2436 channel, as a plist. It must return a string or nil.")
2438 (defvar org-export-filter-planning-functions nil
2439 "List of functions applied to a transcoded planning.
2440 Each filter is called with three arguments: the transcoded data,
2441 as a string, the back-end, as a symbol, and the communication
2442 channel, as a plist. It must return a string or nil.")
2444 (defvar org-export-filter-property-drawer-functions nil
2445 "List of functions applied to a transcoded property-drawer.
2446 Each filter is called with three arguments: the transcoded data,
2447 as a string, the back-end, as a symbol, and the communication
2448 channel, as a plist. It must return a string or nil.")
2450 (defvar org-export-filter-quote-block-functions nil
2451 "List of functions applied to a transcoded quote block.
2452 Each filter is called with three arguments: the transcoded quote
2453 data, as a string, the back-end, as a symbol, and the
2454 communication channel, as a plist. It must return a string or
2455 nil.")
2457 (defvar org-export-filter-quote-section-functions nil
2458 "List of functions applied to a transcoded quote-section.
2459 Each filter is called with three arguments: the transcoded data,
2460 as a string, the back-end, as a symbol, and the communication
2461 channel, as a plist. It must return a string or nil.")
2463 (defvar org-export-filter-section-functions nil
2464 "List of functions applied to a transcoded section.
2465 Each filter is called with three arguments: the transcoded data,
2466 as a string, the back-end, as a symbol, and the communication
2467 channel, as a plist. It must return a string or nil.")
2469 (defvar org-export-filter-special-block-functions nil
2470 "List of functions applied to a transcoded special block.
2471 Each filter is called with three arguments: the transcoded data,
2472 as a string, the back-end, as a symbol, and the communication
2473 channel, as a plist. It must return a string or nil.")
2475 (defvar org-export-filter-src-block-functions nil
2476 "List of functions applied to a transcoded src-block.
2477 Each filter is called with three arguments: the transcoded data,
2478 as a string, the back-end, as a symbol, and the communication
2479 channel, as a plist. It must return a string or nil.")
2481 (defvar org-export-filter-table-functions nil
2482 "List of functions applied to a transcoded table.
2483 Each filter is called with three arguments: the transcoded data,
2484 as a string, the back-end, as a symbol, and the communication
2485 channel, as a plist. It must return a string or nil.")
2487 (defvar org-export-filter-table-cell-functions nil
2488 "List of functions applied to a transcoded table-cell.
2489 Each filter is called with three arguments: the transcoded data,
2490 as a string, the back-end, as a symbol, and the communication
2491 channel, as a plist. It must return a string or nil.")
2493 (defvar org-export-filter-table-row-functions nil
2494 "List of functions applied to a transcoded table-row.
2495 Each filter is called with three arguments: the transcoded data,
2496 as a string, the back-end, as a symbol, and the communication
2497 channel, as a plist. It must return a string or nil.")
2499 (defvar org-export-filter-verse-block-functions nil
2500 "List of functions applied to a transcoded verse block.
2501 Each filter is called with three arguments: the transcoded data,
2502 as a string, the back-end, as a symbol, and the communication
2503 channel, as a plist. It must return a string or nil.")
2506 ;;;; Objects Filters
2508 (defvar org-export-filter-bold-functions nil
2509 "List of functions applied to transcoded bold text.
2510 Each filter is called with three arguments: the transcoded data,
2511 as a string, the back-end, as a symbol, and the communication
2512 channel, as a plist. It must return a string or nil.")
2514 (defvar org-export-filter-code-functions nil
2515 "List of functions applied to transcoded code text.
2516 Each filter is called with three arguments: the transcoded data,
2517 as a string, the back-end, as a symbol, and the communication
2518 channel, as a plist. It must return a string or nil.")
2520 (defvar org-export-filter-entity-functions nil
2521 "List of functions applied to a transcoded entity.
2522 Each filter is called with three arguments: the transcoded data,
2523 as a string, the back-end, as a symbol, and the communication
2524 channel, as a plist. It must return a string or nil.")
2526 (defvar org-export-filter-export-snippet-functions nil
2527 "List of functions applied to a transcoded export-snippet.
2528 Each filter is called with three arguments: the transcoded data,
2529 as a string, the back-end, as a symbol, and the communication
2530 channel, as a plist. It must return a string or nil.")
2532 (defvar org-export-filter-footnote-reference-functions nil
2533 "List of functions applied to a transcoded footnote-reference.
2534 Each filter is called with three arguments: the transcoded data,
2535 as a string, the back-end, as a symbol, and the communication
2536 channel, as a plist. It must return a string or nil.")
2538 (defvar org-export-filter-inline-babel-call-functions nil
2539 "List of functions applied to a transcoded inline-babel-call.
2540 Each filter is called with three arguments: the transcoded data,
2541 as a string, the back-end, as a symbol, and the communication
2542 channel, as a plist. It must return a string or nil.")
2544 (defvar org-export-filter-inline-src-block-functions nil
2545 "List of functions applied to a transcoded inline-src-block.
2546 Each filter is called with three arguments: the transcoded data,
2547 as a string, the back-end, as a symbol, and the communication
2548 channel, as a plist. It must return a string or nil.")
2550 (defvar org-export-filter-italic-functions nil
2551 "List of functions applied to transcoded italic text.
2552 Each filter is called with three arguments: the transcoded data,
2553 as a string, the back-end, as a symbol, and the communication
2554 channel, as a plist. It must return a string or nil.")
2556 (defvar org-export-filter-latex-fragment-functions nil
2557 "List of functions applied to a transcoded latex-fragment.
2558 Each filter is called with three arguments: the transcoded data,
2559 as a string, the back-end, as a symbol, and the communication
2560 channel, as a plist. It must return a string or nil.")
2562 (defvar org-export-filter-line-break-functions nil
2563 "List of functions applied to a transcoded line-break.
2564 Each filter is called with three arguments: the transcoded data,
2565 as a string, the back-end, as a symbol, and the communication
2566 channel, as a plist. It must return a string or nil.")
2568 (defvar org-export-filter-link-functions nil
2569 "List of functions applied to a transcoded link.
2570 Each filter is called with three arguments: the transcoded data,
2571 as a string, the back-end, as a symbol, and the communication
2572 channel, as a plist. It must return a string or nil.")
2574 (defvar org-export-filter-macro-functions nil
2575 "List of functions applied to a transcoded macro.
2576 Each filter is called with three arguments: the transcoded data,
2577 as a string, the back-end, as a symbol, and the communication
2578 channel, as a plist. It must return a string or nil.")
2580 (defvar org-export-filter-radio-target-functions nil
2581 "List of functions applied to a transcoded radio-target.
2582 Each filter is called with three arguments: the transcoded data,
2583 as a string, the back-end, as a symbol, and the communication
2584 channel, as a plist. It must return a string or nil.")
2586 (defvar org-export-filter-statistics-cookie-functions nil
2587 "List of functions applied to a transcoded statistics-cookie.
2588 Each filter is called with three arguments: the transcoded data,
2589 as a string, the back-end, as a symbol, and the communication
2590 channel, as a plist. It must return a string or nil.")
2592 (defvar org-export-filter-strike-through-functions nil
2593 "List of functions applied to transcoded strike-through text.
2594 Each filter is called with three arguments: the transcoded data,
2595 as a string, the back-end, as a symbol, and the communication
2596 channel, as a plist. It must return a string or nil.")
2598 (defvar org-export-filter-subscript-functions nil
2599 "List of functions applied to a transcoded subscript.
2600 Each filter is called with three arguments: the transcoded data,
2601 as a string, the back-end, as a symbol, and the communication
2602 channel, as a plist. It must return a string or nil.")
2604 (defvar org-export-filter-superscript-functions nil
2605 "List of functions applied to a transcoded superscript.
2606 Each filter is called with three arguments: the transcoded data,
2607 as a string, the back-end, as a symbol, and the communication
2608 channel, as a plist. It must return a string or nil.")
2610 (defvar org-export-filter-target-functions nil
2611 "List of functions applied to a transcoded target.
2612 Each filter is called with three arguments: the transcoded data,
2613 as a string, the back-end, as a symbol, and the communication
2614 channel, as a plist. It must return a string or nil.")
2616 (defvar org-export-filter-timestamp-functions nil
2617 "List of functions applied to a transcoded timestamp.
2618 Each filter is called with three arguments: the transcoded data,
2619 as a string, the back-end, as a symbol, and the communication
2620 channel, as a plist. It must return a string or nil.")
2622 (defvar org-export-filter-underline-functions nil
2623 "List of functions applied to transcoded underline text.
2624 Each filter is called with three arguments: the transcoded data,
2625 as a string, the back-end, as a symbol, and the communication
2626 channel, as a plist. It must return a string or nil.")
2628 (defvar org-export-filter-verbatim-functions nil
2629 "List of functions applied to transcoded verbatim text.
2630 Each filter is called with three arguments: the transcoded data,
2631 as a string, the back-end, as a symbol, and the communication
2632 channel, as a plist. It must return a string or nil.")
2635 ;;;; Filters Tools
2637 ;; Internal function `org-export-install-filters' installs filters
2638 ;; hard-coded in back-ends (developer filters) and filters from global
2639 ;; variables (user filters) in the communication channel.
2641 ;; Internal function `org-export-filter-apply-functions' takes care
2642 ;; about applying each filter in order to a given data. It ignores
2643 ;; filters returning a nil value but stops whenever a filter returns
2644 ;; an empty string.
2646 (defun org-export-filter-apply-functions (filters value info)
2647 "Call every function in FILTERS.
2649 Functions are called with arguments VALUE, current export
2650 back-end and INFO. A function returning a nil value will be
2651 skipped. If it returns the empty string, the process ends and
2652 VALUE is ignored.
2654 Call is done in a LIFO fashion, to be sure that developer
2655 specified filters, if any, are called first."
2656 (catch 'exit
2657 (dolist (filter filters value)
2658 (let ((result (funcall filter value (plist-get info :back-end) info)))
2659 (cond ((not result) value)
2660 ((equal value "") (throw 'exit nil))
2661 (t (setq value result)))))))
2663 (defun org-export-install-filters (info)
2664 "Install filters properties in communication channel.
2665 INFO is a plist containing the current communication channel.
2666 Return the updated communication channel."
2667 (let (plist)
2668 ;; Install user-defined filters with `org-export-filters-alist'
2669 ;; and filters already in INFO (through ext-plist mechanism).
2670 (mapc (lambda (p)
2671 (let* ((prop (car p))
2672 (info-value (plist-get info prop))
2673 (default-value (symbol-value (cdr p))))
2674 (setq plist
2675 (plist-put plist prop
2676 ;; Filters in INFO will be called
2677 ;; before those user provided.
2678 (append (if (listp info-value) info-value
2679 (list info-value))
2680 default-value)))))
2681 org-export-filters-alist)
2682 ;; Prepend back-end specific filters to that list.
2683 (mapc (lambda (p)
2684 ;; Single values get consed, lists are appended.
2685 (let ((key (car p)) (value (cdr p)))
2686 (when value
2687 (setq plist
2688 (plist-put
2689 plist key
2690 (if (atom value) (cons value (plist-get plist key))
2691 (append value (plist-get plist key))))))))
2692 (org-export-backend-filters (plist-get info :back-end)))
2693 ;; Return new communication channel.
2694 (org-combine-plists info plist)))
2698 ;;; Core functions
2700 ;; This is the room for the main function, `org-export-as', along with
2701 ;; its derivatives, `org-export-to-buffer', `org-export-to-file' and
2702 ;; `org-export-string-as'. They differ either by the way they output
2703 ;; the resulting code (for the first two) or by the input type (for
2704 ;; the latter). `org-export--copy-to-kill-ring-p' determines if
2705 ;; output of these function should be added to kill ring.
2707 ;; `org-export-output-file-name' is an auxiliary function meant to be
2708 ;; used with `org-export-to-file'. With a given extension, it tries
2709 ;; to provide a canonical file name to write export output to.
2711 ;; Note that `org-export-as' doesn't really parse the current buffer,
2712 ;; but a copy of it (with the same buffer-local variables and
2713 ;; visibility), where macros and include keywords are expanded and
2714 ;; Babel blocks are executed, if appropriate.
2715 ;; `org-export-with-buffer-copy' macro prepares that copy.
2717 ;; File inclusion is taken care of by
2718 ;; `org-export-expand-include-keyword' and
2719 ;; `org-export--prepare-file-contents'. Structure wise, including
2720 ;; a whole Org file in a buffer often makes little sense. For
2721 ;; example, if the file contains a headline and the include keyword
2722 ;; was within an item, the item should contain the headline. That's
2723 ;; why file inclusion should be done before any structure can be
2724 ;; associated to the file, that is before parsing.
2726 (defun org-export-copy-buffer ()
2727 "Return a copy of the current buffer.
2728 The copy preserves Org buffer-local variables, visibility and
2729 narrowing."
2730 (let ((copy-buffer-fun (org-export--generate-copy-script (current-buffer)))
2731 (new-buf (generate-new-buffer (buffer-name))))
2732 (with-current-buffer new-buf
2733 (funcall copy-buffer-fun)
2734 (set-buffer-modified-p nil))
2735 new-buf))
2737 (defmacro org-export-with-buffer-copy (&rest body)
2738 "Apply BODY in a copy of the current buffer.
2739 The copy preserves local variables, visibility and contents of
2740 the original buffer. Point is at the beginning of the buffer
2741 when BODY is applied."
2742 (declare (debug t))
2743 (org-with-gensyms (buf-copy)
2744 `(let ((,buf-copy (org-export-copy-buffer)))
2745 (unwind-protect
2746 (with-current-buffer ,buf-copy
2747 (goto-char (point-min))
2748 (progn ,@body))
2749 (and (buffer-live-p ,buf-copy)
2750 ;; Kill copy without confirmation.
2751 (progn (with-current-buffer ,buf-copy
2752 (restore-buffer-modified-p nil))
2753 (kill-buffer ,buf-copy)))))))
2755 (defun org-export--generate-copy-script (buffer)
2756 "Generate a function duplicating BUFFER.
2758 The copy will preserve local variables, visibility, contents and
2759 narrowing of the original buffer. If a region was active in
2760 BUFFER, contents will be narrowed to that region instead.
2762 The resulting function can be evaled at a later time, from
2763 another buffer, effectively cloning the original buffer there.
2765 The function assumes BUFFER's major mode is `org-mode'."
2766 (with-current-buffer buffer
2767 `(lambda ()
2768 (let ((inhibit-modification-hooks t))
2769 ;; Set major mode. Ignore `org-mode-hook' as it has been run
2770 ;; already in BUFFER.
2771 (let ((org-mode-hook nil)) (org-mode))
2772 ;; Buffer local variables.
2773 ,@(let (local-vars)
2774 (mapc
2775 (lambda (entry)
2776 (when (consp entry)
2777 (let ((var (car entry))
2778 (val (cdr entry)))
2779 (and (not (eq var 'org-font-lock-keywords))
2780 (or (memq var
2781 '(default-directory
2782 buffer-file-name
2783 buffer-file-coding-system))
2784 (string-match "^\\(org-\\|orgtbl-\\)"
2785 (symbol-name var)))
2786 ;; Skip unreadable values, as they cannot be
2787 ;; sent to external process.
2788 (or (not val) (ignore-errors (read (format "%S" val))))
2789 (push `(set (make-local-variable (quote ,var))
2790 (quote ,val))
2791 local-vars)))))
2792 (buffer-local-variables (buffer-base-buffer)))
2793 local-vars)
2794 ;; Whole buffer contents.
2795 (insert
2796 ,(org-with-wide-buffer
2797 (buffer-substring-no-properties
2798 (point-min) (point-max))))
2799 ;; Narrowing.
2800 ,(if (org-region-active-p)
2801 `(narrow-to-region ,(region-beginning) ,(region-end))
2802 `(narrow-to-region ,(point-min) ,(point-max)))
2803 ;; Current position of point.
2804 (goto-char ,(point))
2805 ;; Overlays with invisible property.
2806 ,@(let (ov-set)
2807 (mapc
2808 (lambda (ov)
2809 (let ((invis-prop (overlay-get ov 'invisible)))
2810 (when invis-prop
2811 (push `(overlay-put
2812 (make-overlay ,(overlay-start ov)
2813 ,(overlay-end ov))
2814 'invisible (quote ,invis-prop))
2815 ov-set))))
2816 (overlays-in (point-min) (point-max)))
2817 ov-set)))))
2819 ;;;###autoload
2820 (defun org-export-as
2821 (backend &optional subtreep visible-only body-only ext-plist)
2822 "Transcode current Org buffer into BACKEND code.
2824 If narrowing is active in the current buffer, only transcode its
2825 narrowed part.
2827 If a region is active, transcode that region.
2829 When optional argument SUBTREEP is non-nil, transcode the
2830 sub-tree at point, extracting information from the headline
2831 properties first.
2833 When optional argument VISIBLE-ONLY is non-nil, don't export
2834 contents of hidden elements.
2836 When optional argument BODY-ONLY is non-nil, only return body
2837 code, without surrounding template.
2839 Optional argument EXT-PLIST, when provided, is a property list
2840 with external parameters overriding Org default settings, but
2841 still inferior to file-local settings.
2843 Return code as a string."
2844 (org-export-barf-if-invalid-backend backend)
2845 (save-excursion
2846 (save-restriction
2847 ;; Narrow buffer to an appropriate region or subtree for
2848 ;; parsing. If parsing subtree, be sure to remove main headline
2849 ;; too.
2850 (cond ((org-region-active-p)
2851 (narrow-to-region (region-beginning) (region-end)))
2852 (subtreep
2853 (org-narrow-to-subtree)
2854 (goto-char (point-min))
2855 (forward-line)
2856 (narrow-to-region (point) (point-max))))
2857 ;; Initialize communication channel with original buffer
2858 ;; attributes, unavailable in its copy.
2859 (let ((info (org-combine-plists
2860 (list :export-options
2861 (delq nil
2862 (list (and subtreep 'subtree)
2863 (and visible-only 'visible-only)
2864 (and body-only 'body-only))))
2865 (org-export--get-buffer-attributes)))
2866 tree)
2867 ;; Update communication channel and get parse tree. Buffer
2868 ;; isn't parsed directly. Instead, a temporary copy is
2869 ;; created, where include keywords, macros are expanded and
2870 ;; code blocks are evaluated.
2871 (org-export-with-buffer-copy
2872 ;; Run first hook with current back-end as argument.
2873 (run-hook-with-args 'org-export-before-processing-hook backend)
2874 (org-export-expand-include-keyword)
2875 ;; Update macro templates since #+INCLUDE keywords might have
2876 ;; added some new ones.
2877 (org-macro-initialize-templates)
2878 (org-macro-replace-all org-macro-templates)
2879 (org-export-execute-babel-code)
2880 ;; Update radio targets since keyword inclusion might have
2881 ;; added some more.
2882 (org-update-radio-target-regexp)
2883 ;; Run last hook with current back-end as argument.
2884 (goto-char (point-min))
2885 (save-excursion
2886 (run-hook-with-args 'org-export-before-parsing-hook backend))
2887 ;; Update communication channel with environment. Also
2888 ;; install user's and developer's filters.
2889 (setq info
2890 (org-export-install-filters
2891 (org-combine-plists
2892 info (org-export-get-environment backend subtreep ext-plist))))
2893 ;; Expand export-specific set of macros: {{{author}}},
2894 ;; {{{date}}}, {{{email}}} and {{{title}}}. It must be done
2895 ;; once regular macros have been expanded, since document
2896 ;; keywords may contain one of them.
2897 (org-macro-replace-all
2898 (list (cons "author"
2899 (org-element-interpret-data (plist-get info :author)))
2900 (cons "date"
2901 (org-element-interpret-data (plist-get info :date)))
2902 ;; EMAIL is not a parsed keyword: store it as-is.
2903 (cons "email" (or (plist-get info :email) ""))
2904 (cons "title"
2905 (org-element-interpret-data (plist-get info :title)))))
2906 ;; Call options filters and update export options. We do not
2907 ;; use `org-export-filter-apply-functions' here since the
2908 ;; arity of such filters is different.
2909 (dolist (filter (plist-get info :filter-options))
2910 (let ((result (funcall filter info backend)))
2911 (when result (setq info result))))
2912 ;; Parse buffer and call parse-tree filter on it.
2913 (setq tree
2914 (org-export-filter-apply-functions
2915 (plist-get info :filter-parse-tree)
2916 (org-element-parse-buffer nil visible-only) info))
2917 ;; Now tree is complete, compute its properties and add them
2918 ;; to communication channel.
2919 (setq info
2920 (org-combine-plists
2921 info (org-export-collect-tree-properties tree info)))
2922 ;; Eventually transcode TREE. Wrap the resulting string into
2923 ;; a template.
2924 (let* ((body (org-element-normalize-string
2925 (or (org-export-data tree info) "")))
2926 (inner-template (cdr (assq 'inner-template
2927 (plist-get info :translate-alist))))
2928 (full-body (if (not (functionp inner-template)) body
2929 (funcall inner-template body info)))
2930 (template (cdr (assq 'template
2931 (plist-get info :translate-alist)))))
2932 ;; Remove all text properties since they cannot be
2933 ;; retrieved from an external process. Finally call
2934 ;; final-output filter and return result.
2935 (org-no-properties
2936 (org-export-filter-apply-functions
2937 (plist-get info :filter-final-output)
2938 (if (or (not (functionp template)) body-only) full-body
2939 (funcall template full-body info))
2940 info))))))))
2942 ;;;###autoload
2943 (defun org-export-to-buffer
2944 (backend buffer &optional subtreep visible-only body-only ext-plist)
2945 "Call `org-export-as' with output to a specified buffer.
2947 BACKEND is the back-end used for transcoding, as a symbol.
2949 BUFFER is the output buffer. If it already exists, it will be
2950 erased first, otherwise, it will be created.
2952 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
2953 EXT-PLIST are similar to those used in `org-export-as', which
2954 see.
2956 Depending on `org-export-copy-to-kill-ring', add buffer contents
2957 to kill ring. Return buffer."
2958 (let ((out (org-export-as backend subtreep visible-only body-only ext-plist))
2959 (buffer (get-buffer-create buffer)))
2960 (with-current-buffer buffer
2961 (erase-buffer)
2962 (insert out)
2963 (goto-char (point-min)))
2964 ;; Maybe add buffer contents to kill ring.
2965 (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p out))
2966 (org-kill-new out))
2967 ;; Return buffer.
2968 buffer))
2970 ;;;###autoload
2971 (defun org-export-to-file
2972 (backend file &optional subtreep visible-only body-only ext-plist)
2973 "Call `org-export-as' with output to a specified file.
2975 BACKEND is the back-end used for transcoding, as a symbol. FILE
2976 is the name of the output file, as a string.
2978 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
2979 EXT-PLIST are similar to those used in `org-export-as', which
2980 see.
2982 Depending on `org-export-copy-to-kill-ring', add file contents
2983 to kill ring. Return output file's name."
2984 ;; Checks for FILE permissions. `write-file' would do the same, but
2985 ;; we'd rather avoid needless transcoding of parse tree.
2986 (unless (file-writable-p file) (error "Output file not writable"))
2987 ;; Insert contents to a temporary buffer and write it to FILE.
2988 (let ((out (org-export-as backend subtreep visible-only body-only ext-plist)))
2989 (with-temp-buffer
2990 (insert out)
2991 (let ((coding-system-for-write org-export-coding-system))
2992 (write-file file)))
2993 ;; Maybe add file contents to kill ring.
2994 (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p out))
2995 (org-kill-new out)))
2996 ;; Return full path.
2997 file)
2999 ;;;###autoload
3000 (defun org-export-string-as (string backend &optional body-only ext-plist)
3001 "Transcode STRING into BACKEND code.
3003 When optional argument BODY-ONLY is non-nil, only return body
3004 code, without preamble nor postamble.
3006 Optional argument EXT-PLIST, when provided, is a property list
3007 with external parameters overriding Org default settings, but
3008 still inferior to file-local settings.
3010 Return code as a string."
3011 (with-temp-buffer
3012 (insert string)
3013 (org-mode)
3014 (org-export-as backend nil nil body-only ext-plist)))
3016 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
3017 "Return output file's name according to buffer specifications.
3019 EXTENSION is a string representing the output file extension,
3020 with the leading dot.
3022 With a non-nil optional argument SUBTREEP, try to determine
3023 output file's name by looking for \"EXPORT_FILE_NAME\" property
3024 of subtree at point.
3026 When optional argument PUB-DIR is set, use it as the publishing
3027 directory.
3029 When optional argument VISIBLE-ONLY is non-nil, don't export
3030 contents of hidden elements.
3032 Return file name as a string."
3033 (let* ((visited-file (buffer-file-name (buffer-base-buffer)))
3034 (base-name
3035 ;; File name may come from EXPORT_FILE_NAME subtree
3036 ;; property, assuming point is at beginning of said
3037 ;; sub-tree.
3038 (file-name-sans-extension
3039 (or (and subtreep
3040 (org-entry-get
3041 (save-excursion
3042 (ignore-errors (org-back-to-heading) (point)))
3043 "EXPORT_FILE_NAME" t))
3044 ;; File name may be extracted from buffer's associated
3045 ;; file, if any.
3046 (and visited-file (file-name-nondirectory visited-file))
3047 ;; Can't determine file name on our own: Ask user.
3048 (let ((read-file-name-function
3049 (and org-completion-use-ido 'ido-read-file-name)))
3050 (read-file-name
3051 "Output file: " pub-dir nil nil nil
3052 (lambda (name)
3053 (string= (file-name-extension name t) extension)))))))
3054 (output-file
3055 ;; Build file name. Enforce EXTENSION over whatever user
3056 ;; may have come up with. PUB-DIR, if defined, always has
3057 ;; precedence over any provided path.
3058 (cond
3059 (pub-dir
3060 (concat (file-name-as-directory pub-dir)
3061 (file-name-nondirectory base-name)
3062 extension))
3063 ((file-name-absolute-p base-name) (concat base-name extension))
3064 (t (concat (file-name-as-directory ".") base-name extension)))))
3065 ;; If writing to OUTPUT-FILE would overwrite original file, append
3066 ;; EXTENSION another time to final name.
3067 (if (and visited-file (org-file-equal-p visited-file output-file))
3068 (concat output-file extension)
3069 output-file)))
3071 (defun org-export-expand-include-keyword (&optional included dir)
3072 "Expand every include keyword in buffer.
3073 Optional argument INCLUDED is a list of included file names along
3074 with their line restriction, when appropriate. It is used to
3075 avoid infinite recursion. Optional argument DIR is the current
3076 working directory. It is used to properly resolve relative
3077 paths."
3078 (let ((case-fold-search t))
3079 (goto-char (point-min))
3080 (while (re-search-forward "^[ \t]*#\\+INCLUDE: +\\(.*\\)[ \t]*$" nil t)
3081 (when (eq (org-element-type (save-match-data (org-element-at-point)))
3082 'keyword)
3083 (beginning-of-line)
3084 ;; Extract arguments from keyword's value.
3085 (let* ((value (match-string 1))
3086 (ind (org-get-indentation))
3087 (file (and (string-match "^\"\\(\\S-+\\)\"" value)
3088 (prog1 (expand-file-name (match-string 1 value) dir)
3089 (setq value (replace-match "" nil nil value)))))
3090 (lines
3091 (and (string-match
3092 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\"" value)
3093 (prog1 (match-string 1 value)
3094 (setq value (replace-match "" nil nil value)))))
3095 (env (cond ((string-match "\\<example\\>" value) 'example)
3096 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
3097 (match-string 1 value))))
3098 ;; Minimal level of included file defaults to the child
3099 ;; level of the current headline, if any, or one. It
3100 ;; only applies is the file is meant to be included as
3101 ;; an Org one.
3102 (minlevel
3103 (and (not env)
3104 (if (string-match ":minlevel +\\([0-9]+\\)" value)
3105 (prog1 (string-to-number (match-string 1 value))
3106 (setq value (replace-match "" nil nil value)))
3107 (let ((cur (org-current-level)))
3108 (if cur (1+ (org-reduced-level cur)) 1))))))
3109 ;; Remove keyword.
3110 (delete-region (point) (progn (forward-line) (point)))
3111 (cond
3112 ((not file) (error "Invalid syntax in INCLUDE keyword"))
3113 ((not (file-readable-p file)) (error "Cannot include file %s" file))
3114 ;; Check if files has already been parsed. Look after
3115 ;; inclusion lines too, as different parts of the same file
3116 ;; can be included too.
3117 ((member (list file lines) included)
3118 (error "Recursive file inclusion: %s" file))
3120 (cond
3121 ((eq env 'example)
3122 (insert
3123 (let ((ind-str (make-string ind ? ))
3124 (contents
3125 (org-escape-code-in-string
3126 (org-export--prepare-file-contents file lines))))
3127 (format "%s#+BEGIN_EXAMPLE\n%s%s#+END_EXAMPLE\n"
3128 ind-str contents ind-str))))
3129 ((stringp env)
3130 (insert
3131 (let ((ind-str (make-string ind ? ))
3132 (contents
3133 (org-escape-code-in-string
3134 (org-export--prepare-file-contents file lines))))
3135 (format "%s#+BEGIN_SRC %s\n%s%s#+END_SRC\n"
3136 ind-str env contents ind-str))))
3138 (insert
3139 (with-temp-buffer
3140 (org-mode)
3141 (insert
3142 (org-export--prepare-file-contents file lines ind minlevel))
3143 (org-export-expand-include-keyword
3144 (cons (list file lines) included)
3145 (file-name-directory file))
3146 (buffer-string))))))))))))
3148 (defun org-export--prepare-file-contents (file &optional lines ind minlevel)
3149 "Prepare the contents of FILE for inclusion and return them as a string.
3151 When optional argument LINES is a string specifying a range of
3152 lines, include only those lines.
3154 Optional argument IND, when non-nil, is an integer specifying the
3155 global indentation of returned contents. Since its purpose is to
3156 allow an included file to stay in the same environment it was
3157 created \(i.e. a list item), it doesn't apply past the first
3158 headline encountered.
3160 Optional argument MINLEVEL, when non-nil, is an integer
3161 specifying the level that any top-level headline in the included
3162 file should have."
3163 (with-temp-buffer
3164 (insert-file-contents file)
3165 (when lines
3166 (let* ((lines (split-string lines "-"))
3167 (lbeg (string-to-number (car lines)))
3168 (lend (string-to-number (cadr lines)))
3169 (beg (if (zerop lbeg) (point-min)
3170 (goto-char (point-min))
3171 (forward-line (1- lbeg))
3172 (point)))
3173 (end (if (zerop lend) (point-max)
3174 (goto-char (point-min))
3175 (forward-line (1- lend))
3176 (point))))
3177 (narrow-to-region beg end)))
3178 ;; Remove blank lines at beginning and end of contents. The logic
3179 ;; behind that removal is that blank lines around include keyword
3180 ;; override blank lines in included file.
3181 (goto-char (point-min))
3182 (org-skip-whitespace)
3183 (beginning-of-line)
3184 (delete-region (point-min) (point))
3185 (goto-char (point-max))
3186 (skip-chars-backward " \r\t\n")
3187 (forward-line)
3188 (delete-region (point) (point-max))
3189 ;; If IND is set, preserve indentation of include keyword until
3190 ;; the first headline encountered.
3191 (when ind
3192 (unless (eq major-mode 'org-mode) (org-mode))
3193 (goto-char (point-min))
3194 (let ((ind-str (make-string ind ? )))
3195 (while (not (or (eobp) (looking-at org-outline-regexp-bol)))
3196 ;; Do not move footnote definitions out of column 0.
3197 (unless (and (looking-at org-footnote-definition-re)
3198 (eq (org-element-type (org-element-at-point))
3199 'footnote-definition))
3200 (insert ind-str))
3201 (forward-line))))
3202 ;; When MINLEVEL is specified, compute minimal level for headlines
3203 ;; in the file (CUR-MIN), and remove stars to each headline so
3204 ;; that headlines with minimal level have a level of MINLEVEL.
3205 (when minlevel
3206 (unless (eq major-mode 'org-mode) (org-mode))
3207 (org-with-limited-levels
3208 (let ((levels (org-map-entries
3209 (lambda () (org-reduced-level (org-current-level))))))
3210 (when levels
3211 (let ((offset (- minlevel (apply 'min levels))))
3212 (unless (zerop offset)
3213 (when org-odd-levels-only (setq offset (* offset 2)))
3214 ;; Only change stars, don't bother moving whole
3215 ;; sections.
3216 (org-map-entries
3217 (lambda () (if (< offset 0) (delete-char (abs offset))
3218 (insert (make-string offset ?*)))))))))))
3219 (org-element-normalize-string (buffer-string))))
3221 (defun org-export-execute-babel-code ()
3222 "Execute every Babel code in the visible part of current buffer."
3223 ;; Get a pristine copy of current buffer so Babel references can be
3224 ;; properly resolved.
3225 (let ((reference (org-export-copy-buffer)))
3226 (unwind-protect (let ((org-current-export-file reference))
3227 (org-babel-exp-process-buffer))
3228 (kill-buffer reference))))
3230 (defun org-export--copy-to-kill-ring-p ()
3231 "Return a non-nil value when output should be added to the kill ring.
3232 See also `org-export-copy-to-kill-ring'."
3233 (if (eq org-export-copy-to-kill-ring 'if-interactive)
3234 (not (or executing-kbd-macro noninteractive))
3235 (eq org-export-copy-to-kill-ring t)))
3239 ;;; Tools For Back-Ends
3241 ;; A whole set of tools is available to help build new exporters. Any
3242 ;; function general enough to have its use across many back-ends
3243 ;; should be added here.
3245 ;;;; For Affiliated Keywords
3247 ;; `org-export-read-attribute' reads a property from a given element
3248 ;; as a plist. It can be used to normalize affiliated keywords'
3249 ;; syntax.
3251 ;; Since captions can span over multiple lines and accept dual values,
3252 ;; their internal representation is a bit tricky. Therefore,
3253 ;; `org-export-get-caption' transparently returns a given element's
3254 ;; caption as a secondary string.
3256 (defun org-export-read-attribute (attribute element &optional property)
3257 "Turn ATTRIBUTE property from ELEMENT into a plist.
3259 When optional argument PROPERTY is non-nil, return the value of
3260 that property within attributes.
3262 This function assumes attributes are defined as \":keyword
3263 value\" pairs. It is appropriate for `:attr_html' like
3264 properties. All values will become strings except the empty
3265 string and \"nil\", which will become nil."
3266 (let ((attributes
3267 (let ((value (org-element-property attribute element)))
3268 (when value
3269 (let ((s (mapconcat 'identity value " ")) result)
3270 (while (string-match
3271 "\\(?:^\\|[ \t]+\\)\\(:[-a-zA-Z0-9_]+\\)\\([ \t]+\\|$\\)"
3273 (let ((value (substring s 0 (match-beginning 0))))
3274 (push (and (not (member value '("nil" ""))) value) result))
3275 (push (intern (match-string 1 s)) result)
3276 (setq s (substring s (match-end 0))))
3277 ;; Ignore any string before the first property with `cdr'.
3278 (cdr (nreverse (cons (and (org-string-nw-p s)
3279 (not (equal s "nil"))
3281 result))))))))
3282 (if property (plist-get attributes property) attributes)))
3284 (defun org-export-get-caption (element &optional shortp)
3285 "Return caption from ELEMENT as a secondary string.
3287 When optional argument SHORTP is non-nil, return short caption,
3288 as a secondary string, instead.
3290 Caption lines are separated by a white space."
3291 (let ((full-caption (org-element-property :caption element)) caption)
3292 (dolist (line full-caption (cdr caption))
3293 (let ((cap (funcall (if shortp 'cdr 'car) line)))
3294 (when cap
3295 (setq caption (nconc (list " ") (copy-sequence cap) caption)))))))
3298 ;;;; For Derived Back-ends
3300 ;; `org-export-with-backend' is a function allowing to locally use
3301 ;; another back-end to transcode some object or element. In a derived
3302 ;; back-end, it may be used as a fall-back function once all specific
3303 ;; cases have been treated.
3305 (defun org-export-with-backend (back-end data &optional contents info)
3306 "Call a transcoder from BACK-END on DATA.
3307 CONTENTS, when non-nil, is the transcoded contents of DATA
3308 element, as a string. INFO, when non-nil, is the communication
3309 channel used for export, as a plist.."
3310 (org-export-barf-if-invalid-backend back-end)
3311 (let ((type (org-element-type data)))
3312 (if (memq type '(nil org-data)) (error "No foreign transcoder available")
3313 (let ((transcoder
3314 (cdr (assq type (org-export-backend-translate-table back-end)))))
3315 (if (functionp transcoder) (funcall transcoder data contents info)
3316 (error "No foreign transcoder available"))))))
3319 ;;;; For Export Snippets
3321 ;; Every export snippet is transmitted to the back-end. Though, the
3322 ;; latter will only retain one type of export-snippet, ignoring
3323 ;; others, based on the former's target back-end. The function
3324 ;; `org-export-snippet-backend' returns that back-end for a given
3325 ;; export-snippet.
3327 (defun org-export-snippet-backend (export-snippet)
3328 "Return EXPORT-SNIPPET targeted back-end as a symbol.
3329 Translation, with `org-export-snippet-translation-alist', is
3330 applied."
3331 (let ((back-end (org-element-property :back-end export-snippet)))
3332 (intern
3333 (or (cdr (assoc back-end org-export-snippet-translation-alist))
3334 back-end))))
3337 ;;;; For Footnotes
3339 ;; `org-export-collect-footnote-definitions' is a tool to list
3340 ;; actually used footnotes definitions in the whole parse tree, or in
3341 ;; a headline, in order to add footnote listings throughout the
3342 ;; transcoded data.
3344 ;; `org-export-footnote-first-reference-p' is a predicate used by some
3345 ;; back-ends, when they need to attach the footnote definition only to
3346 ;; the first occurrence of the corresponding label.
3348 ;; `org-export-get-footnote-definition' and
3349 ;; `org-export-get-footnote-number' provide easier access to
3350 ;; additional information relative to a footnote reference.
3352 (defun org-export-collect-footnote-definitions (data info)
3353 "Return an alist between footnote numbers, labels and definitions.
3355 DATA is the parse tree from which definitions are collected.
3356 INFO is the plist used as a communication channel.
3358 Definitions are sorted by order of references. They either
3359 appear as Org data or as a secondary string for inlined
3360 footnotes. Unreferenced definitions are ignored."
3361 (let* (num-alist
3362 collect-fn ; for byte-compiler.
3363 (collect-fn
3364 (function
3365 (lambda (data)
3366 ;; Collect footnote number, label and definition in DATA.
3367 (org-element-map data 'footnote-reference
3368 (lambda (fn)
3369 (when (org-export-footnote-first-reference-p fn info)
3370 (let ((def (org-export-get-footnote-definition fn info)))
3371 (push
3372 (list (org-export-get-footnote-number fn info)
3373 (org-element-property :label fn)
3374 def)
3375 num-alist)
3376 ;; Also search in definition for nested footnotes.
3377 (when (eq (org-element-property :type fn) 'standard)
3378 (funcall collect-fn def)))))
3379 ;; Don't enter footnote definitions since it will happen
3380 ;; when their first reference is found.
3381 info nil 'footnote-definition)))))
3382 (funcall collect-fn (plist-get info :parse-tree))
3383 (reverse num-alist)))
3385 (defun org-export-footnote-first-reference-p (footnote-reference info)
3386 "Non-nil when a footnote reference is the first one for its label.
3388 FOOTNOTE-REFERENCE is the footnote reference being considered.
3389 INFO is the plist used as a communication channel."
3390 (let ((label (org-element-property :label footnote-reference)))
3391 ;; Anonymous footnotes are always a first reference.
3392 (if (not label) t
3393 ;; Otherwise, return the first footnote with the same LABEL and
3394 ;; test if it is equal to FOOTNOTE-REFERENCE.
3395 (let* (search-refs ; for byte-compiler.
3396 (search-refs
3397 (function
3398 (lambda (data)
3399 (org-element-map data 'footnote-reference
3400 (lambda (fn)
3401 (cond
3402 ((string= (org-element-property :label fn) label)
3403 (throw 'exit fn))
3404 ;; If FN isn't inlined, be sure to traverse its
3405 ;; definition before resuming search. See
3406 ;; comments in `org-export-get-footnote-number'
3407 ;; for more information.
3408 ((eq (org-element-property :type fn) 'standard)
3409 (funcall search-refs
3410 (org-export-get-footnote-definition fn info)))))
3411 ;; Don't enter footnote definitions since it will
3412 ;; happen when their first reference is found.
3413 info 'first-match 'footnote-definition)))))
3414 (eq (catch 'exit (funcall search-refs (plist-get info :parse-tree)))
3415 footnote-reference)))))
3417 (defun org-export-get-footnote-definition (footnote-reference info)
3418 "Return definition of FOOTNOTE-REFERENCE as parsed data.
3419 INFO is the plist used as a communication channel. If no such
3420 definition can be found, return the \"DEFINITION NOT FOUND\"
3421 string."
3422 (let ((label (org-element-property :label footnote-reference)))
3423 (or (org-element-property :inline-definition footnote-reference)
3424 (cdr (assoc label (plist-get info :footnote-definition-alist)))
3425 "DEFINITION NOT FOUND.")))
3427 (defun org-export-get-footnote-number (footnote info)
3428 "Return number associated to a footnote.
3430 FOOTNOTE is either a footnote reference or a footnote definition.
3431 INFO is the plist used as a communication channel."
3432 (let* ((label (org-element-property :label footnote))
3433 seen-refs
3434 search-ref ; For byte-compiler.
3435 (search-ref
3436 (function
3437 (lambda (data)
3438 ;; Search footnote references through DATA, filling
3439 ;; SEEN-REFS along the way.
3440 (org-element-map data 'footnote-reference
3441 (lambda (fn)
3442 (let ((fn-lbl (org-element-property :label fn)))
3443 (cond
3444 ;; Anonymous footnote match: return number.
3445 ((and (not fn-lbl) (eq fn footnote))
3446 (throw 'exit (1+ (length seen-refs))))
3447 ;; Labels match: return number.
3448 ((and label (string= label fn-lbl))
3449 (throw 'exit (1+ (length seen-refs))))
3450 ;; Anonymous footnote: it's always a new one.
3451 ;; Also, be sure to return nil from the `cond' so
3452 ;; `first-match' doesn't get us out of the loop.
3453 ((not fn-lbl) (push 'inline seen-refs) nil)
3454 ;; Label not seen so far: add it so SEEN-REFS.
3456 ;; Also search for subsequent references in
3457 ;; footnote definition so numbering follows
3458 ;; reading logic. Note that we don't have to care
3459 ;; about inline definitions, since
3460 ;; `org-element-map' already traverses them at the
3461 ;; right time.
3463 ;; Once again, return nil to stay in the loop.
3464 ((not (member fn-lbl seen-refs))
3465 (push fn-lbl seen-refs)
3466 (funcall search-ref
3467 (org-export-get-footnote-definition fn info))
3468 nil))))
3469 ;; Don't enter footnote definitions since it will
3470 ;; happen when their first reference is found.
3471 info 'first-match 'footnote-definition)))))
3472 (catch 'exit (funcall search-ref (plist-get info :parse-tree)))))
3475 ;;;; For Headlines
3477 ;; `org-export-get-relative-level' is a shortcut to get headline
3478 ;; level, relatively to the lower headline level in the parsed tree.
3480 ;; `org-export-get-headline-number' returns the section number of an
3481 ;; headline, while `org-export-number-to-roman' allows to convert it
3482 ;; to roman numbers.
3484 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
3485 ;; `org-export-last-sibling-p' are three useful predicates when it
3486 ;; comes to fulfill the `:headline-levels' property.
3488 ;; `org-export-get-tags', `org-export-get-category' and
3489 ;; `org-export-get-node-property' extract useful information from an
3490 ;; headline or a parent headline. They all handle inheritance.
3492 ;; `org-export-get-alt-title' tries to retrieve an alternative title,
3493 ;; as a secondary string, suitable for table of contents. It falls
3494 ;; back onto default title.
3496 (defun org-export-get-relative-level (headline info)
3497 "Return HEADLINE relative level within current parsed tree.
3498 INFO is a plist holding contextual information."
3499 (+ (org-element-property :level headline)
3500 (or (plist-get info :headline-offset) 0)))
3502 (defun org-export-low-level-p (headline info)
3503 "Non-nil when HEADLINE is considered as low level.
3505 INFO is a plist used as a communication channel.
3507 A low level headlines has a relative level greater than
3508 `:headline-levels' property value.
3510 Return value is the difference between HEADLINE relative level
3511 and the last level being considered as high enough, or nil."
3512 (let ((limit (plist-get info :headline-levels)))
3513 (when (wholenump limit)
3514 (let ((level (org-export-get-relative-level headline info)))
3515 (and (> level limit) (- level limit))))))
3517 (defun org-export-get-headline-number (headline info)
3518 "Return HEADLINE numbering as a list of numbers.
3519 INFO is a plist holding contextual information."
3520 (cdr (assoc headline (plist-get info :headline-numbering))))
3522 (defun org-export-numbered-headline-p (headline info)
3523 "Return a non-nil value if HEADLINE element should be numbered.
3524 INFO is a plist used as a communication channel."
3525 (let ((sec-num (plist-get info :section-numbers))
3526 (level (org-export-get-relative-level headline info)))
3527 (if (wholenump sec-num) (<= level sec-num) sec-num)))
3529 (defun org-export-number-to-roman (n)
3530 "Convert integer N into a roman numeral."
3531 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
3532 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
3533 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
3534 ( 1 . "I")))
3535 (res ""))
3536 (if (<= n 0)
3537 (number-to-string n)
3538 (while roman
3539 (if (>= n (caar roman))
3540 (setq n (- n (caar roman))
3541 res (concat res (cdar roman)))
3542 (pop roman)))
3543 res)))
3545 (defun org-export-get-tags (element info &optional tags inherited)
3546 "Return list of tags associated to ELEMENT.
3548 ELEMENT has either an `headline' or an `inlinetask' type. INFO
3549 is a plist used as a communication channel.
3551 Select tags (see `org-export-select-tags') and exclude tags (see
3552 `org-export-exclude-tags') are removed from the list.
3554 When non-nil, optional argument TAGS should be a list of strings.
3555 Any tag belonging to this list will also be removed.
3557 When optional argument INHERITED is non-nil, tags can also be
3558 inherited from parent headlines and FILETAGS keywords."
3559 (org-remove-if
3560 (lambda (tag) (or (member tag (plist-get info :select-tags))
3561 (member tag (plist-get info :exclude-tags))
3562 (member tag tags)))
3563 (if (not inherited) (org-element-property :tags element)
3564 ;; Build complete list of inherited tags.
3565 (let ((current-tag-list (org-element-property :tags element)))
3566 (mapc
3567 (lambda (parent)
3568 (mapc
3569 (lambda (tag)
3570 (when (and (memq (org-element-type parent) '(headline inlinetask))
3571 (not (member tag current-tag-list)))
3572 (push tag current-tag-list)))
3573 (org-element-property :tags parent)))
3574 (org-export-get-genealogy element))
3575 ;; Add FILETAGS keywords and return results.
3576 (org-uniquify (append (plist-get info :filetags) current-tag-list))))))
3578 (defun org-export-get-node-property (property blob &optional inherited)
3579 "Return node PROPERTY value for BLOB.
3581 PROPERTY is an upcase symbol (i.e. `:COOKIE_DATA'). BLOB is an
3582 element or object.
3584 If optional argument INHERITED is non-nil, the value can be
3585 inherited from a parent headline.
3587 Return value is a string or nil."
3588 (let ((headline (if (eq (org-element-type blob) 'headline) blob
3589 (org-export-get-parent-headline blob))))
3590 (if (not inherited) (org-element-property property blob)
3591 (let ((parent headline) value)
3592 (catch 'found
3593 (while parent
3594 (when (plist-member (nth 1 parent) property)
3595 (throw 'found (org-element-property property parent)))
3596 (setq parent (org-element-property :parent parent))))))))
3598 (defun org-export-get-category (blob info)
3599 "Return category for element or object BLOB.
3601 INFO is a plist used as a communication channel.
3603 CATEGORY is automatically inherited from a parent headline, from
3604 #+CATEGORY: keyword or created out of original file name. If all
3605 fail, the fall-back value is \"???\"."
3606 (or (let ((headline (if (eq (org-element-type blob) 'headline) blob
3607 (org-export-get-parent-headline blob))))
3608 ;; Almost like `org-export-node-property', but we cannot trust
3609 ;; `plist-member' as every headline has a `:CATEGORY'
3610 ;; property, would it be nil or equal to "???" (which has the
3611 ;; same meaning).
3612 (let ((parent headline) value)
3613 (catch 'found
3614 (while parent
3615 (let ((category (org-element-property :CATEGORY parent)))
3616 (and category (not (equal "???" category))
3617 (throw 'found category)))
3618 (setq parent (org-element-property :parent parent))))))
3619 (org-element-map (plist-get info :parse-tree) 'keyword
3620 (lambda (kwd)
3621 (when (equal (org-element-property :key kwd) "CATEGORY")
3622 (org-element-property :value kwd)))
3623 info 'first-match)
3624 (let ((file (plist-get info :input-file)))
3625 (and file (file-name-sans-extension (file-name-nondirectory file))))
3626 "???"))
3628 (defun org-export-get-alt-title (headline info)
3629 "Return alternative title for HEADLINE, as a secondary string.
3630 INFO is a plist used as a communication channel. If no optional
3631 title is defined, fall-back to the regular title."
3632 (or (org-element-property :alt-title headline)
3633 (org-element-property :title headline)))
3635 (defun org-export-first-sibling-p (headline info)
3636 "Non-nil when HEADLINE is the first sibling in its sub-tree.
3637 INFO is a plist used as a communication channel."
3638 (not (eq (org-element-type (org-export-get-previous-element headline info))
3639 'headline)))
3641 (defun org-export-last-sibling-p (headline info)
3642 "Non-nil when HEADLINE is the last sibling in its sub-tree.
3643 INFO is a plist used as a communication channel."
3644 (not (org-export-get-next-element headline info)))
3647 ;;;; For Links
3649 ;; `org-export-solidify-link-text' turns a string into a safer version
3650 ;; for links, replacing most non-standard characters with hyphens.
3652 ;; `org-export-get-coderef-format' returns an appropriate format
3653 ;; string for coderefs.
3655 ;; `org-export-inline-image-p' returns a non-nil value when the link
3656 ;; provided should be considered as an inline image.
3658 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
3659 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
3660 ;; returns an appropriate unique identifier when found, or nil.
3662 ;; `org-export-resolve-id-link' returns the first headline with
3663 ;; specified id or custom-id in parse tree, the path to the external
3664 ;; file with the id or nil when neither was found.
3666 ;; `org-export-resolve-coderef' associates a reference to a line
3667 ;; number in the element it belongs, or returns the reference itself
3668 ;; when the element isn't numbered.
3670 (defun org-export-solidify-link-text (s)
3671 "Take link text S and make a safe target out of it."
3672 (save-match-data
3673 (mapconcat 'identity (org-split-string s "[^a-zA-Z0-9_.-:]+") "-")))
3675 (defun org-export-get-coderef-format (path desc)
3676 "Return format string for code reference link.
3677 PATH is the link path. DESC is its description."
3678 (save-match-data
3679 (cond ((not desc) "%s")
3680 ((string-match (regexp-quote (concat "(" path ")")) desc)
3681 (replace-match "%s" t t desc))
3682 (t desc))))
3684 (defun org-export-inline-image-p (link &optional rules)
3685 "Non-nil if LINK object points to an inline image.
3687 Optional argument is a set of RULES defining inline images. It
3688 is an alist where associations have the following shape:
3690 \(TYPE . REGEXP)
3692 Applying a rule means apply REGEXP against LINK's path when its
3693 type is TYPE. The function will return a non-nil value if any of
3694 the provided rules is non-nil. The default rule is
3695 `org-export-default-inline-image-rule'.
3697 This only applies to links without a description."
3698 (and (not (org-element-contents link))
3699 (let ((case-fold-search t)
3700 (rules (or rules org-export-default-inline-image-rule)))
3701 (catch 'exit
3702 (mapc
3703 (lambda (rule)
3704 (and (string= (org-element-property :type link) (car rule))
3705 (string-match (cdr rule)
3706 (org-element-property :path link))
3707 (throw 'exit t)))
3708 rules)
3709 ;; Return nil if no rule matched.
3710 nil))))
3712 (defun org-export-resolve-coderef (ref info)
3713 "Resolve a code reference REF.
3715 INFO is a plist used as a communication channel.
3717 Return associated line number in source code, or REF itself,
3718 depending on src-block or example element's switches."
3719 (org-element-map (plist-get info :parse-tree) '(example-block src-block)
3720 (lambda (el)
3721 (with-temp-buffer
3722 (insert (org-trim (org-element-property :value el)))
3723 (let* ((label-fmt (regexp-quote
3724 (or (org-element-property :label-fmt el)
3725 org-coderef-label-format)))
3726 (ref-re
3727 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
3728 (replace-regexp-in-string "%s" ref label-fmt nil t))))
3729 ;; Element containing REF is found. Resolve it to either
3730 ;; a label or a line number, as needed.
3731 (when (re-search-backward ref-re nil t)
3732 (cond
3733 ((org-element-property :use-labels el) ref)
3734 ((eq (org-element-property :number-lines el) 'continued)
3735 (+ (org-export-get-loc el info) (line-number-at-pos)))
3736 (t (line-number-at-pos)))))))
3737 info 'first-match))
3739 (defun org-export-resolve-fuzzy-link (link info)
3740 "Return LINK destination.
3742 INFO is a plist holding contextual information.
3744 Return value can be an object, an element, or nil:
3746 - If LINK path matches a target object (i.e. <<path>>) or
3747 element (i.e. \"#+TARGET: path\"), return it.
3749 - If LINK path exactly matches the name affiliated keyword
3750 \(i.e. #+NAME: path) of an element, return that element.
3752 - If LINK path exactly matches any headline name, return that
3753 element. If more than one headline share that name, priority
3754 will be given to the one with the closest common ancestor, if
3755 any, or the first one in the parse tree otherwise.
3757 - Otherwise, return nil.
3759 Assume LINK type is \"fuzzy\". White spaces are not
3760 significant."
3761 (let* ((raw-path (org-element-property :path link))
3762 (match-title-p (eq (aref raw-path 0) ?*))
3763 ;; Split PATH at white spaces so matches are space
3764 ;; insensitive.
3765 (path (org-split-string
3766 (if match-title-p (substring raw-path 1) raw-path))))
3767 (cond
3768 ;; First try to find a matching "<<path>>" unless user specified
3769 ;; he was looking for a headline (path starts with a *
3770 ;; character).
3771 ((and (not match-title-p)
3772 (org-element-map (plist-get info :parse-tree) '(keyword target)
3773 (lambda (blob)
3774 (and (or (eq (org-element-type blob) 'target)
3775 (equal (org-element-property :key blob) "TARGET"))
3776 (equal (org-split-string (org-element-property :value blob))
3777 path)
3778 blob))
3779 info t)))
3780 ;; Then try to find an element with a matching "#+NAME: path"
3781 ;; affiliated keyword.
3782 ((and (not match-title-p)
3783 (org-element-map (plist-get info :parse-tree)
3784 org-element-all-elements
3785 (lambda (el)
3786 (let ((name (org-element-property :name el)))
3787 (when (and name (equal (org-split-string name) path)) el)))
3788 info 'first-match)))
3789 ;; Last case: link either points to a headline or to
3790 ;; nothingness. Try to find the source, with priority given to
3791 ;; headlines with the closest common ancestor. If such candidate
3792 ;; is found, return it, otherwise return nil.
3794 (let ((find-headline
3795 (function
3796 ;; Return first headline whose `:raw-value' property is
3797 ;; NAME in parse tree DATA, or nil. Statistics cookies
3798 ;; are ignored.
3799 (lambda (name data)
3800 (org-element-map data 'headline
3801 (lambda (headline)
3802 (when (equal (org-split-string
3803 (replace-regexp-in-string
3804 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
3805 (org-element-property :raw-value headline)))
3806 name)
3807 headline))
3808 info 'first-match)))))
3809 ;; Search among headlines sharing an ancestor with link, from
3810 ;; closest to farthest.
3811 (or (catch 'exit
3812 (mapc
3813 (lambda (parent)
3814 (when (eq (org-element-type parent) 'headline)
3815 (let ((foundp (funcall find-headline path parent)))
3816 (when foundp (throw 'exit foundp)))))
3817 (org-export-get-genealogy link)) nil)
3818 ;; No match with a common ancestor: try full parse-tree.
3819 (funcall find-headline path (plist-get info :parse-tree))))))))
3821 (defun org-export-resolve-id-link (link info)
3822 "Return headline referenced as LINK destination.
3824 INFO is a plist used as a communication channel.
3826 Return value can be the headline element matched in current parse
3827 tree, a file name or nil. Assume LINK type is either \"id\" or
3828 \"custom-id\"."
3829 (let ((id (org-element-property :path link)))
3830 ;; First check if id is within the current parse tree.
3831 (or (org-element-map (plist-get info :parse-tree) 'headline
3832 (lambda (headline)
3833 (when (or (string= (org-element-property :ID headline) id)
3834 (string= (org-element-property :CUSTOM_ID headline) id))
3835 headline))
3836 info 'first-match)
3837 ;; Otherwise, look for external files.
3838 (cdr (assoc id (plist-get info :id-alist))))))
3840 (defun org-export-resolve-radio-link (link info)
3841 "Return radio-target object referenced as LINK destination.
3843 INFO is a plist used as a communication channel.
3845 Return value can be a radio-target object or nil. Assume LINK
3846 has type \"radio\"."
3847 (let ((path (org-element-property :path link)))
3848 (org-element-map (plist-get info :parse-tree) 'radio-target
3849 (lambda (radio)
3850 (and (compare-strings
3851 (org-element-property :value radio) 0 nil path 0 nil t)
3852 radio))
3853 info 'first-match)))
3856 ;;;; For References
3858 ;; `org-export-get-ordinal' associates a sequence number to any object
3859 ;; or element.
3861 (defun org-export-get-ordinal (element info &optional types predicate)
3862 "Return ordinal number of an element or object.
3864 ELEMENT is the element or object considered. INFO is the plist
3865 used as a communication channel.
3867 Optional argument TYPES, when non-nil, is a list of element or
3868 object types, as symbols, that should also be counted in.
3869 Otherwise, only provided element's type is considered.
3871 Optional argument PREDICATE is a function returning a non-nil
3872 value if the current element or object should be counted in. It
3873 accepts two arguments: the element or object being considered and
3874 the plist used as a communication channel. This allows to count
3875 only a certain type of objects (i.e. inline images).
3877 Return value is a list of numbers if ELEMENT is a headline or an
3878 item. It is nil for keywords. It represents the footnote number
3879 for footnote definitions and footnote references. If ELEMENT is
3880 a target, return the same value as if ELEMENT was the closest
3881 table, item or headline containing the target. In any other
3882 case, return the sequence number of ELEMENT among elements or
3883 objects of the same type."
3884 ;; A target keyword, representing an invisible target, never has
3885 ;; a sequence number.
3886 (unless (eq (org-element-type element) 'keyword)
3887 ;; Ordinal of a target object refer to the ordinal of the closest
3888 ;; table, item, or headline containing the object.
3889 (when (eq (org-element-type element) 'target)
3890 (setq element
3891 (loop for parent in (org-export-get-genealogy element)
3892 when
3893 (memq
3894 (org-element-type parent)
3895 '(footnote-definition footnote-reference headline item
3896 table))
3897 return parent)))
3898 (case (org-element-type element)
3899 ;; Special case 1: A headline returns its number as a list.
3900 (headline (org-export-get-headline-number element info))
3901 ;; Special case 2: An item returns its number as a list.
3902 (item (let ((struct (org-element-property :structure element)))
3903 (org-list-get-item-number
3904 (org-element-property :begin element)
3905 struct
3906 (org-list-prevs-alist struct)
3907 (org-list-parents-alist struct))))
3908 ((footnote-definition footnote-reference)
3909 (org-export-get-footnote-number element info))
3910 (otherwise
3911 (let ((counter 0))
3912 ;; Increment counter until ELEMENT is found again.
3913 (org-element-map (plist-get info :parse-tree)
3914 (or types (org-element-type element))
3915 (lambda (el)
3916 (cond
3917 ((eq element el) (1+ counter))
3918 ((not predicate) (incf counter) nil)
3919 ((funcall predicate el info) (incf counter) nil)))
3920 info 'first-match))))))
3923 ;;;; For Src-Blocks
3925 ;; `org-export-get-loc' counts number of code lines accumulated in
3926 ;; src-block or example-block elements with a "+n" switch until
3927 ;; a given element, excluded. Note: "-n" switches reset that count.
3929 ;; `org-export-unravel-code' extracts source code (along with a code
3930 ;; references alist) from an `element-block' or `src-block' type
3931 ;; element.
3933 ;; `org-export-format-code' applies a formatting function to each line
3934 ;; of code, providing relative line number and code reference when
3935 ;; appropriate. Since it doesn't access the original element from
3936 ;; which the source code is coming, it expects from the code calling
3937 ;; it to know if lines should be numbered and if code references
3938 ;; should appear.
3940 ;; Eventually, `org-export-format-code-default' is a higher-level
3941 ;; function (it makes use of the two previous functions) which handles
3942 ;; line numbering and code references inclusion, and returns source
3943 ;; code in a format suitable for plain text or verbatim output.
3945 (defun org-export-get-loc (element info)
3946 "Return accumulated lines of code up to ELEMENT.
3948 INFO is the plist used as a communication channel.
3950 ELEMENT is excluded from count."
3951 (let ((loc 0))
3952 (org-element-map (plist-get info :parse-tree)
3953 `(src-block example-block ,(org-element-type element))
3954 (lambda (el)
3955 (cond
3956 ;; ELEMENT is reached: Quit the loop.
3957 ((eq el element))
3958 ;; Only count lines from src-block and example-block elements
3959 ;; with a "+n" or "-n" switch. A "-n" switch resets counter.
3960 ((not (memq (org-element-type el) '(src-block example-block))) nil)
3961 ((let ((linums (org-element-property :number-lines el)))
3962 (when linums
3963 ;; Accumulate locs or reset them.
3964 (let ((lines (org-count-lines
3965 (org-trim (org-element-property :value el)))))
3966 (setq loc (if (eq linums 'new) lines (+ loc lines))))))
3967 ;; Return nil to stay in the loop.
3968 nil)))
3969 info 'first-match)
3970 ;; Return value.
3971 loc))
3973 (defun org-export-unravel-code (element)
3974 "Clean source code and extract references out of it.
3976 ELEMENT has either a `src-block' an `example-block' type.
3978 Return a cons cell whose CAR is the source code, cleaned from any
3979 reference and protective comma and CDR is an alist between
3980 relative line number (integer) and name of code reference on that
3981 line (string)."
3982 (let* ((line 0) refs
3983 ;; Get code and clean it. Remove blank lines at its
3984 ;; beginning and end.
3985 (code (let ((c (replace-regexp-in-string
3986 "\\`\\([ \t]*\n\\)+" ""
3987 (replace-regexp-in-string
3988 "\\([ \t]*\n\\)*[ \t]*\\'" "\n"
3989 (org-element-property :value element)))))
3990 ;; If appropriate, remove global indentation.
3991 (if (or org-src-preserve-indentation
3992 (org-element-property :preserve-indent element))
3994 (org-remove-indentation c))))
3995 ;; Get format used for references.
3996 (label-fmt (regexp-quote
3997 (or (org-element-property :label-fmt element)
3998 org-coderef-label-format)))
3999 ;; Build a regexp matching a loc with a reference.
4000 (with-ref-re
4001 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)[ \t]*\\)$"
4002 (replace-regexp-in-string
4003 "%s" "\\([-a-zA-Z0-9_ ]+\\)" label-fmt nil t))))
4004 ;; Return value.
4005 (cons
4006 ;; Code with references removed.
4007 (org-element-normalize-string
4008 (mapconcat
4009 (lambda (loc)
4010 (incf line)
4011 (if (not (string-match with-ref-re loc)) loc
4012 ;; Ref line: remove ref, and signal its position in REFS.
4013 (push (cons line (match-string 3 loc)) refs)
4014 (replace-match "" nil nil loc 1)))
4015 (org-split-string code "\n") "\n"))
4016 ;; Reference alist.
4017 refs)))
4019 (defun org-export-format-code (code fun &optional num-lines ref-alist)
4020 "Format CODE by applying FUN line-wise and return it.
4022 CODE is a string representing the code to format. FUN is
4023 a function. It must accept three arguments: a line of
4024 code (string), the current line number (integer) or nil and the
4025 reference associated to the current line (string) or nil.
4027 Optional argument NUM-LINES can be an integer representing the
4028 number of code lines accumulated until the current code. Line
4029 numbers passed to FUN will take it into account. If it is nil,
4030 FUN's second argument will always be nil. This number can be
4031 obtained with `org-export-get-loc' function.
4033 Optional argument REF-ALIST can be an alist between relative line
4034 number (i.e. ignoring NUM-LINES) and the name of the code
4035 reference on it. If it is nil, FUN's third argument will always
4036 be nil. It can be obtained through the use of
4037 `org-export-unravel-code' function."
4038 (let ((--locs (org-split-string code "\n"))
4039 (--line 0))
4040 (org-element-normalize-string
4041 (mapconcat
4042 (lambda (--loc)
4043 (incf --line)
4044 (let ((--ref (cdr (assq --line ref-alist))))
4045 (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
4046 --locs "\n"))))
4048 (defun org-export-format-code-default (element info)
4049 "Return source code from ELEMENT, formatted in a standard way.
4051 ELEMENT is either a `src-block' or `example-block' element. INFO
4052 is a plist used as a communication channel.
4054 This function takes care of line numbering and code references
4055 inclusion. Line numbers, when applicable, appear at the
4056 beginning of the line, separated from the code by two white
4057 spaces. Code references, on the other hand, appear flushed to
4058 the right, separated by six white spaces from the widest line of
4059 code."
4060 ;; Extract code and references.
4061 (let* ((code-info (org-export-unravel-code element))
4062 (code (car code-info))
4063 (code-lines (org-split-string code "\n")))
4064 (if (null code-lines) ""
4065 (let* ((refs (and (org-element-property :retain-labels element)
4066 (cdr code-info)))
4067 ;; Handle line numbering.
4068 (num-start (case (org-element-property :number-lines element)
4069 (continued (org-export-get-loc element info))
4070 (new 0)))
4071 (num-fmt
4072 (and num-start
4073 (format "%%%ds "
4074 (length (number-to-string
4075 (+ (length code-lines) num-start))))))
4076 ;; Prepare references display, if required. Any reference
4077 ;; should start six columns after the widest line of code,
4078 ;; wrapped with parenthesis.
4079 (max-width
4080 (+ (apply 'max (mapcar 'length code-lines))
4081 (if (not num-start) 0 (length (format num-fmt num-start))))))
4082 (org-export-format-code
4083 code
4084 (lambda (loc line-num ref)
4085 (let ((number-str (and num-fmt (format num-fmt line-num))))
4086 (concat
4087 number-str
4089 (and ref
4090 (concat (make-string
4091 (- (+ 6 max-width)
4092 (+ (length loc) (length number-str))) ? )
4093 (format "(%s)" ref))))))
4094 num-start refs)))))
4097 ;;;; For Tables
4099 ;; `org-export-table-has-special-column-p' and and
4100 ;; `org-export-table-row-is-special-p' are predicates used to look for
4101 ;; meta-information about the table structure.
4103 ;; `org-table-has-header-p' tells when the rows before the first rule
4104 ;; should be considered as table's header.
4106 ;; `org-export-table-cell-width', `org-export-table-cell-alignment'
4107 ;; and `org-export-table-cell-borders' extract information from
4108 ;; a table-cell element.
4110 ;; `org-export-table-dimensions' gives the number on rows and columns
4111 ;; in the table, ignoring horizontal rules and special columns.
4112 ;; `org-export-table-cell-address', given a table-cell object, returns
4113 ;; the absolute address of a cell. On the other hand,
4114 ;; `org-export-get-table-cell-at' does the contrary.
4116 ;; `org-export-table-cell-starts-colgroup-p',
4117 ;; `org-export-table-cell-ends-colgroup-p',
4118 ;; `org-export-table-row-starts-rowgroup-p',
4119 ;; `org-export-table-row-ends-rowgroup-p',
4120 ;; `org-export-table-row-starts-header-p' and
4121 ;; `org-export-table-row-ends-header-p' indicate position of current
4122 ;; row or cell within the table.
4124 (defun org-export-table-has-special-column-p (table)
4125 "Non-nil when TABLE has a special column.
4126 All special columns will be ignored during export."
4127 ;; The table has a special column when every first cell of every row
4128 ;; has an empty value or contains a symbol among "/", "#", "!", "$",
4129 ;; "*" "_" and "^". Though, do not consider a first row containing
4130 ;; only empty cells as special.
4131 (let ((special-column-p 'empty))
4132 (catch 'exit
4133 (mapc
4134 (lambda (row)
4135 (when (eq (org-element-property :type row) 'standard)
4136 (let ((value (org-element-contents
4137 (car (org-element-contents row)))))
4138 (cond ((member value '(("/") ("#") ("!") ("$") ("*") ("_") ("^")))
4139 (setq special-column-p 'special))
4140 ((not value))
4141 (t (throw 'exit nil))))))
4142 (org-element-contents table))
4143 (eq special-column-p 'special))))
4145 (defun org-export-table-has-header-p (table info)
4146 "Non-nil when TABLE has an header.
4148 INFO is a plist used as a communication channel.
4150 A table has an header when it contains at least two row groups."
4151 (let ((rowgroup 1) row-flag)
4152 (org-element-map table 'table-row
4153 (lambda (row)
4154 (cond
4155 ((> rowgroup 1) t)
4156 ((and row-flag (eq (org-element-property :type row) 'rule))
4157 (incf rowgroup) (setq row-flag nil))
4158 ((and (not row-flag) (eq (org-element-property :type row) 'standard))
4159 (setq row-flag t) nil)))
4160 info)))
4162 (defun org-export-table-row-is-special-p (table-row info)
4163 "Non-nil if TABLE-ROW is considered special.
4165 INFO is a plist used as the communication channel.
4167 All special rows will be ignored during export."
4168 (when (eq (org-element-property :type table-row) 'standard)
4169 (let ((first-cell (org-element-contents
4170 (car (org-element-contents table-row)))))
4171 ;; A row is special either when...
4173 ;; ... it starts with a field only containing "/",
4174 (equal first-cell '("/"))
4175 ;; ... the table contains a special column and the row start
4176 ;; with a marking character among, "^", "_", "$" or "!",
4177 (and (org-export-table-has-special-column-p
4178 (org-export-get-parent table-row))
4179 (member first-cell '(("^") ("_") ("$") ("!"))))
4180 ;; ... it contains only alignment cookies and empty cells.
4181 (let ((special-row-p 'empty))
4182 (catch 'exit
4183 (mapc
4184 (lambda (cell)
4185 (let ((value (org-element-contents cell)))
4186 ;; Since VALUE is a secondary string, the following
4187 ;; checks avoid expanding it with `org-export-data'.
4188 (cond ((not value))
4189 ((and (not (cdr value))
4190 (stringp (car value))
4191 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'"
4192 (car value)))
4193 (setq special-row-p 'cookie))
4194 (t (throw 'exit nil)))))
4195 (org-element-contents table-row))
4196 (eq special-row-p 'cookie)))))))
4198 (defun org-export-table-row-group (table-row info)
4199 "Return TABLE-ROW's group.
4201 INFO is a plist used as the communication channel.
4203 Return value is the group number, as an integer, or nil special
4204 rows and table rules. Group 1 is also table's header."
4205 (unless (or (eq (org-element-property :type table-row) 'rule)
4206 (org-export-table-row-is-special-p table-row info))
4207 (let ((group 0) row-flag)
4208 (catch 'found
4209 (mapc
4210 (lambda (row)
4211 (cond
4212 ((and (eq (org-element-property :type row) 'standard)
4213 (not (org-export-table-row-is-special-p row info)))
4214 (unless row-flag (incf group) (setq row-flag t)))
4215 ((eq (org-element-property :type row) 'rule)
4216 (setq row-flag nil)))
4217 (when (eq table-row row) (throw 'found group)))
4218 (org-element-contents (org-export-get-parent table-row)))))))
4220 (defun org-export-table-cell-width (table-cell info)
4221 "Return TABLE-CELL contents width.
4223 INFO is a plist used as the communication channel.
4225 Return value is the width given by the last width cookie in the
4226 same column as TABLE-CELL, or nil."
4227 (let* ((row (org-export-get-parent table-cell))
4228 (column (let ((cells (org-element-contents row)))
4229 (- (length cells) (length (memq table-cell cells)))))
4230 (table (org-export-get-parent-table table-cell))
4231 cookie-width)
4232 (mapc
4233 (lambda (row)
4234 (cond
4235 ;; In a special row, try to find a width cookie at COLUMN.
4236 ((org-export-table-row-is-special-p row info)
4237 (let ((value (org-element-contents
4238 (elt (org-element-contents row) column))))
4239 ;; The following checks avoid expanding unnecessarily the
4240 ;; cell with `org-export-data'
4241 (when (and value
4242 (not (cdr value))
4243 (stringp (car value))
4244 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'" (car value))
4245 (match-string 1 (car value)))
4246 (setq cookie-width
4247 (string-to-number (match-string 1 (car value)))))))
4248 ;; Ignore table rules.
4249 ((eq (org-element-property :type row) 'rule))))
4250 (org-element-contents table))
4251 ;; Return value.
4252 cookie-width))
4254 (defun org-export-table-cell-alignment (table-cell info)
4255 "Return TABLE-CELL contents alignment.
4257 INFO is a plist used as the communication channel.
4259 Return alignment as specified by the last alignment cookie in the
4260 same column as TABLE-CELL. If no such cookie is found, a default
4261 alignment value will be deduced from fraction of numbers in the
4262 column (see `org-table-number-fraction' for more information).
4263 Possible values are `left', `right' and `center'."
4264 (let* ((row (org-export-get-parent table-cell))
4265 (column (let ((cells (org-element-contents row)))
4266 (- (length cells) (length (memq table-cell cells)))))
4267 (table (org-export-get-parent-table table-cell))
4268 (number-cells 0)
4269 (total-cells 0)
4270 cookie-align
4271 previous-cell-number-p)
4272 (mapc
4273 (lambda (row)
4274 (cond
4275 ;; In a special row, try to find an alignment cookie at
4276 ;; COLUMN.
4277 ((org-export-table-row-is-special-p row info)
4278 (let ((value (org-element-contents
4279 (elt (org-element-contents row) column))))
4280 ;; Since VALUE is a secondary string, the following checks
4281 ;; avoid useless expansion through `org-export-data'.
4282 (when (and value
4283 (not (cdr value))
4284 (stringp (car value))
4285 (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'"
4286 (car value))
4287 (match-string 1 (car value)))
4288 (setq cookie-align (match-string 1 (car value))))))
4289 ;; Ignore table rules.
4290 ((eq (org-element-property :type row) 'rule))
4291 ;; In a standard row, check if cell's contents are expressing
4292 ;; some kind of number. Increase NUMBER-CELLS accordingly.
4293 ;; Though, don't bother if an alignment cookie has already
4294 ;; defined cell's alignment.
4295 ((not cookie-align)
4296 (let ((value (org-export-data
4297 (org-element-contents
4298 (elt (org-element-contents row) column))
4299 info)))
4300 (incf total-cells)
4301 ;; Treat an empty cell as a number if it follows a number
4302 (if (not (or (string-match org-table-number-regexp value)
4303 (and (string= value "") previous-cell-number-p)))
4304 (setq previous-cell-number-p nil)
4305 (setq previous-cell-number-p t)
4306 (incf number-cells))))))
4307 (org-element-contents table))
4308 ;; Return value. Alignment specified by cookies has precedence
4309 ;; over alignment deduced from cells contents.
4310 (cond ((equal cookie-align "l") 'left)
4311 ((equal cookie-align "r") 'right)
4312 ((equal cookie-align "c") 'center)
4313 ((>= (/ (float number-cells) total-cells) org-table-number-fraction)
4314 'right)
4315 (t 'left))))
4317 (defun org-export-table-cell-borders (table-cell info)
4318 "Return TABLE-CELL borders.
4320 INFO is a plist used as a communication channel.
4322 Return value is a list of symbols, or nil. Possible values are:
4323 `top', `bottom', `above', `below', `left' and `right'. Note:
4324 `top' (resp. `bottom') only happen for a cell in the first
4325 row (resp. last row) of the table, ignoring table rules, if any.
4327 Returned borders ignore special rows."
4328 (let* ((row (org-export-get-parent table-cell))
4329 (table (org-export-get-parent-table table-cell))
4330 borders)
4331 ;; Top/above border? TABLE-CELL has a border above when a rule
4332 ;; used to demarcate row groups can be found above. Hence,
4333 ;; finding a rule isn't sufficient to push `above' in BORDERS:
4334 ;; another regular row has to be found above that rule.
4335 (let (rule-flag)
4336 (catch 'exit
4337 (mapc (lambda (row)
4338 (cond ((eq (org-element-property :type row) 'rule)
4339 (setq rule-flag t))
4340 ((not (org-export-table-row-is-special-p row info))
4341 (if rule-flag (throw 'exit (push 'above borders))
4342 (throw 'exit nil)))))
4343 ;; Look at every row before the current one.
4344 (cdr (memq row (reverse (org-element-contents table)))))
4345 ;; No rule above, or rule found starts the table (ignoring any
4346 ;; special row): TABLE-CELL is at the top of the table.
4347 (when rule-flag (push 'above borders))
4348 (push 'top borders)))
4349 ;; Bottom/below border? TABLE-CELL has a border below when next
4350 ;; non-regular row below is a rule.
4351 (let (rule-flag)
4352 (catch 'exit
4353 (mapc (lambda (row)
4354 (cond ((eq (org-element-property :type row) 'rule)
4355 (setq rule-flag t))
4356 ((not (org-export-table-row-is-special-p row info))
4357 (if rule-flag (throw 'exit (push 'below borders))
4358 (throw 'exit nil)))))
4359 ;; Look at every row after the current one.
4360 (cdr (memq row (org-element-contents table))))
4361 ;; No rule below, or rule found ends the table (modulo some
4362 ;; special row): TABLE-CELL is at the bottom of the table.
4363 (when rule-flag (push 'below borders))
4364 (push 'bottom borders)))
4365 ;; Right/left borders? They can only be specified by column
4366 ;; groups. Column groups are defined in a row starting with "/".
4367 ;; Also a column groups row only contains "<", "<>", ">" or blank
4368 ;; cells.
4369 (catch 'exit
4370 (let ((column (let ((cells (org-element-contents row)))
4371 (- (length cells) (length (memq table-cell cells))))))
4372 (mapc
4373 (lambda (row)
4374 (unless (eq (org-element-property :type row) 'rule)
4375 (when (equal (org-element-contents
4376 (car (org-element-contents row)))
4377 '("/"))
4378 (let ((column-groups
4379 (mapcar
4380 (lambda (cell)
4381 (let ((value (org-element-contents cell)))
4382 (when (member value '(("<") ("<>") (">") nil))
4383 (car value))))
4384 (org-element-contents row))))
4385 ;; There's a left border when previous cell, if
4386 ;; any, ends a group, or current one starts one.
4387 (when (or (and (not (zerop column))
4388 (member (elt column-groups (1- column))
4389 '(">" "<>")))
4390 (member (elt column-groups column) '("<" "<>")))
4391 (push 'left borders))
4392 ;; There's a right border when next cell, if any,
4393 ;; starts a group, or current one ends one.
4394 (when (or (and (/= (1+ column) (length column-groups))
4395 (member (elt column-groups (1+ column))
4396 '("<" "<>")))
4397 (member (elt column-groups column) '(">" "<>")))
4398 (push 'right borders))
4399 (throw 'exit nil)))))
4400 ;; Table rows are read in reverse order so last column groups
4401 ;; row has precedence over any previous one.
4402 (reverse (org-element-contents table)))))
4403 ;; Return value.
4404 borders))
4406 (defun org-export-table-cell-starts-colgroup-p (table-cell info)
4407 "Non-nil when TABLE-CELL is at the beginning of a row group.
4408 INFO is a plist used as a communication channel."
4409 ;; A cell starts a column group either when it is at the beginning
4410 ;; of a row (or after the special column, if any) or when it has
4411 ;; a left border.
4412 (or (eq (org-element-map (org-export-get-parent table-cell) 'table-cell
4413 'identity info 'first-match)
4414 table-cell)
4415 (memq 'left (org-export-table-cell-borders table-cell info))))
4417 (defun org-export-table-cell-ends-colgroup-p (table-cell info)
4418 "Non-nil when TABLE-CELL is at the end of a row group.
4419 INFO is a plist used as a communication channel."
4420 ;; A cell ends a column group either when it is at the end of a row
4421 ;; or when it has a right border.
4422 (or (eq (car (last (org-element-contents
4423 (org-export-get-parent table-cell))))
4424 table-cell)
4425 (memq 'right (org-export-table-cell-borders table-cell info))))
4427 (defun org-export-table-row-starts-rowgroup-p (table-row info)
4428 "Non-nil when TABLE-ROW is at the beginning of a column group.
4429 INFO is a plist used as a communication channel."
4430 (unless (or (eq (org-element-property :type table-row) 'rule)
4431 (org-export-table-row-is-special-p table-row info))
4432 (let ((borders (org-export-table-cell-borders
4433 (car (org-element-contents table-row)) info)))
4434 (or (memq 'top borders) (memq 'above borders)))))
4436 (defun org-export-table-row-ends-rowgroup-p (table-row info)
4437 "Non-nil when TABLE-ROW is at the end of a column group.
4438 INFO is a plist used as a communication channel."
4439 (unless (or (eq (org-element-property :type table-row) 'rule)
4440 (org-export-table-row-is-special-p table-row info))
4441 (let ((borders (org-export-table-cell-borders
4442 (car (org-element-contents table-row)) info)))
4443 (or (memq 'bottom borders) (memq 'below borders)))))
4445 (defun org-export-table-row-starts-header-p (table-row info)
4446 "Non-nil when TABLE-ROW is the first table header's row.
4447 INFO is a plist used as a communication channel."
4448 (and (org-export-table-has-header-p
4449 (org-export-get-parent-table table-row) info)
4450 (org-export-table-row-starts-rowgroup-p table-row info)
4451 (= (org-export-table-row-group table-row info) 1)))
4453 (defun org-export-table-row-ends-header-p (table-row info)
4454 "Non-nil when TABLE-ROW is the last table header's row.
4455 INFO is a plist used as a communication channel."
4456 (and (org-export-table-has-header-p
4457 (org-export-get-parent-table table-row) info)
4458 (org-export-table-row-ends-rowgroup-p table-row info)
4459 (= (org-export-table-row-group table-row info) 1)))
4461 (defun org-export-table-dimensions (table info)
4462 "Return TABLE dimensions.
4464 INFO is a plist used as a communication channel.
4466 Return value is a CONS like (ROWS . COLUMNS) where
4467 ROWS (resp. COLUMNS) is the number of exportable
4468 rows (resp. columns)."
4469 (let (first-row (columns 0) (rows 0))
4470 ;; Set number of rows, and extract first one.
4471 (org-element-map table 'table-row
4472 (lambda (row)
4473 (when (eq (org-element-property :type row) 'standard)
4474 (incf rows)
4475 (unless first-row (setq first-row row)))) info)
4476 ;; Set number of columns.
4477 (org-element-map first-row 'table-cell (lambda (cell) (incf columns)) info)
4478 ;; Return value.
4479 (cons rows columns)))
4481 (defun org-export-table-cell-address (table-cell info)
4482 "Return address of a regular TABLE-CELL object.
4484 TABLE-CELL is the cell considered. INFO is a plist used as
4485 a communication channel.
4487 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4488 zero-based index. Only exportable cells are considered. The
4489 function returns nil for other cells."
4490 (let* ((table-row (org-export-get-parent table-cell))
4491 (table (org-export-get-parent-table table-cell)))
4492 ;; Ignore cells in special rows or in special column.
4493 (unless (or (org-export-table-row-is-special-p table-row info)
4494 (and (org-export-table-has-special-column-p table)
4495 (eq (car (org-element-contents table-row)) table-cell)))
4496 (cons
4497 ;; Row number.
4498 (let ((row-count 0))
4499 (org-element-map table 'table-row
4500 (lambda (row)
4501 (cond ((eq (org-element-property :type row) 'rule) nil)
4502 ((eq row table-row) row-count)
4503 (t (incf row-count) nil)))
4504 info 'first-match))
4505 ;; Column number.
4506 (let ((col-count 0))
4507 (org-element-map table-row 'table-cell
4508 (lambda (cell)
4509 (if (eq cell table-cell) col-count (incf col-count) nil))
4510 info 'first-match))))))
4512 (defun org-export-get-table-cell-at (address table info)
4513 "Return regular table-cell object at ADDRESS in TABLE.
4515 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4516 zero-based index. TABLE is a table type element. INFO is
4517 a plist used as a communication channel.
4519 If no table-cell, among exportable cells, is found at ADDRESS,
4520 return nil."
4521 (let ((column-pos (cdr address)) (column-count 0))
4522 (org-element-map
4523 ;; Row at (car address) or nil.
4524 (let ((row-pos (car address)) (row-count 0))
4525 (org-element-map table 'table-row
4526 (lambda (row)
4527 (cond ((eq (org-element-property :type row) 'rule) nil)
4528 ((= row-count row-pos) row)
4529 (t (incf row-count) nil)))
4530 info 'first-match))
4531 'table-cell
4532 (lambda (cell)
4533 (if (= column-count column-pos) cell
4534 (incf column-count) nil))
4535 info 'first-match)))
4538 ;;;; For Tables Of Contents
4540 ;; `org-export-collect-headlines' builds a list of all exportable
4541 ;; headline elements, maybe limited to a certain depth. One can then
4542 ;; easily parse it and transcode it.
4544 ;; Building lists of tables, figures or listings is quite similar.
4545 ;; Once the generic function `org-export-collect-elements' is defined,
4546 ;; `org-export-collect-tables', `org-export-collect-figures' and
4547 ;; `org-export-collect-listings' can be derived from it.
4549 (defun org-export-collect-headlines (info &optional n)
4550 "Collect headlines in order to build a table of contents.
4552 INFO is a plist used as a communication channel.
4554 When optional argument N is an integer, it specifies the depth of
4555 the table of contents. Otherwise, it is set to the value of the
4556 last headline level. See `org-export-headline-levels' for more
4557 information.
4559 Return a list of all exportable headlines as parsed elements.
4560 Footnote sections, if any, will be ignored."
4561 (unless (wholenump n) (setq n (plist-get info :headline-levels)))
4562 (org-element-map (plist-get info :parse-tree) 'headline
4563 (lambda (headline)
4564 (unless (org-element-property :footnote-section-p headline)
4565 ;; Strip contents from HEADLINE.
4566 (let ((relative-level (org-export-get-relative-level headline info)))
4567 (unless (> relative-level n) headline))))
4568 info))
4570 (defun org-export-collect-elements (type info &optional predicate)
4571 "Collect referenceable elements of a determined type.
4573 TYPE can be a symbol or a list of symbols specifying element
4574 types to search. Only elements with a caption are collected.
4576 INFO is a plist used as a communication channel.
4578 When non-nil, optional argument PREDICATE is a function accepting
4579 one argument, an element of type TYPE. It returns a non-nil
4580 value when that element should be collected.
4582 Return a list of all elements found, in order of appearance."
4583 (org-element-map (plist-get info :parse-tree) type
4584 (lambda (element)
4585 (and (org-element-property :caption element)
4586 (or (not predicate) (funcall predicate element))
4587 element))
4588 info))
4590 (defun org-export-collect-tables (info)
4591 "Build a list of tables.
4592 INFO is a plist used as a communication channel.
4594 Return a list of table elements with a caption."
4595 (org-export-collect-elements 'table info))
4597 (defun org-export-collect-figures (info predicate)
4598 "Build a list of figures.
4600 INFO is a plist used as a communication channel. PREDICATE is
4601 a function which accepts one argument: a paragraph element and
4602 whose return value is non-nil when that element should be
4603 collected.
4605 A figure is a paragraph type element, with a caption, verifying
4606 PREDICATE. The latter has to be provided since a \"figure\" is
4607 a vague concept that may depend on back-end.
4609 Return a list of elements recognized as figures."
4610 (org-export-collect-elements 'paragraph info predicate))
4612 (defun org-export-collect-listings (info)
4613 "Build a list of src blocks.
4615 INFO is a plist used as a communication channel.
4617 Return a list of src-block elements with a caption."
4618 (org-export-collect-elements 'src-block info))
4621 ;;;; Smart Quotes
4623 ;; The main function for the smart quotes sub-system is
4624 ;; `org-export-activate-smart-quotes', which replaces every quote in
4625 ;; a given string from the parse tree with its "smart" counterpart.
4627 ;; Dictionary for smart quotes is stored in
4628 ;; `org-export-smart-quotes-alist'.
4630 ;; Internally, regexps matching potential smart quotes (checks at
4631 ;; string boundaries are also necessary) are defined in
4632 ;; `org-export-smart-quotes-regexps'.
4634 (defconst org-export-smart-quotes-alist
4635 '(("de"
4636 (opening-double-quote :utf-8 "„" :html "&bdquo;" :latex "\"`"
4637 :texinfo "@quotedblbase{}")
4638 (closing-double-quote :utf-8 "“" :html "&ldquo;" :latex "\"'"
4639 :texinfo "@quotedblleft{}")
4640 (opening-single-quote :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}"
4641 :texinfo "@quotesinglbase{}")
4642 (closing-single-quote :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}"
4643 :texinfo "@quoteleft{}")
4644 (apostrophe :utf-8 "’" :html "&rsquo;"))
4645 ("en"
4646 (opening-double-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
4647 (closing-double-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
4648 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
4649 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
4650 (apostrophe :utf-8 "’" :html "&rsquo;"))
4651 ("es"
4652 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
4653 :texinfo "@guillemetleft{}")
4654 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
4655 :texinfo "@guillemetright{}")
4656 (opening-single-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
4657 (closing-single-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
4658 (apostrophe :utf-8 "’" :html "&rsquo;"))
4659 ("fr"
4660 (opening-double-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
4661 :texinfo "@guillemetleft{}@tie{}")
4662 (closing-double-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
4663 :texinfo "@tie{}@guillemetright{}")
4664 (opening-single-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
4665 :texinfo "@guillemetleft{}@tie{}")
4666 (closing-single-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
4667 :texinfo "@tie{}@guillemetright{}")
4668 (apostrophe :utf-8 "’" :html "&rsquo;")))
4669 "Smart quotes translations.
4671 Alist whose CAR is a language string and CDR is an alist with
4672 quote type as key and a plist associating various encodings to
4673 their translation as value.
4675 A quote type can be any symbol among `opening-double-quote',
4676 `closing-double-quote', `opening-single-quote',
4677 `closing-single-quote' and `apostrophe'.
4679 Valid encodings include `:utf-8', `:html', `:latex' and
4680 `:texinfo'.
4682 If no translation is found, the quote character is left as-is.")
4684 (defconst org-export-smart-quotes-regexps
4685 (list
4686 ;; Possible opening quote at beginning of string.
4687 "\\`\\([\"']\\)\\(\\w\\|\\s.\\|\\s_\\)"
4688 ;; Possible closing quote at beginning of string.
4689 "\\`\\([\"']\\)\\(\\s-\\|\\s)\\|\\s.\\)"
4690 ;; Possible apostrophe at beginning of string.
4691 "\\`\\('\\)\\S-"
4692 ;; Opening single and double quotes.
4693 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\(?:\\w\\|\\s.\\|\\s_\\)"
4694 ;; Closing single and double quotes.
4695 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\(?:\\s-\\|\\s)\\|\\s.\\)"
4696 ;; Apostrophe.
4697 "\\S-\\('\\)\\S-"
4698 ;; Possible opening quote at end of string.
4699 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\'"
4700 ;; Possible closing quote at end of string.
4701 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\'"
4702 ;; Possible apostrophe at end of string.
4703 "\\S-\\('\\)\\'")
4704 "List of regexps matching a quote or an apostrophe.
4705 In every regexp, quote or apostrophe matched is put in group 1.")
4707 (defun org-export-activate-smart-quotes (s encoding info &optional original)
4708 "Replace regular quotes with \"smart\" quotes in string S.
4710 ENCODING is a symbol among `:html', `:latex', `:texinfo' and
4711 `:utf-8'. INFO is a plist used as a communication channel.
4713 The function has to retrieve information about string
4714 surroundings in parse tree. It can only happen with an
4715 unmodified string. Thus, if S has already been through another
4716 process, a non-nil ORIGINAL optional argument will provide that
4717 original string.
4719 Return the new string."
4720 (if (equal s "") ""
4721 (let* ((prev (org-export-get-previous-element (or original s) info))
4722 ;; Try to be flexible when computing number of blanks
4723 ;; before object. The previous object may be a string
4724 ;; introduced by the back-end and not completely parsed.
4725 (pre-blank (and prev
4726 (or (org-element-property :post-blank prev)
4727 ;; A string with missing `:post-blank'
4728 ;; property.
4729 (and (stringp prev)
4730 (string-match " *\\'" prev)
4731 (length (match-string 0 prev)))
4732 ;; Fallback value.
4733 0)))
4734 (next (org-export-get-next-element (or original s) info))
4735 (get-smart-quote
4736 (lambda (q type)
4737 ;; Return smart quote associated to a give quote Q, as
4738 ;; a string. TYPE is a symbol among `open', `close' and
4739 ;; `apostrophe'.
4740 (let ((key (case type
4741 (apostrophe 'apostrophe)
4742 (open (if (equal "'" q) 'opening-single-quote
4743 'opening-double-quote))
4744 (otherwise (if (equal "'" q) 'closing-single-quote
4745 'closing-double-quote)))))
4746 (or (plist-get
4747 (cdr (assq key
4748 (cdr (assoc (plist-get info :language)
4749 org-export-smart-quotes-alist))))
4750 encoding)
4751 q)))))
4752 (if (or (equal "\"" s) (equal "'" s))
4753 ;; Only a quote: no regexp can match. We have to check both
4754 ;; sides and decide what to do.
4755 (cond ((and (not prev) (not next)) s)
4756 ((not prev) (funcall get-smart-quote s 'open))
4757 ((and (not next) (zerop pre-blank))
4758 (funcall get-smart-quote s 'close))
4759 ((not next) s)
4760 ((zerop pre-blank) (funcall get-smart-quote s 'apostrophe))
4761 (t (funcall get-smart-quote 'open)))
4762 ;; 1. Replace quote character at the beginning of S.
4763 (cond
4764 ;; Apostrophe?
4765 ((and prev (zerop pre-blank)
4766 (string-match (nth 2 org-export-smart-quotes-regexps) s))
4767 (setq s (replace-match
4768 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
4769 nil t s 1)))
4770 ;; Closing quote?
4771 ((and prev (zerop pre-blank)
4772 (string-match (nth 1 org-export-smart-quotes-regexps) s))
4773 (setq s (replace-match
4774 (funcall get-smart-quote (match-string 1 s) 'close)
4775 nil t s 1)))
4776 ;; Opening quote?
4777 ((and (or (not prev) (> pre-blank 0))
4778 (string-match (nth 0 org-export-smart-quotes-regexps) s))
4779 (setq s (replace-match
4780 (funcall get-smart-quote (match-string 1 s) 'open)
4781 nil t s 1))))
4782 ;; 2. Replace quotes in the middle of the string.
4783 (setq s (replace-regexp-in-string
4784 ;; Opening quotes.
4785 (nth 3 org-export-smart-quotes-regexps)
4786 (lambda (text)
4787 (funcall get-smart-quote (match-string 1 text) 'open))
4788 s nil t 1))
4789 (setq s (replace-regexp-in-string
4790 ;; Closing quotes.
4791 (nth 4 org-export-smart-quotes-regexps)
4792 (lambda (text)
4793 (funcall get-smart-quote (match-string 1 text) 'close))
4794 s nil t 1))
4795 (setq s (replace-regexp-in-string
4796 ;; Apostrophes.
4797 (nth 5 org-export-smart-quotes-regexps)
4798 (lambda (text)
4799 (funcall get-smart-quote (match-string 1 text) 'apostrophe))
4800 s nil t 1))
4801 ;; 3. Replace quote character at the end of S.
4802 (cond
4803 ;; Apostrophe?
4804 ((and next (string-match (nth 8 org-export-smart-quotes-regexps) s))
4805 (setq s (replace-match
4806 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
4807 nil t s 1)))
4808 ;; Closing quote?
4809 ((and (not next)
4810 (string-match (nth 7 org-export-smart-quotes-regexps) s))
4811 (setq s (replace-match
4812 (funcall get-smart-quote (match-string 1 s) 'close)
4813 nil t s 1)))
4814 ;; Opening quote?
4815 ((and next (string-match (nth 6 org-export-smart-quotes-regexps) s))
4816 (setq s (replace-match
4817 (funcall get-smart-quote (match-string 1 s) 'open)
4818 nil t s 1))))
4819 ;; Return string with smart quotes.
4820 s))))
4822 ;;;; Topology
4824 ;; Here are various functions to retrieve information about the
4825 ;; neighbourhood of a given element or object. Neighbours of interest
4826 ;; are direct parent (`org-export-get-parent'), parent headline
4827 ;; (`org-export-get-parent-headline'), first element containing an
4828 ;; object, (`org-export-get-parent-element'), parent table
4829 ;; (`org-export-get-parent-table'), previous element or object
4830 ;; (`org-export-get-previous-element') and next element or object
4831 ;; (`org-export-get-next-element').
4833 ;; `org-export-get-genealogy' returns the full genealogy of a given
4834 ;; element or object, from closest parent to full parse tree.
4836 (defun org-export-get-parent (blob)
4837 "Return BLOB parent or nil.
4838 BLOB is the element or object considered."
4839 (org-element-property :parent blob))
4841 (defun org-export-get-genealogy (blob)
4842 "Return full genealogy relative to a given element or object.
4844 BLOB is the element or object being considered.
4846 Ancestors are returned from closest to farthest, the last one
4847 being the full parse tree."
4848 (let (genealogy (parent blob))
4849 (while (setq parent (org-element-property :parent parent))
4850 (push parent genealogy))
4851 (nreverse genealogy)))
4853 (defun org-export-get-parent-headline (blob)
4854 "Return BLOB parent headline or nil.
4855 BLOB is the element or object being considered."
4856 (let ((parent blob))
4857 (while (and (setq parent (org-element-property :parent parent))
4858 (not (eq (org-element-type parent) 'headline))))
4859 parent))
4861 (defun org-export-get-parent-element (object)
4862 "Return first element containing OBJECT or nil.
4863 OBJECT is the object to consider."
4864 (let ((parent object))
4865 (while (and (setq parent (org-element-property :parent parent))
4866 (memq (org-element-type parent) org-element-all-objects)))
4867 parent))
4869 (defun org-export-get-parent-table (object)
4870 "Return OBJECT parent table or nil.
4871 OBJECT is either a `table-cell' or `table-element' type object."
4872 (let ((parent object))
4873 (while (and (setq parent (org-element-property :parent parent))
4874 (not (eq (org-element-type parent) 'table))))
4875 parent))
4877 (defun org-export-get-previous-element (blob info &optional n)
4878 "Return previous element or object.
4880 BLOB is an element or object. INFO is a plist used as
4881 a communication channel. Return previous exportable element or
4882 object, a string, or nil.
4884 When optional argument N is a positive integer, return a list
4885 containing up to N siblings before BLOB, from farthest to
4886 closest. With any other non-nil value, return a list containing
4887 all of them."
4888 (let ((siblings
4889 ;; An object can belong to the contents of its parent or
4890 ;; to a secondary string. We check the latter option
4891 ;; first.
4892 (let ((parent (org-export-get-parent blob)))
4893 (or (and (not (memq (org-element-type blob)
4894 org-element-all-elements))
4895 (let ((sec-value
4896 (org-element-property
4897 (cdr (assq (org-element-type parent)
4898 org-element-secondary-value-alist))
4899 parent)))
4900 (and (memq blob sec-value) sec-value)))
4901 (org-element-contents parent))))
4902 prev)
4903 (catch 'exit
4904 (mapc (lambda (obj)
4905 (cond ((memq obj (plist-get info :ignore-list)))
4906 ((null n) (throw 'exit obj))
4907 ((not (wholenump n)) (push obj prev))
4908 ((zerop n) (throw 'exit prev))
4909 (t (decf n) (push obj prev))))
4910 (cdr (memq blob (reverse siblings))))
4911 prev)))
4913 (defun org-export-get-next-element (blob info &optional n)
4914 "Return next element or object.
4916 BLOB is an element or object. INFO is a plist used as
4917 a communication channel. Return next exportable element or
4918 object, a string, or nil.
4920 When optional argument N is a positive integer, return a list
4921 containing up to N siblings after BLOB, from closest to farthest.
4922 With any other non-nil value, return a list containing all of
4923 them."
4924 (let ((siblings
4925 ;; An object can belong to the contents of its parent or to
4926 ;; a secondary string. We check the latter option first.
4927 (let ((parent (org-export-get-parent blob)))
4928 (or (and (not (memq (org-element-type blob)
4929 org-element-all-objects))
4930 (let ((sec-value
4931 (org-element-property
4932 (cdr (assq (org-element-type parent)
4933 org-element-secondary-value-alist))
4934 parent)))
4935 (cdr (memq blob sec-value))))
4936 (cdr (memq blob (org-element-contents parent))))))
4937 next)
4938 (catch 'exit
4939 (mapc (lambda (obj)
4940 (cond ((memq obj (plist-get info :ignore-list)))
4941 ((null n) (throw 'exit obj))
4942 ((not (wholenump n)) (push obj next))
4943 ((zerop n) (throw 'exit (nreverse next)))
4944 (t (decf n) (push obj next))))
4945 siblings)
4946 (nreverse next))))
4949 ;;;; Translation
4951 ;; `org-export-translate' translates a string according to language
4952 ;; specified by LANGUAGE keyword or `org-export-language-setup'
4953 ;; variable and a specified charset. `org-export-dictionary' contains
4954 ;; the dictionary used for the translation.
4956 (defconst org-export-dictionary
4957 '(("Author"
4958 ("ca" :default "Autor")
4959 ("cs" :default "Autor")
4960 ("da" :default "Ophavsmand")
4961 ("de" :default "Autor")
4962 ("eo" :html "A&#365;toro")
4963 ("es" :default "Autor")
4964 ("fi" :html "Tekij&auml;")
4965 ("fr" :default "Auteur")
4966 ("hu" :default "Szerz&otilde;")
4967 ("is" :html "H&ouml;fundur")
4968 ("it" :default "Autore")
4969 ("ja" :html "&#33879;&#32773;" :utf-8 "著者")
4970 ("nl" :default "Auteur")
4971 ("no" :default "Forfatter")
4972 ("nb" :default "Forfatter")
4973 ("nn" :default "Forfattar")
4974 ("pl" :default "Autor")
4975 ("ru" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
4976 ("sv" :html "F&ouml;rfattare")
4977 ("uk" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
4978 ("zh-CN" :html "&#20316;&#32773;" :utf-8 "作者")
4979 ("zh-TW" :html "&#20316;&#32773;" :utf-8 "作者"))
4980 ("Date"
4981 ("ca" :default "Data")
4982 ("cs" :default "Datum")
4983 ("da" :default "Dato")
4984 ("de" :default "Datum")
4985 ("eo" :default "Dato")
4986 ("es" :default "Fecha")
4987 ("fi" :html "P&auml;iv&auml;m&auml;&auml;r&auml;")
4988 ("hu" :html "D&aacute;tum")
4989 ("is" :default "Dagsetning")
4990 ("it" :default "Data")
4991 ("ja" :html "&#26085;&#20184;" :utf-8 "日付")
4992 ("nl" :default "Datum")
4993 ("no" :default "Dato")
4994 ("nb" :default "Dato")
4995 ("nn" :default "Dato")
4996 ("pl" :default "Data")
4997 ("ru" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
4998 ("sv" :default "Datum")
4999 ("uk" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5000 ("zh-CN" :html "&#26085;&#26399;" :utf-8 "日期")
5001 ("zh-TW" :html "&#26085;&#26399;" :utf-8 "日期"))
5002 ("Equation"
5003 ("fr" :ascii "Equation" :default "Équation"))
5004 ("Figure")
5005 ("Footnotes"
5006 ("ca" :html "Peus de p&agrave;gina")
5007 ("cs" :default "Pozn\xe1mky pod carou")
5008 ("da" :default "Fodnoter")
5009 ("de" :html "Fu&szlig;noten")
5010 ("eo" :default "Piednotoj")
5011 ("es" :html "Pies de p&aacute;gina")
5012 ("fi" :default "Alaviitteet")
5013 ("fr" :default "Notes de bas de page")
5014 ("hu" :html "L&aacute;bjegyzet")
5015 ("is" :html "Aftanm&aacute;lsgreinar")
5016 ("it" :html "Note a pi&egrave; di pagina")
5017 ("ja" :html "&#33050;&#27880;" :utf-8 "脚注")
5018 ("nl" :default "Voetnoten")
5019 ("no" :default "Fotnoter")
5020 ("nb" :default "Fotnoter")
5021 ("nn" :default "Fotnotar")
5022 ("pl" :default "Przypis")
5023 ("ru" :html "&#1057;&#1085;&#1086;&#1089;&#1082;&#1080;" :utf-8 "Сноски")
5024 ("sv" :default "Fotnoter")
5025 ("uk" :html "&#1055;&#1088;&#1080;&#1084;&#1110;&#1090;&#1082;&#1080;"
5026 :utf-8 "Примітки")
5027 ("zh-CN" :html "&#33050;&#27880;" :utf-8 "脚注")
5028 ("zh-TW" :html "&#33139;&#35387;" :utf-8 "腳註"))
5029 ("List of Listings"
5030 ("fr" :default "Liste des programmes"))
5031 ("List of Tables"
5032 ("fr" :default "Liste des tableaux"))
5033 ("Listing %d:"
5034 ("fr"
5035 :ascii "Programme %d :" :default "Programme nº %d :"
5036 :latin1 "Programme %d :"))
5037 ("Listing %d: %s"
5038 ("fr"
5039 :ascii "Programme %d : %s" :default "Programme nº %d : %s"
5040 :latin1 "Programme %d : %s"))
5041 ("See section %s"
5042 ("fr" :default "cf. section %s"))
5043 ("Table %d:"
5044 ("fr"
5045 :ascii "Tableau %d :" :default "Tableau nº %d :" :latin1 "Tableau %d :"))
5046 ("Table %d: %s"
5047 ("fr"
5048 :ascii "Tableau %d : %s" :default "Tableau nº %d : %s"
5049 :latin1 "Tableau %d : %s"))
5050 ("Table of Contents"
5051 ("ca" :html "&Iacute;ndex")
5052 ("cs" :default "Obsah")
5053 ("da" :default "Indhold")
5054 ("de" :default "Inhaltsverzeichnis")
5055 ("eo" :default "Enhavo")
5056 ("es" :html "&Iacute;ndice")
5057 ("fi" :html "Sis&auml;llysluettelo")
5058 ("fr" :ascii "Sommaire" :default "Table des matières")
5059 ("hu" :html "Tartalomjegyz&eacute;k")
5060 ("is" :default "Efnisyfirlit")
5061 ("it" :default "Indice")
5062 ("ja" :html "&#30446;&#27425;" :utf-8 "目次")
5063 ("nl" :default "Inhoudsopgave")
5064 ("no" :default "Innhold")
5065 ("nb" :default "Innhold")
5066 ("nn" :default "Innhald")
5067 ("pl" :html "Spis tre&#x015b;ci")
5068 ("ru" :html "&#1057;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1077;"
5069 :utf-8 "Содержание")
5070 ("sv" :html "Inneh&aring;ll")
5071 ("uk" :html "&#1047;&#1084;&#1110;&#1089;&#1090;" :utf-8 "Зміст")
5072 ("zh-CN" :html "&#30446;&#24405;" :utf-8 "目录")
5073 ("zh-TW" :html "&#30446;&#37636;" :utf-8 "目錄"))
5074 ("Unknown reference"
5075 ("fr" :ascii "Destination inconnue" :default "Référence inconnue")))
5076 "Dictionary for export engine.
5078 Alist whose CAR is the string to translate and CDR is an alist
5079 whose CAR is the language string and CDR is a plist whose
5080 properties are possible charsets and values translated terms.
5082 It is used as a database for `org-export-translate'. Since this
5083 function returns the string as-is if no translation was found,
5084 the variable only needs to record values different from the
5085 entry.")
5087 (defun org-export-translate (s encoding info)
5088 "Translate string S according to language specification.
5090 ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1'
5091 and `:utf-8'. INFO is a plist used as a communication channel.
5093 Translation depends on `:language' property. Return the
5094 translated string. If no translation is found, try to fall back
5095 to `:default' encoding. If it fails, return S."
5096 (let* ((lang (plist-get info :language))
5097 (translations (cdr (assoc lang
5098 (cdr (assoc s org-export-dictionary))))))
5099 (or (plist-get translations encoding)
5100 (plist-get translations :default)
5101 s)))
5105 ;;; Asynchronous Export
5107 ;; `org-export-async-start' is the entry point for asynchronous
5108 ;; export. It recreates current buffer (including visibility,
5109 ;; narrowing and visited file) in an external Emacs process, and
5110 ;; evaluates a command there. It then applies a function on the
5111 ;; returned results in the current process.
5113 ;; Asynchronously generated results are never displayed directly.
5114 ;; Instead, they are stored in `org-export-stack-contents'. They can
5115 ;; then be retrieved by calling `org-export-stack'.
5117 ;; Export Stack is viewed through a dedicated major mode
5118 ;;`org-export-stack-mode' and tools: `org-export-stack-refresh',
5119 ;;`org-export-stack-delete', `org-export-stack-view' and
5120 ;;`org-export-stack-clear'.
5122 ;; For back-ends, `org-export-add-to-stack' add a new source to stack.
5123 ;; It should used whenever `org-export-async-start' is called.
5125 (defmacro org-export-async-start (fun &rest body)
5126 "Call function FUN on the results returned by BODY evaluation.
5128 BODY evaluation happens in an asynchronous process, from a buffer
5129 which is an exact copy of the current one.
5131 Use `org-export-add-to-stack' in FUN in order to register results
5132 in the stack. Examples for, respectively a temporary buffer and
5133 a file are:
5135 \(org-export-async-start
5136 \(lambda (output)
5137 \(with-current-buffer (get-buffer-create \"*Org BACKEND Export*\")
5138 \(erase-buffer)
5139 \(insert output)
5140 \(goto-char (point-min))
5141 \(org-export-add-to-stack (current-buffer) 'backend)))
5142 `(org-export-as 'backend ,subtreep ,visible-only ,body-only ',ext-plist))
5146 \(org-export-async-start
5147 \(lambda (f) (org-export-add-to-stack f 'backend))
5148 `(expand-file-name
5149 \(org-export-to-file
5150 'backend ,outfile ,subtreep ,visible-only ,body-only ',ext-plist)))"
5151 (declare (indent 1) (debug t))
5152 (org-with-gensyms (process temp-file copy-fun proc-buffer handler coding)
5153 ;; Write the full sexp evaluating BODY in a copy of the current
5154 ;; buffer to a temporary file, as it may be too long for program
5155 ;; args in `start-process'.
5156 `(with-temp-message "Initializing asynchronous export process"
5157 (let ((,copy-fun (org-export--generate-copy-script (current-buffer)))
5158 (,temp-file (make-temp-file "org-export-process"))
5159 (,coding buffer-file-coding-system))
5160 (with-temp-file ,temp-file
5161 (insert
5162 ;; Null characters (from variable values) are inserted
5163 ;; within the file. As a consequence, coding system for
5164 ;; buffer contents will not be recognized properly. So,
5165 ;; we make sure it is the same as the one used to display
5166 ;; the original buffer.
5167 (format ";; -*- coding: %s; -*-\n%S"
5168 ,coding
5169 `(with-temp-buffer
5170 ,(when org-export-async-debug '(setq debug-on-error t))
5171 ;; Ignore `kill-emacs-hook' and code evaluation
5172 ;; queries from Babel as we need a truly
5173 ;; non-interactive process.
5174 (setq kill-emacs-hook nil
5175 org-babel-confirm-evaluate-answer-no t)
5176 ;; Initialize export framework.
5177 (require 'ox)
5178 ;; Re-create current buffer there.
5179 (funcall ,,copy-fun)
5180 (restore-buffer-modified-p nil)
5181 ;; Sexp to evaluate in the buffer.
5182 (print (progn ,,@body))))))
5183 ;; Start external process.
5184 (let* ((process-connection-type nil)
5185 (,proc-buffer (generate-new-buffer-name "*Org Export Process*"))
5186 (,process
5187 (start-process
5188 "org-export-process" ,proc-buffer
5189 (expand-file-name invocation-name invocation-directory)
5190 "-Q" "--batch"
5191 "-l" org-export-async-init-file
5192 "-l" ,temp-file)))
5193 ;; Register running process in stack.
5194 (org-export-add-to-stack (get-buffer ,proc-buffer) nil ,process)
5195 ;; Set-up sentinel in order to catch results.
5196 (set-process-sentinel
5197 ,process
5198 (let ((handler ',fun))
5199 `(lambda (p status)
5200 (let ((proc-buffer (process-buffer p)))
5201 (when (eq (process-status p) 'exit)
5202 (unwind-protect
5203 (if (zerop (process-exit-status p))
5204 (unwind-protect
5205 (let ((results
5206 (with-current-buffer proc-buffer
5207 (goto-char (point-max))
5208 (backward-sexp)
5209 (read (current-buffer)))))
5210 (funcall ,handler results))
5211 (unless org-export-async-debug
5212 (and (get-buffer proc-buffer)
5213 (kill-buffer proc-buffer))))
5214 (org-export-add-to-stack proc-buffer nil p)
5215 (ding)
5216 (message "Process '%s' exited abnormally" p))
5217 (unless org-export-async-debug
5218 (delete-file ,,temp-file)))))))))))))
5220 (defun org-export-add-to-stack (source backend &optional process)
5221 "Add a new result to export stack if not present already.
5223 SOURCE is a buffer or a file name containing export results.
5224 BACKEND is a symbol representing export back-end used to generate
5227 Entries already pointing to SOURCE and unavailable entries are
5228 removed beforehand. Return the new stack."
5229 (setq org-export-stack-contents
5230 (cons (list source backend (or process (current-time)))
5231 (org-export-stack-remove source))))
5233 (defun org-export-stack ()
5234 "Menu for asynchronous export results and running processes."
5235 (interactive)
5236 (let ((buffer (get-buffer-create "*Org Export Stack*")))
5237 (set-buffer buffer)
5238 (when (zerop (buffer-size)) (org-export-stack-mode))
5239 (org-export-stack-refresh)
5240 (pop-to-buffer buffer))
5241 (message "Type \"q\" to quit, \"?\" for help"))
5243 (defun org-export--stack-source-at-point ()
5244 "Return source from export results at point in stack."
5245 (let ((source (car (nth (1- (org-current-line)) org-export-stack-contents))))
5246 (if (not source) (error "Source unavailable, please refresh buffer")
5247 (let ((source-name (if (stringp source) source (buffer-name source))))
5248 (if (save-excursion
5249 (beginning-of-line)
5250 (looking-at (concat ".* +" (regexp-quote source-name) "$")))
5251 source
5252 ;; SOURCE is not consistent with current line. The stack
5253 ;; view is outdated.
5254 (error "Source unavailable; type `g' to update buffer"))))))
5256 (defun org-export-stack-clear ()
5257 "Remove all entries from export stack."
5258 (interactive)
5259 (setq org-export-stack-contents nil))
5261 (defun org-export-stack-refresh (&rest dummy)
5262 "Refresh the asynchronous export stack.
5263 DUMMY is ignored. Unavailable sources are removed from the list.
5264 Return the new stack."
5265 (let ((inhibit-read-only t))
5266 (org-preserve-lc
5267 (erase-buffer)
5268 (insert (concat
5269 (let ((counter 0))
5270 (mapconcat
5271 (lambda (entry)
5272 (let ((proc-p (processp (nth 2 entry))))
5273 (concat
5274 ;; Back-end.
5275 (format " %-12s " (or (nth 1 entry) ""))
5276 ;; Age.
5277 (let ((data (nth 2 entry)))
5278 (if proc-p (format " %6s " (process-status data))
5279 ;; Compute age of the results.
5280 (org-format-seconds
5281 "%4h:%.2m "
5282 (float-time (time-since data)))))
5283 ;; Source.
5284 (format " %s"
5285 (let ((source (car entry)))
5286 (if (stringp source) source
5287 (buffer-name source)))))))
5288 ;; Clear stack from exited processes, dead buffers or
5289 ;; non-existent files.
5290 (setq org-export-stack-contents
5291 (org-remove-if-not
5292 (lambda (el)
5293 (if (processp (nth 2 el))
5294 (buffer-live-p (process-buffer (nth 2 el)))
5295 (let ((source (car el)))
5296 (if (bufferp source) (buffer-live-p source)
5297 (file-exists-p source)))))
5298 org-export-stack-contents)) "\n")))))))
5300 (defun org-export-stack-remove (&optional source)
5301 "Remove export results at point from stack.
5302 If optional argument SOURCE is non-nil, remove it instead."
5303 (interactive)
5304 (let ((source (or source (org-export--stack-source-at-point))))
5305 (setq org-export-stack-contents
5306 (org-remove-if (lambda (el) (equal (car el) source))
5307 org-export-stack-contents))))
5309 (defun org-export-stack-view (&optional in-emacs)
5310 "View export results at point in stack.
5311 With an optional prefix argument IN-EMACS, force viewing files
5312 within Emacs."
5313 (interactive "P")
5314 (let ((source (org-export--stack-source-at-point)))
5315 (cond ((processp source)
5316 (org-switch-to-buffer-other-window (process-buffer source)))
5317 ((bufferp source) (org-switch-to-buffer-other-window source))
5318 (t (org-open-file source in-emacs)))))
5320 (defconst org-export-stack-mode-map
5321 (let ((km (make-sparse-keymap)))
5322 (define-key km " " 'next-line)
5323 (define-key km "n" 'next-line)
5324 (define-key km "\C-n" 'next-line)
5325 (define-key km [down] 'next-line)
5326 (define-key km "p" 'previous-line)
5327 (define-key km "\C-p" 'previous-line)
5328 (define-key km "\C-?" 'previous-line)
5329 (define-key km [up] 'previous-line)
5330 (define-key km "C" 'org-export-stack-clear)
5331 (define-key km "v" 'org-export-stack-view)
5332 (define-key km (kbd "RET") 'org-export-stack-view)
5333 (define-key km "d" 'org-export-stack-remove)
5335 "Keymap for Org Export Stack.")
5337 (define-derived-mode org-export-stack-mode special-mode "Org-Stack"
5338 "Mode for displaying asynchronous export stack.
5340 Type \\[org-export-stack] to visualize the asynchronous export
5341 stack.
5343 In an Org Export Stack buffer, use \\<org-export-stack-mode-map>\\[org-export-stack-view] to view export output
5344 on current line, \\[org-export-stack-remove] to remove it from the stack and \\[org-export-stack-clear] to clear
5345 stack completely.
5347 Removing entries in an Org Export Stack buffer doesn't affect
5348 files or buffers, only the display.
5350 \\{org-export-stack-mode-map}"
5351 (abbrev-mode 0)
5352 (auto-fill-mode 0)
5353 (setq buffer-read-only t
5354 buffer-undo-list t
5355 truncate-lines t
5356 header-line-format
5357 '(:eval
5358 (format " %-12s | %6s | %s" "Back-End" "Age" "Source")))
5359 (add-hook 'post-command-hook 'org-export-stack-refresh nil t)
5360 (set (make-local-variable 'revert-buffer-function)
5361 'org-export-stack-refresh))
5365 ;;; The Dispatcher
5367 ;; `org-export-dispatch' is the standard interactive way to start an
5368 ;; export process. It uses `org-export--dispatch-ui' as a subroutine
5369 ;; for its interface, which, in turn, delegates response to key
5370 ;; pressed to `org-export--dispatch-action'.
5372 ;;;###autoload
5373 (defun org-export-dispatch (&optional arg)
5374 "Export dispatcher for Org mode.
5376 It provides an access to common export related tasks in a buffer.
5377 Its interface comes in two flavours: standard and expert.
5379 While both share the same set of bindings, only the former
5380 displays the valid keys associations in a dedicated buffer.
5381 Scrolling (resp. line-wise motion) in this buffer is done with
5382 SPC and DEL (resp. C-n and C-p) keys.
5384 Set variable `org-export-dispatch-use-expert-ui' to switch to one
5385 flavour or the other.
5387 When ARG is \\[universal-argument], repeat the last export action, with the same set
5388 of options used back then, on the current buffer.
5390 When ARG is \\[universal-argument] \\[universal-argument], display the asynchronous export stack."
5391 (interactive "P")
5392 (let* ((input
5393 (cond ((equal arg '(16)) '(stack))
5394 ((and arg org-export-dispatch-last-action))
5395 (t (save-window-excursion
5396 (unwind-protect
5397 (progn
5398 ;; Remember where we are
5399 (move-marker org-export-dispatch-last-position
5400 (point)
5401 (org-base-buffer (current-buffer)))
5402 ;; Get and store an export command
5403 (setq org-export-dispatch-last-action
5404 (org-export--dispatch-ui
5405 (list org-export-initial-scope
5406 (and org-export-in-background 'async))
5408 org-export-dispatch-use-expert-ui)))
5409 (and (get-buffer "*Org Export Dispatcher*")
5410 (kill-buffer "*Org Export Dispatcher*")))))))
5411 (action (car input))
5412 (optns (cdr input)))
5413 (unless (memq 'subtree optns)
5414 (move-marker org-export-dispatch-last-position nil))
5415 (case action
5416 ;; First handle special hard-coded actions.
5417 (stack (org-export-stack))
5418 (publish-current-file
5419 (org-publish-current-file (memq 'force optns) (memq 'async optns)))
5420 (publish-current-project
5421 (org-publish-current-project (memq 'force optns) (memq 'async optns)))
5422 (publish-choose-project
5423 (org-publish (assoc (org-icompleting-read
5424 "Publish project: "
5425 org-publish-project-alist nil t)
5426 org-publish-project-alist)
5427 (memq 'force optns)
5428 (memq 'async optns)))
5429 (publish-all (org-publish-all (memq 'force optns) (memq 'async optns)))
5430 (otherwise
5431 (save-excursion
5432 (when arg
5433 ;; Repeating command, maybe move cursor
5434 ;; to restore subtree context
5435 (if (eq (marker-buffer org-export-dispatch-last-position)
5436 (org-base-buffer (current-buffer)))
5437 (goto-char org-export-dispatch-last-position)
5438 ;; We are in a differnet buffer, forget position
5439 (move-marker org-export-dispatch-last-position nil)))
5440 (funcall action
5441 ;; Return a symbol instead of a list to ease
5442 ;; asynchronous export macro use.
5443 (and (memq 'async optns) t)
5444 (and (memq 'subtree optns) t)
5445 (and (memq 'visible optns) t)
5446 (and (memq 'body optns) t)))))))
5448 (defun org-export--dispatch-ui (options first-key expertp)
5449 "Handle interface for `org-export-dispatch'.
5451 OPTIONS is a list containing current interactive options set for
5452 export. It can contain any of the following symbols:
5453 `body' toggles a body-only export
5454 `subtree' restricts export to current subtree
5455 `visible' restricts export to visible part of buffer.
5456 `force' force publishing files.
5457 `async' use asynchronous export process
5459 FIRST-KEY is the key pressed to select the first level menu. It
5460 is nil when this menu hasn't been selected yet.
5462 EXPERTP, when non-nil, triggers expert UI. In that case, no help
5463 buffer is provided, but indications about currently active
5464 options are given in the prompt. Moreover, \[?] allows to switch
5465 back to standard interface."
5466 (let* ((fontify-key
5467 (lambda (key &optional access-key)
5468 ;; Fontify KEY string. Optional argument ACCESS-KEY, when
5469 ;; non-nil is the required first-level key to activate
5470 ;; KEY. When its value is t, activate KEY independently
5471 ;; on the first key, if any. A nil value means KEY will
5472 ;; only be activated at first level.
5473 (if (or (eq access-key t) (eq access-key first-key))
5474 (org-propertize key 'face 'org-warning)
5475 key)))
5476 (fontify-value
5477 (lambda (value)
5478 ;; Fontify VALUE string.
5479 (org-propertize value 'face 'font-lock-variable-name-face)))
5480 ;; Prepare menu entries by extracting them from
5481 ;; `org-export-registered-backends', and sorting them by
5482 ;; access key and by ordinal, if any.
5483 (backends
5484 (sort
5485 (sort
5486 (delq nil
5487 (mapcar
5488 (lambda (b)
5489 (let ((name (car b)))
5490 (catch 'ignored
5491 ;; Ignore any back-end belonging to
5492 ;; `org-export-invisible-backends' or derived
5493 ;; from one of them.
5494 (dolist (ignored org-export-invisible-backends)
5495 (when (org-export-derived-backend-p name ignored)
5496 (throw 'ignored nil)))
5497 (org-export-backend-menu name))))
5498 org-export-registered-backends))
5499 (lambda (a b)
5500 (let ((key-a (nth 1 a))
5501 (key-b (nth 1 b)))
5502 (cond ((and (numberp key-a) (numberp key-b))
5503 (< key-a key-b))
5504 ((numberp key-b) t)))))
5505 (lambda (a b) (< (car a) (car b)))))
5506 ;; Compute a list of allowed keys based on the first key
5507 ;; pressed, if any. Some keys (?^B, ?^V, ?^S, ?^F, ?^A
5508 ;; and ?q) are always available.
5509 (allowed-keys
5510 (nconc (list 2 22 19 6 1)
5511 (if (not first-key) (org-uniquify (mapcar 'car backends))
5512 (let (sub-menu)
5513 (dolist (backend backends (sort (mapcar 'car sub-menu) '<))
5514 (when (eq (car backend) first-key)
5515 (setq sub-menu (append (nth 2 backend) sub-menu))))))
5516 (cond ((eq first-key ?P) (list ?f ?p ?x ?a))
5517 ((not first-key) (list ?P)))
5518 (list ?&)
5519 (when expertp (list ??))
5520 (list ?q)))
5521 ;; Build the help menu for standard UI.
5522 (help
5523 (unless expertp
5524 (concat
5525 ;; Options are hard-coded.
5526 (format "Options
5527 [%s] Body only: %s [%s] Visible only: %s
5528 [%s] Export scope: %s [%s] Force publishing: %s
5529 [%s] Async export: %s\n"
5530 (funcall fontify-key "C-b" t)
5531 (funcall fontify-value
5532 (if (memq 'body options) "On " "Off"))
5533 (funcall fontify-key "C-v" t)
5534 (funcall fontify-value
5535 (if (memq 'visible options) "On " "Off"))
5536 (funcall fontify-key "C-s" t)
5537 (funcall fontify-value
5538 (if (memq 'subtree options) "Subtree" "Buffer "))
5539 (funcall fontify-key "C-f" t)
5540 (funcall fontify-value
5541 (if (memq 'force options) "On " "Off"))
5542 (funcall fontify-key "C-a" t)
5543 (funcall fontify-value
5544 (if (memq 'async options) "On " "Off")))
5545 ;; Display registered back-end entries. When a key
5546 ;; appears for the second time, do not create another
5547 ;; entry, but append its sub-menu to existing menu.
5548 (let (last-key)
5549 (mapconcat
5550 (lambda (entry)
5551 (let ((top-key (car entry)))
5552 (concat
5553 (unless (eq top-key last-key)
5554 (setq last-key top-key)
5555 (format "\n[%s] %s\n"
5556 (funcall fontify-key (char-to-string top-key))
5557 (nth 1 entry)))
5558 (let ((sub-menu (nth 2 entry)))
5559 (unless (functionp sub-menu)
5560 ;; Split sub-menu into two columns.
5561 (let ((index -1))
5562 (concat
5563 (mapconcat
5564 (lambda (sub-entry)
5565 (incf index)
5566 (format
5567 (if (zerop (mod index 2)) " [%s] %-26s"
5568 "[%s] %s\n")
5569 (funcall fontify-key
5570 (char-to-string (car sub-entry))
5571 top-key)
5572 (nth 1 sub-entry)))
5573 sub-menu "")
5574 (when (zerop (mod index 2)) "\n"))))))))
5575 backends ""))
5576 ;; Publishing menu is hard-coded.
5577 (format "\n[%s] Publish
5578 [%s] Current file [%s] Current project
5579 [%s] Choose project [%s] All projects\n\n"
5580 (funcall fontify-key "P")
5581 (funcall fontify-key "f" ?P)
5582 (funcall fontify-key "p" ?P)
5583 (funcall fontify-key "x" ?P)
5584 (funcall fontify-key "a" ?P))
5585 (format "\[%s] Export stack\n" (funcall fontify-key "&" t))
5586 (format "\[%s] %s"
5587 (funcall fontify-key "q" t)
5588 (if first-key "Main menu" "Exit")))))
5589 ;; Build prompts for both standard and expert UI.
5590 (standard-prompt (unless expertp "Export command: "))
5591 (expert-prompt
5592 (when expertp
5593 (format
5594 "Export command (C-%s%s%s%s%s) [%s]: "
5595 (if (memq 'body options) (funcall fontify-key "b" t) "b")
5596 (if (memq 'visible options) (funcall fontify-key "v" t) "v")
5597 (if (memq 'subtree options) (funcall fontify-key "s" t) "s")
5598 (if (memq 'force options) (funcall fontify-key "f" t) "f")
5599 (if (memq 'async options) (funcall fontify-key "a" t) "a")
5600 (mapconcat (lambda (k)
5601 ;; Strip control characters.
5602 (unless (< k 27) (char-to-string k)))
5603 allowed-keys "")))))
5604 ;; With expert UI, just read key with a fancy prompt. In standard
5605 ;; UI, display an intrusive help buffer.
5606 (if expertp
5607 (org-export--dispatch-action
5608 expert-prompt allowed-keys backends options first-key expertp)
5609 ;; At first call, create frame layout in order to display menu.
5610 (unless (get-buffer "*Org Export Dispatcher*")
5611 (delete-other-windows)
5612 (org-switch-to-buffer-other-window
5613 (get-buffer-create "*Org Export Dispatcher*"))
5614 (setq cursor-type nil
5615 header-line-format "Use SPC, DEL, C-n or C-p to navigate.")
5616 ;; Make sure that invisible cursor will not highlight square
5617 ;; brackets.
5618 (set-syntax-table (copy-syntax-table))
5619 (modify-syntax-entry ?\[ "w"))
5620 ;; At this point, the buffer containing the menu exists and is
5621 ;; visible in the current window. So, refresh it.
5622 (with-current-buffer "*Org Export Dispatcher*"
5623 ;; Refresh help. Maintain display continuity by re-visiting
5624 ;; previous window position.
5625 (let ((pos (window-start)))
5626 (erase-buffer)
5627 (insert help)
5628 (set-window-start nil pos)))
5629 (org-fit-window-to-buffer)
5630 (org-export--dispatch-action
5631 standard-prompt allowed-keys backends options first-key expertp))))
5633 (defun org-export--dispatch-action
5634 (prompt allowed-keys backends options first-key expertp)
5635 "Read a character from command input and act accordingly.
5637 PROMPT is the displayed prompt, as a string. ALLOWED-KEYS is
5638 a list of characters available at a given step in the process.
5639 BACKENDS is a list of menu entries. OPTIONS, FIRST-KEY and
5640 EXPERTP are the same as defined in `org-export--dispatch-ui',
5641 which see.
5643 Toggle export options when required. Otherwise, return value is
5644 a list with action as CAR and a list of interactive export
5645 options as CDR."
5646 (let (key)
5647 ;; Scrolling: when in non-expert mode, act on motion keys (C-n,
5648 ;; C-p, SPC, DEL).
5649 (while (and (setq key (read-char-exclusive prompt))
5650 (not expertp)
5651 (memq key '(14 16 ?\s ?\d)))
5652 (case key
5653 (14 (if (not (pos-visible-in-window-p (point-max)))
5654 (ignore-errors (scroll-up-line))
5655 (message "End of buffer")
5656 (sit-for 1)))
5657 (16 (if (not (pos-visible-in-window-p (point-min)))
5658 (ignore-errors (scroll-down-line))
5659 (message "Beginning of buffer")
5660 (sit-for 1)))
5661 (?\s (if (not (pos-visible-in-window-p (point-max)))
5662 (scroll-up nil)
5663 (message "End of buffer")
5664 (sit-for 1)))
5665 (?\d (if (not (pos-visible-in-window-p (point-min)))
5666 (scroll-down nil)
5667 (message "Beginning of buffer")
5668 (sit-for 1)))))
5669 (cond
5670 ;; Ignore undefined associations.
5671 ((not (memq key allowed-keys))
5672 (ding)
5673 (unless expertp (message "Invalid key") (sit-for 1))
5674 (org-export--dispatch-ui options first-key expertp))
5675 ;; q key at first level aborts export. At second
5676 ;; level, cancel first key instead.
5677 ((eq key ?q) (if (not first-key) (error "Export aborted")
5678 (org-export--dispatch-ui options nil expertp)))
5679 ;; Help key: Switch back to standard interface if
5680 ;; expert UI was active.
5681 ((eq key ??) (org-export--dispatch-ui options first-key nil))
5682 ;; Switch to asynchronous export stack.
5683 ((eq key ?&) '(stack))
5684 ;; Toggle export options
5685 ;; C-b (2) C-v (22) C-s (19) C-f (6) C-a (1)
5686 ((memq key '(2 22 19 6 1))
5687 (org-export--dispatch-ui
5688 (let ((option (case key (2 'body) (22 'visible) (19 'subtree)
5689 (6 'force) (1 'async))))
5690 (if (memq option options) (remq option options)
5691 (cons option options)))
5692 first-key expertp))
5693 ;; Action selected: Send key and options back to
5694 ;; `org-export-dispatch'.
5695 ((or first-key (functionp (nth 2 (assq key backends))))
5696 (cons (cond
5697 ((not first-key) (nth 2 (assq key backends)))
5698 ;; Publishing actions are hard-coded. Send a special
5699 ;; signal to `org-export-dispatch'.
5700 ((eq first-key ?P)
5701 (case key
5702 (?f 'publish-current-file)
5703 (?p 'publish-current-project)
5704 (?x 'publish-choose-project)
5705 (?a 'publish-all)))
5706 ;; Return first action associated to FIRST-KEY + KEY
5707 ;; path. Indeed, derived backends can share the same
5708 ;; FIRST-KEY.
5709 (t (catch 'found
5710 (mapc (lambda (backend)
5711 (let ((match (assq key (nth 2 backend))))
5712 (when match (throw 'found (nth 2 match)))))
5713 (member (assq first-key backends) backends)))))
5714 options))
5715 ;; Otherwise, enter sub-menu.
5716 (t (org-export--dispatch-ui options key expertp)))))
5720 (provide 'ox)
5722 ;; Local variables:
5723 ;; generated-autoload-file: "org-loaddefs.el"
5724 ;; End:
5726 ;;; ox.el ends here