71435b77e82b0101d4a27f7e1f69ce73c1f6c418
[org-mode.git] / lisp / ox.el
blob71435b77e82b0101d4a27f7e1f69ce73c1f6c418
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 ;; This function can also support specific buffer keywords, OPTION
52 ;; keyword's items and filters. Refer to function's documentation for
53 ;; more information.
55 ;; If the new back-end shares most properties with another one,
56 ;; `org-export-define-derived-backend' can be used to simplify the
57 ;; process.
59 ;; Any back-end can define its own variables. Among them, those
60 ;; customizable should belong to the `org-export-BACKEND' group.
62 ;; Tools for common tasks across back-ends are implemented in the
63 ;; following part of the file.
65 ;; Then, a wrapper macro for asynchronous export,
66 ;; `org-export-async-start', along with tools to display results. are
67 ;; given in the penultimate part.
69 ;; Eventually, a dispatcher (`org-export-dispatch') for standard
70 ;; back-ends is provided in the last one.
72 ;;; Code:
74 (eval-when-compile (require 'cl))
75 (require 'org-element)
76 (require 'org-macro)
77 (require 'ob-exp)
79 (declare-function org-publish "ox-publish" (project &optional force async))
80 (declare-function org-publish-all "ox-publish" (&optional force async))
81 (declare-function
82 org-publish-current-file "ox-publish" (&optional force async))
83 (declare-function org-publish-current-project "ox-publish"
84 (&optional force async))
86 (defvar org-publish-project-alist)
87 (defvar org-table-number-fraction)
88 (defvar org-table-number-regexp)
92 ;;; Internal Variables
94 ;; Among internal variables, the most important is
95 ;; `org-export-options-alist'. This variable define the global export
96 ;; options, shared between every exporter, and how they are acquired.
98 (defconst org-export-max-depth 19
99 "Maximum nesting depth for headlines, counting from 0.")
101 (defconst org-export-options-alist
102 '((:author "AUTHOR" nil user-full-name t)
103 (:creator "CREATOR" nil org-export-creator-string)
104 (:date "DATE" nil nil t)
105 (:description "DESCRIPTION" nil nil newline)
106 (:email "EMAIL" nil user-mail-address t)
107 (:exclude-tags "EXCLUDE_TAGS" nil org-export-exclude-tags split)
108 (:headline-levels nil "H" org-export-headline-levels)
109 (:keywords "KEYWORDS" nil nil space)
110 (:language "LANGUAGE" nil org-export-default-language t)
111 (:preserve-breaks nil "\\n" org-export-preserve-breaks)
112 (:section-numbers nil "num" org-export-with-section-numbers)
113 (:select-tags "SELECT_TAGS" nil org-export-select-tags split)
114 (:time-stamp-file nil "timestamp" org-export-time-stamp-file)
115 (:title "TITLE" nil org-export--default-title space)
116 (:with-archived-trees nil "arch" org-export-with-archived-trees)
117 (:with-author nil "author" org-export-with-author)
118 (:with-clocks nil "c" org-export-with-clocks)
119 (:with-creator nil "creator" org-export-with-creator)
120 (:with-date nil "date" org-export-with-date)
121 (:with-drawers nil "d" org-export-with-drawers)
122 (:with-email nil "email" org-export-with-email)
123 (:with-emphasize nil "*" org-export-with-emphasize)
124 (:with-entities nil "e" org-export-with-entities)
125 (:with-fixed-width nil ":" org-export-with-fixed-width)
126 (:with-footnotes nil "f" org-export-with-footnotes)
127 (:with-inlinetasks nil "inline" org-export-with-inlinetasks)
128 (:with-latex nil "tex" org-export-with-latex)
129 (:with-planning nil "p" org-export-with-planning)
130 (:with-priority nil "pri" org-export-with-priority)
131 (:with-smart-quotes nil "'" org-export-with-smart-quotes)
132 (:with-special-strings nil "-" org-export-with-special-strings)
133 (:with-statistics-cookies nil "stat" org-export-with-statistics-cookies)
134 (:with-sub-superscript nil "^" org-export-with-sub-superscripts)
135 (:with-toc nil "toc" org-export-with-toc)
136 (:with-tables nil "|" org-export-with-tables)
137 (:with-tags nil "tags" org-export-with-tags)
138 (:with-tasks nil "tasks" org-export-with-tasks)
139 (:with-timestamps nil "<" org-export-with-timestamps)
140 (:with-todo-keywords nil "todo" org-export-with-todo-keywords))
141 "Alist between export properties and ways to set them.
143 The CAR of the alist is the property name, and the CDR is a list
144 like (KEYWORD OPTION DEFAULT BEHAVIOUR) where:
146 KEYWORD is a string representing a buffer keyword, or nil. Each
147 property defined this way can also be set, during subtree
148 export, through a headline property named after the keyword
149 with the \"EXPORT_\" prefix (i.e. DATE keyword and EXPORT_DATE
150 property).
151 OPTION is a string that could be found in an #+OPTIONS: line.
152 DEFAULT is the default value for the property.
153 BEHAVIOUR determines how Org should handle multiple keywords for
154 the same property. It is a symbol among:
155 nil Keep old value and discard the new one.
156 t Replace old value with the new one.
157 `space' Concatenate the values, separating them with a space.
158 `newline' Concatenate the values, separating them with
159 a newline.
160 `split' Split values at white spaces, and cons them to the
161 previous list.
163 Values set through KEYWORD and OPTION have precedence over
164 DEFAULT.
166 All these properties should be back-end agnostic. Back-end
167 specific properties are set through `org-export-define-backend'.
168 Properties redefined there have precedence over these.")
170 (defconst org-export-special-keywords '("FILETAGS" "SETUPFILE" "OPTIONS")
171 "List of in-buffer keywords that require special treatment.
172 These keywords are not directly associated to a property. The
173 way they are handled must be hard-coded into
174 `org-export--get-inbuffer-options' function.")
176 (defconst org-export-filters-alist
177 '((:filter-bold . org-export-filter-bold-functions)
178 (:filter-babel-call . org-export-filter-babel-call-functions)
179 (:filter-center-block . org-export-filter-center-block-functions)
180 (:filter-clock . org-export-filter-clock-functions)
181 (:filter-code . org-export-filter-code-functions)
182 (:filter-comment . org-export-filter-comment-functions)
183 (:filter-comment-block . org-export-filter-comment-block-functions)
184 (:filter-diary-sexp . org-export-filter-diary-sexp-functions)
185 (:filter-drawer . org-export-filter-drawer-functions)
186 (:filter-dynamic-block . org-export-filter-dynamic-block-functions)
187 (:filter-entity . org-export-filter-entity-functions)
188 (:filter-example-block . org-export-filter-example-block-functions)
189 (:filter-export-block . org-export-filter-export-block-functions)
190 (:filter-export-snippet . org-export-filter-export-snippet-functions)
191 (:filter-final-output . org-export-filter-final-output-functions)
192 (:filter-fixed-width . org-export-filter-fixed-width-functions)
193 (:filter-footnote-definition . org-export-filter-footnote-definition-functions)
194 (:filter-footnote-reference . org-export-filter-footnote-reference-functions)
195 (:filter-headline . org-export-filter-headline-functions)
196 (:filter-horizontal-rule . org-export-filter-horizontal-rule-functions)
197 (:filter-inline-babel-call . org-export-filter-inline-babel-call-functions)
198 (:filter-inline-src-block . org-export-filter-inline-src-block-functions)
199 (:filter-inlinetask . org-export-filter-inlinetask-functions)
200 (:filter-italic . org-export-filter-italic-functions)
201 (:filter-item . org-export-filter-item-functions)
202 (:filter-keyword . org-export-filter-keyword-functions)
203 (:filter-latex-environment . org-export-filter-latex-environment-functions)
204 (:filter-latex-fragment . org-export-filter-latex-fragment-functions)
205 (:filter-line-break . org-export-filter-line-break-functions)
206 (:filter-link . org-export-filter-link-functions)
207 (:filter-node-property . org-export-filter-node-property-functions)
208 (:filter-options . org-export-filter-options-functions)
209 (:filter-paragraph . org-export-filter-paragraph-functions)
210 (:filter-parse-tree . org-export-filter-parse-tree-functions)
211 (:filter-plain-list . org-export-filter-plain-list-functions)
212 (:filter-plain-text . org-export-filter-plain-text-functions)
213 (:filter-planning . org-export-filter-planning-functions)
214 (:filter-property-drawer . org-export-filter-property-drawer-functions)
215 (:filter-quote-block . org-export-filter-quote-block-functions)
216 (:filter-quote-section . org-export-filter-quote-section-functions)
217 (:filter-radio-target . org-export-filter-radio-target-functions)
218 (:filter-section . org-export-filter-section-functions)
219 (:filter-special-block . org-export-filter-special-block-functions)
220 (:filter-src-block . org-export-filter-src-block-functions)
221 (:filter-statistics-cookie . org-export-filter-statistics-cookie-functions)
222 (:filter-strike-through . org-export-filter-strike-through-functions)
223 (:filter-subscript . org-export-filter-subscript-functions)
224 (:filter-superscript . org-export-filter-superscript-functions)
225 (:filter-table . org-export-filter-table-functions)
226 (:filter-table-cell . org-export-filter-table-cell-functions)
227 (:filter-table-row . org-export-filter-table-row-functions)
228 (:filter-target . org-export-filter-target-functions)
229 (:filter-timestamp . org-export-filter-timestamp-functions)
230 (:filter-underline . org-export-filter-underline-functions)
231 (:filter-verbatim . org-export-filter-verbatim-functions)
232 (:filter-verse-block . org-export-filter-verse-block-functions))
233 "Alist between filters properties and initial values.
235 The key of each association is a property name accessible through
236 the communication channel. Its value is a configurable global
237 variable defining initial filters.
239 This list is meant to install user specified filters. Back-end
240 developers may install their own filters using
241 `org-export-define-backend'. Filters defined there will always
242 be prepended to the current list, so they always get applied
243 first.")
245 (defconst org-export-default-inline-image-rule
246 `(("file" .
247 ,(format "\\.%s\\'"
248 (regexp-opt
249 '("png" "jpeg" "jpg" "gif" "tiff" "tif" "xbm"
250 "xpm" "pbm" "pgm" "ppm") t))))
251 "Default rule for link matching an inline image.
252 This rule applies to links with no description. By default, it
253 will be considered as an inline image if it targets a local file
254 whose extension is either \"png\", \"jpeg\", \"jpg\", \"gif\",
255 \"tiff\", \"tif\", \"xbm\", \"xpm\", \"pbm\", \"pgm\" or \"ppm\".
256 See `org-export-inline-image-p' for more information about
257 rules.")
259 (defvar org-export-async-debug nil
260 "Non-nil means asynchronous export process should leave data behind.
262 This data is found in the appropriate \"*Org Export Process*\"
263 buffer, and in files prefixed with \"org-export-process\" and
264 located in `temporary-file-directory'.
266 When non-nil, it will also set `debug-on-error' to a non-nil
267 value in the external process.")
269 (defvar org-export-stack-contents nil
270 "Record asynchronously generated export results and processes.
271 This is an alist: its CAR is the source of the
272 result (destination file or buffer for a finished process,
273 original buffer for a running one) and its CDR is a list
274 containing the back-end used, as a symbol, and either a process
275 or the time at which it finished. It is used to build the menu
276 from `org-export-stack'.")
278 (defvar org-export--registered-backends nil
279 "List of backends currently available in the exporter.
280 This variable is set with `org-export-define-backend' and
281 `org-export-define-derived-backend' functions.")
283 (defvar org-export-dispatch-last-action nil
284 "Last command called from the dispatcher.
285 The value should be a list. Its CAR is the action, as a symbol,
286 and its CDR is a list of export options.")
288 (defvar org-export-dispatch-last-position (make-marker)
289 "The position where the last export command was created using the dispatcher.
290 This marker will be used with `C-u C-c C-e' to make sure export repetition
291 uses the same subtree if the previous command was restricted to a subtree.")
294 ;;; User-configurable Variables
296 ;; Configuration for the masses.
298 ;; They should never be accessed directly, as their value is to be
299 ;; stored in a property list (cf. `org-export-options-alist').
300 ;; Back-ends will read their value from there instead.
302 (defgroup org-export nil
303 "Options for exporting Org mode files."
304 :tag "Org Export"
305 :group 'org)
307 (defgroup org-export-general nil
308 "General options for export engine."
309 :tag "Org Export General"
310 :group 'org-export)
312 (defcustom org-export-with-archived-trees 'headline
313 "Whether sub-trees with the ARCHIVE tag should be exported.
315 This can have three different values:
316 nil Do not export, pretend this tree is not present.
317 t Do export the entire tree.
318 `headline' Only export the headline, but skip the tree below it.
320 This option can also be set with the OPTIONS keyword,
321 e.g. \"arch:nil\"."
322 :group 'org-export-general
323 :type '(choice
324 (const :tag "Not at all" nil)
325 (const :tag "Headline only" headline)
326 (const :tag "Entirely" t)))
328 (defcustom org-export-with-author t
329 "Non-nil means insert author name into the exported file.
330 This option can also be set with the OPTIONS keyword,
331 e.g. \"author:nil\"."
332 :group 'org-export-general
333 :type 'boolean)
335 (defcustom org-export-with-clocks nil
336 "Non-nil means export CLOCK keywords.
337 This option can also be set with the OPTIONS keyword,
338 e.g. \"c:t\"."
339 :group 'org-export-general
340 :type 'boolean)
342 (defcustom org-export-with-creator 'comment
343 "Non-nil means the postamble should contain a creator sentence.
345 The sentence can be set in `org-export-creator-string' and
346 defaults to \"Generated by Org mode XX in Emacs XXX.\".
348 If the value is `comment' insert it as a comment."
349 :group 'org-export-general
350 :type '(choice
351 (const :tag "No creator sentence" nil)
352 (const :tag "Sentence as a comment" 'comment)
353 (const :tag "Insert the sentence" t)))
355 (defcustom org-export-with-date t
356 "Non-nil means insert date in the exported document.
357 This option can also be set with the OPTIONS keyword,
358 e.g. \"date:nil\"."
359 :group 'org-export-general
360 :type 'boolean)
362 (defcustom org-export-date-timestamp-format nil
363 "Time-stamp format string to use for DATE keyword.
365 The format string, when specified, only applies if date consists
366 in a single time-stamp. Otherwise its value will be ignored.
368 See `format-time-string' for details on how to build this
369 string."
370 :group 'org-export-general
371 :type '(choice
372 (string :tag "Time-stamp format string")
373 (const :tag "No format string" nil)))
375 (defcustom org-export-creator-string
376 (format "Emacs %s (Org mode %s)"
377 emacs-version
378 (if (fboundp 'org-version) (org-version) "unknown version"))
379 "Information about the creator of the document.
380 This option can also be set on with the CREATOR keyword."
381 :group 'org-export-general
382 :type '(string :tag "Creator string"))
384 (defcustom org-export-with-drawers '(not "LOGBOOK")
385 "Non-nil means export contents of standard drawers.
387 When t, all drawers are exported. This may also be a list of
388 drawer names to export. If that list starts with `not', only
389 drawers with such names will be ignored.
391 This variable doesn't apply to properties drawers.
393 This option can also be set with the OPTIONS keyword,
394 e.g. \"d:nil\"."
395 :group 'org-export-general
396 :version "24.4"
397 :package-version '(Org . "8.0")
398 :type '(choice
399 (const :tag "All drawers" t)
400 (const :tag "None" nil)
401 (repeat :tag "Selected drawers"
402 (string :tag "Drawer name"))
403 (list :tag "Ignored drawers"
404 (const :format "" not)
405 (repeat :tag "Specify names of drawers to ignore during export"
406 :inline t
407 (string :tag "Drawer name")))))
409 (defcustom org-export-with-email nil
410 "Non-nil means insert author email into the exported file.
411 This option can also be set with the OPTIONS keyword,
412 e.g. \"email:t\"."
413 :group 'org-export-general
414 :type 'boolean)
416 (defcustom org-export-with-emphasize t
417 "Non-nil means interpret *word*, /word/, _word_ and +word+.
419 If the export target supports emphasizing text, the word will be
420 typeset in bold, italic, with an underline or strike-through,
421 respectively.
423 This option can also be set with the OPTIONS keyword,
424 e.g. \"*:nil\"."
425 :group 'org-export-general
426 :type 'boolean)
428 (defcustom org-export-exclude-tags '("noexport")
429 "Tags that exclude a tree from export.
431 All trees carrying any of these tags will be excluded from
432 export. This is without condition, so even subtrees inside that
433 carry one of the `org-export-select-tags' will be removed.
435 This option can also be set with the EXCLUDE_TAGS keyword."
436 :group 'org-export-general
437 :type '(repeat (string :tag "Tag")))
439 (defcustom org-export-with-fixed-width t
440 "Non-nil means lines starting with \":\" will be in fixed width font.
442 This can be used to have pre-formatted text, fragments of code
443 etc. For example:
444 : ;; Some Lisp examples
445 : (while (defc cnt)
446 : (ding))
447 will be looking just like this in also HTML. See also the QUOTE
448 keyword. Not all export backends support this.
450 This option can also be set with the OPTIONS keyword,
451 e.g. \"::nil\"."
452 :group 'org-export-general
453 :type 'boolean)
455 (defcustom org-export-with-footnotes t
456 "Non-nil means Org footnotes should be exported.
457 This option can also be set with the OPTIONS keyword,
458 e.g. \"f:nil\"."
459 :group 'org-export-general
460 :type 'boolean)
462 (defcustom org-export-with-latex t
463 "Non-nil means process LaTeX environments and fragments.
465 This option can also be set with the OPTIONS line,
466 e.g. \"tex:verbatim\". Allowed values are:
468 nil Ignore math snippets.
469 `verbatim' Keep everything in verbatim.
470 t Allow export of math snippets."
471 :group 'org-export-general
472 :version "24.4"
473 :package-version '(Org . "8.0")
474 :type '(choice
475 (const :tag "Do not process math in any way" nil)
476 (const :tag "Interpret math snippets" t)
477 (const :tag "Leave math verbatim" verbatim)))
479 (defcustom org-export-headline-levels 3
480 "The last level which is still exported as a headline.
482 Inferior levels will usually produce itemize or enumerate lists
483 when exported, but back-end behaviour may differ.
485 This option can also be set with the OPTIONS keyword,
486 e.g. \"H:2\"."
487 :group 'org-export-general
488 :type 'integer)
490 (defcustom org-export-default-language "en"
491 "The default language for export and clocktable translations, as a string.
492 This may have an association in
493 `org-clock-clocktable-language-setup',
494 `org-export-smart-quotes-alist' and `org-export-dictionary'.
495 This option can also be set with the LANGUAGE keyword."
496 :group 'org-export-general
497 :type '(string :tag "Language"))
499 (defcustom org-export-preserve-breaks nil
500 "Non-nil means preserve all line breaks when exporting.
501 This option can also be set with the OPTIONS keyword,
502 e.g. \"\\n:t\"."
503 :group 'org-export-general
504 :type 'boolean)
506 (defcustom org-export-with-entities t
507 "Non-nil means interpret entities when exporting.
509 For example, HTML export converts \\alpha to &alpha; and \\AA to
510 &Aring;.
512 For a list of supported names, see the constant `org-entities'
513 and the user option `org-entities-user'.
515 This option can also be set with the OPTIONS keyword,
516 e.g. \"e:nil\"."
517 :group 'org-export-general
518 :type 'boolean)
520 (defcustom org-export-with-inlinetasks t
521 "Non-nil means inlinetasks should be exported.
522 This option can also be set with the OPTIONS keyword,
523 e.g. \"inline:nil\"."
524 :group 'org-export-general
525 :version "24.4"
526 :package-version '(Org . "8.0")
527 :type 'boolean)
529 (defcustom org-export-with-planning nil
530 "Non-nil means include planning info in export.
532 Planning info is the line containing either SCHEDULED:,
533 DEADLINE:, CLOSED: time-stamps, or a combination of them.
535 This option can also be set with the OPTIONS keyword,
536 e.g. \"p:t\"."
537 :group 'org-export-general
538 :version "24.4"
539 :package-version '(Org . "8.0")
540 :type 'boolean)
542 (defcustom org-export-with-priority nil
543 "Non-nil means include priority cookies in export.
544 This option can also be set with the OPTIONS keyword,
545 e.g. \"pri:t\"."
546 :group 'org-export-general
547 :type 'boolean)
549 (defcustom org-export-with-section-numbers t
550 "Non-nil means add section numbers to headlines when exporting.
552 When set to an integer n, numbering will only happen for
553 headlines whose relative level is higher or equal to n.
555 This option can also be set with the OPTIONS keyword,
556 e.g. \"num:t\"."
557 :group 'org-export-general
558 :type 'boolean)
560 (defcustom org-export-select-tags '("export")
561 "Tags that select a tree for export.
563 If any such tag is found in a buffer, all trees that do not carry
564 one of these tags will be ignored during export. Inside trees
565 that are selected like this, you can still deselect a subtree by
566 tagging it with one of the `org-export-exclude-tags'.
568 This option can also be set with the SELECT_TAGS keyword."
569 :group 'org-export-general
570 :type '(repeat (string :tag "Tag")))
572 (defcustom org-export-with-smart-quotes nil
573 "Non-nil means activate smart quotes during export.
574 This option can also be set with the OPTIONS keyword,
575 e.g., \"':t\".
577 When setting this to non-nil, you need to take care of
578 using the correct Babel package when exporting to LaTeX.
579 E.g., you can load Babel for french like this:
581 #+LATEX_HEADER: \\usepackage[french]{babel}"
582 :group 'org-export-general
583 :version "24.4"
584 :package-version '(Org . "8.0")
585 :type 'boolean)
587 (defcustom org-export-with-special-strings t
588 "Non-nil means interpret \"\\-\", \"--\" and \"---\" for export.
590 When this option is turned on, these strings will be exported as:
592 Org HTML LaTeX UTF-8
593 -----+----------+--------+-------
594 \\- &shy; \\-
595 -- &ndash; -- –
596 --- &mdash; --- —
597 ... &hellip; \\ldots …
599 This option can also be set with the OPTIONS keyword,
600 e.g. \"-:nil\"."
601 :group 'org-export-general
602 :type 'boolean)
604 (defcustom org-export-with-statistics-cookies t
605 "Non-nil means include statistics cookies in export.
606 This option can also be set with the OPTIONS keyword,
607 e.g. \"stat:nil\""
608 :group 'org-export-general
609 :version "24.4"
610 :package-version '(Org . "8.0")
611 :type 'boolean)
613 (defcustom org-export-with-sub-superscripts t
614 "Non-nil means interpret \"_\" and \"^\" for export.
616 When this option is turned on, you can use TeX-like syntax for
617 sub- and superscripts. Several characters after \"_\" or \"^\"
618 will be considered as a single item - so grouping with {} is
619 normally not needed. For example, the following things will be
620 parsed as single sub- or superscripts.
622 10^24 or 10^tau several digits will be considered 1 item.
623 10^-12 or 10^-tau a leading sign with digits or a word
624 x^2-y^3 will be read as x^2 - y^3, because items are
625 terminated by almost any nonword/nondigit char.
626 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
628 Still, ambiguity is possible - so when in doubt use {} to enclose
629 the sub/superscript. If you set this variable to the symbol
630 `{}', the braces are *required* in order to trigger
631 interpretations as sub/superscript. This can be helpful in
632 documents that need \"_\" frequently in plain text.
634 This option can also be set with the OPTIONS keyword,
635 e.g. \"^:nil\"."
636 :group 'org-export-general
637 :type '(choice
638 (const :tag "Interpret them" t)
639 (const :tag "Curly brackets only" {})
640 (const :tag "Do not interpret them" nil)))
642 (defcustom org-export-with-toc t
643 "Non-nil means create a table of contents in exported files.
645 The TOC contains headlines with levels up
646 to`org-export-headline-levels'. When an integer, include levels
647 up to N in the toc, this may then be different from
648 `org-export-headline-levels', but it will not be allowed to be
649 larger than the number of headline levels. When nil, no table of
650 contents is made.
652 This option can also be set with the OPTIONS keyword,
653 e.g. \"toc:nil\" or \"toc:3\"."
654 :group 'org-export-general
655 :type '(choice
656 (const :tag "No Table of Contents" nil)
657 (const :tag "Full Table of Contents" t)
658 (integer :tag "TOC to level")))
660 (defcustom org-export-with-tables t
661 "If non-nil, lines starting with \"|\" define a table.
662 For example:
664 | Name | Address | Birthday |
665 |-------------+----------+-----------|
666 | Arthur Dent | England | 29.2.2100 |
668 This option can also be set with the OPTIONS keyword,
669 e.g. \"|:nil\"."
670 :group 'org-export-general
671 :type 'boolean)
673 (defcustom org-export-with-tags t
674 "If nil, do not export tags, just remove them from headlines.
676 If this is the symbol `not-in-toc', tags will be removed from
677 table of contents entries, but still be shown in the headlines of
678 the document.
680 This option can also be set with the OPTIONS keyword,
681 e.g. \"tags:nil\"."
682 :group 'org-export-general
683 :type '(choice
684 (const :tag "Off" nil)
685 (const :tag "Not in TOC" not-in-toc)
686 (const :tag "On" t)))
688 (defcustom org-export-with-tasks t
689 "Non-nil means include TODO items for export.
691 This may have the following values:
692 t include tasks independent of state.
693 `todo' include only tasks that are not yet done.
694 `done' include only tasks that are already done.
695 nil ignore all tasks.
696 list of keywords include tasks with these keywords.
698 This option can also be set with the OPTIONS keyword,
699 e.g. \"tasks:nil\"."
700 :group 'org-export-general
701 :type '(choice
702 (const :tag "All tasks" t)
703 (const :tag "No tasks" nil)
704 (const :tag "Not-done tasks" todo)
705 (const :tag "Only done tasks" done)
706 (repeat :tag "Specific TODO keywords"
707 (string :tag "Keyword"))))
709 (defcustom org-export-time-stamp-file t
710 "Non-nil means insert a time stamp into the exported file.
711 The time stamp shows when the file was created. This option can
712 also be set with the OPTIONS keyword, e.g. \"timestamp:nil\"."
713 :group 'org-export-general
714 :type 'boolean)
716 (defcustom org-export-with-timestamps t
717 "Non nil means allow timestamps in export.
719 It can be set to any of the following values:
720 t export all timestamps.
721 `active' export active timestamps only.
722 `inactive' export inactive timestamps only.
723 nil do not export timestamps
725 This only applies to timestamps isolated in a paragraph
726 containing only timestamps. Other timestamps are always
727 exported.
729 This option can also be set with the OPTIONS keyword, e.g.
730 \"<:nil\"."
731 :group 'org-export-general
732 :type '(choice
733 (const :tag "All timestamps" t)
734 (const :tag "Only active timestamps" active)
735 (const :tag "Only inactive timestamps" inactive)
736 (const :tag "No timestamp" nil)))
738 (defcustom org-export-with-todo-keywords t
739 "Non-nil means include TODO keywords in export.
740 When nil, remove all these keywords from the export. This option
741 can also be set with the OPTIONS keyword, e.g. \"todo:nil\"."
742 :group 'org-export-general
743 :type 'boolean)
745 (defcustom org-export-allow-bind-keywords nil
746 "Non-nil means BIND keywords can define local variable values.
747 This is a potential security risk, which is why the default value
748 is nil. You can also allow them through local buffer variables."
749 :group 'org-export-general
750 :version "24.4"
751 :package-version '(Org . "8.0")
752 :type 'boolean)
754 (defcustom org-export-snippet-translation-alist nil
755 "Alist between export snippets back-ends and exporter back-ends.
757 This variable allows to provide shortcuts for export snippets.
759 For example, with a value of '\(\(\"h\" . \"html\"\)\), the
760 HTML back-end will recognize the contents of \"@@h:<b>@@\" as
761 HTML code while every other back-end will ignore it."
762 :group 'org-export-general
763 :version "24.4"
764 :package-version '(Org . "8.0")
765 :type '(repeat
766 (cons (string :tag "Shortcut")
767 (string :tag "Back-end"))))
769 (defcustom org-export-coding-system nil
770 "Coding system for the exported file."
771 :group 'org-export-general
772 :version "24.4"
773 :package-version '(Org . "8.0")
774 :type 'coding-system)
776 (defcustom org-export-copy-to-kill-ring 'if-interactive
777 "Should we push exported content to the kill ring?"
778 :group 'org-export-general
779 :version "24.3"
780 :type '(choice
781 (const :tag "Always" t)
782 (const :tag "When export is done interactively" if-interactive)
783 (const :tag "Never" nil)))
785 (defcustom org-export-initial-scope 'buffer
786 "The initial scope when exporting with `org-export-dispatch'.
787 This variable can be either set to `buffer' or `subtree'."
788 :group 'org-export-general
789 :type '(choice
790 (const :tag "Export current buffer" buffer)
791 (const :tag "Export current subtree" subtree)))
793 (defcustom org-export-show-temporary-export-buffer t
794 "Non-nil means show buffer after exporting to temp buffer.
795 When Org exports to a file, the buffer visiting that file is ever
796 shown, but remains buried. However, when exporting to
797 a temporary buffer, that buffer is popped up in a second window.
798 When this variable is nil, the buffer remains buried also in
799 these cases."
800 :group 'org-export-general
801 :type 'boolean)
803 (defcustom org-export-in-background nil
804 "Non-nil means export and publishing commands will run in background.
805 Results from an asynchronous export are never displayed
806 automatically. But you can retrieve them with \\[org-export-stack]."
807 :group 'org-export-general
808 :version "24.4"
809 :package-version '(Org . "8.0")
810 :type 'boolean)
812 (defcustom org-export-async-init-file user-init-file
813 "File used to initialize external export process.
814 Value must be an absolute file name. It defaults to user's
815 initialization file. Though, a specific configuration makes the
816 process faster and the export more portable."
817 :group 'org-export-general
818 :version "24.4"
819 :package-version '(Org . "8.0")
820 :type '(file :must-match t))
822 (defcustom org-export-dispatch-use-expert-ui nil
823 "Non-nil means using a non-intrusive `org-export-dispatch'.
824 In that case, no help buffer is displayed. Though, an indicator
825 for current export scope is added to the prompt (\"b\" when
826 output is restricted to body only, \"s\" when it is restricted to
827 the current subtree, \"v\" when only visible elements are
828 considered for export, \"f\" when publishing functions should be
829 passed the FORCE argument and \"a\" when the export should be
830 asynchronous). Also, \[?] allows to switch back to standard
831 mode."
832 :group 'org-export-general
833 :version "24.4"
834 :package-version '(Org . "8.0")
835 :type 'boolean)
839 ;;; Defining Back-ends
841 ;; An export back-end is a structure with `org-export-backend' type
842 ;; and `name', `parent', `transcoders', `options', `filters', `blocks'
843 ;; and `menu' slots.
845 ;; At the lowest level, a back-end is created with
846 ;; `org-export-create-backend' function.
848 ;; A named back-end can be registered with
849 ;; `org-export-register-backend' function. A registered back-end can
850 ;; later be referred to by its name, with `org-export-get-backend'
851 ;; function. Also, such a back-end can become the parent of a derived
852 ;; back-end from which slot values will be inherited by default.
853 ;; `org-export-derived-backend-p' can check if a given back-end is
854 ;; derived from a list of back-end names.
856 ;; `org-export-get-all-transcoders', `org-export-get-all-options' and
857 ;; `org-export-get-all-filters' return the full alist of transcoders,
858 ;; options and filters, including those inherited from ancestors.
860 ;; At a higher level, `org-export-define-backend' is the standard way
861 ;; to define an export back-end. If the new back-end is similar to
862 ;; a registered back-end, `org-export-define-derived-backend' may be
863 ;; used instead.
865 ;; Eventually `org-export-barf-if-invalid-backend' returns an error
866 ;; when a given back-end hasn't been registered yet.
868 (defstruct (org-export-backend (:constructor org-export-create-backend)
869 (:copier nil))
870 name parent transcoders options filters blocks menu)
872 (defun org-export-get-backend (name)
873 "Return export back-end named after NAME.
874 NAME is a symbol. Return nil if no such back-end is found."
875 (catch 'found
876 (dolist (b org-export--registered-backends)
877 (when (eq (org-export-backend-name b) name)
878 (throw 'found b)))))
880 (defun org-export-register-backend (backend)
881 "Register BACKEND as a known export back-end.
882 BACKEND is a structure with `org-export-backend' type."
883 ;; Refuse to register an unnamed back-end.
884 (unless (org-export-backend-name backend)
885 (error "Cannot register a unnamed export back-end"))
886 ;; Refuse to register a back-end with an unknown parent.
887 (let ((parent (org-export-backend-parent backend)))
888 (when (and parent (not (org-export-get-backend parent)))
889 (error "Cannot use unknown \"%s\" back-end as a parent" parent)))
890 ;; Register dedicated export blocks in the parser.
891 (dolist (name (org-export-backend-blocks backend))
892 (add-to-list 'org-element-block-name-alist
893 (cons name 'org-element-export-block-parser)))
894 ;; If a back-end with the same name as BACKEND is already
895 ;; registered, replace it with BACKEND. Otherwise, simply add
896 ;; BACKEND to the list of registered back-ends.
897 (let ((old (org-export-get-backend (org-export-backend-name backend))))
898 (if old (setcar (memq old org-export--registered-backends) backend)
899 (push backend org-export--registered-backends))))
901 (defun org-export-barf-if-invalid-backend (backend)
902 "Signal an error if BACKEND isn't defined."
903 (unless (org-export-backend-p backend)
904 (error "Unknown \"%s\" back-end: Aborting export" backend)))
906 (defun org-export-derived-backend-p (backend &rest backends)
907 "Non-nil if BACKEND is derived from one of BACKENDS.
908 BACKEND is an export back-end, as returned by, e.g.,
909 `org-export-create-backend', or a symbol referring to
910 a registered back-end. BACKENDS is constituted of symbols."
911 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
912 (when backend
913 (catch 'exit
914 (while (org-export-backend-parent backend)
915 (when (memq (org-export-backend-name backend) backends)
916 (throw 'exit t))
917 (setq backend
918 (org-export-get-backend (org-export-backend-parent backend))))
919 (memq (org-export-backend-name backend) backends))))
921 (defun org-export-get-all-transcoders (backend)
922 "Return full translation table for BACKEND.
924 BACKEND is an export back-end, as return by, e.g,,
925 `org-export-create-backend'. Return value is an alist where
926 keys are element or object types, as symbols, and values are
927 transcoders.
929 Unlike to `org-export-backend-transcoders', this function
930 also returns transcoders inherited from parent back-ends,
931 if any."
932 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
933 (when backend
934 (let ((transcoders (org-export-backend-transcoders backend))
935 parent)
936 (while (setq parent (org-export-backend-parent backend))
937 (setq backend (org-export-get-backend parent))
938 (setq transcoders
939 (append transcoders (org-export-backend-transcoders backend))))
940 transcoders)))
942 (defun org-export-get-all-options (backend)
943 "Return export options for BACKEND.
945 BACKEND is an export back-end, as return by, e.g,,
946 `org-export-create-backend'. See `org-export-options-alist'
947 for the shape of the return value.
949 Unlike to `org-export-backend-options', this function also
950 returns options inherited from parent back-ends, if any."
951 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
952 (when backend
953 (let ((options (org-export-backend-options backend))
954 parent)
955 (while (setq parent (org-export-backend-parent backend))
956 (setq backend (org-export-get-backend parent))
957 (setq options (append options (org-export-backend-options backend))))
958 options)))
960 (defun org-export-get-all-filters (backend)
961 "Return complete list of filters for BACKEND.
963 BACKEND is an export back-end, as return by, e.g,,
964 `org-export-create-backend'. Return value is an alist where
965 keys are symbols and values lists of functions.
967 Unlike to `org-export-backend-filters', this function also
968 returns filters inherited from parent back-ends, if any."
969 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
970 (when backend
971 (let ((filters (org-export-backend-filters backend))
972 parent)
973 (while (setq parent (org-export-backend-parent backend))
974 (setq backend (org-export-get-backend parent))
975 (setq filters (append filters (org-export-backend-filters backend))))
976 filters)))
978 (defun org-export-define-backend (backend transcoders &rest body)
979 "Define a new back-end BACKEND.
981 TRANSCODERS is an alist between object or element types and
982 functions handling them.
984 These functions should return a string without any trailing
985 space, or nil. They must accept three arguments: the object or
986 element itself, its contents or nil when it isn't recursive and
987 the property list used as a communication channel.
989 Contents, when not nil, are stripped from any global indentation
990 \(although the relative one is preserved). They also always end
991 with a single newline character.
993 If, for a given type, no function is found, that element or
994 object type will simply be ignored, along with any blank line or
995 white space at its end. The same will happen if the function
996 returns the nil value. If that function returns the empty
997 string, the type will be ignored, but the blank lines or white
998 spaces will be kept.
1000 In addition to element and object types, one function can be
1001 associated to the `template' (or `inner-template') symbol and
1002 another one to the `plain-text' symbol.
1004 The former returns the final transcoded string, and can be used
1005 to add a preamble and a postamble to document's body. It must
1006 accept two arguments: the transcoded string and the property list
1007 containing export options. A function associated to `template'
1008 will not be applied if export has option \"body-only\".
1009 A function associated to `inner-template' is always applied.
1011 The latter, when defined, is to be called on every text not
1012 recognized as an element or an object. It must accept two
1013 arguments: the text string and the information channel. It is an
1014 appropriate place to protect special chars relative to the
1015 back-end.
1017 BODY can start with pre-defined keyword arguments. The following
1018 keywords are understood:
1020 :export-block
1022 String, or list of strings, representing block names that
1023 will not be parsed. This is used to specify blocks that will
1024 contain raw code specific to the back-end. These blocks
1025 still have to be handled by the relative `export-block' type
1026 translator.
1028 :filters-alist
1030 Alist between filters and function, or list of functions,
1031 specific to the back-end. See `org-export-filters-alist' for
1032 a list of all allowed filters. Filters defined here
1033 shouldn't make a back-end test, as it may prevent back-ends
1034 derived from this one to behave properly.
1036 :menu-entry
1038 Menu entry for the export dispatcher. It should be a list
1039 like:
1041 '(KEY DESCRIPTION-OR-ORDINAL ACTION-OR-MENU)
1043 where :
1045 KEY is a free character selecting the back-end.
1047 DESCRIPTION-OR-ORDINAL is either a string or a number.
1049 If it is a string, is will be used to name the back-end in
1050 its menu entry. If it is a number, the following menu will
1051 be displayed as a sub-menu of the back-end with the same
1052 KEY. Also, the number will be used to determine in which
1053 order such sub-menus will appear (lowest first).
1055 ACTION-OR-MENU is either a function or an alist.
1057 If it is an action, it will be called with four
1058 arguments (booleans): ASYNC, SUBTREEP, VISIBLE-ONLY and
1059 BODY-ONLY. See `org-export-as' for further explanations on
1060 some of them.
1062 If it is an alist, associations should follow the
1063 pattern:
1065 '(KEY DESCRIPTION ACTION)
1067 where KEY, DESCRIPTION and ACTION are described above.
1069 Valid values include:
1071 '(?m \"My Special Back-end\" my-special-export-function)
1075 '(?l \"Export to LaTeX\"
1076 \(?p \"As PDF file\" org-latex-export-to-pdf)
1077 \(?o \"As PDF file and open\"
1078 \(lambda (a s v b)
1079 \(if a (org-latex-export-to-pdf t s v b)
1080 \(org-open-file
1081 \(org-latex-export-to-pdf nil s v b)))))))
1083 or the following, which will be added to the previous
1084 sub-menu,
1086 '(?l 1
1087 \((?B \"As TEX buffer (Beamer)\" org-beamer-export-as-latex)
1088 \(?P \"As PDF file (Beamer)\" org-beamer-export-to-pdf)))
1090 :options-alist
1092 Alist between back-end specific properties introduced in
1093 communication channel and how their value are acquired. See
1094 `org-export-options-alist' for more information about
1095 structure of the values."
1096 (declare (indent 1))
1097 (let (blocks filters menu-entry options contents)
1098 (while (keywordp (car body))
1099 (case (pop body)
1100 (:export-block (let ((names (pop body)))
1101 (setq blocks (if (consp names) (mapcar 'upcase names)
1102 (list (upcase names))))))
1103 (:filters-alist (setq filters (pop body)))
1104 (:menu-entry (setq menu-entry (pop body)))
1105 (:options-alist (setq options (pop body)))
1106 (t (pop body))))
1107 (org-export-register-backend
1108 (org-export-create-backend :name backend
1109 :transcoders transcoders
1110 :options options
1111 :filters filters
1112 :blocks blocks
1113 :menu menu-entry))))
1115 (defun org-export-define-derived-backend (child parent &rest body)
1116 "Create a new back-end as a variant of an existing one.
1118 CHILD is the name of the derived back-end. PARENT is the name of
1119 the parent back-end.
1121 BODY can start with pre-defined keyword arguments. The following
1122 keywords are understood:
1124 :export-block
1126 String, or list of strings, representing block names that
1127 will not be parsed. This is used to specify blocks that will
1128 contain raw code specific to the back-end. These blocks
1129 still have to be handled by the relative `export-block' type
1130 translator.
1132 :filters-alist
1134 Alist of filters that will overwrite or complete filters
1135 defined in PARENT back-end. See `org-export-filters-alist'
1136 for a list of allowed filters.
1138 :menu-entry
1140 Menu entry for the export dispatcher. See
1141 `org-export-define-backend' for more information about the
1142 expected value.
1144 :options-alist
1146 Alist of back-end specific properties that will overwrite or
1147 complete those defined in PARENT back-end. Refer to
1148 `org-export-options-alist' for more information about
1149 structure of the values.
1151 :translate-alist
1153 Alist of element and object types and transcoders that will
1154 overwrite or complete transcode table from PARENT back-end.
1155 Refer to `org-export-define-backend' for detailed information
1156 about transcoders.
1158 As an example, here is how one could define \"my-latex\" back-end
1159 as a variant of `latex' back-end with a custom template function:
1161 \(org-export-define-derived-backend 'my-latex 'latex
1162 :translate-alist '((template . my-latex-template-fun)))
1164 The back-end could then be called with, for example:
1166 \(org-export-to-buffer 'my-latex \"*Test my-latex*\")"
1167 (declare (indent 2))
1168 (let (blocks filters menu-entry options transcoders contents)
1169 (while (keywordp (car body))
1170 (case (pop body)
1171 (:export-block (let ((names (pop body)))
1172 (setq blocks (if (consp names) (mapcar 'upcase names)
1173 (list (upcase names))))))
1174 (:filters-alist (setq filters (pop body)))
1175 (:menu-entry (setq menu-entry (pop body)))
1176 (:options-alist (setq options (pop body)))
1177 (:translate-alist (setq transcoders (pop body)))
1178 (t (pop body))))
1179 (org-export-register-backend
1180 (org-export-create-backend :name child
1181 :parent parent
1182 :transcoders transcoders
1183 :options options
1184 :filters filters
1185 :blocks blocks
1186 :menu menu-entry))))
1190 ;;; The Communication Channel
1192 ;; During export process, every function has access to a number of
1193 ;; properties. They are of two types:
1195 ;; 1. Environment options are collected once at the very beginning of
1196 ;; the process, out of the original buffer and configuration.
1197 ;; Collecting them is handled by `org-export-get-environment'
1198 ;; function.
1200 ;; Most environment options are defined through the
1201 ;; `org-export-options-alist' variable.
1203 ;; 2. Tree properties are extracted directly from the parsed tree,
1204 ;; just before export, by `org-export-collect-tree-properties'.
1206 ;; Here is the full list of properties available during transcode
1207 ;; process, with their category and their value type.
1209 ;; + `:author' :: Author's name.
1210 ;; - category :: option
1211 ;; - type :: string
1213 ;; + `:back-end' :: Current back-end used for transcoding.
1214 ;; - category :: tree
1215 ;; - type :: symbol
1217 ;; + `:creator' :: String to write as creation information.
1218 ;; - category :: option
1219 ;; - type :: string
1221 ;; + `:date' :: String to use as date.
1222 ;; - category :: option
1223 ;; - type :: string
1225 ;; + `:description' :: Description text for the current data.
1226 ;; - category :: option
1227 ;; - type :: string
1229 ;; + `:email' :: Author's email.
1230 ;; - category :: option
1231 ;; - type :: string
1233 ;; + `:exclude-tags' :: Tags for exclusion of subtrees from export
1234 ;; process.
1235 ;; - category :: option
1236 ;; - type :: list of strings
1238 ;; + `:export-options' :: List of export options available for current
1239 ;; process.
1240 ;; - category :: none
1241 ;; - type :: list of symbols, among `subtree', `body-only' and
1242 ;; `visible-only'.
1244 ;; + `:exported-data' :: Hash table used for memoizing
1245 ;; `org-export-data'.
1246 ;; - category :: tree
1247 ;; - type :: hash table
1249 ;; + `:filetags' :: List of global tags for buffer. Used by
1250 ;; `org-export-get-tags' to get tags with inheritance.
1251 ;; - category :: option
1252 ;; - type :: list of strings
1254 ;; + `:footnote-definition-alist' :: Alist between footnote labels and
1255 ;; their definition, as parsed data. Only non-inlined footnotes
1256 ;; are represented in this alist. Also, every definition isn't
1257 ;; guaranteed to be referenced in the parse tree. The purpose of
1258 ;; this property is to preserve definitions from oblivion
1259 ;; (i.e. when the parse tree comes from a part of the original
1260 ;; buffer), it isn't meant for direct use in a back-end. To
1261 ;; retrieve a definition relative to a reference, use
1262 ;; `org-export-get-footnote-definition' instead.
1263 ;; - category :: option
1264 ;; - type :: alist (STRING . LIST)
1266 ;; + `:headline-levels' :: Maximum level being exported as an
1267 ;; headline. Comparison is done with the relative level of
1268 ;; headlines in the parse tree, not necessarily with their
1269 ;; actual level.
1270 ;; - category :: option
1271 ;; - type :: integer
1273 ;; + `:headline-offset' :: Difference between relative and real level
1274 ;; of headlines in the parse tree. For example, a value of -1
1275 ;; means a level 2 headline should be considered as level
1276 ;; 1 (cf. `org-export-get-relative-level').
1277 ;; - category :: tree
1278 ;; - type :: integer
1280 ;; + `:headline-numbering' :: Alist between headlines and their
1281 ;; numbering, as a list of numbers
1282 ;; (cf. `org-export-get-headline-number').
1283 ;; - category :: tree
1284 ;; - type :: alist (INTEGER . LIST)
1286 ;; + `:id-alist' :: Alist between ID strings and destination file's
1287 ;; path, relative to current directory. It is used by
1288 ;; `org-export-resolve-id-link' to resolve ID links targeting an
1289 ;; external file.
1290 ;; - category :: option
1291 ;; - type :: alist (STRING . STRING)
1293 ;; + `:ignore-list' :: List of elements and objects that should be
1294 ;; ignored during export.
1295 ;; - category :: tree
1296 ;; - type :: list of elements and objects
1298 ;; + `:input-file' :: Full path to input file, if any.
1299 ;; - category :: option
1300 ;; - type :: string or nil
1302 ;; + `:keywords' :: List of keywords attached to data.
1303 ;; - category :: option
1304 ;; - type :: string
1306 ;; + `:language' :: Default language used for translations.
1307 ;; - category :: option
1308 ;; - type :: string
1310 ;; + `:parse-tree' :: Whole parse tree, available at any time during
1311 ;; transcoding.
1312 ;; - category :: option
1313 ;; - type :: list (as returned by `org-element-parse-buffer')
1315 ;; + `:preserve-breaks' :: Non-nil means transcoding should preserve
1316 ;; all line breaks.
1317 ;; - category :: option
1318 ;; - type :: symbol (nil, t)
1320 ;; + `:section-numbers' :: Non-nil means transcoding should add
1321 ;; section numbers to headlines.
1322 ;; - category :: option
1323 ;; - type :: symbol (nil, t)
1325 ;; + `:select-tags' :: List of tags enforcing inclusion of sub-trees
1326 ;; in transcoding. When such a tag is present, subtrees without
1327 ;; it are de facto excluded from the process. See
1328 ;; `use-select-tags'.
1329 ;; - category :: option
1330 ;; - type :: list of strings
1332 ;; + `:time-stamp-file' :: Non-nil means transcoding should insert
1333 ;; a time stamp in the output.
1334 ;; - category :: option
1335 ;; - type :: symbol (nil, t)
1337 ;; + `:translate-alist' :: Alist between element and object types and
1338 ;; transcoding functions relative to the current back-end.
1339 ;; Special keys `inner-template', `template' and `plain-text' are
1340 ;; also possible.
1341 ;; - category :: option
1342 ;; - type :: alist (SYMBOL . FUNCTION)
1344 ;; + `:with-archived-trees' :: Non-nil when archived subtrees should
1345 ;; also be transcoded. If it is set to the `headline' symbol,
1346 ;; only the archived headline's name is retained.
1347 ;; - category :: option
1348 ;; - type :: symbol (nil, t, `headline')
1350 ;; + `:with-author' :: Non-nil means author's name should be included
1351 ;; in the output.
1352 ;; - category :: option
1353 ;; - type :: symbol (nil, t)
1355 ;; + `:with-clocks' :: Non-nil means clock keywords should be exported.
1356 ;; - category :: option
1357 ;; - type :: symbol (nil, t)
1359 ;; + `:with-creator' :: Non-nil means a creation sentence should be
1360 ;; inserted at the end of the transcoded string. If the value
1361 ;; is `comment', it should be commented.
1362 ;; - category :: option
1363 ;; - type :: symbol (`comment', nil, t)
1365 ;; + `:with-date' :: Non-nil means output should contain a date.
1366 ;; - category :: option
1367 ;; - type :. symbol (nil, t)
1369 ;; + `:with-drawers' :: Non-nil means drawers should be exported. If
1370 ;; its value is a list of names, only drawers with such names
1371 ;; will be transcoded. If that list starts with `not', drawer
1372 ;; with these names will be skipped.
1373 ;; - category :: option
1374 ;; - type :: symbol (nil, t) or list of strings
1376 ;; + `:with-email' :: Non-nil means output should contain author's
1377 ;; email.
1378 ;; - category :: option
1379 ;; - type :: symbol (nil, t)
1381 ;; + `:with-emphasize' :: Non-nil means emphasized text should be
1382 ;; interpreted.
1383 ;; - category :: option
1384 ;; - type :: symbol (nil, t)
1386 ;; + `:with-fixed-width' :: Non-nil if transcoder should interpret
1387 ;; strings starting with a colon as a fixed-with (verbatim) area.
1388 ;; - category :: option
1389 ;; - type :: symbol (nil, t)
1391 ;; + `:with-footnotes' :: Non-nil if transcoder should interpret
1392 ;; footnotes.
1393 ;; - category :: option
1394 ;; - type :: symbol (nil, t)
1396 ;; + `:with-latex' :: Non-nil means `latex-environment' elements and
1397 ;; `latex-fragment' objects should appear in export output. When
1398 ;; this property is set to `verbatim', they will be left as-is.
1399 ;; - category :: option
1400 ;; - type :: symbol (`verbatim', nil, t)
1402 ;; + `:with-planning' :: Non-nil means transcoding should include
1403 ;; planning info.
1404 ;; - category :: option
1405 ;; - type :: symbol (nil, t)
1407 ;; + `:with-priority' :: Non-nil means transcoding should include
1408 ;; priority cookies.
1409 ;; - category :: option
1410 ;; - type :: symbol (nil, t)
1412 ;; + `:with-smart-quotes' :: Non-nil means activate smart quotes in
1413 ;; plain text.
1414 ;; - category :: option
1415 ;; - type :: symbol (nil, t)
1417 ;; + `:with-special-strings' :: Non-nil means transcoding should
1418 ;; interpret special strings in plain text.
1419 ;; - category :: option
1420 ;; - type :: symbol (nil, t)
1422 ;; + `:with-sub-superscript' :: Non-nil means transcoding should
1423 ;; interpret subscript and superscript. With a value of "{}",
1424 ;; only interpret those using curly brackets.
1425 ;; - category :: option
1426 ;; - type :: symbol (nil, {}, t)
1428 ;; + `:with-tables' :: Non-nil means transcoding should interpret
1429 ;; tables.
1430 ;; - category :: option
1431 ;; - type :: symbol (nil, t)
1433 ;; + `:with-tags' :: Non-nil means transcoding should keep tags in
1434 ;; headlines. A `not-in-toc' value will remove them from the
1435 ;; table of contents, if any, nonetheless.
1436 ;; - category :: option
1437 ;; - type :: symbol (nil, t, `not-in-toc')
1439 ;; + `:with-tasks' :: Non-nil means transcoding should include
1440 ;; headlines with a TODO keyword. A `todo' value will only
1441 ;; include headlines with a todo type keyword while a `done'
1442 ;; value will do the contrary. If a list of strings is provided,
1443 ;; only tasks with keywords belonging to that list will be kept.
1444 ;; - category :: option
1445 ;; - type :: symbol (t, todo, done, nil) or list of strings
1447 ;; + `:with-timestamps' :: Non-nil means transcoding should include
1448 ;; time stamps. Special value `active' (resp. `inactive') ask to
1449 ;; export only active (resp. inactive) timestamps. Otherwise,
1450 ;; completely remove them.
1451 ;; - category :: option
1452 ;; - type :: symbol: (`active', `inactive', t, nil)
1454 ;; + `:with-toc' :: Non-nil means that a table of contents has to be
1455 ;; added to the output. An integer value limits its depth.
1456 ;; - category :: option
1457 ;; - type :: symbol (nil, t or integer)
1459 ;; + `:with-todo-keywords' :: Non-nil means transcoding should
1460 ;; include TODO keywords.
1461 ;; - category :: option
1462 ;; - type :: symbol (nil, t)
1465 ;;;; Environment Options
1467 ;; Environment options encompass all parameters defined outside the
1468 ;; scope of the parsed data. They come from five sources, in
1469 ;; increasing precedence order:
1471 ;; - Global variables,
1472 ;; - Buffer's attributes,
1473 ;; - Options keyword symbols,
1474 ;; - Buffer keywords,
1475 ;; - Subtree properties.
1477 ;; The central internal function with regards to environment options
1478 ;; is `org-export-get-environment'. It updates global variables with
1479 ;; "#+BIND:" keywords, then retrieve and prioritize properties from
1480 ;; the different sources.
1482 ;; The internal functions doing the retrieval are:
1483 ;; `org-export--get-global-options',
1484 ;; `org-export--get-buffer-attributes',
1485 ;; `org-export--parse-option-keyword',
1486 ;; `org-export--get-subtree-options' and
1487 ;; `org-export--get-inbuffer-options'
1489 ;; Also, `org-export--list-bound-variables' collects bound variables
1490 ;; along with their value in order to set them as buffer local
1491 ;; variables later in the process.
1493 (defun org-export-get-environment (&optional backend subtreep ext-plist)
1494 "Collect export options from the current buffer.
1496 Optional argument BACKEND is an export back-end, as returned by
1497 `org-export-create-backend'.
1499 When optional argument SUBTREEP is non-nil, assume the export is
1500 done against the current sub-tree.
1502 Third optional argument EXT-PLIST is a property list with
1503 external parameters overriding Org default settings, but still
1504 inferior to file-local settings."
1505 ;; First install #+BIND variables since these must be set before
1506 ;; global options are read.
1507 (dolist (pair (org-export--list-bound-variables))
1508 (org-set-local (car pair) (nth 1 pair)))
1509 ;; Get and prioritize export options...
1510 (org-combine-plists
1511 ;; ... from global variables...
1512 (org-export--get-global-options backend)
1513 ;; ... from an external property list...
1514 ext-plist
1515 ;; ... from in-buffer settings...
1516 (org-export--get-inbuffer-options backend)
1517 ;; ... and from subtree, when appropriate.
1518 (and subtreep (org-export--get-subtree-options backend))
1519 ;; Eventually add misc. properties.
1520 (list
1521 :back-end
1522 backend
1523 :translate-alist (org-export-get-all-transcoders backend)
1524 :footnote-definition-alist
1525 ;; Footnotes definitions must be collected in the original
1526 ;; buffer, as there's no insurance that they will still be in
1527 ;; the parse tree, due to possible narrowing.
1528 (let (alist)
1529 (org-with-wide-buffer
1530 (goto-char (point-min))
1531 (while (re-search-forward org-footnote-definition-re nil t)
1532 (let ((def (save-match-data (org-element-at-point))))
1533 (when (eq (org-element-type def) 'footnote-definition)
1534 (push
1535 (cons (org-element-property :label def)
1536 (let ((cbeg (org-element-property :contents-begin def)))
1537 (when cbeg
1538 (org-element--parse-elements
1539 cbeg (org-element-property :contents-end def)
1540 nil nil nil nil (list 'org-data nil)))))
1541 alist))))
1542 alist))
1543 :id-alist
1544 ;; Collect id references.
1545 (let (alist)
1546 (org-with-wide-buffer
1547 (goto-char (point-min))
1548 (while (re-search-forward "\\[\\[id:\\S-+?\\]" nil t)
1549 (let ((link (org-element-context)))
1550 (when (eq (org-element-type link) 'link)
1551 (let* ((id (org-element-property :path link))
1552 (file (org-id-find-id-file id)))
1553 (when file
1554 (push (cons id (file-relative-name file)) alist)))))))
1555 alist))))
1557 (defun org-export--parse-option-keyword (options &optional backend)
1558 "Parse an OPTIONS line and return values as a plist.
1559 Optional argument BACKEND is an export back-end, as returned by,
1560 e.g., `org-export-create-backend'. It specifies which back-end
1561 specific items to read, if any."
1562 (let* ((all
1563 ;; Priority is given to back-end specific options.
1564 (append (and backend (org-export-get-all-options backend))
1565 org-export-options-alist))
1566 plist)
1567 (dolist (option all)
1568 (let ((property (car option))
1569 (item (nth 2 option)))
1570 (when (and item
1571 (not (plist-member plist property))
1572 (string-match (concat "\\(\\`\\|[ \t]\\)"
1573 (regexp-quote item)
1574 ":\\(([^)\n]+)\\|[^ \t\n\r;,.]*\\)")
1575 options))
1576 (setq plist (plist-put plist
1577 property
1578 (car (read-from-string
1579 (match-string 2 options))))))))
1580 plist))
1582 (defun org-export--get-subtree-options (&optional backend)
1583 "Get export options in subtree at point.
1584 Optional argument BACKEND is an export back-end, as returned by,
1585 e.g., `org-export-create-backend'. It specifies back-end used
1586 for export. Return options as a plist."
1587 ;; For each buffer keyword, create a headline property setting the
1588 ;; same property in communication channel. The name for the property
1589 ;; is the keyword with "EXPORT_" appended to it.
1590 (org-with-wide-buffer
1591 (let (prop plist)
1592 ;; Make sure point is at a heading.
1593 (if (org-at-heading-p) (org-up-heading-safe) (org-back-to-heading t))
1594 ;; Take care of EXPORT_TITLE. If it isn't defined, use headline's
1595 ;; title as its fallback value.
1596 (when (setq prop (or (org-entry-get (point) "EXPORT_TITLE")
1597 (progn (looking-at org-todo-line-regexp)
1598 (org-match-string-no-properties 3))))
1599 (setq plist
1600 (plist-put
1601 plist :title
1602 (org-element-parse-secondary-string
1603 prop (org-element-restriction 'keyword)))))
1604 ;; EXPORT_OPTIONS are parsed in a non-standard way.
1605 (when (setq prop (org-entry-get (point) "EXPORT_OPTIONS"))
1606 (setq plist
1607 (nconc plist (org-export--parse-option-keyword prop backend))))
1608 ;; Handle other keywords. TITLE keyword is excluded as it has
1609 ;; been handled already.
1610 (let ((seen '("TITLE")))
1611 (mapc
1612 (lambda (option)
1613 (let ((property (car option))
1614 (keyword (nth 1 option)))
1615 (when (and keyword (not (member keyword seen)))
1616 (let* ((subtree-prop (concat "EXPORT_" keyword))
1617 ;; Export properties are not case-sensitive.
1618 (value (let ((case-fold-search t))
1619 (org-entry-get (point) subtree-prop))))
1620 (push keyword seen)
1621 (when (and value (not (plist-member plist property)))
1622 (setq plist
1623 (plist-put
1624 plist
1625 property
1626 (cond
1627 ;; Parse VALUE if required.
1628 ((member keyword org-element-document-properties)
1629 (org-element-parse-secondary-string
1630 value (org-element-restriction 'keyword)))
1631 ;; If BEHAVIOUR is `split' expected value is
1632 ;; a list of strings, not a string.
1633 ((eq (nth 4 option) 'split) (org-split-string value))
1634 (t value)))))))))
1635 ;; Look for both general keywords and back-end specific
1636 ;; options, with priority given to the latter.
1637 (append (and backend (org-export-get-all-options backend))
1638 org-export-options-alist)))
1639 ;; Return value.
1640 plist)))
1642 (defun org-export--get-inbuffer-options (&optional backend)
1643 "Return current buffer export options, as a plist.
1645 Optional argument BACKEND, when non-nil, is an export back-end,
1646 as returned by, e.g., `org-export-create-backend'. It specifies
1647 which back-end specific options should also be read in the
1648 process.
1650 Assume buffer is in Org mode. Narrowing, if any, is ignored."
1651 (let* (plist
1652 get-options ; For byte-compiler.
1653 (case-fold-search t)
1654 (options (append
1655 ;; Priority is given to back-end specific options.
1656 (and backend (org-export-get-all-options backend))
1657 org-export-options-alist))
1658 (regexp (format "^[ \t]*#\\+%s:"
1659 (regexp-opt (nconc (delq nil (mapcar 'cadr options))
1660 org-export-special-keywords))))
1661 (find-opt
1662 (lambda (keyword)
1663 ;; Return property name associated to KEYWORD.
1664 (catch 'exit
1665 (mapc (lambda (option)
1666 (when (equal (nth 1 option) keyword)
1667 (throw 'exit (car option))))
1668 options))))
1669 (get-options
1670 (lambda (&optional files plist)
1671 ;; Recursively read keywords in buffer. FILES is a list
1672 ;; of files read so far. PLIST is the current property
1673 ;; list obtained.
1674 (org-with-wide-buffer
1675 (goto-char (point-min))
1676 (while (re-search-forward regexp nil t)
1677 (let ((element (org-element-at-point)))
1678 (when (eq (org-element-type element) 'keyword)
1679 (let ((key (org-element-property :key element))
1680 (val (org-element-property :value element)))
1681 (cond
1682 ;; Options in `org-export-special-keywords'.
1683 ((equal key "SETUPFILE")
1684 (let ((file (expand-file-name
1685 (org-remove-double-quotes (org-trim val)))))
1686 ;; Avoid circular dependencies.
1687 (unless (member file files)
1688 (with-temp-buffer
1689 (insert (org-file-contents file 'noerror))
1690 (let ((org-inhibit-startup t)) (org-mode))
1691 (setq plist (funcall get-options
1692 (cons file files) plist))))))
1693 ((equal key "OPTIONS")
1694 (setq plist
1695 (org-combine-plists
1696 plist
1697 (org-export--parse-option-keyword val backend))))
1698 ((equal key "FILETAGS")
1699 (setq plist
1700 (org-combine-plists
1701 plist
1702 (list :filetags
1703 (org-uniquify
1704 (append (org-split-string val ":")
1705 (plist-get plist :filetags)))))))
1707 ;; Options in `org-export-options-alist'.
1708 (let* ((prop (funcall find-opt key))
1709 (behaviour (nth 4 (assq prop options))))
1710 (setq plist
1711 (plist-put
1712 plist prop
1713 ;; Handle value depending on specified
1714 ;; BEHAVIOUR.
1715 (case behaviour
1716 (space
1717 (if (not (plist-get plist prop))
1718 (org-trim val)
1719 (concat (plist-get plist prop)
1721 (org-trim val))))
1722 (newline
1723 (org-trim (concat (plist-get plist prop)
1724 "\n"
1725 (org-trim val))))
1726 (split `(,@(plist-get plist prop)
1727 ,@(org-split-string val)))
1728 ('t val)
1729 (otherwise
1730 (if (not (plist-member plist prop)) val
1731 (plist-get plist prop)))))))))))))
1732 ;; Return final value.
1733 plist))))
1734 ;; Read options in the current buffer.
1735 (setq plist (funcall get-options buffer-file-name nil))
1736 ;; Parse keywords specified in `org-element-document-properties'.
1737 (mapc (lambda (keyword)
1738 ;; Find the property associated to the keyword.
1739 (let* ((prop (funcall find-opt keyword))
1740 (value (and prop (plist-get plist prop))))
1741 (when (stringp value)
1742 (setq plist
1743 (plist-put plist prop
1744 (org-element-parse-secondary-string
1745 value (org-element-restriction 'keyword)))))))
1746 org-element-document-properties)
1747 ;; Return value.
1748 plist))
1750 (defun org-export--get-buffer-attributes ()
1751 "Return properties related to buffer attributes, as a plist."
1752 ;; Store full path of input file name, or nil. For internal use.
1753 (list :input-file (buffer-file-name (buffer-base-buffer))))
1755 (defvar org-export--default-title nil) ; Dynamically scoped.
1756 (defun org-export-store-default-title ()
1757 "Return default title for current document, as a string.
1758 Title is extracted from associated file name, if any, or buffer's
1759 name."
1760 (setq org-export--default-title
1761 (or (let ((visited-file (buffer-file-name (buffer-base-buffer))))
1762 (and visited-file
1763 (file-name-sans-extension
1764 (file-name-nondirectory visited-file))))
1765 (buffer-name (buffer-base-buffer)))))
1767 (defun org-export--get-global-options (&optional backend)
1768 "Return global export options as a plist.
1769 Optional argument BACKEND, if non-nil, is an export back-end, as
1770 returned by, e.g., `org-export-create-backend'. It specifies
1771 which back-end specific export options should also be read in the
1772 process."
1773 (let (plist
1774 ;; Priority is given to back-end specific options.
1775 (all (append (and backend (org-export-get-all-options backend))
1776 org-export-options-alist)))
1777 (dolist (cell all plist)
1778 (let ((prop (car cell)))
1779 (unless (plist-member plist prop)
1780 (setq plist
1781 (plist-put
1782 plist
1783 prop
1784 ;; Eval default value provided. If keyword is
1785 ;; a member of `org-element-document-properties',
1786 ;; parse it as a secondary string before storing it.
1787 (let ((value (eval (nth 3 cell))))
1788 (if (not (stringp value)) value
1789 (let ((keyword (nth 1 cell)))
1790 (if (member keyword org-element-document-properties)
1791 (org-element-parse-secondary-string
1792 value (org-element-restriction 'keyword))
1793 value)))))))))))
1795 (defun org-export--list-bound-variables ()
1796 "Return variables bound from BIND keywords in current buffer.
1797 Also look for BIND keywords in setup files. The return value is
1798 an alist where associations are (VARIABLE-NAME VALUE)."
1799 (when org-export-allow-bind-keywords
1800 (let* (collect-bind ; For byte-compiler.
1801 (collect-bind
1802 (lambda (files alist)
1803 ;; Return an alist between variable names and their
1804 ;; value. FILES is a list of setup files names read so
1805 ;; far, used to avoid circular dependencies. ALIST is
1806 ;; the alist collected so far.
1807 (let ((case-fold-search t))
1808 (org-with-wide-buffer
1809 (goto-char (point-min))
1810 (while (re-search-forward
1811 "^[ \t]*#\\+\\(BIND\\|SETUPFILE\\):" nil t)
1812 (let ((element (org-element-at-point)))
1813 (when (eq (org-element-type element) 'keyword)
1814 (let ((val (org-element-property :value element)))
1815 (if (equal (org-element-property :key element) "BIND")
1816 (push (read (format "(%s)" val)) alist)
1817 ;; Enter setup file.
1818 (let ((file (expand-file-name
1819 (org-remove-double-quotes val))))
1820 (unless (member file files)
1821 (with-temp-buffer
1822 (let ((org-inhibit-startup t)) (org-mode))
1823 (insert (org-file-contents file 'noerror))
1824 (setq alist
1825 (funcall collect-bind
1826 (cons file files)
1827 alist))))))))))
1828 alist)))))
1829 ;; Return value in appropriate order of appearance.
1830 (nreverse (funcall collect-bind nil nil)))))
1833 ;;;; Tree Properties
1835 ;; Tree properties are information extracted from parse tree. They
1836 ;; are initialized at the beginning of the transcoding process by
1837 ;; `org-export-collect-tree-properties'.
1839 ;; Dedicated functions focus on computing the value of specific tree
1840 ;; properties during initialization. Thus,
1841 ;; `org-export--populate-ignore-list' lists elements and objects that
1842 ;; should be skipped during export, `org-export--get-min-level' gets
1843 ;; the minimal exportable level, used as a basis to compute relative
1844 ;; level for headlines. Eventually
1845 ;; `org-export--collect-headline-numbering' builds an alist between
1846 ;; headlines and their numbering.
1848 (defun org-export-collect-tree-properties (data info)
1849 "Extract tree properties from parse tree.
1851 DATA is the parse tree from which information is retrieved. INFO
1852 is a list holding export options.
1854 Following tree properties are set or updated:
1856 `:exported-data' Hash table used to memoize results from
1857 `org-export-data'.
1859 `:footnote-definition-alist' List of footnotes definitions in
1860 original buffer and current parse tree.
1862 `:headline-offset' Offset between true level of headlines and
1863 local level. An offset of -1 means a headline
1864 of level 2 should be considered as a level
1865 1 headline in the context.
1867 `:headline-numbering' Alist of all headlines as key an the
1868 associated numbering as value.
1870 `:ignore-list' List of elements that should be ignored during
1871 export.
1873 Return updated plist."
1874 ;; Install the parse tree in the communication channel, in order to
1875 ;; use `org-export-get-genealogy' and al.
1876 (setq info (plist-put info :parse-tree data))
1877 ;; Get the list of elements and objects to ignore, and put it into
1878 ;; `:ignore-list'. Do not overwrite any user ignore that might have
1879 ;; been done during parse tree filtering.
1880 (setq info
1881 (plist-put info
1882 :ignore-list
1883 (append (org-export--populate-ignore-list data info)
1884 (plist-get info :ignore-list))))
1885 ;; Compute `:headline-offset' in order to be able to use
1886 ;; `org-export-get-relative-level'.
1887 (setq info
1888 (plist-put info
1889 :headline-offset
1890 (- 1 (org-export--get-min-level data info))))
1891 ;; Update footnotes definitions list with definitions in parse tree.
1892 ;; This is required since buffer expansion might have modified
1893 ;; boundaries of footnote definitions contained in the parse tree.
1894 ;; This way, definitions in `footnote-definition-alist' are bound to
1895 ;; match those in the parse tree.
1896 (let ((defs (plist-get info :footnote-definition-alist)))
1897 (org-element-map data 'footnote-definition
1898 (lambda (fn)
1899 (push (cons (org-element-property :label fn)
1900 `(org-data nil ,@(org-element-contents fn)))
1901 defs)))
1902 (setq info (plist-put info :footnote-definition-alist defs)))
1903 ;; Properties order doesn't matter: get the rest of the tree
1904 ;; properties.
1905 (nconc
1906 `(:headline-numbering ,(org-export--collect-headline-numbering data info)
1907 :exported-data ,(make-hash-table :test 'eq :size 4001))
1908 info))
1910 (defun org-export--get-min-level (data options)
1911 "Return minimum exportable headline's level in DATA.
1912 DATA is parsed tree as returned by `org-element-parse-buffer'.
1913 OPTIONS is a plist holding export options."
1914 (catch 'exit
1915 (let ((min-level 10000))
1916 (mapc
1917 (lambda (blob)
1918 (when (and (eq (org-element-type blob) 'headline)
1919 (not (org-element-property :footnote-section-p blob))
1920 (not (memq blob (plist-get options :ignore-list))))
1921 (setq min-level (min (org-element-property :level blob) min-level)))
1922 (when (= min-level 1) (throw 'exit 1)))
1923 (org-element-contents data))
1924 ;; If no headline was found, for the sake of consistency, set
1925 ;; minimum level to 1 nonetheless.
1926 (if (= min-level 10000) 1 min-level))))
1928 (defun org-export--collect-headline-numbering (data options)
1929 "Return numbering of all exportable headlines in a parse tree.
1931 DATA is the parse tree. OPTIONS is the plist holding export
1932 options.
1934 Return an alist whose key is a headline and value is its
1935 associated numbering \(in the shape of a list of numbers\) or nil
1936 for a footnotes section."
1937 (let ((numbering (make-vector org-export-max-depth 0)))
1938 (org-element-map data 'headline
1939 (lambda (headline)
1940 (unless (org-element-property :footnote-section-p headline)
1941 (let ((relative-level
1942 (1- (org-export-get-relative-level headline options))))
1943 (cons
1944 headline
1945 (loop for n across numbering
1946 for idx from 0 to org-export-max-depth
1947 when (< idx relative-level) collect n
1948 when (= idx relative-level) collect (aset numbering idx (1+ n))
1949 when (> idx relative-level) do (aset numbering idx 0))))))
1950 options)))
1952 (defun org-export--populate-ignore-list (data options)
1953 "Return list of elements and objects to ignore during export.
1954 DATA is the parse tree to traverse. OPTIONS is the plist holding
1955 export options."
1956 (let* (ignore
1957 walk-data
1958 ;; First find trees containing a select tag, if any.
1959 (selected (org-export--selected-trees data options))
1960 (walk-data
1961 (lambda (data)
1962 ;; Collect ignored elements or objects into IGNORE-LIST.
1963 (let ((type (org-element-type data)))
1964 (if (org-export--skip-p data options selected) (push data ignore)
1965 (if (and (eq type 'headline)
1966 (eq (plist-get options :with-archived-trees) 'headline)
1967 (org-element-property :archivedp data))
1968 ;; If headline is archived but tree below has
1969 ;; to be skipped, add it to ignore list.
1970 (mapc (lambda (e) (push e ignore))
1971 (org-element-contents data))
1972 ;; Move into secondary string, if any.
1973 (let ((sec-prop
1974 (cdr (assq type org-element-secondary-value-alist))))
1975 (when sec-prop
1976 (mapc walk-data (org-element-property sec-prop data))))
1977 ;; Move into recursive objects/elements.
1978 (mapc walk-data (org-element-contents data))))))))
1979 ;; Main call.
1980 (funcall walk-data data)
1981 ;; Return value.
1982 ignore))
1984 (defun org-export--selected-trees (data info)
1985 "Return list of headlines and inlinetasks with a select tag in their tree.
1986 DATA is parsed data as returned by `org-element-parse-buffer'.
1987 INFO is a plist holding export options."
1988 (let* (selected-trees
1989 walk-data ; For byte-compiler.
1990 (walk-data
1991 (function
1992 (lambda (data genealogy)
1993 (let ((type (org-element-type data)))
1994 (cond
1995 ((memq type '(headline inlinetask))
1996 (let ((tags (org-element-property :tags data)))
1997 (if (loop for tag in (plist-get info :select-tags)
1998 thereis (member tag tags))
1999 ;; When a select tag is found, mark full
2000 ;; genealogy and every headline within the tree
2001 ;; as acceptable.
2002 (setq selected-trees
2003 (append
2004 genealogy
2005 (org-element-map data '(headline inlinetask)
2006 'identity)
2007 selected-trees))
2008 ;; If at a headline, continue searching in tree,
2009 ;; recursively.
2010 (when (eq type 'headline)
2011 (mapc (lambda (el)
2012 (funcall walk-data el (cons data genealogy)))
2013 (org-element-contents data))))))
2014 ((or (eq type 'org-data)
2015 (memq type org-element-greater-elements))
2016 (mapc (lambda (el) (funcall walk-data el genealogy))
2017 (org-element-contents data)))))))))
2018 (funcall walk-data data nil)
2019 selected-trees))
2021 (defun org-export--skip-p (blob options selected)
2022 "Non-nil when element or object BLOB should be skipped during export.
2023 OPTIONS is the plist holding export options. SELECTED, when
2024 non-nil, is a list of headlines or inlinetasks belonging to
2025 a tree with a select tag."
2026 (case (org-element-type blob)
2027 (clock (not (plist-get options :with-clocks)))
2028 (drawer
2029 (let ((with-drawers-p (plist-get options :with-drawers)))
2030 (or (not with-drawers-p)
2031 (and (consp with-drawers-p)
2032 ;; If `:with-drawers' value starts with `not', ignore
2033 ;; every drawer whose name belong to that list.
2034 ;; Otherwise, ignore drawers whose name isn't in that
2035 ;; list.
2036 (let ((name (org-element-property :drawer-name blob)))
2037 (if (eq (car with-drawers-p) 'not)
2038 (member-ignore-case name (cdr with-drawers-p))
2039 (not (member-ignore-case name with-drawers-p))))))))
2040 ((footnote-definition footnote-reference)
2041 (not (plist-get options :with-footnotes)))
2042 ((headline inlinetask)
2043 (let ((with-tasks (plist-get options :with-tasks))
2044 (todo (org-element-property :todo-keyword blob))
2045 (todo-type (org-element-property :todo-type blob))
2046 (archived (plist-get options :with-archived-trees))
2047 (tags (org-element-property :tags blob)))
2049 (and (eq (org-element-type blob) 'inlinetask)
2050 (not (plist-get options :with-inlinetasks)))
2051 ;; Ignore subtrees with an exclude tag.
2052 (loop for k in (plist-get options :exclude-tags)
2053 thereis (member k tags))
2054 ;; When a select tag is present in the buffer, ignore any tree
2055 ;; without it.
2056 (and selected (not (memq blob selected)))
2057 ;; Ignore commented sub-trees.
2058 (org-element-property :commentedp blob)
2059 ;; Ignore archived subtrees if `:with-archived-trees' is nil.
2060 (and (not archived) (org-element-property :archivedp blob))
2061 ;; Ignore tasks, if specified by `:with-tasks' property.
2062 (and todo
2063 (or (not with-tasks)
2064 (and (memq with-tasks '(todo done))
2065 (not (eq todo-type with-tasks)))
2066 (and (consp with-tasks) (not (member todo with-tasks))))))))
2067 ((latex-environment latex-fragment) (not (plist-get options :with-latex)))
2068 (planning (not (plist-get options :with-planning)))
2069 (statistics-cookie (not (plist-get options :with-statistics-cookies)))
2070 (table-cell
2071 (and (org-export-table-has-special-column-p
2072 (org-export-get-parent-table blob))
2073 (not (org-export-get-previous-element blob options))))
2074 (table-row (org-export-table-row-is-special-p blob options))
2075 (timestamp
2076 ;; `:with-timestamps' only applies to isolated timestamps
2077 ;; objects, i.e. timestamp objects in a paragraph containing only
2078 ;; timestamps and whitespaces.
2079 (when (let ((parent (org-export-get-parent-element blob)))
2080 (and (memq (org-element-type parent) '(paragraph verse-block))
2081 (not (org-element-map parent
2082 (cons 'plain-text
2083 (remq 'timestamp org-element-all-objects))
2084 (lambda (obj)
2085 (or (not (stringp obj)) (org-string-nw-p obj)))
2086 options t))))
2087 (case (plist-get options :with-timestamps)
2088 ('nil t)
2089 (active
2090 (not (memq (org-element-property :type blob) '(active active-range))))
2091 (inactive
2092 (not (memq (org-element-property :type blob)
2093 '(inactive inactive-range)))))))))
2096 ;;; The Transcoder
2098 ;; `org-export-data' reads a parse tree (obtained with, i.e.
2099 ;; `org-element-parse-buffer') and transcodes it into a specified
2100 ;; back-end output. It takes care of filtering out elements or
2101 ;; objects according to export options and organizing the output blank
2102 ;; lines and white space are preserved. The function memoizes its
2103 ;; results, so it is cheap to call it within transcoders.
2105 ;; It is possible to modify locally the back-end used by
2106 ;; `org-export-data' or even use a temporary back-end by using
2107 ;; `org-export-data-with-backend'.
2109 ;; Internally, three functions handle the filtering of objects and
2110 ;; elements during the export. In particular,
2111 ;; `org-export-ignore-element' marks an element or object so future
2112 ;; parse tree traversals skip it, `org-export--interpret-p' tells which
2113 ;; elements or objects should be seen as real Org syntax and
2114 ;; `org-export-expand' transforms the others back into their original
2115 ;; shape
2117 ;; `org-export-transcoder' is an accessor returning appropriate
2118 ;; translator function for a given element or object.
2120 (defun org-export-transcoder (blob info)
2121 "Return appropriate transcoder for BLOB.
2122 INFO is a plist containing export directives."
2123 (let ((type (org-element-type blob)))
2124 ;; Return contents only for complete parse trees.
2125 (if (eq type 'org-data) (lambda (blob contents info) contents)
2126 (let ((transcoder (cdr (assq type (plist-get info :translate-alist)))))
2127 (and (functionp transcoder) transcoder)))))
2129 (defun org-export-data (data info)
2130 "Convert DATA into current back-end format.
2132 DATA is a parse tree, an element or an object or a secondary
2133 string. INFO is a plist holding export options.
2135 Return transcoded string."
2136 (let ((memo (gethash data (plist-get info :exported-data) 'no-memo)))
2137 (if (not (eq memo 'no-memo)) memo
2138 (let* ((type (org-element-type data))
2139 (results
2140 (cond
2141 ;; Ignored element/object.
2142 ((memq data (plist-get info :ignore-list)) nil)
2143 ;; Plain text.
2144 ((eq type 'plain-text)
2145 (org-export-filter-apply-functions
2146 (plist-get info :filter-plain-text)
2147 (let ((transcoder (org-export-transcoder data info)))
2148 (if transcoder (funcall transcoder data info) data))
2149 info))
2150 ;; Uninterpreted element/object: change it back to Org
2151 ;; syntax and export again resulting raw string.
2152 ((not (org-export--interpret-p data info))
2153 (org-export-data
2154 (org-export-expand
2155 data
2156 (mapconcat (lambda (blob) (org-export-data blob info))
2157 (org-element-contents data)
2158 ""))
2159 info))
2160 ;; Secondary string.
2161 ((not type)
2162 (mapconcat (lambda (obj) (org-export-data obj info)) data ""))
2163 ;; Element/Object without contents or, as a special case,
2164 ;; headline with archive tag and archived trees restricted
2165 ;; to title only.
2166 ((or (not (org-element-contents data))
2167 (and (eq type 'headline)
2168 (eq (plist-get info :with-archived-trees) 'headline)
2169 (org-element-property :archivedp data)))
2170 (let ((transcoder (org-export-transcoder data info)))
2171 (or (and (functionp transcoder)
2172 (funcall transcoder data nil info))
2173 ;; Export snippets never return a nil value so
2174 ;; that white spaces following them are never
2175 ;; ignored.
2176 (and (eq type 'export-snippet) ""))))
2177 ;; Element/Object with contents.
2179 (let ((transcoder (org-export-transcoder data info)))
2180 (when transcoder
2181 (let* ((greaterp (memq type org-element-greater-elements))
2182 (objectp
2183 (and (not greaterp)
2184 (memq type org-element-recursive-objects)))
2185 (contents
2186 (mapconcat
2187 (lambda (element) (org-export-data element info))
2188 (org-element-contents
2189 (if (or greaterp objectp) data
2190 ;; Elements directly containing objects
2191 ;; must have their indentation normalized
2192 ;; first.
2193 (org-element-normalize-contents
2194 data
2195 ;; When normalizing contents of the first
2196 ;; paragraph in an item or a footnote
2197 ;; definition, ignore first line's
2198 ;; indentation: there is none and it
2199 ;; might be misleading.
2200 (when (eq type 'paragraph)
2201 (let ((parent (org-export-get-parent data)))
2202 (and
2203 (eq (car (org-element-contents parent))
2204 data)
2205 (memq (org-element-type parent)
2206 '(footnote-definition item))))))))
2207 "")))
2208 (funcall transcoder data
2209 (if (not greaterp) contents
2210 (org-element-normalize-string contents))
2211 info))))))))
2212 ;; Final result will be memoized before being returned.
2213 (puthash
2214 data
2215 (cond
2216 ((not results) nil)
2217 ((memq type '(org-data plain-text nil)) results)
2218 ;; Append the same white space between elements or objects as in
2219 ;; the original buffer, and call appropriate filters.
2221 (let ((results
2222 (org-export-filter-apply-functions
2223 (plist-get info (intern (format ":filter-%s" type)))
2224 (let ((post-blank (or (org-element-property :post-blank data)
2225 0)))
2226 (if (memq type org-element-all-elements)
2227 (concat (org-element-normalize-string results)
2228 (make-string post-blank ?\n))
2229 (concat results (make-string post-blank ? ))))
2230 info)))
2231 results)))
2232 (plist-get info :exported-data))))))
2234 (defun org-export-data-with-backend (data backend info)
2235 "Convert DATA into BACKEND format.
2237 DATA is an element, an object, a secondary string or a string.
2238 BACKEND is a symbol. INFO is a plist used as a communication
2239 channel.
2241 Unlike to `org-export-with-backend', this function will
2242 recursively convert DATA using BACKEND translation table."
2243 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
2244 (org-export-data
2245 data
2246 ;; Set-up a new communication channel with translations defined in
2247 ;; BACKEND as the translate table and a new hash table for
2248 ;; memoization.
2249 (org-combine-plists
2250 info
2251 (list :translate-alist (org-export-get-all-transcoders backend)
2252 ;; Size of the hash table is reduced since this function
2253 ;; will probably be used on short trees.
2254 :exported-data (make-hash-table :test 'eq :size 401)))))
2256 (defun org-export--interpret-p (blob info)
2257 "Non-nil if element or object BLOB should be interpreted during export.
2258 If nil, BLOB will appear as raw Org syntax. Check is done
2259 according to export options INFO, stored as a plist."
2260 (case (org-element-type blob)
2261 ;; ... entities...
2262 (entity (plist-get info :with-entities))
2263 ;; ... emphasis...
2264 ((bold italic strike-through underline)
2265 (plist-get info :with-emphasize))
2266 ;; ... fixed-width areas.
2267 (fixed-width (plist-get info :with-fixed-width))
2268 ;; ... LaTeX environments and fragments...
2269 ((latex-environment latex-fragment)
2270 (let ((with-latex-p (plist-get info :with-latex)))
2271 (and with-latex-p (not (eq with-latex-p 'verbatim)))))
2272 ;; ... sub/superscripts...
2273 ((subscript superscript)
2274 (let ((sub/super-p (plist-get info :with-sub-superscript)))
2275 (if (eq sub/super-p '{})
2276 (org-element-property :use-brackets-p blob)
2277 sub/super-p)))
2278 ;; ... tables...
2279 (table (plist-get info :with-tables))
2280 (otherwise t)))
2282 (defun org-export-expand (blob contents &optional with-affiliated)
2283 "Expand a parsed element or object to its original state.
2285 BLOB is either an element or an object. CONTENTS is its
2286 contents, as a string or nil.
2288 When optional argument WITH-AFFILIATED is non-nil, add affiliated
2289 keywords before output."
2290 (let ((type (org-element-type blob)))
2291 (concat (and with-affiliated (memq type org-element-all-elements)
2292 (org-element--interpret-affiliated-keywords blob))
2293 (funcall (intern (format "org-element-%s-interpreter" type))
2294 blob contents))))
2296 (defun org-export-ignore-element (element info)
2297 "Add ELEMENT to `:ignore-list' in INFO.
2299 Any element in `:ignore-list' will be skipped when using
2300 `org-element-map'. INFO is modified by side effects."
2301 (plist-put info :ignore-list (cons element (plist-get info :ignore-list))))
2305 ;;; The Filter System
2307 ;; Filters allow end-users to tweak easily the transcoded output.
2308 ;; They are the functional counterpart of hooks, as every filter in
2309 ;; a set is applied to the return value of the previous one.
2311 ;; Every set is back-end agnostic. Although, a filter is always
2312 ;; called, in addition to the string it applies to, with the back-end
2313 ;; used as argument, so it's easy for the end-user to add back-end
2314 ;; specific filters in the set. The communication channel, as
2315 ;; a plist, is required as the third argument.
2317 ;; From the developer side, filters sets can be installed in the
2318 ;; process with the help of `org-export-define-backend', which
2319 ;; internally stores filters as an alist. Each association has a key
2320 ;; among the following symbols and a function or a list of functions
2321 ;; as value.
2323 ;; - `:filter-options' applies to the property list containing export
2324 ;; options. Unlike to other filters, functions in this list accept
2325 ;; two arguments instead of three: the property list containing
2326 ;; export options and the back-end. Users can set its value through
2327 ;; `org-export-filter-options-functions' variable.
2329 ;; - `:filter-parse-tree' applies directly to the complete parsed
2330 ;; tree. Users can set it through
2331 ;; `org-export-filter-parse-tree-functions' variable.
2333 ;; - `:filter-final-output' applies to the final transcoded string.
2334 ;; Users can set it with `org-export-filter-final-output-functions'
2335 ;; variable
2337 ;; - `:filter-plain-text' applies to any string not recognized as Org
2338 ;; syntax. `org-export-filter-plain-text-functions' allows users to
2339 ;; configure it.
2341 ;; - `:filter-TYPE' applies on the string returned after an element or
2342 ;; object of type TYPE has been transcoded. A user can modify
2343 ;; `org-export-filter-TYPE-functions'
2345 ;; All filters sets are applied with
2346 ;; `org-export-filter-apply-functions' function. Filters in a set are
2347 ;; applied in a LIFO fashion. It allows developers to be sure that
2348 ;; their filters will be applied first.
2350 ;; Filters properties are installed in communication channel with
2351 ;; `org-export-install-filters' function.
2353 ;; Eventually, two hooks (`org-export-before-processing-hook' and
2354 ;; `org-export-before-parsing-hook') are run at the beginning of the
2355 ;; export process and just before parsing to allow for heavy structure
2356 ;; modifications.
2359 ;;;; Hooks
2361 (defvar org-export-before-processing-hook nil
2362 "Hook run at the beginning of the export process.
2364 This is run before include keywords and macros are expanded and
2365 Babel code blocks executed, on a copy of the original buffer
2366 being exported. Visibility and narrowing are preserved. Point
2367 is at the beginning of the buffer.
2369 Every function in this hook will be called with one argument: the
2370 back-end currently used, as a symbol.")
2372 (defvar org-export-before-parsing-hook nil
2373 "Hook run before parsing an export buffer.
2375 This is run after include keywords and macros have been expanded
2376 and Babel code blocks executed, on a copy of the original buffer
2377 being exported. Visibility and narrowing are preserved. Point
2378 is at the beginning of the buffer.
2380 Every function in this hook will be called with one argument: the
2381 back-end currently used, as a symbol.")
2384 ;;;; Special Filters
2386 (defvar org-export-filter-options-functions nil
2387 "List of functions applied to the export options.
2388 Each filter is called with two arguments: the export options, as
2389 a plist, and the back-end, as a symbol. It must return
2390 a property list containing export options.")
2392 (defvar org-export-filter-parse-tree-functions nil
2393 "List of functions applied to the parsed tree.
2394 Each filter is called with three arguments: the parse tree, as
2395 returned by `org-element-parse-buffer', the back-end, as
2396 a symbol, and the communication channel, as a plist. It must
2397 return the modified parse tree to transcode.")
2399 (defvar org-export-filter-plain-text-functions nil
2400 "List of functions applied to plain text.
2401 Each filter is called with three arguments: a string which
2402 contains no Org syntax, the back-end, as a symbol, and the
2403 communication channel, as a plist. It must return a string or
2404 nil.")
2406 (defvar org-export-filter-final-output-functions nil
2407 "List of functions applied to the transcoded string.
2408 Each filter is called with three arguments: the full transcoded
2409 string, the back-end, as a symbol, and the communication channel,
2410 as a plist. It must return a string that will be used as the
2411 final export output.")
2414 ;;;; Elements Filters
2416 (defvar org-export-filter-babel-call-functions nil
2417 "List of functions applied to a transcoded babel-call.
2418 Each filter is called with three arguments: the transcoded data,
2419 as a string, the back-end, as a symbol, and the communication
2420 channel, as a plist. It must return a string or nil.")
2422 (defvar org-export-filter-center-block-functions nil
2423 "List of functions applied to a transcoded center block.
2424 Each filter is called with three arguments: the transcoded data,
2425 as a string, the back-end, as a symbol, and the communication
2426 channel, as a plist. It must return a string or nil.")
2428 (defvar org-export-filter-clock-functions nil
2429 "List of functions applied to a transcoded clock.
2430 Each filter is called with three arguments: the transcoded data,
2431 as a string, the back-end, as a symbol, and the communication
2432 channel, as a plist. It must return a string or nil.")
2434 (defvar org-export-filter-comment-functions nil
2435 "List of functions applied to a transcoded comment.
2436 Each filter is called with three arguments: the transcoded data,
2437 as a string, the back-end, as a symbol, and the communication
2438 channel, as a plist. It must return a string or nil.")
2440 (defvar org-export-filter-comment-block-functions nil
2441 "List of functions applied to a transcoded comment-block.
2442 Each filter is called with three arguments: the transcoded data,
2443 as a string, the back-end, as a symbol, and the communication
2444 channel, as a plist. It must return a string or nil.")
2446 (defvar org-export-filter-diary-sexp-functions nil
2447 "List of functions applied to a transcoded diary-sexp.
2448 Each filter is called with three arguments: the transcoded data,
2449 as a string, the back-end, as a symbol, and the communication
2450 channel, as a plist. It must return a string or nil.")
2452 (defvar org-export-filter-drawer-functions nil
2453 "List of functions applied to a transcoded drawer.
2454 Each filter is called with three arguments: the transcoded data,
2455 as a string, the back-end, as a symbol, and the communication
2456 channel, as a plist. It must return a string or nil.")
2458 (defvar org-export-filter-dynamic-block-functions nil
2459 "List of functions applied to a transcoded dynamic-block.
2460 Each filter is called with three arguments: the transcoded data,
2461 as a string, the back-end, as a symbol, and the communication
2462 channel, as a plist. It must return a string or nil.")
2464 (defvar org-export-filter-example-block-functions nil
2465 "List of functions applied to a transcoded example-block.
2466 Each filter is called with three arguments: the transcoded data,
2467 as a string, the back-end, as a symbol, and the communication
2468 channel, as a plist. It must return a string or nil.")
2470 (defvar org-export-filter-export-block-functions nil
2471 "List of functions applied to a transcoded export-block.
2472 Each filter is called with three arguments: the transcoded data,
2473 as a string, the back-end, as a symbol, and the communication
2474 channel, as a plist. It must return a string or nil.")
2476 (defvar org-export-filter-fixed-width-functions nil
2477 "List of functions applied to a transcoded fixed-width.
2478 Each filter is called with three arguments: the transcoded data,
2479 as a string, the back-end, as a symbol, and the communication
2480 channel, as a plist. It must return a string or nil.")
2482 (defvar org-export-filter-footnote-definition-functions nil
2483 "List of functions applied to a transcoded footnote-definition.
2484 Each filter is called with three arguments: the transcoded data,
2485 as a string, the back-end, as a symbol, and the communication
2486 channel, as a plist. It must return a string or nil.")
2488 (defvar org-export-filter-headline-functions nil
2489 "List of functions applied to a transcoded headline.
2490 Each filter is called with three arguments: the transcoded data,
2491 as a string, the back-end, as a symbol, and the communication
2492 channel, as a plist. It must return a string or nil.")
2494 (defvar org-export-filter-horizontal-rule-functions nil
2495 "List of functions applied to a transcoded horizontal-rule.
2496 Each filter is called with three arguments: the transcoded data,
2497 as a string, the back-end, as a symbol, and the communication
2498 channel, as a plist. It must return a string or nil.")
2500 (defvar org-export-filter-inlinetask-functions nil
2501 "List of functions applied to a transcoded inlinetask.
2502 Each filter is called with three arguments: the transcoded data,
2503 as a string, the back-end, as a symbol, and the communication
2504 channel, as a plist. It must return a string or nil.")
2506 (defvar org-export-filter-item-functions nil
2507 "List of functions applied to a transcoded item.
2508 Each filter is called with three arguments: the transcoded data,
2509 as a string, the back-end, as a symbol, and the communication
2510 channel, as a plist. It must return a string or nil.")
2512 (defvar org-export-filter-keyword-functions nil
2513 "List of functions applied to a transcoded keyword.
2514 Each filter is called with three arguments: the transcoded data,
2515 as a string, the back-end, as a symbol, and the communication
2516 channel, as a plist. It must return a string or nil.")
2518 (defvar org-export-filter-latex-environment-functions nil
2519 "List of functions applied to a transcoded latex-environment.
2520 Each filter is called with three arguments: the transcoded data,
2521 as a string, the back-end, as a symbol, and the communication
2522 channel, as a plist. It must return a string or nil.")
2524 (defvar org-export-filter-node-property-functions nil
2525 "List of functions applied to a transcoded node-property.
2526 Each filter is called with three arguments: the transcoded data,
2527 as a string, the back-end, as a symbol, and the communication
2528 channel, as a plist. It must return a string or nil.")
2530 (defvar org-export-filter-paragraph-functions nil
2531 "List of functions applied to a transcoded paragraph.
2532 Each filter is called with three arguments: the transcoded data,
2533 as a string, the back-end, as a symbol, and the communication
2534 channel, as a plist. It must return a string or nil.")
2536 (defvar org-export-filter-plain-list-functions nil
2537 "List of functions applied to a transcoded plain-list.
2538 Each filter is called with three arguments: the transcoded data,
2539 as a string, the back-end, as a symbol, and the communication
2540 channel, as a plist. It must return a string or nil.")
2542 (defvar org-export-filter-planning-functions nil
2543 "List of functions applied to a transcoded planning.
2544 Each filter is called with three arguments: the transcoded data,
2545 as a string, the back-end, as a symbol, and the communication
2546 channel, as a plist. It must return a string or nil.")
2548 (defvar org-export-filter-property-drawer-functions nil
2549 "List of functions applied to a transcoded property-drawer.
2550 Each filter is called with three arguments: the transcoded data,
2551 as a string, the back-end, as a symbol, and the communication
2552 channel, as a plist. It must return a string or nil.")
2554 (defvar org-export-filter-quote-block-functions nil
2555 "List of functions applied to a transcoded quote block.
2556 Each filter is called with three arguments: the transcoded quote
2557 data, as a string, the back-end, as a symbol, and the
2558 communication channel, as a plist. It must return a string or
2559 nil.")
2561 (defvar org-export-filter-quote-section-functions nil
2562 "List of functions applied to a transcoded quote-section.
2563 Each filter is called with three arguments: the transcoded data,
2564 as a string, the back-end, as a symbol, and the communication
2565 channel, as a plist. It must return a string or nil.")
2567 (defvar org-export-filter-section-functions nil
2568 "List of functions applied to a transcoded section.
2569 Each filter is called with three arguments: the transcoded data,
2570 as a string, the back-end, as a symbol, and the communication
2571 channel, as a plist. It must return a string or nil.")
2573 (defvar org-export-filter-special-block-functions nil
2574 "List of functions applied to a transcoded special block.
2575 Each filter is called with three arguments: the transcoded data,
2576 as a string, the back-end, as a symbol, and the communication
2577 channel, as a plist. It must return a string or nil.")
2579 (defvar org-export-filter-src-block-functions nil
2580 "List of functions applied to a transcoded src-block.
2581 Each filter is called with three arguments: the transcoded data,
2582 as a string, the back-end, as a symbol, and the communication
2583 channel, as a plist. It must return a string or nil.")
2585 (defvar org-export-filter-table-functions nil
2586 "List of functions applied to a transcoded table.
2587 Each filter is called with three arguments: the transcoded data,
2588 as a string, the back-end, as a symbol, and the communication
2589 channel, as a plist. It must return a string or nil.")
2591 (defvar org-export-filter-table-cell-functions nil
2592 "List of functions applied to a transcoded table-cell.
2593 Each filter is called with three arguments: the transcoded data,
2594 as a string, the back-end, as a symbol, and the communication
2595 channel, as a plist. It must return a string or nil.")
2597 (defvar org-export-filter-table-row-functions nil
2598 "List of functions applied to a transcoded table-row.
2599 Each filter is called with three arguments: the transcoded data,
2600 as a string, the back-end, as a symbol, and the communication
2601 channel, as a plist. It must return a string or nil.")
2603 (defvar org-export-filter-verse-block-functions nil
2604 "List of functions applied to a transcoded verse block.
2605 Each filter is called with three arguments: the transcoded data,
2606 as a string, the back-end, as a symbol, and the communication
2607 channel, as a plist. It must return a string or nil.")
2610 ;;;; Objects Filters
2612 (defvar org-export-filter-bold-functions nil
2613 "List of functions applied to transcoded bold text.
2614 Each filter is called with three arguments: the transcoded data,
2615 as a string, the back-end, as a symbol, and the communication
2616 channel, as a plist. It must return a string or nil.")
2618 (defvar org-export-filter-code-functions nil
2619 "List of functions applied to transcoded code text.
2620 Each filter is called with three arguments: the transcoded data,
2621 as a string, the back-end, as a symbol, and the communication
2622 channel, as a plist. It must return a string or nil.")
2624 (defvar org-export-filter-entity-functions nil
2625 "List of functions applied to a transcoded entity.
2626 Each filter is called with three arguments: the transcoded data,
2627 as a string, the back-end, as a symbol, and the communication
2628 channel, as a plist. It must return a string or nil.")
2630 (defvar org-export-filter-export-snippet-functions nil
2631 "List of functions applied to a transcoded export-snippet.
2632 Each filter is called with three arguments: the transcoded data,
2633 as a string, the back-end, as a symbol, and the communication
2634 channel, as a plist. It must return a string or nil.")
2636 (defvar org-export-filter-footnote-reference-functions nil
2637 "List of functions applied to a transcoded footnote-reference.
2638 Each filter is called with three arguments: the transcoded data,
2639 as a string, the back-end, as a symbol, and the communication
2640 channel, as a plist. It must return a string or nil.")
2642 (defvar org-export-filter-inline-babel-call-functions nil
2643 "List of functions applied to a transcoded inline-babel-call.
2644 Each filter is called with three arguments: the transcoded data,
2645 as a string, the back-end, as a symbol, and the communication
2646 channel, as a plist. It must return a string or nil.")
2648 (defvar org-export-filter-inline-src-block-functions nil
2649 "List of functions applied to a transcoded inline-src-block.
2650 Each filter is called with three arguments: the transcoded data,
2651 as a string, the back-end, as a symbol, and the communication
2652 channel, as a plist. It must return a string or nil.")
2654 (defvar org-export-filter-italic-functions nil
2655 "List of functions applied to transcoded italic text.
2656 Each filter is called with three arguments: the transcoded data,
2657 as a string, the back-end, as a symbol, and the communication
2658 channel, as a plist. It must return a string or nil.")
2660 (defvar org-export-filter-latex-fragment-functions nil
2661 "List of functions applied to a transcoded latex-fragment.
2662 Each filter is called with three arguments: the transcoded data,
2663 as a string, the back-end, as a symbol, and the communication
2664 channel, as a plist. It must return a string or nil.")
2666 (defvar org-export-filter-line-break-functions nil
2667 "List of functions applied to a transcoded line-break.
2668 Each filter is called with three arguments: the transcoded data,
2669 as a string, the back-end, as a symbol, and the communication
2670 channel, as a plist. It must return a string or nil.")
2672 (defvar org-export-filter-link-functions nil
2673 "List of functions applied to a transcoded link.
2674 Each filter is called with three arguments: the transcoded data,
2675 as a string, the back-end, as a symbol, and the communication
2676 channel, as a plist. It must return a string or nil.")
2678 (defvar org-export-filter-radio-target-functions nil
2679 "List of functions applied to a transcoded radio-target.
2680 Each filter is called with three arguments: the transcoded data,
2681 as a string, the back-end, as a symbol, and the communication
2682 channel, as a plist. It must return a string or nil.")
2684 (defvar org-export-filter-statistics-cookie-functions nil
2685 "List of functions applied to a transcoded statistics-cookie.
2686 Each filter is called with three arguments: the transcoded data,
2687 as a string, the back-end, as a symbol, and the communication
2688 channel, as a plist. It must return a string or nil.")
2690 (defvar org-export-filter-strike-through-functions nil
2691 "List of functions applied to transcoded strike-through text.
2692 Each filter is called with three arguments: the transcoded data,
2693 as a string, the back-end, as a symbol, and the communication
2694 channel, as a plist. It must return a string or nil.")
2696 (defvar org-export-filter-subscript-functions nil
2697 "List of functions applied to a transcoded subscript.
2698 Each filter is called with three arguments: the transcoded data,
2699 as a string, the back-end, as a symbol, and the communication
2700 channel, as a plist. It must return a string or nil.")
2702 (defvar org-export-filter-superscript-functions nil
2703 "List of functions applied to a transcoded superscript.
2704 Each filter is called with three arguments: the transcoded data,
2705 as a string, the back-end, as a symbol, and the communication
2706 channel, as a plist. It must return a string or nil.")
2708 (defvar org-export-filter-target-functions nil
2709 "List of functions applied to a transcoded target.
2710 Each filter is called with three arguments: the transcoded data,
2711 as a string, the back-end, as a symbol, and the communication
2712 channel, as a plist. It must return a string or nil.")
2714 (defvar org-export-filter-timestamp-functions nil
2715 "List of functions applied to a transcoded timestamp.
2716 Each filter is called with three arguments: the transcoded data,
2717 as a string, the back-end, as a symbol, and the communication
2718 channel, as a plist. It must return a string or nil.")
2720 (defvar org-export-filter-underline-functions nil
2721 "List of functions applied to transcoded underline text.
2722 Each filter is called with three arguments: the transcoded data,
2723 as a string, the back-end, as a symbol, and the communication
2724 channel, as a plist. It must return a string or nil.")
2726 (defvar org-export-filter-verbatim-functions nil
2727 "List of functions applied to transcoded verbatim text.
2728 Each filter is called with three arguments: the transcoded data,
2729 as a string, the back-end, as a symbol, and the communication
2730 channel, as a plist. It must return a string or nil.")
2733 ;;;; Filters Tools
2735 ;; Internal function `org-export-install-filters' installs filters
2736 ;; hard-coded in back-ends (developer filters) and filters from global
2737 ;; variables (user filters) in the communication channel.
2739 ;; Internal function `org-export-filter-apply-functions' takes care
2740 ;; about applying each filter in order to a given data. It ignores
2741 ;; filters returning a nil value but stops whenever a filter returns
2742 ;; an empty string.
2744 (defun org-export-filter-apply-functions (filters value info)
2745 "Call every function in FILTERS.
2747 Functions are called with arguments VALUE, current export
2748 back-end's name and INFO. A function returning a nil value will
2749 be skipped. If it returns the empty string, the process ends and
2750 VALUE is ignored.
2752 Call is done in a LIFO fashion, to be sure that developer
2753 specified filters, if any, are called first."
2754 (catch 'exit
2755 (let ((backend-name (plist-get info :back-end)))
2756 (dolist (filter filters value)
2757 (let ((result (funcall filter value backend-name info)))
2758 (cond ((not result) value)
2759 ((equal value "") (throw 'exit nil))
2760 (t (setq value result))))))))
2762 (defun org-export-install-filters (info)
2763 "Install filters properties in communication channel.
2764 INFO is a plist containing the current communication channel.
2765 Return the updated communication channel."
2766 (let (plist)
2767 ;; Install user-defined filters with `org-export-filters-alist'
2768 ;; and filters already in INFO (through ext-plist mechanism).
2769 (mapc (lambda (p)
2770 (let* ((prop (car p))
2771 (info-value (plist-get info prop))
2772 (default-value (symbol-value (cdr p))))
2773 (setq plist
2774 (plist-put plist prop
2775 ;; Filters in INFO will be called
2776 ;; before those user provided.
2777 (append (if (listp info-value) info-value
2778 (list info-value))
2779 default-value)))))
2780 org-export-filters-alist)
2781 ;; Prepend back-end specific filters to that list.
2782 (mapc (lambda (p)
2783 ;; Single values get consed, lists are appended.
2784 (let ((key (car p)) (value (cdr p)))
2785 (when value
2786 (setq plist
2787 (plist-put
2788 plist key
2789 (if (atom value) (cons value (plist-get plist key))
2790 (append value (plist-get plist key))))))))
2791 (org-export-get-all-filters (plist-get info :back-end)))
2792 ;; Return new communication channel.
2793 (org-combine-plists info plist)))
2797 ;;; Core functions
2799 ;; This is the room for the main function, `org-export-as', along with
2800 ;; its derivatives, `org-export-to-buffer', `org-export-to-file' and
2801 ;; `org-export-string-as'. They differ either by the way they output
2802 ;; the resulting code (for the first two) or by the input type (for
2803 ;; the latter). `org-export--copy-to-kill-ring-p' determines if
2804 ;; output of these function should be added to kill ring.
2806 ;; `org-export-output-file-name' is an auxiliary function meant to be
2807 ;; used with `org-export-to-file'. With a given extension, it tries
2808 ;; to provide a canonical file name to write export output to.
2810 ;; Note that `org-export-as' doesn't really parse the current buffer,
2811 ;; but a copy of it (with the same buffer-local variables and
2812 ;; visibility), where macros and include keywords are expanded and
2813 ;; Babel blocks are executed, if appropriate.
2814 ;; `org-export-with-buffer-copy' macro prepares that copy.
2816 ;; File inclusion is taken care of by
2817 ;; `org-export-expand-include-keyword' and
2818 ;; `org-export--prepare-file-contents'. Structure wise, including
2819 ;; a whole Org file in a buffer often makes little sense. For
2820 ;; example, if the file contains a headline and the include keyword
2821 ;; was within an item, the item should contain the headline. That's
2822 ;; why file inclusion should be done before any structure can be
2823 ;; associated to the file, that is before parsing.
2825 ;; `org-export-insert-default-template' is a command to insert
2826 ;; a default template (or a back-end specific template) at point or in
2827 ;; current subtree.
2829 (defun org-export-copy-buffer ()
2830 "Return a copy of the current buffer.
2831 The copy preserves Org buffer-local variables, visibility and
2832 narrowing."
2833 (let ((copy-buffer-fun (org-export--generate-copy-script (current-buffer)))
2834 (new-buf (generate-new-buffer (buffer-name))))
2835 (with-current-buffer new-buf
2836 (funcall copy-buffer-fun)
2837 (set-buffer-modified-p nil))
2838 new-buf))
2840 (defmacro org-export-with-buffer-copy (&rest body)
2841 "Apply BODY in a copy of the current buffer.
2842 The copy preserves local variables, visibility and contents of
2843 the original buffer. Point is at the beginning of the buffer
2844 when BODY is applied."
2845 (declare (debug t))
2846 (org-with-gensyms (buf-copy)
2847 `(let ((,buf-copy (org-export-copy-buffer)))
2848 (unwind-protect
2849 (with-current-buffer ,buf-copy
2850 (goto-char (point-min))
2851 (progn ,@body))
2852 (and (buffer-live-p ,buf-copy)
2853 ;; Kill copy without confirmation.
2854 (progn (with-current-buffer ,buf-copy
2855 (restore-buffer-modified-p nil))
2856 (kill-buffer ,buf-copy)))))))
2858 (defun org-export--generate-copy-script (buffer)
2859 "Generate a function duplicating BUFFER.
2861 The copy will preserve local variables, visibility, contents and
2862 narrowing of the original buffer. If a region was active in
2863 BUFFER, contents will be narrowed to that region instead.
2865 The resulting function can be evaled at a later time, from
2866 another buffer, effectively cloning the original buffer there.
2868 The function assumes BUFFER's major mode is `org-mode'."
2869 (with-current-buffer buffer
2870 `(lambda ()
2871 (let ((inhibit-modification-hooks t))
2872 ;; Set major mode. Ignore `org-mode-hook' as it has been run
2873 ;; already in BUFFER.
2874 (let ((org-mode-hook nil) (org-inhibit-startup t)) (org-mode))
2875 ;; Copy specific buffer local variables and variables set
2876 ;; through BIND keywords.
2877 ,@(let ((bound-variables (org-export--list-bound-variables))
2878 vars)
2879 (dolist (entry (buffer-local-variables (buffer-base-buffer)) vars)
2880 (when (consp entry)
2881 (let ((var (car entry))
2882 (val (cdr entry)))
2883 (and (not (eq var 'org-font-lock-keywords))
2884 (or (memq var
2885 '(default-directory
2886 buffer-file-name
2887 buffer-file-coding-system))
2888 (assq var bound-variables)
2889 (string-match "^\\(org-\\|orgtbl-\\)"
2890 (symbol-name var)))
2891 ;; Skip unreadable values, as they cannot be
2892 ;; sent to external process.
2893 (or (not val) (ignore-errors (read (format "%S" val))))
2894 (push `(set (make-local-variable (quote ,var))
2895 (quote ,val))
2896 vars))))))
2897 ;; Whole buffer contents.
2898 (insert
2899 ,(org-with-wide-buffer
2900 (buffer-substring-no-properties
2901 (point-min) (point-max))))
2902 ;; Narrowing.
2903 ,(if (org-region-active-p)
2904 `(narrow-to-region ,(region-beginning) ,(region-end))
2905 `(narrow-to-region ,(point-min) ,(point-max)))
2906 ;; Current position of point.
2907 (goto-char ,(point))
2908 ;; Overlays with invisible property.
2909 ,@(let (ov-set)
2910 (mapc
2911 (lambda (ov)
2912 (let ((invis-prop (overlay-get ov 'invisible)))
2913 (when invis-prop
2914 (push `(overlay-put
2915 (make-overlay ,(overlay-start ov)
2916 ,(overlay-end ov))
2917 'invisible (quote ,invis-prop))
2918 ov-set))))
2919 (overlays-in (point-min) (point-max)))
2920 ov-set)))))
2922 ;;;###autoload
2923 (defun org-export-as
2924 (backend &optional subtreep visible-only body-only ext-plist)
2925 "Transcode current Org buffer into BACKEND code.
2927 BACKEND is either an export back-end, as returned by, e.g.,
2928 `org-export-create-backend', or a symbol referring to
2929 a registered back-end.
2931 If narrowing is active in the current buffer, only transcode its
2932 narrowed part.
2934 If a region is active, transcode that region.
2936 When optional argument SUBTREEP is non-nil, transcode the
2937 sub-tree at point, extracting information from the headline
2938 properties first.
2940 When optional argument VISIBLE-ONLY is non-nil, don't export
2941 contents of hidden elements.
2943 When optional argument BODY-ONLY is non-nil, only return body
2944 code, without surrounding template.
2946 Optional argument EXT-PLIST, when provided, is a property list
2947 with external parameters overriding Org default settings, but
2948 still inferior to file-local settings.
2950 Return code as a string."
2951 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
2952 (org-export-barf-if-invalid-backend backend)
2953 (save-excursion
2954 (save-restriction
2955 ;; Narrow buffer to an appropriate region or subtree for
2956 ;; parsing. If parsing subtree, be sure to remove main headline
2957 ;; too.
2958 (cond ((org-region-active-p)
2959 (narrow-to-region (region-beginning) (region-end)))
2960 (subtreep
2961 (org-narrow-to-subtree)
2962 (goto-char (point-min))
2963 (forward-line)
2964 (narrow-to-region (point) (point-max))))
2965 ;; Initialize communication channel with original buffer
2966 ;; attributes, unavailable in its copy.
2967 (let* ((info (org-combine-plists
2968 (list :export-options
2969 (delq nil
2970 (list (and subtreep 'subtree)
2971 (and visible-only 'visible-only)
2972 (and body-only 'body-only))))
2973 (org-export--get-buffer-attributes)))
2974 tree)
2975 ;; Store default title in `org-export--default-title' so that
2976 ;; `org-export-get-environment' can access it from buffer's
2977 ;; copy and then add it properly to communication channel.
2978 (org-export-store-default-title)
2979 ;; Update communication channel and get parse tree. Buffer
2980 ;; isn't parsed directly. Instead, a temporary copy is
2981 ;; created, where include keywords, macros are expanded and
2982 ;; code blocks are evaluated.
2983 (org-export-with-buffer-copy
2984 ;; Run first hook with current back-end's name as argument.
2985 (run-hook-with-args 'org-export-before-processing-hook
2986 (org-export-backend-name backend))
2987 (org-export-expand-include-keyword)
2988 ;; Update macro templates since #+INCLUDE keywords might have
2989 ;; added some new ones.
2990 (org-macro-initialize-templates)
2991 (org-macro-replace-all org-macro-templates)
2992 (org-export-execute-babel-code)
2993 ;; Update radio targets since keyword inclusion might have
2994 ;; added some more.
2995 (org-update-radio-target-regexp)
2996 ;; Run last hook with current back-end's name as argument.
2997 (goto-char (point-min))
2998 (save-excursion
2999 (run-hook-with-args 'org-export-before-parsing-hook
3000 (org-export-backend-name backend)))
3001 ;; Update communication channel with environment. Also
3002 ;; install user's and developer's filters.
3003 (setq info
3004 (org-export-install-filters
3005 (org-combine-plists
3006 info (org-export-get-environment backend subtreep ext-plist))))
3007 ;; Expand export-specific set of macros: {{{author}}},
3008 ;; {{{date}}}, {{{email}}} and {{{title}}}. It must be done
3009 ;; once regular macros have been expanded, since document
3010 ;; keywords may contain one of them.
3011 (org-macro-replace-all
3012 (list (cons "author"
3013 (org-element-interpret-data (plist-get info :author)))
3014 (cons "date"
3015 (org-element-interpret-data (plist-get info :date)))
3016 ;; EMAIL is not a parsed keyword: store it as-is.
3017 (cons "email" (or (plist-get info :email) ""))
3018 (cons "title"
3019 (org-element-interpret-data (plist-get info :title)))))
3020 ;; Call options filters and update export options. We do not
3021 ;; use `org-export-filter-apply-functions' here since the
3022 ;; arity of such filters is different.
3023 (let ((backend-name (org-export-backend-name backend)))
3024 (dolist (filter (plist-get info :filter-options))
3025 (let ((result (funcall filter info backend-name)))
3026 (when result (setq info result)))))
3027 ;; Parse buffer and call parse-tree filter on it.
3028 (setq tree
3029 (org-export-filter-apply-functions
3030 (plist-get info :filter-parse-tree)
3031 (org-element-parse-buffer nil visible-only) info))
3032 ;; Now tree is complete, compute its properties and add them
3033 ;; to communication channel.
3034 (setq info
3035 (org-combine-plists
3036 info (org-export-collect-tree-properties tree info)))
3037 ;; Eventually transcode TREE. Wrap the resulting string into
3038 ;; a template.
3039 (let* ((body (org-element-normalize-string
3040 (or (org-export-data tree info) "")))
3041 (inner-template (cdr (assq 'inner-template
3042 (plist-get info :translate-alist))))
3043 (full-body (if (not (functionp inner-template)) body
3044 (funcall inner-template body info)))
3045 (template (cdr (assq 'template
3046 (plist-get info :translate-alist)))))
3047 ;; Remove all text properties since they cannot be
3048 ;; retrieved from an external process. Finally call
3049 ;; final-output filter and return result.
3050 (org-no-properties
3051 (org-export-filter-apply-functions
3052 (plist-get info :filter-final-output)
3053 (if (or (not (functionp template)) body-only) full-body
3054 (funcall template full-body info))
3055 info))))))))
3057 ;;;###autoload
3058 (defun org-export-to-buffer
3059 (backend buffer &optional subtreep visible-only body-only ext-plist)
3060 "Call `org-export-as' with output to a specified buffer.
3062 BACKEND is either an export back-end, as returned by, e.g.,
3063 `org-export-create-backend', or a symbol referring to
3064 a registered back-end.
3066 BUFFER is the output buffer. If it already exists, it will be
3067 erased first, otherwise, it will be created.
3069 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
3070 EXT-PLIST are similar to those used in `org-export-as', which
3071 see.
3073 Depending on `org-export-copy-to-kill-ring', add buffer contents
3074 to kill ring. Return buffer."
3075 (let ((out (org-export-as backend subtreep visible-only body-only ext-plist))
3076 (buffer (get-buffer-create buffer)))
3077 (with-current-buffer buffer
3078 (erase-buffer)
3079 (insert out)
3080 (goto-char (point-min)))
3081 ;; Maybe add buffer contents to kill ring.
3082 (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p out))
3083 (org-kill-new out))
3084 ;; Return buffer.
3085 buffer))
3087 ;;;###autoload
3088 (defun org-export-to-file
3089 (backend file &optional subtreep visible-only body-only ext-plist)
3090 "Call `org-export-as' with output to a specified file.
3092 BACKEND is either an export back-end, as returned by, e.g.,
3093 `org-export-create-backend', or a symbol referring to
3094 a registered back-end. FILE is the name of the output file, as
3095 a string.
3097 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
3098 EXT-PLIST are similar to those used in `org-export-as', which
3099 see.
3101 Depending on `org-export-copy-to-kill-ring', add file contents
3102 to kill ring. Return output file's name."
3103 ;; Checks for FILE permissions. `write-file' would do the same, but
3104 ;; we'd rather avoid needless transcoding of parse tree.
3105 (unless (file-writable-p file) (error "Output file not writable"))
3106 ;; Insert contents to a temporary buffer and write it to FILE.
3107 (let ((out (org-export-as backend subtreep visible-only body-only ext-plist)))
3108 (with-temp-buffer
3109 (insert out)
3110 (let ((coding-system-for-write org-export-coding-system))
3111 (write-file file)))
3112 ;; Maybe add file contents to kill ring.
3113 (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p out))
3114 (org-kill-new out)))
3115 ;; Return full path.
3116 file)
3118 ;;;###autoload
3119 (defun org-export-string-as (string backend &optional body-only ext-plist)
3120 "Transcode STRING into BACKEND code.
3122 BACKEND is either an export back-end, as returned by, e.g.,
3123 `org-export-create-backend', or a symbol referring to
3124 a registered back-end.
3126 When optional argument BODY-ONLY is non-nil, only return body
3127 code, without preamble nor postamble.
3129 Optional argument EXT-PLIST, when provided, is a property list
3130 with external parameters overriding Org default settings, but
3131 still inferior to file-local settings.
3133 Return code as a string."
3134 (with-temp-buffer
3135 (insert string)
3136 (let ((org-inhibit-startup t)) (org-mode))
3137 (org-export-as backend nil nil body-only ext-plist)))
3139 ;;;###autoload
3140 (defun org-export-replace-region-by (backend)
3141 "Replace the active region by its export to BACKEND.
3142 BACKEND is either an export back-end, as returned by, e.g.,
3143 `org-export-create-backend', or a symbol referring to
3144 a registered back-end."
3145 (if (not (org-region-active-p))
3146 (user-error "No active region to replace")
3147 (let* ((beg (region-beginning))
3148 (end (region-end))
3149 (str (buffer-substring beg end)) rpl)
3150 (setq rpl (org-export-string-as str backend t))
3151 (delete-region beg end)
3152 (insert rpl))))
3154 ;;;###autoload
3155 (defun org-export-insert-default-template (&optional backend subtreep)
3156 "Insert all export keywords with default values at beginning of line.
3158 BACKEND is a symbol referring to the name of a registered export
3159 back-end, for which specific export options should be added to
3160 the template, or `default' for default template. When it is nil,
3161 the user will be prompted for a category.
3163 If SUBTREEP is non-nil, export configuration will be set up
3164 locally for the subtree through node properties."
3165 (interactive)
3166 (unless (derived-mode-p 'org-mode) (user-error "Not in an Org mode buffer"))
3167 (when (and subtreep (org-before-first-heading-p))
3168 (user-error "No subtree to set export options for"))
3169 (let ((node (and subtreep (save-excursion (org-back-to-heading t) (point))))
3170 (backend
3171 (or backend
3172 (intern
3173 (org-completing-read
3174 "Options category: "
3175 (cons "default"
3176 (mapcar (lambda (b)
3177 (symbol-name (org-export-backend-name b)))
3178 org-export--registered-backends))))))
3179 options keywords)
3180 ;; Populate OPTIONS and KEYWORDS.
3181 (dolist (entry (cond ((eq backend 'default) org-export-options-alist)
3182 ((org-export-backend-p backend)
3183 (org-export-get-all-options backend))
3184 (t (org-export-get-all-options
3185 (org-export-backend-name backend)))))
3186 (let ((keyword (nth 1 entry))
3187 (option (nth 2 entry)))
3188 (cond
3189 (keyword (unless (assoc keyword keywords)
3190 (let ((value
3191 (if (eq (nth 4 entry) 'split)
3192 (mapconcat 'identity (eval (nth 3 entry)) " ")
3193 (eval (nth 3 entry)))))
3194 (push (cons keyword value) keywords))))
3195 (option (unless (assoc option options)
3196 (push (cons option (eval (nth 3 entry))) options))))))
3197 ;; Move to an appropriate location in order to insert options.
3198 (unless subtreep (beginning-of-line))
3199 ;; First get TITLE, DATE, AUTHOR and EMAIL if they belong to the
3200 ;; list of available keywords.
3201 (when (assoc "TITLE" keywords)
3202 (let ((title
3203 (or (let ((visited-file (buffer-file-name (buffer-base-buffer))))
3204 (and visited-file
3205 (file-name-sans-extension
3206 (file-name-nondirectory visited-file))))
3207 (buffer-name (buffer-base-buffer)))))
3208 (if (not subtreep) (insert (format "#+TITLE: %s\n" title))
3209 (org-entry-put node "EXPORT_TITLE" title))))
3210 (when (assoc "DATE" keywords)
3211 (let ((date (with-temp-buffer (org-insert-time-stamp (current-time)))))
3212 (if (not subtreep) (insert "#+DATE: " date "\n")
3213 (org-entry-put node "EXPORT_DATE" date))))
3214 (when (assoc "AUTHOR" keywords)
3215 (let ((author (cdr (assoc "AUTHOR" keywords))))
3216 (if subtreep (org-entry-put node "EXPORT_AUTHOR" author)
3217 (insert
3218 (format "#+AUTHOR:%s\n"
3219 (if (not (org-string-nw-p author)) ""
3220 (concat " " author)))))))
3221 (when (assoc "EMAIL" keywords)
3222 (let ((email (cdr (assoc "EMAIL" keywords))))
3223 (if subtreep (org-entry-put node "EXPORT_EMAIL" email)
3224 (insert
3225 (format "#+EMAIL:%s\n"
3226 (if (not (org-string-nw-p email)) ""
3227 (concat " " email)))))))
3228 ;; Then (multiple) OPTIONS lines. Never go past fill-column.
3229 (when options
3230 (let ((items
3231 (mapcar
3232 (lambda (opt)
3233 (format "%s:%s" (car opt) (format "%s" (cdr opt))))
3234 (sort options (lambda (k1 k2) (string< (car k1) (car k2)))))))
3235 (if subtreep
3236 (org-entry-put
3237 node "EXPORT_OPTIONS" (mapconcat 'identity items " "))
3238 (while items
3239 (insert "#+OPTIONS:")
3240 (let ((width 10))
3241 (while (and items
3242 (< (+ width (length (car items)) 1) fill-column))
3243 (let ((item (pop items)))
3244 (insert " " item)
3245 (incf width (1+ (length item))))))
3246 (insert "\n")))))
3247 ;; And the rest of keywords.
3248 (dolist (key (sort keywords (lambda (k1 k2) (string< (car k1) (car k2)))))
3249 (unless (member (car key) '("TITLE" "DATE" "AUTHOR" "EMAIL"))
3250 (let ((val (cdr key)))
3251 (if subtreep (org-entry-put node (concat "EXPORT_" (car key)) val)
3252 (insert
3253 (format "#+%s:%s\n"
3254 (car key)
3255 (if (org-string-nw-p val) (format " %s" val) "")))))))))
3257 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
3258 "Return output file's name according to buffer specifications.
3260 EXTENSION is a string representing the output file extension,
3261 with the leading dot.
3263 With a non-nil optional argument SUBTREEP, try to determine
3264 output file's name by looking for \"EXPORT_FILE_NAME\" property
3265 of subtree at point.
3267 When optional argument PUB-DIR is set, use it as the publishing
3268 directory.
3270 When optional argument VISIBLE-ONLY is non-nil, don't export
3271 contents of hidden elements.
3273 Return file name as a string."
3274 (let* ((visited-file (buffer-file-name (buffer-base-buffer)))
3275 (base-name
3276 ;; File name may come from EXPORT_FILE_NAME subtree
3277 ;; property, assuming point is at beginning of said
3278 ;; sub-tree.
3279 (file-name-sans-extension
3280 (or (and subtreep
3281 (org-entry-get
3282 (save-excursion
3283 (ignore-errors (org-back-to-heading) (point)))
3284 "EXPORT_FILE_NAME" t))
3285 ;; File name may be extracted from buffer's associated
3286 ;; file, if any.
3287 (and visited-file (file-name-nondirectory visited-file))
3288 ;; Can't determine file name on our own: Ask user.
3289 (let ((read-file-name-function
3290 (and org-completion-use-ido 'ido-read-file-name)))
3291 (read-file-name
3292 "Output file: " pub-dir nil nil nil
3293 (lambda (name)
3294 (string= (file-name-extension name t) extension)))))))
3295 (output-file
3296 ;; Build file name. Enforce EXTENSION over whatever user
3297 ;; may have come up with. PUB-DIR, if defined, always has
3298 ;; precedence over any provided path.
3299 (cond
3300 (pub-dir
3301 (concat (file-name-as-directory pub-dir)
3302 (file-name-nondirectory base-name)
3303 extension))
3304 ((file-name-absolute-p base-name) (concat base-name extension))
3305 (t (concat (file-name-as-directory ".") base-name extension)))))
3306 ;; If writing to OUTPUT-FILE would overwrite original file, append
3307 ;; EXTENSION another time to final name.
3308 (if (and visited-file (org-file-equal-p visited-file output-file))
3309 (concat output-file extension)
3310 output-file)))
3312 (defun org-export-expand-include-keyword (&optional included dir)
3313 "Expand every include keyword in buffer.
3314 Optional argument INCLUDED is a list of included file names along
3315 with their line restriction, when appropriate. It is used to
3316 avoid infinite recursion. Optional argument DIR is the current
3317 working directory. It is used to properly resolve relative
3318 paths."
3319 (let ((case-fold-search t))
3320 (goto-char (point-min))
3321 (while (re-search-forward "^[ \t]*#\\+INCLUDE:" nil t)
3322 (let ((element (save-match-data (org-element-at-point))))
3323 (when (eq (org-element-type element) 'keyword)
3324 (beginning-of-line)
3325 ;; Extract arguments from keyword's value.
3326 (let* ((value (org-element-property :value element))
3327 (ind (org-get-indentation))
3328 (file (and (string-match
3329 "^\\(\".+?\"\\|\\S-+\\)\\(?:\\s-+\\|$\\)" value)
3330 (prog1 (expand-file-name
3331 (org-remove-double-quotes
3332 (match-string 1 value))
3333 dir)
3334 (setq value (replace-match "" nil nil value)))))
3335 (lines
3336 (and (string-match
3337 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\""
3338 value)
3339 (prog1 (match-string 1 value)
3340 (setq value (replace-match "" nil nil value)))))
3341 (env (cond ((string-match "\\<example\\>" value) 'example)
3342 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
3343 (match-string 1 value))))
3344 ;; Minimal level of included file defaults to the child
3345 ;; level of the current headline, if any, or one. It
3346 ;; only applies is the file is meant to be included as
3347 ;; an Org one.
3348 (minlevel
3349 (and (not env)
3350 (if (string-match ":minlevel +\\([0-9]+\\)" value)
3351 (prog1 (string-to-number (match-string 1 value))
3352 (setq value (replace-match "" nil nil value)))
3353 (let ((cur (org-current-level)))
3354 (if cur (1+ (org-reduced-level cur)) 1))))))
3355 ;; Remove keyword.
3356 (delete-region (point) (progn (forward-line) (point)))
3357 (cond
3358 ((not file) nil)
3359 ((not (file-readable-p file))
3360 (error "Cannot include file %s" file))
3361 ;; Check if files has already been parsed. Look after
3362 ;; inclusion lines too, as different parts of the same file
3363 ;; can be included too.
3364 ((member (list file lines) included)
3365 (error "Recursive file inclusion: %s" file))
3367 (cond
3368 ((eq env 'example)
3369 (insert
3370 (let ((ind-str (make-string ind ? ))
3371 (contents
3372 (org-escape-code-in-string
3373 (org-export--prepare-file-contents file lines))))
3374 (format "%s#+BEGIN_EXAMPLE\n%s%s#+END_EXAMPLE\n"
3375 ind-str contents ind-str))))
3376 ((stringp env)
3377 (insert
3378 (let ((ind-str (make-string ind ? ))
3379 (contents
3380 (org-escape-code-in-string
3381 (org-export--prepare-file-contents file lines))))
3382 (format "%s#+BEGIN_SRC %s\n%s%s#+END_SRC\n"
3383 ind-str env contents ind-str))))
3385 (insert
3386 (with-temp-buffer
3387 (let ((org-inhibit-startup t)) (org-mode))
3388 (insert
3389 (org-export--prepare-file-contents file lines ind minlevel))
3390 (org-export-expand-include-keyword
3391 (cons (list file lines) included)
3392 (file-name-directory file))
3393 (buffer-string)))))))))))))
3395 (defun org-export--prepare-file-contents (file &optional lines ind minlevel)
3396 "Prepare the contents of FILE for inclusion and return them as a string.
3398 When optional argument LINES is a string specifying a range of
3399 lines, include only those lines.
3401 Optional argument IND, when non-nil, is an integer specifying the
3402 global indentation of returned contents. Since its purpose is to
3403 allow an included file to stay in the same environment it was
3404 created \(i.e. a list item), it doesn't apply past the first
3405 headline encountered.
3407 Optional argument MINLEVEL, when non-nil, is an integer
3408 specifying the level that any top-level headline in the included
3409 file should have."
3410 (with-temp-buffer
3411 (insert-file-contents file)
3412 (when lines
3413 (let* ((lines (split-string lines "-"))
3414 (lbeg (string-to-number (car lines)))
3415 (lend (string-to-number (cadr lines)))
3416 (beg (if (zerop lbeg) (point-min)
3417 (goto-char (point-min))
3418 (forward-line (1- lbeg))
3419 (point)))
3420 (end (if (zerop lend) (point-max)
3421 (goto-char (point-min))
3422 (forward-line (1- lend))
3423 (point))))
3424 (narrow-to-region beg end)))
3425 ;; Remove blank lines at beginning and end of contents. The logic
3426 ;; behind that removal is that blank lines around include keyword
3427 ;; override blank lines in included file.
3428 (goto-char (point-min))
3429 (org-skip-whitespace)
3430 (beginning-of-line)
3431 (delete-region (point-min) (point))
3432 (goto-char (point-max))
3433 (skip-chars-backward " \r\t\n")
3434 (forward-line)
3435 (delete-region (point) (point-max))
3436 ;; If IND is set, preserve indentation of include keyword until
3437 ;; the first headline encountered.
3438 (when ind
3439 (unless (eq major-mode 'org-mode)
3440 (let ((org-inhibit-startup t)) (org-mode)))
3441 (goto-char (point-min))
3442 (let ((ind-str (make-string ind ? )))
3443 (while (not (or (eobp) (looking-at org-outline-regexp-bol)))
3444 ;; Do not move footnote definitions out of column 0.
3445 (unless (and (looking-at org-footnote-definition-re)
3446 (eq (org-element-type (org-element-at-point))
3447 'footnote-definition))
3448 (insert ind-str))
3449 (forward-line))))
3450 ;; When MINLEVEL is specified, compute minimal level for headlines
3451 ;; in the file (CUR-MIN), and remove stars to each headline so
3452 ;; that headlines with minimal level have a level of MINLEVEL.
3453 (when minlevel
3454 (unless (eq major-mode 'org-mode)
3455 (let ((org-inhibit-startup t)) (org-mode)))
3456 (org-with-limited-levels
3457 (let ((levels (org-map-entries
3458 (lambda () (org-reduced-level (org-current-level))))))
3459 (when levels
3460 (let ((offset (- minlevel (apply 'min levels))))
3461 (unless (zerop offset)
3462 (when org-odd-levels-only (setq offset (* offset 2)))
3463 ;; Only change stars, don't bother moving whole
3464 ;; sections.
3465 (org-map-entries
3466 (lambda () (if (< offset 0) (delete-char (abs offset))
3467 (insert (make-string offset ?*)))))))))))
3468 (org-element-normalize-string (buffer-string))))
3470 (defun org-export-execute-babel-code ()
3471 "Execute every Babel code in the visible part of current buffer."
3472 ;; Get a pristine copy of current buffer so Babel references can be
3473 ;; properly resolved.
3474 (let ((reference (org-export-copy-buffer)))
3475 (unwind-protect (let ((org-current-export-file reference))
3476 (org-babel-exp-process-buffer))
3477 (kill-buffer reference))))
3479 (defun org-export--copy-to-kill-ring-p ()
3480 "Return a non-nil value when output should be added to the kill ring.
3481 See also `org-export-copy-to-kill-ring'."
3482 (if (eq org-export-copy-to-kill-ring 'if-interactive)
3483 (not (or executing-kbd-macro noninteractive))
3484 (eq org-export-copy-to-kill-ring t)))
3488 ;;; Tools For Back-Ends
3490 ;; A whole set of tools is available to help build new exporters. Any
3491 ;; function general enough to have its use across many back-ends
3492 ;; should be added here.
3494 ;;;; For Affiliated Keywords
3496 ;; `org-export-read-attribute' reads a property from a given element
3497 ;; as a plist. It can be used to normalize affiliated keywords'
3498 ;; syntax.
3500 ;; Since captions can span over multiple lines and accept dual values,
3501 ;; their internal representation is a bit tricky. Therefore,
3502 ;; `org-export-get-caption' transparently returns a given element's
3503 ;; caption as a secondary string.
3505 (defun org-export-read-attribute (attribute element &optional property)
3506 "Turn ATTRIBUTE property from ELEMENT into a plist.
3508 When optional argument PROPERTY is non-nil, return the value of
3509 that property within attributes.
3511 This function assumes attributes are defined as \":keyword
3512 value\" pairs. It is appropriate for `:attr_html' like
3513 properties.
3515 All values will become strings except the empty string and
3516 \"nil\", which will become nil. Also, values containing only
3517 double quotes will be read as-is, which means that \"\" value
3518 will become the empty string."
3519 (let* ((prepare-value
3520 (lambda (str)
3521 (save-match-data
3522 (cond ((member str '(nil "" "nil")) nil)
3523 ((string-match "^\"\\(\"+\\)?\"$" str)
3524 (or (match-string 1 str) ""))
3525 (t str)))))
3526 (attributes
3527 (let ((value (org-element-property attribute element)))
3528 (when value
3529 (let ((s (mapconcat 'identity value " ")) result)
3530 (while (string-match
3531 "\\(?:^\\|[ \t]+\\)\\(:[-a-zA-Z0-9_]+\\)\\([ \t]+\\|$\\)"
3533 (let ((value (substring s 0 (match-beginning 0))))
3534 (push (funcall prepare-value value) result))
3535 (push (intern (match-string 1 s)) result)
3536 (setq s (substring s (match-end 0))))
3537 ;; Ignore any string before first property with `cdr'.
3538 (cdr (nreverse (cons (funcall prepare-value s) result))))))))
3539 (if property (plist-get attributes property) attributes)))
3541 (defun org-export-get-caption (element &optional shortp)
3542 "Return caption from ELEMENT as a secondary string.
3544 When optional argument SHORTP is non-nil, return short caption,
3545 as a secondary string, instead.
3547 Caption lines are separated by a white space."
3548 (let ((full-caption (org-element-property :caption element)) caption)
3549 (dolist (line full-caption (cdr caption))
3550 (let ((cap (funcall (if shortp 'cdr 'car) line)))
3551 (when cap
3552 (setq caption (nconc (list " ") (copy-sequence cap) caption)))))))
3555 ;;;; For Derived Back-ends
3557 ;; `org-export-with-backend' is a function allowing to locally use
3558 ;; another back-end to transcode some object or element. In a derived
3559 ;; back-end, it may be used as a fall-back function once all specific
3560 ;; cases have been treated.
3562 (defun org-export-with-backend (backend data &optional contents info)
3563 "Call a transcoder from BACKEND on DATA.
3564 BACKEND is an export back-end, as returned by, e.g.,
3565 `org-export-create-backend', or a symbol referring to
3566 a registered back-end. DATA is an Org element, object, secondary
3567 string or string. CONTENTS, when non-nil, is the transcoded
3568 contents of DATA element, as a string. INFO, when non-nil, is
3569 the communication channel used for export, as a plist."
3570 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
3571 (org-export-barf-if-invalid-backend backend)
3572 (let ((type (org-element-type data)))
3573 (if (memq type '(nil org-data)) (error "No foreign transcoder available")
3574 (let ((transcoder
3575 (cdr (assq type (org-export-get-all-transcoders backend)))))
3576 (if (functionp transcoder) (funcall transcoder data contents info)
3577 (error "No foreign transcoder available"))))))
3580 ;;;; For Export Snippets
3582 ;; Every export snippet is transmitted to the back-end. Though, the
3583 ;; latter will only retain one type of export-snippet, ignoring
3584 ;; others, based on the former's target back-end. The function
3585 ;; `org-export-snippet-backend' returns that back-end for a given
3586 ;; export-snippet.
3588 (defun org-export-snippet-backend (export-snippet)
3589 "Return EXPORT-SNIPPET targeted back-end as a symbol.
3590 Translation, with `org-export-snippet-translation-alist', is
3591 applied."
3592 (let ((back-end (org-element-property :back-end export-snippet)))
3593 (intern
3594 (or (cdr (assoc back-end org-export-snippet-translation-alist))
3595 back-end))))
3598 ;;;; For Footnotes
3600 ;; `org-export-collect-footnote-definitions' is a tool to list
3601 ;; actually used footnotes definitions in the whole parse tree, or in
3602 ;; a headline, in order to add footnote listings throughout the
3603 ;; transcoded data.
3605 ;; `org-export-footnote-first-reference-p' is a predicate used by some
3606 ;; back-ends, when they need to attach the footnote definition only to
3607 ;; the first occurrence of the corresponding label.
3609 ;; `org-export-get-footnote-definition' and
3610 ;; `org-export-get-footnote-number' provide easier access to
3611 ;; additional information relative to a footnote reference.
3613 (defun org-export-collect-footnote-definitions (data info)
3614 "Return an alist between footnote numbers, labels and definitions.
3616 DATA is the parse tree from which definitions are collected.
3617 INFO is the plist used as a communication channel.
3619 Definitions are sorted by order of references. They either
3620 appear as Org data or as a secondary string for inlined
3621 footnotes. Unreferenced definitions are ignored."
3622 (let* (num-alist
3623 collect-fn ; for byte-compiler.
3624 (collect-fn
3625 (function
3626 (lambda (data)
3627 ;; Collect footnote number, label and definition in DATA.
3628 (org-element-map data 'footnote-reference
3629 (lambda (fn)
3630 (when (org-export-footnote-first-reference-p fn info)
3631 (let ((def (org-export-get-footnote-definition fn info)))
3632 (push
3633 (list (org-export-get-footnote-number fn info)
3634 (org-element-property :label fn)
3635 def)
3636 num-alist)
3637 ;; Also search in definition for nested footnotes.
3638 (when (eq (org-element-property :type fn) 'standard)
3639 (funcall collect-fn def)))))
3640 ;; Don't enter footnote definitions since it will happen
3641 ;; when their first reference is found.
3642 info nil 'footnote-definition)))))
3643 (funcall collect-fn (plist-get info :parse-tree))
3644 (reverse num-alist)))
3646 (defun org-export-footnote-first-reference-p (footnote-reference info)
3647 "Non-nil when a footnote reference is the first one for its label.
3649 FOOTNOTE-REFERENCE is the footnote reference being considered.
3650 INFO is the plist used as a communication channel."
3651 (let ((label (org-element-property :label footnote-reference)))
3652 ;; Anonymous footnotes are always a first reference.
3653 (if (not label) t
3654 ;; Otherwise, return the first footnote with the same LABEL and
3655 ;; test if it is equal to FOOTNOTE-REFERENCE.
3656 (let* (search-refs ; for byte-compiler.
3657 (search-refs
3658 (function
3659 (lambda (data)
3660 (org-element-map data 'footnote-reference
3661 (lambda (fn)
3662 (cond
3663 ((string= (org-element-property :label fn) label)
3664 (throw 'exit fn))
3665 ;; If FN isn't inlined, be sure to traverse its
3666 ;; definition before resuming search. See
3667 ;; comments in `org-export-get-footnote-number'
3668 ;; for more information.
3669 ((eq (org-element-property :type fn) 'standard)
3670 (funcall search-refs
3671 (org-export-get-footnote-definition fn info)))))
3672 ;; Don't enter footnote definitions since it will
3673 ;; happen when their first reference is found.
3674 info 'first-match 'footnote-definition)))))
3675 (eq (catch 'exit (funcall search-refs (plist-get info :parse-tree)))
3676 footnote-reference)))))
3678 (defun org-export-get-footnote-definition (footnote-reference info)
3679 "Return definition of FOOTNOTE-REFERENCE as parsed data.
3680 INFO is the plist used as a communication channel. If no such
3681 definition can be found, return the \"DEFINITION NOT FOUND\"
3682 string."
3683 (let ((label (org-element-property :label footnote-reference)))
3684 (or (org-element-property :inline-definition footnote-reference)
3685 (cdr (assoc label (plist-get info :footnote-definition-alist)))
3686 "DEFINITION NOT FOUND.")))
3688 (defun org-export-get-footnote-number (footnote info)
3689 "Return number associated to a footnote.
3691 FOOTNOTE is either a footnote reference or a footnote definition.
3692 INFO is the plist used as a communication channel."
3693 (let* ((label (org-element-property :label footnote))
3694 seen-refs
3695 search-ref ; For byte-compiler.
3696 (search-ref
3697 (function
3698 (lambda (data)
3699 ;; Search footnote references through DATA, filling
3700 ;; SEEN-REFS along the way.
3701 (org-element-map data 'footnote-reference
3702 (lambda (fn)
3703 (let ((fn-lbl (org-element-property :label fn)))
3704 (cond
3705 ;; Anonymous footnote match: return number.
3706 ((and (not fn-lbl) (eq fn footnote))
3707 (throw 'exit (1+ (length seen-refs))))
3708 ;; Labels match: return number.
3709 ((and label (string= label fn-lbl))
3710 (throw 'exit (1+ (length seen-refs))))
3711 ;; Anonymous footnote: it's always a new one.
3712 ;; Also, be sure to return nil from the `cond' so
3713 ;; `first-match' doesn't get us out of the loop.
3714 ((not fn-lbl) (push 'inline seen-refs) nil)
3715 ;; Label not seen so far: add it so SEEN-REFS.
3717 ;; Also search for subsequent references in
3718 ;; footnote definition so numbering follows
3719 ;; reading logic. Note that we don't have to care
3720 ;; about inline definitions, since
3721 ;; `org-element-map' already traverses them at the
3722 ;; right time.
3724 ;; Once again, return nil to stay in the loop.
3725 ((not (member fn-lbl seen-refs))
3726 (push fn-lbl seen-refs)
3727 (funcall search-ref
3728 (org-export-get-footnote-definition fn info))
3729 nil))))
3730 ;; Don't enter footnote definitions since it will
3731 ;; happen when their first reference is found.
3732 info 'first-match 'footnote-definition)))))
3733 (catch 'exit (funcall search-ref (plist-get info :parse-tree)))))
3736 ;;;; For Headlines
3738 ;; `org-export-get-relative-level' is a shortcut to get headline
3739 ;; level, relatively to the lower headline level in the parsed tree.
3741 ;; `org-export-get-headline-number' returns the section number of an
3742 ;; headline, while `org-export-number-to-roman' allows to convert it
3743 ;; to roman numbers.
3745 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
3746 ;; `org-export-last-sibling-p' are three useful predicates when it
3747 ;; comes to fulfill the `:headline-levels' property.
3749 ;; `org-export-get-tags', `org-export-get-category' and
3750 ;; `org-export-get-node-property' extract useful information from an
3751 ;; headline or a parent headline. They all handle inheritance.
3753 ;; `org-export-get-alt-title' tries to retrieve an alternative title,
3754 ;; as a secondary string, suitable for table of contents. It falls
3755 ;; back onto default title.
3757 (defun org-export-get-relative-level (headline info)
3758 "Return HEADLINE relative level within current parsed tree.
3759 INFO is a plist holding contextual information."
3760 (+ (org-element-property :level headline)
3761 (or (plist-get info :headline-offset) 0)))
3763 (defun org-export-low-level-p (headline info)
3764 "Non-nil when HEADLINE is considered as low level.
3766 INFO is a plist used as a communication channel.
3768 A low level headlines has a relative level greater than
3769 `:headline-levels' property value.
3771 Return value is the difference between HEADLINE relative level
3772 and the last level being considered as high enough, or nil."
3773 (let ((limit (plist-get info :headline-levels)))
3774 (when (wholenump limit)
3775 (let ((level (org-export-get-relative-level headline info)))
3776 (and (> level limit) (- level limit))))))
3778 (defun org-export-get-headline-number (headline info)
3779 "Return HEADLINE numbering as a list of numbers.
3780 INFO is a plist holding contextual information."
3781 (cdr (assoc headline (plist-get info :headline-numbering))))
3783 (defun org-export-numbered-headline-p (headline info)
3784 "Return a non-nil value if HEADLINE element should be numbered.
3785 INFO is a plist used as a communication channel."
3786 (let ((sec-num (plist-get info :section-numbers))
3787 (level (org-export-get-relative-level headline info)))
3788 (if (wholenump sec-num) (<= level sec-num) sec-num)))
3790 (defun org-export-number-to-roman (n)
3791 "Convert integer N into a roman numeral."
3792 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
3793 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
3794 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
3795 ( 1 . "I")))
3796 (res ""))
3797 (if (<= n 0)
3798 (number-to-string n)
3799 (while roman
3800 (if (>= n (caar roman))
3801 (setq n (- n (caar roman))
3802 res (concat res (cdar roman)))
3803 (pop roman)))
3804 res)))
3806 (defun org-export-get-tags (element info &optional tags inherited)
3807 "Return list of tags associated to ELEMENT.
3809 ELEMENT has either an `headline' or an `inlinetask' type. INFO
3810 is a plist used as a communication channel.
3812 Select tags (see `org-export-select-tags') and exclude tags (see
3813 `org-export-exclude-tags') are removed from the list.
3815 When non-nil, optional argument TAGS should be a list of strings.
3816 Any tag belonging to this list will also be removed.
3818 When optional argument INHERITED is non-nil, tags can also be
3819 inherited from parent headlines and FILETAGS keywords."
3820 (org-remove-if
3821 (lambda (tag) (or (member tag (plist-get info :select-tags))
3822 (member tag (plist-get info :exclude-tags))
3823 (member tag tags)))
3824 (if (not inherited) (org-element-property :tags element)
3825 ;; Build complete list of inherited tags.
3826 (let ((current-tag-list (org-element-property :tags element)))
3827 (mapc
3828 (lambda (parent)
3829 (mapc
3830 (lambda (tag)
3831 (when (and (memq (org-element-type parent) '(headline inlinetask))
3832 (not (member tag current-tag-list)))
3833 (push tag current-tag-list)))
3834 (org-element-property :tags parent)))
3835 (org-export-get-genealogy element))
3836 ;; Add FILETAGS keywords and return results.
3837 (org-uniquify (append (plist-get info :filetags) current-tag-list))))))
3839 (defun org-export-get-node-property (property blob &optional inherited)
3840 "Return node PROPERTY value for BLOB.
3842 PROPERTY is an upcase symbol (i.e. `:COOKIE_DATA'). BLOB is an
3843 element or object.
3845 If optional argument INHERITED is non-nil, the value can be
3846 inherited from a parent headline.
3848 Return value is a string or nil."
3849 (let ((headline (if (eq (org-element-type blob) 'headline) blob
3850 (org-export-get-parent-headline blob))))
3851 (if (not inherited) (org-element-property property blob)
3852 (let ((parent headline) value)
3853 (catch 'found
3854 (while parent
3855 (when (plist-member (nth 1 parent) property)
3856 (throw 'found (org-element-property property parent)))
3857 (setq parent (org-element-property :parent parent))))))))
3859 (defun org-export-get-category (blob info)
3860 "Return category for element or object BLOB.
3862 INFO is a plist used as a communication channel.
3864 CATEGORY is automatically inherited from a parent headline, from
3865 #+CATEGORY: keyword or created out of original file name. If all
3866 fail, the fall-back value is \"???\"."
3867 (or (let ((headline (if (eq (org-element-type blob) 'headline) blob
3868 (org-export-get-parent-headline blob))))
3869 ;; Almost like `org-export-node-property', but we cannot trust
3870 ;; `plist-member' as every headline has a `:CATEGORY'
3871 ;; property, would it be nil or equal to "???" (which has the
3872 ;; same meaning).
3873 (let ((parent headline) value)
3874 (catch 'found
3875 (while parent
3876 (let ((category (org-element-property :CATEGORY parent)))
3877 (and category (not (equal "???" category))
3878 (throw 'found category)))
3879 (setq parent (org-element-property :parent parent))))))
3880 (org-element-map (plist-get info :parse-tree) 'keyword
3881 (lambda (kwd)
3882 (when (equal (org-element-property :key kwd) "CATEGORY")
3883 (org-element-property :value kwd)))
3884 info 'first-match)
3885 (let ((file (plist-get info :input-file)))
3886 (and file (file-name-sans-extension (file-name-nondirectory file))))
3887 "???"))
3889 (defun org-export-get-alt-title (headline info)
3890 "Return alternative title for HEADLINE, as a secondary string.
3891 INFO is a plist used as a communication channel. If no optional
3892 title is defined, fall-back to the regular title."
3893 (or (org-element-property :alt-title headline)
3894 (org-element-property :title headline)))
3896 (defun org-export-first-sibling-p (headline info)
3897 "Non-nil when HEADLINE is the first sibling in its sub-tree.
3898 INFO is a plist used as a communication channel."
3899 (not (eq (org-element-type (org-export-get-previous-element headline info))
3900 'headline)))
3902 (defun org-export-last-sibling-p (headline info)
3903 "Non-nil when HEADLINE is the last sibling in its sub-tree.
3904 INFO is a plist used as a communication channel."
3905 (not (org-export-get-next-element headline info)))
3908 ;;;; For Keywords
3910 ;; `org-export-get-date' returns a date appropriate for the document
3911 ;; to about to be exported. In particular, it takes care of
3912 ;; `org-export-date-timestamp-format'.
3914 (defun org-export-get-date (info &optional fmt)
3915 "Return date value for the current document.
3917 INFO is a plist used as a communication channel. FMT, when
3918 non-nil, is a time format string that will be applied on the date
3919 if it consists in a single timestamp object. It defaults to
3920 `org-export-date-timestamp-format' when nil.
3922 A proper date can be a secondary string, a string or nil. It is
3923 meant to be translated with `org-export-data' or alike."
3924 (let ((date (plist-get info :date))
3925 (fmt (or fmt org-export-date-timestamp-format)))
3926 (cond ((not date) nil)
3927 ((and fmt
3928 (not (cdr date))
3929 (eq (org-element-type (car date)) 'timestamp))
3930 (org-timestamp-format (car date) fmt))
3931 (t date))))
3934 ;;;; For Links
3936 ;; `org-export-solidify-link-text' turns a string into a safer version
3937 ;; for links, replacing most non-standard characters with hyphens.
3939 ;; `org-export-get-coderef-format' returns an appropriate format
3940 ;; string for coderefs.
3942 ;; `org-export-inline-image-p' returns a non-nil value when the link
3943 ;; provided should be considered as an inline image.
3945 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
3946 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
3947 ;; returns an appropriate unique identifier when found, or nil.
3949 ;; `org-export-resolve-id-link' returns the first headline with
3950 ;; specified id or custom-id in parse tree, the path to the external
3951 ;; file with the id or nil when neither was found.
3953 ;; `org-export-resolve-coderef' associates a reference to a line
3954 ;; number in the element it belongs, or returns the reference itself
3955 ;; when the element isn't numbered.
3957 (defun org-export-solidify-link-text (s)
3958 "Take link text S and make a safe target out of it."
3959 (save-match-data
3960 (mapconcat 'identity (org-split-string s "[^a-zA-Z0-9_.-:]+") "-")))
3962 (defun org-export-get-coderef-format (path desc)
3963 "Return format string for code reference link.
3964 PATH is the link path. DESC is its description."
3965 (save-match-data
3966 (cond ((not desc) "%s")
3967 ((string-match (regexp-quote (concat "(" path ")")) desc)
3968 (replace-match "%s" t t desc))
3969 (t desc))))
3971 (defun org-export-inline-image-p (link &optional rules)
3972 "Non-nil if LINK object points to an inline image.
3974 Optional argument is a set of RULES defining inline images. It
3975 is an alist where associations have the following shape:
3977 \(TYPE . REGEXP)
3979 Applying a rule means apply REGEXP against LINK's path when its
3980 type is TYPE. The function will return a non-nil value if any of
3981 the provided rules is non-nil. The default rule is
3982 `org-export-default-inline-image-rule'.
3984 This only applies to links without a description."
3985 (and (not (org-element-contents link))
3986 (let ((case-fold-search t)
3987 (rules (or rules org-export-default-inline-image-rule)))
3988 (catch 'exit
3989 (mapc
3990 (lambda (rule)
3991 (and (string= (org-element-property :type link) (car rule))
3992 (string-match (cdr rule)
3993 (org-element-property :path link))
3994 (throw 'exit t)))
3995 rules)
3996 ;; Return nil if no rule matched.
3997 nil))))
3999 (defun org-export-resolve-coderef (ref info)
4000 "Resolve a code reference REF.
4002 INFO is a plist used as a communication channel.
4004 Return associated line number in source code, or REF itself,
4005 depending on src-block or example element's switches."
4006 (org-element-map (plist-get info :parse-tree) '(example-block src-block)
4007 (lambda (el)
4008 (with-temp-buffer
4009 (insert (org-trim (org-element-property :value el)))
4010 (let* ((label-fmt (regexp-quote
4011 (or (org-element-property :label-fmt el)
4012 org-coderef-label-format)))
4013 (ref-re
4014 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
4015 (replace-regexp-in-string "%s" ref label-fmt nil t))))
4016 ;; Element containing REF is found. Resolve it to either
4017 ;; a label or a line number, as needed.
4018 (when (re-search-backward ref-re nil t)
4019 (cond
4020 ((org-element-property :use-labels el) ref)
4021 ((eq (org-element-property :number-lines el) 'continued)
4022 (+ (org-export-get-loc el info) (line-number-at-pos)))
4023 (t (line-number-at-pos)))))))
4024 info 'first-match))
4026 (defun org-export-resolve-fuzzy-link (link info)
4027 "Return LINK destination.
4029 INFO is a plist holding contextual information.
4031 Return value can be an object, an element, or nil:
4033 - If LINK path matches a target object (i.e. <<path>>) return it.
4035 - If LINK path exactly matches the name affiliated keyword
4036 \(i.e. #+NAME: path) of an element, return that element.
4038 - If LINK path exactly matches any headline name, return that
4039 element. If more than one headline share that name, priority
4040 will be given to the one with the closest common ancestor, if
4041 any, or the first one in the parse tree otherwise.
4043 - Otherwise, return nil.
4045 Assume LINK type is \"fuzzy\". White spaces are not
4046 significant."
4047 (let* ((raw-path (org-element-property :path link))
4048 (match-title-p (eq (aref raw-path 0) ?*))
4049 ;; Split PATH at white spaces so matches are space
4050 ;; insensitive.
4051 (path (org-split-string
4052 (if match-title-p (substring raw-path 1) raw-path)))
4053 ;; Cache for destinations that are not position dependent.
4054 (link-cache
4055 (or (plist-get info :resolve-fuzzy-link-cache)
4056 (plist-get (setq info (plist-put info :resolve-fuzzy-link-cache
4057 (make-hash-table :test 'equal)))
4058 :resolve-fuzzy-link-cache)))
4059 (cached (gethash path link-cache 'not-found)))
4060 (cond
4061 ;; Destination is not position dependent: use cached value.
4062 ((and (not match-title-p) (not (eq cached 'not-found))) cached)
4063 ;; First try to find a matching "<<path>>" unless user specified
4064 ;; he was looking for a headline (path starts with a "*"
4065 ;; character).
4066 ((and (not match-title-p)
4067 (let ((match (org-element-map (plist-get info :parse-tree) 'target
4068 (lambda (blob)
4069 (and (equal (org-split-string
4070 (org-element-property :value blob))
4071 path)
4072 blob))
4073 info 'first-match)))
4074 (and match (puthash path match link-cache)))))
4075 ;; Then try to find an element with a matching "#+NAME: path"
4076 ;; affiliated keyword.
4077 ((and (not match-title-p)
4078 (let ((match (org-element-map (plist-get info :parse-tree)
4079 org-element-all-elements
4080 (lambda (el)
4081 (let ((name (org-element-property :name el)))
4082 (when (and name
4083 (equal (org-split-string name) path))
4084 el)))
4085 info 'first-match)))
4086 (and match (puthash path match link-cache)))))
4087 ;; Last case: link either points to a headline or to nothingness.
4088 ;; Try to find the source, with priority given to headlines with
4089 ;; the closest common ancestor. If such candidate is found,
4090 ;; return it, otherwise return nil.
4092 (let ((find-headline
4093 (function
4094 ;; Return first headline whose `:raw-value' property is
4095 ;; NAME in parse tree DATA, or nil. Statistics cookies
4096 ;; are ignored.
4097 (lambda (name data)
4098 (org-element-map data 'headline
4099 (lambda (headline)
4100 (when (equal (org-split-string
4101 (replace-regexp-in-string
4102 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
4103 (org-element-property :raw-value headline)))
4104 name)
4105 headline))
4106 info 'first-match)))))
4107 ;; Search among headlines sharing an ancestor with link, from
4108 ;; closest to farthest.
4109 (catch 'exit
4110 (mapc
4111 (lambda (parent)
4112 (let ((foundp (funcall find-headline path parent)))
4113 (when foundp (throw 'exit foundp))))
4114 (let ((parent-hl (org-export-get-parent-headline link)))
4115 (if (not parent-hl) (list (plist-get info :parse-tree))
4116 (cons parent-hl (org-export-get-genealogy parent-hl)))))
4117 ;; No destination found: return nil.
4118 (and (not match-title-p) (puthash path nil link-cache))))))))
4120 (defun org-export-resolve-id-link (link info)
4121 "Return headline referenced as LINK destination.
4123 INFO is a plist used as a communication channel.
4125 Return value can be the headline element matched in current parse
4126 tree, a file name or nil. Assume LINK type is either \"id\" or
4127 \"custom-id\"."
4128 (let ((id (org-element-property :path link)))
4129 ;; First check if id is within the current parse tree.
4130 (or (org-element-map (plist-get info :parse-tree) 'headline
4131 (lambda (headline)
4132 (when (or (string= (org-element-property :ID headline) id)
4133 (string= (org-element-property :CUSTOM_ID headline) id))
4134 headline))
4135 info 'first-match)
4136 ;; Otherwise, look for external files.
4137 (cdr (assoc id (plist-get info :id-alist))))))
4139 (defun org-export-resolve-radio-link (link info)
4140 "Return radio-target object referenced as LINK destination.
4142 INFO is a plist used as a communication channel.
4144 Return value can be a radio-target object or nil. Assume LINK
4145 has type \"radio\"."
4146 (let ((path (replace-regexp-in-string
4147 "[ \r\t\n]+" " " (org-element-property :path link))))
4148 (org-element-map (plist-get info :parse-tree) 'radio-target
4149 (lambda (radio)
4150 (and (eq (compare-strings
4151 (replace-regexp-in-string
4152 "[ \r\t\n]+" " " (org-element-property :value radio))
4153 nil nil path nil nil t)
4155 radio))
4156 info 'first-match)))
4159 ;;;; For References
4161 ;; `org-export-get-ordinal' associates a sequence number to any object
4162 ;; or element.
4164 (defun org-export-get-ordinal (element info &optional types predicate)
4165 "Return ordinal number of an element or object.
4167 ELEMENT is the element or object considered. INFO is the plist
4168 used as a communication channel.
4170 Optional argument TYPES, when non-nil, is a list of element or
4171 object types, as symbols, that should also be counted in.
4172 Otherwise, only provided element's type is considered.
4174 Optional argument PREDICATE is a function returning a non-nil
4175 value if the current element or object should be counted in. It
4176 accepts two arguments: the element or object being considered and
4177 the plist used as a communication channel. This allows to count
4178 only a certain type of objects (i.e. inline images).
4180 Return value is a list of numbers if ELEMENT is a headline or an
4181 item. It is nil for keywords. It represents the footnote number
4182 for footnote definitions and footnote references. If ELEMENT is
4183 a target, return the same value as if ELEMENT was the closest
4184 table, item or headline containing the target. In any other
4185 case, return the sequence number of ELEMENT among elements or
4186 objects of the same type."
4187 ;; Ordinal of a target object refer to the ordinal of the closest
4188 ;; table, item, or headline containing the object.
4189 (when (eq (org-element-type element) 'target)
4190 (setq element
4191 (loop for parent in (org-export-get-genealogy element)
4192 when
4193 (memq
4194 (org-element-type parent)
4195 '(footnote-definition footnote-reference headline item
4196 table))
4197 return parent)))
4198 (case (org-element-type element)
4199 ;; Special case 1: A headline returns its number as a list.
4200 (headline (org-export-get-headline-number element info))
4201 ;; Special case 2: An item returns its number as a list.
4202 (item (let ((struct (org-element-property :structure element)))
4203 (org-list-get-item-number
4204 (org-element-property :begin element)
4205 struct
4206 (org-list-prevs-alist struct)
4207 (org-list-parents-alist struct))))
4208 ((footnote-definition footnote-reference)
4209 (org-export-get-footnote-number element info))
4210 (otherwise
4211 (let ((counter 0))
4212 ;; Increment counter until ELEMENT is found again.
4213 (org-element-map (plist-get info :parse-tree)
4214 (or types (org-element-type element))
4215 (lambda (el)
4216 (cond
4217 ((eq element el) (1+ counter))
4218 ((not predicate) (incf counter) nil)
4219 ((funcall predicate el info) (incf counter) nil)))
4220 info 'first-match)))))
4223 ;;;; For Src-Blocks
4225 ;; `org-export-get-loc' counts number of code lines accumulated in
4226 ;; src-block or example-block elements with a "+n" switch until
4227 ;; a given element, excluded. Note: "-n" switches reset that count.
4229 ;; `org-export-unravel-code' extracts source code (along with a code
4230 ;; references alist) from an `element-block' or `src-block' type
4231 ;; element.
4233 ;; `org-export-format-code' applies a formatting function to each line
4234 ;; of code, providing relative line number and code reference when
4235 ;; appropriate. Since it doesn't access the original element from
4236 ;; which the source code is coming, it expects from the code calling
4237 ;; it to know if lines should be numbered and if code references
4238 ;; should appear.
4240 ;; Eventually, `org-export-format-code-default' is a higher-level
4241 ;; function (it makes use of the two previous functions) which handles
4242 ;; line numbering and code references inclusion, and returns source
4243 ;; code in a format suitable for plain text or verbatim output.
4245 (defun org-export-get-loc (element info)
4246 "Return accumulated lines of code up to ELEMENT.
4248 INFO is the plist used as a communication channel.
4250 ELEMENT is excluded from count."
4251 (let ((loc 0))
4252 (org-element-map (plist-get info :parse-tree)
4253 `(src-block example-block ,(org-element-type element))
4254 (lambda (el)
4255 (cond
4256 ;; ELEMENT is reached: Quit the loop.
4257 ((eq el element))
4258 ;; Only count lines from src-block and example-block elements
4259 ;; with a "+n" or "-n" switch. A "-n" switch resets counter.
4260 ((not (memq (org-element-type el) '(src-block example-block))) nil)
4261 ((let ((linums (org-element-property :number-lines el)))
4262 (when linums
4263 ;; Accumulate locs or reset them.
4264 (let ((lines (org-count-lines
4265 (org-trim (org-element-property :value el)))))
4266 (setq loc (if (eq linums 'new) lines (+ loc lines))))))
4267 ;; Return nil to stay in the loop.
4268 nil)))
4269 info 'first-match)
4270 ;; Return value.
4271 loc))
4273 (defun org-export-unravel-code (element)
4274 "Clean source code and extract references out of it.
4276 ELEMENT has either a `src-block' an `example-block' type.
4278 Return a cons cell whose CAR is the source code, cleaned from any
4279 reference and protective comma and CDR is an alist between
4280 relative line number (integer) and name of code reference on that
4281 line (string)."
4282 (let* ((line 0) refs
4283 ;; Get code and clean it. Remove blank lines at its
4284 ;; beginning and end.
4285 (code (replace-regexp-in-string
4286 "\\`\\([ \t]*\n\\)+" ""
4287 (replace-regexp-in-string
4288 "\\([ \t]*\n\\)*[ \t]*\\'" "\n"
4289 (org-element-property :value element))))
4290 ;; Get format used for references.
4291 (label-fmt (regexp-quote
4292 (or (org-element-property :label-fmt element)
4293 org-coderef-label-format)))
4294 ;; Build a regexp matching a loc with a reference.
4295 (with-ref-re
4296 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)[ \t]*\\)$"
4297 (replace-regexp-in-string
4298 "%s" "\\([-a-zA-Z0-9_ ]+\\)" label-fmt nil t))))
4299 ;; Return value.
4300 (cons
4301 ;; Code with references removed.
4302 (org-element-normalize-string
4303 (mapconcat
4304 (lambda (loc)
4305 (incf line)
4306 (if (not (string-match with-ref-re loc)) loc
4307 ;; Ref line: remove ref, and signal its position in REFS.
4308 (push (cons line (match-string 3 loc)) refs)
4309 (replace-match "" nil nil loc 1)))
4310 (org-split-string code "\n") "\n"))
4311 ;; Reference alist.
4312 refs)))
4314 (defun org-export-format-code (code fun &optional num-lines ref-alist)
4315 "Format CODE by applying FUN line-wise and return it.
4317 CODE is a string representing the code to format. FUN is
4318 a function. It must accept three arguments: a line of
4319 code (string), the current line number (integer) or nil and the
4320 reference associated to the current line (string) or nil.
4322 Optional argument NUM-LINES can be an integer representing the
4323 number of code lines accumulated until the current code. Line
4324 numbers passed to FUN will take it into account. If it is nil,
4325 FUN's second argument will always be nil. This number can be
4326 obtained with `org-export-get-loc' function.
4328 Optional argument REF-ALIST can be an alist between relative line
4329 number (i.e. ignoring NUM-LINES) and the name of the code
4330 reference on it. If it is nil, FUN's third argument will always
4331 be nil. It can be obtained through the use of
4332 `org-export-unravel-code' function."
4333 (let ((--locs (org-split-string code "\n"))
4334 (--line 0))
4335 (org-element-normalize-string
4336 (mapconcat
4337 (lambda (--loc)
4338 (incf --line)
4339 (let ((--ref (cdr (assq --line ref-alist))))
4340 (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
4341 --locs "\n"))))
4343 (defun org-export-format-code-default (element info)
4344 "Return source code from ELEMENT, formatted in a standard way.
4346 ELEMENT is either a `src-block' or `example-block' element. INFO
4347 is a plist used as a communication channel.
4349 This function takes care of line numbering and code references
4350 inclusion. Line numbers, when applicable, appear at the
4351 beginning of the line, separated from the code by two white
4352 spaces. Code references, on the other hand, appear flushed to
4353 the right, separated by six white spaces from the widest line of
4354 code."
4355 ;; Extract code and references.
4356 (let* ((code-info (org-export-unravel-code element))
4357 (code (car code-info))
4358 (code-lines (org-split-string code "\n")))
4359 (if (null code-lines) ""
4360 (let* ((refs (and (org-element-property :retain-labels element)
4361 (cdr code-info)))
4362 ;; Handle line numbering.
4363 (num-start (case (org-element-property :number-lines element)
4364 (continued (org-export-get-loc element info))
4365 (new 0)))
4366 (num-fmt
4367 (and num-start
4368 (format "%%%ds "
4369 (length (number-to-string
4370 (+ (length code-lines) num-start))))))
4371 ;; Prepare references display, if required. Any reference
4372 ;; should start six columns after the widest line of code,
4373 ;; wrapped with parenthesis.
4374 (max-width
4375 (+ (apply 'max (mapcar 'length code-lines))
4376 (if (not num-start) 0 (length (format num-fmt num-start))))))
4377 (org-export-format-code
4378 code
4379 (lambda (loc line-num ref)
4380 (let ((number-str (and num-fmt (format num-fmt line-num))))
4381 (concat
4382 number-str
4384 (and ref
4385 (concat (make-string
4386 (- (+ 6 max-width)
4387 (+ (length loc) (length number-str))) ? )
4388 (format "(%s)" ref))))))
4389 num-start refs)))))
4392 ;;;; For Tables
4394 ;; `org-export-table-has-special-column-p' and and
4395 ;; `org-export-table-row-is-special-p' are predicates used to look for
4396 ;; meta-information about the table structure.
4398 ;; `org-table-has-header-p' tells when the rows before the first rule
4399 ;; should be considered as table's header.
4401 ;; `org-export-table-cell-width', `org-export-table-cell-alignment'
4402 ;; and `org-export-table-cell-borders' extract information from
4403 ;; a table-cell element.
4405 ;; `org-export-table-dimensions' gives the number on rows and columns
4406 ;; in the table, ignoring horizontal rules and special columns.
4407 ;; `org-export-table-cell-address', given a table-cell object, returns
4408 ;; the absolute address of a cell. On the other hand,
4409 ;; `org-export-get-table-cell-at' does the contrary.
4411 ;; `org-export-table-cell-starts-colgroup-p',
4412 ;; `org-export-table-cell-ends-colgroup-p',
4413 ;; `org-export-table-row-starts-rowgroup-p',
4414 ;; `org-export-table-row-ends-rowgroup-p',
4415 ;; `org-export-table-row-starts-header-p' and
4416 ;; `org-export-table-row-ends-header-p' indicate position of current
4417 ;; row or cell within the table.
4419 (defun org-export-table-has-special-column-p (table)
4420 "Non-nil when TABLE has a special column.
4421 All special columns will be ignored during export."
4422 ;; The table has a special column when every first cell of every row
4423 ;; has an empty value or contains a symbol among "/", "#", "!", "$",
4424 ;; "*" "_" and "^". Though, do not consider a first row containing
4425 ;; only empty cells as special.
4426 (let ((special-column-p 'empty))
4427 (catch 'exit
4428 (mapc
4429 (lambda (row)
4430 (when (eq (org-element-property :type row) 'standard)
4431 (let ((value (org-element-contents
4432 (car (org-element-contents row)))))
4433 (cond ((member value '(("/") ("#") ("!") ("$") ("*") ("_") ("^")))
4434 (setq special-column-p 'special))
4435 ((not value))
4436 (t (throw 'exit nil))))))
4437 (org-element-contents table))
4438 (eq special-column-p 'special))))
4440 (defun org-export-table-has-header-p (table info)
4441 "Non-nil when TABLE has a header.
4443 INFO is a plist used as a communication channel.
4445 A table has a header when it contains at least two row groups."
4446 (let ((cache (or (plist-get info :table-header-cache)
4447 (plist-get (setq info
4448 (plist-put info :table-header-cache
4449 (make-hash-table :test 'eq)))
4450 :table-header-cache))))
4451 (or (gethash table cache)
4452 (let ((rowgroup 1) row-flag)
4453 (puthash
4454 table
4455 (org-element-map table 'table-row
4456 (lambda (row)
4457 (cond
4458 ((> rowgroup 1) t)
4459 ((and row-flag (eq (org-element-property :type row) 'rule))
4460 (incf rowgroup) (setq row-flag nil))
4461 ((and (not row-flag) (eq (org-element-property :type row)
4462 'standard))
4463 (setq row-flag t) nil)))
4464 info 'first-match)
4465 cache)))))
4467 (defun org-export-table-row-is-special-p (table-row info)
4468 "Non-nil if TABLE-ROW is considered special.
4470 INFO is a plist used as the communication channel.
4472 All special rows will be ignored during export."
4473 (when (eq (org-element-property :type table-row) 'standard)
4474 (let ((first-cell (org-element-contents
4475 (car (org-element-contents table-row)))))
4476 ;; A row is special either when...
4478 ;; ... it starts with a field only containing "/",
4479 (equal first-cell '("/"))
4480 ;; ... the table contains a special column and the row start
4481 ;; with a marking character among, "^", "_", "$" or "!",
4482 (and (org-export-table-has-special-column-p
4483 (org-export-get-parent table-row))
4484 (member first-cell '(("^") ("_") ("$") ("!"))))
4485 ;; ... it contains only alignment cookies and empty cells.
4486 (let ((special-row-p 'empty))
4487 (catch 'exit
4488 (mapc
4489 (lambda (cell)
4490 (let ((value (org-element-contents cell)))
4491 ;; Since VALUE is a secondary string, the following
4492 ;; checks avoid expanding it with `org-export-data'.
4493 (cond ((not value))
4494 ((and (not (cdr value))
4495 (stringp (car value))
4496 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'"
4497 (car value)))
4498 (setq special-row-p 'cookie))
4499 (t (throw 'exit nil)))))
4500 (org-element-contents table-row))
4501 (eq special-row-p 'cookie)))))))
4503 (defun org-export-table-row-group (table-row info)
4504 "Return TABLE-ROW's group number, as an integer.
4506 INFO is a plist used as the communication channel.
4508 Return value is the group number, as an integer, or nil for
4509 special rows and rows separators. First group is also table's
4510 header."
4511 (let ((cache (or (plist-get info :table-row-group-cache)
4512 (plist-get (setq info
4513 (plist-put info :table-row-group-cache
4514 (make-hash-table :test 'eq)))
4515 :table-row-group-cache))))
4516 (cond ((gethash table-row cache))
4517 ((eq (org-element-property :type table-row) 'rule) nil)
4518 (t (let ((group 0) row-flag)
4519 (org-element-map (org-export-get-parent table-row) 'table-row
4520 (lambda (row)
4521 (if (eq (org-element-property :type row) 'rule)
4522 (setq row-flag nil)
4523 (unless row-flag (incf group) (setq row-flag t)))
4524 (when (eq table-row row) (puthash table-row group cache)))
4525 info 'first-match))))))
4527 (defun org-export-table-cell-width (table-cell info)
4528 "Return TABLE-CELL contents width.
4530 INFO is a plist used as the communication channel.
4532 Return value is the width given by the last width cookie in the
4533 same column as TABLE-CELL, or nil."
4534 (let* ((row (org-export-get-parent table-cell))
4535 (table (org-export-get-parent row))
4536 (column (let ((cells (org-element-contents row)))
4537 (- (length cells) (length (memq table-cell cells)))))
4538 (cache (or (plist-get info :table-cell-width-cache)
4539 (plist-get (setq info
4540 (plist-put info :table-cell-width-cache
4541 (make-hash-table :test 'equal)))
4542 :table-cell-width-cache)))
4543 (key (cons table column))
4544 (value (gethash key cache 'no-result)))
4545 (if (not (eq value 'no-result)) value
4546 (let (cookie-width)
4547 (dolist (row (org-element-contents table)
4548 (puthash key cookie-width cache))
4549 (when (org-export-table-row-is-special-p row info)
4550 ;; In a special row, try to find a width cookie at COLUMN.
4551 (let* ((value (org-element-contents
4552 (elt (org-element-contents row) column)))
4553 (cookie (car value)))
4554 ;; The following checks avoid expanding unnecessarily
4555 ;; the cell with `org-export-data'.
4556 (when (and value
4557 (not (cdr value))
4558 (stringp cookie)
4559 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'" cookie)
4560 (match-string 1 cookie))
4561 (setq cookie-width
4562 (string-to-number (match-string 1 cookie)))))))))))
4564 (defun org-export-table-cell-alignment (table-cell info)
4565 "Return TABLE-CELL contents alignment.
4567 INFO is a plist used as the communication channel.
4569 Return alignment as specified by the last alignment cookie in the
4570 same column as TABLE-CELL. If no such cookie is found, a default
4571 alignment value will be deduced from fraction of numbers in the
4572 column (see `org-table-number-fraction' for more information).
4573 Possible values are `left', `right' and `center'."
4574 (let* ((row (org-export-get-parent table-cell))
4575 (table (org-export-get-parent row))
4576 (column (let ((cells (org-element-contents row)))
4577 (- (length cells) (length (memq table-cell cells)))))
4578 (cache (or (plist-get info :table-cell-alignment-cache)
4579 (plist-get (setq info
4580 (plist-put info :table-cell-alignment-cache
4581 (make-hash-table :test 'equal)))
4582 :table-cell-alignment-cache))))
4583 (or (gethash (cons table column) cache)
4584 (let ((number-cells 0)
4585 (total-cells 0)
4586 cookie-align
4587 previous-cell-number-p)
4588 (dolist (row (org-element-contents (org-export-get-parent row)))
4589 (cond
4590 ;; In a special row, try to find an alignment cookie at
4591 ;; COLUMN.
4592 ((org-export-table-row-is-special-p row info)
4593 (let ((value (org-element-contents
4594 (elt (org-element-contents row) column))))
4595 ;; Since VALUE is a secondary string, the following
4596 ;; checks avoid useless expansion through
4597 ;; `org-export-data'.
4598 (when (and value
4599 (not (cdr value))
4600 (stringp (car value))
4601 (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'"
4602 (car value))
4603 (match-string 1 (car value)))
4604 (setq cookie-align (match-string 1 (car value))))))
4605 ;; Ignore table rules.
4606 ((eq (org-element-property :type row) 'rule))
4607 ;; In a standard row, check if cell's contents are
4608 ;; expressing some kind of number. Increase NUMBER-CELLS
4609 ;; accordingly. Though, don't bother if an alignment
4610 ;; cookie has already defined cell's alignment.
4611 ((not cookie-align)
4612 (let ((value (org-export-data
4613 (org-element-contents
4614 (elt (org-element-contents row) column))
4615 info)))
4616 (incf total-cells)
4617 ;; Treat an empty cell as a number if it follows
4618 ;; a number.
4619 (if (not (or (string-match org-table-number-regexp value)
4620 (and (string= value "") previous-cell-number-p)))
4621 (setq previous-cell-number-p nil)
4622 (setq previous-cell-number-p t)
4623 (incf number-cells))))))
4624 ;; Return value. Alignment specified by cookies has
4625 ;; precedence over alignment deduced from cell's contents.
4626 (puthash (cons table column)
4627 (cond ((equal cookie-align "l") 'left)
4628 ((equal cookie-align "r") 'right)
4629 ((equal cookie-align "c") 'center)
4630 ((>= (/ (float number-cells) total-cells)
4631 org-table-number-fraction)
4632 'right)
4633 (t 'left))
4634 cache)))))
4636 (defun org-export-table-cell-borders (table-cell info)
4637 "Return TABLE-CELL borders.
4639 INFO is a plist used as a communication channel.
4641 Return value is a list of symbols, or nil. Possible values are:
4642 `top', `bottom', `above', `below', `left' and `right'. Note:
4643 `top' (resp. `bottom') only happen for a cell in the first
4644 row (resp. last row) of the table, ignoring table rules, if any.
4646 Returned borders ignore special rows."
4647 (let* ((row (org-export-get-parent table-cell))
4648 (table (org-export-get-parent-table table-cell))
4649 borders)
4650 ;; Top/above border? TABLE-CELL has a border above when a rule
4651 ;; used to demarcate row groups can be found above. Hence,
4652 ;; finding a rule isn't sufficient to push `above' in BORDERS:
4653 ;; another regular row has to be found above that rule.
4654 (let (rule-flag)
4655 (catch 'exit
4656 (mapc (lambda (row)
4657 (cond ((eq (org-element-property :type row) 'rule)
4658 (setq rule-flag t))
4659 ((not (org-export-table-row-is-special-p row info))
4660 (if rule-flag (throw 'exit (push 'above borders))
4661 (throw 'exit nil)))))
4662 ;; Look at every row before the current one.
4663 (cdr (memq row (reverse (org-element-contents table)))))
4664 ;; No rule above, or rule found starts the table (ignoring any
4665 ;; special row): TABLE-CELL is at the top of the table.
4666 (when rule-flag (push 'above borders))
4667 (push 'top borders)))
4668 ;; Bottom/below border? TABLE-CELL has a border below when next
4669 ;; non-regular row below is a rule.
4670 (let (rule-flag)
4671 (catch 'exit
4672 (mapc (lambda (row)
4673 (cond ((eq (org-element-property :type row) 'rule)
4674 (setq rule-flag t))
4675 ((not (org-export-table-row-is-special-p row info))
4676 (if rule-flag (throw 'exit (push 'below borders))
4677 (throw 'exit nil)))))
4678 ;; Look at every row after the current one.
4679 (cdr (memq row (org-element-contents table))))
4680 ;; No rule below, or rule found ends the table (modulo some
4681 ;; special row): TABLE-CELL is at the bottom of the table.
4682 (when rule-flag (push 'below borders))
4683 (push 'bottom borders)))
4684 ;; Right/left borders? They can only be specified by column
4685 ;; groups. Column groups are defined in a row starting with "/".
4686 ;; Also a column groups row only contains "<", "<>", ">" or blank
4687 ;; cells.
4688 (catch 'exit
4689 (let ((column (let ((cells (org-element-contents row)))
4690 (- (length cells) (length (memq table-cell cells))))))
4691 (mapc
4692 (lambda (row)
4693 (unless (eq (org-element-property :type row) 'rule)
4694 (when (equal (org-element-contents
4695 (car (org-element-contents row)))
4696 '("/"))
4697 (let ((column-groups
4698 (mapcar
4699 (lambda (cell)
4700 (let ((value (org-element-contents cell)))
4701 (when (member value '(("<") ("<>") (">") nil))
4702 (car value))))
4703 (org-element-contents row))))
4704 ;; There's a left border when previous cell, if
4705 ;; any, ends a group, or current one starts one.
4706 (when (or (and (not (zerop column))
4707 (member (elt column-groups (1- column))
4708 '(">" "<>")))
4709 (member (elt column-groups column) '("<" "<>")))
4710 (push 'left borders))
4711 ;; There's a right border when next cell, if any,
4712 ;; starts a group, or current one ends one.
4713 (when (or (and (/= (1+ column) (length column-groups))
4714 (member (elt column-groups (1+ column))
4715 '("<" "<>")))
4716 (member (elt column-groups column) '(">" "<>")))
4717 (push 'right borders))
4718 (throw 'exit nil)))))
4719 ;; Table rows are read in reverse order so last column groups
4720 ;; row has precedence over any previous one.
4721 (reverse (org-element-contents table)))))
4722 ;; Return value.
4723 borders))
4725 (defun org-export-table-cell-starts-colgroup-p (table-cell info)
4726 "Non-nil when TABLE-CELL is at the beginning of a row group.
4727 INFO is a plist used as a communication channel."
4728 ;; A cell starts a column group either when it is at the beginning
4729 ;; of a row (or after the special column, if any) or when it has
4730 ;; a left border.
4731 (or (eq (org-element-map (org-export-get-parent table-cell) 'table-cell
4732 'identity info 'first-match)
4733 table-cell)
4734 (memq 'left (org-export-table-cell-borders table-cell info))))
4736 (defun org-export-table-cell-ends-colgroup-p (table-cell info)
4737 "Non-nil when TABLE-CELL is at the end of a row group.
4738 INFO is a plist used as a communication channel."
4739 ;; A cell ends a column group either when it is at the end of a row
4740 ;; or when it has a right border.
4741 (or (eq (car (last (org-element-contents
4742 (org-export-get-parent table-cell))))
4743 table-cell)
4744 (memq 'right (org-export-table-cell-borders table-cell info))))
4746 (defun org-export-table-row-starts-rowgroup-p (table-row info)
4747 "Non-nil when TABLE-ROW is at the beginning of a column group.
4748 INFO is a plist used as a communication channel."
4749 (unless (or (eq (org-element-property :type table-row) 'rule)
4750 (org-export-table-row-is-special-p table-row info))
4751 (let ((borders (org-export-table-cell-borders
4752 (car (org-element-contents table-row)) info)))
4753 (or (memq 'top borders) (memq 'above borders)))))
4755 (defun org-export-table-row-ends-rowgroup-p (table-row info)
4756 "Non-nil when TABLE-ROW is at the end of a column group.
4757 INFO is a plist used as a communication channel."
4758 (unless (or (eq (org-element-property :type table-row) 'rule)
4759 (org-export-table-row-is-special-p table-row info))
4760 (let ((borders (org-export-table-cell-borders
4761 (car (org-element-contents table-row)) info)))
4762 (or (memq 'bottom borders) (memq 'below borders)))))
4764 (defun org-export-table-row-starts-header-p (table-row info)
4765 "Non-nil when TABLE-ROW is the first table header's row.
4766 INFO is a plist used as a communication channel."
4767 (and (org-export-table-has-header-p
4768 (org-export-get-parent-table table-row) info)
4769 (org-export-table-row-starts-rowgroup-p table-row info)
4770 (= (org-export-table-row-group table-row info) 1)))
4772 (defun org-export-table-row-ends-header-p (table-row info)
4773 "Non-nil when TABLE-ROW is the last table header's row.
4774 INFO is a plist used as a communication channel."
4775 (and (org-export-table-has-header-p
4776 (org-export-get-parent-table table-row) info)
4777 (org-export-table-row-ends-rowgroup-p table-row info)
4778 (= (org-export-table-row-group table-row info) 1)))
4780 (defun org-export-table-row-number (table-row info)
4781 "Return TABLE-ROW number.
4782 INFO is a plist used as a communication channel. Return value is
4783 zero-based and ignores separators. The function returns nil for
4784 special colums and separators."
4785 (when (and (eq (org-element-property :type table-row) 'standard)
4786 (not (org-export-table-row-is-special-p table-row info)))
4787 (let ((number 0))
4788 (org-element-map (org-export-get-parent-table table-row) 'table-row
4789 (lambda (row)
4790 (cond ((eq row table-row) number)
4791 ((eq (org-element-property :type row) 'standard)
4792 (incf number) nil)))
4793 info 'first-match))))
4795 (defun org-export-table-dimensions (table info)
4796 "Return TABLE dimensions.
4798 INFO is a plist used as a communication channel.
4800 Return value is a CONS like (ROWS . COLUMNS) where
4801 ROWS (resp. COLUMNS) is the number of exportable
4802 rows (resp. columns)."
4803 (let (first-row (columns 0) (rows 0))
4804 ;; Set number of rows, and extract first one.
4805 (org-element-map table 'table-row
4806 (lambda (row)
4807 (when (eq (org-element-property :type row) 'standard)
4808 (incf rows)
4809 (unless first-row (setq first-row row)))) info)
4810 ;; Set number of columns.
4811 (org-element-map first-row 'table-cell (lambda (cell) (incf columns)) info)
4812 ;; Return value.
4813 (cons rows columns)))
4815 (defun org-export-table-cell-address (table-cell info)
4816 "Return address of a regular TABLE-CELL object.
4818 TABLE-CELL is the cell considered. INFO is a plist used as
4819 a communication channel.
4821 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4822 zero-based index. Only exportable cells are considered. The
4823 function returns nil for other cells."
4824 (let* ((table-row (org-export-get-parent table-cell))
4825 (row-number (org-export-table-row-number table-row info)))
4826 (when row-number
4827 (cons row-number
4828 (let ((col-count 0))
4829 (org-element-map table-row 'table-cell
4830 (lambda (cell)
4831 (if (eq cell table-cell) col-count (incf col-count) nil))
4832 info 'first-match))))))
4834 (defun org-export-get-table-cell-at (address table info)
4835 "Return regular table-cell object at ADDRESS in TABLE.
4837 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4838 zero-based index. TABLE is a table type element. INFO is
4839 a plist used as a communication channel.
4841 If no table-cell, among exportable cells, is found at ADDRESS,
4842 return nil."
4843 (let ((column-pos (cdr address)) (column-count 0))
4844 (org-element-map
4845 ;; Row at (car address) or nil.
4846 (let ((row-pos (car address)) (row-count 0))
4847 (org-element-map table 'table-row
4848 (lambda (row)
4849 (cond ((eq (org-element-property :type row) 'rule) nil)
4850 ((= row-count row-pos) row)
4851 (t (incf row-count) nil)))
4852 info 'first-match))
4853 'table-cell
4854 (lambda (cell)
4855 (if (= column-count column-pos) cell
4856 (incf column-count) nil))
4857 info 'first-match)))
4860 ;;;; For Tables Of Contents
4862 ;; `org-export-collect-headlines' builds a list of all exportable
4863 ;; headline elements, maybe limited to a certain depth. One can then
4864 ;; easily parse it and transcode it.
4866 ;; Building lists of tables, figures or listings is quite similar.
4867 ;; Once the generic function `org-export-collect-elements' is defined,
4868 ;; `org-export-collect-tables', `org-export-collect-figures' and
4869 ;; `org-export-collect-listings' can be derived from it.
4871 (defun org-export-collect-headlines (info &optional n)
4872 "Collect headlines in order to build a table of contents.
4874 INFO is a plist used as a communication channel.
4876 When optional argument N is an integer, it specifies the depth of
4877 the table of contents. Otherwise, it is set to the value of the
4878 last headline level. See `org-export-headline-levels' for more
4879 information.
4881 Return a list of all exportable headlines as parsed elements.
4882 Footnote sections, if any, will be ignored."
4883 (unless (wholenump n) (setq n (plist-get info :headline-levels)))
4884 (org-element-map (plist-get info :parse-tree) 'headline
4885 (lambda (headline)
4886 (unless (org-element-property :footnote-section-p headline)
4887 ;; Strip contents from HEADLINE.
4888 (let ((relative-level (org-export-get-relative-level headline info)))
4889 (unless (> relative-level n) headline))))
4890 info))
4892 (defun org-export-collect-elements (type info &optional predicate)
4893 "Collect referenceable elements of a determined type.
4895 TYPE can be a symbol or a list of symbols specifying element
4896 types to search. Only elements with a caption are collected.
4898 INFO is a plist used as a communication channel.
4900 When non-nil, optional argument PREDICATE is a function accepting
4901 one argument, an element of type TYPE. It returns a non-nil
4902 value when that element should be collected.
4904 Return a list of all elements found, in order of appearance."
4905 (org-element-map (plist-get info :parse-tree) type
4906 (lambda (element)
4907 (and (org-element-property :caption element)
4908 (or (not predicate) (funcall predicate element))
4909 element))
4910 info))
4912 (defun org-export-collect-tables (info)
4913 "Build a list of tables.
4914 INFO is a plist used as a communication channel.
4916 Return a list of table elements with a caption."
4917 (org-export-collect-elements 'table info))
4919 (defun org-export-collect-figures (info predicate)
4920 "Build a list of figures.
4922 INFO is a plist used as a communication channel. PREDICATE is
4923 a function which accepts one argument: a paragraph element and
4924 whose return value is non-nil when that element should be
4925 collected.
4927 A figure is a paragraph type element, with a caption, verifying
4928 PREDICATE. The latter has to be provided since a \"figure\" is
4929 a vague concept that may depend on back-end.
4931 Return a list of elements recognized as figures."
4932 (org-export-collect-elements 'paragraph info predicate))
4934 (defun org-export-collect-listings (info)
4935 "Build a list of src blocks.
4937 INFO is a plist used as a communication channel.
4939 Return a list of src-block elements with a caption."
4940 (org-export-collect-elements 'src-block info))
4943 ;;;; Smart Quotes
4945 ;; The main function for the smart quotes sub-system is
4946 ;; `org-export-activate-smart-quotes', which replaces every quote in
4947 ;; a given string from the parse tree with its "smart" counterpart.
4949 ;; Dictionary for smart quotes is stored in
4950 ;; `org-export-smart-quotes-alist'.
4952 ;; Internally, regexps matching potential smart quotes (checks at
4953 ;; string boundaries are also necessary) are defined in
4954 ;; `org-export-smart-quotes-regexps'.
4956 (defconst org-export-smart-quotes-alist
4957 '(("da"
4958 ;; one may use: »...«, "...", ›...‹, or '...'.
4959 ;; http://sproget.dk/raad-og-regler/retskrivningsregler/retskrivningsregler/a7-40-60/a7-58-anforselstegn/
4960 ;; LaTeX quotes require Babel!
4961 (opening-double-quote :utf-8 "»" :html "&raquo;" :latex ">>"
4962 :texinfo "@guillemetright{}")
4963 (closing-double-quote :utf-8 "«" :html "&laquo;" :latex "<<"
4964 :texinfo "@guillemetleft{}")
4965 (opening-single-quote :utf-8 "›" :html "&rsaquo;" :latex "\\frq{}"
4966 :texinfo "@guilsinglright{}")
4967 (closing-single-quote :utf-8 "‹" :html "&lsaquo;" :latex "\\flq{}"
4968 :texinfo "@guilsingleft{}")
4969 (apostrophe :utf-8 "’" :html "&rsquo;"))
4970 ("de"
4971 (opening-double-quote :utf-8 "„" :html "&bdquo;" :latex "\"`"
4972 :texinfo "@quotedblbase{}")
4973 (closing-double-quote :utf-8 "“" :html "&ldquo;" :latex "\"'"
4974 :texinfo "@quotedblleft{}")
4975 (opening-single-quote :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}"
4976 :texinfo "@quotesinglbase{}")
4977 (closing-single-quote :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}"
4978 :texinfo "@quoteleft{}")
4979 (apostrophe :utf-8 "’" :html "&rsquo;"))
4980 ("en"
4981 (opening-double-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
4982 (closing-double-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
4983 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
4984 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
4985 (apostrophe :utf-8 "’" :html "&rsquo;"))
4986 ("es"
4987 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
4988 :texinfo "@guillemetleft{}")
4989 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
4990 :texinfo "@guillemetright{}")
4991 (opening-single-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
4992 (closing-single-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
4993 (apostrophe :utf-8 "’" :html "&rsquo;"))
4994 ("fr"
4995 (opening-double-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
4996 :texinfo "@guillemetleft{}@tie{}")
4997 (closing-double-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
4998 :texinfo "@tie{}@guillemetright{}")
4999 (opening-single-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
5000 :texinfo "@guillemetleft{}@tie{}")
5001 (closing-single-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
5002 :texinfo "@tie{}@guillemetright{}")
5003 (apostrophe :utf-8 "’" :html "&rsquo;"))
5004 ("no"
5005 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5006 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5007 :texinfo "@guillemetleft{}")
5008 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5009 :texinfo "@guillemetright{}")
5010 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5011 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5012 (apostrophe :utf-8 "’" :html "&rsquo;"))
5013 ("nb"
5014 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5015 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5016 :texinfo "@guillemetleft{}")
5017 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5018 :texinfo "@guillemetright{}")
5019 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5020 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5021 (apostrophe :utf-8 "’" :html "&rsquo;"))
5022 ("nn"
5023 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5024 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5025 :texinfo "@guillemetleft{}")
5026 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5027 :texinfo "@guillemetright{}")
5028 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5029 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5030 (apostrophe :utf-8 "’" :html "&rsquo;"))
5031 ("sv"
5032 ;; based on https://sv.wikipedia.org/wiki/Citattecken
5033 (opening-double-quote :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
5034 (closing-double-quote :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
5035 (opening-single-quote :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "`")
5036 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "'")
5037 (apostrophe :utf-8 "’" :html "&rsquo;"))
5039 "Smart quotes translations.
5041 Alist whose CAR is a language string and CDR is an alist with
5042 quote type as key and a plist associating various encodings to
5043 their translation as value.
5045 A quote type can be any symbol among `opening-double-quote',
5046 `closing-double-quote', `opening-single-quote',
5047 `closing-single-quote' and `apostrophe'.
5049 Valid encodings include `:utf-8', `:html', `:latex' and
5050 `:texinfo'.
5052 If no translation is found, the quote character is left as-is.")
5054 (defconst org-export-smart-quotes-regexps
5055 (list
5056 ;; Possible opening quote at beginning of string.
5057 "\\`\\([\"']\\)\\(\\w\\|\\s.\\|\\s_\\)"
5058 ;; Possible closing quote at beginning of string.
5059 "\\`\\([\"']\\)\\(\\s-\\|\\s)\\|\\s.\\)"
5060 ;; Possible apostrophe at beginning of string.
5061 "\\`\\('\\)\\S-"
5062 ;; Opening single and double quotes.
5063 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\(?:\\w\\|\\s.\\|\\s_\\)"
5064 ;; Closing single and double quotes.
5065 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\(?:\\s-\\|\\s)\\|\\s.\\)"
5066 ;; Apostrophe.
5067 "\\S-\\('\\)\\S-"
5068 ;; Possible opening quote at end of string.
5069 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\'"
5070 ;; Possible closing quote at end of string.
5071 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\'"
5072 ;; Possible apostrophe at end of string.
5073 "\\S-\\('\\)\\'")
5074 "List of regexps matching a quote or an apostrophe.
5075 In every regexp, quote or apostrophe matched is put in group 1.")
5077 (defun org-export-activate-smart-quotes (s encoding info &optional original)
5078 "Replace regular quotes with \"smart\" quotes in string S.
5080 ENCODING is a symbol among `:html', `:latex', `:texinfo' and
5081 `:utf-8'. INFO is a plist used as a communication channel.
5083 The function has to retrieve information about string
5084 surroundings in parse tree. It can only happen with an
5085 unmodified string. Thus, if S has already been through another
5086 process, a non-nil ORIGINAL optional argument will provide that
5087 original string.
5089 Return the new string."
5090 (if (equal s "") ""
5091 (let* ((prev (org-export-get-previous-element (or original s) info))
5092 ;; Try to be flexible when computing number of blanks
5093 ;; before object. The previous object may be a string
5094 ;; introduced by the back-end and not completely parsed.
5095 (pre-blank (and prev
5096 (or (org-element-property :post-blank prev)
5097 ;; A string with missing `:post-blank'
5098 ;; property.
5099 (and (stringp prev)
5100 (string-match " *\\'" prev)
5101 (length (match-string 0 prev)))
5102 ;; Fallback value.
5103 0)))
5104 (next (org-export-get-next-element (or original s) info))
5105 (get-smart-quote
5106 (lambda (q type)
5107 ;; Return smart quote associated to a give quote Q, as
5108 ;; a string. TYPE is a symbol among `open', `close' and
5109 ;; `apostrophe'.
5110 (let ((key (case type
5111 (apostrophe 'apostrophe)
5112 (open (if (equal "'" q) 'opening-single-quote
5113 'opening-double-quote))
5114 (otherwise (if (equal "'" q) 'closing-single-quote
5115 'closing-double-quote)))))
5116 (or (plist-get
5117 (cdr (assq key
5118 (cdr (assoc (plist-get info :language)
5119 org-export-smart-quotes-alist))))
5120 encoding)
5121 q)))))
5122 (if (or (equal "\"" s) (equal "'" s))
5123 ;; Only a quote: no regexp can match. We have to check both
5124 ;; sides and decide what to do.
5125 (cond ((and (not prev) (not next)) s)
5126 ((not prev) (funcall get-smart-quote s 'open))
5127 ((and (not next) (zerop pre-blank))
5128 (funcall get-smart-quote s 'close))
5129 ((not next) s)
5130 ((zerop pre-blank) (funcall get-smart-quote s 'apostrophe))
5131 (t (funcall get-smart-quote 'open)))
5132 ;; 1. Replace quote character at the beginning of S.
5133 (cond
5134 ;; Apostrophe?
5135 ((and prev (zerop pre-blank)
5136 (string-match (nth 2 org-export-smart-quotes-regexps) s))
5137 (setq s (replace-match
5138 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
5139 nil t s 1)))
5140 ;; Closing quote?
5141 ((and prev (zerop pre-blank)
5142 (string-match (nth 1 org-export-smart-quotes-regexps) s))
5143 (setq s (replace-match
5144 (funcall get-smart-quote (match-string 1 s) 'close)
5145 nil t s 1)))
5146 ;; Opening quote?
5147 ((and (or (not prev) (> pre-blank 0))
5148 (string-match (nth 0 org-export-smart-quotes-regexps) s))
5149 (setq s (replace-match
5150 (funcall get-smart-quote (match-string 1 s) 'open)
5151 nil t s 1))))
5152 ;; 2. Replace quotes in the middle of the string.
5153 (setq s (replace-regexp-in-string
5154 ;; Opening quotes.
5155 (nth 3 org-export-smart-quotes-regexps)
5156 (lambda (text)
5157 (funcall get-smart-quote (match-string 1 text) 'open))
5158 s nil t 1))
5159 (setq s (replace-regexp-in-string
5160 ;; Closing quotes.
5161 (nth 4 org-export-smart-quotes-regexps)
5162 (lambda (text)
5163 (funcall get-smart-quote (match-string 1 text) 'close))
5164 s nil t 1))
5165 (setq s (replace-regexp-in-string
5166 ;; Apostrophes.
5167 (nth 5 org-export-smart-quotes-regexps)
5168 (lambda (text)
5169 (funcall get-smart-quote (match-string 1 text) 'apostrophe))
5170 s nil t 1))
5171 ;; 3. Replace quote character at the end of S.
5172 (cond
5173 ;; Apostrophe?
5174 ((and next (string-match (nth 8 org-export-smart-quotes-regexps) s))
5175 (setq s (replace-match
5176 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
5177 nil t s 1)))
5178 ;; Closing quote?
5179 ((and (not next)
5180 (string-match (nth 7 org-export-smart-quotes-regexps) s))
5181 (setq s (replace-match
5182 (funcall get-smart-quote (match-string 1 s) 'close)
5183 nil t s 1)))
5184 ;; Opening quote?
5185 ((and next (string-match (nth 6 org-export-smart-quotes-regexps) s))
5186 (setq s (replace-match
5187 (funcall get-smart-quote (match-string 1 s) 'open)
5188 nil t s 1))))
5189 ;; Return string with smart quotes.
5190 s))))
5192 ;;;; Topology
5194 ;; Here are various functions to retrieve information about the
5195 ;; neighbourhood of a given element or object. Neighbours of interest
5196 ;; are direct parent (`org-export-get-parent'), parent headline
5197 ;; (`org-export-get-parent-headline'), first element containing an
5198 ;; object, (`org-export-get-parent-element'), parent table
5199 ;; (`org-export-get-parent-table'), previous element or object
5200 ;; (`org-export-get-previous-element') and next element or object
5201 ;; (`org-export-get-next-element').
5203 ;; `org-export-get-genealogy' returns the full genealogy of a given
5204 ;; element or object, from closest parent to full parse tree.
5206 (defsubst org-export-get-parent (blob)
5207 "Return BLOB parent or nil.
5208 BLOB is the element or object considered."
5209 (org-element-property :parent blob))
5211 (defun org-export-get-genealogy (blob)
5212 "Return full genealogy relative to a given element or object.
5214 BLOB is the element or object being considered.
5216 Ancestors are returned from closest to farthest, the last one
5217 being the full parse tree."
5218 (let (genealogy (parent blob))
5219 (while (setq parent (org-element-property :parent parent))
5220 (push parent genealogy))
5221 (nreverse genealogy)))
5223 (defun org-export-get-parent-headline (blob)
5224 "Return BLOB parent headline or nil.
5225 BLOB is the element or object being considered."
5226 (let ((parent blob))
5227 (while (and (setq parent (org-element-property :parent parent))
5228 (not (eq (org-element-type parent) 'headline))))
5229 parent))
5231 (defun org-export-get-parent-element (object)
5232 "Return first element containing OBJECT or nil.
5233 OBJECT is the object to consider."
5234 (let ((parent object))
5235 (while (and (setq parent (org-element-property :parent parent))
5236 (memq (org-element-type parent) org-element-all-objects)))
5237 parent))
5239 (defun org-export-get-parent-table (object)
5240 "Return OBJECT parent table or nil.
5241 OBJECT is either a `table-cell' or `table-element' type object."
5242 (let ((parent object))
5243 (while (and (setq parent (org-element-property :parent parent))
5244 (not (eq (org-element-type parent) 'table))))
5245 parent))
5247 (defun org-export-get-previous-element (blob info &optional n)
5248 "Return previous element or object.
5250 BLOB is an element or object. INFO is a plist used as
5251 a communication channel. Return previous exportable element or
5252 object, a string, or nil.
5254 When optional argument N is a positive integer, return a list
5255 containing up to N siblings before BLOB, from farthest to
5256 closest. With any other non-nil value, return a list containing
5257 all of them."
5258 (let ((siblings
5259 ;; An object can belong to the contents of its parent or
5260 ;; to a secondary string. We check the latter option
5261 ;; first.
5262 (let ((parent (org-export-get-parent blob)))
5263 (or (and (not (memq (org-element-type blob)
5264 org-element-all-elements))
5265 (let ((sec-value
5266 (org-element-property
5267 (cdr (assq (org-element-type parent)
5268 org-element-secondary-value-alist))
5269 parent)))
5270 (and (memq blob sec-value) sec-value)))
5271 (org-element-contents parent))))
5272 prev)
5273 (catch 'exit
5274 (mapc (lambda (obj)
5275 (cond ((memq obj (plist-get info :ignore-list)))
5276 ((null n) (throw 'exit obj))
5277 ((not (wholenump n)) (push obj prev))
5278 ((zerop n) (throw 'exit prev))
5279 (t (decf n) (push obj prev))))
5280 (cdr (memq blob (reverse siblings))))
5281 prev)))
5283 (defun org-export-get-next-element (blob info &optional n)
5284 "Return next element or object.
5286 BLOB is an element or object. INFO is a plist used as
5287 a communication channel. Return next exportable element or
5288 object, a string, or nil.
5290 When optional argument N is a positive integer, return a list
5291 containing up to N siblings after BLOB, from closest to farthest.
5292 With any other non-nil value, return a list containing all of
5293 them."
5294 (let ((siblings
5295 ;; An object can belong to the contents of its parent or to
5296 ;; a secondary string. We check the latter option first.
5297 (let ((parent (org-export-get-parent blob)))
5298 (or (and (not (memq (org-element-type blob)
5299 org-element-all-objects))
5300 (let ((sec-value
5301 (org-element-property
5302 (cdr (assq (org-element-type parent)
5303 org-element-secondary-value-alist))
5304 parent)))
5305 (cdr (memq blob sec-value))))
5306 (cdr (memq blob (org-element-contents parent))))))
5307 next)
5308 (catch 'exit
5309 (mapc (lambda (obj)
5310 (cond ((memq obj (plist-get info :ignore-list)))
5311 ((null n) (throw 'exit obj))
5312 ((not (wholenump n)) (push obj next))
5313 ((zerop n) (throw 'exit (nreverse next)))
5314 (t (decf n) (push obj next))))
5315 siblings)
5316 (nreverse next))))
5319 ;;;; Translation
5321 ;; `org-export-translate' translates a string according to language
5322 ;; specified by LANGUAGE keyword or `org-export-language-setup'
5323 ;; variable and a specified charset. `org-export-dictionary' contains
5324 ;; the dictionary used for the translation.
5326 (defconst org-export-dictionary
5327 '(("%e %n: %c"
5328 ("fr" :default "%e %n : %c" :html "%e&nbsp;%n&nbsp;: %c"))
5329 ("Author"
5330 ("ca" :default "Autor")
5331 ("cs" :default "Autor")
5332 ("da" :default "Forfatter")
5333 ("de" :default "Autor")
5334 ("eo" :html "A&#365;toro")
5335 ("es" :default "Autor")
5336 ("fi" :html "Tekij&auml;")
5337 ("fr" :default "Auteur")
5338 ("hu" :default "Szerz&otilde;")
5339 ("is" :html "H&ouml;fundur")
5340 ("it" :default "Autore")
5341 ("ja" :html "&#33879;&#32773;" :utf-8 "著者")
5342 ("nl" :default "Auteur")
5343 ("no" :default "Forfatter")
5344 ("nb" :default "Forfatter")
5345 ("nn" :default "Forfattar")
5346 ("pl" :default "Autor")
5347 ("ru" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5348 ("sv" :html "F&ouml;rfattare")
5349 ("uk" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5350 ("zh-CN" :html "&#20316;&#32773;" :utf-8 "作者")
5351 ("zh-TW" :html "&#20316;&#32773;" :utf-8 "作者"))
5352 ("Date"
5353 ("ca" :default "Data")
5354 ("cs" :default "Datum")
5355 ("da" :default "Dato")
5356 ("de" :default "Datum")
5357 ("eo" :default "Dato")
5358 ("es" :default "Fecha")
5359 ("fi" :html "P&auml;iv&auml;m&auml;&auml;r&auml;")
5360 ("hu" :html "D&aacute;tum")
5361 ("is" :default "Dagsetning")
5362 ("it" :default "Data")
5363 ("ja" :html "&#26085;&#20184;" :utf-8 "日付")
5364 ("nl" :default "Datum")
5365 ("no" :default "Dato")
5366 ("nb" :default "Dato")
5367 ("nn" :default "Dato")
5368 ("pl" :default "Data")
5369 ("ru" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5370 ("sv" :default "Datum")
5371 ("uk" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5372 ("zh-CN" :html "&#26085;&#26399;" :utf-8 "日期")
5373 ("zh-TW" :html "&#26085;&#26399;" :utf-8 "日期"))
5374 ("Equation"
5375 ("da" :default "Ligning")
5376 ("de" :default "Gleichung")
5377 ("es" :html "Ecuaci&oacute;n" :default "Ecuación")
5378 ("fr" :ascii "Equation" :default "Équation")
5379 ("no" :default "Ligning")
5380 ("nb" :default "Ligning")
5381 ("nn" :default "Likning")
5382 ("sv" :default "Ekvation")
5383 ("zh-CN" :html "&#26041;&#31243;" :utf-8 "方程"))
5384 ("Figure"
5385 ("da" :default "Figur")
5386 ("de" :default "Abbildung")
5387 ("es" :default "Figura")
5388 ("ja" :html "&#22259;" :utf-8 "図")
5389 ("no" :default "Illustrasjon")
5390 ("nb" :default "Illustrasjon")
5391 ("nn" :default "Illustrasjon")
5392 ("sv" :default "Illustration")
5393 ("zh-CN" :html "&#22270;" :utf-8 "图"))
5394 ("Figure %d:"
5395 ("da" :default "Figur %d")
5396 ("de" :default "Abbildung %d:")
5397 ("es" :default "Figura %d:")
5398 ("fr" :default "Figure %d :" :html "Figure&nbsp;%d&nbsp;:")
5399 ("ja" :html "&#22259;%d: " :utf-8 "図%d: ")
5400 ("no" :default "Illustrasjon %d")
5401 ("nb" :default "Illustrasjon %d")
5402 ("nn" :default "Illustrasjon %d")
5403 ("sv" :default "Illustration %d")
5404 ("zh-CN" :html "&#22270;%d&nbsp;" :utf-8 "图%d "))
5405 ("Footnotes"
5406 ("ca" :html "Peus de p&agrave;gina")
5407 ("cs" :default "Pozn\xe1mky pod carou")
5408 ("da" :default "Fodnoter")
5409 ("de" :html "Fu&szlig;noten" :default "Fußnoten")
5410 ("eo" :default "Piednotoj")
5411 ("es" :html "Nota al pie de p&aacute;gina" :default "Nota al pie de página")
5412 ("fi" :default "Alaviitteet")
5413 ("fr" :default "Notes de bas de page")
5414 ("hu" :html "L&aacute;bjegyzet")
5415 ("is" :html "Aftanm&aacute;lsgreinar")
5416 ("it" :html "Note a pi&egrave; di pagina")
5417 ("ja" :html "&#33050;&#27880;" :utf-8 "脚注")
5418 ("nl" :default "Voetnoten")
5419 ("no" :default "Fotnoter")
5420 ("nb" :default "Fotnoter")
5421 ("nn" :default "Fotnotar")
5422 ("pl" :default "Przypis")
5423 ("ru" :html "&#1057;&#1085;&#1086;&#1089;&#1082;&#1080;" :utf-8 "Сноски")
5424 ("sv" :default "Fotnoter")
5425 ("uk" :html "&#1055;&#1088;&#1080;&#1084;&#1110;&#1090;&#1082;&#1080;"
5426 :utf-8 "Примітки")
5427 ("zh-CN" :html "&#33050;&#27880;" :utf-8 "脚注")
5428 ("zh-TW" :html "&#33139;&#35387;" :utf-8 "腳註"))
5429 ("List of Listings"
5430 ("da" :default "Programmer")
5431 ("de" :default "Programmauflistungsverzeichnis")
5432 ("es" :default "Indice de Listados de programas")
5433 ("fr" :default "Liste des programmes")
5434 ("no" :default "Dataprogrammer")
5435 ("nb" :default "Dataprogrammer")
5436 ("zh-CN" :html "&#20195;&#30721;&#30446;&#24405;" :utf-8 "代码目录"))
5437 ("List of Tables"
5438 ("da" :default "Tabeller")
5439 ("de" :default "Tabellenverzeichnis")
5440 ("es" :default "Indice de tablas")
5441 ("fr" :default "Liste des tableaux")
5442 ("no" :default "Tabeller")
5443 ("nb" :default "Tabeller")
5444 ("nn" :default "Tabeller")
5445 ("sv" :default "Tabeller")
5446 ("zh-CN" :html "&#34920;&#26684;&#30446;&#24405;" :utf-8 "表格目录"))
5447 ("Listing %d:"
5448 ("da" :default "Program %d")
5449 ("de" :default "Programmlisting %d")
5450 ("es" :default "Listado de programa %d")
5451 ("fr" :default "Programme %d :" :html "Programme&nbsp;%d&nbsp;:")
5452 ("no" :default "Dataprogram")
5453 ("nb" :default "Dataprogram")
5454 ("zh-CN" :html "&#20195;&#30721;%d&nbsp;" :utf-8 "代码%d "))
5455 ("See section %s"
5456 ("da" :default "jævnfør afsnit %s")
5457 ("de" :default "siehe Abschnitt %s")
5458 ("es" :default "vea seccion %s")
5459 ("fr" :default "cf. section %s")
5460 ("zh-CN" :html "&#21442;&#35265;&#31532;%d&#33410;" :utf-8 "参见第%s节"))
5461 ("Table"
5462 ("de" :default "Tabelle")
5463 ("es" :default "Tabla")
5464 ("fr" :default "Tableau")
5465 ("ja" :html "&#34920;" :utf-8 "表")
5466 ("zh-CN" :html "&#34920;" :utf-8 "表"))
5467 ("Table %d:"
5468 ("da" :default "Tabel %d")
5469 ("de" :default "Tabelle %d")
5470 ("es" :default "Tabla %d")
5471 ("fr" :default "Tableau %d :")
5472 ("ja" :html "&#34920;%d:" :utf-8 "表%d:")
5473 ("no" :default "Tabell %d")
5474 ("nb" :default "Tabell %d")
5475 ("nn" :default "Tabell %d")
5476 ("sv" :default "Tabell %d")
5477 ("zh-CN" :html "&#34920;%d&nbsp;" :utf-8 "表%d "))
5478 ("Table of Contents"
5479 ("ca" :html "&Iacute;ndex")
5480 ("cs" :default "Obsah")
5481 ("da" :default "Indhold")
5482 ("de" :default "Inhaltsverzeichnis")
5483 ("eo" :default "Enhavo")
5484 ("es" :html "&Iacute;ndice")
5485 ("fi" :html "Sis&auml;llysluettelo")
5486 ("fr" :ascii "Sommaire" :default "Table des matières")
5487 ("hu" :html "Tartalomjegyz&eacute;k")
5488 ("is" :default "Efnisyfirlit")
5489 ("it" :default "Indice")
5490 ("ja" :html "&#30446;&#27425;" :utf-8 "目次")
5491 ("nl" :default "Inhoudsopgave")
5492 ("no" :default "Innhold")
5493 ("nb" :default "Innhold")
5494 ("nn" :default "Innhald")
5495 ("pl" :html "Spis tre&#x015b;ci")
5496 ("ru" :html "&#1057;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1077;"
5497 :utf-8 "Содержание")
5498 ("sv" :html "Inneh&aring;ll")
5499 ("uk" :html "&#1047;&#1084;&#1110;&#1089;&#1090;" :utf-8 "Зміст")
5500 ("zh-CN" :html "&#30446;&#24405;" :utf-8 "目录")
5501 ("zh-TW" :html "&#30446;&#37636;" :utf-8 "目錄"))
5502 ("Unknown reference"
5503 ("da" :default "ukendt reference")
5504 ("de" :default "Unbekannter Verweis")
5505 ("es" :default "referencia desconocida")
5506 ("fr" :ascii "Destination inconnue" :default "Référence inconnue")
5507 ("zh-CN" :html "&#26410;&#30693;&#24341;&#29992;" :utf-8 "未知引用")))
5508 "Dictionary for export engine.
5510 Alist whose CAR is the string to translate and CDR is an alist
5511 whose CAR is the language string and CDR is a plist whose
5512 properties are possible charsets and values translated terms.
5514 It is used as a database for `org-export-translate'. Since this
5515 function returns the string as-is if no translation was found,
5516 the variable only needs to record values different from the
5517 entry.")
5519 (defun org-export-translate (s encoding info)
5520 "Translate string S according to language specification.
5522 ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1'
5523 and `:utf-8'. INFO is a plist used as a communication channel.
5525 Translation depends on `:language' property. Return the
5526 translated string. If no translation is found, try to fall back
5527 to `:default' encoding. If it fails, return S."
5528 (let* ((lang (plist-get info :language))
5529 (translations (cdr (assoc lang
5530 (cdr (assoc s org-export-dictionary))))))
5531 (or (plist-get translations encoding)
5532 (plist-get translations :default)
5533 s)))
5537 ;;; Asynchronous Export
5539 ;; `org-export-async-start' is the entry point for asynchronous
5540 ;; export. It recreates current buffer (including visibility,
5541 ;; narrowing and visited file) in an external Emacs process, and
5542 ;; evaluates a command there. It then applies a function on the
5543 ;; returned results in the current process.
5545 ;; Asynchronously generated results are never displayed directly.
5546 ;; Instead, they are stored in `org-export-stack-contents'. They can
5547 ;; then be retrieved by calling `org-export-stack'.
5549 ;; Export Stack is viewed through a dedicated major mode
5550 ;;`org-export-stack-mode' and tools: `org-export-stack-refresh',
5551 ;;`org-export-stack-delete', `org-export-stack-view' and
5552 ;;`org-export-stack-clear'.
5554 ;; For back-ends, `org-export-add-to-stack' add a new source to stack.
5555 ;; It should used whenever `org-export-async-start' is called.
5557 (defmacro org-export-async-start (fun &rest body)
5558 "Call function FUN on the results returned by BODY evaluation.
5560 BODY evaluation happens in an asynchronous process, from a buffer
5561 which is an exact copy of the current one.
5563 Use `org-export-add-to-stack' in FUN in order to register results
5564 in the stack. Examples for, respectively a temporary buffer and
5565 a file are:
5567 \(org-export-async-start
5568 \(lambda (output)
5569 \(with-current-buffer (get-buffer-create \"*Org BACKEND Export*\")
5570 \(erase-buffer)
5571 \(insert output)
5572 \(goto-char (point-min))
5573 \(org-export-add-to-stack (current-buffer) 'backend)))
5574 `(org-export-as 'backend ,subtreep ,visible-only ,body-only ',ext-plist))
5578 \(org-export-async-start
5579 \(lambda (f) (org-export-add-to-stack f 'backend))
5580 `(expand-file-name
5581 \(org-export-to-file
5582 'backend ,outfile ,subtreep ,visible-only ,body-only ',ext-plist)))"
5583 (declare (indent 1) (debug t))
5584 (org-with-gensyms (process temp-file copy-fun proc-buffer handler coding)
5585 ;; Write the full sexp evaluating BODY in a copy of the current
5586 ;; buffer to a temporary file, as it may be too long for program
5587 ;; args in `start-process'.
5588 `(with-temp-message "Initializing asynchronous export process"
5589 (let ((,copy-fun (org-export--generate-copy-script (current-buffer)))
5590 (,temp-file (make-temp-file "org-export-process"))
5591 (,coding buffer-file-coding-system))
5592 (with-temp-file ,temp-file
5593 (insert
5594 ;; Null characters (from variable values) are inserted
5595 ;; within the file. As a consequence, coding system for
5596 ;; buffer contents will not be recognized properly. So,
5597 ;; we make sure it is the same as the one used to display
5598 ;; the original buffer.
5599 (format ";; -*- coding: %s; -*-\n%S"
5600 ,coding
5601 `(with-temp-buffer
5602 ,(when org-export-async-debug '(setq debug-on-error t))
5603 ;; Ignore `kill-emacs-hook' and code evaluation
5604 ;; queries from Babel as we need a truly
5605 ;; non-interactive process.
5606 (setq kill-emacs-hook nil
5607 org-babel-confirm-evaluate-answer-no t)
5608 ;; Initialize export framework.
5609 (require 'ox)
5610 ;; Re-create current buffer there.
5611 (funcall ,,copy-fun)
5612 (restore-buffer-modified-p nil)
5613 ;; Sexp to evaluate in the buffer.
5614 (print (progn ,,@body))))))
5615 ;; Start external process.
5616 (let* ((process-connection-type nil)
5617 (,proc-buffer (generate-new-buffer-name "*Org Export Process*"))
5618 (,process
5619 (start-process
5620 "org-export-process" ,proc-buffer
5621 (expand-file-name invocation-name invocation-directory)
5622 "-Q" "--batch"
5623 "-l" org-export-async-init-file
5624 "-l" ,temp-file)))
5625 ;; Register running process in stack.
5626 (org-export-add-to-stack (get-buffer ,proc-buffer) nil ,process)
5627 ;; Set-up sentinel in order to catch results.
5628 (set-process-sentinel
5629 ,process
5630 (let ((handler ',fun))
5631 `(lambda (p status)
5632 (let ((proc-buffer (process-buffer p)))
5633 (when (eq (process-status p) 'exit)
5634 (unwind-protect
5635 (if (zerop (process-exit-status p))
5636 (unwind-protect
5637 (let ((results
5638 (with-current-buffer proc-buffer
5639 (goto-char (point-max))
5640 (backward-sexp)
5641 (read (current-buffer)))))
5642 (funcall ,handler results))
5643 (unless org-export-async-debug
5644 (and (get-buffer proc-buffer)
5645 (kill-buffer proc-buffer))))
5646 (org-export-add-to-stack proc-buffer nil p)
5647 (ding)
5648 (message "Process '%s' exited abnormally" p))
5649 (unless org-export-async-debug
5650 (delete-file ,,temp-file)))))))))))))
5652 (defun org-export-add-to-stack (source backend &optional process)
5653 "Add a new result to export stack if not present already.
5655 SOURCE is a buffer or a file name containing export results.
5656 BACKEND is a symbol representing export back-end used to generate
5659 Entries already pointing to SOURCE and unavailable entries are
5660 removed beforehand. Return the new stack."
5661 (setq org-export-stack-contents
5662 (cons (list source backend (or process (current-time)))
5663 (org-export-stack-remove source))))
5665 (defun org-export-stack ()
5666 "Menu for asynchronous export results and running processes."
5667 (interactive)
5668 (let ((buffer (get-buffer-create "*Org Export Stack*")))
5669 (set-buffer buffer)
5670 (when (zerop (buffer-size)) (org-export-stack-mode))
5671 (org-export-stack-refresh)
5672 (pop-to-buffer buffer))
5673 (message "Type \"q\" to quit, \"?\" for help"))
5675 (defun org-export--stack-source-at-point ()
5676 "Return source from export results at point in stack."
5677 (let ((source (car (nth (1- (org-current-line)) org-export-stack-contents))))
5678 (if (not source) (error "Source unavailable, please refresh buffer")
5679 (let ((source-name (if (stringp source) source (buffer-name source))))
5680 (if (save-excursion
5681 (beginning-of-line)
5682 (looking-at (concat ".* +" (regexp-quote source-name) "$")))
5683 source
5684 ;; SOURCE is not consistent with current line. The stack
5685 ;; view is outdated.
5686 (error "Source unavailable; type `g' to update buffer"))))))
5688 (defun org-export-stack-clear ()
5689 "Remove all entries from export stack."
5690 (interactive)
5691 (setq org-export-stack-contents nil))
5693 (defun org-export-stack-refresh (&rest dummy)
5694 "Refresh the asynchronous export stack.
5695 DUMMY is ignored. Unavailable sources are removed from the list.
5696 Return the new stack."
5697 (let ((inhibit-read-only t))
5698 (org-preserve-lc
5699 (erase-buffer)
5700 (insert (concat
5701 (let ((counter 0))
5702 (mapconcat
5703 (lambda (entry)
5704 (let ((proc-p (processp (nth 2 entry))))
5705 (concat
5706 ;; Back-end.
5707 (format " %-12s " (or (nth 1 entry) ""))
5708 ;; Age.
5709 (let ((data (nth 2 entry)))
5710 (if proc-p (format " %6s " (process-status data))
5711 ;; Compute age of the results.
5712 (org-format-seconds
5713 "%4h:%.2m "
5714 (float-time (time-since data)))))
5715 ;; Source.
5716 (format " %s"
5717 (let ((source (car entry)))
5718 (if (stringp source) source
5719 (buffer-name source)))))))
5720 ;; Clear stack from exited processes, dead buffers or
5721 ;; non-existent files.
5722 (setq org-export-stack-contents
5723 (org-remove-if-not
5724 (lambda (el)
5725 (if (processp (nth 2 el))
5726 (buffer-live-p (process-buffer (nth 2 el)))
5727 (let ((source (car el)))
5728 (if (bufferp source) (buffer-live-p source)
5729 (file-exists-p source)))))
5730 org-export-stack-contents)) "\n")))))))
5732 (defun org-export-stack-remove (&optional source)
5733 "Remove export results at point from stack.
5734 If optional argument SOURCE is non-nil, remove it instead."
5735 (interactive)
5736 (let ((source (or source (org-export--stack-source-at-point))))
5737 (setq org-export-stack-contents
5738 (org-remove-if (lambda (el) (equal (car el) source))
5739 org-export-stack-contents))))
5741 (defun org-export-stack-view (&optional in-emacs)
5742 "View export results at point in stack.
5743 With an optional prefix argument IN-EMACS, force viewing files
5744 within Emacs."
5745 (interactive "P")
5746 (let ((source (org-export--stack-source-at-point)))
5747 (cond ((processp source)
5748 (org-switch-to-buffer-other-window (process-buffer source)))
5749 ((bufferp source) (org-switch-to-buffer-other-window source))
5750 (t (org-open-file source in-emacs)))))
5752 (defconst org-export-stack-mode-map
5753 (let ((km (make-sparse-keymap)))
5754 (define-key km " " 'next-line)
5755 (define-key km "n" 'next-line)
5756 (define-key km "\C-n" 'next-line)
5757 (define-key km [down] 'next-line)
5758 (define-key km "p" 'previous-line)
5759 (define-key km "\C-p" 'previous-line)
5760 (define-key km "\C-?" 'previous-line)
5761 (define-key km [up] 'previous-line)
5762 (define-key km "C" 'org-export-stack-clear)
5763 (define-key km "v" 'org-export-stack-view)
5764 (define-key km (kbd "RET") 'org-export-stack-view)
5765 (define-key km "d" 'org-export-stack-remove)
5767 "Keymap for Org Export Stack.")
5769 (define-derived-mode org-export-stack-mode special-mode "Org-Stack"
5770 "Mode for displaying asynchronous export stack.
5772 Type \\[org-export-stack] to visualize the asynchronous export
5773 stack.
5775 In an Org Export Stack buffer, use \\<org-export-stack-mode-map>\\[org-export-stack-view] to view export output
5776 on current line, \\[org-export-stack-remove] to remove it from the stack and \\[org-export-stack-clear] to clear
5777 stack completely.
5779 Removing entries in an Org Export Stack buffer doesn't affect
5780 files or buffers, only the display.
5782 \\{org-export-stack-mode-map}"
5783 (abbrev-mode 0)
5784 (auto-fill-mode 0)
5785 (setq buffer-read-only t
5786 buffer-undo-list t
5787 truncate-lines t
5788 header-line-format
5789 '(:eval
5790 (format " %-12s | %6s | %s" "Back-End" "Age" "Source")))
5791 (org-add-hook 'post-command-hook 'org-export-stack-refresh nil t)
5792 (set (make-local-variable 'revert-buffer-function)
5793 'org-export-stack-refresh))
5797 ;;; The Dispatcher
5799 ;; `org-export-dispatch' is the standard interactive way to start an
5800 ;; export process. It uses `org-export--dispatch-ui' as a subroutine
5801 ;; for its interface, which, in turn, delegates response to key
5802 ;; pressed to `org-export--dispatch-action'.
5804 ;;;###autoload
5805 (defun org-export-dispatch (&optional arg)
5806 "Export dispatcher for Org mode.
5808 It provides an access to common export related tasks in a buffer.
5809 Its interface comes in two flavours: standard and expert.
5811 While both share the same set of bindings, only the former
5812 displays the valid keys associations in a dedicated buffer.
5813 Scrolling (resp. line-wise motion) in this buffer is done with
5814 SPC and DEL (resp. C-n and C-p) keys.
5816 Set variable `org-export-dispatch-use-expert-ui' to switch to one
5817 flavour or the other.
5819 When ARG is \\[universal-argument], repeat the last export action, with the same set
5820 of options used back then, on the current buffer.
5822 When ARG is \\[universal-argument] \\[universal-argument], display the asynchronous export stack."
5823 (interactive "P")
5824 (let* ((input
5825 (cond ((equal arg '(16)) '(stack))
5826 ((and arg org-export-dispatch-last-action))
5827 (t (save-window-excursion
5828 (unwind-protect
5829 (progn
5830 ;; Remember where we are
5831 (move-marker org-export-dispatch-last-position
5832 (point)
5833 (org-base-buffer (current-buffer)))
5834 ;; Get and store an export command
5835 (setq org-export-dispatch-last-action
5836 (org-export--dispatch-ui
5837 (list org-export-initial-scope
5838 (and org-export-in-background 'async))
5840 org-export-dispatch-use-expert-ui)))
5841 (and (get-buffer "*Org Export Dispatcher*")
5842 (kill-buffer "*Org Export Dispatcher*")))))))
5843 (action (car input))
5844 (optns (cdr input)))
5845 (unless (memq 'subtree optns)
5846 (move-marker org-export-dispatch-last-position nil))
5847 (case action
5848 ;; First handle special hard-coded actions.
5849 (template (org-export-insert-default-template nil optns))
5850 (stack (org-export-stack))
5851 (publish-current-file
5852 (org-publish-current-file (memq 'force optns) (memq 'async optns)))
5853 (publish-current-project
5854 (org-publish-current-project (memq 'force optns) (memq 'async optns)))
5855 (publish-choose-project
5856 (org-publish (assoc (org-icompleting-read
5857 "Publish project: "
5858 org-publish-project-alist nil t)
5859 org-publish-project-alist)
5860 (memq 'force optns)
5861 (memq 'async optns)))
5862 (publish-all (org-publish-all (memq 'force optns) (memq 'async optns)))
5863 (otherwise
5864 (save-excursion
5865 (when arg
5866 ;; Repeating command, maybe move cursor to restore subtree
5867 ;; context.
5868 (if (eq (marker-buffer org-export-dispatch-last-position)
5869 (org-base-buffer (current-buffer)))
5870 (goto-char org-export-dispatch-last-position)
5871 ;; We are in a different buffer, forget position.
5872 (move-marker org-export-dispatch-last-position nil)))
5873 (funcall action
5874 ;; Return a symbol instead of a list to ease
5875 ;; asynchronous export macro use.
5876 (and (memq 'async optns) t)
5877 (and (memq 'subtree optns) t)
5878 (and (memq 'visible optns) t)
5879 (and (memq 'body optns) t)))))))
5881 (defun org-export--dispatch-ui (options first-key expertp)
5882 "Handle interface for `org-export-dispatch'.
5884 OPTIONS is a list containing current interactive options set for
5885 export. It can contain any of the following symbols:
5886 `body' toggles a body-only export
5887 `subtree' restricts export to current subtree
5888 `visible' restricts export to visible part of buffer.
5889 `force' force publishing files.
5890 `async' use asynchronous export process
5892 FIRST-KEY is the key pressed to select the first level menu. It
5893 is nil when this menu hasn't been selected yet.
5895 EXPERTP, when non-nil, triggers expert UI. In that case, no help
5896 buffer is provided, but indications about currently active
5897 options are given in the prompt. Moreover, \[?] allows to switch
5898 back to standard interface."
5899 (let* ((fontify-key
5900 (lambda (key &optional access-key)
5901 ;; Fontify KEY string. Optional argument ACCESS-KEY, when
5902 ;; non-nil is the required first-level key to activate
5903 ;; KEY. When its value is t, activate KEY independently
5904 ;; on the first key, if any. A nil value means KEY will
5905 ;; only be activated at first level.
5906 (if (or (eq access-key t) (eq access-key first-key))
5907 (org-propertize key 'face 'org-warning)
5908 key)))
5909 (fontify-value
5910 (lambda (value)
5911 ;; Fontify VALUE string.
5912 (org-propertize value 'face 'font-lock-variable-name-face)))
5913 ;; Prepare menu entries by extracting them from registered
5914 ;; back-ends and sorting them by access key and by ordinal,
5915 ;; if any.
5916 (entries
5917 (sort (sort (delq nil
5918 (mapcar 'org-export-backend-menu
5919 org-export--registered-backends))
5920 (lambda (a b)
5921 (let ((key-a (nth 1 a))
5922 (key-b (nth 1 b)))
5923 (cond ((and (numberp key-a) (numberp key-b))
5924 (< key-a key-b))
5925 ((numberp key-b) t)))))
5926 'car-less-than-car))
5927 ;; Compute a list of allowed keys based on the first key
5928 ;; pressed, if any. Some keys
5929 ;; (?^B, ?^V, ?^S, ?^F, ?^A, ?&, ?# and ?q) are always
5930 ;; available.
5931 (allowed-keys
5932 (nconc (list 2 22 19 6 1)
5933 (if (not first-key) (org-uniquify (mapcar 'car entries))
5934 (let (sub-menu)
5935 (dolist (entry entries (sort (mapcar 'car sub-menu) '<))
5936 (when (eq (car entry) first-key)
5937 (setq sub-menu (append (nth 2 entry) sub-menu))))))
5938 (cond ((eq first-key ?P) (list ?f ?p ?x ?a))
5939 ((not first-key) (list ?P)))
5940 (list ?& ?#)
5941 (when expertp (list ??))
5942 (list ?q)))
5943 ;; Build the help menu for standard UI.
5944 (help
5945 (unless expertp
5946 (concat
5947 ;; Options are hard-coded.
5948 (format "[%s] Body only: %s [%s] Visible only: %s
5949 \[%s] Export scope: %s [%s] Force publishing: %s
5950 \[%s] Async export: %s\n\n"
5951 (funcall fontify-key "C-b" t)
5952 (funcall fontify-value
5953 (if (memq 'body options) "On " "Off"))
5954 (funcall fontify-key "C-v" t)
5955 (funcall fontify-value
5956 (if (memq 'visible options) "On " "Off"))
5957 (funcall fontify-key "C-s" t)
5958 (funcall fontify-value
5959 (if (memq 'subtree options) "Subtree" "Buffer "))
5960 (funcall fontify-key "C-f" t)
5961 (funcall fontify-value
5962 (if (memq 'force options) "On " "Off"))
5963 (funcall fontify-key "C-a" t)
5964 (funcall fontify-value
5965 (if (memq 'async options) "On " "Off")))
5966 ;; Display registered back-end entries. When a key
5967 ;; appears for the second time, do not create another
5968 ;; entry, but append its sub-menu to existing menu.
5969 (let (last-key)
5970 (mapconcat
5971 (lambda (entry)
5972 (let ((top-key (car entry)))
5973 (concat
5974 (unless (eq top-key last-key)
5975 (setq last-key top-key)
5976 (format "\n[%s] %s\n"
5977 (funcall fontify-key (char-to-string top-key))
5978 (nth 1 entry)))
5979 (let ((sub-menu (nth 2 entry)))
5980 (unless (functionp sub-menu)
5981 ;; Split sub-menu into two columns.
5982 (let ((index -1))
5983 (concat
5984 (mapconcat
5985 (lambda (sub-entry)
5986 (incf index)
5987 (format
5988 (if (zerop (mod index 2)) " [%s] %-26s"
5989 "[%s] %s\n")
5990 (funcall fontify-key
5991 (char-to-string (car sub-entry))
5992 top-key)
5993 (nth 1 sub-entry)))
5994 sub-menu "")
5995 (when (zerop (mod index 2)) "\n"))))))))
5996 entries ""))
5997 ;; Publishing menu is hard-coded.
5998 (format "\n[%s] Publish
5999 [%s] Current file [%s] Current project
6000 [%s] Choose project [%s] All projects\n\n\n"
6001 (funcall fontify-key "P")
6002 (funcall fontify-key "f" ?P)
6003 (funcall fontify-key "p" ?P)
6004 (funcall fontify-key "x" ?P)
6005 (funcall fontify-key "a" ?P))
6006 (format "[%s] Export stack [%s] Insert template\n"
6007 (funcall fontify-key "&" t)
6008 (funcall fontify-key "#" t))
6009 (format "[%s] %s"
6010 (funcall fontify-key "q" t)
6011 (if first-key "Main menu" "Exit")))))
6012 ;; Build prompts for both standard and expert UI.
6013 (standard-prompt (unless expertp "Export command: "))
6014 (expert-prompt
6015 (when expertp
6016 (format
6017 "Export command (C-%s%s%s%s%s) [%s]: "
6018 (if (memq 'body options) (funcall fontify-key "b" t) "b")
6019 (if (memq 'visible options) (funcall fontify-key "v" t) "v")
6020 (if (memq 'subtree options) (funcall fontify-key "s" t) "s")
6021 (if (memq 'force options) (funcall fontify-key "f" t) "f")
6022 (if (memq 'async options) (funcall fontify-key "a" t) "a")
6023 (mapconcat (lambda (k)
6024 ;; Strip control characters.
6025 (unless (< k 27) (char-to-string k)))
6026 allowed-keys "")))))
6027 ;; With expert UI, just read key with a fancy prompt. In standard
6028 ;; UI, display an intrusive help buffer.
6029 (if expertp
6030 (org-export--dispatch-action
6031 expert-prompt allowed-keys entries options first-key expertp)
6032 ;; At first call, create frame layout in order to display menu.
6033 (unless (get-buffer "*Org Export Dispatcher*")
6034 (delete-other-windows)
6035 (org-switch-to-buffer-other-window
6036 (get-buffer-create "*Org Export Dispatcher*"))
6037 (setq cursor-type nil
6038 header-line-format "Use SPC, DEL, C-n or C-p to navigate.")
6039 ;; Make sure that invisible cursor will not highlight square
6040 ;; brackets.
6041 (set-syntax-table (copy-syntax-table))
6042 (modify-syntax-entry ?\[ "w"))
6043 ;; At this point, the buffer containing the menu exists and is
6044 ;; visible in the current window. So, refresh it.
6045 (with-current-buffer "*Org Export Dispatcher*"
6046 ;; Refresh help. Maintain display continuity by re-visiting
6047 ;; previous window position.
6048 (let ((pos (window-start)))
6049 (erase-buffer)
6050 (insert help)
6051 (set-window-start nil pos)))
6052 (org-fit-window-to-buffer)
6053 (org-export--dispatch-action
6054 standard-prompt allowed-keys entries options first-key expertp))))
6056 (defun org-export--dispatch-action
6057 (prompt allowed-keys entries options first-key expertp)
6058 "Read a character from command input and act accordingly.
6060 PROMPT is the displayed prompt, as a string. ALLOWED-KEYS is
6061 a list of characters available at a given step in the process.
6062 ENTRIES is a list of menu entries. OPTIONS, FIRST-KEY and
6063 EXPERTP are the same as defined in `org-export--dispatch-ui',
6064 which see.
6066 Toggle export options when required. Otherwise, return value is
6067 a list with action as CAR and a list of interactive export
6068 options as CDR."
6069 (let (key)
6070 ;; Scrolling: when in non-expert mode, act on motion keys (C-n,
6071 ;; C-p, SPC, DEL).
6072 (while (and (setq key (read-char-exclusive prompt))
6073 (not expertp)
6074 (memq key '(14 16 ?\s ?\d)))
6075 (case key
6076 (14 (if (not (pos-visible-in-window-p (point-max)))
6077 (ignore-errors (scroll-up-line))
6078 (message "End of buffer")
6079 (sit-for 1)))
6080 (16 (if (not (pos-visible-in-window-p (point-min)))
6081 (ignore-errors (scroll-down-line))
6082 (message "Beginning of buffer")
6083 (sit-for 1)))
6084 (?\s (if (not (pos-visible-in-window-p (point-max)))
6085 (scroll-up nil)
6086 (message "End of buffer")
6087 (sit-for 1)))
6088 (?\d (if (not (pos-visible-in-window-p (point-min)))
6089 (scroll-down nil)
6090 (message "Beginning of buffer")
6091 (sit-for 1)))))
6092 (cond
6093 ;; Ignore undefined associations.
6094 ((not (memq key allowed-keys))
6095 (ding)
6096 (unless expertp (message "Invalid key") (sit-for 1))
6097 (org-export--dispatch-ui options first-key expertp))
6098 ;; q key at first level aborts export. At second level, cancel
6099 ;; first key instead.
6100 ((eq key ?q) (if (not first-key) (error "Export aborted")
6101 (org-export--dispatch-ui options nil expertp)))
6102 ;; Help key: Switch back to standard interface if expert UI was
6103 ;; active.
6104 ((eq key ??) (org-export--dispatch-ui options first-key nil))
6105 ;; Send request for template insertion along with export scope.
6106 ((eq key ?#) (cons 'template (memq 'subtree options)))
6107 ;; Switch to asynchronous export stack.
6108 ((eq key ?&) '(stack))
6109 ;; Toggle options: C-b (2) C-v (22) C-s (19) C-f (6) C-a (1).
6110 ((memq key '(2 22 19 6 1))
6111 (org-export--dispatch-ui
6112 (let ((option (case key (2 'body) (22 'visible) (19 'subtree)
6113 (6 'force) (1 'async))))
6114 (if (memq option options) (remq option options)
6115 (cons option options)))
6116 first-key expertp))
6117 ;; Action selected: Send key and options back to
6118 ;; `org-export-dispatch'.
6119 ((or first-key (functionp (nth 2 (assq key entries))))
6120 (cons (cond
6121 ((not first-key) (nth 2 (assq key entries)))
6122 ;; Publishing actions are hard-coded. Send a special
6123 ;; signal to `org-export-dispatch'.
6124 ((eq first-key ?P)
6125 (case key
6126 (?f 'publish-current-file)
6127 (?p 'publish-current-project)
6128 (?x 'publish-choose-project)
6129 (?a 'publish-all)))
6130 ;; Return first action associated to FIRST-KEY + KEY
6131 ;; path. Indeed, derived backends can share the same
6132 ;; FIRST-KEY.
6133 (t (catch 'found
6134 (mapc (lambda (entry)
6135 (let ((match (assq key (nth 2 entry))))
6136 (when match (throw 'found (nth 2 match)))))
6137 (member (assq first-key entries) entries)))))
6138 options))
6139 ;; Otherwise, enter sub-menu.
6140 (t (org-export--dispatch-ui options key expertp)))))
6144 (provide 'ox)
6146 ;; Local variables:
6147 ;; generated-autoload-file: "org-loaddefs.el"
6148 ;; End:
6150 ;;; ox.el ends here