Add :version and :package-version
[org-mode.git] / lisp / ox.el
blob3a0764d58f2b87d7f4b807519fb2e49588449b17
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 :type '(choice
393 (const :tag "All drawers" t)
394 (const :tag "None" nil)
395 (repeat :tag "Selected drawers"
396 (string :tag "Drawer name"))
397 (list :tag "Ignored drawers"
398 (const :format "" not)
399 (repeat :tag "Specify names of drawers to ignore during export"
400 :inline t
401 (string :tag "Drawer name")))))
403 (defcustom org-export-with-email nil
404 "Non-nil means insert author email into the exported file.
405 This option can also be set with the #+OPTIONS line,
406 e.g. \"email:t\"."
407 :group 'org-export-general
408 :type 'boolean)
410 (defcustom org-export-with-emphasize t
411 "Non-nil means interpret *word*, /word/, _word_ and +word+.
413 If the export target supports emphasizing text, the word will be
414 typeset in bold, italic, with an underline or strike-through,
415 respectively.
417 This option can also be set with the #+OPTIONS line, e.g. \"*:nil\"."
418 :group 'org-export-general
419 :type 'boolean)
421 (defcustom org-export-exclude-tags '("noexport")
422 "Tags that exclude a tree from export.
424 All trees carrying any of these tags will be excluded from
425 export. This is without condition, so even subtrees inside that
426 carry one of the `org-export-select-tags' will be removed.
428 This option can also be set with the #+EXCLUDE_TAGS: keyword."
429 :group 'org-export-general
430 :type '(repeat (string :tag "Tag")))
432 (defcustom org-export-with-fixed-width t
433 "Non-nil means lines starting with \":\" will be in fixed width font.
435 This can be used to have pre-formatted text, fragments of code
436 etc. For example:
437 : ;; Some Lisp examples
438 : (while (defc cnt)
439 : (ding))
440 will be looking just like this in also HTML. See also the QUOTE
441 keyword. Not all export backends support this.
443 This option can also be set with the #+OPTIONS line, e.g. \"::nil\"."
444 :group 'org-export-general
445 :type 'boolean)
447 (defcustom org-export-with-footnotes t
448 "Non-nil means Org footnotes should be exported.
449 This option can also be set with the #+OPTIONS line,
450 e.g. \"f:nil\"."
451 :group 'org-export-general
452 :type 'boolean)
454 (defcustom org-export-with-latex t
455 "Non-nil means process LaTeX environments and fragments.
457 This option can also be set with the +OPTIONS line,
458 e.g. \"tex:verbatim\". Allowed values are:
460 nil Ignore math snippets.
461 `verbatim' Keep everything in verbatim.
462 t Allow export of math snippets."
463 :group 'org-export-general
464 :type '(choice
465 (const :tag "Do not process math in any way" nil)
466 (const :tag "Interpret math snippets" t)
467 (const :tag "Leave math verbatim" verbatim)))
469 (defcustom org-export-headline-levels 3
470 "The last level which is still exported as a headline.
472 Inferior levels will produce itemize or enumerate lists when
473 exported.
475 This option can also be set with the #+OPTIONS line, e.g. \"H:2\"."
476 :group 'org-export-general
477 :type 'integer)
479 (defcustom org-export-default-language "en"
480 "The default language for export and clocktable translations, as a string.
481 This may have an association in
482 `org-clock-clocktable-language-setup'."
483 :group 'org-export-general
484 :type '(string :tag "Language"))
486 (defcustom org-export-preserve-breaks nil
487 "Non-nil means preserve all line breaks when exporting.
488 This option can also be set with the #+OPTIONS line,
489 e.g. \"\\n:t\"."
490 :group 'org-export-general
491 :type 'boolean)
493 (defcustom org-export-with-entities t
494 "Non-nil means interpret entities when exporting.
496 For example, HTML export converts \\alpha to &alpha; and \\AA to
497 &Aring;.
499 For a list of supported names, see the constant `org-entities'
500 and the user option `org-entities-user'.
502 This option can also be set with the #+OPTIONS line,
503 e.g. \"e:nil\"."
504 :group 'org-export-general
505 :type 'boolean)
507 (defcustom org-export-with-inlinetasks t
508 "Non-nil means inlinetasks should be exported.
509 This option can also be set with the #+OPTIONS line,
510 e.g. \"inline:nil\"."
511 :group 'org-export-general
512 :type 'boolean)
514 (defcustom org-export-with-planning nil
515 "Non-nil means include planning info in export.
516 This option can also be set with the #+OPTIONS: line,
517 e.g. \"p:t\"."
518 :group 'org-export-general
519 :type 'boolean)
521 (defcustom org-export-with-priority nil
522 "Non-nil means include priority cookies in export.
523 This option can also be set with the #+OPTIONS line,
524 e.g. \"pri:t\"."
525 :group 'org-export-general
526 :type 'boolean)
528 (defcustom org-export-with-section-numbers t
529 "Non-nil means add section numbers to headlines when exporting.
531 When set to an integer n, numbering will only happen for
532 headlines whose relative level is higher or equal to n.
534 This option can also be set with the #+OPTIONS line,
535 e.g. \"num:t\"."
536 :group 'org-export-general
537 :type 'boolean)
539 (defcustom org-export-select-tags '("export")
540 "Tags that select a tree for export.
542 If any such tag is found in a buffer, all trees that do not carry
543 one of these tags will be ignored during export. Inside trees
544 that are selected like this, you can still deselect a subtree by
545 tagging it with one of the `org-export-exclude-tags'.
547 This option can also be set with the #+SELECT_TAGS: keyword."
548 :group 'org-export-general
549 :type '(repeat (string :tag "Tag")))
551 (defcustom org-export-with-smart-quotes nil
552 "Non-nil means activate smart quotes during export.
553 This option can also be set with the #+OPTIONS: line,
554 e.g. \"':t\"."
555 :group 'org-export-general
556 :type 'boolean)
558 (defcustom org-export-with-special-strings t
559 "Non-nil means interpret \"\\-\", \"--\" and \"---\" for export.
561 When this option is turned on, these strings will be exported as:
563 Org HTML LaTeX UTF-8
564 -----+----------+--------+-------
565 \\- &shy; \\-
566 -- &ndash; -- –
567 --- &mdash; --- —
568 ... &hellip; \\ldots …
570 This option can also be set with the #+OPTIONS line,
571 e.g. \"-:nil\"."
572 :group 'org-export-general
573 :type 'boolean)
575 (defcustom org-export-with-statistics-cookies t
576 "Non-nil means include statistics cookies in export.
577 This option can also be set with the #+OPTIONS: line,
578 e.g. \"stat:nil\""
579 :group 'org-export-general
580 :type 'boolean)
582 (defcustom org-export-with-sub-superscripts t
583 "Non-nil means interpret \"_\" and \"^\" for export.
585 When this option is turned on, you can use TeX-like syntax for
586 sub- and superscripts. Several characters after \"_\" or \"^\"
587 will be considered as a single item - so grouping with {} is
588 normally not needed. For example, the following things will be
589 parsed as single sub- or superscripts.
591 10^24 or 10^tau several digits will be considered 1 item.
592 10^-12 or 10^-tau a leading sign with digits or a word
593 x^2-y^3 will be read as x^2 - y^3, because items are
594 terminated by almost any nonword/nondigit char.
595 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
597 Still, ambiguity is possible - so when in doubt use {} to enclose
598 the sub/superscript. If you set this variable to the symbol
599 `{}', the braces are *required* in order to trigger
600 interpretations as sub/superscript. This can be helpful in
601 documents that need \"_\" frequently in plain text.
603 This option can also be set with the #+OPTIONS line,
604 e.g. \"^:nil\"."
605 :group 'org-export-general
606 :type '(choice
607 (const :tag "Interpret them" t)
608 (const :tag "Curly brackets only" {})
609 (const :tag "Do not interpret them" nil)))
611 (defcustom org-export-with-toc t
612 "Non-nil means create a table of contents in exported files.
614 The TOC contains headlines with levels up
615 to`org-export-headline-levels'. When an integer, include levels
616 up to N in the toc, this may then be different from
617 `org-export-headline-levels', but it will not be allowed to be
618 larger than the number of headline levels. When nil, no table of
619 contents is made.
621 This option can also be set with the #+OPTIONS line,
622 e.g. \"toc:nil\" or \"toc:3\"."
623 :group 'org-export-general
624 :type '(choice
625 (const :tag "No Table of Contents" nil)
626 (const :tag "Full Table of Contents" t)
627 (integer :tag "TOC to level")))
629 (defcustom org-export-with-tables t
630 "If non-nil, lines starting with \"|\" define a table.
631 For example:
633 | Name | Address | Birthday |
634 |-------------+----------+-----------|
635 | Arthur Dent | England | 29.2.2100 |
637 This option can also be set with the #+OPTIONS line, e.g. \"|:nil\"."
638 :group 'org-export-general
639 :type 'boolean)
641 (defcustom org-export-with-tags t
642 "If nil, do not export tags, just remove them from headlines.
644 If this is the symbol `not-in-toc', tags will be removed from
645 table of contents entries, but still be shown in the headlines of
646 the document.
648 This option can also be set with the #+OPTIONS line,
649 e.g. \"tags:nil\"."
650 :group 'org-export-general
651 :type '(choice
652 (const :tag "Off" nil)
653 (const :tag "Not in TOC" not-in-toc)
654 (const :tag "On" t)))
656 (defcustom org-export-with-tasks t
657 "Non-nil means include TODO items for export.
659 This may have the following values:
660 t include tasks independent of state.
661 `todo' include only tasks that are not yet done.
662 `done' include only tasks that are already done.
663 nil ignore all tasks.
664 list of keywords include tasks with these keywords.
666 This option can also be set with the #+OPTIONS line,
667 e.g. \"tasks:nil\"."
668 :group 'org-export-general
669 :type '(choice
670 (const :tag "All tasks" t)
671 (const :tag "No tasks" nil)
672 (const :tag "Not-done tasks" todo)
673 (const :tag "Only done tasks" done)
674 (repeat :tag "Specific TODO keywords"
675 (string :tag "Keyword"))))
677 (defcustom org-export-time-stamp-file t
678 "Non-nil means insert a time stamp into the exported file.
679 The time stamp shows when the file was created.
681 This option can also be set with the #+OPTIONS line,
682 e.g. \"timestamp:nil\"."
683 :group 'org-export-general
684 :type 'boolean)
686 (defcustom org-export-with-timestamps t
687 "Non nil means allow timestamps in export.
689 It can be set to `active', `inactive', t or nil, in order to
690 export, respectively, only active timestamps, only inactive ones,
691 all of them or none.
693 This option can also be set with the #+OPTIONS line, e.g.
694 \"<:nil\"."
695 :group 'org-export-general
696 :type '(choice
697 (const :tag "All timestamps" t)
698 (const :tag "Only active timestamps" active)
699 (const :tag "Only inactive timestamps" inactive)
700 (const :tag "No timestamp" nil)))
702 (defcustom org-export-with-todo-keywords t
703 "Non-nil means include TODO keywords in export.
704 When nil, remove all these keywords from the export."
705 :group 'org-export-general
706 :type 'boolean)
708 (defcustom org-export-allow-bind-keywords nil
709 "Non-nil means BIND keywords can define local variable values.
710 This is a potential security risk, which is why the default value
711 is nil. You can also allow them through local buffer variables."
712 :group 'org-export-general
713 :type 'boolean)
715 (defcustom org-export-snippet-translation-alist nil
716 "Alist between export snippets back-ends and exporter back-ends.
718 This variable allows to provide shortcuts for export snippets.
720 For example, with a value of '\(\(\"h\" . \"html\"\)\), the
721 HTML back-end will recognize the contents of \"@@h:<b>@@\" as
722 HTML code while every other back-end will ignore it."
723 :group 'org-export-general
724 :version "24.4"
725 :package-version '(Org . "8.0")
726 :type '(repeat
727 (cons (string :tag "Shortcut")
728 (string :tag "Back-end"))))
730 (defcustom org-export-coding-system nil
731 "Coding system for the exported file."
732 :group 'org-export-general
733 :version "24.4"
734 :package-version '(Org . "8.0")
735 :type 'coding-system)
737 (defcustom org-export-copy-to-kill-ring t
738 "Non-nil means exported stuff will also be pushed onto the kill ring."
739 :group 'org-export-general
740 :type 'boolean)
742 (defcustom org-export-initial-scope 'buffer
743 "The initial scope when exporting with `org-export-dispatch'.
744 This variable can be either set to `buffer' or `subtree'."
745 :group 'org-export-general
746 :type '(choice
747 (const :tag "Export current buffer" 'buffer)
748 (const :tag "Export current subtree" 'subtree)))
750 (defcustom org-export-show-temporary-export-buffer t
751 "Non-nil means show buffer after exporting to temp buffer.
752 When Org exports to a file, the buffer visiting that file is ever
753 shown, but remains buried. However, when exporting to
754 a temporary buffer, that buffer is popped up in a second window.
755 When this variable is nil, the buffer remains buried also in
756 these cases."
757 :group 'org-export-general
758 :type 'boolean)
760 (defcustom org-export-in-background nil
761 "Non-nil means export and publishing commands will run in background.
762 Results from an asynchronous export are never displayed
763 automatically. But you can retrieve them with \\[org-export-stack]."
764 :group 'org-export-general
765 :version "24.4"
766 :package-version '(Org . "8.0")
767 :type 'boolean)
769 (defcustom org-export-async-init-file user-init-file
770 "File used to initialize external export process.
771 Value must be an absolute file name. It defaults to user's
772 initialization file. Though, a specific configuration makes the
773 process faster and the export more portable."
774 :group 'org-export-general
775 :version "24.4"
776 :package-version '(Org . "8.0")
777 :type '(file :must-match t))
779 (defcustom org-export-invisible-backends nil
780 "List of back-ends that shouldn't appear in the dispatcher.
782 Any back-end belonging to this list or derived from a back-end
783 belonging to it will not appear in the dispatcher menu.
785 Indeed, Org may require some export back-ends without notice. If
786 these modules are never to be used interactively, adding them
787 here will avoid cluttering the dispatcher menu."
788 :group 'org-export-general
789 :version "24.4"
790 :package-version '(Org . "8.0")
791 :type '(repeat (symbol :tag "Back-End")))
793 (defcustom org-export-dispatch-use-expert-ui nil
794 "Non-nil means using a non-intrusive `org-export-dispatch'.
795 In that case, no help buffer is displayed. Though, an indicator
796 for current export scope is added to the prompt (\"b\" when
797 output is restricted to body only, \"s\" when it is restricted to
798 the current subtree, \"v\" when only visible elements are
799 considered for export, \"f\" when publishing functions should be
800 passed the FORCE argument and \"a\" when the export should be
801 asynchronous). Also, \[?] allows to switch back to standard
802 mode."
803 :group 'org-export-general
804 :version "24.4"
805 :package-version '(Org . "8.0")
806 :type 'boolean)
810 ;;; Defining Back-ends
812 ;; `org-export-define-backend' is the standard way to define an export
813 ;; back-end. It allows to specify translators, filters, buffer
814 ;; options and a menu entry. If the new back-end shares translators
815 ;; with another back-end, `org-export-define-derived-backend' may be
816 ;; used instead.
818 ;; Internally, a back-end is stored as a list, of which CAR is the
819 ;; name of the back-end, as a symbol, and CDR a plist. Accessors to
820 ;; properties of a given back-end are: `org-export-backend-filters',
821 ;; `org-export-backend-menu', `org-export-backend-options' and
822 ;; `org-export-backend-translate-table'.
824 ;; Eventually `org-export-barf-if-invalid-backend' returns an error
825 ;; when a given back-end hasn't been registered yet.
827 (defmacro org-export-define-backend (backend translators &rest body)
828 "Define a new back-end BACKEND.
830 TRANSLATORS is an alist between object or element types and
831 functions handling them.
833 These functions should return a string without any trailing
834 space, or nil. They must accept three arguments: the object or
835 element itself, its contents or nil when it isn't recursive and
836 the property list used as a communication channel.
838 Contents, when not nil, are stripped from any global indentation
839 \(although the relative one is preserved). They also always end
840 with a single newline character.
842 If, for a given type, no function is found, that element or
843 object type will simply be ignored, along with any blank line or
844 white space at its end. The same will happen if the function
845 returns the nil value. If that function returns the empty
846 string, the type will be ignored, but the blank lines or white
847 spaces will be kept.
849 In addition to element and object types, one function can be
850 associated to the `template' (or `inner-template') symbol and
851 another one to the `plain-text' symbol.
853 The former returns the final transcoded string, and can be used
854 to add a preamble and a postamble to document's body. It must
855 accept two arguments: the transcoded string and the property list
856 containing export options. A function associated to `template'
857 will not be applied if export has option \"body-only\".
858 A function associated to `inner-template' is always applied.
860 The latter, when defined, is to be called on every text not
861 recognized as an element or an object. It must accept two
862 arguments: the text string and the information channel. It is an
863 appropriate place to protect special chars relative to the
864 back-end.
866 BODY can start with pre-defined keyword arguments. The following
867 keywords are understood:
869 :export-block
871 String, or list of strings, representing block names that
872 will not be parsed. This is used to specify blocks that will
873 contain raw code specific to the back-end. These blocks
874 still have to be handled by the relative `export-block' type
875 translator.
877 :filters-alist
879 Alist between filters and function, or list of functions,
880 specific to the back-end. See `org-export-filters-alist' for
881 a list of all allowed filters. Filters defined here
882 shouldn't make a back-end test, as it may prevent back-ends
883 derived from this one to behave properly.
885 :menu-entry
887 Menu entry for the export dispatcher. It should be a list
888 like:
890 \(KEY DESCRIPTION-OR-ORDINAL ACTION-OR-MENU)
892 where :
894 KEY is a free character selecting the back-end.
896 DESCRIPTION-OR-ORDINAL is either a string or a number.
898 If it is a string, is will be used to name the back-end in
899 its menu entry. If it is a number, the following menu will
900 be displayed as a sub-menu of the back-end with the same
901 KEY. Also, the number will be used to determine in which
902 order such sub-menus will appear (lowest first).
904 ACTION-OR-MENU is either a function or an alist.
906 If it is an action, it will be called with four
907 arguments (booleans): ASYNC, SUBTREEP, VISIBLE-ONLY and
908 BODY-ONLY. See `org-export-as' for further explanations on
909 some of them.
911 If it is an alist, associations should follow the
912 pattern:
914 \(KEY DESCRIPTION ACTION)
916 where KEY, DESCRIPTION and ACTION are described above.
918 Valid values include:
920 \(?m \"My Special Back-end\" my-special-export-function)
924 \(?l \"Export to LaTeX\"
925 \(?p \"As PDF file\" org-latex-export-to-pdf)
926 \(?o \"As PDF file and open\"
927 \(lambda (a s v b)
928 \(if a (org-latex-export-to-pdf t s v b)
929 \(org-open-file
930 \(org-latex-export-to-pdf nil s v b)))))))
932 or the following, which will be added to the previous
933 sub-menu,
935 \(?l 1
936 \((?B \"As TEX buffer (Beamer)\" org-beamer-export-as-latex)
937 \(?P \"As PDF file (Beamer)\" org-beamer-export-to-pdf)))
939 :options-alist
941 Alist between back-end specific properties introduced in
942 communication channel and how their value are acquired. See
943 `org-export-options-alist' for more information about
944 structure of the values."
945 (declare (debug (&define name sexp [&rest [keywordp sexp]] defbody))
946 (indent 1))
947 (let (export-block filters menu-entry options contents)
948 (while (keywordp (car body))
949 (case (pop body)
950 (:export-block (let ((names (pop body)))
951 (setq export-block
952 (if (consp names) (mapcar 'upcase names)
953 (list (upcase names))))))
954 (:filters-alist (setq filters (pop body)))
955 (:menu-entry (setq menu-entry (pop body)))
956 (:options-alist (setq options (pop body)))
957 (t (pop body))))
958 (setq contents (append (list :translate-alist translators)
959 (and filters (list :filters-alist filters))
960 (and options (list :options-alist options))
961 (and menu-entry (list :menu-entry menu-entry))))
962 `(progn
963 ;; Register back-end.
964 (let ((registeredp (assq ',backend org-export-registered-backends)))
965 (if registeredp (setcdr registeredp ',contents)
966 (push (cons ',backend ',contents) org-export-registered-backends)))
967 ;; Tell parser to not parse EXPORT-BLOCK blocks.
968 ,(when export-block
969 `(mapc
970 (lambda (name)
971 (add-to-list 'org-element-block-name-alist
972 `(,name . org-element-export-block-parser)))
973 ',export-block))
974 ;; Splice in the body, if any.
975 ,@body)))
977 (defmacro org-export-define-derived-backend (child parent &rest body)
978 "Create a new back-end as a variant of an existing one.
980 CHILD is the name of the derived back-end. PARENT is the name of
981 the parent back-end.
983 BODY can start with pre-defined keyword arguments. The following
984 keywords are understood:
986 :export-block
988 String, or list of strings, representing block names that
989 will not be parsed. This is used to specify blocks that will
990 contain raw code specific to the back-end. These blocks
991 still have to be handled by the relative `export-block' type
992 translator.
994 :filters-alist
996 Alist of filters that will overwrite or complete filters
997 defined in PARENT back-end. See `org-export-filters-alist'
998 for a list of allowed filters.
1000 :menu-entry
1002 Menu entry for the export dispatcher. See
1003 `org-export-define-backend' for more information about the
1004 expected value.
1006 :options-alist
1008 Alist of back-end specific properties that will overwrite or
1009 complete those defined in PARENT back-end. Refer to
1010 `org-export-options-alist' for more information about
1011 structure of the values.
1013 :translate-alist
1015 Alist of element and object types and transcoders that will
1016 overwrite or complete transcode table from PARENT back-end.
1017 Refer to `org-export-define-backend' for detailed information
1018 about transcoders.
1020 As an example, here is how one could define \"my-latex\" back-end
1021 as a variant of `latex' back-end with a custom template function:
1023 \(org-export-define-derived-backend my-latex latex
1024 :translate-alist ((template . my-latex-template-fun)))
1026 The back-end could then be called with, for example:
1028 \(org-export-to-buffer 'my-latex \"*Test my-latex*\")"
1029 (declare (debug (&define name sexp [&rest [keywordp sexp]] def-body))
1030 (indent 2))
1031 (let (export-block filters menu-entry options translators contents)
1032 (while (keywordp (car body))
1033 (case (pop body)
1034 (:export-block (let ((names (pop body)))
1035 (setq export-block
1036 (if (consp names) (mapcar 'upcase names)
1037 (list (upcase names))))))
1038 (:filters-alist (setq filters (pop body)))
1039 (:menu-entry (setq menu-entry (pop body)))
1040 (:options-alist (setq options (pop body)))
1041 (:translate-alist (setq translators (pop body)))
1042 (t (pop body))))
1043 (setq contents (append
1044 (list :parent parent)
1045 (let ((p-table (org-export-backend-translate-table parent)))
1046 (list :translate-alist (append translators p-table)))
1047 (let ((p-filters (org-export-backend-filters parent)))
1048 (list :filters-alist (append filters p-filters)))
1049 (let ((p-options (org-export-backend-options parent)))
1050 (list :options-alist (append options p-options)))
1051 (and menu-entry (list :menu-entry menu-entry))))
1052 `(progn
1053 (org-export-barf-if-invalid-backend ',parent)
1054 ;; Register back-end.
1055 (let ((registeredp (assq ',child org-export-registered-backends)))
1056 (if registeredp (setcdr registeredp ',contents)
1057 (push (cons ',child ',contents) org-export-registered-backends)))
1058 ;; Tell parser to not parse EXPORT-BLOCK blocks.
1059 ,(when export-block
1060 `(mapc
1061 (lambda (name)
1062 (add-to-list 'org-element-block-name-alist
1063 `(,name . org-element-export-block-parser)))
1064 ',export-block))
1065 ;; Splice in the body, if any.
1066 ,@body)))
1068 (defun org-export-backend-parent (backend)
1069 "Return back-end from which BACKEND is derived, or nil."
1070 (plist-get (cdr (assq backend org-export-registered-backends)) :parent))
1072 (defun org-export-backend-filters (backend)
1073 "Return filters for BACKEND."
1074 (plist-get (cdr (assq backend org-export-registered-backends))
1075 :filters-alist))
1077 (defun org-export-backend-menu (backend)
1078 "Return menu entry for BACKEND."
1079 (plist-get (cdr (assq backend org-export-registered-backends))
1080 :menu-entry))
1082 (defun org-export-backend-options (backend)
1083 "Return export options for BACKEND."
1084 (plist-get (cdr (assq backend org-export-registered-backends))
1085 :options-alist))
1087 (defun org-export-backend-translate-table (backend)
1088 "Return translate table for BACKEND."
1089 (plist-get (cdr (assq backend org-export-registered-backends))
1090 :translate-alist))
1092 (defun org-export-barf-if-invalid-backend (backend)
1093 "Signal an error if BACKEND isn't defined."
1094 (unless (org-export-backend-translate-table backend)
1095 (error "Unknown \"%s\" back-end: Aborting export" backend)))
1097 (defun org-export-derived-backend-p (backend &rest backends)
1098 "Non-nil if BACKEND is derived from one of BACKENDS."
1099 (let ((parent backend))
1100 (while (and (not (memq parent backends))
1101 (setq parent (org-export-backend-parent parent))))
1102 parent))
1106 ;;; The Communication Channel
1108 ;; During export process, every function has access to a number of
1109 ;; properties. They are of two types:
1111 ;; 1. Environment options are collected once at the very beginning of
1112 ;; the process, out of the original buffer and configuration.
1113 ;; Collecting them is handled by `org-export-get-environment'
1114 ;; function.
1116 ;; Most environment options are defined through the
1117 ;; `org-export-options-alist' variable.
1119 ;; 2. Tree properties are extracted directly from the parsed tree,
1120 ;; just before export, by `org-export-collect-tree-properties'.
1122 ;; Here is the full list of properties available during transcode
1123 ;; process, with their category and their value type.
1125 ;; + `:author' :: Author's name.
1126 ;; - category :: option
1127 ;; - type :: string
1129 ;; + `:back-end' :: Current back-end used for transcoding.
1130 ;; - category :: tree
1131 ;; - type :: symbol
1133 ;; + `:creator' :: String to write as creation information.
1134 ;; - category :: option
1135 ;; - type :: string
1137 ;; + `:date' :: String to use as date.
1138 ;; - category :: option
1139 ;; - type :: string
1141 ;; + `:description' :: Description text for the current data.
1142 ;; - category :: option
1143 ;; - type :: string
1145 ;; + `:email' :: Author's email.
1146 ;; - category :: option
1147 ;; - type :: string
1149 ;; + `:exclude-tags' :: Tags for exclusion of subtrees from export
1150 ;; process.
1151 ;; - category :: option
1152 ;; - type :: list of strings
1154 ;; + `:export-options' :: List of export options available for current
1155 ;; process.
1156 ;; - category :: none
1157 ;; - type :: list of symbols, among `subtree', `body-only' and
1158 ;; `visible-only'.
1160 ;; + `:exported-data' :: Hash table used for memoizing
1161 ;; `org-export-data'.
1162 ;; - category :: tree
1163 ;; - type :: hash table
1165 ;; + `:filetags' :: List of global tags for buffer. Used by
1166 ;; `org-export-get-tags' to get tags with inheritance.
1167 ;; - category :: option
1168 ;; - type :: list of strings
1170 ;; + `:footnote-definition-alist' :: Alist between footnote labels and
1171 ;; their definition, as parsed data. Only non-inlined footnotes
1172 ;; are represented in this alist. Also, every definition isn't
1173 ;; guaranteed to be referenced in the parse tree. The purpose of
1174 ;; this property is to preserve definitions from oblivion
1175 ;; (i.e. when the parse tree comes from a part of the original
1176 ;; buffer), it isn't meant for direct use in a back-end. To
1177 ;; retrieve a definition relative to a reference, use
1178 ;; `org-export-get-footnote-definition' instead.
1179 ;; - category :: option
1180 ;; - type :: alist (STRING . LIST)
1182 ;; + `:headline-levels' :: Maximum level being exported as an
1183 ;; headline. Comparison is done with the relative level of
1184 ;; headlines in the parse tree, not necessarily with their
1185 ;; actual level.
1186 ;; - category :: option
1187 ;; - type :: integer
1189 ;; + `:headline-offset' :: Difference between relative and real level
1190 ;; of headlines in the parse tree. For example, a value of -1
1191 ;; means a level 2 headline should be considered as level
1192 ;; 1 (cf. `org-export-get-relative-level').
1193 ;; - category :: tree
1194 ;; - type :: integer
1196 ;; + `:headline-numbering' :: Alist between headlines and their
1197 ;; numbering, as a list of numbers
1198 ;; (cf. `org-export-get-headline-number').
1199 ;; - category :: tree
1200 ;; - type :: alist (INTEGER . LIST)
1202 ;; + `:id-alist' :: Alist between ID strings and destination file's
1203 ;; path, relative to current directory. It is used by
1204 ;; `org-export-resolve-id-link' to resolve ID links targeting an
1205 ;; external file.
1206 ;; - category :: option
1207 ;; - type :: alist (STRING . STRING)
1209 ;; + `:ignore-list' :: List of elements and objects that should be
1210 ;; ignored during export.
1211 ;; - category :: tree
1212 ;; - type :: list of elements and objects
1214 ;; + `:input-file' :: Full path to input file, if any.
1215 ;; - category :: option
1216 ;; - type :: string or nil
1218 ;; + `:keywords' :: List of keywords attached to data.
1219 ;; - category :: option
1220 ;; - type :: string
1222 ;; + `:language' :: Default language used for translations.
1223 ;; - category :: option
1224 ;; - type :: string
1226 ;; + `:parse-tree' :: Whole parse tree, available at any time during
1227 ;; transcoding.
1228 ;; - category :: option
1229 ;; - type :: list (as returned by `org-element-parse-buffer')
1231 ;; + `:preserve-breaks' :: Non-nil means transcoding should preserve
1232 ;; all line breaks.
1233 ;; - category :: option
1234 ;; - type :: symbol (nil, t)
1236 ;; + `:section-numbers' :: Non-nil means transcoding should add
1237 ;; section numbers to headlines.
1238 ;; - category :: option
1239 ;; - type :: symbol (nil, t)
1241 ;; + `:select-tags' :: List of tags enforcing inclusion of sub-trees
1242 ;; in transcoding. When such a tag is present, subtrees without
1243 ;; it are de facto excluded from the process. See
1244 ;; `use-select-tags'.
1245 ;; - category :: option
1246 ;; - type :: list of strings
1248 ;; + `:time-stamp-file' :: Non-nil means transcoding should insert
1249 ;; a time stamp in the output.
1250 ;; - category :: option
1251 ;; - type :: symbol (nil, t)
1253 ;; + `:translate-alist' :: Alist between element and object types and
1254 ;; transcoding functions relative to the current back-end.
1255 ;; Special keys `inner-template', `template' and `plain-text' are
1256 ;; also possible.
1257 ;; - category :: option
1258 ;; - type :: alist (SYMBOL . FUNCTION)
1260 ;; + `:with-archived-trees' :: Non-nil when archived subtrees should
1261 ;; also be transcoded. If it is set to the `headline' symbol,
1262 ;; only the archived headline's name is retained.
1263 ;; - category :: option
1264 ;; - type :: symbol (nil, t, `headline')
1266 ;; + `:with-author' :: Non-nil means author's name should be included
1267 ;; in the output.
1268 ;; - category :: option
1269 ;; - type :: symbol (nil, t)
1271 ;; + `:with-clocks' :: Non-nil means clock keywords should be exported.
1272 ;; - category :: option
1273 ;; - type :: symbol (nil, t)
1275 ;; + `:with-creator' :: Non-nil means a creation sentence should be
1276 ;; inserted at the end of the transcoded string. If the value
1277 ;; is `comment', it should be commented.
1278 ;; - category :: option
1279 ;; - type :: symbol (`comment', nil, t)
1281 ;; + `:with-date' :: Non-nil means output should contain a date.
1282 ;; - category :: option
1283 ;; - type :. symbol (nil, t)
1285 ;; + `:with-drawers' :: Non-nil means drawers should be exported. If
1286 ;; its value is a list of names, only drawers with such names
1287 ;; will be transcoded. If that list starts with `not', drawer
1288 ;; with these names will be skipped.
1289 ;; - category :: option
1290 ;; - type :: symbol (nil, t) or list of strings
1292 ;; + `:with-email' :: Non-nil means output should contain author's
1293 ;; email.
1294 ;; - category :: option
1295 ;; - type :: symbol (nil, t)
1297 ;; + `:with-emphasize' :: Non-nil means emphasized text should be
1298 ;; interpreted.
1299 ;; - category :: option
1300 ;; - type :: symbol (nil, t)
1302 ;; + `:with-fixed-width' :: Non-nil if transcoder should interpret
1303 ;; strings starting with a colon as a fixed-with (verbatim) area.
1304 ;; - category :: option
1305 ;; - type :: symbol (nil, t)
1307 ;; + `:with-footnotes' :: Non-nil if transcoder should interpret
1308 ;; footnotes.
1309 ;; - category :: option
1310 ;; - type :: symbol (nil, t)
1312 ;; + `:with-latex' :: Non-nil means `latex-environment' elements and
1313 ;; `latex-fragment' objects should appear in export output. When
1314 ;; this property is set to `verbatim', they will be left as-is.
1315 ;; - category :: option
1316 ;; - type :: symbol (`verbatim', nil, t)
1318 ;; + `:with-plannings' :: Non-nil means transcoding should include
1319 ;; planning info.
1320 ;; - category :: option
1321 ;; - type :: symbol (nil, t)
1323 ;; + `:with-priority' :: Non-nil means transcoding should include
1324 ;; priority cookies.
1325 ;; - category :: option
1326 ;; - type :: symbol (nil, t)
1328 ;; + `:with-smart-quotes' :: Non-nil means activate smart quotes in
1329 ;; plain text.
1330 ;; - category :: option
1331 ;; - type :: symbol (nil, t)
1333 ;; + `:with-special-strings' :: Non-nil means transcoding should
1334 ;; interpret special strings in plain text.
1335 ;; - category :: option
1336 ;; - type :: symbol (nil, t)
1338 ;; + `:with-sub-superscript' :: Non-nil means transcoding should
1339 ;; interpret subscript and superscript. With a value of "{}",
1340 ;; only interpret those using curly brackets.
1341 ;; - category :: option
1342 ;; - type :: symbol (nil, {}, t)
1344 ;; + `:with-tables' :: Non-nil means transcoding should interpret
1345 ;; tables.
1346 ;; - category :: option
1347 ;; - type :: symbol (nil, t)
1349 ;; + `:with-tags' :: Non-nil means transcoding should keep tags in
1350 ;; headlines. A `not-in-toc' value will remove them from the
1351 ;; table of contents, if any, nonetheless.
1352 ;; - category :: option
1353 ;; - type :: symbol (nil, t, `not-in-toc')
1355 ;; + `:with-tasks' :: Non-nil means transcoding should include
1356 ;; headlines with a TODO keyword. A `todo' value will only
1357 ;; include headlines with a todo type keyword while a `done'
1358 ;; value will do the contrary. If a list of strings is provided,
1359 ;; only tasks with keywords belonging to that list will be kept.
1360 ;; - category :: option
1361 ;; - type :: symbol (t, todo, done, nil) or list of strings
1363 ;; + `:with-timestamps' :: Non-nil means transcoding should include
1364 ;; time stamps. Special value `active' (resp. `inactive') ask to
1365 ;; export only active (resp. inactive) timestamps. Otherwise,
1366 ;; completely remove them.
1367 ;; - category :: option
1368 ;; - type :: symbol: (`active', `inactive', t, nil)
1370 ;; + `:with-toc' :: Non-nil means that a table of contents has to be
1371 ;; added to the output. An integer value limits its depth.
1372 ;; - category :: option
1373 ;; - type :: symbol (nil, t or integer)
1375 ;; + `:with-todo-keywords' :: Non-nil means transcoding should
1376 ;; include TODO keywords.
1377 ;; - category :: option
1378 ;; - type :: symbol (nil, t)
1381 ;;;; Environment Options
1383 ;; Environment options encompass all parameters defined outside the
1384 ;; scope of the parsed data. They come from five sources, in
1385 ;; increasing precedence order:
1387 ;; - Global variables,
1388 ;; - Buffer's attributes,
1389 ;; - Options keyword symbols,
1390 ;; - Buffer keywords,
1391 ;; - Subtree properties.
1393 ;; The central internal function with regards to environment options
1394 ;; is `org-export-get-environment'. It updates global variables with
1395 ;; "#+BIND:" keywords, then retrieve and prioritize properties from
1396 ;; the different sources.
1398 ;; The internal functions doing the retrieval are:
1399 ;; `org-export--get-global-options',
1400 ;; `org-export--get-buffer-attributes',
1401 ;; `org-export--parse-option-keyword',
1402 ;; `org-export--get-subtree-options' and
1403 ;; `org-export--get-inbuffer-options'
1405 ;; Also, `org-export--install-letbind-maybe' takes care of the part
1406 ;; relative to "#+BIND:" keywords.
1408 (defun org-export-get-environment (&optional backend subtreep ext-plist)
1409 "Collect export options from the current buffer.
1411 Optional argument BACKEND is a symbol specifying which back-end
1412 specific options to read, if any.
1414 When optional argument SUBTREEP is non-nil, assume the export is
1415 done against the current sub-tree.
1417 Third optional argument EXT-PLIST is a property list with
1418 external parameters overriding Org default settings, but still
1419 inferior to file-local settings."
1420 ;; First install #+BIND variables.
1421 (org-export--install-letbind-maybe)
1422 ;; Get and prioritize export options...
1423 (org-combine-plists
1424 ;; ... from global variables...
1425 (org-export--get-global-options backend)
1426 ;; ... from an external property list...
1427 ext-plist
1428 ;; ... from in-buffer settings...
1429 (org-export--get-inbuffer-options backend)
1430 ;; ... and from subtree, when appropriate.
1431 (and subtreep (org-export--get-subtree-options backend))
1432 ;; Eventually add misc. properties.
1433 (list
1434 :back-end
1435 backend
1436 :translate-alist
1437 (org-export-backend-translate-table backend)
1438 :footnote-definition-alist
1439 ;; Footnotes definitions must be collected in the original
1440 ;; buffer, as there's no insurance that they will still be in
1441 ;; the parse tree, due to possible narrowing.
1442 (let (alist)
1443 (org-with-wide-buffer
1444 (goto-char (point-min))
1445 (while (re-search-forward org-footnote-definition-re nil t)
1446 (let ((def (save-match-data (org-element-at-point))))
1447 (when (eq (org-element-type def) 'footnote-definition)
1448 (push
1449 (cons (org-element-property :label def)
1450 (let ((cbeg (org-element-property :contents-begin def)))
1451 (when cbeg
1452 (org-element--parse-elements
1453 cbeg (org-element-property :contents-end def)
1454 nil nil nil nil (list 'org-data nil)))))
1455 alist))))
1456 alist))
1457 :id-alist
1458 ;; Collect id references.
1459 (let (alist)
1460 (org-with-wide-buffer
1461 (goto-char (point-min))
1462 (while (re-search-forward "\\[\\[id:\\S-+?\\]" nil t)
1463 (let ((link (org-element-context)))
1464 (when (eq (org-element-type link) 'link)
1465 (let* ((id (org-element-property :path link))
1466 (file (org-id-find-id-file id)))
1467 (when file
1468 (push (cons id (file-relative-name file)) alist)))))))
1469 alist))))
1471 (defun org-export--parse-option-keyword (options &optional backend)
1472 "Parse an OPTIONS line and return values as a plist.
1473 Optional argument BACKEND is a symbol specifying which back-end
1474 specific items to read, if any."
1475 (let* ((all
1476 ;; Priority is given to back-end specific options.
1477 (append (and backend (org-export-backend-options backend))
1478 org-export-options-alist))
1479 plist)
1480 (dolist (option all)
1481 (let ((property (car option))
1482 (item (nth 2 option)))
1483 (when (and item
1484 (not (plist-member plist property))
1485 (string-match (concat "\\(\\`\\|[ \t]\\)"
1486 (regexp-quote item)
1487 ":\\(([^)\n]+)\\|[^ \t\n\r;,.]*\\)")
1488 options))
1489 (setq plist (plist-put plist
1490 property
1491 (car (read-from-string
1492 (match-string 2 options))))))))
1493 plist))
1495 (defun org-export--get-subtree-options (&optional backend)
1496 "Get export options in subtree at point.
1497 Optional argument BACKEND is a symbol specifying back-end used
1498 for export. Return options as a plist."
1499 ;; For each buffer keyword, create a headline property setting the
1500 ;; same property in communication channel. The name for the property
1501 ;; is the keyword with "EXPORT_" appended to it.
1502 (org-with-wide-buffer
1503 (let (prop plist)
1504 ;; Make sure point is at an heading.
1505 (if (org-at-heading-p) (org-up-heading-safe) (org-back-to-heading t))
1506 ;; Take care of EXPORT_TITLE. If it isn't defined, use headline's
1507 ;; title as its fallback value.
1508 (when (setq prop (or (org-entry-get (point) "EXPORT_TITLE")
1509 (progn (looking-at org-todo-line-regexp)
1510 (org-match-string-no-properties 3))))
1511 (setq plist
1512 (plist-put
1513 plist :title
1514 (org-element-parse-secondary-string
1515 prop (org-element-restriction 'keyword)))))
1516 ;; EXPORT_OPTIONS are parsed in a non-standard way.
1517 (when (setq prop (org-entry-get (point) "EXPORT_OPTIONS"))
1518 (setq plist
1519 (nconc plist (org-export--parse-option-keyword prop backend))))
1520 ;; Handle other keywords. TITLE keyword is excluded as it has
1521 ;; been handled already.
1522 (let ((seen '("TITLE")))
1523 (mapc
1524 (lambda (option)
1525 (let ((property (car option))
1526 (keyword (nth 1 option)))
1527 (when (and keyword (not (member keyword seen)))
1528 (let* ((subtree-prop (concat "EXPORT_" keyword))
1529 ;; Export properties are not case-sensitive.
1530 (value (let ((case-fold-search t))
1531 (org-entry-get (point) subtree-prop))))
1532 (push keyword seen)
1533 (when (and value (not (plist-member plist property)))
1534 (setq plist
1535 (plist-put
1536 plist
1537 property
1538 (cond
1539 ;; Parse VALUE if required.
1540 ((member keyword org-element-document-properties)
1541 (org-element-parse-secondary-string
1542 value (org-element-restriction 'keyword)))
1543 ;; If BEHAVIOUR is `split' expected value is
1544 ;; a list of strings, not a string.
1545 ((eq (nth 4 option) 'split) (org-split-string value))
1546 (t value)))))))))
1547 ;; Look for both general keywords and back-end specific
1548 ;; options, with priority given to the latter.
1549 (append (and backend (org-export-backend-options backend))
1550 org-export-options-alist)))
1551 ;; Return value.
1552 plist)))
1554 (defun org-export--get-inbuffer-options (&optional backend)
1555 "Return current buffer export options, as a plist.
1557 Optional argument BACKEND, when non-nil, is a symbol specifying
1558 which back-end specific options should also be read in the
1559 process.
1561 Assume buffer is in Org mode. Narrowing, if any, is ignored."
1562 (let* (plist
1563 get-options ; For byte-compiler.
1564 (case-fold-search t)
1565 (options (append
1566 ;; Priority is given to back-end specific options.
1567 (and backend (org-export-backend-options backend))
1568 org-export-options-alist))
1569 (regexp (format "^[ \t]*#\\+%s:"
1570 (regexp-opt (nconc (delq nil (mapcar 'cadr options))
1571 org-export-special-keywords))))
1572 (find-opt
1573 (lambda (keyword)
1574 ;; Return property name associated to KEYWORD.
1575 (catch 'exit
1576 (mapc (lambda (option)
1577 (when (equal (nth 1 option) keyword)
1578 (throw 'exit (car option))))
1579 options))))
1580 (get-options
1581 (lambda (&optional files plist)
1582 ;; Recursively read keywords in buffer. FILES is a list
1583 ;; of files read so far. PLIST is the current property
1584 ;; list obtained.
1585 (org-with-wide-buffer
1586 (goto-char (point-min))
1587 (while (re-search-forward regexp nil t)
1588 (let ((element (org-element-at-point)))
1589 (when (eq (org-element-type element) 'keyword)
1590 (let ((key (org-element-property :key element))
1591 (val (org-element-property :value element)))
1592 (cond
1593 ;; Options in `org-export-special-keywords'.
1594 ((equal key "SETUPFILE")
1595 (let ((file (expand-file-name
1596 (org-remove-double-quotes (org-trim val)))))
1597 ;; Avoid circular dependencies.
1598 (unless (member file files)
1599 (with-temp-buffer
1600 (insert (org-file-contents file 'noerror))
1601 (org-mode)
1602 (setq plist (funcall get-options
1603 (cons file files) plist))))))
1604 ((equal key "OPTIONS")
1605 (setq plist
1606 (org-combine-plists
1607 plist
1608 (org-export--parse-option-keyword val backend))))
1609 ((equal key "FILETAGS")
1610 (setq plist
1611 (org-combine-plists
1612 plist
1613 (list :filetags
1614 (org-uniquify
1615 (append (org-split-string val ":")
1616 (plist-get plist :filetags)))))))
1618 ;; Options in `org-export-options-alist'.
1619 (let* ((prop (funcall find-opt key))
1620 (behaviour (nth 4 (assq prop options))))
1621 (setq plist
1622 (plist-put
1623 plist prop
1624 ;; Handle value depending on specified
1625 ;; BEHAVIOUR.
1626 (case behaviour
1627 (space
1628 (if (not (plist-get plist prop))
1629 (org-trim val)
1630 (concat (plist-get plist prop)
1632 (org-trim val))))
1633 (newline
1634 (org-trim (concat (plist-get plist prop)
1635 "\n"
1636 (org-trim val))))
1637 (split `(,@(plist-get plist prop)
1638 ,@(org-split-string val)))
1639 ('t val)
1640 (otherwise
1641 (if (not (plist-member plist prop)) val
1642 (plist-get plist prop)))))))))))))
1643 ;; Return final value.
1644 plist))))
1645 ;; Read options in the current buffer.
1646 (setq plist (funcall get-options buffer-file-name nil))
1647 ;; Parse keywords specified in `org-element-document-properties'.
1648 (mapc (lambda (keyword)
1649 ;; Find the property associated to the keyword.
1650 (let* ((prop (funcall find-opt keyword))
1651 (value (and prop (plist-get plist prop))))
1652 (when (stringp value)
1653 (setq plist
1654 (plist-put plist prop
1655 (org-element-parse-secondary-string
1656 value (org-element-restriction 'keyword)))))))
1657 org-element-document-properties)
1658 ;; Return value.
1659 plist))
1661 (defun org-export--get-buffer-attributes ()
1662 "Return properties related to buffer attributes, as a plist."
1663 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
1664 (list
1665 ;; Store full path of input file name, or nil. For internal use.
1666 :input-file visited-file
1667 :title (or (and visited-file
1668 (file-name-sans-extension
1669 (file-name-nondirectory visited-file)))
1670 (buffer-name (buffer-base-buffer))))))
1672 (defun org-export--get-global-options (&optional backend)
1673 "Return global export options as a plist.
1675 Optional argument BACKEND, if non-nil, is a symbol specifying
1676 which back-end specific export options should also be read in the
1677 process."
1678 (let ((all
1679 ;; Priority is given to back-end specific options.
1680 (append (and backend (org-export-backend-options backend))
1681 org-export-options-alist))
1682 plist)
1683 (mapc
1684 (lambda (cell)
1685 (let ((prop (car cell)))
1686 (unless (plist-member plist prop)
1687 (setq plist
1688 (plist-put
1689 plist
1690 prop
1691 ;; Eval default value provided. If keyword is a member
1692 ;; of `org-element-document-properties', parse it as
1693 ;; a secondary string before storing it.
1694 (let ((value (eval (nth 3 cell))))
1695 (if (not (stringp value)) value
1696 (let ((keyword (nth 1 cell)))
1697 (if (not (member keyword org-element-document-properties))
1698 value
1699 (org-element-parse-secondary-string
1700 value (org-element-restriction 'keyword)))))))))))
1701 all)
1702 ;; Return value.
1703 plist))
1705 (defun org-export--install-letbind-maybe ()
1706 "Install the values from #+BIND lines as local variables.
1707 Variables must be installed before in-buffer options are
1708 retrieved."
1709 (when org-export-allow-bind-keywords
1710 (let ((case-fold-search t) letbind)
1711 (org-with-wide-buffer
1712 (goto-char (point-min))
1713 (while (re-search-forward "^[ \t]*#\\+BIND:" nil t)
1714 (let* ((element (org-element-at-point))
1715 (value (org-element-property :value element)))
1716 (when (and (eq (org-element-type element) 'keyword)
1717 (not (equal value "")))
1718 (push (read (format "(%s)" value)) letbind)))))
1719 (dolist (pair (nreverse letbind))
1720 (org-set-local (car pair) (nth 1 pair))))))
1723 ;;;; Tree Properties
1725 ;; Tree properties are information extracted from parse tree. They
1726 ;; are initialized at the beginning of the transcoding process by
1727 ;; `org-export-collect-tree-properties'.
1729 ;; Dedicated functions focus on computing the value of specific tree
1730 ;; properties during initialization. Thus,
1731 ;; `org-export--populate-ignore-list' lists elements and objects that
1732 ;; should be skipped during export, `org-export--get-min-level' gets
1733 ;; the minimal exportable level, used as a basis to compute relative
1734 ;; level for headlines. Eventually
1735 ;; `org-export--collect-headline-numbering' builds an alist between
1736 ;; headlines and their numbering.
1738 (defun org-export-collect-tree-properties (data info)
1739 "Extract tree properties from parse tree.
1741 DATA is the parse tree from which information is retrieved. INFO
1742 is a list holding export options.
1744 Following tree properties are set or updated:
1746 `:exported-data' Hash table used to memoize results from
1747 `org-export-data'.
1749 `:footnote-definition-alist' List of footnotes definitions in
1750 original buffer and current parse tree.
1752 `:headline-offset' Offset between true level of headlines and
1753 local level. An offset of -1 means a headline
1754 of level 2 should be considered as a level
1755 1 headline in the context.
1757 `:headline-numbering' Alist of all headlines as key an the
1758 associated numbering as value.
1760 `:ignore-list' List of elements that should be ignored during
1761 export.
1763 Return updated plist."
1764 ;; Install the parse tree in the communication channel, in order to
1765 ;; use `org-export-get-genealogy' and al.
1766 (setq info (plist-put info :parse-tree data))
1767 ;; Get the list of elements and objects to ignore, and put it into
1768 ;; `:ignore-list'. Do not overwrite any user ignore that might have
1769 ;; been done during parse tree filtering.
1770 (setq info
1771 (plist-put info
1772 :ignore-list
1773 (append (org-export--populate-ignore-list data info)
1774 (plist-get info :ignore-list))))
1775 ;; Compute `:headline-offset' in order to be able to use
1776 ;; `org-export-get-relative-level'.
1777 (setq info
1778 (plist-put info
1779 :headline-offset
1780 (- 1 (org-export--get-min-level data info))))
1781 ;; Update footnotes definitions list with definitions in parse tree.
1782 ;; This is required since buffer expansion might have modified
1783 ;; boundaries of footnote definitions contained in the parse tree.
1784 ;; This way, definitions in `footnote-definition-alist' are bound to
1785 ;; match those in the parse tree.
1786 (let ((defs (plist-get info :footnote-definition-alist)))
1787 (org-element-map data 'footnote-definition
1788 (lambda (fn)
1789 (push (cons (org-element-property :label fn)
1790 `(org-data nil ,@(org-element-contents fn)))
1791 defs)))
1792 (setq info (plist-put info :footnote-definition-alist defs)))
1793 ;; Properties order doesn't matter: get the rest of the tree
1794 ;; properties.
1795 (nconc
1796 `(:headline-numbering ,(org-export--collect-headline-numbering data info)
1797 :exported-data ,(make-hash-table :test 'eq :size 4001))
1798 info))
1800 (defun org-export--get-min-level (data options)
1801 "Return minimum exportable headline's level in DATA.
1802 DATA is parsed tree as returned by `org-element-parse-buffer'.
1803 OPTIONS is a plist holding export options."
1804 (catch 'exit
1805 (let ((min-level 10000))
1806 (mapc
1807 (lambda (blob)
1808 (when (and (eq (org-element-type blob) 'headline)
1809 (not (org-element-property :footnote-section-p blob))
1810 (not (memq blob (plist-get options :ignore-list))))
1811 (setq min-level (min (org-element-property :level blob) min-level)))
1812 (when (= min-level 1) (throw 'exit 1)))
1813 (org-element-contents data))
1814 ;; If no headline was found, for the sake of consistency, set
1815 ;; minimum level to 1 nonetheless.
1816 (if (= min-level 10000) 1 min-level))))
1818 (defun org-export--collect-headline-numbering (data options)
1819 "Return numbering of all exportable headlines in a parse tree.
1821 DATA is the parse tree. OPTIONS is the plist holding export
1822 options.
1824 Return an alist whose key is a headline and value is its
1825 associated numbering \(in the shape of a list of numbers\) or nil
1826 for a footnotes section."
1827 (let ((numbering (make-vector org-export-max-depth 0)))
1828 (org-element-map data 'headline
1829 (lambda (headline)
1830 (unless (org-element-property :footnote-section-p headline)
1831 (let ((relative-level
1832 (1- (org-export-get-relative-level headline options))))
1833 (cons
1834 headline
1835 (loop for n across numbering
1836 for idx from 0 to org-export-max-depth
1837 when (< idx relative-level) collect n
1838 when (= idx relative-level) collect (aset numbering idx (1+ n))
1839 when (> idx relative-level) do (aset numbering idx 0))))))
1840 options)))
1842 (defun org-export--populate-ignore-list (data options)
1843 "Return list of elements and objects to ignore during export.
1844 DATA is the parse tree to traverse. OPTIONS is the plist holding
1845 export options."
1846 (let* (ignore
1847 walk-data
1848 ;; First find trees containing a select tag, if any.
1849 (selected (org-export--selected-trees data options))
1850 (walk-data
1851 (lambda (data)
1852 ;; Collect ignored elements or objects into IGNORE-LIST.
1853 (let ((type (org-element-type data)))
1854 (if (org-export--skip-p data options selected) (push data ignore)
1855 (if (and (eq type 'headline)
1856 (eq (plist-get options :with-archived-trees) 'headline)
1857 (org-element-property :archivedp data))
1858 ;; If headline is archived but tree below has
1859 ;; to be skipped, add it to ignore list.
1860 (mapc (lambda (e) (push e ignore))
1861 (org-element-contents data))
1862 ;; Move into secondary string, if any.
1863 (let ((sec-prop
1864 (cdr (assq type org-element-secondary-value-alist))))
1865 (when sec-prop
1866 (mapc walk-data (org-element-property sec-prop data))))
1867 ;; Move into recursive objects/elements.
1868 (mapc walk-data (org-element-contents data))))))))
1869 ;; Main call.
1870 (funcall walk-data data)
1871 ;; Return value.
1872 ignore))
1874 (defun org-export--selected-trees (data info)
1875 "Return list of headlines and inlinetasks with a select tag in their tree.
1876 DATA is parsed data as returned by `org-element-parse-buffer'.
1877 INFO is a plist holding export options."
1878 (let* (selected-trees
1879 walk-data ; For byte-compiler.
1880 (walk-data
1881 (function
1882 (lambda (data genealogy)
1883 (let ((type (org-element-type data)))
1884 (cond
1885 ((memq type '(headline inlinetask))
1886 (let ((tags (org-element-property :tags data)))
1887 (if (loop for tag in (plist-get info :select-tags)
1888 thereis (member tag tags))
1889 ;; When a select tag is found, mark full
1890 ;; genealogy and every headline within the tree
1891 ;; as acceptable.
1892 (setq selected-trees
1893 (append
1894 genealogy
1895 (org-element-map data '(headline inlinetask)
1896 'identity)
1897 selected-trees))
1898 ;; If at a headline, continue searching in tree,
1899 ;; recursively.
1900 (when (eq type 'headline)
1901 (mapc (lambda (el)
1902 (funcall walk-data el (cons data genealogy)))
1903 (org-element-contents data))))))
1904 ((or (eq type 'org-data)
1905 (memq type org-element-greater-elements))
1906 (mapc (lambda (el) (funcall walk-data el genealogy))
1907 (org-element-contents data)))))))))
1908 (funcall walk-data data nil)
1909 selected-trees))
1911 (defun org-export--skip-p (blob options selected)
1912 "Non-nil when element or object BLOB should be skipped during export.
1913 OPTIONS is the plist holding export options. SELECTED, when
1914 non-nil, is a list of headlines or inlinetasks belonging to
1915 a tree with a select tag."
1916 (case (org-element-type blob)
1917 (clock (not (plist-get options :with-clocks)))
1918 (drawer
1919 (let ((with-drawers-p (plist-get options :with-drawers)))
1920 (or (not with-drawers-p)
1921 (and (consp with-drawers-p)
1922 ;; If `:with-drawers' value starts with `not', ignore
1923 ;; every drawer whose name belong to that list.
1924 ;; Otherwise, ignore drawers whose name isn't in that
1925 ;; list.
1926 (let ((name (org-element-property :drawer-name blob)))
1927 (if (eq (car with-drawers-p) 'not)
1928 (member-ignore-case name (cdr with-drawers-p))
1929 (not (member-ignore-case name with-drawers-p))))))))
1930 ((headline inlinetask)
1931 (let ((with-tasks (plist-get options :with-tasks))
1932 (todo (org-element-property :todo-keyword blob))
1933 (todo-type (org-element-property :todo-type blob))
1934 (archived (plist-get options :with-archived-trees))
1935 (tags (org-element-property :tags blob)))
1937 (and (eq (org-element-type blob) 'inlinetask)
1938 (not (plist-get options :with-inlinetasks)))
1939 ;; Ignore subtrees with an exclude tag.
1940 (loop for k in (plist-get options :exclude-tags)
1941 thereis (member k tags))
1942 ;; When a select tag is present in the buffer, ignore any tree
1943 ;; without it.
1944 (and selected (not (memq blob selected)))
1945 ;; Ignore commented sub-trees.
1946 (org-element-property :commentedp blob)
1947 ;; Ignore archived subtrees if `:with-archived-trees' is nil.
1948 (and (not archived) (org-element-property :archivedp blob))
1949 ;; Ignore tasks, if specified by `:with-tasks' property.
1950 (and todo
1951 (or (not with-tasks)
1952 (and (memq with-tasks '(todo done))
1953 (not (eq todo-type with-tasks)))
1954 (and (consp with-tasks) (not (member todo with-tasks))))))))
1955 ((latex-environment latex-fragment) (not (plist-get options :with-latex)))
1956 (planning (not (plist-get options :with-plannings)))
1957 (statistics-cookie (not (plist-get options :with-statistics-cookies)))
1958 (table-cell
1959 (and (org-export-table-has-special-column-p
1960 (org-export-get-parent-table blob))
1961 (not (org-export-get-previous-element blob options))))
1962 (table-row (org-export-table-row-is-special-p blob options))
1963 (timestamp
1964 (case (plist-get options :with-timestamps)
1965 ;; No timestamp allowed.
1966 ('nil t)
1967 ;; Only active timestamps allowed and the current one isn't
1968 ;; active.
1969 (active
1970 (not (memq (org-element-property :type blob)
1971 '(active active-range))))
1972 ;; Only inactive timestamps allowed and the current one isn't
1973 ;; inactive.
1974 (inactive
1975 (not (memq (org-element-property :type blob)
1976 '(inactive inactive-range))))))))
1980 ;;; The Transcoder
1982 ;; `org-export-data' reads a parse tree (obtained with, i.e.
1983 ;; `org-element-parse-buffer') and transcodes it into a specified
1984 ;; back-end output. It takes care of filtering out elements or
1985 ;; objects according to export options and organizing the output blank
1986 ;; lines and white space are preserved. The function memoizes its
1987 ;; results, so it is cheap to call it within translators.
1989 ;; It is possible to modify locally the back-end used by
1990 ;; `org-export-data' or even use a temporary back-end by using
1991 ;; `org-export-data-with-translations' and
1992 ;; `org-export-data-with-backend'.
1994 ;; Internally, three functions handle the filtering of objects and
1995 ;; elements during the export. In particular,
1996 ;; `org-export-ignore-element' marks an element or object so future
1997 ;; parse tree traversals skip it, `org-export--interpret-p' tells which
1998 ;; elements or objects should be seen as real Org syntax and
1999 ;; `org-export-expand' transforms the others back into their original
2000 ;; shape
2002 ;; `org-export-transcoder' is an accessor returning appropriate
2003 ;; translator function for a given element or object.
2005 (defun org-export-transcoder (blob info)
2006 "Return appropriate transcoder for BLOB.
2007 INFO is a plist containing export directives."
2008 (let ((type (org-element-type blob)))
2009 ;; Return contents only for complete parse trees.
2010 (if (eq type 'org-data) (lambda (blob contents info) contents)
2011 (let ((transcoder (cdr (assq type (plist-get info :translate-alist)))))
2012 (and (functionp transcoder) transcoder)))))
2014 (defun org-export-data (data info)
2015 "Convert DATA into current back-end format.
2017 DATA is a parse tree, an element or an object or a secondary
2018 string. INFO is a plist holding export options.
2020 Return transcoded string."
2021 (let ((memo (gethash data (plist-get info :exported-data) 'no-memo)))
2022 (if (not (eq memo 'no-memo)) memo
2023 (let* ((type (org-element-type data))
2024 (results
2025 (cond
2026 ;; Ignored element/object.
2027 ((memq data (plist-get info :ignore-list)) nil)
2028 ;; Plain text.
2029 ((eq type 'plain-text)
2030 (org-export-filter-apply-functions
2031 (plist-get info :filter-plain-text)
2032 (let ((transcoder (org-export-transcoder data info)))
2033 (if transcoder (funcall transcoder data info) data))
2034 info))
2035 ;; Uninterpreted element/object: change it back to Org
2036 ;; syntax and export again resulting raw string.
2037 ((not (org-export--interpret-p data info))
2038 (org-export-data
2039 (org-export-expand
2040 data
2041 (mapconcat (lambda (blob) (org-export-data blob info))
2042 (org-element-contents data)
2043 ""))
2044 info))
2045 ;; Secondary string.
2046 ((not type)
2047 (mapconcat (lambda (obj) (org-export-data obj info)) data ""))
2048 ;; Element/Object without contents or, as a special case,
2049 ;; headline with archive tag and archived trees restricted
2050 ;; to title only.
2051 ((or (not (org-element-contents data))
2052 (and (eq type 'headline)
2053 (eq (plist-get info :with-archived-trees) 'headline)
2054 (org-element-property :archivedp data)))
2055 (let ((transcoder (org-export-transcoder data info)))
2056 (and (functionp transcoder)
2057 (funcall transcoder data nil info))))
2058 ;; Element/Object with contents.
2060 (let ((transcoder (org-export-transcoder data info)))
2061 (when transcoder
2062 (let* ((greaterp (memq type org-element-greater-elements))
2063 (objectp
2064 (and (not greaterp)
2065 (memq type org-element-recursive-objects)))
2066 (contents
2067 (mapconcat
2068 (lambda (element) (org-export-data element info))
2069 (org-element-contents
2070 (if (or greaterp objectp) data
2071 ;; Elements directly containing objects
2072 ;; must have their indentation normalized
2073 ;; first.
2074 (org-element-normalize-contents
2075 data
2076 ;; When normalizing contents of the first
2077 ;; paragraph in an item or a footnote
2078 ;; definition, ignore first line's
2079 ;; indentation: there is none and it
2080 ;; might be misleading.
2081 (when (eq type 'paragraph)
2082 (let ((parent (org-export-get-parent data)))
2083 (and
2084 (eq (car (org-element-contents parent))
2085 data)
2086 (memq (org-element-type parent)
2087 '(footnote-definition item))))))))
2088 "")))
2089 (funcall transcoder data
2090 (if (not greaterp) contents
2091 (org-element-normalize-string contents))
2092 info))))))))
2093 ;; Final result will be memoized before being returned.
2094 (puthash
2095 data
2096 (cond
2097 ((not results) nil)
2098 ((memq type '(org-data plain-text nil)) results)
2099 ;; Append the same white space between elements or objects as in
2100 ;; the original buffer, and call appropriate filters.
2102 (let ((results
2103 (org-export-filter-apply-functions
2104 (plist-get info (intern (format ":filter-%s" type)))
2105 (let ((post-blank (or (org-element-property :post-blank data)
2106 0)))
2107 (if (memq type org-element-all-elements)
2108 (concat (org-element-normalize-string results)
2109 (make-string post-blank ?\n))
2110 (concat results (make-string post-blank ? ))))
2111 info)))
2112 results)))
2113 (plist-get info :exported-data))))))
2115 (defun org-export-data-with-translations (data translations info)
2116 "Convert DATA into another format using a given translation table.
2117 DATA is an element, an object, a secondary string or a string.
2118 TRANSLATIONS is an alist between element or object types and
2119 a functions handling them. See `org-export-define-backend' for
2120 more information. INFO is a plist used as a communication
2121 channel."
2122 (org-export-data
2123 data
2124 ;; Set-up a new communication channel with TRANSLATIONS as the
2125 ;; translate table and a new hash table for memoization.
2126 (org-combine-plists
2127 info
2128 (list :translate-alist translations
2129 ;; Size of the hash table is reduced since this function
2130 ;; will probably be used on short trees.
2131 :exported-data (make-hash-table :test 'eq :size 401)))))
2133 (defun org-export-data-with-backend (data backend info)
2134 "Convert DATA into BACKEND format.
2136 DATA is an element, an object, a secondary string or a string.
2137 BACKEND is a symbol. INFO is a plist used as a communication
2138 channel.
2140 Unlike to `org-export-with-backend', this function will
2141 recursively convert DATA using BACKEND translation table."
2142 (org-export-barf-if-invalid-backend backend)
2143 (org-export-data-with-translations
2144 data (org-export-backend-translate-table backend) info))
2146 (defun org-export--interpret-p (blob info)
2147 "Non-nil if element or object BLOB should be interpreted during export.
2148 If nil, BLOB will appear as raw Org syntax. Check is done
2149 according to export options INFO, stored as a plist."
2150 (case (org-element-type blob)
2151 ;; ... entities...
2152 (entity (plist-get info :with-entities))
2153 ;; ... emphasis...
2154 ((bold italic strike-through underline)
2155 (plist-get info :with-emphasize))
2156 ;; ... fixed-width areas.
2157 (fixed-width (plist-get info :with-fixed-width))
2158 ;; ... footnotes...
2159 ((footnote-definition footnote-reference)
2160 (plist-get info :with-footnotes))
2161 ;; ... LaTeX environments and fragments...
2162 ((latex-environment latex-fragment)
2163 (let ((with-latex-p (plist-get info :with-latex)))
2164 (and with-latex-p (not (eq with-latex-p 'verbatim)))))
2165 ;; ... sub/superscripts...
2166 ((subscript superscript)
2167 (let ((sub/super-p (plist-get info :with-sub-superscript)))
2168 (if (eq sub/super-p '{})
2169 (org-element-property :use-brackets-p blob)
2170 sub/super-p)))
2171 ;; ... tables...
2172 (table (plist-get info :with-tables))
2173 (otherwise t)))
2175 (defun org-export-expand (blob contents)
2176 "Expand a parsed element or object to its original state.
2177 BLOB is either an element or an object. CONTENTS is its
2178 contents, as a string or nil."
2179 (funcall
2180 (intern (format "org-element-%s-interpreter" (org-element-type blob)))
2181 blob contents))
2183 (defun org-export-ignore-element (element info)
2184 "Add ELEMENT to `:ignore-list' in INFO.
2186 Any element in `:ignore-list' will be skipped when using
2187 `org-element-map'. INFO is modified by side effects."
2188 (plist-put info :ignore-list (cons element (plist-get info :ignore-list))))
2192 ;;; The Filter System
2194 ;; Filters allow end-users to tweak easily the transcoded output.
2195 ;; They are the functional counterpart of hooks, as every filter in
2196 ;; a set is applied to the return value of the previous one.
2198 ;; Every set is back-end agnostic. Although, a filter is always
2199 ;; called, in addition to the string it applies to, with the back-end
2200 ;; used as argument, so it's easy for the end-user to add back-end
2201 ;; specific filters in the set. The communication channel, as
2202 ;; a plist, is required as the third argument.
2204 ;; From the developer side, filters sets can be installed in the
2205 ;; process with the help of `org-export-define-backend', which
2206 ;; internally stores filters as an alist. Each association has a key
2207 ;; among the following symbols and a function or a list of functions
2208 ;; as value.
2210 ;; - `:filter-options' applies to the property list containing export
2211 ;; options. Unlike to other filters, functions in this list accept
2212 ;; two arguments instead of three: the property list containing
2213 ;; export options and the back-end. Users can set its value through
2214 ;; `org-export-filter-options-functions' variable.
2216 ;; - `:filter-parse-tree' applies directly to the complete parsed
2217 ;; tree. Users can set it through
2218 ;; `org-export-filter-parse-tree-functions' variable.
2220 ;; - `:filter-final-output' applies to the final transcoded string.
2221 ;; Users can set it with `org-export-filter-final-output-functions'
2222 ;; variable
2224 ;; - `:filter-plain-text' applies to any string not recognized as Org
2225 ;; syntax. `org-export-filter-plain-text-functions' allows users to
2226 ;; configure it.
2228 ;; - `:filter-TYPE' applies on the string returned after an element or
2229 ;; object of type TYPE has been transcoded. An user can modify
2230 ;; `org-export-filter-TYPE-functions'
2232 ;; All filters sets are applied with
2233 ;; `org-export-filter-apply-functions' function. Filters in a set are
2234 ;; applied in a LIFO fashion. It allows developers to be sure that
2235 ;; their filters will be applied first.
2237 ;; Filters properties are installed in communication channel with
2238 ;; `org-export-install-filters' function.
2240 ;; Eventually, two hooks (`org-export-before-processing-hook' and
2241 ;; `org-export-before-parsing-hook') are run at the beginning of the
2242 ;; export process and just before parsing to allow for heavy structure
2243 ;; modifications.
2246 ;;;; Hooks
2248 (defvar org-export-before-processing-hook nil
2249 "Hook run at the beginning of the export process.
2251 This is run before include keywords and macros are expanded and
2252 Babel code blocks executed, on a copy of the original buffer
2253 being exported. Visibility and narrowing are preserved. Point
2254 is at the beginning of the buffer.
2256 Every function in this hook will be called with one argument: the
2257 back-end currently used, as a symbol.")
2259 (defvar org-export-before-parsing-hook nil
2260 "Hook run before parsing an export buffer.
2262 This is run after include keywords and macros have been expanded
2263 and Babel code blocks executed, on a copy of the original buffer
2264 being exported. Visibility and narrowing are preserved. Point
2265 is at the beginning of the buffer.
2267 Every function in this hook will be called with one argument: the
2268 back-end currently used, as a symbol.")
2271 ;;;; Special Filters
2273 (defvar org-export-filter-options-functions nil
2274 "List of functions applied to the export options.
2275 Each filter is called with two arguments: the export options, as
2276 a plist, and the back-end, as a symbol. It must return
2277 a property list containing export options.")
2279 (defvar org-export-filter-parse-tree-functions nil
2280 "List of functions applied to the parsed tree.
2281 Each filter is called with three arguments: the parse tree, as
2282 returned by `org-element-parse-buffer', the back-end, as
2283 a symbol, and the communication channel, as a plist. It must
2284 return the modified parse tree to transcode.")
2286 (defvar org-export-filter-plain-text-functions nil
2287 "List of functions applied to plain text.
2288 Each filter is called with three arguments: a string which
2289 contains no Org syntax, the back-end, as a symbol, and the
2290 communication channel, as a plist. It must return a string or
2291 nil.")
2293 (defvar org-export-filter-final-output-functions nil
2294 "List of functions applied to the transcoded string.
2295 Each filter is called with three arguments: the full transcoded
2296 string, the back-end, as a symbol, and the communication channel,
2297 as a plist. It must return a string that will be used as the
2298 final export output.")
2301 ;;;; Elements Filters
2303 (defvar org-export-filter-babel-call-functions nil
2304 "List of functions applied to a transcoded babel-call.
2305 Each filter is called with three arguments: the transcoded data,
2306 as a string, the back-end, as a symbol, and the communication
2307 channel, as a plist. It must return a string or nil.")
2309 (defvar org-export-filter-center-block-functions nil
2310 "List of functions applied to a transcoded center block.
2311 Each filter is called with three arguments: the transcoded data,
2312 as a string, the back-end, as a symbol, and the communication
2313 channel, as a plist. It must return a string or nil.")
2315 (defvar org-export-filter-clock-functions nil
2316 "List of functions applied to a transcoded clock.
2317 Each filter is called with three arguments: the transcoded data,
2318 as a string, the back-end, as a symbol, and the communication
2319 channel, as a plist. It must return a string or nil.")
2321 (defvar org-export-filter-comment-functions nil
2322 "List of functions applied to a transcoded comment.
2323 Each filter is called with three arguments: the transcoded data,
2324 as a string, the back-end, as a symbol, and the communication
2325 channel, as a plist. It must return a string or nil.")
2327 (defvar org-export-filter-comment-block-functions nil
2328 "List of functions applied to a transcoded comment-block.
2329 Each filter is called with three arguments: the transcoded data,
2330 as a string, the back-end, as a symbol, and the communication
2331 channel, as a plist. It must return a string or nil.")
2333 (defvar org-export-filter-diary-sexp-functions nil
2334 "List of functions applied to a transcoded diary-sexp.
2335 Each filter is called with three arguments: the transcoded data,
2336 as a string, the back-end, as a symbol, and the communication
2337 channel, as a plist. It must return a string or nil.")
2339 (defvar org-export-filter-drawer-functions nil
2340 "List of functions applied to a transcoded drawer.
2341 Each filter is called with three arguments: the transcoded data,
2342 as a string, the back-end, as a symbol, and the communication
2343 channel, as a plist. It must return a string or nil.")
2345 (defvar org-export-filter-dynamic-block-functions nil
2346 "List of functions applied to a transcoded dynamic-block.
2347 Each filter is called with three arguments: the transcoded data,
2348 as a string, the back-end, as a symbol, and the communication
2349 channel, as a plist. It must return a string or nil.")
2351 (defvar org-export-filter-example-block-functions nil
2352 "List of functions applied to a transcoded example-block.
2353 Each filter is called with three arguments: the transcoded data,
2354 as a string, the back-end, as a symbol, and the communication
2355 channel, as a plist. It must return a string or nil.")
2357 (defvar org-export-filter-export-block-functions nil
2358 "List of functions applied to a transcoded export-block.
2359 Each filter is called with three arguments: the transcoded data,
2360 as a string, the back-end, as a symbol, and the communication
2361 channel, as a plist. It must return a string or nil.")
2363 (defvar org-export-filter-fixed-width-functions nil
2364 "List of functions applied to a transcoded fixed-width.
2365 Each filter is called with three arguments: the transcoded data,
2366 as a string, the back-end, as a symbol, and the communication
2367 channel, as a plist. It must return a string or nil.")
2369 (defvar org-export-filter-footnote-definition-functions nil
2370 "List of functions applied to a transcoded footnote-definition.
2371 Each filter is called with three arguments: the transcoded data,
2372 as a string, the back-end, as a symbol, and the communication
2373 channel, as a plist. It must return a string or nil.")
2375 (defvar org-export-filter-headline-functions nil
2376 "List of functions applied to a transcoded headline.
2377 Each filter is called with three arguments: the transcoded data,
2378 as a string, the back-end, as a symbol, and the communication
2379 channel, as a plist. It must return a string or nil.")
2381 (defvar org-export-filter-horizontal-rule-functions nil
2382 "List of functions applied to a transcoded horizontal-rule.
2383 Each filter is called with three arguments: the transcoded data,
2384 as a string, the back-end, as a symbol, and the communication
2385 channel, as a plist. It must return a string or nil.")
2387 (defvar org-export-filter-inlinetask-functions nil
2388 "List of functions applied to a transcoded inlinetask.
2389 Each filter is called with three arguments: the transcoded data,
2390 as a string, the back-end, as a symbol, and the communication
2391 channel, as a plist. It must return a string or nil.")
2393 (defvar org-export-filter-item-functions nil
2394 "List of functions applied to a transcoded item.
2395 Each filter is called with three arguments: the transcoded data,
2396 as a string, the back-end, as a symbol, and the communication
2397 channel, as a plist. It must return a string or nil.")
2399 (defvar org-export-filter-keyword-functions nil
2400 "List of functions applied to a transcoded keyword.
2401 Each filter is called with three arguments: the transcoded data,
2402 as a string, the back-end, as a symbol, and the communication
2403 channel, as a plist. It must return a string or nil.")
2405 (defvar org-export-filter-latex-environment-functions nil
2406 "List of functions applied to a transcoded latex-environment.
2407 Each filter is called with three arguments: the transcoded data,
2408 as a string, the back-end, as a symbol, and the communication
2409 channel, as a plist. It must return a string or nil.")
2411 (defvar org-export-filter-node-property-functions nil
2412 "List of functions applied to a transcoded node-property.
2413 Each filter is called with three arguments: the transcoded data,
2414 as a string, the back-end, as a symbol, and the communication
2415 channel, as a plist. It must return a string or nil.")
2417 (defvar org-export-filter-paragraph-functions nil
2418 "List of functions applied to a transcoded paragraph.
2419 Each filter is called with three arguments: the transcoded data,
2420 as a string, the back-end, as a symbol, and the communication
2421 channel, as a plist. It must return a string or nil.")
2423 (defvar org-export-filter-plain-list-functions nil
2424 "List of functions applied to a transcoded plain-list.
2425 Each filter is called with three arguments: the transcoded data,
2426 as a string, the back-end, as a symbol, and the communication
2427 channel, as a plist. It must return a string or nil.")
2429 (defvar org-export-filter-planning-functions nil
2430 "List of functions applied to a transcoded planning.
2431 Each filter is called with three arguments: the transcoded data,
2432 as a string, the back-end, as a symbol, and the communication
2433 channel, as a plist. It must return a string or nil.")
2435 (defvar org-export-filter-property-drawer-functions nil
2436 "List of functions applied to a transcoded property-drawer.
2437 Each filter is called with three arguments: the transcoded data,
2438 as a string, the back-end, as a symbol, and the communication
2439 channel, as a plist. It must return a string or nil.")
2441 (defvar org-export-filter-quote-block-functions nil
2442 "List of functions applied to a transcoded quote block.
2443 Each filter is called with three arguments: the transcoded quote
2444 data, as a string, the back-end, as a symbol, and the
2445 communication channel, as a plist. It must return a string or
2446 nil.")
2448 (defvar org-export-filter-quote-section-functions nil
2449 "List of functions applied to a transcoded quote-section.
2450 Each filter is called with three arguments: the transcoded data,
2451 as a string, the back-end, as a symbol, and the communication
2452 channel, as a plist. It must return a string or nil.")
2454 (defvar org-export-filter-section-functions nil
2455 "List of functions applied to a transcoded section.
2456 Each filter is called with three arguments: the transcoded data,
2457 as a string, the back-end, as a symbol, and the communication
2458 channel, as a plist. It must return a string or nil.")
2460 (defvar org-export-filter-special-block-functions nil
2461 "List of functions applied to a transcoded special block.
2462 Each filter is called with three arguments: the transcoded data,
2463 as a string, the back-end, as a symbol, and the communication
2464 channel, as a plist. It must return a string or nil.")
2466 (defvar org-export-filter-src-block-functions nil
2467 "List of functions applied to a transcoded src-block.
2468 Each filter is called with three arguments: the transcoded data,
2469 as a string, the back-end, as a symbol, and the communication
2470 channel, as a plist. It must return a string or nil.")
2472 (defvar org-export-filter-table-functions nil
2473 "List of functions applied to a transcoded table.
2474 Each filter is called with three arguments: the transcoded data,
2475 as a string, the back-end, as a symbol, and the communication
2476 channel, as a plist. It must return a string or nil.")
2478 (defvar org-export-filter-table-cell-functions nil
2479 "List of functions applied to a transcoded table-cell.
2480 Each filter is called with three arguments: the transcoded data,
2481 as a string, the back-end, as a symbol, and the communication
2482 channel, as a plist. It must return a string or nil.")
2484 (defvar org-export-filter-table-row-functions nil
2485 "List of functions applied to a transcoded table-row.
2486 Each filter is called with three arguments: the transcoded data,
2487 as a string, the back-end, as a symbol, and the communication
2488 channel, as a plist. It must return a string or nil.")
2490 (defvar org-export-filter-verse-block-functions nil
2491 "List of functions applied to a transcoded verse block.
2492 Each filter is called with three arguments: the transcoded data,
2493 as a string, the back-end, as a symbol, and the communication
2494 channel, as a plist. It must return a string or nil.")
2497 ;;;; Objects Filters
2499 (defvar org-export-filter-bold-functions nil
2500 "List of functions applied to transcoded bold text.
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.")
2505 (defvar org-export-filter-code-functions nil
2506 "List of functions applied to transcoded code text.
2507 Each filter is called with three arguments: the transcoded data,
2508 as a string, the back-end, as a symbol, and the communication
2509 channel, as a plist. It must return a string or nil.")
2511 (defvar org-export-filter-entity-functions nil
2512 "List of functions applied to a transcoded entity.
2513 Each filter is called with three arguments: the transcoded data,
2514 as a string, the back-end, as a symbol, and the communication
2515 channel, as a plist. It must return a string or nil.")
2517 (defvar org-export-filter-export-snippet-functions nil
2518 "List of functions applied to a transcoded export-snippet.
2519 Each filter is called with three arguments: the transcoded data,
2520 as a string, the back-end, as a symbol, and the communication
2521 channel, as a plist. It must return a string or nil.")
2523 (defvar org-export-filter-footnote-reference-functions nil
2524 "List of functions applied to a transcoded footnote-reference.
2525 Each filter is called with three arguments: the transcoded data,
2526 as a string, the back-end, as a symbol, and the communication
2527 channel, as a plist. It must return a string or nil.")
2529 (defvar org-export-filter-inline-babel-call-functions nil
2530 "List of functions applied to a transcoded inline-babel-call.
2531 Each filter is called with three arguments: the transcoded data,
2532 as a string, the back-end, as a symbol, and the communication
2533 channel, as a plist. It must return a string or nil.")
2535 (defvar org-export-filter-inline-src-block-functions nil
2536 "List of functions applied to a transcoded inline-src-block.
2537 Each filter is called with three arguments: the transcoded data,
2538 as a string, the back-end, as a symbol, and the communication
2539 channel, as a plist. It must return a string or nil.")
2541 (defvar org-export-filter-italic-functions nil
2542 "List of functions applied to transcoded italic text.
2543 Each filter is called with three arguments: the transcoded data,
2544 as a string, the back-end, as a symbol, and the communication
2545 channel, as a plist. It must return a string or nil.")
2547 (defvar org-export-filter-latex-fragment-functions nil
2548 "List of functions applied to a transcoded latex-fragment.
2549 Each filter is called with three arguments: the transcoded data,
2550 as a string, the back-end, as a symbol, and the communication
2551 channel, as a plist. It must return a string or nil.")
2553 (defvar org-export-filter-line-break-functions nil
2554 "List of functions applied to a transcoded line-break.
2555 Each filter is called with three arguments: the transcoded data,
2556 as a string, the back-end, as a symbol, and the communication
2557 channel, as a plist. It must return a string or nil.")
2559 (defvar org-export-filter-link-functions nil
2560 "List of functions applied to a transcoded link.
2561 Each filter is called with three arguments: the transcoded data,
2562 as a string, the back-end, as a symbol, and the communication
2563 channel, as a plist. It must return a string or nil.")
2565 (defvar org-export-filter-macro-functions nil
2566 "List of functions applied to a transcoded macro.
2567 Each filter is called with three arguments: the transcoded data,
2568 as a string, the back-end, as a symbol, and the communication
2569 channel, as a plist. It must return a string or nil.")
2571 (defvar org-export-filter-radio-target-functions nil
2572 "List of functions applied to a transcoded radio-target.
2573 Each filter is called with three arguments: the transcoded data,
2574 as a string, the back-end, as a symbol, and the communication
2575 channel, as a plist. It must return a string or nil.")
2577 (defvar org-export-filter-statistics-cookie-functions nil
2578 "List of functions applied to a transcoded statistics-cookie.
2579 Each filter is called with three arguments: the transcoded data,
2580 as a string, the back-end, as a symbol, and the communication
2581 channel, as a plist. It must return a string or nil.")
2583 (defvar org-export-filter-strike-through-functions nil
2584 "List of functions applied to transcoded strike-through text.
2585 Each filter is called with three arguments: the transcoded data,
2586 as a string, the back-end, as a symbol, and the communication
2587 channel, as a plist. It must return a string or nil.")
2589 (defvar org-export-filter-subscript-functions nil
2590 "List of functions applied to a transcoded subscript.
2591 Each filter is called with three arguments: the transcoded data,
2592 as a string, the back-end, as a symbol, and the communication
2593 channel, as a plist. It must return a string or nil.")
2595 (defvar org-export-filter-superscript-functions nil
2596 "List of functions applied to a transcoded superscript.
2597 Each filter is called with three arguments: the transcoded data,
2598 as a string, the back-end, as a symbol, and the communication
2599 channel, as a plist. It must return a string or nil.")
2601 (defvar org-export-filter-target-functions nil
2602 "List of functions applied to a transcoded target.
2603 Each filter is called with three arguments: the transcoded data,
2604 as a string, the back-end, as a symbol, and the communication
2605 channel, as a plist. It must return a string or nil.")
2607 (defvar org-export-filter-timestamp-functions nil
2608 "List of functions applied to a transcoded timestamp.
2609 Each filter is called with three arguments: the transcoded data,
2610 as a string, the back-end, as a symbol, and the communication
2611 channel, as a plist. It must return a string or nil.")
2613 (defvar org-export-filter-underline-functions nil
2614 "List of functions applied to transcoded underline text.
2615 Each filter is called with three arguments: the transcoded data,
2616 as a string, the back-end, as a symbol, and the communication
2617 channel, as a plist. It must return a string or nil.")
2619 (defvar org-export-filter-verbatim-functions nil
2620 "List of functions applied to transcoded verbatim text.
2621 Each filter is called with three arguments: the transcoded data,
2622 as a string, the back-end, as a symbol, and the communication
2623 channel, as a plist. It must return a string or nil.")
2626 ;;;; Filters Tools
2628 ;; Internal function `org-export-install-filters' installs filters
2629 ;; hard-coded in back-ends (developer filters) and filters from global
2630 ;; variables (user filters) in the communication channel.
2632 ;; Internal function `org-export-filter-apply-functions' takes care
2633 ;; about applying each filter in order to a given data. It ignores
2634 ;; filters returning a nil value but stops whenever a filter returns
2635 ;; an empty string.
2637 (defun org-export-filter-apply-functions (filters value info)
2638 "Call every function in FILTERS.
2640 Functions are called with arguments VALUE, current export
2641 back-end and INFO. A function returning a nil value will be
2642 skipped. If it returns the empty string, the process ends and
2643 VALUE is ignored.
2645 Call is done in a LIFO fashion, to be sure that developer
2646 specified filters, if any, are called first."
2647 (catch 'exit
2648 (dolist (filter filters value)
2649 (let ((result (funcall filter value (plist-get info :back-end) info)))
2650 (cond ((not result) value)
2651 ((equal value "") (throw 'exit nil))
2652 (t (setq value result)))))))
2654 (defun org-export-install-filters (info)
2655 "Install filters properties in communication channel.
2656 INFO is a plist containing the current communication channel.
2657 Return the updated communication channel."
2658 (let (plist)
2659 ;; Install user-defined filters with `org-export-filters-alist'
2660 ;; and filters already in INFO (through ext-plist mechanism).
2661 (mapc (lambda (p)
2662 (let* ((prop (car p))
2663 (info-value (plist-get info prop))
2664 (default-value (symbol-value (cdr p))))
2665 (setq plist
2666 (plist-put plist prop
2667 ;; Filters in INFO will be called
2668 ;; before those user provided.
2669 (append (if (listp info-value) info-value
2670 (list info-value))
2671 default-value)))))
2672 org-export-filters-alist)
2673 ;; Prepend back-end specific filters to that list.
2674 (mapc (lambda (p)
2675 ;; Single values get consed, lists are appended.
2676 (let ((key (car p)) (value (cdr p)))
2677 (when value
2678 (setq plist
2679 (plist-put
2680 plist key
2681 (if (atom value) (cons value (plist-get plist key))
2682 (append value (plist-get plist key))))))))
2683 (org-export-backend-filters (plist-get info :back-end)))
2684 ;; Return new communication channel.
2685 (org-combine-plists info plist)))
2689 ;;; Core functions
2691 ;; This is the room for the main function, `org-export-as', along with
2692 ;; its derivatives, `org-export-to-buffer', `org-export-to-file' and
2693 ;; `org-export-string-as'. They differ either by the way they output
2694 ;; the resulting code (for the first two) or by the input type (for
2695 ;; the latter).
2697 ;; `org-export-output-file-name' is an auxiliary function meant to be
2698 ;; used with `org-export-to-file'. With a given extension, it tries
2699 ;; to provide a canonical file name to write export output to.
2701 ;; Note that `org-export-as' doesn't really parse the current buffer,
2702 ;; but a copy of it (with the same buffer-local variables and
2703 ;; visibility), where macros and include keywords are expanded and
2704 ;; Babel blocks are executed, if appropriate.
2705 ;; `org-export-with-buffer-copy' macro prepares that copy.
2707 ;; File inclusion is taken care of by
2708 ;; `org-export-expand-include-keyword' and
2709 ;; `org-export--prepare-file-contents'. Structure wise, including
2710 ;; a whole Org file in a buffer often makes little sense. For
2711 ;; example, if the file contains a headline and the include keyword
2712 ;; was within an item, the item should contain the headline. That's
2713 ;; why file inclusion should be done before any structure can be
2714 ;; associated to the file, that is before parsing.
2716 (defun org-export-copy-buffer ()
2717 "Return a copy of the current buffer.
2718 The copy preserves Org buffer-local variables, visibility and
2719 narrowing."
2720 (let ((copy-buffer-fun (org-export--generate-copy-script (current-buffer)))
2721 (new-buf (generate-new-buffer (buffer-name))))
2722 (with-current-buffer new-buf
2723 (funcall copy-buffer-fun)
2724 (set-buffer-modified-p nil))
2725 new-buf))
2727 (defmacro org-export-with-buffer-copy (&rest body)
2728 "Apply BODY in a copy of the current buffer.
2729 The copy preserves local variables, visibility and contents of
2730 the original buffer. Point is at the beginning of the buffer
2731 when BODY is applied."
2732 (declare (debug t))
2733 (org-with-gensyms (buf-copy)
2734 `(let ((,buf-copy (org-export-copy-buffer)))
2735 (unwind-protect
2736 (with-current-buffer ,buf-copy
2737 (goto-char (point-min))
2738 (progn ,@body))
2739 (and (buffer-live-p ,buf-copy)
2740 ;; Kill copy without confirmation.
2741 (progn (with-current-buffer ,buf-copy
2742 (restore-buffer-modified-p nil))
2743 (kill-buffer ,buf-copy)))))))
2745 (defun org-export--generate-copy-script (buffer)
2746 "Generate a function duplicating BUFFER.
2748 The copy will preserve local variables, visibility, contents and
2749 narrowing of the original buffer. If a region was active in
2750 BUFFER, contents will be narrowed to that region instead.
2752 The resulting function can be eval'ed at a later time, from
2753 another buffer, effectively cloning the original buffer there."
2754 (with-current-buffer buffer
2755 `(lambda ()
2756 (let ((inhibit-modification-hooks t))
2757 ;; Buffer local variables.
2758 ,@(let (local-vars)
2759 (mapc
2760 (lambda (entry)
2761 (when (consp entry)
2762 (let ((var (car entry))
2763 (val (cdr entry)))
2764 (and (not (eq var 'org-font-lock-keywords))
2765 (or (memq var
2766 '(major-mode
2767 default-directory
2768 buffer-file-name
2769 buffer-file-coding-system
2770 outline-level
2771 outline-regexp
2772 buffer-invisibility-spec))
2773 (string-match "^\\(org-\\|orgtbl-\\)"
2774 (symbol-name var)))
2775 ;; Skip unreadable values, as they cannot be
2776 ;; sent to external process.
2777 (or (not val) (ignore-errors (read (format "%S" val))))
2778 (push `(set (make-local-variable (quote ,var))
2779 (quote ,val))
2780 local-vars)))))
2781 (buffer-local-variables (buffer-base-buffer)))
2782 local-vars)
2783 ;; Whole buffer contents.
2784 (insert
2785 ,(org-with-wide-buffer
2786 (buffer-substring-no-properties
2787 (point-min) (point-max))))
2788 ;; Narrowing.
2789 ,(if (org-region-active-p)
2790 `(narrow-to-region ,(region-beginning) ,(region-end))
2791 `(narrow-to-region ,(point-min) ,(point-max)))
2792 ;; Current position of point.
2793 (goto-char ,(point))
2794 ;; Overlays with invisible property.
2795 ,@(let (ov-set)
2796 (mapc
2797 (lambda (ov)
2798 (let ((invis-prop (overlay-get ov 'invisible)))
2799 (when invis-prop
2800 (push `(overlay-put
2801 (make-overlay ,(overlay-start ov)
2802 ,(overlay-end ov))
2803 'invisible (quote ,invis-prop))
2804 ov-set))))
2805 (overlays-in (point-min) (point-max)))
2806 ov-set)))))
2808 ;;;###autoload
2809 (defun org-export-as
2810 (backend &optional subtreep visible-only body-only ext-plist)
2811 "Transcode current Org buffer into BACKEND code.
2813 If narrowing is active in the current buffer, only transcode its
2814 narrowed part.
2816 If a region is active, transcode that region.
2818 When optional argument SUBTREEP is non-nil, transcode the
2819 sub-tree at point, extracting information from the headline
2820 properties first.
2822 When optional argument VISIBLE-ONLY is non-nil, don't export
2823 contents of hidden elements.
2825 When optional argument BODY-ONLY is non-nil, only return body
2826 code, without surrounding template.
2828 Optional argument EXT-PLIST, when provided, is a property list
2829 with external parameters overriding Org default settings, but
2830 still inferior to file-local settings.
2832 Return code as a string."
2833 (org-export-barf-if-invalid-backend backend)
2834 (save-excursion
2835 (save-restriction
2836 ;; Narrow buffer to an appropriate region or subtree for
2837 ;; parsing. If parsing subtree, be sure to remove main headline
2838 ;; too.
2839 (cond ((org-region-active-p)
2840 (narrow-to-region (region-beginning) (region-end)))
2841 (subtreep
2842 (org-narrow-to-subtree)
2843 (goto-char (point-min))
2844 (forward-line)
2845 (narrow-to-region (point) (point-max))))
2846 ;; Initialize communication channel with original buffer
2847 ;; attributes, unavailable in its copy.
2848 (let ((info (org-combine-plists
2849 (list :export-options
2850 (delq nil
2851 (list (and subtreep 'subtree)
2852 (and visible-only 'visible-only)
2853 (and body-only 'body-only))))
2854 (org-export--get-buffer-attributes)))
2855 tree)
2856 ;; Update communication channel and get parse tree. Buffer
2857 ;; isn't parsed directly. Instead, a temporary copy is
2858 ;; created, where include keywords, macros are expanded and
2859 ;; code blocks are evaluated.
2860 (org-export-with-buffer-copy
2861 ;; Run first hook with current back-end as argument.
2862 (run-hook-with-args 'org-export-before-processing-hook backend)
2863 (org-export-expand-include-keyword)
2864 ;; Update macro templates since #+INCLUDE keywords might have
2865 ;; added some new ones.
2866 (org-macro-initialize-templates)
2867 (org-macro-replace-all org-macro-templates)
2868 (org-export-execute-babel-code)
2869 ;; Update radio targets since keyword inclusion might have
2870 ;; added some more.
2871 (org-update-radio-target-regexp)
2872 ;; Run last hook with current back-end as argument.
2873 (goto-char (point-min))
2874 (run-hook-with-args 'org-export-before-parsing-hook backend)
2875 ;; Update communication channel with environment. Also
2876 ;; install user's and developer's filters.
2877 (setq info
2878 (org-export-install-filters
2879 (org-combine-plists
2880 info (org-export-get-environment backend subtreep ext-plist))))
2881 ;; Expand export-specific set of macros: {{{author}}},
2882 ;; {{{date}}}, {{{email}}} and {{{title}}}. It must be done
2883 ;; once regular macros have been expanded, since document
2884 ;; keywords may contain one of them.
2885 (org-macro-replace-all
2886 (list (cons "author"
2887 (org-element-interpret-data (plist-get info :author)))
2888 (cons "date"
2889 (org-element-interpret-data (plist-get info :date)))
2890 ;; EMAIL is not a parsed keyword: store it as-is.
2891 (cons "email" (or (plist-get info :email) ""))
2892 (cons "title"
2893 (org-element-interpret-data (plist-get info :title)))))
2894 ;; Call options filters and update export options. We do not
2895 ;; use `org-export-filter-apply-functions' here since the
2896 ;; arity of such filters is different.
2897 (dolist (filter (plist-get info :filter-options))
2898 (let ((result (funcall filter info backend)))
2899 (when result (setq info result))))
2900 ;; Parse buffer and call parse-tree filter on it.
2901 (setq tree
2902 (org-export-filter-apply-functions
2903 (plist-get info :filter-parse-tree)
2904 (org-element-parse-buffer nil visible-only) info))
2905 ;; Now tree is complete, compute its properties and add them
2906 ;; to communication channel.
2907 (setq info
2908 (org-combine-plists
2909 info (org-export-collect-tree-properties tree info)))
2910 ;; Eventually transcode TREE. Wrap the resulting string into
2911 ;; a template.
2912 (let* ((body (org-element-normalize-string
2913 (or (org-export-data tree info) "")))
2914 (inner-template (cdr (assq 'inner-template
2915 (plist-get info :translate-alist))))
2916 (full-body (if (not (functionp inner-template)) body
2917 (funcall inner-template body info)))
2918 (template (cdr (assq 'template
2919 (plist-get info :translate-alist)))))
2920 ;; Remove all text properties since they cannot be
2921 ;; retrieved from an external process. Finally call
2922 ;; final-output filter and return result.
2923 (org-no-properties
2924 (org-export-filter-apply-functions
2925 (plist-get info :filter-final-output)
2926 (if (or (not (functionp template)) body-only) full-body
2927 (funcall template full-body info))
2928 info))))))))
2930 ;;;###autoload
2931 (defun org-export-to-buffer
2932 (backend buffer &optional subtreep visible-only body-only ext-plist)
2933 "Call `org-export-as' with output to a specified buffer.
2935 BACKEND is the back-end used for transcoding, as a symbol.
2937 BUFFER is the output buffer. If it already exists, it will be
2938 erased first, otherwise, it will be created.
2940 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
2941 EXT-PLIST are similar to those used in `org-export-as', which
2942 see.
2944 If `org-export-copy-to-kill-ring' is non-nil, add buffer contents
2945 to kill ring. Return buffer."
2946 (let ((out (org-export-as backend subtreep visible-only body-only ext-plist))
2947 (buffer (get-buffer-create buffer)))
2948 (with-current-buffer buffer
2949 (erase-buffer)
2950 (insert out)
2951 (goto-char (point-min)))
2952 ;; Maybe add buffer contents to kill ring.
2953 (when (and org-export-copy-to-kill-ring (org-string-nw-p out))
2954 (org-kill-new out))
2955 ;; Return buffer.
2956 buffer))
2958 ;;;###autoload
2959 (defun org-export-to-file
2960 (backend file &optional subtreep visible-only body-only ext-plist)
2961 "Call `org-export-as' with output to a specified file.
2963 BACKEND is the back-end used for transcoding, as a symbol. FILE
2964 is the name of the output file, as a string.
2966 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
2967 EXT-PLIST are similar to those used in `org-export-as', which
2968 see.
2970 If `org-export-copy-to-kill-ring' is non-nil, add file contents
2971 to kill ring. Return output file's name."
2972 ;; Checks for FILE permissions. `write-file' would do the same, but
2973 ;; we'd rather avoid needless transcoding of parse tree.
2974 (unless (file-writable-p file) (error "Output file not writable"))
2975 ;; Insert contents to a temporary buffer and write it to FILE.
2976 (let ((out (org-export-as backend subtreep visible-only body-only ext-plist)))
2977 (with-temp-buffer
2978 (insert out)
2979 (let ((coding-system-for-write org-export-coding-system))
2980 (write-file file)))
2981 ;; Maybe add file contents to kill ring.
2982 (when (and org-export-copy-to-kill-ring (org-string-nw-p out))
2983 (org-kill-new out)))
2984 ;; Return full path.
2985 file)
2987 ;;;###autoload
2988 (defun org-export-string-as (string backend &optional body-only ext-plist)
2989 "Transcode STRING into BACKEND code.
2991 When optional argument BODY-ONLY is non-nil, only return body
2992 code, without preamble nor postamble.
2994 Optional argument EXT-PLIST, when provided, is a property list
2995 with external parameters overriding Org default settings, but
2996 still inferior to file-local settings.
2998 Return code as a string."
2999 (with-temp-buffer
3000 (insert string)
3001 (org-mode)
3002 (org-export-as backend nil nil body-only ext-plist)))
3004 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
3005 "Return output file's name according to buffer specifications.
3007 EXTENSION is a string representing the output file extension,
3008 with the leading dot.
3010 With a non-nil optional argument SUBTREEP, try to determine
3011 output file's name by looking for \"EXPORT_FILE_NAME\" property
3012 of subtree at point.
3014 When optional argument PUB-DIR is set, use it as the publishing
3015 directory.
3017 When optional argument VISIBLE-ONLY is non-nil, don't export
3018 contents of hidden elements.
3020 Return file name as a string."
3021 (let* ((visited-file (buffer-file-name (buffer-base-buffer)))
3022 (base-name
3023 ;; File name may come from EXPORT_FILE_NAME subtree
3024 ;; property, assuming point is at beginning of said
3025 ;; sub-tree.
3026 (file-name-sans-extension
3027 (or (and subtreep
3028 (org-entry-get
3029 (save-excursion
3030 (ignore-errors (org-back-to-heading) (point)))
3031 "EXPORT_FILE_NAME" t))
3032 ;; File name may be extracted from buffer's associated
3033 ;; file, if any.
3034 (and visited-file (file-name-nondirectory visited-file))
3035 ;; Can't determine file name on our own: Ask user.
3036 (let ((read-file-name-function
3037 (and org-completion-use-ido 'ido-read-file-name)))
3038 (read-file-name
3039 "Output file: " pub-dir nil nil nil
3040 (lambda (name)
3041 (string= (file-name-extension name t) extension)))))))
3042 (output-file
3043 ;; Build file name. Enforce EXTENSION over whatever user
3044 ;; may have come up with. PUB-DIR, if defined, always has
3045 ;; precedence over any provided path.
3046 (cond
3047 (pub-dir
3048 (concat (file-name-as-directory pub-dir)
3049 (file-name-nondirectory base-name)
3050 extension))
3051 ((file-name-absolute-p base-name) (concat base-name extension))
3052 (t (concat (file-name-as-directory ".") base-name extension)))))
3053 ;; If writing to OUTPUT-FILE would overwrite original file, append
3054 ;; EXTENSION another time to final name.
3055 (if (and visited-file (org-file-equal-p visited-file output-file))
3056 (concat output-file extension)
3057 output-file)))
3059 (defun org-export-expand-include-keyword (&optional included dir)
3060 "Expand every include keyword in buffer.
3061 Optional argument INCLUDED is a list of included file names along
3062 with their line restriction, when appropriate. It is used to
3063 avoid infinite recursion. Optional argument DIR is the current
3064 working directory. It is used to properly resolve relative
3065 paths."
3066 (let ((case-fold-search t))
3067 (goto-char (point-min))
3068 (while (re-search-forward "^[ \t]*#\\+INCLUDE: +\\(.*\\)[ \t]*$" nil t)
3069 (when (eq (org-element-type (save-match-data (org-element-at-point)))
3070 'keyword)
3071 (beginning-of-line)
3072 ;; Extract arguments from keyword's value.
3073 (let* ((value (match-string 1))
3074 (ind (org-get-indentation))
3075 (file (and (string-match "^\"\\(\\S-+\\)\"" value)
3076 (prog1 (expand-file-name (match-string 1 value) dir)
3077 (setq value (replace-match "" nil nil value)))))
3078 (lines
3079 (and (string-match
3080 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\"" value)
3081 (prog1 (match-string 1 value)
3082 (setq value (replace-match "" nil nil value)))))
3083 (env (cond ((string-match "\\<example\\>" value) 'example)
3084 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
3085 (match-string 1 value))))
3086 ;; Minimal level of included file defaults to the child
3087 ;; level of the current headline, if any, or one. It
3088 ;; only applies is the file is meant to be included as
3089 ;; an Org one.
3090 (minlevel
3091 (and (not env)
3092 (if (string-match ":minlevel +\\([0-9]+\\)" value)
3093 (prog1 (string-to-number (match-string 1 value))
3094 (setq value (replace-match "" nil nil value)))
3095 (let ((cur (org-current-level)))
3096 (if cur (1+ (org-reduced-level cur)) 1))))))
3097 ;; Remove keyword.
3098 (delete-region (point) (progn (forward-line) (point)))
3099 (cond
3100 ((not file) (error "Invalid syntax in INCLUDE keyword"))
3101 ((not (file-readable-p file)) (error "Cannot include file %s" file))
3102 ;; Check if files has already been parsed. Look after
3103 ;; inclusion lines too, as different parts of the same file
3104 ;; can be included too.
3105 ((member (list file lines) included)
3106 (error "Recursive file inclusion: %s" file))
3108 (cond
3109 ((eq env 'example)
3110 (insert
3111 (let ((ind-str (make-string ind ? ))
3112 (contents
3113 (org-escape-code-in-string
3114 (org-export--prepare-file-contents file lines))))
3115 (format "%s#+BEGIN_EXAMPLE\n%s%s#+END_EXAMPLE\n"
3116 ind-str contents ind-str))))
3117 ((stringp env)
3118 (insert
3119 (let ((ind-str (make-string ind ? ))
3120 (contents
3121 (org-escape-code-in-string
3122 (org-export--prepare-file-contents file lines))))
3123 (format "%s#+BEGIN_SRC %s\n%s%s#+END_SRC\n"
3124 ind-str env contents ind-str))))
3126 (insert
3127 (with-temp-buffer
3128 (org-mode)
3129 (insert
3130 (org-export--prepare-file-contents file lines ind minlevel))
3131 (org-export-expand-include-keyword
3132 (cons (list file lines) included)
3133 (file-name-directory file))
3134 (buffer-string))))))))))))
3136 (defun org-export--prepare-file-contents (file &optional lines ind minlevel)
3137 "Prepare the contents of FILE for inclusion and return them as a string.
3139 When optional argument LINES is a string specifying a range of
3140 lines, include only those lines.
3142 Optional argument IND, when non-nil, is an integer specifying the
3143 global indentation of returned contents. Since its purpose is to
3144 allow an included file to stay in the same environment it was
3145 created \(i.e. a list item), it doesn't apply past the first
3146 headline encountered.
3148 Optional argument MINLEVEL, when non-nil, is an integer
3149 specifying the level that any top-level headline in the included
3150 file should have."
3151 (with-temp-buffer
3152 (insert-file-contents file)
3153 (when lines
3154 (let* ((lines (split-string lines "-"))
3155 (lbeg (string-to-number (car lines)))
3156 (lend (string-to-number (cadr lines)))
3157 (beg (if (zerop lbeg) (point-min)
3158 (goto-char (point-min))
3159 (forward-line (1- lbeg))
3160 (point)))
3161 (end (if (zerop lend) (point-max)
3162 (goto-char (point-min))
3163 (forward-line (1- lend))
3164 (point))))
3165 (narrow-to-region beg end)))
3166 ;; Remove blank lines at beginning and end of contents. The logic
3167 ;; behind that removal is that blank lines around include keyword
3168 ;; override blank lines in included file.
3169 (goto-char (point-min))
3170 (org-skip-whitespace)
3171 (beginning-of-line)
3172 (delete-region (point-min) (point))
3173 (goto-char (point-max))
3174 (skip-chars-backward " \r\t\n")
3175 (forward-line)
3176 (delete-region (point) (point-max))
3177 ;; If IND is set, preserve indentation of include keyword until
3178 ;; the first headline encountered.
3179 (when ind
3180 (unless (eq major-mode 'org-mode) (org-mode))
3181 (goto-char (point-min))
3182 (let ((ind-str (make-string ind ? )))
3183 (while (not (or (eobp) (looking-at org-outline-regexp-bol)))
3184 ;; Do not move footnote definitions out of column 0.
3185 (unless (and (looking-at org-footnote-definition-re)
3186 (eq (org-element-type (org-element-at-point))
3187 'footnote-definition))
3188 (insert ind-str))
3189 (forward-line))))
3190 ;; When MINLEVEL is specified, compute minimal level for headlines
3191 ;; in the file (CUR-MIN), and remove stars to each headline so
3192 ;; that headlines with minimal level have a level of MINLEVEL.
3193 (when minlevel
3194 (unless (eq major-mode 'org-mode) (org-mode))
3195 (org-with-limited-levels
3196 (let ((levels (org-map-entries
3197 (lambda () (org-reduced-level (org-current-level))))))
3198 (when levels
3199 (let ((offset (- minlevel (apply 'min levels))))
3200 (unless (zerop offset)
3201 (when org-odd-levels-only (setq offset (* offset 2)))
3202 ;; Only change stars, don't bother moving whole
3203 ;; sections.
3204 (org-map-entries
3205 (lambda () (if (< offset 0) (delete-char (abs offset))
3206 (insert (make-string offset ?*)))))))))))
3207 (org-element-normalize-string (buffer-string))))
3209 (defun org-export-execute-babel-code ()
3210 "Execute every Babel code in the visible part of current buffer."
3211 ;; Get a pristine copy of current buffer so Babel references can be
3212 ;; properly resolved.
3213 (let ((reference (org-export-copy-buffer)))
3214 (unwind-protect (let ((org-current-export-file reference))
3215 (org-babel-exp-process-buffer))
3216 (kill-buffer reference))))
3220 ;;; Tools For Back-Ends
3222 ;; A whole set of tools is available to help build new exporters. Any
3223 ;; function general enough to have its use across many back-ends
3224 ;; should be added here.
3226 ;;;; For Affiliated Keywords
3228 ;; `org-export-read-attribute' reads a property from a given element
3229 ;; as a plist. It can be used to normalize affiliated keywords'
3230 ;; syntax.
3232 ;; Since captions can span over multiple lines and accept dual values,
3233 ;; their internal representation is a bit tricky. Therefore,
3234 ;; `org-export-get-caption' transparently returns a given element's
3235 ;; caption as a secondary string.
3237 (defun org-export-read-attribute (attribute element &optional property)
3238 "Turn ATTRIBUTE property from ELEMENT into a plist.
3240 When optional argument PROPERTY is non-nil, return the value of
3241 that property within attributes.
3243 This function assumes attributes are defined as \":keyword
3244 value\" pairs. It is appropriate for `:attr_html' like
3245 properties."
3246 (let ((attributes
3247 (let ((value (org-element-property attribute element)))
3248 (and value
3249 (read (format "(%s)" (mapconcat 'identity value " ")))))))
3250 (if property (plist-get attributes property) attributes)))
3252 (defun org-export-get-caption (element &optional shortp)
3253 "Return caption from ELEMENT as a secondary string.
3255 When optional argument SHORTP is non-nil, return short caption,
3256 as a secondary string, instead.
3258 Caption lines are separated by a white space."
3259 (let ((full-caption (org-element-property :caption element)) caption)
3260 (dolist (line full-caption (cdr caption))
3261 (let ((cap (funcall (if shortp 'cdr 'car) line)))
3262 (when cap
3263 (setq caption (nconc (list " ") (copy-sequence cap) caption)))))))
3266 ;;;; For Derived Back-ends
3268 ;; `org-export-with-backend' is a function allowing to locally use
3269 ;; another back-end to transcode some object or element. In a derived
3270 ;; back-end, it may be used as a fall-back function once all specific
3271 ;; cases have been treated.
3273 (defun org-export-with-backend (back-end data &optional contents info)
3274 "Call a transcoder from BACK-END on DATA.
3275 CONTENTS, when non-nil, is the transcoded contents of DATA
3276 element, as a string. INFO, when non-nil, is the communication
3277 channel used for export, as a plist.."
3278 (org-export-barf-if-invalid-backend back-end)
3279 (let ((type (org-element-type data)))
3280 (if (memq type '(nil org-data)) (error "No foreign transcoder available")
3281 (let ((transcoder
3282 (cdr (assq type (org-export-backend-translate-table back-end)))))
3283 (if (functionp transcoder) (funcall transcoder data contents info)
3284 (error "No foreign transcoder available"))))))
3287 ;;;; For Export Snippets
3289 ;; Every export snippet is transmitted to the back-end. Though, the
3290 ;; latter will only retain one type of export-snippet, ignoring
3291 ;; others, based on the former's target back-end. The function
3292 ;; `org-export-snippet-backend' returns that back-end for a given
3293 ;; export-snippet.
3295 (defun org-export-snippet-backend (export-snippet)
3296 "Return EXPORT-SNIPPET targeted back-end as a symbol.
3297 Translation, with `org-export-snippet-translation-alist', is
3298 applied."
3299 (let ((back-end (org-element-property :back-end export-snippet)))
3300 (intern
3301 (or (cdr (assoc back-end org-export-snippet-translation-alist))
3302 back-end))))
3305 ;;;; For Footnotes
3307 ;; `org-export-collect-footnote-definitions' is a tool to list
3308 ;; actually used footnotes definitions in the whole parse tree, or in
3309 ;; a headline, in order to add footnote listings throughout the
3310 ;; transcoded data.
3312 ;; `org-export-footnote-first-reference-p' is a predicate used by some
3313 ;; back-ends, when they need to attach the footnote definition only to
3314 ;; the first occurrence of the corresponding label.
3316 ;; `org-export-get-footnote-definition' and
3317 ;; `org-export-get-footnote-number' provide easier access to
3318 ;; additional information relative to a footnote reference.
3320 (defun org-export-collect-footnote-definitions (data info)
3321 "Return an alist between footnote numbers, labels and definitions.
3323 DATA is the parse tree from which definitions are collected.
3324 INFO is the plist used as a communication channel.
3326 Definitions are sorted by order of references. They either
3327 appear as Org data or as a secondary string for inlined
3328 footnotes. Unreferenced definitions are ignored."
3329 (let* (num-alist
3330 collect-fn ; for byte-compiler.
3331 (collect-fn
3332 (function
3333 (lambda (data)
3334 ;; Collect footnote number, label and definition in DATA.
3335 (org-element-map data 'footnote-reference
3336 (lambda (fn)
3337 (when (org-export-footnote-first-reference-p fn info)
3338 (let ((def (org-export-get-footnote-definition fn info)))
3339 (push
3340 (list (org-export-get-footnote-number fn info)
3341 (org-element-property :label fn)
3342 def)
3343 num-alist)
3344 ;; Also search in definition for nested footnotes.
3345 (when (eq (org-element-property :type fn) 'standard)
3346 (funcall collect-fn def)))))
3347 ;; Don't enter footnote definitions since it will happen
3348 ;; when their first reference is found.
3349 info nil 'footnote-definition)))))
3350 (funcall collect-fn (plist-get info :parse-tree))
3351 (reverse num-alist)))
3353 (defun org-export-footnote-first-reference-p (footnote-reference info)
3354 "Non-nil when a footnote reference is the first one for its label.
3356 FOOTNOTE-REFERENCE is the footnote reference being considered.
3357 INFO is the plist used as a communication channel."
3358 (let ((label (org-element-property :label footnote-reference)))
3359 ;; Anonymous footnotes are always a first reference.
3360 (if (not label) t
3361 ;; Otherwise, return the first footnote with the same LABEL and
3362 ;; test if it is equal to FOOTNOTE-REFERENCE.
3363 (let* (search-refs ; for byte-compiler.
3364 (search-refs
3365 (function
3366 (lambda (data)
3367 (org-element-map data 'footnote-reference
3368 (lambda (fn)
3369 (cond
3370 ((string= (org-element-property :label fn) label)
3371 (throw 'exit fn))
3372 ;; If FN isn't inlined, be sure to traverse its
3373 ;; definition before resuming search. See
3374 ;; comments in `org-export-get-footnote-number'
3375 ;; for more information.
3376 ((eq (org-element-property :type fn) 'standard)
3377 (funcall search-refs
3378 (org-export-get-footnote-definition fn info)))))
3379 ;; Don't enter footnote definitions since it will
3380 ;; happen when their first reference is found.
3381 info 'first-match 'footnote-definition)))))
3382 (eq (catch 'exit (funcall search-refs (plist-get info :parse-tree)))
3383 footnote-reference)))))
3385 (defun org-export-get-footnote-definition (footnote-reference info)
3386 "Return definition of FOOTNOTE-REFERENCE as parsed data.
3387 INFO is the plist used as a communication channel. If no such
3388 definition can be found, return the \"DEFINITION NOT FOUND\"
3389 string."
3390 (let ((label (org-element-property :label footnote-reference)))
3391 (or (org-element-property :inline-definition footnote-reference)
3392 (cdr (assoc label (plist-get info :footnote-definition-alist)))
3393 "DEFINITION NOT FOUND.")))
3395 (defun org-export-get-footnote-number (footnote info)
3396 "Return number associated to a footnote.
3398 FOOTNOTE is either a footnote reference or a footnote definition.
3399 INFO is the plist used as a communication channel."
3400 (let* ((label (org-element-property :label footnote))
3401 seen-refs
3402 search-ref ; For byte-compiler.
3403 (search-ref
3404 (function
3405 (lambda (data)
3406 ;; Search footnote references through DATA, filling
3407 ;; SEEN-REFS along the way.
3408 (org-element-map data 'footnote-reference
3409 (lambda (fn)
3410 (let ((fn-lbl (org-element-property :label fn)))
3411 (cond
3412 ;; Anonymous footnote match: return number.
3413 ((and (not fn-lbl) (eq fn footnote))
3414 (throw 'exit (1+ (length seen-refs))))
3415 ;; Labels match: return number.
3416 ((and label (string= label fn-lbl))
3417 (throw 'exit (1+ (length seen-refs))))
3418 ;; Anonymous footnote: it's always a new one.
3419 ;; Also, be sure to return nil from the `cond' so
3420 ;; `first-match' doesn't get us out of the loop.
3421 ((not fn-lbl) (push 'inline seen-refs) nil)
3422 ;; Label not seen so far: add it so SEEN-REFS.
3424 ;; Also search for subsequent references in
3425 ;; footnote definition so numbering follows
3426 ;; reading logic. Note that we don't have to care
3427 ;; about inline definitions, since
3428 ;; `org-element-map' already traverses them at the
3429 ;; right time.
3431 ;; Once again, return nil to stay in the loop.
3432 ((not (member fn-lbl seen-refs))
3433 (push fn-lbl seen-refs)
3434 (funcall search-ref
3435 (org-export-get-footnote-definition fn info))
3436 nil))))
3437 ;; Don't enter footnote definitions since it will
3438 ;; happen when their first reference is found.
3439 info 'first-match 'footnote-definition)))))
3440 (catch 'exit (funcall search-ref (plist-get info :parse-tree)))))
3443 ;;;; For Headlines
3445 ;; `org-export-get-relative-level' is a shortcut to get headline
3446 ;; level, relatively to the lower headline level in the parsed tree.
3448 ;; `org-export-get-headline-number' returns the section number of an
3449 ;; headline, while `org-export-number-to-roman' allows to convert it
3450 ;; to roman numbers.
3452 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
3453 ;; `org-export-last-sibling-p' are three useful predicates when it
3454 ;; comes to fulfill the `:headline-levels' property.
3456 ;; `org-export-get-tags', `org-export-get-category' and
3457 ;; `org-export-get-node-property' extract useful information from an
3458 ;; headline or a parent headline. They all handle inheritance.
3460 ;; `org-export-get-alt-title' tries to retrieve an alternative title,
3461 ;; as a secondary string, suitable for table of contents. It falls
3462 ;; back onto default title.
3464 (defun org-export-get-relative-level (headline info)
3465 "Return HEADLINE relative level within current parsed tree.
3466 INFO is a plist holding contextual information."
3467 (+ (org-element-property :level headline)
3468 (or (plist-get info :headline-offset) 0)))
3470 (defun org-export-low-level-p (headline info)
3471 "Non-nil when HEADLINE is considered as low level.
3473 INFO is a plist used as a communication channel.
3475 A low level headlines has a relative level greater than
3476 `:headline-levels' property value.
3478 Return value is the difference between HEADLINE relative level
3479 and the last level being considered as high enough, or nil."
3480 (let ((limit (plist-get info :headline-levels)))
3481 (when (wholenump limit)
3482 (let ((level (org-export-get-relative-level headline info)))
3483 (and (> level limit) (- level limit))))))
3485 (defun org-export-get-headline-number (headline info)
3486 "Return HEADLINE numbering as a list of numbers.
3487 INFO is a plist holding contextual information."
3488 (cdr (assoc headline (plist-get info :headline-numbering))))
3490 (defun org-export-numbered-headline-p (headline info)
3491 "Return a non-nil value if HEADLINE element should be numbered.
3492 INFO is a plist used as a communication channel."
3493 (let ((sec-num (plist-get info :section-numbers))
3494 (level (org-export-get-relative-level headline info)))
3495 (if (wholenump sec-num) (<= level sec-num) sec-num)))
3497 (defun org-export-number-to-roman (n)
3498 "Convert integer N into a roman numeral."
3499 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
3500 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
3501 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
3502 ( 1 . "I")))
3503 (res ""))
3504 (if (<= n 0)
3505 (number-to-string n)
3506 (while roman
3507 (if (>= n (caar roman))
3508 (setq n (- n (caar roman))
3509 res (concat res (cdar roman)))
3510 (pop roman)))
3511 res)))
3513 (defun org-export-get-tags (element info &optional tags inherited)
3514 "Return list of tags associated to ELEMENT.
3516 ELEMENT has either an `headline' or an `inlinetask' type. INFO
3517 is a plist used as a communication channel.
3519 Select tags (see `org-export-select-tags') and exclude tags (see
3520 `org-export-exclude-tags') are removed from the list.
3522 When non-nil, optional argument TAGS should be a list of strings.
3523 Any tag belonging to this list will also be removed.
3525 When optional argument INHERITED is non-nil, tags can also be
3526 inherited from parent headlines and FILETAGS keywords."
3527 (org-remove-if
3528 (lambda (tag) (or (member tag (plist-get info :select-tags))
3529 (member tag (plist-get info :exclude-tags))
3530 (member tag tags)))
3531 (if (not inherited) (org-element-property :tags element)
3532 ;; Build complete list of inherited tags.
3533 (let ((current-tag-list (org-element-property :tags element)))
3534 (mapc
3535 (lambda (parent)
3536 (mapc
3537 (lambda (tag)
3538 (when (and (memq (org-element-type parent) '(headline inlinetask))
3539 (not (member tag current-tag-list)))
3540 (push tag current-tag-list)))
3541 (org-element-property :tags parent)))
3542 (org-export-get-genealogy element))
3543 ;; Add FILETAGS keywords and return results.
3544 (org-uniquify (append (plist-get info :filetags) current-tag-list))))))
3546 (defun org-export-get-node-property (property blob &optional inherited)
3547 "Return node PROPERTY value for BLOB.
3549 PROPERTY is an upcase symbol (i.e. `:COOKIE_DATA'). BLOB is an
3550 element or object.
3552 If optional argument INHERITED is non-nil, the value can be
3553 inherited from a parent headline.
3555 Return value is a string or nil."
3556 (let ((headline (if (eq (org-element-type blob) 'headline) blob
3557 (org-export-get-parent-headline blob))))
3558 (if (not inherited) (org-element-property property blob)
3559 (let ((parent headline) value)
3560 (catch 'found
3561 (while parent
3562 (when (plist-member (nth 1 parent) property)
3563 (throw 'found (org-element-property property parent)))
3564 (setq parent (org-element-property :parent parent))))))))
3566 (defun org-export-get-category (blob info)
3567 "Return category for element or object BLOB.
3569 INFO is a plist used as a communication channel.
3571 CATEGORY is automatically inherited from a parent headline, from
3572 #+CATEGORY: keyword or created out of original file name. If all
3573 fail, the fall-back value is \"???\"."
3574 (or (let ((headline (if (eq (org-element-type blob) 'headline) blob
3575 (org-export-get-parent-headline blob))))
3576 ;; Almost like `org-export-node-property', but we cannot trust
3577 ;; `plist-member' as every headline has a `:CATEGORY'
3578 ;; property, would it be nil or equal to "???" (which has the
3579 ;; same meaning).
3580 (let ((parent headline) value)
3581 (catch 'found
3582 (while parent
3583 (let ((category (org-element-property :CATEGORY parent)))
3584 (and category (not (equal "???" category))
3585 (throw 'found category)))
3586 (setq parent (org-element-property :parent parent))))))
3587 (org-element-map (plist-get info :parse-tree) 'keyword
3588 (lambda (kwd)
3589 (when (equal (org-element-property :key kwd) "CATEGORY")
3590 (org-element-property :value kwd)))
3591 info 'first-match)
3592 (let ((file (plist-get info :input-file)))
3593 (and file (file-name-sans-extension (file-name-nondirectory file))))
3594 "???"))
3596 (defun org-export-get-alt-title (headline info)
3597 "Return alternative title for HEADLINE, as a secondary string.
3598 INFO is a plist used as a communication channel. If no optional
3599 title is defined, fall-back to the regular title."
3600 (or (org-element-property :alt-title headline)
3601 (org-element-property :title headline)))
3603 (defun org-export-first-sibling-p (headline info)
3604 "Non-nil when HEADLINE is the first sibling in its sub-tree.
3605 INFO is a plist used as a communication channel."
3606 (not (eq (org-element-type (org-export-get-previous-element headline info))
3607 'headline)))
3609 (defun org-export-last-sibling-p (headline info)
3610 "Non-nil when HEADLINE is the last sibling in its sub-tree.
3611 INFO is a plist used as a communication channel."
3612 (not (org-export-get-next-element headline info)))
3615 ;;;; For Links
3617 ;; `org-export-solidify-link-text' turns a string into a safer version
3618 ;; for links, replacing most non-standard characters with hyphens.
3620 ;; `org-export-get-coderef-format' returns an appropriate format
3621 ;; string for coderefs.
3623 ;; `org-export-inline-image-p' returns a non-nil value when the link
3624 ;; provided should be considered as an inline image.
3626 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
3627 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
3628 ;; returns an appropriate unique identifier when found, or nil.
3630 ;; `org-export-resolve-id-link' returns the first headline with
3631 ;; specified id or custom-id in parse tree, the path to the external
3632 ;; file with the id or nil when neither was found.
3634 ;; `org-export-resolve-coderef' associates a reference to a line
3635 ;; number in the element it belongs, or returns the reference itself
3636 ;; when the element isn't numbered.
3638 (defun org-export-solidify-link-text (s)
3639 "Take link text S and make a safe target out of it."
3640 (save-match-data
3641 (mapconcat 'identity (org-split-string s "[^a-zA-Z0-9_.-:]+") "-")))
3643 (defun org-export-get-coderef-format (path desc)
3644 "Return format string for code reference link.
3645 PATH is the link path. DESC is its description."
3646 (save-match-data
3647 (cond ((not desc) "%s")
3648 ((string-match (regexp-quote (concat "(" path ")")) desc)
3649 (replace-match "%s" t t desc))
3650 (t desc))))
3652 (defun org-export-inline-image-p (link &optional rules)
3653 "Non-nil if LINK object points to an inline image.
3655 Optional argument is a set of RULES defining inline images. It
3656 is an alist where associations have the following shape:
3658 \(TYPE . REGEXP)
3660 Applying a rule means apply REGEXP against LINK's path when its
3661 type is TYPE. The function will return a non-nil value if any of
3662 the provided rules is non-nil. The default rule is
3663 `org-export-default-inline-image-rule'.
3665 This only applies to links without a description."
3666 (and (not (org-element-contents link))
3667 (let ((case-fold-search t)
3668 (rules (or rules org-export-default-inline-image-rule)))
3669 (catch 'exit
3670 (mapc
3671 (lambda (rule)
3672 (and (string= (org-element-property :type link) (car rule))
3673 (string-match (cdr rule)
3674 (org-element-property :path link))
3675 (throw 'exit t)))
3676 rules)
3677 ;; Return nil if no rule matched.
3678 nil))))
3680 (defun org-export-resolve-coderef (ref info)
3681 "Resolve a code reference REF.
3683 INFO is a plist used as a communication channel.
3685 Return associated line number in source code, or REF itself,
3686 depending on src-block or example element's switches."
3687 (org-element-map (plist-get info :parse-tree) '(example-block src-block)
3688 (lambda (el)
3689 (with-temp-buffer
3690 (insert (org-trim (org-element-property :value el)))
3691 (let* ((label-fmt (regexp-quote
3692 (or (org-element-property :label-fmt el)
3693 org-coderef-label-format)))
3694 (ref-re
3695 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
3696 (replace-regexp-in-string "%s" ref label-fmt nil t))))
3697 ;; Element containing REF is found. Resolve it to either
3698 ;; a label or a line number, as needed.
3699 (when (re-search-backward ref-re nil t)
3700 (cond
3701 ((org-element-property :use-labels el) ref)
3702 ((eq (org-element-property :number-lines el) 'continued)
3703 (+ (org-export-get-loc el info) (line-number-at-pos)))
3704 (t (line-number-at-pos)))))))
3705 info 'first-match))
3707 (defun org-export-resolve-fuzzy-link (link info)
3708 "Return LINK destination.
3710 INFO is a plist holding contextual information.
3712 Return value can be an object, an element, or nil:
3714 - If LINK path matches a target object (i.e. <<path>>) or
3715 element (i.e. \"#+TARGET: path\"), return it.
3717 - If LINK path exactly matches the name affiliated keyword
3718 \(i.e. #+NAME: path) of an element, return that element.
3720 - If LINK path exactly matches any headline name, return that
3721 element. If more than one headline share that name, priority
3722 will be given to the one with the closest common ancestor, if
3723 any, or the first one in the parse tree otherwise.
3725 - Otherwise, return nil.
3727 Assume LINK type is \"fuzzy\". White spaces are not
3728 significant."
3729 (let* ((raw-path (org-element-property :path link))
3730 (match-title-p (eq (aref raw-path 0) ?*))
3731 ;; Split PATH at white spaces so matches are space
3732 ;; insensitive.
3733 (path (org-split-string
3734 (if match-title-p (substring raw-path 1) raw-path))))
3735 (cond
3736 ;; First try to find a matching "<<path>>" unless user specified
3737 ;; he was looking for a headline (path starts with a *
3738 ;; character).
3739 ((and (not match-title-p)
3740 (org-element-map (plist-get info :parse-tree) '(keyword target)
3741 (lambda (blob)
3742 (and (or (eq (org-element-type blob) 'target)
3743 (equal (org-element-property :key blob) "TARGET"))
3744 (equal (org-split-string (org-element-property :value blob))
3745 path)
3746 blob))
3747 info t)))
3748 ;; Then try to find an element with a matching "#+NAME: path"
3749 ;; affiliated keyword.
3750 ((and (not match-title-p)
3751 (org-element-map (plist-get info :parse-tree)
3752 org-element-all-elements
3753 (lambda (el)
3754 (let ((name (org-element-property :name el)))
3755 (when (and name (equal (org-split-string name) path)) el)))
3756 info 'first-match)))
3757 ;; Last case: link either points to a headline or to
3758 ;; nothingness. Try to find the source, with priority given to
3759 ;; headlines with the closest common ancestor. If such candidate
3760 ;; is found, return it, otherwise return nil.
3762 (let ((find-headline
3763 (function
3764 ;; Return first headline whose `:raw-value' property is
3765 ;; NAME in parse tree DATA, or nil. Statistics cookies
3766 ;; are ignored.
3767 (lambda (name data)
3768 (org-element-map data 'headline
3769 (lambda (headline)
3770 (when (equal (org-split-string
3771 (replace-regexp-in-string
3772 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
3773 (org-element-property :raw-value headline)))
3774 name)
3775 headline))
3776 info 'first-match)))))
3777 ;; Search among headlines sharing an ancestor with link, from
3778 ;; closest to farthest.
3779 (or (catch 'exit
3780 (mapc
3781 (lambda (parent)
3782 (when (eq (org-element-type parent) 'headline)
3783 (let ((foundp (funcall find-headline path parent)))
3784 (when foundp (throw 'exit foundp)))))
3785 (org-export-get-genealogy link)) nil)
3786 ;; No match with a common ancestor: try full parse-tree.
3787 (funcall find-headline path (plist-get info :parse-tree))))))))
3789 (defun org-export-resolve-id-link (link info)
3790 "Return headline referenced as LINK destination.
3792 INFO is a plist used as a communication channel.
3794 Return value can be the headline element matched in current parse
3795 tree, a file name or nil. Assume LINK type is either \"id\" or
3796 \"custom-id\"."
3797 (let ((id (org-element-property :path link)))
3798 ;; First check if id is within the current parse tree.
3799 (or (org-element-map (plist-get info :parse-tree) 'headline
3800 (lambda (headline)
3801 (when (or (string= (org-element-property :ID headline) id)
3802 (string= (org-element-property :CUSTOM_ID headline) id))
3803 headline))
3804 info 'first-match)
3805 ;; Otherwise, look for external files.
3806 (cdr (assoc id (plist-get info :id-alist))))))
3808 (defun org-export-resolve-radio-link (link info)
3809 "Return radio-target object referenced as LINK destination.
3811 INFO is a plist used as a communication channel.
3813 Return value can be a radio-target object or nil. Assume LINK
3814 has type \"radio\"."
3815 (let ((path (org-element-property :path link)))
3816 (org-element-map (plist-get info :parse-tree) 'radio-target
3817 (lambda (radio)
3818 (and (compare-strings
3819 (org-element-property :value radio) 0 nil path 0 nil t)
3820 radio))
3821 info 'first-match)))
3824 ;;;; For References
3826 ;; `org-export-get-ordinal' associates a sequence number to any object
3827 ;; or element.
3829 (defun org-export-get-ordinal (element info &optional types predicate)
3830 "Return ordinal number of an element or object.
3832 ELEMENT is the element or object considered. INFO is the plist
3833 used as a communication channel.
3835 Optional argument TYPES, when non-nil, is a list of element or
3836 object types, as symbols, that should also be counted in.
3837 Otherwise, only provided element's type is considered.
3839 Optional argument PREDICATE is a function returning a non-nil
3840 value if the current element or object should be counted in. It
3841 accepts two arguments: the element or object being considered and
3842 the plist used as a communication channel. This allows to count
3843 only a certain type of objects (i.e. inline images).
3845 Return value is a list of numbers if ELEMENT is a headline or an
3846 item. It is nil for keywords. It represents the footnote number
3847 for footnote definitions and footnote references. If ELEMENT is
3848 a target, return the same value as if ELEMENT was the closest
3849 table, item or headline containing the target. In any other
3850 case, return the sequence number of ELEMENT among elements or
3851 objects of the same type."
3852 ;; A target keyword, representing an invisible target, never has
3853 ;; a sequence number.
3854 (unless (eq (org-element-type element) 'keyword)
3855 ;; Ordinal of a target object refer to the ordinal of the closest
3856 ;; table, item, or headline containing the object.
3857 (when (eq (org-element-type element) 'target)
3858 (setq element
3859 (loop for parent in (org-export-get-genealogy element)
3860 when
3861 (memq
3862 (org-element-type parent)
3863 '(footnote-definition footnote-reference headline item
3864 table))
3865 return parent)))
3866 (case (org-element-type element)
3867 ;; Special case 1: A headline returns its number as a list.
3868 (headline (org-export-get-headline-number element info))
3869 ;; Special case 2: An item returns its number as a list.
3870 (item (let ((struct (org-element-property :structure element)))
3871 (org-list-get-item-number
3872 (org-element-property :begin element)
3873 struct
3874 (org-list-prevs-alist struct)
3875 (org-list-parents-alist struct))))
3876 ((footnote-definition footnote-reference)
3877 (org-export-get-footnote-number element info))
3878 (otherwise
3879 (let ((counter 0))
3880 ;; Increment counter until ELEMENT is found again.
3881 (org-element-map (plist-get info :parse-tree)
3882 (or types (org-element-type element))
3883 (lambda (el)
3884 (cond
3885 ((eq element el) (1+ counter))
3886 ((not predicate) (incf counter) nil)
3887 ((funcall predicate el info) (incf counter) nil)))
3888 info 'first-match))))))
3891 ;;;; For Src-Blocks
3893 ;; `org-export-get-loc' counts number of code lines accumulated in
3894 ;; src-block or example-block elements with a "+n" switch until
3895 ;; a given element, excluded. Note: "-n" switches reset that count.
3897 ;; `org-export-unravel-code' extracts source code (along with a code
3898 ;; references alist) from an `element-block' or `src-block' type
3899 ;; element.
3901 ;; `org-export-format-code' applies a formatting function to each line
3902 ;; of code, providing relative line number and code reference when
3903 ;; appropriate. Since it doesn't access the original element from
3904 ;; which the source code is coming, it expects from the code calling
3905 ;; it to know if lines should be numbered and if code references
3906 ;; should appear.
3908 ;; Eventually, `org-export-format-code-default' is a higher-level
3909 ;; function (it makes use of the two previous functions) which handles
3910 ;; line numbering and code references inclusion, and returns source
3911 ;; code in a format suitable for plain text or verbatim output.
3913 (defun org-export-get-loc (element info)
3914 "Return accumulated lines of code up to ELEMENT.
3916 INFO is the plist used as a communication channel.
3918 ELEMENT is excluded from count."
3919 (let ((loc 0))
3920 (org-element-map (plist-get info :parse-tree)
3921 `(src-block example-block ,(org-element-type element))
3922 (lambda (el)
3923 (cond
3924 ;; ELEMENT is reached: Quit the loop.
3925 ((eq el element))
3926 ;; Only count lines from src-block and example-block elements
3927 ;; with a "+n" or "-n" switch. A "-n" switch resets counter.
3928 ((not (memq (org-element-type el) '(src-block example-block))) nil)
3929 ((let ((linums (org-element-property :number-lines el)))
3930 (when linums
3931 ;; Accumulate locs or reset them.
3932 (let ((lines (org-count-lines
3933 (org-trim (org-element-property :value el)))))
3934 (setq loc (if (eq linums 'new) lines (+ loc lines))))))
3935 ;; Return nil to stay in the loop.
3936 nil)))
3937 info 'first-match)
3938 ;; Return value.
3939 loc))
3941 (defun org-export-unravel-code (element)
3942 "Clean source code and extract references out of it.
3944 ELEMENT has either a `src-block' an `example-block' type.
3946 Return a cons cell whose CAR is the source code, cleaned from any
3947 reference and protective comma and CDR is an alist between
3948 relative line number (integer) and name of code reference on that
3949 line (string)."
3950 (let* ((line 0) refs
3951 ;; Get code and clean it. Remove blank lines at its
3952 ;; beginning and end.
3953 (code (let ((c (replace-regexp-in-string
3954 "\\`\\([ \t]*\n\\)+" ""
3955 (replace-regexp-in-string
3956 "\\([ \t]*\n\\)*[ \t]*\\'" "\n"
3957 (org-element-property :value element)))))
3958 ;; If appropriate, remove global indentation.
3959 (if (or org-src-preserve-indentation
3960 (org-element-property :preserve-indent element))
3962 (org-remove-indentation c))))
3963 ;; Get format used for references.
3964 (label-fmt (regexp-quote
3965 (or (org-element-property :label-fmt element)
3966 org-coderef-label-format)))
3967 ;; Build a regexp matching a loc with a reference.
3968 (with-ref-re
3969 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)[ \t]*\\)$"
3970 (replace-regexp-in-string
3971 "%s" "\\([-a-zA-Z0-9_ ]+\\)" label-fmt nil t))))
3972 ;; Return value.
3973 (cons
3974 ;; Code with references removed.
3975 (org-element-normalize-string
3976 (mapconcat
3977 (lambda (loc)
3978 (incf line)
3979 (if (not (string-match with-ref-re loc)) loc
3980 ;; Ref line: remove ref, and signal its position in REFS.
3981 (push (cons line (match-string 3 loc)) refs)
3982 (replace-match "" nil nil loc 1)))
3983 (org-split-string code "\n") "\n"))
3984 ;; Reference alist.
3985 refs)))
3987 (defun org-export-format-code (code fun &optional num-lines ref-alist)
3988 "Format CODE by applying FUN line-wise and return it.
3990 CODE is a string representing the code to format. FUN is
3991 a function. It must accept three arguments: a line of
3992 code (string), the current line number (integer) or nil and the
3993 reference associated to the current line (string) or nil.
3995 Optional argument NUM-LINES can be an integer representing the
3996 number of code lines accumulated until the current code. Line
3997 numbers passed to FUN will take it into account. If it is nil,
3998 FUN's second argument will always be nil. This number can be
3999 obtained with `org-export-get-loc' function.
4001 Optional argument REF-ALIST can be an alist between relative line
4002 number (i.e. ignoring NUM-LINES) and the name of the code
4003 reference on it. If it is nil, FUN's third argument will always
4004 be nil. It can be obtained through the use of
4005 `org-export-unravel-code' function."
4006 (let ((--locs (org-split-string code "\n"))
4007 (--line 0))
4008 (org-element-normalize-string
4009 (mapconcat
4010 (lambda (--loc)
4011 (incf --line)
4012 (let ((--ref (cdr (assq --line ref-alist))))
4013 (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
4014 --locs "\n"))))
4016 (defun org-export-format-code-default (element info)
4017 "Return source code from ELEMENT, formatted in a standard way.
4019 ELEMENT is either a `src-block' or `example-block' element. INFO
4020 is a plist used as a communication channel.
4022 This function takes care of line numbering and code references
4023 inclusion. Line numbers, when applicable, appear at the
4024 beginning of the line, separated from the code by two white
4025 spaces. Code references, on the other hand, appear flushed to
4026 the right, separated by six white spaces from the widest line of
4027 code."
4028 ;; Extract code and references.
4029 (let* ((code-info (org-export-unravel-code element))
4030 (code (car code-info))
4031 (code-lines (org-split-string code "\n")))
4032 (if (null code-lines) ""
4033 (let* ((refs (and (org-element-property :retain-labels element)
4034 (cdr code-info)))
4035 ;; Handle line numbering.
4036 (num-start (case (org-element-property :number-lines element)
4037 (continued (org-export-get-loc element info))
4038 (new 0)))
4039 (num-fmt
4040 (and num-start
4041 (format "%%%ds "
4042 (length (number-to-string
4043 (+ (length code-lines) num-start))))))
4044 ;; Prepare references display, if required. Any reference
4045 ;; should start six columns after the widest line of code,
4046 ;; wrapped with parenthesis.
4047 (max-width
4048 (+ (apply 'max (mapcar 'length code-lines))
4049 (if (not num-start) 0 (length (format num-fmt num-start))))))
4050 (org-export-format-code
4051 code
4052 (lambda (loc line-num ref)
4053 (let ((number-str (and num-fmt (format num-fmt line-num))))
4054 (concat
4055 number-str
4057 (and ref
4058 (concat (make-string
4059 (- (+ 6 max-width)
4060 (+ (length loc) (length number-str))) ? )
4061 (format "(%s)" ref))))))
4062 num-start refs)))))
4065 ;;;; For Tables
4067 ;; `org-export-table-has-special-column-p' and and
4068 ;; `org-export-table-row-is-special-p' are predicates used to look for
4069 ;; meta-information about the table structure.
4071 ;; `org-table-has-header-p' tells when the rows before the first rule
4072 ;; should be considered as table's header.
4074 ;; `org-export-table-cell-width', `org-export-table-cell-alignment'
4075 ;; and `org-export-table-cell-borders' extract information from
4076 ;; a table-cell element.
4078 ;; `org-export-table-dimensions' gives the number on rows and columns
4079 ;; in the table, ignoring horizontal rules and special columns.
4080 ;; `org-export-table-cell-address', given a table-cell object, returns
4081 ;; the absolute address of a cell. On the other hand,
4082 ;; `org-export-get-table-cell-at' does the contrary.
4084 ;; `org-export-table-cell-starts-colgroup-p',
4085 ;; `org-export-table-cell-ends-colgroup-p',
4086 ;; `org-export-table-row-starts-rowgroup-p',
4087 ;; `org-export-table-row-ends-rowgroup-p',
4088 ;; `org-export-table-row-starts-header-p' and
4089 ;; `org-export-table-row-ends-header-p' indicate position of current
4090 ;; row or cell within the table.
4092 (defun org-export-table-has-special-column-p (table)
4093 "Non-nil when TABLE has a special column.
4094 All special columns will be ignored during export."
4095 ;; The table has a special column when every first cell of every row
4096 ;; has an empty value or contains a symbol among "/", "#", "!", "$",
4097 ;; "*" "_" and "^". Though, do not consider a first row containing
4098 ;; only empty cells as special.
4099 (let ((special-column-p 'empty))
4100 (catch 'exit
4101 (mapc
4102 (lambda (row)
4103 (when (eq (org-element-property :type row) 'standard)
4104 (let ((value (org-element-contents
4105 (car (org-element-contents row)))))
4106 (cond ((member value '(("/") ("#") ("!") ("$") ("*") ("_") ("^")))
4107 (setq special-column-p 'special))
4108 ((not value))
4109 (t (throw 'exit nil))))))
4110 (org-element-contents table))
4111 (eq special-column-p 'special))))
4113 (defun org-export-table-has-header-p (table info)
4114 "Non-nil when TABLE has an header.
4116 INFO is a plist used as a communication channel.
4118 A table has an header when it contains at least two row groups."
4119 (let ((rowgroup 1) row-flag)
4120 (org-element-map table 'table-row
4121 (lambda (row)
4122 (cond
4123 ((> rowgroup 1) t)
4124 ((and row-flag (eq (org-element-property :type row) 'rule))
4125 (incf rowgroup) (setq row-flag nil))
4126 ((and (not row-flag) (eq (org-element-property :type row) 'standard))
4127 (setq row-flag t) nil)))
4128 info)))
4130 (defun org-export-table-row-is-special-p (table-row info)
4131 "Non-nil if TABLE-ROW is considered special.
4133 INFO is a plist used as the communication channel.
4135 All special rows will be ignored during export."
4136 (when (eq (org-element-property :type table-row) 'standard)
4137 (let ((first-cell (org-element-contents
4138 (car (org-element-contents table-row)))))
4139 ;; A row is special either when...
4141 ;; ... it starts with a field only containing "/",
4142 (equal first-cell '("/"))
4143 ;; ... the table contains a special column and the row start
4144 ;; with a marking character among, "^", "_", "$" or "!",
4145 (and (org-export-table-has-special-column-p
4146 (org-export-get-parent table-row))
4147 (member first-cell '(("^") ("_") ("$") ("!"))))
4148 ;; ... it contains only alignment cookies and empty cells.
4149 (let ((special-row-p 'empty))
4150 (catch 'exit
4151 (mapc
4152 (lambda (cell)
4153 (let ((value (org-element-contents cell)))
4154 ;; Since VALUE is a secondary string, the following
4155 ;; checks avoid expanding it with `org-export-data'.
4156 (cond ((not value))
4157 ((and (not (cdr value))
4158 (stringp (car value))
4159 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'"
4160 (car value)))
4161 (setq special-row-p 'cookie))
4162 (t (throw 'exit nil)))))
4163 (org-element-contents table-row))
4164 (eq special-row-p 'cookie)))))))
4166 (defun org-export-table-row-group (table-row info)
4167 "Return TABLE-ROW's group.
4169 INFO is a plist used as the communication channel.
4171 Return value is the group number, as an integer, or nil special
4172 rows and table rules. Group 1 is also table's header."
4173 (unless (or (eq (org-element-property :type table-row) 'rule)
4174 (org-export-table-row-is-special-p table-row info))
4175 (let ((group 0) row-flag)
4176 (catch 'found
4177 (mapc
4178 (lambda (row)
4179 (cond
4180 ((and (eq (org-element-property :type row) 'standard)
4181 (not (org-export-table-row-is-special-p row info)))
4182 (unless row-flag (incf group) (setq row-flag t)))
4183 ((eq (org-element-property :type row) 'rule)
4184 (setq row-flag nil)))
4185 (when (eq table-row row) (throw 'found group)))
4186 (org-element-contents (org-export-get-parent table-row)))))))
4188 (defun org-export-table-cell-width (table-cell info)
4189 "Return TABLE-CELL contents width.
4191 INFO is a plist used as the communication channel.
4193 Return value is the width given by the last width cookie in the
4194 same column as TABLE-CELL, or nil."
4195 (let* ((row (org-export-get-parent table-cell))
4196 (column (let ((cells (org-element-contents row)))
4197 (- (length cells) (length (memq table-cell cells)))))
4198 (table (org-export-get-parent-table table-cell))
4199 cookie-width)
4200 (mapc
4201 (lambda (row)
4202 (cond
4203 ;; In a special row, try to find a width cookie at COLUMN.
4204 ((org-export-table-row-is-special-p row info)
4205 (let ((value (org-element-contents
4206 (elt (org-element-contents row) column))))
4207 ;; The following checks avoid expanding unnecessarily the
4208 ;; cell with `org-export-data'
4209 (when (and value
4210 (not (cdr value))
4211 (stringp (car value))
4212 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'" (car value))
4213 (match-string 1 (car value)))
4214 (setq cookie-width
4215 (string-to-number (match-string 1 (car value)))))))
4216 ;; Ignore table rules.
4217 ((eq (org-element-property :type row) 'rule))))
4218 (org-element-contents table))
4219 ;; Return value.
4220 cookie-width))
4222 (defun org-export-table-cell-alignment (table-cell info)
4223 "Return TABLE-CELL contents alignment.
4225 INFO is a plist used as the communication channel.
4227 Return alignment as specified by the last alignment cookie in the
4228 same column as TABLE-CELL. If no such cookie is found, a default
4229 alignment value will be deduced from fraction of numbers in the
4230 column (see `org-table-number-fraction' for more information).
4231 Possible values are `left', `right' and `center'."
4232 (let* ((row (org-export-get-parent table-cell))
4233 (column (let ((cells (org-element-contents row)))
4234 (- (length cells) (length (memq table-cell cells)))))
4235 (table (org-export-get-parent-table table-cell))
4236 (number-cells 0)
4237 (total-cells 0)
4238 cookie-align)
4239 (mapc
4240 (lambda (row)
4241 (cond
4242 ;; In a special row, try to find an alignment cookie at
4243 ;; COLUMN.
4244 ((org-export-table-row-is-special-p row info)
4245 (let ((value (org-element-contents
4246 (elt (org-element-contents row) column))))
4247 ;; Since VALUE is a secondary string, the following checks
4248 ;; avoid useless expansion through `org-export-data'.
4249 (when (and value
4250 (not (cdr value))
4251 (stringp (car value))
4252 (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'"
4253 (car value))
4254 (match-string 1 (car value)))
4255 (setq cookie-align (match-string 1 (car value))))))
4256 ;; Ignore table rules.
4257 ((eq (org-element-property :type row) 'rule))
4258 ;; In a standard row, check if cell's contents are expressing
4259 ;; some kind of number. Increase NUMBER-CELLS accordingly.
4260 ;; Though, don't bother if an alignment cookie has already
4261 ;; defined cell's alignment.
4262 ((not cookie-align)
4263 (let ((value (org-export-data
4264 (org-element-contents
4265 (elt (org-element-contents row) column))
4266 info)))
4267 (incf total-cells)
4268 (when (string-match org-table-number-regexp value)
4269 (incf number-cells))))))
4270 (org-element-contents table))
4271 ;; Return value. Alignment specified by cookies has precedence
4272 ;; over alignment deduced from cells contents.
4273 (cond ((equal cookie-align "l") 'left)
4274 ((equal cookie-align "r") 'right)
4275 ((equal cookie-align "c") 'center)
4276 ((>= (/ (float number-cells) total-cells) org-table-number-fraction)
4277 'right)
4278 (t 'left))))
4280 (defun org-export-table-cell-borders (table-cell info)
4281 "Return TABLE-CELL borders.
4283 INFO is a plist used as a communication channel.
4285 Return value is a list of symbols, or nil. Possible values are:
4286 `top', `bottom', `above', `below', `left' and `right'. Note:
4287 `top' (resp. `bottom') only happen for a cell in the first
4288 row (resp. last row) of the table, ignoring table rules, if any.
4290 Returned borders ignore special rows."
4291 (let* ((row (org-export-get-parent table-cell))
4292 (table (org-export-get-parent-table table-cell))
4293 borders)
4294 ;; Top/above border? TABLE-CELL has a border above when a rule
4295 ;; used to demarcate row groups can be found above. Hence,
4296 ;; finding a rule isn't sufficient to push `above' in BORDERS:
4297 ;; another regular row has to be found above that rule.
4298 (let (rule-flag)
4299 (catch 'exit
4300 (mapc (lambda (row)
4301 (cond ((eq (org-element-property :type row) 'rule)
4302 (setq rule-flag t))
4303 ((not (org-export-table-row-is-special-p row info))
4304 (if rule-flag (throw 'exit (push 'above borders))
4305 (throw 'exit nil)))))
4306 ;; Look at every row before the current one.
4307 (cdr (memq row (reverse (org-element-contents table)))))
4308 ;; No rule above, or rule found starts the table (ignoring any
4309 ;; special row): TABLE-CELL is at the top of the table.
4310 (when rule-flag (push 'above borders))
4311 (push 'top borders)))
4312 ;; Bottom/below border? TABLE-CELL has a border below when next
4313 ;; non-regular row below is a rule.
4314 (let (rule-flag)
4315 (catch 'exit
4316 (mapc (lambda (row)
4317 (cond ((eq (org-element-property :type row) 'rule)
4318 (setq rule-flag t))
4319 ((not (org-export-table-row-is-special-p row info))
4320 (if rule-flag (throw 'exit (push 'below borders))
4321 (throw 'exit nil)))))
4322 ;; Look at every row after the current one.
4323 (cdr (memq row (org-element-contents table))))
4324 ;; No rule below, or rule found ends the table (modulo some
4325 ;; special row): TABLE-CELL is at the bottom of the table.
4326 (when rule-flag (push 'below borders))
4327 (push 'bottom borders)))
4328 ;; Right/left borders? They can only be specified by column
4329 ;; groups. Column groups are defined in a row starting with "/".
4330 ;; Also a column groups row only contains "<", "<>", ">" or blank
4331 ;; cells.
4332 (catch 'exit
4333 (let ((column (let ((cells (org-element-contents row)))
4334 (- (length cells) (length (memq table-cell cells))))))
4335 (mapc
4336 (lambda (row)
4337 (unless (eq (org-element-property :type row) 'rule)
4338 (when (equal (org-element-contents
4339 (car (org-element-contents row)))
4340 '("/"))
4341 (let ((column-groups
4342 (mapcar
4343 (lambda (cell)
4344 (let ((value (org-element-contents cell)))
4345 (when (member value '(("<") ("<>") (">") nil))
4346 (car value))))
4347 (org-element-contents row))))
4348 ;; There's a left border when previous cell, if
4349 ;; any, ends a group, or current one starts one.
4350 (when (or (and (not (zerop column))
4351 (member (elt column-groups (1- column))
4352 '(">" "<>")))
4353 (member (elt column-groups column) '("<" "<>")))
4354 (push 'left borders))
4355 ;; There's a right border when next cell, if any,
4356 ;; starts a group, or current one ends one.
4357 (when (or (and (/= (1+ column) (length column-groups))
4358 (member (elt column-groups (1+ column))
4359 '("<" "<>")))
4360 (member (elt column-groups column) '(">" "<>")))
4361 (push 'right borders))
4362 (throw 'exit nil)))))
4363 ;; Table rows are read in reverse order so last column groups
4364 ;; row has precedence over any previous one.
4365 (reverse (org-element-contents table)))))
4366 ;; Return value.
4367 borders))
4369 (defun org-export-table-cell-starts-colgroup-p (table-cell info)
4370 "Non-nil when TABLE-CELL is at the beginning of a row group.
4371 INFO is a plist used as a communication channel."
4372 ;; A cell starts a column group either when it is at the beginning
4373 ;; of a row (or after the special column, if any) or when it has
4374 ;; a left border.
4375 (or (eq (org-element-map (org-export-get-parent table-cell) 'table-cell
4376 'identity info 'first-match)
4377 table-cell)
4378 (memq 'left (org-export-table-cell-borders table-cell info))))
4380 (defun org-export-table-cell-ends-colgroup-p (table-cell info)
4381 "Non-nil when TABLE-CELL is at the end of a row group.
4382 INFO is a plist used as a communication channel."
4383 ;; A cell ends a column group either when it is at the end of a row
4384 ;; or when it has a right border.
4385 (or (eq (car (last (org-element-contents
4386 (org-export-get-parent table-cell))))
4387 table-cell)
4388 (memq 'right (org-export-table-cell-borders table-cell info))))
4390 (defun org-export-table-row-starts-rowgroup-p (table-row info)
4391 "Non-nil when TABLE-ROW is at the beginning of a column group.
4392 INFO is a plist used as a communication channel."
4393 (unless (or (eq (org-element-property :type table-row) 'rule)
4394 (org-export-table-row-is-special-p table-row info))
4395 (let ((borders (org-export-table-cell-borders
4396 (car (org-element-contents table-row)) info)))
4397 (or (memq 'top borders) (memq 'above borders)))))
4399 (defun org-export-table-row-ends-rowgroup-p (table-row info)
4400 "Non-nil when TABLE-ROW is at the end of a column group.
4401 INFO is a plist used as a communication channel."
4402 (unless (or (eq (org-element-property :type table-row) 'rule)
4403 (org-export-table-row-is-special-p table-row info))
4404 (let ((borders (org-export-table-cell-borders
4405 (car (org-element-contents table-row)) info)))
4406 (or (memq 'bottom borders) (memq 'below borders)))))
4408 (defun org-export-table-row-starts-header-p (table-row info)
4409 "Non-nil when TABLE-ROW is the first table header's row.
4410 INFO is a plist used as a communication channel."
4411 (and (org-export-table-has-header-p
4412 (org-export-get-parent-table table-row) info)
4413 (org-export-table-row-starts-rowgroup-p table-row info)
4414 (= (org-export-table-row-group table-row info) 1)))
4416 (defun org-export-table-row-ends-header-p (table-row info)
4417 "Non-nil when TABLE-ROW is the last table header's row.
4418 INFO is a plist used as a communication channel."
4419 (and (org-export-table-has-header-p
4420 (org-export-get-parent-table table-row) info)
4421 (org-export-table-row-ends-rowgroup-p table-row info)
4422 (= (org-export-table-row-group table-row info) 1)))
4424 (defun org-export-table-dimensions (table info)
4425 "Return TABLE dimensions.
4427 INFO is a plist used as a communication channel.
4429 Return value is a CONS like (ROWS . COLUMNS) where
4430 ROWS (resp. COLUMNS) is the number of exportable
4431 rows (resp. columns)."
4432 (let (first-row (columns 0) (rows 0))
4433 ;; Set number of rows, and extract first one.
4434 (org-element-map table 'table-row
4435 (lambda (row)
4436 (when (eq (org-element-property :type row) 'standard)
4437 (incf rows)
4438 (unless first-row (setq first-row row)))) info)
4439 ;; Set number of columns.
4440 (org-element-map first-row 'table-cell (lambda (cell) (incf columns)) info)
4441 ;; Return value.
4442 (cons rows columns)))
4444 (defun org-export-table-cell-address (table-cell info)
4445 "Return address of a regular TABLE-CELL object.
4447 TABLE-CELL is the cell considered. INFO is a plist used as
4448 a communication channel.
4450 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4451 zero-based index. Only exportable cells are considered. The
4452 function returns nil for other cells."
4453 (let* ((table-row (org-export-get-parent table-cell))
4454 (table (org-export-get-parent-table table-cell)))
4455 ;; Ignore cells in special rows or in special column.
4456 (unless (or (org-export-table-row-is-special-p table-row info)
4457 (and (org-export-table-has-special-column-p table)
4458 (eq (car (org-element-contents table-row)) table-cell)))
4459 (cons
4460 ;; Row number.
4461 (let ((row-count 0))
4462 (org-element-map table 'table-row
4463 (lambda (row)
4464 (cond ((eq (org-element-property :type row) 'rule) nil)
4465 ((eq row table-row) row-count)
4466 (t (incf row-count) nil)))
4467 info 'first-match))
4468 ;; Column number.
4469 (let ((col-count 0))
4470 (org-element-map table-row 'table-cell
4471 (lambda (cell)
4472 (if (eq cell table-cell) col-count (incf col-count) nil))
4473 info 'first-match))))))
4475 (defun org-export-get-table-cell-at (address table info)
4476 "Return regular table-cell object at ADDRESS in TABLE.
4478 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4479 zero-based index. TABLE is a table type element. INFO is
4480 a plist used as a communication channel.
4482 If no table-cell, among exportable cells, is found at ADDRESS,
4483 return nil."
4484 (let ((column-pos (cdr address)) (column-count 0))
4485 (org-element-map
4486 ;; Row at (car address) or nil.
4487 (let ((row-pos (car address)) (row-count 0))
4488 (org-element-map table 'table-row
4489 (lambda (row)
4490 (cond ((eq (org-element-property :type row) 'rule) nil)
4491 ((= row-count row-pos) row)
4492 (t (incf row-count) nil)))
4493 info 'first-match))
4494 'table-cell
4495 (lambda (cell)
4496 (if (= column-count column-pos) cell
4497 (incf column-count) nil))
4498 info 'first-match)))
4501 ;;;; For Tables Of Contents
4503 ;; `org-export-collect-headlines' builds a list of all exportable
4504 ;; headline elements, maybe limited to a certain depth. One can then
4505 ;; easily parse it and transcode it.
4507 ;; Building lists of tables, figures or listings is quite similar.
4508 ;; Once the generic function `org-export-collect-elements' is defined,
4509 ;; `org-export-collect-tables', `org-export-collect-figures' and
4510 ;; `org-export-collect-listings' can be derived from it.
4512 (defun org-export-collect-headlines (info &optional n)
4513 "Collect headlines in order to build a table of contents.
4515 INFO is a plist used as a communication channel.
4517 When optional argument N is an integer, it specifies the depth of
4518 the table of contents. Otherwise, it is set to the value of the
4519 last headline level. See `org-export-headline-levels' for more
4520 information.
4522 Return a list of all exportable headlines as parsed elements.
4523 Footnote sections, if any, will be ignored."
4524 (unless (wholenump n) (setq n (plist-get info :headline-levels)))
4525 (org-element-map (plist-get info :parse-tree) 'headline
4526 (lambda (headline)
4527 (unless (org-element-property :footnote-section-p headline)
4528 ;; Strip contents from HEADLINE.
4529 (let ((relative-level (org-export-get-relative-level headline info)))
4530 (unless (> relative-level n) headline))))
4531 info))
4533 (defun org-export-collect-elements (type info &optional predicate)
4534 "Collect referenceable elements of a determined type.
4536 TYPE can be a symbol or a list of symbols specifying element
4537 types to search. Only elements with a caption are collected.
4539 INFO is a plist used as a communication channel.
4541 When non-nil, optional argument PREDICATE is a function accepting
4542 one argument, an element of type TYPE. It returns a non-nil
4543 value when that element should be collected.
4545 Return a list of all elements found, in order of appearance."
4546 (org-element-map (plist-get info :parse-tree) type
4547 (lambda (element)
4548 (and (org-element-property :caption element)
4549 (or (not predicate) (funcall predicate element))
4550 element))
4551 info))
4553 (defun org-export-collect-tables (info)
4554 "Build a list of tables.
4555 INFO is a plist used as a communication channel.
4557 Return a list of table elements with a caption."
4558 (org-export-collect-elements 'table info))
4560 (defun org-export-collect-figures (info predicate)
4561 "Build a list of figures.
4563 INFO is a plist used as a communication channel. PREDICATE is
4564 a function which accepts one argument: a paragraph element and
4565 whose return value is non-nil when that element should be
4566 collected.
4568 A figure is a paragraph type element, with a caption, verifying
4569 PREDICATE. The latter has to be provided since a \"figure\" is
4570 a vague concept that may depend on back-end.
4572 Return a list of elements recognized as figures."
4573 (org-export-collect-elements 'paragraph info predicate))
4575 (defun org-export-collect-listings (info)
4576 "Build a list of src blocks.
4578 INFO is a plist used as a communication channel.
4580 Return a list of src-block elements with a caption."
4581 (org-export-collect-elements 'src-block info))
4584 ;;;; Smart Quotes
4586 ;; The main function for the smart quotes sub-system is
4587 ;; `org-export-activate-smart-quotes', which replaces every quote in
4588 ;; a given string from the parse tree with its "smart" counterpart.
4590 ;; Dictionary for smart quotes is stored in
4591 ;; `org-export-smart-quotes-alist'.
4593 ;; Internally, regexps matching potential smart quotes (checks at
4594 ;; string boundaries are also necessary) are defined in
4595 ;; `org-export-smart-quotes-regexps'.
4597 (defconst org-export-smart-quotes-alist
4598 '(("de"
4599 (opening-double-quote :utf-8 "„" :html "&bdquo;" :latex "\"`"
4600 :texinfo "@quotedblbase{}")
4601 (closing-double-quote :utf-8 "“" :html "&ldquo;" :latex "\"'"
4602 :texinfo "@quotedblleft{}")
4603 (opening-single-quote :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}"
4604 :texinfo "@quotesinglbase{}")
4605 (closing-single-quote :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}"
4606 :texinfo "@quoteleft{}")
4607 (apostrophe :utf-8 "’" :html "&rsquo;"))
4608 ("en"
4609 (opening-double-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
4610 (closing-double-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
4611 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
4612 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
4613 (apostrophe :utf-8 "’" :html "&rsquo;"))
4614 ("es"
4615 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
4616 :texinfo "@guillemetleft{}")
4617 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
4618 :texinfo "@guillemetright{}")
4619 (opening-single-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
4620 (closing-single-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
4621 (apostrophe :utf-8 "’" :html "&rsquo;"))
4622 ("fr"
4623 (opening-double-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
4624 :texinfo "@guillemetleft{}@tie{}")
4625 (closing-double-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
4626 :texinfo "@tie{}@guillemetright{}")
4627 (opening-single-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
4628 :texinfo "@guillemetleft{}@tie{}")
4629 (closing-single-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
4630 :texinfo "@tie{}@guillemetright{}")
4631 (apostrophe :utf-8 "’" :html "&rsquo;")))
4632 "Smart quotes translations.
4634 Alist whose CAR is a language string and CDR is an alist with
4635 quote type as key and a plist associating various encodings to
4636 their translation as value.
4638 A quote type can be any symbol among `opening-double-quote',
4639 `closing-double-quote', `opening-single-quote',
4640 `closing-single-quote' and `apostrophe'.
4642 Valid encodings include `:utf-8', `:html', `:latex' and
4643 `:texinfo'.
4645 If no translation is found, the quote character is left as-is.")
4647 (defconst org-export-smart-quotes-regexps
4648 (list
4649 ;; Possible opening quote at beginning of string.
4650 "\\`\\([\"']\\)\\(\\w\\|\\s.\\|\\s_\\)"
4651 ;; Possible closing quote at beginning of string.
4652 "\\`\\([\"']\\)\\(\\s-\\|\\s)\\|\\s.\\)"
4653 ;; Possible apostrophe at beginning of string.
4654 "\\`\\('\\)\\S-"
4655 ;; Opening single and double quotes.
4656 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\(?:\\w\\|\\s.\\|\\s_\\)"
4657 ;; Closing single and double quotes.
4658 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\(?:\\s-\\|\\s)\\|\\s.\\)"
4659 ;; Apostrophe.
4660 "\\S-\\('\\)\\S-"
4661 ;; Possible opening quote at end of string.
4662 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\'"
4663 ;; Possible closing quote at end of string.
4664 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\'"
4665 ;; Possible apostrophe at end of string.
4666 "\\S-\\('\\)\\'")
4667 "List of regexps matching a quote or an apostrophe.
4668 In every regexp, quote or apostrophe matched is put in group 1.")
4670 (defun org-export-activate-smart-quotes (s encoding info &optional original)
4671 "Replace regular quotes with \"smart\" quotes in string S.
4673 ENCODING is a symbol among `:html', `:latex', `:texinfo' and
4674 `:utf-8'. INFO is a plist used as a communication channel.
4676 The function has to retrieve information about string
4677 surroundings in parse tree. It can only happen with an
4678 unmodified string. Thus, if S has already been through another
4679 process, a non-nil ORIGINAL optional argument will provide that
4680 original string.
4682 Return the new string."
4683 (if (equal s "") ""
4684 (let* ((prev (org-export-get-previous-element (or original s) info))
4685 ;; Try to be flexible when computing number of blanks
4686 ;; before object. The previous object may be a string
4687 ;; introduced by the back-end and not completely parsed.
4688 (pre-blank (and prev
4689 (or (org-element-property :post-blank prev)
4690 ;; A string with missing `:post-blank'
4691 ;; property.
4692 (and (stringp prev)
4693 (string-match " *\\'" prev)
4694 (length (match-string 0 prev)))
4695 ;; Fallback value.
4696 0)))
4697 (next (org-export-get-next-element (or original s) info))
4698 (get-smart-quote
4699 (lambda (q type)
4700 ;; Return smart quote associated to a give quote Q, as
4701 ;; a string. TYPE is a symbol among `open', `close' and
4702 ;; `apostrophe'.
4703 (let ((key (case type
4704 (apostrophe 'apostrophe)
4705 (open (if (equal "'" q) 'opening-single-quote
4706 'opening-double-quote))
4707 (otherwise (if (equal "'" q) 'closing-single-quote
4708 'closing-double-quote)))))
4709 (or (plist-get
4710 (cdr (assq key
4711 (cdr (assoc (plist-get info :language)
4712 org-export-smart-quotes-alist))))
4713 encoding)
4714 q)))))
4715 (if (or (equal "\"" s) (equal "'" s))
4716 ;; Only a quote: no regexp can match. We have to check both
4717 ;; sides and decide what to do.
4718 (cond ((and (not prev) (not next)) s)
4719 ((not prev) (funcall get-smart-quote s 'open))
4720 ((and (not next) (zerop pre-blank))
4721 (funcall get-smart-quote s 'close))
4722 ((not next) s)
4723 ((zerop pre-blank) (funcall get-smart-quote s 'apostrophe))
4724 (t (funcall get-smart-quote 'open)))
4725 ;; 1. Replace quote character at the beginning of S.
4726 (cond
4727 ;; Apostrophe?
4728 ((and prev (zerop pre-blank)
4729 (string-match (nth 2 org-export-smart-quotes-regexps) s))
4730 (setq s (replace-match
4731 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
4732 nil t s 1)))
4733 ;; Closing quote?
4734 ((and prev (zerop pre-blank)
4735 (string-match (nth 1 org-export-smart-quotes-regexps) s))
4736 (setq s (replace-match
4737 (funcall get-smart-quote (match-string 1 s) 'close)
4738 nil t s 1)))
4739 ;; Opening quote?
4740 ((and (or (not prev) (> pre-blank 0))
4741 (string-match (nth 0 org-export-smart-quotes-regexps) s))
4742 (setq s (replace-match
4743 (funcall get-smart-quote (match-string 1 s) 'open)
4744 nil t s 1))))
4745 ;; 2. Replace quotes in the middle of the string.
4746 (setq s (replace-regexp-in-string
4747 ;; Opening quotes.
4748 (nth 3 org-export-smart-quotes-regexps)
4749 (lambda (text)
4750 (funcall get-smart-quote (match-string 1 text) 'open))
4751 s nil t 1))
4752 (setq s (replace-regexp-in-string
4753 ;; Closing quotes.
4754 (nth 4 org-export-smart-quotes-regexps)
4755 (lambda (text)
4756 (funcall get-smart-quote (match-string 1 text) 'close))
4757 s nil t 1))
4758 (setq s (replace-regexp-in-string
4759 ;; Apostrophes.
4760 (nth 5 org-export-smart-quotes-regexps)
4761 (lambda (text)
4762 (funcall get-smart-quote (match-string 1 text) 'apostrophe))
4763 s nil t 1))
4764 ;; 3. Replace quote character at the end of S.
4765 (cond
4766 ;; Apostrophe?
4767 ((and next (string-match (nth 8 org-export-smart-quotes-regexps) s))
4768 (setq s (replace-match
4769 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
4770 nil t s 1)))
4771 ;; Closing quote?
4772 ((and (not next)
4773 (string-match (nth 7 org-export-smart-quotes-regexps) s))
4774 (setq s (replace-match
4775 (funcall get-smart-quote (match-string 1 s) 'close)
4776 nil t s 1)))
4777 ;; Opening quote?
4778 ((and next (string-match (nth 6 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 ;; Return string with smart quotes.
4783 s))))
4785 ;;;; Topology
4787 ;; Here are various functions to retrieve information about the
4788 ;; neighbourhood of a given element or object. Neighbours of interest
4789 ;; are direct parent (`org-export-get-parent'), parent headline
4790 ;; (`org-export-get-parent-headline'), first element containing an
4791 ;; object, (`org-export-get-parent-element'), parent table
4792 ;; (`org-export-get-parent-table'), previous element or object
4793 ;; (`org-export-get-previous-element') and next element or object
4794 ;; (`org-export-get-next-element').
4796 ;; `org-export-get-genealogy' returns the full genealogy of a given
4797 ;; element or object, from closest parent to full parse tree.
4799 (defun org-export-get-parent (blob)
4800 "Return BLOB parent or nil.
4801 BLOB is the element or object considered."
4802 (org-element-property :parent blob))
4804 (defun org-export-get-genealogy (blob)
4805 "Return full genealogy relative to a given element or object.
4807 BLOB is the element or object being considered.
4809 Ancestors are returned from closest to farthest, the last one
4810 being the full parse tree."
4811 (let (genealogy (parent blob))
4812 (while (setq parent (org-element-property :parent parent))
4813 (push parent genealogy))
4814 (nreverse genealogy)))
4816 (defun org-export-get-parent-headline (blob)
4817 "Return BLOB parent headline or nil.
4818 BLOB is the element or object being considered."
4819 (let ((parent blob))
4820 (while (and (setq parent (org-element-property :parent parent))
4821 (not (eq (org-element-type parent) 'headline))))
4822 parent))
4824 (defun org-export-get-parent-element (object)
4825 "Return first element containing OBJECT or nil.
4826 OBJECT is the object to consider."
4827 (let ((parent object))
4828 (while (and (setq parent (org-element-property :parent parent))
4829 (memq (org-element-type parent) org-element-all-objects)))
4830 parent))
4832 (defun org-export-get-parent-table (object)
4833 "Return OBJECT parent table or nil.
4834 OBJECT is either a `table-cell' or `table-element' type object."
4835 (let ((parent object))
4836 (while (and (setq parent (org-element-property :parent parent))
4837 (not (eq (org-element-type parent) 'table))))
4838 parent))
4840 (defun org-export-get-previous-element (blob info &optional n)
4841 "Return previous element or object.
4843 BLOB is an element or object. INFO is a plist used as
4844 a communication channel. Return previous exportable element or
4845 object, a string, or nil.
4847 When optional argument N is a positive integer, return a list
4848 containing up to N siblings before BLOB, from farthest to
4849 closest. With any other non-nil value, return a list containing
4850 all of them."
4851 (let ((siblings
4852 ;; An object can belong to the contents of its parent or
4853 ;; to a secondary string. We check the latter option
4854 ;; first.
4855 (let ((parent (org-export-get-parent blob)))
4856 (or (and (not (memq (org-element-type blob)
4857 org-element-all-elements))
4858 (let ((sec-value
4859 (org-element-property
4860 (cdr (assq (org-element-type parent)
4861 org-element-secondary-value-alist))
4862 parent)))
4863 (and (memq blob sec-value) sec-value)))
4864 (org-element-contents parent))))
4865 prev)
4866 (catch 'exit
4867 (mapc (lambda (obj)
4868 (cond ((memq obj (plist-get info :ignore-list)))
4869 ((null n) (throw 'exit obj))
4870 ((not (wholenump n)) (push obj prev))
4871 ((zerop n) (throw 'exit prev))
4872 (t (decf n) (push obj prev))))
4873 (cdr (memq blob (reverse siblings))))
4874 prev)))
4876 (defun org-export-get-next-element (blob info &optional n)
4877 "Return next element or object.
4879 BLOB is an element or object. INFO is a plist used as
4880 a communication channel. Return next exportable element or
4881 object, a string, or nil.
4883 When optional argument N is a positive integer, return a list
4884 containing up to N siblings after BLOB, from closest to farthest.
4885 With any other non-nil value, return a list containing all of
4886 them."
4887 (let ((siblings
4888 ;; An object can belong to the contents of its parent or to
4889 ;; a secondary string. We check the latter option first.
4890 (let ((parent (org-export-get-parent blob)))
4891 (or (and (not (memq (org-element-type blob)
4892 org-element-all-objects))
4893 (let ((sec-value
4894 (org-element-property
4895 (cdr (assq (org-element-type parent)
4896 org-element-secondary-value-alist))
4897 parent)))
4898 (cdr (memq blob sec-value))))
4899 (cdr (memq blob (org-element-contents parent))))))
4900 next)
4901 (catch 'exit
4902 (mapc (lambda (obj)
4903 (cond ((memq obj (plist-get info :ignore-list)))
4904 ((null n) (throw 'exit obj))
4905 ((not (wholenump n)) (push obj next))
4906 ((zerop n) (throw 'exit (nreverse next)))
4907 (t (decf n) (push obj next))))
4908 siblings)
4909 (nreverse next))))
4912 ;;;; Translation
4914 ;; `org-export-translate' translates a string according to language
4915 ;; specified by LANGUAGE keyword or `org-export-language-setup'
4916 ;; variable and a specified charset. `org-export-dictionary' contains
4917 ;; the dictionary used for the translation.
4919 (defconst org-export-dictionary
4920 '(("Author"
4921 ("ca" :default "Autor")
4922 ("cs" :default "Autor")
4923 ("da" :default "Ophavsmand")
4924 ("de" :default "Autor")
4925 ("eo" :html "A&#365;toro")
4926 ("es" :default "Autor")
4927 ("fi" :html "Tekij&auml;")
4928 ("fr" :default "Auteur")
4929 ("hu" :default "Szerz&otilde;")
4930 ("is" :html "H&ouml;fundur")
4931 ("it" :default "Autore")
4932 ("ja" :html "&#33879;&#32773;" :utf-8 "著者")
4933 ("nl" :default "Auteur")
4934 ("no" :default "Forfatter")
4935 ("nb" :default "Forfatter")
4936 ("nn" :default "Forfattar")
4937 ("pl" :default "Autor")
4938 ("ru" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
4939 ("sv" :html "F&ouml;rfattare")
4940 ("uk" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
4941 ("zh-CN" :html "&#20316;&#32773;" :utf-8 "作者")
4942 ("zh-TW" :html "&#20316;&#32773;" :utf-8 "作者"))
4943 ("Date"
4944 ("ca" :default "Data")
4945 ("cs" :default "Datum")
4946 ("da" :default "Dato")
4947 ("de" :default "Datum")
4948 ("eo" :default "Dato")
4949 ("es" :default "Fecha")
4950 ("fi" :html "P&auml;iv&auml;m&auml;&auml;r&auml;")
4951 ("hu" :html "D&aacute;tum")
4952 ("is" :default "Dagsetning")
4953 ("it" :default "Data")
4954 ("ja" :html "&#26085;&#20184;" :utf-8 "日付")
4955 ("nl" :default "Datum")
4956 ("no" :default "Dato")
4957 ("nb" :default "Dato")
4958 ("nn" :default "Dato")
4959 ("pl" :default "Data")
4960 ("ru" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
4961 ("sv" :default "Datum")
4962 ("uk" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
4963 ("zh-CN" :html "&#26085;&#26399;" :utf-8 "日期")
4964 ("zh-TW" :html "&#26085;&#26399;" :utf-8 "日期"))
4965 ("Equation"
4966 ("fr" :ascii "Equation" :default "Équation"))
4967 ("Figure")
4968 ("Footnotes"
4969 ("ca" :html "Peus de p&agrave;gina")
4970 ("cs" :default "Pozn\xe1mky pod carou")
4971 ("da" :default "Fodnoter")
4972 ("de" :html "Fu&szlig;noten")
4973 ("eo" :default "Piednotoj")
4974 ("es" :html "Pies de p&aacute;gina")
4975 ("fi" :default "Alaviitteet")
4976 ("fr" :default "Notes de bas de page")
4977 ("hu" :html "L&aacute;bjegyzet")
4978 ("is" :html "Aftanm&aacute;lsgreinar")
4979 ("it" :html "Note a pi&egrave; di pagina")
4980 ("ja" :html "&#33050;&#27880;" :utf-8 "脚注")
4981 ("nl" :default "Voetnoten")
4982 ("no" :default "Fotnoter")
4983 ("nb" :default "Fotnoter")
4984 ("nn" :default "Fotnotar")
4985 ("pl" :default "Przypis")
4986 ("ru" :html "&#1057;&#1085;&#1086;&#1089;&#1082;&#1080;" :utf-8 "Сноски")
4987 ("sv" :default "Fotnoter")
4988 ("uk" :html "&#1055;&#1088;&#1080;&#1084;&#1110;&#1090;&#1082;&#1080;"
4989 :utf-8 "Примітки")
4990 ("zh-CN" :html "&#33050;&#27880;" :utf-8 "脚注")
4991 ("zh-TW" :html "&#33139;&#35387;" :utf-8 "腳註"))
4992 ("List of Listings"
4993 ("fr" :default "Liste des programmes"))
4994 ("List of Tables"
4995 ("fr" :default "Liste des tableaux"))
4996 ("Listing %d:"
4997 ("fr"
4998 :ascii "Programme %d :" :default "Programme nº %d :"
4999 :latin1 "Programme %d :"))
5000 ("Listing %d: %s"
5001 ("fr"
5002 :ascii "Programme %d : %s" :default "Programme nº %d : %s"
5003 :latin1 "Programme %d : %s"))
5004 ("See section %s"
5005 ("fr" :default "cf. section %s"))
5006 ("Table %d:"
5007 ("fr"
5008 :ascii "Tableau %d :" :default "Tableau nº %d :" :latin1 "Tableau %d :"))
5009 ("Table %d: %s"
5010 ("fr"
5011 :ascii "Tableau %d : %s" :default "Tableau nº %d : %s"
5012 :latin1 "Tableau %d : %s"))
5013 ("Table of Contents"
5014 ("ca" :html "&Iacute;ndex")
5015 ("cs" :default "Obsah")
5016 ("da" :default "Indhold")
5017 ("de" :default "Inhaltsverzeichnis")
5018 ("eo" :default "Enhavo")
5019 ("es" :html "&Iacute;ndice")
5020 ("fi" :html "Sis&auml;llysluettelo")
5021 ("fr" :ascii "Sommaire" :default "Table des matières")
5022 ("hu" :html "Tartalomjegyz&eacute;k")
5023 ("is" :default "Efnisyfirlit")
5024 ("it" :default "Indice")
5025 ("ja" :html "&#30446;&#27425;" :utf-8 "目次")
5026 ("nl" :default "Inhoudsopgave")
5027 ("no" :default "Innhold")
5028 ("nb" :default "Innhold")
5029 ("nn" :default "Innhald")
5030 ("pl" :html "Spis tre&#x015b;ci")
5031 ("ru" :html "&#1057;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1077;"
5032 :utf-8 "Содержание")
5033 ("sv" :html "Inneh&aring;ll")
5034 ("uk" :html "&#1047;&#1084;&#1110;&#1089;&#1090;" :utf-8 "Зміст")
5035 ("zh-CN" :html "&#30446;&#24405;" :utf-8 "目录")
5036 ("zh-TW" :html "&#30446;&#37636;" :utf-8 "目錄"))
5037 ("Unknown reference"
5038 ("fr" :ascii "Destination inconnue" :default "Référence inconnue")))
5039 "Dictionary for export engine.
5041 Alist whose CAR is the string to translate and CDR is an alist
5042 whose CAR is the language string and CDR is a plist whose
5043 properties are possible charsets and values translated terms.
5045 It is used as a database for `org-export-translate'. Since this
5046 function returns the string as-is if no translation was found,
5047 the variable only needs to record values different from the
5048 entry.")
5050 (defun org-export-translate (s encoding info)
5051 "Translate string S according to language specification.
5053 ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1'
5054 and `:utf-8'. INFO is a plist used as a communication channel.
5056 Translation depends on `:language' property. Return the
5057 translated string. If no translation is found, try to fall back
5058 to `:default' encoding. If it fails, return S."
5059 (let* ((lang (plist-get info :language))
5060 (translations (cdr (assoc lang
5061 (cdr (assoc s org-export-dictionary))))))
5062 (or (plist-get translations encoding)
5063 (plist-get translations :default)
5064 s)))
5068 ;;; Asynchronous Export
5070 ;; `org-export-async-start' is the entry point for asynchronous
5071 ;; export. It recreates current buffer (including visibility,
5072 ;; narrowing and visited file) in an external Emacs process, and
5073 ;; evaluates a command there. It then applies a function on the
5074 ;; returned results in the current process.
5076 ;; Asynchronously generated results are never displayed directly.
5077 ;; Instead, they are stored in `org-export-stack-contents'. They can
5078 ;; then be retrieved by calling `org-export-stack'.
5080 ;; Export Stack is viewed through a dedicated major mode
5081 ;;`org-export-stack-mode' and tools: `org-export-stack-refresh',
5082 ;;`org-export-stack-delete', `org-export-stack-view' and
5083 ;;`org-export-stack-clear'.
5085 ;; For back-ends, `org-export-add-to-stack' add a new source to stack.
5086 ;; It should used whenever `org-export-async-start' is called.
5088 (defmacro org-export-async-start (fun &rest body)
5089 "Call function FUN on the results returned by BODY evaluation.
5091 BODY evaluation happens in an asynchronous process, from a buffer
5092 which is an exact copy of the current one.
5094 Use `org-export-add-to-stack' in FUN in order to register results
5095 in the stack. Examples for, respectively a temporary buffer and
5096 a file are:
5098 \(org-export-async-start
5099 \(lambda (output)
5100 \(with-current-buffer (get-buffer-create \"*Org BACKEND Export*\")
5101 \(erase-buffer)
5102 \(insert output)
5103 \(goto-char (point-min))
5104 \(org-export-add-to-stack (current-buffer) 'backend)))
5105 `(org-export-as 'backend ,subtreep ,visible-only ,body-only ',ext-plist))
5109 \(org-export-async-start
5110 \(lambda (f) (org-export-add-to-stack f 'backend))
5111 `(expand-file-name
5112 \(org-export-to-file
5113 'backend ,outfile ,subtreep ,visible-only ,body-only ',ext-plist)))"
5114 (declare (indent 1) (debug t))
5115 (org-with-gensyms (process temp-file copy-fun proc-buffer handler)
5116 ;; Write the full sexp evaluating BODY in a copy of the current
5117 ;; buffer to a temporary file, as it may be too long for program
5118 ;; args in `start-process'.
5119 `(with-temp-message "Initializing asynchronous export process"
5120 (let ((,copy-fun (org-export--generate-copy-script (current-buffer)))
5121 (,temp-file (make-temp-file "org-export-process")))
5122 (with-temp-file ,temp-file
5123 (insert
5124 (format
5125 "%S"
5126 `(with-temp-buffer
5127 ,(when org-export-async-debug '(setq debug-on-error t))
5128 ;; Ignore `org-mode-hook' as it has been run already
5129 ;; in the original buffer. Ignore `kill-emacs-hook'
5130 ;; as we need a truly non-interactive process.
5131 (setq org-mode-hook nil kill-emacs-hook nil)
5132 ;; Initialize `org-mode' and export framework in the
5133 ;; external process.
5134 (org-mode)
5135 (require 'ox)
5136 ;; Re-create current buffer there.
5137 (funcall ,,copy-fun)
5138 (restore-buffer-modified-p nil)
5139 ;; Sexp to evaluate in the buffer.
5140 (print (progn ,,@body))))))
5141 ;; Start external process.
5142 (let* ((process-connection-type nil)
5143 (,proc-buffer (generate-new-buffer-name "*Org Export Process*"))
5144 (,process
5145 (start-process
5146 "org-export-process" ,proc-buffer
5147 (expand-file-name invocation-name invocation-directory)
5148 "-Q" "--batch"
5149 "-l" org-export-async-init-file
5150 "-l" ,temp-file)))
5151 ;; Register running process in stack.
5152 (org-export-add-to-stack (get-buffer ,proc-buffer) nil ,process)
5153 ;; Set-up sentinel in order to catch results.
5154 (set-process-sentinel
5155 ,process
5156 (let ((handler ',fun))
5157 `(lambda (p status)
5158 (let ((proc-buffer (process-buffer p)))
5159 (when (eq (process-status p) 'exit)
5160 (unwind-protect
5161 (if (zerop (process-exit-status p))
5162 (unwind-protect
5163 (let ((results
5164 (with-current-buffer proc-buffer
5165 (goto-char (point-max))
5166 (backward-sexp)
5167 (read (current-buffer)))))
5168 (funcall ,handler results))
5169 (unless org-export-async-debug
5170 (and (get-buffer proc-buffer)
5171 (kill-buffer proc-buffer))))
5172 (org-export-add-to-stack proc-buffer nil p)
5173 (ding)
5174 (message "Process '%s' exited abnormally" p))
5175 (unless org-export-async-debug
5176 (delete-file ,,temp-file)))))))))))))
5178 (defun org-export-add-to-stack (source backend &optional process)
5179 "Add a new result to export stack if not present already.
5181 SOURCE is a buffer or a file name containing export results.
5182 BACKEND is a symbol representing export back-end used to generate
5185 Entries already pointing to SOURCE and unavailable entries are
5186 removed beforehand. Return the new stack."
5187 (setq org-export-stack-contents
5188 (cons (list source backend (or process (current-time)))
5189 (org-export-stack-remove source))))
5191 (defun org-export-stack ()
5192 "Menu for asynchronous export results and running processes."
5193 (interactive)
5194 (let ((buffer (get-buffer-create "*Org Export Stack*")))
5195 (set-buffer buffer)
5196 (when (zerop (buffer-size)) (org-export-stack-mode))
5197 (org-export-stack-refresh)
5198 (pop-to-buffer buffer))
5199 (message "Type \"q\" to quit, \"?\" for help"))
5201 (defun org-export--stack-source-at-point ()
5202 "Return source from export results at point in stack."
5203 (let ((source (car (nth (1- (org-current-line)) org-export-stack-contents))))
5204 (if (not source) (error "Source unavailable, please refresh buffer")
5205 (let ((source-name (if (stringp source) source (buffer-name source))))
5206 (if (save-excursion
5207 (beginning-of-line)
5208 (looking-at (concat ".* +" (regexp-quote source-name) "$")))
5209 source
5210 ;; SOURCE is not consistent with current line. The stack
5211 ;; view is outdated.
5212 (error "Source unavailable; type `g' to update buffer"))))))
5214 (defun org-export-stack-clear ()
5215 "Remove all entries from export stack."
5216 (interactive)
5217 (setq org-export-stack-contents nil))
5219 (defun org-export-stack-refresh (&rest dummy)
5220 "Refresh the asynchronous export stack.
5221 DUMMY is ignored. Unavailable sources are removed from the list.
5222 Return the new stack."
5223 (let ((inhibit-read-only t))
5224 (org-preserve-lc
5225 (erase-buffer)
5226 (insert (concat
5227 (let ((counter 0))
5228 (mapconcat
5229 (lambda (entry)
5230 (let ((proc-p (processp (nth 2 entry))))
5231 (concat
5232 ;; Back-end.
5233 (format " %-12s " (or (nth 1 entry) ""))
5234 ;; Age.
5235 (let ((data (nth 2 entry)))
5236 (if proc-p (format " %6s " (process-status data))
5237 ;; Compute age of the results.
5238 (org-format-seconds
5239 "%4h:%.2m "
5240 (float-time (time-since data)))))
5241 ;; Source.
5242 (format " %s"
5243 (let ((source (car entry)))
5244 (if (stringp source) source
5245 (buffer-name source)))))))
5246 ;; Clear stack from exited processes, dead buffers or
5247 ;; non-existent files.
5248 (setq org-export-stack-contents
5249 (org-remove-if-not
5250 (lambda (el)
5251 (if (processp (nth 2 el))
5252 (buffer-live-p (process-buffer (nth 2 el)))
5253 (let ((source (car el)))
5254 (if (bufferp source) (buffer-live-p source)
5255 (file-exists-p source)))))
5256 org-export-stack-contents)) "\n")))))))
5258 (defun org-export-stack-remove (&optional source)
5259 "Remove export results at point from stack.
5260 If optional argument SOURCE is non-nil, remove it instead."
5261 (interactive)
5262 (let ((source (or source (org-export--stack-source-at-point))))
5263 (setq org-export-stack-contents
5264 (org-remove-if (lambda (el) (equal (car el) source))
5265 org-export-stack-contents))))
5267 (defun org-export-stack-view (&optional in-emacs)
5268 "View export results at point in stack.
5269 With an optional prefix argument IN-EMACS, force viewing files
5270 within Emacs."
5271 (interactive "P")
5272 (let ((source (org-export--stack-source-at-point)))
5273 (cond ((processp source)
5274 (org-switch-to-buffer-other-window (process-buffer source)))
5275 ((bufferp source) (org-switch-to-buffer-other-window source))
5276 (t (org-open-file source in-emacs)))))
5278 (defconst org-export-stack-mode-map
5279 (let ((km (make-sparse-keymap)))
5280 (define-key km " " 'next-line)
5281 (define-key km "n" 'next-line)
5282 (define-key km "\C-n" 'next-line)
5283 (define-key km [down] 'next-line)
5284 (define-key km "p" 'previous-line)
5285 (define-key km "\C-p" 'previous-line)
5286 (define-key km "\C-?" 'previous-line)
5287 (define-key km [up] 'previous-line)
5288 (define-key km "C" 'org-export-stack-clear)
5289 (define-key km "v" 'org-export-stack-view)
5290 (define-key km (kbd "RET") 'org-export-stack-view)
5291 (define-key km "d" 'org-export-stack-remove)
5293 "Keymap for Org Export Stack.")
5295 (define-derived-mode org-export-stack-mode special-mode "Org-Stack"
5296 "Mode for displaying asynchronous export stack.
5298 Type \\[org-export-stack] to visualize the asynchronous export
5299 stack.
5301 In an Org Export Stack buffer, use \\<org-export-stack-mode-map>\\[org-export-stack-view] to view export output
5302 on current line, \\[org-export-stack-remove] to remove it from the stack and \\[org-export-stack-clear] to clear
5303 stack completely.
5305 Removing entries in an Org Export Stack buffer doesn't affect
5306 files or buffers, only the display.
5308 \\{org-export-stack-mode-map}"
5309 (abbrev-mode 0)
5310 (auto-fill-mode 0)
5311 (setq buffer-read-only t
5312 buffer-undo-list t
5313 truncate-lines t
5314 header-line-format
5315 '(:eval
5316 (format " %-12s | %6s | %s" "Back-End" "Age" "Source")))
5317 (add-hook 'post-command-hook 'org-export-stack-refresh nil t)
5318 (set (make-local-variable 'revert-buffer-function)
5319 'org-export-stack-refresh))
5323 ;;; The Dispatcher
5325 ;; `org-export-dispatch' is the standard interactive way to start an
5326 ;; export process. It uses `org-export--dispatch-ui' as a subroutine
5327 ;; for its interface, which, in turn, delegates response to key
5328 ;; pressed to `org-export--dispatch-action'.
5330 ;;;###autoload
5331 (defun org-export-dispatch (&optional arg)
5332 "Export dispatcher for Org mode.
5334 It provides an access to common export related tasks in a buffer.
5335 Its interface comes in two flavours: standard and expert.
5337 While both share the same set of bindings, only the former
5338 displays the valid keys associations in a dedicated buffer.
5339 Scrolling (resp. line-wise motion) in this buffer is done with
5340 SPC and DEL (resp. C-n and C-p) keys.
5342 Set variable `org-export-dispatch-use-expert-ui' to switch to one
5343 flavour or the other.
5345 When ARG is \\[universal-argument], repeat the last export action, with the same set
5346 of options used back then, on the current buffer.
5348 When ARG is \\[universal-argument] \\[universal-argument], display the asynchronous export stack."
5349 (interactive "P")
5350 (let* ((input
5351 (cond ((equal arg '(16)) '(stack))
5352 ((and arg org-export-dispatch-last-action))
5353 (t (save-window-excursion
5354 (unwind-protect
5355 (progn
5356 ;; Remember where we are
5357 (move-marker org-export-dispatch-last-position
5358 (point)
5359 (org-base-buffer (current-buffer)))
5360 ;; Get and store an export command
5361 (setq org-export-dispatch-last-action
5362 (org-export--dispatch-ui
5363 (list org-export-initial-scope
5364 (and org-export-in-background 'async))
5366 org-export-dispatch-use-expert-ui)))
5367 (and (get-buffer "*Org Export Dispatcher*")
5368 (kill-buffer "*Org Export Dispatcher*")))))))
5369 (action (car input))
5370 (optns (cdr input)))
5371 (unless (memq 'subtree optns)
5372 (move-marker org-export-dispatch-last-position nil))
5373 (case action
5374 ;; First handle special hard-coded actions.
5375 (stack (org-export-stack))
5376 (publish-current-file
5377 (org-publish-current-file (memq 'force optns) (memq 'async optns)))
5378 (publish-current-project
5379 (org-publish-current-project (memq 'force optns) (memq 'async optns)))
5380 (publish-choose-project
5381 (org-publish (assoc (org-icompleting-read
5382 "Publish project: "
5383 org-publish-project-alist nil t)
5384 org-publish-project-alist)
5385 (memq 'force optns)
5386 (memq 'async optns)))
5387 (publish-all (org-publish-all (memq 'force optns) (memq 'async optns)))
5388 (otherwise
5389 (save-excursion
5390 (when arg
5391 ;; Repeating command, maybe move cursor
5392 ;; to restore subtree context
5393 (if (eq (marker-buffer org-export-dispatch-last-position)
5394 (org-base-buffer (current-buffer)))
5395 (goto-char org-export-dispatch-last-position)
5396 ;; We are in a differnet buffer, forget position
5397 (move-marker org-export-dispatch-last-position nil)))
5398 (funcall action
5399 ;; Return a symbol instead of a list to ease
5400 ;; asynchronous export macro use.
5401 (and (memq 'async optns) t)
5402 (and (memq 'subtree optns) t)
5403 (and (memq 'visible optns) t)
5404 (and (memq 'body optns) t)))))))
5406 (defun org-export--dispatch-ui (options first-key expertp)
5407 "Handle interface for `org-export-dispatch'.
5409 OPTIONS is a list containing current interactive options set for
5410 export. It can contain any of the following symbols:
5411 `body' toggles a body-only export
5412 `subtree' restricts export to current subtree
5413 `visible' restricts export to visible part of buffer.
5414 `force' force publishing files.
5415 `async' use asynchronous export process
5417 FIRST-KEY is the key pressed to select the first level menu. It
5418 is nil when this menu hasn't been selected yet.
5420 EXPERTP, when non-nil, triggers expert UI. In that case, no help
5421 buffer is provided, but indications about currently active
5422 options are given in the prompt. Moreover, \[?] allows to switch
5423 back to standard interface."
5424 (let* ((fontify-key
5425 (lambda (key &optional access-key)
5426 ;; Fontify KEY string. Optional argument ACCESS-KEY, when
5427 ;; non-nil is the required first-level key to activate
5428 ;; KEY. When its value is t, activate KEY independently
5429 ;; on the first key, if any. A nil value means KEY will
5430 ;; only be activated at first level.
5431 (if (or (eq access-key t) (eq access-key first-key))
5432 (org-propertize key 'face 'org-warning)
5433 key)))
5434 (fontify-value
5435 (lambda (value)
5436 ;; Fontify VALUE string.
5437 (org-propertize value 'face 'font-lock-variable-name-face)))
5438 ;; Prepare menu entries by extracting them from
5439 ;; `org-export-registered-backends', and sorting them by
5440 ;; access key and by ordinal, if any.
5441 (backends
5442 (sort
5443 (sort
5444 (delq nil
5445 (mapcar
5446 (lambda (b)
5447 (let ((name (car b)))
5448 (catch 'ignored
5449 ;; Ignore any back-end belonging to
5450 ;; `org-export-invisible-backends' or derived
5451 ;; from one of them.
5452 (dolist (ignored org-export-invisible-backends)
5453 (when (org-export-derived-backend-p name ignored)
5454 (throw 'ignored nil)))
5455 (org-export-backend-menu name))))
5456 org-export-registered-backends))
5457 (lambda (a b)
5458 (let ((key-a (nth 1 a))
5459 (key-b (nth 1 b)))
5460 (cond ((and (numberp key-a) (numberp key-b))
5461 (< key-a key-b))
5462 ((numberp key-b) t)))))
5463 (lambda (a b) (< (car a) (car b)))))
5464 ;; Compute a list of allowed keys based on the first key
5465 ;; pressed, if any. Some keys (?^B, ?^V, ?^S, ?^F, ?^A
5466 ;; and ?q) are always available.
5467 (allowed-keys
5468 (nconc (list 2 22 19 6 1)
5469 (if (not first-key) (org-uniquify (mapcar 'car backends))
5470 (let (sub-menu)
5471 (dolist (backend backends (sort (mapcar 'car sub-menu) '<))
5472 (when (eq (car backend) first-key)
5473 (setq sub-menu (append (nth 2 backend) sub-menu))))))
5474 (cond ((eq first-key ?P) (list ?f ?p ?x ?a))
5475 ((not first-key) (list ?P)))
5476 (list ?&)
5477 (when expertp (list ??))
5478 (list ?q)))
5479 ;; Build the help menu for standard UI.
5480 (help
5481 (unless expertp
5482 (concat
5483 ;; Options are hard-coded.
5484 (format "Options
5485 [%s] Body only: %s [%s] Visible only: %s
5486 [%s] Export scope: %s [%s] Force publishing: %s
5487 [%s] Async export: %s\n"
5488 (funcall fontify-key "C-b" t)
5489 (funcall fontify-value
5490 (if (memq 'body options) "On " "Off"))
5491 (funcall fontify-key "C-v" t)
5492 (funcall fontify-value
5493 (if (memq 'visible options) "On " "Off"))
5494 (funcall fontify-key "C-s" t)
5495 (funcall fontify-value
5496 (if (memq 'subtree options) "Subtree" "Buffer "))
5497 (funcall fontify-key "C-f" t)
5498 (funcall fontify-value
5499 (if (memq 'force options) "On " "Off"))
5500 (funcall fontify-key "C-a" t)
5501 (funcall fontify-value
5502 (if (memq 'async options) "On " "Off")))
5503 ;; Display registered back-end entries. When a key
5504 ;; appears for the second time, do not create another
5505 ;; entry, but append its sub-menu to existing menu.
5506 (let (last-key)
5507 (mapconcat
5508 (lambda (entry)
5509 (let ((top-key (car entry)))
5510 (concat
5511 (unless (eq top-key last-key)
5512 (setq last-key top-key)
5513 (format "\n[%s] %s\n"
5514 (funcall fontify-key (char-to-string top-key))
5515 (nth 1 entry)))
5516 (let ((sub-menu (nth 2 entry)))
5517 (unless (functionp sub-menu)
5518 ;; Split sub-menu into two columns.
5519 (let ((index -1))
5520 (concat
5521 (mapconcat
5522 (lambda (sub-entry)
5523 (incf index)
5524 (format
5525 (if (zerop (mod index 2)) " [%s] %-26s"
5526 "[%s] %s\n")
5527 (funcall fontify-key
5528 (char-to-string (car sub-entry))
5529 top-key)
5530 (nth 1 sub-entry)))
5531 sub-menu "")
5532 (when (zerop (mod index 2)) "\n"))))))))
5533 backends ""))
5534 ;; Publishing menu is hard-coded.
5535 (format "\n[%s] Publish
5536 [%s] Current file [%s] Current project
5537 [%s] Choose project [%s] All projects\n\n"
5538 (funcall fontify-key "P")
5539 (funcall fontify-key "f" ?P)
5540 (funcall fontify-key "p" ?P)
5541 (funcall fontify-key "x" ?P)
5542 (funcall fontify-key "a" ?P))
5543 (format "\[%s] Export stack\n" (funcall fontify-key "&" t))
5544 (format "\[%s] %s"
5545 (funcall fontify-key "q" t)
5546 (if first-key "Main menu" "Exit")))))
5547 ;; Build prompts for both standard and expert UI.
5548 (standard-prompt (unless expertp "Export command: "))
5549 (expert-prompt
5550 (when expertp
5551 (format
5552 "Export command (C-%s%s%s%s%s) [%s]: "
5553 (if (memq 'body options) (funcall fontify-key "b" t) "b")
5554 (if (memq 'visible options) (funcall fontify-key "v" t) "v")
5555 (if (memq 'subtree options) (funcall fontify-key "s" t) "s")
5556 (if (memq 'force options) (funcall fontify-key "f" t) "f")
5557 (if (memq 'async options) (funcall fontify-key "a" t) "a")
5558 (mapconcat (lambda (k)
5559 ;; Strip control characters.
5560 (unless (< k 27) (char-to-string k)))
5561 allowed-keys "")))))
5562 ;; With expert UI, just read key with a fancy prompt. In standard
5563 ;; UI, display an intrusive help buffer.
5564 (if expertp
5565 (org-export--dispatch-action
5566 expert-prompt allowed-keys backends options first-key expertp)
5567 ;; At first call, create frame layout in order to display menu.
5568 (unless (get-buffer "*Org Export Dispatcher*")
5569 (delete-other-windows)
5570 (org-switch-to-buffer-other-window
5571 (get-buffer-create "*Org Export Dispatcher*"))
5572 (setq cursor-type nil
5573 header-line-format "Use SPC, DEL, C-n or C-p to navigate.")
5574 ;; Make sure that invisible cursor will not highlight square
5575 ;; brackets.
5576 (set-syntax-table (copy-syntax-table))
5577 (modify-syntax-entry ?\[ "w"))
5578 ;; At this point, the buffer containing the menu exists and is
5579 ;; visible in the current window. So, refresh it.
5580 (with-current-buffer "*Org Export Dispatcher*"
5581 ;; Refresh help. Maintain display continuity by re-visiting
5582 ;; previous window position.
5583 (let ((pos (window-start)))
5584 (erase-buffer)
5585 (insert help)
5586 (set-window-start nil pos)))
5587 (org-fit-window-to-buffer)
5588 (org-export--dispatch-action
5589 standard-prompt allowed-keys backends options first-key expertp))))
5591 (defun org-export--dispatch-action
5592 (prompt allowed-keys backends options first-key expertp)
5593 "Read a character from command input and act accordingly.
5595 PROMPT is the displayed prompt, as a string. ALLOWED-KEYS is
5596 a list of characters available at a given step in the process.
5597 BACKENDS is a list of menu entries. OPTIONS, FIRST-KEY and
5598 EXPERTP are the same as defined in `org-export--dispatch-ui',
5599 which see.
5601 Toggle export options when required. Otherwise, return value is
5602 a list with action as CAR and a list of interactive export
5603 options as CDR."
5604 (let (key)
5605 ;; Scrolling: when in non-expert mode, act on motion keys (C-n,
5606 ;; C-p, SPC, DEL).
5607 (while (and (setq key (read-char-exclusive prompt))
5608 (not expertp)
5609 (memq key '(14 16 ?\s ?\d)))
5610 (case key
5611 (14 (if (not (pos-visible-in-window-p (point-max)))
5612 (ignore-errors (scroll-up-line))
5613 (message "End of buffer")
5614 (sit-for 1)))
5615 (16 (if (not (pos-visible-in-window-p (point-min)))
5616 (ignore-errors (scroll-down-line))
5617 (message "Beginning of buffer")
5618 (sit-for 1)))
5619 (?\s (if (not (pos-visible-in-window-p (point-max)))
5620 (scroll-up nil)
5621 (message "End of buffer")
5622 (sit-for 1)))
5623 (?\d (if (not (pos-visible-in-window-p (point-min)))
5624 (scroll-down nil)
5625 (message "Beginning of buffer")
5626 (sit-for 1)))))
5627 (cond
5628 ;; Ignore undefined associations.
5629 ((not (memq key allowed-keys))
5630 (ding)
5631 (unless expertp (message "Invalid key") (sit-for 1))
5632 (org-export--dispatch-ui options first-key expertp))
5633 ;; q key at first level aborts export. At second
5634 ;; level, cancel first key instead.
5635 ((eq key ?q) (if (not first-key) (error "Export aborted")
5636 (org-export--dispatch-ui options nil expertp)))
5637 ;; Help key: Switch back to standard interface if
5638 ;; expert UI was active.
5639 ((eq key ??) (org-export--dispatch-ui options first-key nil))
5640 ;; Switch to asynchronous export stack.
5641 ((eq key ?&) '(stack))
5642 ;; Toggle export options
5643 ;; C-b (2) C-v (22) C-s (19) C-f (6) C-a (1)
5644 ((memq key '(2 22 19 6 1))
5645 (org-export--dispatch-ui
5646 (let ((option (case key (2 'body) (22 'visible) (19 'subtree)
5647 (6 'force) (1 'async))))
5648 (if (memq option options) (remq option options)
5649 (cons option options)))
5650 first-key expertp))
5651 ;; Action selected: Send key and options back to
5652 ;; `org-export-dispatch'.
5653 ((or first-key (functionp (nth 2 (assq key backends))))
5654 (cons (cond
5655 ((not first-key) (nth 2 (assq key backends)))
5656 ;; Publishing actions are hard-coded. Send a special
5657 ;; signal to `org-export-dispatch'.
5658 ((eq first-key ?P)
5659 (case key
5660 (?f 'publish-current-file)
5661 (?p 'publish-current-project)
5662 (?x 'publish-choose-project)
5663 (?a 'publish-all)))
5664 ;; Return first action associated to FIRST-KEY + KEY
5665 ;; path. Indeed, derived backends can share the same
5666 ;; FIRST-KEY.
5667 (t (catch 'found
5668 (mapc (lambda (backend)
5669 (let ((match (assq key (nth 2 backend))))
5670 (when match (throw 'found (nth 2 match)))))
5671 (member (assq first-key backends) backends)))))
5672 options))
5673 ;; Otherwise, enter sub-menu.
5674 (t (org-export--dispatch-ui options key expertp)))))
5678 (provide 'ox)
5680 ;; Local variables:
5681 ;; generated-autoload-file: "org-loaddefs.el"
5682 ;; End:
5684 ;;; ox.el ends here