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