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