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