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