abc301207ee2afb95c825ab8041f4a89cc6a705a
[org-mode.git] / lisp / ox.el
blobabc301207ee2afb95c825ab8041f4a89cc6a705a
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 :: symbol
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-file' :: Full path to input file, if any.
1337 ;; - category :: option
1338 ;; - type :: string or nil
1340 ;; + `:keywords' :: List of keywords attached to data.
1341 ;; - category :: option
1342 ;; - type :: string
1344 ;; + `:language' :: Default language used for translations.
1345 ;; - category :: option
1346 ;; - type :: string
1348 ;; + `:parse-tree' :: Whole parse tree, available at any time during
1349 ;; transcoding.
1350 ;; - category :: option
1351 ;; - type :: list (as returned by `org-element-parse-buffer')
1353 ;; + `:preserve-breaks' :: Non-nil means transcoding should preserve
1354 ;; all line breaks.
1355 ;; - category :: option
1356 ;; - type :: symbol (nil, t)
1358 ;; + `:section-numbers' :: Non-nil means transcoding should add
1359 ;; section numbers to headlines.
1360 ;; - category :: option
1361 ;; - type :: symbol (nil, t)
1363 ;; + `:select-tags' :: List of tags enforcing inclusion of sub-trees
1364 ;; in transcoding. When such a tag is present, subtrees without
1365 ;; it are de facto excluded from the process. See
1366 ;; `use-select-tags'.
1367 ;; - category :: option
1368 ;; - type :: list of strings
1370 ;; + `:time-stamp-file' :: Non-nil means transcoding should insert
1371 ;; a time stamp in the output.
1372 ;; - category :: option
1373 ;; - type :: symbol (nil, t)
1375 ;; + `:translate-alist' :: Alist between element and object types and
1376 ;; transcoding functions relative to the current back-end.
1377 ;; Special keys `inner-template', `template' and `plain-text' are
1378 ;; also possible.
1379 ;; - category :: option
1380 ;; - type :: alist (SYMBOL . FUNCTION)
1382 ;; + `:with-archived-trees' :: Non-nil when archived subtrees should
1383 ;; also be transcoded. If it is set to the `headline' symbol,
1384 ;; only the archived headline's name is retained.
1385 ;; - category :: option
1386 ;; - type :: symbol (nil, t, `headline')
1388 ;; + `:with-author' :: Non-nil means author's name should be included
1389 ;; in the output.
1390 ;; - category :: option
1391 ;; - type :: symbol (nil, t)
1393 ;; + `:with-clocks' :: Non-nil means clock keywords should be exported.
1394 ;; - category :: option
1395 ;; - type :: symbol (nil, t)
1397 ;; + `:with-creator' :: Non-nil means a creation sentence should be
1398 ;; inserted at the end of the transcoded string. If the value
1399 ;; is `comment', it should be commented.
1400 ;; - category :: option
1401 ;; - type :: symbol (`comment', nil, t)
1403 ;; + `:with-date' :: Non-nil means output should contain a date.
1404 ;; - category :: option
1405 ;; - type :. symbol (nil, t)
1407 ;; + `:with-drawers' :: Non-nil means drawers should be exported. If
1408 ;; its value is a list of names, only drawers with such names
1409 ;; will be transcoded. If that list starts with `not', drawer
1410 ;; with these names will be skipped.
1411 ;; - category :: option
1412 ;; - type :: symbol (nil, t) or list of strings
1414 ;; + `:with-email' :: Non-nil means output should contain author's
1415 ;; email.
1416 ;; - category :: option
1417 ;; - type :: symbol (nil, t)
1419 ;; + `:with-emphasize' :: Non-nil means emphasized text should be
1420 ;; interpreted.
1421 ;; - category :: option
1422 ;; - type :: symbol (nil, t)
1424 ;; + `:with-fixed-width' :: Non-nil if transcoder should interpret
1425 ;; strings starting with a colon as a fixed-with (verbatim) area.
1426 ;; - category :: option
1427 ;; - type :: symbol (nil, t)
1429 ;; + `:with-footnotes' :: Non-nil if transcoder should interpret
1430 ;; footnotes.
1431 ;; - category :: option
1432 ;; - type :: symbol (nil, t)
1434 ;; + `:with-latex' :: Non-nil means `latex-environment' elements and
1435 ;; `latex-fragment' objects should appear in export output. When
1436 ;; this property is set to `verbatim', they will be left as-is.
1437 ;; - category :: option
1438 ;; - type :: symbol (`verbatim', nil, t)
1440 ;; + `:with-planning' :: Non-nil means transcoding should include
1441 ;; planning info.
1442 ;; - category :: option
1443 ;; - type :: symbol (nil, t)
1445 ;; + `:with-priority' :: Non-nil means transcoding should include
1446 ;; priority cookies.
1447 ;; - category :: option
1448 ;; - type :: symbol (nil, t)
1450 ;; + `:with-smart-quotes' :: Non-nil means activate smart quotes in
1451 ;; plain text.
1452 ;; - category :: option
1453 ;; - type :: symbol (nil, t)
1455 ;; + `:with-special-strings' :: Non-nil means transcoding should
1456 ;; interpret special strings in plain text.
1457 ;; - category :: option
1458 ;; - type :: symbol (nil, t)
1460 ;; + `:with-sub-superscript' :: Non-nil means transcoding should
1461 ;; interpret subscript and superscript. With a value of "{}",
1462 ;; only interpret those using curly brackets.
1463 ;; - category :: option
1464 ;; - type :: symbol (nil, {}, t)
1466 ;; + `:with-tables' :: Non-nil means transcoding should interpret
1467 ;; tables.
1468 ;; - category :: option
1469 ;; - type :: symbol (nil, t)
1471 ;; + `:with-tags' :: Non-nil means transcoding should keep tags in
1472 ;; headlines. A `not-in-toc' value will remove them from the
1473 ;; table of contents, if any, nonetheless.
1474 ;; - category :: option
1475 ;; - type :: symbol (nil, t, `not-in-toc')
1477 ;; + `:with-tasks' :: Non-nil means transcoding should include
1478 ;; headlines with a TODO keyword. A `todo' value will only
1479 ;; include headlines with a todo type keyword while a `done'
1480 ;; value will do the contrary. If a list of strings is provided,
1481 ;; only tasks with keywords belonging to that list will be kept.
1482 ;; - category :: option
1483 ;; - type :: symbol (t, todo, done, nil) or list of strings
1485 ;; + `:with-timestamps' :: Non-nil means transcoding should include
1486 ;; time stamps. Special value `active' (resp. `inactive') ask to
1487 ;; export only active (resp. inactive) timestamps. Otherwise,
1488 ;; completely remove them.
1489 ;; - category :: option
1490 ;; - type :: symbol: (`active', `inactive', t, nil)
1492 ;; + `:with-toc' :: Non-nil means that a table of contents has to be
1493 ;; added to the output. An integer value limits its depth.
1494 ;; - category :: option
1495 ;; - type :: symbol (nil, t or integer)
1497 ;; + `:with-todo-keywords' :: Non-nil means transcoding should
1498 ;; include TODO keywords.
1499 ;; - category :: option
1500 ;; - type :: symbol (nil, t)
1503 ;;;; Environment Options
1505 ;; Environment options encompass all parameters defined outside the
1506 ;; scope of the parsed data. They come from five sources, in
1507 ;; increasing precedence order:
1509 ;; - Global variables,
1510 ;; - Buffer's attributes,
1511 ;; - Options keyword symbols,
1512 ;; - Buffer keywords,
1513 ;; - Subtree properties.
1515 ;; The central internal function with regards to environment options
1516 ;; is `org-export-get-environment'. It updates global variables with
1517 ;; "#+BIND:" keywords, then retrieve and prioritize properties from
1518 ;; the different sources.
1520 ;; The internal functions doing the retrieval are:
1521 ;; `org-export--get-global-options',
1522 ;; `org-export--get-buffer-attributes',
1523 ;; `org-export--parse-option-keyword',
1524 ;; `org-export--get-subtree-options' and
1525 ;; `org-export--get-inbuffer-options'
1527 ;; Also, `org-export--list-bound-variables' collects bound variables
1528 ;; along with their value in order to set them as buffer local
1529 ;; variables later in the process.
1531 (defun org-export-get-environment (&optional backend subtreep ext-plist)
1532 "Collect export options from the current buffer.
1534 Optional argument BACKEND is an export back-end, as returned by
1535 `org-export-create-backend'.
1537 When optional argument SUBTREEP is non-nil, assume the export is
1538 done against the current sub-tree.
1540 Third optional argument EXT-PLIST is a property list with
1541 external parameters overriding Org default settings, but still
1542 inferior to file-local settings."
1543 ;; First install #+BIND variables since these must be set before
1544 ;; global options are read.
1545 (dolist (pair (org-export--list-bound-variables))
1546 (org-set-local (car pair) (nth 1 pair)))
1547 ;; Get and prioritize export options...
1548 (org-combine-plists
1549 ;; ... from global variables...
1550 (org-export--get-global-options backend)
1551 ;; ... from an external property list...
1552 ext-plist
1553 ;; ... from in-buffer settings...
1554 (org-export--get-inbuffer-options backend)
1555 ;; ... and from subtree, when appropriate.
1556 (and subtreep (org-export--get-subtree-options backend))
1557 ;; Eventually add misc. properties.
1558 (list
1559 :back-end
1560 backend
1561 :translate-alist (org-export-get-all-transcoders backend)
1562 :footnote-definition-alist
1563 ;; Footnotes definitions must be collected in the original
1564 ;; buffer, as there's no insurance that they will still be in
1565 ;; the parse tree, due to possible narrowing.
1566 (let (alist)
1567 (org-with-wide-buffer
1568 (goto-char (point-min))
1569 (while (re-search-forward org-footnote-definition-re nil t)
1570 (let ((def (save-match-data (org-element-at-point))))
1571 (when (eq (org-element-type def) 'footnote-definition)
1572 (push
1573 (cons (org-element-property :label def)
1574 (let ((cbeg (org-element-property :contents-begin def)))
1575 (when cbeg
1576 (org-element--parse-elements
1577 cbeg (org-element-property :contents-end def)
1578 nil nil nil nil (list 'org-data nil)))))
1579 alist))))
1580 alist))
1581 :id-alist
1582 ;; Collect id references.
1583 (let (alist)
1584 (org-with-wide-buffer
1585 (goto-char (point-min))
1586 (while (re-search-forward "\\[\\[id:\\S-+?\\]" nil t)
1587 (let ((link (org-element-context)))
1588 (when (eq (org-element-type link) 'link)
1589 (let* ((id (org-element-property :path link))
1590 (file (org-id-find-id-file id)))
1591 (when file
1592 (push (cons id (file-relative-name file)) alist)))))))
1593 alist))))
1595 (defun org-export--parse-option-keyword (options &optional backend)
1596 "Parse an OPTIONS line and return values as a plist.
1597 Optional argument BACKEND is an export back-end, as returned by,
1598 e.g., `org-export-create-backend'. It specifies which back-end
1599 specific items to read, if any."
1600 (let* ((all
1601 ;; Priority is given to back-end specific options.
1602 (append (and backend (org-export-get-all-options backend))
1603 org-export-options-alist))
1604 plist)
1605 (dolist (option all)
1606 (let ((property (car option))
1607 (item (nth 2 option)))
1608 (when (and item
1609 (not (plist-member plist property))
1610 (string-match (concat "\\(\\`\\|[ \t]\\)"
1611 (regexp-quote item)
1612 ":\\(([^)\n]+)\\|[^ \t\n\r;,.]*\\)")
1613 options))
1614 (setq plist (plist-put plist
1615 property
1616 (car (read-from-string
1617 (match-string 2 options))))))))
1618 plist))
1620 (defun org-export--get-subtree-options (&optional backend)
1621 "Get export options in subtree at point.
1622 Optional argument BACKEND is an export back-end, as returned by,
1623 e.g., `org-export-create-backend'. It specifies back-end used
1624 for export. Return options as a plist."
1625 ;; For each buffer keyword, create a headline property setting the
1626 ;; same property in communication channel. The name for the property
1627 ;; is the keyword with "EXPORT_" appended to it.
1628 (org-with-wide-buffer
1629 (let (prop plist)
1630 ;; Make sure point is at a heading.
1631 (if (org-at-heading-p) (org-up-heading-safe) (org-back-to-heading t))
1632 ;; Take care of EXPORT_TITLE. If it isn't defined, use headline's
1633 ;; title as its fallback value.
1634 (when (setq prop (or (org-entry-get (point) "EXPORT_TITLE")
1635 (progn (looking-at org-todo-line-regexp)
1636 (org-match-string-no-properties 3))))
1637 (setq plist
1638 (plist-put
1639 plist :title
1640 (org-element-parse-secondary-string
1641 prop (org-element-restriction 'keyword)))))
1642 ;; EXPORT_OPTIONS are parsed in a non-standard way.
1643 (when (setq prop (org-entry-get (point) "EXPORT_OPTIONS"))
1644 (setq plist
1645 (nconc plist (org-export--parse-option-keyword prop backend))))
1646 ;; Handle other keywords. TITLE keyword is excluded as it has
1647 ;; been handled already.
1648 (let ((seen '("TITLE")))
1649 (mapc
1650 (lambda (option)
1651 (let ((property (car option))
1652 (keyword (nth 1 option)))
1653 (when (and keyword (not (member keyword seen)))
1654 (let* ((subtree-prop (concat "EXPORT_" keyword))
1655 ;; Export properties are not case-sensitive.
1656 (value (let ((case-fold-search t))
1657 (org-entry-get (point) subtree-prop))))
1658 (push keyword seen)
1659 (when (and value (not (plist-member plist property)))
1660 (setq plist
1661 (plist-put
1662 plist
1663 property
1664 (cond
1665 ;; Parse VALUE if required.
1666 ((member keyword org-element-document-properties)
1667 (org-element-parse-secondary-string
1668 value (org-element-restriction 'keyword)))
1669 ;; If BEHAVIOUR is `split' expected value is
1670 ;; a list of strings, not a string.
1671 ((eq (nth 4 option) 'split) (org-split-string value))
1672 (t value)))))))))
1673 ;; Look for both general keywords and back-end specific
1674 ;; options, with priority given to the latter.
1675 (append (and backend (org-export-get-all-options backend))
1676 org-export-options-alist)))
1677 ;; Return value.
1678 plist)))
1680 (defun org-export--get-inbuffer-options (&optional backend)
1681 "Return current buffer export options, as a plist.
1683 Optional argument BACKEND, when non-nil, is an export back-end,
1684 as returned by, e.g., `org-export-create-backend'. It specifies
1685 which back-end specific options should also be read in the
1686 process.
1688 Assume buffer is in Org mode. Narrowing, if any, is ignored."
1689 (let* (plist
1690 get-options ; For byte-compiler.
1691 (case-fold-search t)
1692 (options (append
1693 ;; Priority is given to back-end specific options.
1694 (and backend (org-export-get-all-options backend))
1695 org-export-options-alist))
1696 (regexp (format "^[ \t]*#\\+%s:"
1697 (regexp-opt (nconc (delq nil (mapcar 'cadr options))
1698 org-export-special-keywords))))
1699 (find-properties
1700 (lambda (keyword)
1701 ;; Return all properties associated to KEYWORD.
1702 (let (properties)
1703 (dolist (option options properties)
1704 (when (equal (nth 1 option) keyword)
1705 (pushnew (car option) properties))))))
1706 (get-options
1707 (lambda (&optional files plist)
1708 ;; Recursively read keywords in buffer. FILES is a list
1709 ;; of files read so far. PLIST is the current property
1710 ;; list obtained.
1711 (org-with-wide-buffer
1712 (goto-char (point-min))
1713 (while (re-search-forward regexp nil t)
1714 (let ((element (org-element-at-point)))
1715 (when (eq (org-element-type element) 'keyword)
1716 (let ((key (org-element-property :key element))
1717 (val (org-element-property :value element)))
1718 (cond
1719 ;; Options in `org-export-special-keywords'.
1720 ((equal key "SETUPFILE")
1721 (let ((file (expand-file-name
1722 (org-remove-double-quotes (org-trim val)))))
1723 ;; Avoid circular dependencies.
1724 (unless (member file files)
1725 (with-temp-buffer
1726 (insert (org-file-contents file 'noerror))
1727 (let ((org-inhibit-startup t)) (org-mode))
1728 (setq plist (funcall get-options
1729 (cons file files) plist))))))
1730 ((equal key "OPTIONS")
1731 (setq plist
1732 (org-combine-plists
1733 plist
1734 (org-export--parse-option-keyword val backend))))
1735 ((equal key "FILETAGS")
1736 (setq plist
1737 (org-combine-plists
1738 plist
1739 (list :filetags
1740 (org-uniquify
1741 (append (org-split-string val ":")
1742 (plist-get plist :filetags)))))))
1744 ;; Options in `org-export-options-alist'.
1745 (dolist (property (funcall find-properties key))
1746 (let ((behaviour (nth 4 (assq property options))))
1747 (setq plist
1748 (plist-put
1749 plist property
1750 ;; Handle value depending on specified
1751 ;; BEHAVIOUR.
1752 (case behaviour
1753 (space
1754 (if (not (plist-get plist property))
1755 (org-trim val)
1756 (concat (plist-get plist property)
1758 (org-trim val))))
1759 (newline
1760 (org-trim
1761 (concat (plist-get plist property)
1762 "\n"
1763 (org-trim val))))
1764 (split `(,@(plist-get plist property)
1765 ,@(org-split-string val)))
1766 ('t val)
1767 (otherwise
1768 (if (not (plist-member plist property)) val
1769 (plist-get plist property))))))))))))))
1770 ;; Return final value.
1771 plist))))
1772 ;; Read options in the current buffer.
1773 (setq plist (funcall get-options
1774 (and buffer-file-name (list buffer-file-name)) nil))
1775 ;; Parse keywords specified in `org-element-document-properties'
1776 ;; and return PLIST.
1777 (dolist (keyword org-element-document-properties plist)
1778 (dolist (property (funcall find-properties keyword))
1779 (let ((value (plist-get plist property)))
1780 (when (stringp value)
1781 (setq plist
1782 (plist-put plist property
1783 (org-element-parse-secondary-string
1784 value (org-element-restriction 'keyword))))))))))
1786 (defun org-export--get-buffer-attributes ()
1787 "Return properties related to buffer attributes, as a plist."
1788 ;; Store full path of input file name, or nil. For internal use.
1789 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
1790 (list :input-file visited-file
1791 :title (if (not visited-file) (buffer-name (buffer-base-buffer))
1792 (file-name-sans-extension
1793 (file-name-nondirectory visited-file))))))
1795 (defun org-export--get-global-options (&optional backend)
1796 "Return global export options as a plist.
1797 Optional argument BACKEND, if non-nil, is an export back-end, as
1798 returned by, e.g., `org-export-create-backend'. It specifies
1799 which back-end specific export options should also be read in the
1800 process."
1801 (let (plist
1802 ;; Priority is given to back-end specific options.
1803 (all (append (and backend (org-export-get-all-options backend))
1804 org-export-options-alist)))
1805 (dolist (cell all plist)
1806 (let ((prop (car cell))
1807 (default-value (nth 3 cell)))
1808 (unless (or (not default-value) (plist-member plist prop))
1809 (setq plist
1810 (plist-put
1811 plist
1812 prop
1813 ;; Eval default value provided. If keyword is
1814 ;; a member of `org-element-document-properties',
1815 ;; parse it as a secondary string before storing it.
1816 (let ((value (eval (nth 3 cell))))
1817 (if (not (stringp value)) value
1818 (let ((keyword (nth 1 cell)))
1819 (if (member keyword org-element-document-properties)
1820 (org-element-parse-secondary-string
1821 value (org-element-restriction 'keyword))
1822 value)))))))))))
1824 (defun org-export--list-bound-variables ()
1825 "Return variables bound from BIND keywords in current buffer.
1826 Also look for BIND keywords in setup files. The return value is
1827 an alist where associations are (VARIABLE-NAME VALUE)."
1828 (when org-export-allow-bind-keywords
1829 (let* (collect-bind ; For byte-compiler.
1830 (collect-bind
1831 (lambda (files alist)
1832 ;; Return an alist between variable names and their
1833 ;; value. FILES is a list of setup files names read so
1834 ;; far, used to avoid circular dependencies. ALIST is
1835 ;; the alist collected so far.
1836 (let ((case-fold-search t))
1837 (org-with-wide-buffer
1838 (goto-char (point-min))
1839 (while (re-search-forward
1840 "^[ \t]*#\\+\\(BIND\\|SETUPFILE\\):" nil t)
1841 (let ((element (org-element-at-point)))
1842 (when (eq (org-element-type element) 'keyword)
1843 (let ((val (org-element-property :value element)))
1844 (if (equal (org-element-property :key element) "BIND")
1845 (push (read (format "(%s)" val)) alist)
1846 ;; Enter setup file.
1847 (let ((file (expand-file-name
1848 (org-remove-double-quotes val))))
1849 (unless (member file files)
1850 (with-temp-buffer
1851 (let ((org-inhibit-startup t)) (org-mode))
1852 (insert (org-file-contents file 'noerror))
1853 (setq alist
1854 (funcall collect-bind
1855 (cons file files)
1856 alist))))))))))
1857 alist)))))
1858 ;; Return value in appropriate order of appearance.
1859 (nreverse (funcall collect-bind nil nil)))))
1862 ;;;; Tree Properties
1864 ;; Tree properties are information extracted from parse tree. They
1865 ;; are initialized at the beginning of the transcoding process by
1866 ;; `org-export-collect-tree-properties'.
1868 ;; Dedicated functions focus on computing the value of specific tree
1869 ;; properties during initialization. Thus,
1870 ;; `org-export--populate-ignore-list' lists elements and objects that
1871 ;; should be skipped during export, `org-export--get-min-level' gets
1872 ;; the minimal exportable level, used as a basis to compute relative
1873 ;; level for headlines. Eventually
1874 ;; `org-export--collect-headline-numbering' builds an alist between
1875 ;; headlines and their numbering.
1877 (defun org-export-collect-tree-properties (data info)
1878 "Extract tree properties from parse tree.
1880 DATA is the parse tree from which information is retrieved. INFO
1881 is a list holding export options.
1883 Following tree properties are set or updated:
1885 `:exported-data' Hash table used to memoize results from
1886 `org-export-data'.
1888 `:footnote-definition-alist' List of footnotes definitions in
1889 original buffer and current parse tree.
1891 `:headline-offset' Offset between true level of headlines and
1892 local level. An offset of -1 means a headline
1893 of level 2 should be considered as a level
1894 1 headline in the context.
1896 `:headline-numbering' Alist of all headlines as key an the
1897 associated numbering as value.
1899 `:ignore-list' List of elements that should be ignored during
1900 export.
1902 Return updated plist."
1903 ;; Install the parse tree in the communication channel, in order to
1904 ;; use `org-export-get-genealogy' and al.
1905 (setq info (plist-put info :parse-tree data))
1906 ;; Get the list of elements and objects to ignore, and put it into
1907 ;; `:ignore-list'. Do not overwrite any user ignore that might have
1908 ;; been done during parse tree filtering.
1909 (setq info
1910 (plist-put info
1911 :ignore-list
1912 (append (org-export--populate-ignore-list data info)
1913 (plist-get info :ignore-list))))
1914 ;; Compute `:headline-offset' in order to be able to use
1915 ;; `org-export-get-relative-level'.
1916 (setq info
1917 (plist-put info
1918 :headline-offset
1919 (- 1 (org-export--get-min-level data info))))
1920 ;; Update footnotes definitions list with definitions in parse tree.
1921 ;; This is required since buffer expansion might have modified
1922 ;; boundaries of footnote definitions contained in the parse tree.
1923 ;; This way, definitions in `footnote-definition-alist' are bound to
1924 ;; match those in the parse tree.
1925 (let ((defs (plist-get info :footnote-definition-alist)))
1926 (org-element-map data 'footnote-definition
1927 (lambda (fn)
1928 (push (cons (org-element-property :label fn)
1929 `(org-data nil ,@(org-element-contents fn)))
1930 defs)))
1931 (setq info (plist-put info :footnote-definition-alist defs)))
1932 ;; Properties order doesn't matter: get the rest of the tree
1933 ;; properties.
1934 (nconc
1935 `(:headline-numbering ,(org-export--collect-headline-numbering data info)
1936 :exported-data ,(make-hash-table :test 'eq :size 4001))
1937 info))
1939 (defun org-export--get-min-level (data options)
1940 "Return minimum exportable headline's level in DATA.
1941 DATA is parsed tree as returned by `org-element-parse-buffer'.
1942 OPTIONS is a plist holding export options."
1943 (catch 'exit
1944 (let ((min-level 10000))
1945 (mapc
1946 (lambda (blob)
1947 (when (and (eq (org-element-type blob) 'headline)
1948 (not (org-element-property :footnote-section-p blob))
1949 (not (memq blob (plist-get options :ignore-list))))
1950 (setq min-level (min (org-element-property :level blob) min-level)))
1951 (when (= min-level 1) (throw 'exit 1)))
1952 (org-element-contents data))
1953 ;; If no headline was found, for the sake of consistency, set
1954 ;; minimum level to 1 nonetheless.
1955 (if (= min-level 10000) 1 min-level))))
1957 (defun org-export--collect-headline-numbering (data options)
1958 "Return numbering of all exportable headlines in a parse tree.
1960 DATA is the parse tree. OPTIONS is the plist holding export
1961 options.
1963 Return an alist whose key is a headline and value is its
1964 associated numbering \(in the shape of a list of numbers\) or nil
1965 for a footnotes section."
1966 (let ((numbering (make-vector org-export-max-depth 0)))
1967 (org-element-map data 'headline
1968 (lambda (headline)
1969 (unless (org-element-property :footnote-section-p headline)
1970 (let ((relative-level
1971 (1- (org-export-get-relative-level headline options))))
1972 (cons
1973 headline
1974 (loop for n across numbering
1975 for idx from 0 to org-export-max-depth
1976 when (< idx relative-level) collect n
1977 when (= idx relative-level) collect (aset numbering idx (1+ n))
1978 when (> idx relative-level) do (aset numbering idx 0))))))
1979 options)))
1981 (defun org-export--populate-ignore-list (data options)
1982 "Return list of elements and objects to ignore during export.
1983 DATA is the parse tree to traverse. OPTIONS is the plist holding
1984 export options."
1985 (let* (walk-data
1986 ;; First find trees containing a select tag, if any.
1987 (selected (org-export--selected-trees data options))
1988 ;; If a select tag is active, also ignore the section before
1989 ;; the first headline, if any.
1990 (ignore (and selected
1991 (let ((first-element (car (org-element-contents data))))
1992 (and (eq (org-element-type first-element) 'section)
1993 first-element))))
1994 (walk-data
1995 (lambda (data)
1996 ;; Collect ignored elements or objects into IGNORE-LIST.
1997 (let ((type (org-element-type data)))
1998 (if (org-export--skip-p data options selected) (push data ignore)
1999 (if (and (eq type 'headline)
2000 (eq (plist-get options :with-archived-trees) 'headline)
2001 (org-element-property :archivedp data))
2002 ;; If headline is archived but tree below has
2003 ;; to be skipped, add it to ignore list.
2004 (dolist (element (org-element-contents data))
2005 (push element ignore))
2006 ;; Move into secondary string, if any.
2007 (let ((sec-prop
2008 (cdr (assq type org-element-secondary-value-alist))))
2009 (when sec-prop
2010 (mapc walk-data (org-element-property sec-prop data))))
2011 ;; Move into recursive objects/elements.
2012 (mapc walk-data (org-element-contents data))))))))
2013 ;; Main call.
2014 (funcall walk-data data)
2015 ;; Return value.
2016 ignore))
2018 (defun org-export--selected-trees (data info)
2019 "Return list of headlines and inlinetasks with a select tag in their tree.
2020 DATA is parsed data as returned by `org-element-parse-buffer'.
2021 INFO is a plist holding export options."
2022 (let* (selected-trees
2023 walk-data ; For byte-compiler.
2024 (walk-data
2025 (function
2026 (lambda (data genealogy)
2027 (let ((type (org-element-type data)))
2028 (cond
2029 ((memq type '(headline inlinetask))
2030 (let ((tags (org-element-property :tags data)))
2031 (if (loop for tag in (plist-get info :select-tags)
2032 thereis (member tag tags))
2033 ;; When a select tag is found, mark full
2034 ;; genealogy and every headline within the tree
2035 ;; as acceptable.
2036 (setq selected-trees
2037 (append
2038 genealogy
2039 (org-element-map data '(headline inlinetask)
2040 'identity)
2041 selected-trees))
2042 ;; If at a headline, continue searching in tree,
2043 ;; recursively.
2044 (when (eq type 'headline)
2045 (mapc (lambda (el)
2046 (funcall walk-data el (cons data genealogy)))
2047 (org-element-contents data))))))
2048 ((or (eq type 'org-data)
2049 (memq type org-element-greater-elements))
2050 (mapc (lambda (el) (funcall walk-data el genealogy))
2051 (org-element-contents data)))))))))
2052 (funcall walk-data data nil)
2053 selected-trees))
2055 (defun org-export--skip-p (blob options selected)
2056 "Non-nil when element or object BLOB should be skipped during export.
2057 OPTIONS is the plist holding export options. SELECTED, when
2058 non-nil, is a list of headlines or inlinetasks belonging to
2059 a tree with a select tag."
2060 (case (org-element-type blob)
2061 (clock (not (plist-get options :with-clocks)))
2062 (drawer
2063 (let ((with-drawers-p (plist-get options :with-drawers)))
2064 (or (not with-drawers-p)
2065 (and (consp with-drawers-p)
2066 ;; If `:with-drawers' value starts with `not', ignore
2067 ;; every drawer whose name belong to that list.
2068 ;; Otherwise, ignore drawers whose name isn't in that
2069 ;; list.
2070 (let ((name (org-element-property :drawer-name blob)))
2071 (if (eq (car with-drawers-p) 'not)
2072 (member-ignore-case name (cdr with-drawers-p))
2073 (not (member-ignore-case name with-drawers-p))))))))
2074 ((footnote-definition footnote-reference)
2075 (not (plist-get options :with-footnotes)))
2076 ((headline inlinetask)
2077 (let ((with-tasks (plist-get options :with-tasks))
2078 (todo (org-element-property :todo-keyword blob))
2079 (todo-type (org-element-property :todo-type blob))
2080 (archived (plist-get options :with-archived-trees))
2081 (tags (org-element-property :tags blob)))
2083 (and (eq (org-element-type blob) 'inlinetask)
2084 (not (plist-get options :with-inlinetasks)))
2085 ;; Ignore subtrees with an exclude tag.
2086 (loop for k in (plist-get options :exclude-tags)
2087 thereis (member k tags))
2088 ;; When a select tag is present in the buffer, ignore any tree
2089 ;; without it.
2090 (and selected (not (memq blob selected)))
2091 ;; Ignore commented sub-trees.
2092 (org-element-property :commentedp blob)
2093 ;; Ignore archived subtrees if `:with-archived-trees' is nil.
2094 (and (not archived) (org-element-property :archivedp blob))
2095 ;; Ignore tasks, if specified by `:with-tasks' property.
2096 (and todo
2097 (or (not with-tasks)
2098 (and (memq with-tasks '(todo done))
2099 (not (eq todo-type with-tasks)))
2100 (and (consp with-tasks) (not (member todo with-tasks))))))))
2101 ((latex-environment latex-fragment) (not (plist-get options :with-latex)))
2102 (node-property
2103 (let ((properties-set (plist-get options :with-properties)))
2104 (cond ((null properties-set) t)
2105 ((consp properties-set)
2106 (not (member-ignore-case (org-element-property :key blob)
2107 properties-set))))))
2108 (planning (not (plist-get options :with-planning)))
2109 (property-drawer (not (plist-get options :with-properties)))
2110 (statistics-cookie (not (plist-get options :with-statistics-cookies)))
2111 (table-cell
2112 (and (org-export-table-has-special-column-p
2113 (org-export-get-parent-table blob))
2114 (not (org-export-get-previous-element blob options))))
2115 (table-row (org-export-table-row-is-special-p blob options))
2116 (timestamp
2117 ;; `:with-timestamps' only applies to isolated timestamps
2118 ;; objects, i.e. timestamp objects in a paragraph containing only
2119 ;; timestamps and whitespaces.
2120 (when (let ((parent (org-export-get-parent-element blob)))
2121 (and (memq (org-element-type parent) '(paragraph verse-block))
2122 (not (org-element-map parent
2123 (cons 'plain-text
2124 (remq 'timestamp org-element-all-objects))
2125 (lambda (obj)
2126 (or (not (stringp obj)) (org-string-nw-p obj)))
2127 options t))))
2128 (case (plist-get options :with-timestamps)
2129 ('nil t)
2130 (active
2131 (not (memq (org-element-property :type blob) '(active active-range))))
2132 (inactive
2133 (not (memq (org-element-property :type blob)
2134 '(inactive inactive-range)))))))))
2137 ;;; The Transcoder
2139 ;; `org-export-data' reads a parse tree (obtained with, i.e.
2140 ;; `org-element-parse-buffer') and transcodes it into a specified
2141 ;; back-end output. It takes care of filtering out elements or
2142 ;; objects according to export options and organizing the output blank
2143 ;; lines and white space are preserved. The function memoizes its
2144 ;; results, so it is cheap to call it within transcoders.
2146 ;; It is possible to modify locally the back-end used by
2147 ;; `org-export-data' or even use a temporary back-end by using
2148 ;; `org-export-data-with-backend'.
2150 ;; Internally, three functions handle the filtering of objects and
2151 ;; elements during the export. In particular,
2152 ;; `org-export-ignore-element' marks an element or object so future
2153 ;; parse tree traversals skip it, `org-export--interpret-p' tells which
2154 ;; elements or objects should be seen as real Org syntax and
2155 ;; `org-export-expand' transforms the others back into their original
2156 ;; shape
2158 ;; `org-export-transcoder' is an accessor returning appropriate
2159 ;; translator function for a given element or object.
2161 (defun org-export-transcoder (blob info)
2162 "Return appropriate transcoder for BLOB.
2163 INFO is a plist containing export directives."
2164 (let ((type (org-element-type blob)))
2165 ;; Return contents only for complete parse trees.
2166 (if (eq type 'org-data) (lambda (blob contents info) contents)
2167 (let ((transcoder (cdr (assq type (plist-get info :translate-alist)))))
2168 (and (functionp transcoder) transcoder)))))
2170 (defun org-export-data (data info)
2171 "Convert DATA into current back-end format.
2173 DATA is a parse tree, an element or an object or a secondary
2174 string. INFO is a plist holding export options.
2176 Return transcoded string."
2177 (let ((memo (gethash data (plist-get info :exported-data) 'no-memo)))
2178 (if (not (eq memo 'no-memo)) memo
2179 (let* ((type (org-element-type data))
2180 (results
2181 (cond
2182 ;; Ignored element/object.
2183 ((memq data (plist-get info :ignore-list)) nil)
2184 ;; Plain text.
2185 ((eq type 'plain-text)
2186 (org-export-filter-apply-functions
2187 (plist-get info :filter-plain-text)
2188 (let ((transcoder (org-export-transcoder data info)))
2189 (if transcoder (funcall transcoder data info) data))
2190 info))
2191 ;; Uninterpreted element/object: change it back to Org
2192 ;; syntax and export again resulting raw string.
2193 ((not (org-export--interpret-p data info))
2194 (org-export-data
2195 (org-export-expand
2196 data
2197 (mapconcat (lambda (blob) (org-export-data blob info))
2198 (org-element-contents data)
2199 ""))
2200 info))
2201 ;; Secondary string.
2202 ((not type)
2203 (mapconcat (lambda (obj) (org-export-data obj info)) data ""))
2204 ;; Element/Object without contents or, as a special case,
2205 ;; headline with archive tag and archived trees restricted
2206 ;; to title only.
2207 ((or (not (org-element-contents data))
2208 (and (eq type 'headline)
2209 (eq (plist-get info :with-archived-trees) 'headline)
2210 (org-element-property :archivedp data)))
2211 (let ((transcoder (org-export-transcoder data info)))
2212 (or (and (functionp transcoder)
2213 (funcall transcoder data nil info))
2214 ;; Export snippets never return a nil value so
2215 ;; that white spaces following them are never
2216 ;; ignored.
2217 (and (eq type 'export-snippet) ""))))
2218 ;; Element/Object with contents.
2220 (let ((transcoder (org-export-transcoder data info)))
2221 (when transcoder
2222 (let* ((greaterp (memq type org-element-greater-elements))
2223 (objectp
2224 (and (not greaterp)
2225 (memq type org-element-recursive-objects)))
2226 (contents
2227 (mapconcat
2228 (lambda (element) (org-export-data element info))
2229 (org-element-contents
2230 (if (or greaterp objectp) data
2231 ;; Elements directly containing objects
2232 ;; must have their indentation normalized
2233 ;; first.
2234 (org-element-normalize-contents
2235 data
2236 ;; When normalizing contents of the first
2237 ;; paragraph in an item or a footnote
2238 ;; definition, ignore first line's
2239 ;; indentation: there is none and it
2240 ;; might be misleading.
2241 (when (eq type 'paragraph)
2242 (let ((parent (org-export-get-parent data)))
2243 (and
2244 (eq (car (org-element-contents parent))
2245 data)
2246 (memq (org-element-type parent)
2247 '(footnote-definition item))))))))
2248 "")))
2249 (funcall transcoder data
2250 (if (not greaterp) contents
2251 (org-element-normalize-string contents))
2252 info))))))))
2253 ;; Final result will be memoized before being returned.
2254 (puthash
2255 data
2256 (cond
2257 ((not results) nil)
2258 ((memq type '(org-data plain-text nil)) results)
2259 ;; Append the same white space between elements or objects as in
2260 ;; the original buffer, and call appropriate filters.
2262 (let ((results
2263 (org-export-filter-apply-functions
2264 (plist-get info (intern (format ":filter-%s" type)))
2265 (let ((post-blank (or (org-element-property :post-blank data)
2266 0)))
2267 (if (memq type org-element-all-elements)
2268 (concat (org-element-normalize-string results)
2269 (make-string post-blank ?\n))
2270 (concat results (make-string post-blank ? ))))
2271 info)))
2272 results)))
2273 (plist-get info :exported-data))))))
2275 (defun org-export-data-with-backend (data backend info)
2276 "Convert DATA into BACKEND format.
2278 DATA is an element, an object, a secondary string or a string.
2279 BACKEND is a symbol. INFO is a plist used as a communication
2280 channel.
2282 Unlike to `org-export-with-backend', this function will
2283 recursively convert DATA using BACKEND translation table."
2284 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
2285 (org-export-data
2286 data
2287 ;; Set-up a new communication channel with translations defined in
2288 ;; BACKEND as the translate table and a new hash table for
2289 ;; memoization.
2290 (org-combine-plists
2291 info
2292 (list :back-end backend
2293 :translate-alist (org-export-get-all-transcoders backend)
2294 ;; Size of the hash table is reduced since this function
2295 ;; will probably be used on small trees.
2296 :exported-data (make-hash-table :test 'eq :size 401)))))
2298 (defun org-export--interpret-p (blob info)
2299 "Non-nil if element or object BLOB should be interpreted during export.
2300 If nil, BLOB will appear as raw Org syntax. Check is done
2301 according to export options INFO, stored as a plist."
2302 (case (org-element-type blob)
2303 ;; ... entities...
2304 (entity (plist-get info :with-entities))
2305 ;; ... emphasis...
2306 ((bold italic strike-through underline)
2307 (plist-get info :with-emphasize))
2308 ;; ... fixed-width areas.
2309 (fixed-width (plist-get info :with-fixed-width))
2310 ;; ... LaTeX environments and fragments...
2311 ((latex-environment latex-fragment)
2312 (let ((with-latex-p (plist-get info :with-latex)))
2313 (and with-latex-p (not (eq with-latex-p 'verbatim)))))
2314 ;; ... sub/superscripts...
2315 ((subscript superscript)
2316 (let ((sub/super-p (plist-get info :with-sub-superscript)))
2317 (if (eq sub/super-p '{})
2318 (org-element-property :use-brackets-p blob)
2319 sub/super-p)))
2320 ;; ... tables...
2321 (table (plist-get info :with-tables))
2322 (otherwise t)))
2324 (defun org-export-expand (blob contents &optional with-affiliated)
2325 "Expand a parsed element or object to its original state.
2327 BLOB is either an element or an object. CONTENTS is its
2328 contents, as a string or nil.
2330 When optional argument WITH-AFFILIATED is non-nil, add affiliated
2331 keywords before output."
2332 (let ((type (org-element-type blob)))
2333 (concat (and with-affiliated (memq type org-element-all-elements)
2334 (org-element--interpret-affiliated-keywords blob))
2335 (funcall (intern (format "org-element-%s-interpreter" type))
2336 blob contents))))
2338 (defun org-export-ignore-element (element info)
2339 "Add ELEMENT to `:ignore-list' in INFO.
2341 Any element in `:ignore-list' will be skipped when using
2342 `org-element-map'. INFO is modified by side effects."
2343 (plist-put info :ignore-list (cons element (plist-get info :ignore-list))))
2347 ;;; The Filter System
2349 ;; Filters allow end-users to tweak easily the transcoded output.
2350 ;; They are the functional counterpart of hooks, as every filter in
2351 ;; a set is applied to the return value of the previous one.
2353 ;; Every set is back-end agnostic. Although, a filter is always
2354 ;; called, in addition to the string it applies to, with the back-end
2355 ;; used as argument, so it's easy for the end-user to add back-end
2356 ;; specific filters in the set. The communication channel, as
2357 ;; a plist, is required as the third argument.
2359 ;; From the developer side, filters sets can be installed in the
2360 ;; process with the help of `org-export-define-backend', which
2361 ;; internally stores filters as an alist. Each association has a key
2362 ;; among the following symbols and a function or a list of functions
2363 ;; as value.
2365 ;; - `:filter-options' applies to the property list containing export
2366 ;; options. Unlike to other filters, functions in this list accept
2367 ;; two arguments instead of three: the property list containing
2368 ;; export options and the back-end. Users can set its value through
2369 ;; `org-export-filter-options-functions' variable.
2371 ;; - `:filter-parse-tree' applies directly to the complete parsed
2372 ;; tree. Users can set it through
2373 ;; `org-export-filter-parse-tree-functions' variable.
2375 ;; - `:filter-final-output' applies to the final transcoded string.
2376 ;; Users can set it with `org-export-filter-final-output-functions'
2377 ;; variable
2379 ;; - `:filter-plain-text' applies to any string not recognized as Org
2380 ;; syntax. `org-export-filter-plain-text-functions' allows users to
2381 ;; configure it.
2383 ;; - `:filter-TYPE' applies on the string returned after an element or
2384 ;; object of type TYPE has been transcoded. A user can modify
2385 ;; `org-export-filter-TYPE-functions'
2387 ;; All filters sets are applied with
2388 ;; `org-export-filter-apply-functions' function. Filters in a set are
2389 ;; applied in a LIFO fashion. It allows developers to be sure that
2390 ;; their filters will be applied first.
2392 ;; Filters properties are installed in communication channel with
2393 ;; `org-export-install-filters' function.
2395 ;; Eventually, two hooks (`org-export-before-processing-hook' and
2396 ;; `org-export-before-parsing-hook') are run at the beginning of the
2397 ;; export process and just before parsing to allow for heavy structure
2398 ;; modifications.
2401 ;;;; Hooks
2403 (defvar org-export-before-processing-hook nil
2404 "Hook run at the beginning of the export process.
2406 This is run before include keywords and macros are expanded and
2407 Babel code blocks executed, on a copy of the original buffer
2408 being exported. Visibility and narrowing are preserved. Point
2409 is at the beginning of the buffer.
2411 Every function in this hook will be called with one argument: the
2412 back-end currently used, as a symbol.")
2414 (defvar org-export-before-parsing-hook nil
2415 "Hook run before parsing an export buffer.
2417 This is run after include keywords and macros have been expanded
2418 and Babel code blocks executed, on a copy of the original buffer
2419 being exported. Visibility and narrowing are preserved. Point
2420 is at the beginning of the buffer.
2422 Every function in this hook will be called with one argument: the
2423 back-end currently used, as a symbol.")
2426 ;;;; Special Filters
2428 (defvar org-export-filter-options-functions nil
2429 "List of functions applied to the export options.
2430 Each filter is called with two arguments: the export options, as
2431 a plist, and the back-end, as a symbol. It must return
2432 a property list containing export options.")
2434 (defvar org-export-filter-parse-tree-functions nil
2435 "List of functions applied to the parsed tree.
2436 Each filter is called with three arguments: the parse tree, as
2437 returned by `org-element-parse-buffer', the back-end, as
2438 a symbol, and the communication channel, as a plist. It must
2439 return the modified parse tree to transcode.")
2441 (defvar org-export-filter-plain-text-functions nil
2442 "List of functions applied to plain text.
2443 Each filter is called with three arguments: a string which
2444 contains no Org syntax, the back-end, as a symbol, and the
2445 communication channel, as a plist. It must return a string or
2446 nil.")
2448 (defvar org-export-filter-final-output-functions nil
2449 "List of functions applied to the transcoded string.
2450 Each filter is called with three arguments: the full transcoded
2451 string, the back-end, as a symbol, and the communication channel,
2452 as a plist. It must return a string that will be used as the
2453 final export output.")
2456 ;;;; Elements Filters
2458 (defvar org-export-filter-babel-call-functions nil
2459 "List of functions applied to a transcoded babel-call.
2460 Each filter is called with three arguments: the transcoded data,
2461 as a string, the back-end, as a symbol, and the communication
2462 channel, as a plist. It must return a string or nil.")
2464 (defvar org-export-filter-center-block-functions nil
2465 "List of functions applied to a transcoded center block.
2466 Each filter is called with three arguments: the transcoded data,
2467 as a string, the back-end, as a symbol, and the communication
2468 channel, as a plist. It must return a string or nil.")
2470 (defvar org-export-filter-clock-functions nil
2471 "List of functions applied to a transcoded clock.
2472 Each filter is called with three arguments: the transcoded data,
2473 as a string, the back-end, as a symbol, and the communication
2474 channel, as a plist. It must return a string or nil.")
2476 (defvar org-export-filter-comment-functions nil
2477 "List of functions applied to a transcoded comment.
2478 Each filter is called with three arguments: the transcoded data,
2479 as a string, the back-end, as a symbol, and the communication
2480 channel, as a plist. It must return a string or nil.")
2482 (defvar org-export-filter-comment-block-functions nil
2483 "List of functions applied to a transcoded comment-block.
2484 Each filter is called with three arguments: the transcoded data,
2485 as a string, the back-end, as a symbol, and the communication
2486 channel, as a plist. It must return a string or nil.")
2488 (defvar org-export-filter-diary-sexp-functions nil
2489 "List of functions applied to a transcoded diary-sexp.
2490 Each filter is called with three arguments: the transcoded data,
2491 as a string, the back-end, as a symbol, and the communication
2492 channel, as a plist. It must return a string or nil.")
2494 (defvar org-export-filter-drawer-functions nil
2495 "List of functions applied to a transcoded drawer.
2496 Each filter is called with three arguments: the transcoded data,
2497 as a string, the back-end, as a symbol, and the communication
2498 channel, as a plist. It must return a string or nil.")
2500 (defvar org-export-filter-dynamic-block-functions nil
2501 "List of functions applied to a transcoded dynamic-block.
2502 Each filter is called with three arguments: the transcoded data,
2503 as a string, the back-end, as a symbol, and the communication
2504 channel, as a plist. It must return a string or nil.")
2506 (defvar org-export-filter-example-block-functions nil
2507 "List of functions applied to a transcoded example-block.
2508 Each filter is called with three arguments: the transcoded data,
2509 as a string, the back-end, as a symbol, and the communication
2510 channel, as a plist. It must return a string or nil.")
2512 (defvar org-export-filter-export-block-functions nil
2513 "List of functions applied to a transcoded export-block.
2514 Each filter is called with three arguments: the transcoded data,
2515 as a string, the back-end, as a symbol, and the communication
2516 channel, as a plist. It must return a string or nil.")
2518 (defvar org-export-filter-fixed-width-functions nil
2519 "List of functions applied to a transcoded fixed-width.
2520 Each filter is called with three arguments: the transcoded data,
2521 as a string, the back-end, as a symbol, and the communication
2522 channel, as a plist. It must return a string or nil.")
2524 (defvar org-export-filter-footnote-definition-functions nil
2525 "List of functions applied to a transcoded footnote-definition.
2526 Each filter is called with three arguments: the transcoded data,
2527 as a string, the back-end, as a symbol, and the communication
2528 channel, as a plist. It must return a string or nil.")
2530 (defvar org-export-filter-headline-functions nil
2531 "List of functions applied to a transcoded headline.
2532 Each filter is called with three arguments: the transcoded data,
2533 as a string, the back-end, as a symbol, and the communication
2534 channel, as a plist. It must return a string or nil.")
2536 (defvar org-export-filter-horizontal-rule-functions nil
2537 "List of functions applied to a transcoded horizontal-rule.
2538 Each filter is called with three arguments: the transcoded data,
2539 as a string, the back-end, as a symbol, and the communication
2540 channel, as a plist. It must return a string or nil.")
2542 (defvar org-export-filter-inlinetask-functions nil
2543 "List of functions applied to a transcoded inlinetask.
2544 Each filter is called with three arguments: the transcoded data,
2545 as a string, the back-end, as a symbol, and the communication
2546 channel, as a plist. It must return a string or nil.")
2548 (defvar org-export-filter-item-functions nil
2549 "List of functions applied to a transcoded item.
2550 Each filter is called with three arguments: the transcoded data,
2551 as a string, the back-end, as a symbol, and the communication
2552 channel, as a plist. It must return a string or nil.")
2554 (defvar org-export-filter-keyword-functions nil
2555 "List of functions applied to a transcoded keyword.
2556 Each filter is called with three arguments: the transcoded data,
2557 as a string, the back-end, as a symbol, and the communication
2558 channel, as a plist. It must return a string or nil.")
2560 (defvar org-export-filter-latex-environment-functions nil
2561 "List of functions applied to a transcoded latex-environment.
2562 Each filter is called with three arguments: the transcoded data,
2563 as a string, the back-end, as a symbol, and the communication
2564 channel, as a plist. It must return a string or nil.")
2566 (defvar org-export-filter-node-property-functions nil
2567 "List of functions applied to a transcoded node-property.
2568 Each filter is called with three arguments: the transcoded data,
2569 as a string, the back-end, as a symbol, and the communication
2570 channel, as a plist. It must return a string or nil.")
2572 (defvar org-export-filter-paragraph-functions nil
2573 "List of functions applied to a transcoded paragraph.
2574 Each filter is called with three arguments: the transcoded data,
2575 as a string, the back-end, as a symbol, and the communication
2576 channel, as a plist. It must return a string or nil.")
2578 (defvar org-export-filter-plain-list-functions nil
2579 "List of functions applied to a transcoded plain-list.
2580 Each filter is called with three arguments: the transcoded data,
2581 as a string, the back-end, as a symbol, and the communication
2582 channel, as a plist. It must return a string or nil.")
2584 (defvar org-export-filter-planning-functions nil
2585 "List of functions applied to a transcoded planning.
2586 Each filter is called with three arguments: the transcoded data,
2587 as a string, the back-end, as a symbol, and the communication
2588 channel, as a plist. It must return a string or nil.")
2590 (defvar org-export-filter-property-drawer-functions nil
2591 "List of functions applied to a transcoded property-drawer.
2592 Each filter is called with three arguments: the transcoded data,
2593 as a string, the back-end, as a symbol, and the communication
2594 channel, as a plist. It must return a string or nil.")
2596 (defvar org-export-filter-quote-block-functions nil
2597 "List of functions applied to a transcoded quote block.
2598 Each filter is called with three arguments: the transcoded quote
2599 data, as a string, the back-end, as a symbol, and the
2600 communication channel, as a plist. It must return a string or
2601 nil.")
2603 (defvar org-export-filter-quote-section-functions nil
2604 "List of functions applied to a transcoded quote-section.
2605 Each filter is called with three arguments: the transcoded data,
2606 as a string, the back-end, as a symbol, and the communication
2607 channel, as a plist. It must return a string or nil.")
2609 (defvar org-export-filter-section-functions nil
2610 "List of functions applied to a transcoded section.
2611 Each filter is called with three arguments: the transcoded data,
2612 as a string, the back-end, as a symbol, and the communication
2613 channel, as a plist. It must return a string or nil.")
2615 (defvar org-export-filter-special-block-functions nil
2616 "List of functions applied to a transcoded special block.
2617 Each filter is called with three arguments: the transcoded data,
2618 as a string, the back-end, as a symbol, and the communication
2619 channel, as a plist. It must return a string or nil.")
2621 (defvar org-export-filter-src-block-functions nil
2622 "List of functions applied to a transcoded src-block.
2623 Each filter is called with three arguments: the transcoded data,
2624 as a string, the back-end, as a symbol, and the communication
2625 channel, as a plist. It must return a string or nil.")
2627 (defvar org-export-filter-table-functions nil
2628 "List of functions applied to a transcoded table.
2629 Each filter is called with three arguments: the transcoded data,
2630 as a string, the back-end, as a symbol, and the communication
2631 channel, as a plist. It must return a string or nil.")
2633 (defvar org-export-filter-table-cell-functions nil
2634 "List of functions applied to a transcoded table-cell.
2635 Each filter is called with three arguments: the transcoded data,
2636 as a string, the back-end, as a symbol, and the communication
2637 channel, as a plist. It must return a string or nil.")
2639 (defvar org-export-filter-table-row-functions nil
2640 "List of functions applied to a transcoded table-row.
2641 Each filter is called with three arguments: the transcoded data,
2642 as a string, the back-end, as a symbol, and the communication
2643 channel, as a plist. It must return a string or nil.")
2645 (defvar org-export-filter-verse-block-functions nil
2646 "List of functions applied to a transcoded verse block.
2647 Each filter is called with three arguments: the transcoded data,
2648 as a string, the back-end, as a symbol, and the communication
2649 channel, as a plist. It must return a string or nil.")
2652 ;;;; Objects Filters
2654 (defvar org-export-filter-bold-functions nil
2655 "List of functions applied to transcoded bold text.
2656 Each filter is called with three arguments: the transcoded data,
2657 as a string, the back-end, as a symbol, and the communication
2658 channel, as a plist. It must return a string or nil.")
2660 (defvar org-export-filter-code-functions nil
2661 "List of functions applied to transcoded code text.
2662 Each filter is called with three arguments: the transcoded data,
2663 as a string, the back-end, as a symbol, and the communication
2664 channel, as a plist. It must return a string or nil.")
2666 (defvar org-export-filter-entity-functions nil
2667 "List of functions applied to a transcoded entity.
2668 Each filter is called with three arguments: the transcoded data,
2669 as a string, the back-end, as a symbol, and the communication
2670 channel, as a plist. It must return a string or nil.")
2672 (defvar org-export-filter-export-snippet-functions nil
2673 "List of functions applied to a transcoded export-snippet.
2674 Each filter is called with three arguments: the transcoded data,
2675 as a string, the back-end, as a symbol, and the communication
2676 channel, as a plist. It must return a string or nil.")
2678 (defvar org-export-filter-footnote-reference-functions nil
2679 "List of functions applied to a transcoded footnote-reference.
2680 Each filter is called with three arguments: the transcoded data,
2681 as a string, the back-end, as a symbol, and the communication
2682 channel, as a plist. It must return a string or nil.")
2684 (defvar org-export-filter-inline-babel-call-functions nil
2685 "List of functions applied to a transcoded inline-babel-call.
2686 Each filter is called with three arguments: the transcoded data,
2687 as a string, the back-end, as a symbol, and the communication
2688 channel, as a plist. It must return a string or nil.")
2690 (defvar org-export-filter-inline-src-block-functions nil
2691 "List of functions applied to a transcoded inline-src-block.
2692 Each filter is called with three arguments: the transcoded data,
2693 as a string, the back-end, as a symbol, and the communication
2694 channel, as a plist. It must return a string or nil.")
2696 (defvar org-export-filter-italic-functions nil
2697 "List of functions applied to transcoded italic text.
2698 Each filter is called with three arguments: the transcoded data,
2699 as a string, the back-end, as a symbol, and the communication
2700 channel, as a plist. It must return a string or nil.")
2702 (defvar org-export-filter-latex-fragment-functions nil
2703 "List of functions applied to a transcoded latex-fragment.
2704 Each filter is called with three arguments: the transcoded data,
2705 as a string, the back-end, as a symbol, and the communication
2706 channel, as a plist. It must return a string or nil.")
2708 (defvar org-export-filter-line-break-functions nil
2709 "List of functions applied to a transcoded line-break.
2710 Each filter is called with three arguments: the transcoded data,
2711 as a string, the back-end, as a symbol, and the communication
2712 channel, as a plist. It must return a string or nil.")
2714 (defvar org-export-filter-link-functions nil
2715 "List of functions applied to a transcoded link.
2716 Each filter is called with three arguments: the transcoded data,
2717 as a string, the back-end, as a symbol, and the communication
2718 channel, as a plist. It must return a string or nil.")
2720 (defvar org-export-filter-radio-target-functions nil
2721 "List of functions applied to a transcoded radio-target.
2722 Each filter is called with three arguments: the transcoded data,
2723 as a string, the back-end, as a symbol, and the communication
2724 channel, as a plist. It must return a string or nil.")
2726 (defvar org-export-filter-statistics-cookie-functions nil
2727 "List of functions applied to a transcoded statistics-cookie.
2728 Each filter is called with three arguments: the transcoded data,
2729 as a string, the back-end, as a symbol, and the communication
2730 channel, as a plist. It must return a string or nil.")
2732 (defvar org-export-filter-strike-through-functions nil
2733 "List of functions applied to transcoded strike-through text.
2734 Each filter is called with three arguments: the transcoded data,
2735 as a string, the back-end, as a symbol, and the communication
2736 channel, as a plist. It must return a string or nil.")
2738 (defvar org-export-filter-subscript-functions nil
2739 "List of functions applied to a transcoded subscript.
2740 Each filter is called with three arguments: the transcoded data,
2741 as a string, the back-end, as a symbol, and the communication
2742 channel, as a plist. It must return a string or nil.")
2744 (defvar org-export-filter-superscript-functions nil
2745 "List of functions applied to a transcoded superscript.
2746 Each filter is called with three arguments: the transcoded data,
2747 as a string, the back-end, as a symbol, and the communication
2748 channel, as a plist. It must return a string or nil.")
2750 (defvar org-export-filter-target-functions nil
2751 "List of functions applied to a transcoded target.
2752 Each filter is called with three arguments: the transcoded data,
2753 as a string, the back-end, as a symbol, and the communication
2754 channel, as a plist. It must return a string or nil.")
2756 (defvar org-export-filter-timestamp-functions nil
2757 "List of functions applied to a transcoded timestamp.
2758 Each filter is called with three arguments: the transcoded data,
2759 as a string, the back-end, as a symbol, and the communication
2760 channel, as a plist. It must return a string or nil.")
2762 (defvar org-export-filter-underline-functions nil
2763 "List of functions applied to transcoded underline text.
2764 Each filter is called with three arguments: the transcoded data,
2765 as a string, the back-end, as a symbol, and the communication
2766 channel, as a plist. It must return a string or nil.")
2768 (defvar org-export-filter-verbatim-functions nil
2769 "List of functions applied to transcoded verbatim text.
2770 Each filter is called with three arguments: the transcoded data,
2771 as a string, the back-end, as a symbol, and the communication
2772 channel, as a plist. It must return a string or nil.")
2775 ;;;; Filters Tools
2777 ;; Internal function `org-export-install-filters' installs filters
2778 ;; hard-coded in back-ends (developer filters) and filters from global
2779 ;; variables (user filters) in the communication channel.
2781 ;; Internal function `org-export-filter-apply-functions' takes care
2782 ;; about applying each filter in order to a given data. It ignores
2783 ;; filters returning a nil value but stops whenever a filter returns
2784 ;; an empty string.
2786 (defun org-export-filter-apply-functions (filters value info)
2787 "Call every function in FILTERS.
2789 Functions are called with arguments VALUE, current export
2790 back-end's name and INFO. A function returning a nil value will
2791 be skipped. If it returns the empty string, the process ends and
2792 VALUE is ignored.
2794 Call is done in a LIFO fashion, to be sure that developer
2795 specified filters, if any, are called first."
2796 (catch 'exit
2797 (let* ((backend (plist-get info :back-end))
2798 (backend-name (and backend (org-export-backend-name backend))))
2799 (dolist (filter filters value)
2800 (let ((result (funcall filter value backend-name info)))
2801 (cond ((not result) value)
2802 ((equal value "") (throw 'exit nil))
2803 (t (setq value result))))))))
2805 (defun org-export-install-filters (info)
2806 "Install filters properties in communication channel.
2807 INFO is a plist containing the current communication channel.
2808 Return the updated communication channel."
2809 (let (plist)
2810 ;; Install user-defined filters with `org-export-filters-alist'
2811 ;; and filters already in INFO (through ext-plist mechanism).
2812 (mapc (lambda (p)
2813 (let* ((prop (car p))
2814 (info-value (plist-get info prop))
2815 (default-value (symbol-value (cdr p))))
2816 (setq plist
2817 (plist-put plist prop
2818 ;; Filters in INFO will be called
2819 ;; before those user provided.
2820 (append (if (listp info-value) info-value
2821 (list info-value))
2822 default-value)))))
2823 org-export-filters-alist)
2824 ;; Prepend back-end specific filters to that list.
2825 (mapc (lambda (p)
2826 ;; Single values get consed, lists are appended.
2827 (let ((key (car p)) (value (cdr p)))
2828 (when value
2829 (setq plist
2830 (plist-put
2831 plist key
2832 (if (atom value) (cons value (plist-get plist key))
2833 (append value (plist-get plist key))))))))
2834 (org-export-get-all-filters (plist-get info :back-end)))
2835 ;; Return new communication channel.
2836 (org-combine-plists info plist)))
2840 ;;; Core functions
2842 ;; This is the room for the main function, `org-export-as', along with
2843 ;; its derivative, `org-export-string-as'.
2844 ;; `org-export--copy-to-kill-ring-p' determines if output of these
2845 ;; function should be added to kill ring.
2847 ;; Note that `org-export-as' doesn't really parse the current buffer,
2848 ;; but a copy of it (with the same buffer-local variables and
2849 ;; visibility), where macros and include keywords are expanded and
2850 ;; Babel blocks are executed, if appropriate.
2851 ;; `org-export-with-buffer-copy' macro prepares that copy.
2853 ;; File inclusion is taken care of by
2854 ;; `org-export-expand-include-keyword' and
2855 ;; `org-export--prepare-file-contents'. Structure wise, including
2856 ;; a whole Org file in a buffer often makes little sense. For
2857 ;; example, if the file contains a headline and the include keyword
2858 ;; was within an item, the item should contain the headline. That's
2859 ;; why file inclusion should be done before any structure can be
2860 ;; associated to the file, that is before parsing.
2862 ;; `org-export-insert-default-template' is a command to insert
2863 ;; a default template (or a back-end specific template) at point or in
2864 ;; current subtree.
2866 (defun org-export-copy-buffer ()
2867 "Return a copy of the current buffer.
2868 The copy preserves Org buffer-local variables, visibility and
2869 narrowing."
2870 (let ((copy-buffer-fun (org-export--generate-copy-script (current-buffer)))
2871 (new-buf (generate-new-buffer (buffer-name))))
2872 (with-current-buffer new-buf
2873 (funcall copy-buffer-fun)
2874 (set-buffer-modified-p nil))
2875 new-buf))
2877 (defmacro org-export-with-buffer-copy (&rest body)
2878 "Apply BODY in a copy of the current buffer.
2879 The copy preserves local variables, visibility and contents of
2880 the original buffer. Point is at the beginning of the buffer
2881 when BODY is applied."
2882 (declare (debug t))
2883 (org-with-gensyms (buf-copy)
2884 `(let ((,buf-copy (org-export-copy-buffer)))
2885 (unwind-protect
2886 (with-current-buffer ,buf-copy
2887 (goto-char (point-min))
2888 (progn ,@body))
2889 (and (buffer-live-p ,buf-copy)
2890 ;; Kill copy without confirmation.
2891 (progn (with-current-buffer ,buf-copy
2892 (restore-buffer-modified-p nil))
2893 (kill-buffer ,buf-copy)))))))
2895 (defun org-export--generate-copy-script (buffer)
2896 "Generate a function duplicating BUFFER.
2898 The copy will preserve local variables, visibility, contents and
2899 narrowing of the original buffer. If a region was active in
2900 BUFFER, contents will be narrowed to that region instead.
2902 The resulting function can be evaled at a later time, from
2903 another buffer, effectively cloning the original buffer there.
2905 The function assumes BUFFER's major mode is `org-mode'."
2906 (with-current-buffer buffer
2907 `(lambda ()
2908 (let ((inhibit-modification-hooks t))
2909 ;; Set major mode. Ignore `org-mode-hook' as it has been run
2910 ;; already in BUFFER.
2911 (let ((org-mode-hook nil) (org-inhibit-startup t)) (org-mode))
2912 ;; Copy specific buffer local variables and variables set
2913 ;; through BIND keywords.
2914 ,@(let ((bound-variables (org-export--list-bound-variables))
2915 vars)
2916 (dolist (entry (buffer-local-variables (buffer-base-buffer)) vars)
2917 (when (consp entry)
2918 (let ((var (car entry))
2919 (val (cdr entry)))
2920 (and (not (eq var 'org-font-lock-keywords))
2921 (or (memq var
2922 '(default-directory
2923 buffer-file-name
2924 buffer-file-coding-system))
2925 (assq var bound-variables)
2926 (string-match "^\\(org-\\|orgtbl-\\)"
2927 (symbol-name var)))
2928 ;; Skip unreadable values, as they cannot be
2929 ;; sent to external process.
2930 (or (not val) (ignore-errors (read (format "%S" val))))
2931 (push `(set (make-local-variable (quote ,var))
2932 (quote ,val))
2933 vars))))))
2934 ;; Whole buffer contents.
2935 (insert
2936 ,(org-with-wide-buffer
2937 (buffer-substring-no-properties
2938 (point-min) (point-max))))
2939 ;; Narrowing.
2940 ,(if (org-region-active-p)
2941 `(narrow-to-region ,(region-beginning) ,(region-end))
2942 `(narrow-to-region ,(point-min) ,(point-max)))
2943 ;; Current position of point.
2944 (goto-char ,(point))
2945 ;; Overlays with invisible property.
2946 ,@(let (ov-set)
2947 (mapc
2948 (lambda (ov)
2949 (let ((invis-prop (overlay-get ov 'invisible)))
2950 (when invis-prop
2951 (push `(overlay-put
2952 (make-overlay ,(overlay-start ov)
2953 ,(overlay-end ov))
2954 'invisible (quote ,invis-prop))
2955 ov-set))))
2956 (overlays-in (point-min) (point-max)))
2957 ov-set)))))
2959 ;;;###autoload
2960 (defun org-export-as
2961 (backend &optional subtreep visible-only body-only ext-plist)
2962 "Transcode current Org buffer into BACKEND code.
2964 BACKEND is either an export back-end, as returned by, e.g.,
2965 `org-export-create-backend', or a symbol referring to
2966 a registered back-end.
2968 If narrowing is active in the current buffer, only transcode its
2969 narrowed part.
2971 If a region is active, transcode that region.
2973 When optional argument SUBTREEP is non-nil, transcode the
2974 sub-tree at point, extracting information from the headline
2975 properties first.
2977 When optional argument VISIBLE-ONLY is non-nil, don't export
2978 contents of hidden elements.
2980 When optional argument BODY-ONLY is non-nil, only return body
2981 code, without surrounding template.
2983 Optional argument EXT-PLIST, when provided, is a property list
2984 with external parameters overriding Org default settings, but
2985 still inferior to file-local settings.
2987 Return code as a string."
2988 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
2989 (org-export-barf-if-invalid-backend backend)
2990 (save-excursion
2991 (save-restriction
2992 ;; Narrow buffer to an appropriate region or subtree for
2993 ;; parsing. If parsing subtree, be sure to remove main headline
2994 ;; too.
2995 (cond ((org-region-active-p)
2996 (narrow-to-region (region-beginning) (region-end)))
2997 (subtreep
2998 (org-narrow-to-subtree)
2999 (goto-char (point-min))
3000 (forward-line)
3001 (narrow-to-region (point) (point-max))))
3002 ;; Initialize communication channel with original buffer
3003 ;; attributes, unavailable in its copy.
3004 (let* ((org-export-current-backend (org-export-backend-name backend))
3005 (info (org-combine-plists
3006 (list :export-options
3007 (delq nil
3008 (list (and subtreep 'subtree)
3009 (and visible-only 'visible-only)
3010 (and body-only 'body-only))))
3011 (org-export--get-buffer-attributes)))
3012 tree)
3013 ;; Update communication channel and get parse tree. Buffer
3014 ;; isn't parsed directly. Instead, a temporary copy is
3015 ;; created, where include keywords, macros are expanded and
3016 ;; code blocks are evaluated.
3017 (org-export-with-buffer-copy
3018 ;; Run first hook with current back-end's name as argument.
3019 (run-hook-with-args 'org-export-before-processing-hook
3020 (org-export-backend-name backend))
3021 (org-export-expand-include-keyword)
3022 ;; Update macro templates since #+INCLUDE keywords might have
3023 ;; added some new ones.
3024 (org-macro-initialize-templates)
3025 (org-macro-replace-all org-macro-templates)
3026 (org-export-execute-babel-code)
3027 ;; Update radio targets since keyword inclusion might have
3028 ;; added some more.
3029 (org-update-radio-target-regexp)
3030 ;; Run last hook with current back-end's name as argument.
3031 (goto-char (point-min))
3032 (save-excursion
3033 (run-hook-with-args 'org-export-before-parsing-hook
3034 (org-export-backend-name backend)))
3035 ;; Update communication channel with environment. Also
3036 ;; install user's and developer's filters.
3037 (setq info
3038 (org-export-install-filters
3039 (org-combine-plists
3040 info (org-export-get-environment backend subtreep ext-plist))))
3041 ;; Expand export-specific set of macros: {{{author}}},
3042 ;; {{{date}}}, {{{email}}} and {{{title}}}. It must be done
3043 ;; once regular macros have been expanded, since document
3044 ;; keywords may contain one of them.
3045 (org-macro-replace-all
3046 (list (cons "author"
3047 (org-element-interpret-data (plist-get info :author)))
3048 (cons "date"
3049 (org-element-interpret-data (plist-get info :date)))
3050 ;; EMAIL is not a parsed keyword: store it as-is.
3051 (cons "email" (or (plist-get info :email) ""))
3052 (cons "title"
3053 (org-element-interpret-data (plist-get info :title)))))
3054 ;; Call options filters and update export options. We do not
3055 ;; use `org-export-filter-apply-functions' here since the
3056 ;; arity of such filters is different.
3057 (let ((backend-name (org-export-backend-name backend)))
3058 (dolist (filter (plist-get info :filter-options))
3059 (let ((result (funcall filter info backend-name)))
3060 (when result (setq info result)))))
3061 ;; Parse buffer and call parse-tree filter on it.
3062 (setq tree
3063 (org-export-filter-apply-functions
3064 (plist-get info :filter-parse-tree)
3065 (org-element-parse-buffer nil visible-only) info))
3066 ;; Now tree is complete, compute its properties and add them
3067 ;; to communication channel.
3068 (setq info
3069 (org-combine-plists
3070 info (org-export-collect-tree-properties tree info)))
3071 ;; Eventually transcode TREE. Wrap the resulting string into
3072 ;; a template.
3073 (let* ((body (org-element-normalize-string
3074 (or (org-export-data tree info) "")))
3075 (inner-template (cdr (assq 'inner-template
3076 (plist-get info :translate-alist))))
3077 (full-body (if (not (functionp inner-template)) body
3078 (funcall inner-template body info)))
3079 (template (cdr (assq 'template
3080 (plist-get info :translate-alist)))))
3081 ;; Remove all text properties since they cannot be
3082 ;; retrieved from an external process. Finally call
3083 ;; final-output filter and return result.
3084 (org-no-properties
3085 (org-export-filter-apply-functions
3086 (plist-get info :filter-final-output)
3087 (if (or (not (functionp template)) body-only) full-body
3088 (funcall template full-body info))
3089 info))))))))
3091 ;;;###autoload
3092 (defun org-export-string-as (string backend &optional body-only ext-plist)
3093 "Transcode STRING into BACKEND code.
3095 BACKEND is either an export back-end, as returned by, e.g.,
3096 `org-export-create-backend', or a symbol referring to
3097 a registered back-end.
3099 When optional argument BODY-ONLY is non-nil, only return body
3100 code, without preamble nor postamble.
3102 Optional argument EXT-PLIST, when provided, is a property list
3103 with external parameters overriding Org default settings, but
3104 still inferior to file-local settings.
3106 Return code as a string."
3107 (with-temp-buffer
3108 (insert string)
3109 (let ((org-inhibit-startup t)) (org-mode))
3110 (org-export-as backend nil nil body-only ext-plist)))
3112 ;;;###autoload
3113 (defun org-export-replace-region-by (backend)
3114 "Replace the active region by its export to BACKEND.
3115 BACKEND is either an export back-end, as returned by, e.g.,
3116 `org-export-create-backend', or a symbol referring to
3117 a registered back-end."
3118 (if (not (org-region-active-p))
3119 (user-error "No active region to replace")
3120 (let* ((beg (region-beginning))
3121 (end (region-end))
3122 (str (buffer-substring beg end)) rpl)
3123 (setq rpl (org-export-string-as str backend t))
3124 (delete-region beg end)
3125 (insert rpl))))
3127 ;;;###autoload
3128 (defun org-export-insert-default-template (&optional backend subtreep)
3129 "Insert all export keywords with default values at beginning of line.
3131 BACKEND is a symbol referring to the name of a registered export
3132 back-end, for which specific export options should be added to
3133 the template, or `default' for default template. When it is nil,
3134 the user will be prompted for a category.
3136 If SUBTREEP is non-nil, export configuration will be set up
3137 locally for the subtree through node properties."
3138 (interactive)
3139 (unless (derived-mode-p 'org-mode) (user-error "Not in an Org mode buffer"))
3140 (when (and subtreep (org-before-first-heading-p))
3141 (user-error "No subtree to set export options for"))
3142 (let ((node (and subtreep (save-excursion (org-back-to-heading t) (point))))
3143 (backend
3144 (or backend
3145 (intern
3146 (org-completing-read
3147 "Options category: "
3148 (cons "default"
3149 (mapcar (lambda (b)
3150 (symbol-name (org-export-backend-name b)))
3151 org-export--registered-backends))))))
3152 options keywords)
3153 ;; Populate OPTIONS and KEYWORDS.
3154 (dolist (entry (cond ((eq backend 'default) org-export-options-alist)
3155 ((org-export-backend-p backend)
3156 (org-export-get-all-options backend))
3157 (t (org-export-get-all-options
3158 (org-export-get-backend backend)))))
3159 (let ((keyword (nth 1 entry))
3160 (option (nth 2 entry)))
3161 (cond
3162 (keyword (unless (assoc keyword keywords)
3163 (let ((value
3164 (if (eq (nth 4 entry) 'split)
3165 (mapconcat 'identity (eval (nth 3 entry)) " ")
3166 (eval (nth 3 entry)))))
3167 (push (cons keyword value) keywords))))
3168 (option (unless (assoc option options)
3169 (push (cons option (eval (nth 3 entry))) options))))))
3170 ;; Move to an appropriate location in order to insert options.
3171 (unless subtreep (beginning-of-line))
3172 ;; First get TITLE, DATE, AUTHOR and EMAIL if they belong to the
3173 ;; list of available keywords.
3174 (when (assoc "TITLE" keywords)
3175 (let ((title
3176 (or (let ((visited-file (buffer-file-name (buffer-base-buffer))))
3177 (and visited-file
3178 (file-name-sans-extension
3179 (file-name-nondirectory visited-file))))
3180 (buffer-name (buffer-base-buffer)))))
3181 (if (not subtreep) (insert (format "#+TITLE: %s\n" title))
3182 (org-entry-put node "EXPORT_TITLE" title))))
3183 (when (assoc "DATE" keywords)
3184 (let ((date (with-temp-buffer (org-insert-time-stamp (current-time)))))
3185 (if (not subtreep) (insert "#+DATE: " date "\n")
3186 (org-entry-put node "EXPORT_DATE" date))))
3187 (when (assoc "AUTHOR" keywords)
3188 (let ((author (cdr (assoc "AUTHOR" keywords))))
3189 (if subtreep (org-entry-put node "EXPORT_AUTHOR" author)
3190 (insert
3191 (format "#+AUTHOR:%s\n"
3192 (if (not (org-string-nw-p author)) ""
3193 (concat " " author)))))))
3194 (when (assoc "EMAIL" keywords)
3195 (let ((email (cdr (assoc "EMAIL" keywords))))
3196 (if subtreep (org-entry-put node "EXPORT_EMAIL" email)
3197 (insert
3198 (format "#+EMAIL:%s\n"
3199 (if (not (org-string-nw-p email)) ""
3200 (concat " " email)))))))
3201 ;; Then (multiple) OPTIONS lines. Never go past fill-column.
3202 (when options
3203 (let ((items
3204 (mapcar
3205 (lambda (opt)
3206 (format "%s:%s" (car opt) (format "%s" (cdr opt))))
3207 (sort options (lambda (k1 k2) (string< (car k1) (car k2)))))))
3208 (if subtreep
3209 (org-entry-put
3210 node "EXPORT_OPTIONS" (mapconcat 'identity items " "))
3211 (while items
3212 (insert "#+OPTIONS:")
3213 (let ((width 10))
3214 (while (and items
3215 (< (+ width (length (car items)) 1) fill-column))
3216 (let ((item (pop items)))
3217 (insert " " item)
3218 (incf width (1+ (length item))))))
3219 (insert "\n")))))
3220 ;; And the rest of keywords.
3221 (dolist (key (sort keywords (lambda (k1 k2) (string< (car k1) (car k2)))))
3222 (unless (member (car key) '("TITLE" "DATE" "AUTHOR" "EMAIL"))
3223 (let ((val (cdr key)))
3224 (if subtreep (org-entry-put node (concat "EXPORT_" (car key)) val)
3225 (insert
3226 (format "#+%s:%s\n"
3227 (car key)
3228 (if (org-string-nw-p val) (format " %s" val) "")))))))))
3230 (defun org-export-expand-include-keyword (&optional included dir)
3231 "Expand every include keyword in buffer.
3232 Optional argument INCLUDED is a list of included file names along
3233 with their line restriction, when appropriate. It is used to
3234 avoid infinite recursion. Optional argument DIR is the current
3235 working directory. It is used to properly resolve relative
3236 paths."
3237 (let ((case-fold-search t))
3238 (goto-char (point-min))
3239 (while (re-search-forward "^[ \t]*#\\+INCLUDE:" nil t)
3240 (let ((element (save-match-data (org-element-at-point))))
3241 (when (eq (org-element-type element) 'keyword)
3242 (beginning-of-line)
3243 ;; Extract arguments from keyword's value.
3244 (let* ((value (org-element-property :value element))
3245 (ind (org-get-indentation))
3246 (file (and (string-match
3247 "^\\(\".+?\"\\|\\S-+\\)\\(?:\\s-+\\|$\\)" value)
3248 (prog1 (expand-file-name
3249 (org-remove-double-quotes
3250 (match-string 1 value))
3251 dir)
3252 (setq value (replace-match "" nil nil value)))))
3253 (lines
3254 (and (string-match
3255 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\""
3256 value)
3257 (prog1 (match-string 1 value)
3258 (setq value (replace-match "" nil nil value)))))
3259 (env (cond ((string-match "\\<example\\>" value) 'example)
3260 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
3261 (match-string 1 value))))
3262 ;; Minimal level of included file defaults to the child
3263 ;; level of the current headline, if any, or one. It
3264 ;; only applies is the file is meant to be included as
3265 ;; an Org one.
3266 (minlevel
3267 (and (not env)
3268 (if (string-match ":minlevel +\\([0-9]+\\)" value)
3269 (prog1 (string-to-number (match-string 1 value))
3270 (setq value (replace-match "" nil nil value)))
3271 (let ((cur (org-current-level)))
3272 (if cur (1+ (org-reduced-level cur)) 1))))))
3273 ;; Remove keyword.
3274 (delete-region (point) (progn (forward-line) (point)))
3275 (cond
3276 ((not file) nil)
3277 ((not (file-readable-p file))
3278 (error "Cannot include file %s" file))
3279 ;; Check if files has already been parsed. Look after
3280 ;; inclusion lines too, as different parts of the same file
3281 ;; can be included too.
3282 ((member (list file lines) included)
3283 (error "Recursive file inclusion: %s" file))
3285 (cond
3286 ((eq env 'example)
3287 (insert
3288 (let ((ind-str (make-string ind ? ))
3289 (contents
3290 (org-escape-code-in-string
3291 (org-export--prepare-file-contents file lines))))
3292 (format "%s#+BEGIN_EXAMPLE\n%s%s#+END_EXAMPLE\n"
3293 ind-str contents ind-str))))
3294 ((stringp env)
3295 (insert
3296 (let ((ind-str (make-string ind ? ))
3297 (contents
3298 (org-escape-code-in-string
3299 (org-export--prepare-file-contents file lines))))
3300 (format "%s#+BEGIN_SRC %s\n%s%s#+END_SRC\n"
3301 ind-str env contents ind-str))))
3303 (insert
3304 (with-temp-buffer
3305 (let ((org-inhibit-startup t)) (org-mode))
3306 (insert
3307 (org-export--prepare-file-contents file lines ind minlevel))
3308 (org-export-expand-include-keyword
3309 (cons (list file lines) included)
3310 (file-name-directory file))
3311 (buffer-string)))))))))))))
3313 (defun org-export--prepare-file-contents (file &optional lines ind minlevel)
3314 "Prepare the contents of FILE for inclusion and return them as a string.
3316 When optional argument LINES is a string specifying a range of
3317 lines, include only those lines.
3319 Optional argument IND, when non-nil, is an integer specifying the
3320 global indentation of returned contents. Since its purpose is to
3321 allow an included file to stay in the same environment it was
3322 created \(i.e. a list item), it doesn't apply past the first
3323 headline encountered.
3325 Optional argument MINLEVEL, when non-nil, is an integer
3326 specifying the level that any top-level headline in the included
3327 file should have."
3328 (with-temp-buffer
3329 (insert-file-contents file)
3330 (when lines
3331 (let* ((lines (split-string lines "-"))
3332 (lbeg (string-to-number (car lines)))
3333 (lend (string-to-number (cadr lines)))
3334 (beg (if (zerop lbeg) (point-min)
3335 (goto-char (point-min))
3336 (forward-line (1- lbeg))
3337 (point)))
3338 (end (if (zerop lend) (point-max)
3339 (goto-char (point-min))
3340 (forward-line (1- lend))
3341 (point))))
3342 (narrow-to-region beg end)))
3343 ;; Remove blank lines at beginning and end of contents. The logic
3344 ;; behind that removal is that blank lines around include keyword
3345 ;; override blank lines in included file.
3346 (goto-char (point-min))
3347 (org-skip-whitespace)
3348 (beginning-of-line)
3349 (delete-region (point-min) (point))
3350 (goto-char (point-max))
3351 (skip-chars-backward " \r\t\n")
3352 (forward-line)
3353 (delete-region (point) (point-max))
3354 ;; If IND is set, preserve indentation of include keyword until
3355 ;; the first headline encountered.
3356 (when ind
3357 (unless (eq major-mode 'org-mode)
3358 (let ((org-inhibit-startup t)) (org-mode)))
3359 (goto-char (point-min))
3360 (let ((ind-str (make-string ind ? )))
3361 (while (not (or (eobp) (looking-at org-outline-regexp-bol)))
3362 ;; Do not move footnote definitions out of column 0.
3363 (unless (and (looking-at org-footnote-definition-re)
3364 (eq (org-element-type (org-element-at-point))
3365 'footnote-definition))
3366 (insert ind-str))
3367 (forward-line))))
3368 ;; When MINLEVEL is specified, compute minimal level for headlines
3369 ;; in the file (CUR-MIN), and remove stars to each headline so
3370 ;; that headlines with minimal level have a level of MINLEVEL.
3371 (when minlevel
3372 (unless (eq major-mode 'org-mode)
3373 (let ((org-inhibit-startup t)) (org-mode)))
3374 (org-with-limited-levels
3375 (let ((levels (org-map-entries
3376 (lambda () (org-reduced-level (org-current-level))))))
3377 (when levels
3378 (let ((offset (- minlevel (apply 'min levels))))
3379 (unless (zerop offset)
3380 (when org-odd-levels-only (setq offset (* offset 2)))
3381 ;; Only change stars, don't bother moving whole
3382 ;; sections.
3383 (org-map-entries
3384 (lambda () (if (< offset 0) (delete-char (abs offset))
3385 (insert (make-string offset ?*)))))))))))
3386 (org-element-normalize-string (buffer-string))))
3388 (defun org-export-execute-babel-code ()
3389 "Execute every Babel code in the visible part of current buffer."
3390 ;; Get a pristine copy of current buffer so Babel references can be
3391 ;; properly resolved.
3392 (let ((reference (org-export-copy-buffer)))
3393 (unwind-protect (let ((org-current-export-file reference))
3394 (org-babel-exp-process-buffer))
3395 (kill-buffer reference))))
3397 (defun org-export--copy-to-kill-ring-p ()
3398 "Return a non-nil value when output should be added to the kill ring.
3399 See also `org-export-copy-to-kill-ring'."
3400 (if (eq org-export-copy-to-kill-ring 'if-interactive)
3401 (not (or executing-kbd-macro noninteractive))
3402 (eq org-export-copy-to-kill-ring t)))
3406 ;;; Tools For Back-Ends
3408 ;; A whole set of tools is available to help build new exporters. Any
3409 ;; function general enough to have its use across many back-ends
3410 ;; should be added here.
3412 ;;;; For Affiliated Keywords
3414 ;; `org-export-read-attribute' reads a property from a given element
3415 ;; as a plist. It can be used to normalize affiliated keywords'
3416 ;; syntax.
3418 ;; Since captions can span over multiple lines and accept dual values,
3419 ;; their internal representation is a bit tricky. Therefore,
3420 ;; `org-export-get-caption' transparently returns a given element's
3421 ;; caption as a secondary string.
3423 (defun org-export-read-attribute (attribute element &optional property)
3424 "Turn ATTRIBUTE property from ELEMENT into a plist.
3426 When optional argument PROPERTY is non-nil, return the value of
3427 that property within attributes.
3429 This function assumes attributes are defined as \":keyword
3430 value\" pairs. It is appropriate for `:attr_html' like
3431 properties.
3433 All values will become strings except the empty string and
3434 \"nil\", which will become nil. Also, values containing only
3435 double quotes will be read as-is, which means that \"\" value
3436 will become the empty string."
3437 (let* ((prepare-value
3438 (lambda (str)
3439 (save-match-data
3440 (cond ((member str '(nil "" "nil")) nil)
3441 ((string-match "^\"\\(\"+\\)?\"$" str)
3442 (or (match-string 1 str) ""))
3443 (t str)))))
3444 (attributes
3445 (let ((value (org-element-property attribute element)))
3446 (when value
3447 (let ((s (mapconcat 'identity value " ")) result)
3448 (while (string-match
3449 "\\(?:^\\|[ \t]+\\)\\(:[-a-zA-Z0-9_]+\\)\\([ \t]+\\|$\\)"
3451 (let ((value (substring s 0 (match-beginning 0))))
3452 (push (funcall prepare-value value) result))
3453 (push (intern (match-string 1 s)) result)
3454 (setq s (substring s (match-end 0))))
3455 ;; Ignore any string before first property with `cdr'.
3456 (cdr (nreverse (cons (funcall prepare-value s) result))))))))
3457 (if property (plist-get attributes property) attributes)))
3459 (defun org-export-get-caption (element &optional shortp)
3460 "Return caption from ELEMENT as a secondary string.
3462 When optional argument SHORTP is non-nil, return short caption,
3463 as a secondary string, instead.
3465 Caption lines are separated by a white space."
3466 (let ((full-caption (org-element-property :caption element)) caption)
3467 (dolist (line full-caption (cdr caption))
3468 (let ((cap (funcall (if shortp 'cdr 'car) line)))
3469 (when cap
3470 (setq caption (nconc (list " ") (copy-sequence cap) caption)))))))
3473 ;;;; For Derived Back-ends
3475 ;; `org-export-with-backend' is a function allowing to locally use
3476 ;; another back-end to transcode some object or element. In a derived
3477 ;; back-end, it may be used as a fall-back function once all specific
3478 ;; cases have been treated.
3480 (defun org-export-with-backend (backend data &optional contents info)
3481 "Call a transcoder from BACKEND on DATA.
3482 BACKEND is an export back-end, as returned by, e.g.,
3483 `org-export-create-backend', or a symbol referring to
3484 a registered back-end. DATA is an Org element, object, secondary
3485 string or string. CONTENTS, when non-nil, is the transcoded
3486 contents of DATA element, as a string. INFO, when non-nil, is
3487 the communication channel used for export, as a plist."
3488 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
3489 (org-export-barf-if-invalid-backend backend)
3490 (let ((type (org-element-type data)))
3491 (if (memq type '(nil org-data)) (error "No foreign transcoder available")
3492 (let* ((all-transcoders (org-export-get-all-transcoders backend))
3493 (transcoder (cdr (assq type all-transcoders))))
3494 (if (not (functionp transcoder))
3495 (error "No foreign transcoder available")
3496 (funcall
3497 transcoder data contents
3498 (org-combine-plists
3499 info (list :back-end backend
3500 :translate-alist all-transcoders
3501 :exported-data (make-hash-table :test 'eq :size 401)))))))))
3504 ;;;; For Export Snippets
3506 ;; Every export snippet is transmitted to the back-end. Though, the
3507 ;; latter will only retain one type of export-snippet, ignoring
3508 ;; others, based on the former's target back-end. The function
3509 ;; `org-export-snippet-backend' returns that back-end for a given
3510 ;; export-snippet.
3512 (defun org-export-snippet-backend (export-snippet)
3513 "Return EXPORT-SNIPPET targeted back-end as a symbol.
3514 Translation, with `org-export-snippet-translation-alist', is
3515 applied."
3516 (let ((back-end (org-element-property :back-end export-snippet)))
3517 (intern
3518 (or (cdr (assoc back-end org-export-snippet-translation-alist))
3519 back-end))))
3522 ;;;; For Footnotes
3524 ;; `org-export-collect-footnote-definitions' is a tool to list
3525 ;; actually used footnotes definitions in the whole parse tree, or in
3526 ;; a headline, in order to add footnote listings throughout the
3527 ;; transcoded data.
3529 ;; `org-export-footnote-first-reference-p' is a predicate used by some
3530 ;; back-ends, when they need to attach the footnote definition only to
3531 ;; the first occurrence of the corresponding label.
3533 ;; `org-export-get-footnote-definition' and
3534 ;; `org-export-get-footnote-number' provide easier access to
3535 ;; additional information relative to a footnote reference.
3537 (defun org-export-collect-footnote-definitions (data info)
3538 "Return an alist between footnote numbers, labels and definitions.
3540 DATA is the parse tree from which definitions are collected.
3541 INFO is the plist used as a communication channel.
3543 Definitions are sorted by order of references. They either
3544 appear as Org data or as a secondary string for inlined
3545 footnotes. Unreferenced definitions are ignored."
3546 (let* (num-alist
3547 collect-fn ; for byte-compiler.
3548 (collect-fn
3549 (function
3550 (lambda (data)
3551 ;; Collect footnote number, label and definition in DATA.
3552 (org-element-map data 'footnote-reference
3553 (lambda (fn)
3554 (when (org-export-footnote-first-reference-p fn info)
3555 (let ((def (org-export-get-footnote-definition fn info)))
3556 (push
3557 (list (org-export-get-footnote-number fn info)
3558 (org-element-property :label fn)
3559 def)
3560 num-alist)
3561 ;; Also search in definition for nested footnotes.
3562 (when (eq (org-element-property :type fn) 'standard)
3563 (funcall collect-fn def)))))
3564 ;; Don't enter footnote definitions since it will happen
3565 ;; when their first reference is found.
3566 info nil 'footnote-definition)))))
3567 (funcall collect-fn (plist-get info :parse-tree))
3568 (reverse num-alist)))
3570 (defun org-export-footnote-first-reference-p (footnote-reference info)
3571 "Non-nil when a footnote reference is the first one for its label.
3573 FOOTNOTE-REFERENCE is the footnote reference being considered.
3574 INFO is the plist used as a communication channel."
3575 (let ((label (org-element-property :label footnote-reference)))
3576 ;; Anonymous footnotes are always a first reference.
3577 (if (not label) t
3578 ;; Otherwise, return the first footnote with the same LABEL and
3579 ;; test if it is equal to FOOTNOTE-REFERENCE.
3580 (let* (search-refs ; for byte-compiler.
3581 (search-refs
3582 (function
3583 (lambda (data)
3584 (org-element-map data 'footnote-reference
3585 (lambda (fn)
3586 (cond
3587 ((string= (org-element-property :label fn) label)
3588 (throw 'exit fn))
3589 ;; If FN isn't inlined, be sure to traverse its
3590 ;; definition before resuming search. See
3591 ;; comments in `org-export-get-footnote-number'
3592 ;; for more information.
3593 ((eq (org-element-property :type fn) 'standard)
3594 (funcall search-refs
3595 (org-export-get-footnote-definition fn info)))))
3596 ;; Don't enter footnote definitions since it will
3597 ;; happen when their first reference is found.
3598 info 'first-match 'footnote-definition)))))
3599 (eq (catch 'exit (funcall search-refs (plist-get info :parse-tree)))
3600 footnote-reference)))))
3602 (defun org-export-get-footnote-definition (footnote-reference info)
3603 "Return definition of FOOTNOTE-REFERENCE as parsed data.
3604 INFO is the plist used as a communication channel. If no such
3605 definition can be found, return the \"DEFINITION NOT FOUND\"
3606 string."
3607 (let ((label (org-element-property :label footnote-reference)))
3608 (or (org-element-property :inline-definition footnote-reference)
3609 (cdr (assoc label (plist-get info :footnote-definition-alist)))
3610 "DEFINITION NOT FOUND.")))
3612 (defun org-export-get-footnote-number (footnote info)
3613 "Return number associated to a footnote.
3615 FOOTNOTE is either a footnote reference or a footnote definition.
3616 INFO is the plist used as a communication channel."
3617 (let* ((label (org-element-property :label footnote))
3618 seen-refs
3619 search-ref ; For byte-compiler.
3620 (search-ref
3621 (function
3622 (lambda (data)
3623 ;; Search footnote references through DATA, filling
3624 ;; SEEN-REFS along the way.
3625 (org-element-map data 'footnote-reference
3626 (lambda (fn)
3627 (let ((fn-lbl (org-element-property :label fn)))
3628 (cond
3629 ;; Anonymous footnote match: return number.
3630 ((and (not fn-lbl) (eq fn footnote))
3631 (throw 'exit (1+ (length seen-refs))))
3632 ;; Labels match: return number.
3633 ((and label (string= label fn-lbl))
3634 (throw 'exit (1+ (length seen-refs))))
3635 ;; Anonymous footnote: it's always a new one.
3636 ;; Also, be sure to return nil from the `cond' so
3637 ;; `first-match' doesn't get us out of the loop.
3638 ((not fn-lbl) (push 'inline seen-refs) nil)
3639 ;; Label not seen so far: add it so SEEN-REFS.
3641 ;; Also search for subsequent references in
3642 ;; footnote definition so numbering follows
3643 ;; reading logic. Note that we don't have to care
3644 ;; about inline definitions, since
3645 ;; `org-element-map' already traverses them at the
3646 ;; right time.
3648 ;; Once again, return nil to stay in the loop.
3649 ((not (member fn-lbl seen-refs))
3650 (push fn-lbl seen-refs)
3651 (funcall search-ref
3652 (org-export-get-footnote-definition fn info))
3653 nil))))
3654 ;; Don't enter footnote definitions since it will
3655 ;; happen when their first reference is found.
3656 info 'first-match 'footnote-definition)))))
3657 (catch 'exit (funcall search-ref (plist-get info :parse-tree)))))
3660 ;;;; For Headlines
3662 ;; `org-export-get-relative-level' is a shortcut to get headline
3663 ;; level, relatively to the lower headline level in the parsed tree.
3665 ;; `org-export-get-headline-number' returns the section number of an
3666 ;; headline, while `org-export-number-to-roman' allows to convert it
3667 ;; to roman numbers.
3669 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
3670 ;; `org-export-last-sibling-p' are three useful predicates when it
3671 ;; comes to fulfill the `:headline-levels' property.
3673 ;; `org-export-get-tags', `org-export-get-category' and
3674 ;; `org-export-get-node-property' extract useful information from an
3675 ;; headline or a parent headline. They all handle inheritance.
3677 ;; `org-export-get-alt-title' tries to retrieve an alternative title,
3678 ;; as a secondary string, suitable for table of contents. It falls
3679 ;; back onto default title.
3681 (defun org-export-get-relative-level (headline info)
3682 "Return HEADLINE relative level within current parsed tree.
3683 INFO is a plist holding contextual information."
3684 (+ (org-element-property :level headline)
3685 (or (plist-get info :headline-offset) 0)))
3687 (defun org-export-low-level-p (headline info)
3688 "Non-nil when HEADLINE is considered as low level.
3690 INFO is a plist used as a communication channel.
3692 A low level headlines has a relative level greater than
3693 `:headline-levels' property value.
3695 Return value is the difference between HEADLINE relative level
3696 and the last level being considered as high enough, or nil."
3697 (let ((limit (plist-get info :headline-levels)))
3698 (when (wholenump limit)
3699 (let ((level (org-export-get-relative-level headline info)))
3700 (and (> level limit) (- level limit))))))
3702 (defun org-export-get-headline-number (headline info)
3703 "Return HEADLINE numbering as a list of numbers.
3704 INFO is a plist holding contextual information."
3705 (cdr (assoc headline (plist-get info :headline-numbering))))
3707 (defun org-export-numbered-headline-p (headline info)
3708 "Return a non-nil value if HEADLINE element should be numbered.
3709 INFO is a plist used as a communication channel."
3710 (let ((sec-num (plist-get info :section-numbers))
3711 (level (org-export-get-relative-level headline info)))
3712 (if (wholenump sec-num) (<= level sec-num) sec-num)))
3714 (defun org-export-number-to-roman (n)
3715 "Convert integer N into a roman numeral."
3716 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
3717 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
3718 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
3719 ( 1 . "I")))
3720 (res ""))
3721 (if (<= n 0)
3722 (number-to-string n)
3723 (while roman
3724 (if (>= n (caar roman))
3725 (setq n (- n (caar roman))
3726 res (concat res (cdar roman)))
3727 (pop roman)))
3728 res)))
3730 (defun org-export-get-tags (element info &optional tags inherited)
3731 "Return list of tags associated to ELEMENT.
3733 ELEMENT has either an `headline' or an `inlinetask' type. INFO
3734 is a plist used as a communication channel.
3736 Select tags (see `org-export-select-tags') and exclude tags (see
3737 `org-export-exclude-tags') are removed from the list.
3739 When non-nil, optional argument TAGS should be a list of strings.
3740 Any tag belonging to this list will also be removed.
3742 When optional argument INHERITED is non-nil, tags can also be
3743 inherited from parent headlines and FILETAGS keywords."
3744 (org-remove-if
3745 (lambda (tag) (or (member tag (plist-get info :select-tags))
3746 (member tag (plist-get info :exclude-tags))
3747 (member tag tags)))
3748 (if (not inherited) (org-element-property :tags element)
3749 ;; Build complete list of inherited tags.
3750 (let ((current-tag-list (org-element-property :tags element)))
3751 (mapc
3752 (lambda (parent)
3753 (mapc
3754 (lambda (tag)
3755 (when (and (memq (org-element-type parent) '(headline inlinetask))
3756 (not (member tag current-tag-list)))
3757 (push tag current-tag-list)))
3758 (org-element-property :tags parent)))
3759 (org-export-get-genealogy element))
3760 ;; Add FILETAGS keywords and return results.
3761 (org-uniquify (append (plist-get info :filetags) current-tag-list))))))
3763 (defun org-export-get-node-property (property blob &optional inherited)
3764 "Return node PROPERTY value for BLOB.
3766 PROPERTY is an upcase symbol (i.e. `:COOKIE_DATA'). BLOB is an
3767 element or object.
3769 If optional argument INHERITED is non-nil, the value can be
3770 inherited from a parent headline.
3772 Return value is a string or nil."
3773 (let ((headline (if (eq (org-element-type blob) 'headline) blob
3774 (org-export-get-parent-headline blob))))
3775 (if (not inherited) (org-element-property property blob)
3776 (let ((parent headline) value)
3777 (catch 'found
3778 (while parent
3779 (when (plist-member (nth 1 parent) property)
3780 (throw 'found (org-element-property property parent)))
3781 (setq parent (org-element-property :parent parent))))))))
3783 (defun org-export-get-category (blob info)
3784 "Return category for element or object BLOB.
3786 INFO is a plist used as a communication channel.
3788 CATEGORY is automatically inherited from a parent headline, from
3789 #+CATEGORY: keyword or created out of original file name. If all
3790 fail, the fall-back value is \"???\"."
3791 (or (let ((headline (if (eq (org-element-type blob) 'headline) blob
3792 (org-export-get-parent-headline blob))))
3793 ;; Almost like `org-export-node-property', but we cannot trust
3794 ;; `plist-member' as every headline has a `:CATEGORY'
3795 ;; property, would it be nil or equal to "???" (which has the
3796 ;; same meaning).
3797 (let ((parent headline) value)
3798 (catch 'found
3799 (while parent
3800 (let ((category (org-element-property :CATEGORY parent)))
3801 (and category (not (equal "???" category))
3802 (throw 'found category)))
3803 (setq parent (org-element-property :parent parent))))))
3804 (org-element-map (plist-get info :parse-tree) 'keyword
3805 (lambda (kwd)
3806 (when (equal (org-element-property :key kwd) "CATEGORY")
3807 (org-element-property :value kwd)))
3808 info 'first-match)
3809 (let ((file (plist-get info :input-file)))
3810 (and file (file-name-sans-extension (file-name-nondirectory file))))
3811 "???"))
3813 (defun org-export-get-alt-title (headline info)
3814 "Return alternative title for HEADLINE, as a secondary string.
3815 INFO is a plist used as a communication channel. If no optional
3816 title is defined, fall-back to the regular title."
3817 (or (org-element-property :alt-title headline)
3818 (org-element-property :title headline)))
3820 (defun org-export-first-sibling-p (headline info)
3821 "Non-nil when HEADLINE is the first sibling in its sub-tree.
3822 INFO is a plist used as a communication channel."
3823 (not (eq (org-element-type (org-export-get-previous-element headline info))
3824 'headline)))
3826 (defun org-export-last-sibling-p (headline info)
3827 "Non-nil when HEADLINE is the last sibling in its sub-tree.
3828 INFO is a plist used as a communication channel."
3829 (not (org-export-get-next-element headline info)))
3832 ;;;; For Keywords
3834 ;; `org-export-get-date' returns a date appropriate for the document
3835 ;; to about to be exported. In particular, it takes care of
3836 ;; `org-export-date-timestamp-format'.
3838 (defun org-export-get-date (info &optional fmt)
3839 "Return date value for the current document.
3841 INFO is a plist used as a communication channel. FMT, when
3842 non-nil, is a time format string that will be applied on the date
3843 if it consists in a single timestamp object. It defaults to
3844 `org-export-date-timestamp-format' when nil.
3846 A proper date can be a secondary string, a string or nil. It is
3847 meant to be translated with `org-export-data' or alike."
3848 (let ((date (plist-get info :date))
3849 (fmt (or fmt org-export-date-timestamp-format)))
3850 (cond ((not date) nil)
3851 ((and fmt
3852 (not (cdr date))
3853 (eq (org-element-type (car date)) 'timestamp))
3854 (org-timestamp-format (car date) fmt))
3855 (t date))))
3858 ;;;; For Links
3860 ;; `org-export-solidify-link-text' turns a string into a safer version
3861 ;; for links, replacing most non-standard characters with hyphens.
3863 ;; `org-export-get-coderef-format' returns an appropriate format
3864 ;; string for coderefs.
3866 ;; `org-export-inline-image-p' returns a non-nil value when the link
3867 ;; provided should be considered as an inline image.
3869 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
3870 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
3871 ;; returns an appropriate unique identifier when found, or nil.
3873 ;; `org-export-resolve-id-link' returns the first headline with
3874 ;; specified id or custom-id in parse tree, the path to the external
3875 ;; file with the id or nil when neither was found.
3877 ;; `org-export-resolve-coderef' associates a reference to a line
3878 ;; number in the element it belongs, or returns the reference itself
3879 ;; when the element isn't numbered.
3881 (defun org-export-solidify-link-text (s)
3882 "Take link text S and make a safe target out of it."
3883 (save-match-data
3884 (mapconcat 'identity (org-split-string s "[^a-zA-Z0-9_.-:]+") "-")))
3886 (defun org-export-get-coderef-format (path desc)
3887 "Return format string for code reference link.
3888 PATH is the link path. DESC is its description."
3889 (save-match-data
3890 (cond ((not desc) "%s")
3891 ((string-match (regexp-quote (concat "(" path ")")) desc)
3892 (replace-match "%s" t t desc))
3893 (t desc))))
3895 (defun org-export-inline-image-p (link &optional rules)
3896 "Non-nil if LINK object points to an inline image.
3898 Optional argument is a set of RULES defining inline images. It
3899 is an alist where associations have the following shape:
3901 \(TYPE . REGEXP)
3903 Applying a rule means apply REGEXP against LINK's path when its
3904 type is TYPE. The function will return a non-nil value if any of
3905 the provided rules is non-nil. The default rule is
3906 `org-export-default-inline-image-rule'.
3908 This only applies to links without a description."
3909 (and (not (org-element-contents link))
3910 (let ((case-fold-search t)
3911 (rules (or rules org-export-default-inline-image-rule)))
3912 (catch 'exit
3913 (mapc
3914 (lambda (rule)
3915 (and (string= (org-element-property :type link) (car rule))
3916 (string-match (cdr rule)
3917 (org-element-property :path link))
3918 (throw 'exit t)))
3919 rules)
3920 ;; Return nil if no rule matched.
3921 nil))))
3923 (defun org-export-resolve-coderef (ref info)
3924 "Resolve a code reference REF.
3926 INFO is a plist used as a communication channel.
3928 Return associated line number in source code, or REF itself,
3929 depending on src-block or example element's switches."
3930 (org-element-map (plist-get info :parse-tree) '(example-block src-block)
3931 (lambda (el)
3932 (with-temp-buffer
3933 (insert (org-trim (org-element-property :value el)))
3934 (let* ((label-fmt (regexp-quote
3935 (or (org-element-property :label-fmt el)
3936 org-coderef-label-format)))
3937 (ref-re
3938 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
3939 (replace-regexp-in-string "%s" ref label-fmt nil t))))
3940 ;; Element containing REF is found. Resolve it to either
3941 ;; a label or a line number, as needed.
3942 (when (re-search-backward ref-re nil t)
3943 (cond
3944 ((org-element-property :use-labels el) ref)
3945 ((eq (org-element-property :number-lines el) 'continued)
3946 (+ (org-export-get-loc el info) (line-number-at-pos)))
3947 (t (line-number-at-pos)))))))
3948 info 'first-match))
3950 (defun org-export-resolve-fuzzy-link (link info)
3951 "Return LINK destination.
3953 INFO is a plist holding contextual information.
3955 Return value can be an object, an element, or nil:
3957 - If LINK path matches a target object (i.e. <<path>>) return it.
3959 - If LINK path exactly matches the name affiliated keyword
3960 \(i.e. #+NAME: path) of an element, return that element.
3962 - If LINK path exactly matches any headline name, return that
3963 element. If more than one headline share that name, priority
3964 will be given to the one with the closest common ancestor, if
3965 any, or the first one in the parse tree otherwise.
3967 - Otherwise, return nil.
3969 Assume LINK type is \"fuzzy\". White spaces are not
3970 significant."
3971 (let* ((raw-path (org-element-property :path link))
3972 (match-title-p (eq (aref raw-path 0) ?*))
3973 ;; Split PATH at white spaces so matches are space
3974 ;; insensitive.
3975 (path (org-split-string
3976 (if match-title-p (substring raw-path 1) raw-path)))
3977 ;; Cache for destinations that are not position dependent.
3978 (link-cache
3979 (or (plist-get info :resolve-fuzzy-link-cache)
3980 (plist-get (setq info (plist-put info :resolve-fuzzy-link-cache
3981 (make-hash-table :test 'equal)))
3982 :resolve-fuzzy-link-cache)))
3983 (cached (gethash path link-cache 'not-found)))
3984 (cond
3985 ;; Destination is not position dependent: use cached value.
3986 ((and (not match-title-p) (not (eq cached 'not-found))) cached)
3987 ;; First try to find a matching "<<path>>" unless user specified
3988 ;; he was looking for a headline (path starts with a "*"
3989 ;; character).
3990 ((and (not match-title-p)
3991 (let ((match (org-element-map (plist-get info :parse-tree) 'target
3992 (lambda (blob)
3993 (and (equal (org-split-string
3994 (org-element-property :value blob))
3995 path)
3996 blob))
3997 info 'first-match)))
3998 (and match (puthash path match link-cache)))))
3999 ;; Then try to find an element with a matching "#+NAME: path"
4000 ;; affiliated keyword.
4001 ((and (not match-title-p)
4002 (let ((match (org-element-map (plist-get info :parse-tree)
4003 org-element-all-elements
4004 (lambda (el)
4005 (let ((name (org-element-property :name el)))
4006 (when (and name
4007 (equal (org-split-string name) path))
4008 el)))
4009 info 'first-match)))
4010 (and match (puthash path match link-cache)))))
4011 ;; Last case: link either points to a headline or to nothingness.
4012 ;; Try to find the source, with priority given to headlines with
4013 ;; the closest common ancestor. If such candidate is found,
4014 ;; return it, otherwise return nil.
4016 (let ((find-headline
4017 (function
4018 ;; Return first headline whose `:raw-value' property is
4019 ;; NAME in parse tree DATA, or nil. Statistics cookies
4020 ;; are ignored.
4021 (lambda (name data)
4022 (org-element-map data 'headline
4023 (lambda (headline)
4024 (when (equal (org-split-string
4025 (replace-regexp-in-string
4026 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
4027 (org-element-property :raw-value headline)))
4028 name)
4029 headline))
4030 info 'first-match)))))
4031 ;; Search among headlines sharing an ancestor with link, from
4032 ;; closest to farthest.
4033 (catch 'exit
4034 (mapc
4035 (lambda (parent)
4036 (let ((foundp (funcall find-headline path parent)))
4037 (when foundp (throw 'exit foundp))))
4038 (let ((parent-hl (org-export-get-parent-headline link)))
4039 (if (not parent-hl) (list (plist-get info :parse-tree))
4040 (cons parent-hl (org-export-get-genealogy parent-hl)))))
4041 ;; No destination found: return nil.
4042 (and (not match-title-p) (puthash path nil link-cache))))))))
4044 (defun org-export-resolve-id-link (link info)
4045 "Return headline referenced as LINK destination.
4047 INFO is a plist used as a communication channel.
4049 Return value can be the headline element matched in current parse
4050 tree, a file name or nil. Assume LINK type is either \"id\" or
4051 \"custom-id\"."
4052 (let ((id (org-element-property :path link)))
4053 ;; First check if id is within the current parse tree.
4054 (or (org-element-map (plist-get info :parse-tree) 'headline
4055 (lambda (headline)
4056 (when (or (string= (org-element-property :ID headline) id)
4057 (string= (org-element-property :CUSTOM_ID headline) id))
4058 headline))
4059 info 'first-match)
4060 ;; Otherwise, look for external files.
4061 (cdr (assoc id (plist-get info :id-alist))))))
4063 (defun org-export-resolve-radio-link (link info)
4064 "Return radio-target object referenced as LINK destination.
4066 INFO is a plist used as a communication channel.
4068 Return value can be a radio-target object or nil. Assume LINK
4069 has type \"radio\"."
4070 (let ((path (replace-regexp-in-string
4071 "[ \r\t\n]+" " " (org-element-property :path link))))
4072 (org-element-map (plist-get info :parse-tree) 'radio-target
4073 (lambda (radio)
4074 (and (eq (compare-strings
4075 (replace-regexp-in-string
4076 "[ \r\t\n]+" " " (org-element-property :value radio))
4077 nil nil path nil nil t)
4079 radio))
4080 info 'first-match)))
4083 ;;;; For References
4085 ;; `org-export-get-ordinal' associates a sequence number to any object
4086 ;; or element.
4088 (defun org-export-get-ordinal (element info &optional types predicate)
4089 "Return ordinal number of an element or object.
4091 ELEMENT is the element or object considered. INFO is the plist
4092 used as a communication channel.
4094 Optional argument TYPES, when non-nil, is a list of element or
4095 object types, as symbols, that should also be counted in.
4096 Otherwise, only provided element's type is considered.
4098 Optional argument PREDICATE is a function returning a non-nil
4099 value if the current element or object should be counted in. It
4100 accepts two arguments: the element or object being considered and
4101 the plist used as a communication channel. This allows to count
4102 only a certain type of objects (i.e. inline images).
4104 Return value is a list of numbers if ELEMENT is a headline or an
4105 item. It is nil for keywords. It represents the footnote number
4106 for footnote definitions and footnote references. If ELEMENT is
4107 a target, return the same value as if ELEMENT was the closest
4108 table, item or headline containing the target. In any other
4109 case, return the sequence number of ELEMENT among elements or
4110 objects of the same type."
4111 ;; Ordinal of a target object refer to the ordinal of the closest
4112 ;; table, item, or headline containing the object.
4113 (when (eq (org-element-type element) 'target)
4114 (setq element
4115 (loop for parent in (org-export-get-genealogy element)
4116 when
4117 (memq
4118 (org-element-type parent)
4119 '(footnote-definition footnote-reference headline item
4120 table))
4121 return parent)))
4122 (case (org-element-type element)
4123 ;; Special case 1: A headline returns its number as a list.
4124 (headline (org-export-get-headline-number element info))
4125 ;; Special case 2: An item returns its number as a list.
4126 (item (let ((struct (org-element-property :structure element)))
4127 (org-list-get-item-number
4128 (org-element-property :begin element)
4129 struct
4130 (org-list-prevs-alist struct)
4131 (org-list-parents-alist struct))))
4132 ((footnote-definition footnote-reference)
4133 (org-export-get-footnote-number element info))
4134 (otherwise
4135 (let ((counter 0))
4136 ;; Increment counter until ELEMENT is found again.
4137 (org-element-map (plist-get info :parse-tree)
4138 (or types (org-element-type element))
4139 (lambda (el)
4140 (cond
4141 ((eq element el) (1+ counter))
4142 ((not predicate) (incf counter) nil)
4143 ((funcall predicate el info) (incf counter) nil)))
4144 info 'first-match)))))
4147 ;;;; For Src-Blocks
4149 ;; `org-export-get-loc' counts number of code lines accumulated in
4150 ;; src-block or example-block elements with a "+n" switch until
4151 ;; a given element, excluded. Note: "-n" switches reset that count.
4153 ;; `org-export-unravel-code' extracts source code (along with a code
4154 ;; references alist) from an `element-block' or `src-block' type
4155 ;; element.
4157 ;; `org-export-format-code' applies a formatting function to each line
4158 ;; of code, providing relative line number and code reference when
4159 ;; appropriate. Since it doesn't access the original element from
4160 ;; which the source code is coming, it expects from the code calling
4161 ;; it to know if lines should be numbered and if code references
4162 ;; should appear.
4164 ;; Eventually, `org-export-format-code-default' is a higher-level
4165 ;; function (it makes use of the two previous functions) which handles
4166 ;; line numbering and code references inclusion, and returns source
4167 ;; code in a format suitable for plain text or verbatim output.
4169 (defun org-export-get-loc (element info)
4170 "Return accumulated lines of code up to ELEMENT.
4172 INFO is the plist used as a communication channel.
4174 ELEMENT is excluded from count."
4175 (let ((loc 0))
4176 (org-element-map (plist-get info :parse-tree)
4177 `(src-block example-block ,(org-element-type element))
4178 (lambda (el)
4179 (cond
4180 ;; ELEMENT is reached: Quit the loop.
4181 ((eq el element))
4182 ;; Only count lines from src-block and example-block elements
4183 ;; with a "+n" or "-n" switch. A "-n" switch resets counter.
4184 ((not (memq (org-element-type el) '(src-block example-block))) nil)
4185 ((let ((linums (org-element-property :number-lines el)))
4186 (when linums
4187 ;; Accumulate locs or reset them.
4188 (let ((lines (org-count-lines
4189 (org-trim (org-element-property :value el)))))
4190 (setq loc (if (eq linums 'new) lines (+ loc lines))))))
4191 ;; Return nil to stay in the loop.
4192 nil)))
4193 info 'first-match)
4194 ;; Return value.
4195 loc))
4197 (defun org-export-unravel-code (element)
4198 "Clean source code and extract references out of it.
4200 ELEMENT has either a `src-block' an `example-block' type.
4202 Return a cons cell whose CAR is the source code, cleaned from any
4203 reference, protective commas and spurious indentation, and CDR is
4204 an alist between relative line number (integer) and name of code
4205 reference on that line (string)."
4206 (let* ((line 0) refs
4207 (value (org-element-property :value element))
4208 ;; Get code and clean it. Remove blank lines at its
4209 ;; beginning and end.
4210 (code (replace-regexp-in-string
4211 "\\`\\([ \t]*\n\\)+" ""
4212 (replace-regexp-in-string
4213 "\\([ \t]*\n\\)*[ \t]*\\'" "\n"
4214 (if (or org-src-preserve-indentation
4215 (org-element-property :preserve-indent element))
4216 value
4217 (org-element-remove-indentation value)))))
4218 ;; Get format used for references.
4219 (label-fmt (regexp-quote
4220 (or (org-element-property :label-fmt element)
4221 org-coderef-label-format)))
4222 ;; Build a regexp matching a loc with a reference.
4223 (with-ref-re
4224 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)[ \t]*\\)$"
4225 (replace-regexp-in-string
4226 "%s" "\\([-a-zA-Z0-9_ ]+\\)" label-fmt nil t))))
4227 ;; Return value.
4228 (cons
4229 ;; Code with references removed.
4230 (org-element-normalize-string
4231 (mapconcat
4232 (lambda (loc)
4233 (incf line)
4234 (if (not (string-match with-ref-re loc)) loc
4235 ;; Ref line: remove ref, and signal its position in REFS.
4236 (push (cons line (match-string 3 loc)) refs)
4237 (replace-match "" nil nil loc 1)))
4238 (org-split-string code "\n") "\n"))
4239 ;; Reference alist.
4240 refs)))
4242 (defun org-export-format-code (code fun &optional num-lines ref-alist)
4243 "Format CODE by applying FUN line-wise and return it.
4245 CODE is a string representing the code to format. FUN is
4246 a function. It must accept three arguments: a line of
4247 code (string), the current line number (integer) or nil and the
4248 reference associated to the current line (string) or nil.
4250 Optional argument NUM-LINES can be an integer representing the
4251 number of code lines accumulated until the current code. Line
4252 numbers passed to FUN will take it into account. If it is nil,
4253 FUN's second argument will always be nil. This number can be
4254 obtained with `org-export-get-loc' function.
4256 Optional argument REF-ALIST can be an alist between relative line
4257 number (i.e. ignoring NUM-LINES) and the name of the code
4258 reference on it. If it is nil, FUN's third argument will always
4259 be nil. It can be obtained through the use of
4260 `org-export-unravel-code' function."
4261 (let ((--locs (org-split-string code "\n"))
4262 (--line 0))
4263 (org-element-normalize-string
4264 (mapconcat
4265 (lambda (--loc)
4266 (incf --line)
4267 (let ((--ref (cdr (assq --line ref-alist))))
4268 (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
4269 --locs "\n"))))
4271 (defun org-export-format-code-default (element info)
4272 "Return source code from ELEMENT, formatted in a standard way.
4274 ELEMENT is either a `src-block' or `example-block' element. INFO
4275 is a plist used as a communication channel.
4277 This function takes care of line numbering and code references
4278 inclusion. Line numbers, when applicable, appear at the
4279 beginning of the line, separated from the code by two white
4280 spaces. Code references, on the other hand, appear flushed to
4281 the right, separated by six white spaces from the widest line of
4282 code."
4283 ;; Extract code and references.
4284 (let* ((code-info (org-export-unravel-code element))
4285 (code (car code-info))
4286 (code-lines (org-split-string code "\n")))
4287 (if (null code-lines) ""
4288 (let* ((refs (and (org-element-property :retain-labels element)
4289 (cdr code-info)))
4290 ;; Handle line numbering.
4291 (num-start (case (org-element-property :number-lines element)
4292 (continued (org-export-get-loc element info))
4293 (new 0)))
4294 (num-fmt
4295 (and num-start
4296 (format "%%%ds "
4297 (length (number-to-string
4298 (+ (length code-lines) num-start))))))
4299 ;; Prepare references display, if required. Any reference
4300 ;; should start six columns after the widest line of code,
4301 ;; wrapped with parenthesis.
4302 (max-width
4303 (+ (apply 'max (mapcar 'length code-lines))
4304 (if (not num-start) 0 (length (format num-fmt num-start))))))
4305 (org-export-format-code
4306 code
4307 (lambda (loc line-num ref)
4308 (let ((number-str (and num-fmt (format num-fmt line-num))))
4309 (concat
4310 number-str
4312 (and ref
4313 (concat (make-string
4314 (- (+ 6 max-width)
4315 (+ (length loc) (length number-str))) ? )
4316 (format "(%s)" ref))))))
4317 num-start refs)))))
4320 ;;;; For Tables
4322 ;; `org-export-table-has-special-column-p' and and
4323 ;; `org-export-table-row-is-special-p' are predicates used to look for
4324 ;; meta-information about the table structure.
4326 ;; `org-table-has-header-p' tells when the rows before the first rule
4327 ;; should be considered as table's header.
4329 ;; `org-export-table-cell-width', `org-export-table-cell-alignment'
4330 ;; and `org-export-table-cell-borders' extract information from
4331 ;; a table-cell element.
4333 ;; `org-export-table-dimensions' gives the number on rows and columns
4334 ;; in the table, ignoring horizontal rules and special columns.
4335 ;; `org-export-table-cell-address', given a table-cell object, returns
4336 ;; the absolute address of a cell. On the other hand,
4337 ;; `org-export-get-table-cell-at' does the contrary.
4339 ;; `org-export-table-cell-starts-colgroup-p',
4340 ;; `org-export-table-cell-ends-colgroup-p',
4341 ;; `org-export-table-row-starts-rowgroup-p',
4342 ;; `org-export-table-row-ends-rowgroup-p',
4343 ;; `org-export-table-row-starts-header-p' and
4344 ;; `org-export-table-row-ends-header-p' indicate position of current
4345 ;; row or cell within the table.
4347 (defun org-export-table-has-special-column-p (table)
4348 "Non-nil when TABLE has a special column.
4349 All special columns will be ignored during export."
4350 ;; The table has a special column when every first cell of every row
4351 ;; has an empty value or contains a symbol among "/", "#", "!", "$",
4352 ;; "*" "_" and "^". Though, do not consider a first row containing
4353 ;; only empty cells as special.
4354 (let ((special-column-p 'empty))
4355 (catch 'exit
4356 (mapc
4357 (lambda (row)
4358 (when (eq (org-element-property :type row) 'standard)
4359 (let ((value (org-element-contents
4360 (car (org-element-contents row)))))
4361 (cond ((member value '(("/") ("#") ("!") ("$") ("*") ("_") ("^")))
4362 (setq special-column-p 'special))
4363 ((not value))
4364 (t (throw 'exit nil))))))
4365 (org-element-contents table))
4366 (eq special-column-p 'special))))
4368 (defun org-export-table-has-header-p (table info)
4369 "Non-nil when TABLE has a header.
4371 INFO is a plist used as a communication channel.
4373 A table has a header when it contains at least two row groups."
4374 (let ((cache (or (plist-get info :table-header-cache)
4375 (plist-get (setq info
4376 (plist-put info :table-header-cache
4377 (make-hash-table :test 'eq)))
4378 :table-header-cache))))
4379 (or (gethash table cache)
4380 (let ((rowgroup 1) row-flag)
4381 (puthash
4382 table
4383 (org-element-map table 'table-row
4384 (lambda (row)
4385 (cond
4386 ((> rowgroup 1) t)
4387 ((and row-flag (eq (org-element-property :type row) 'rule))
4388 (incf rowgroup) (setq row-flag nil))
4389 ((and (not row-flag) (eq (org-element-property :type row)
4390 'standard))
4391 (setq row-flag t) nil)))
4392 info 'first-match)
4393 cache)))))
4395 (defun org-export-table-row-is-special-p (table-row info)
4396 "Non-nil if TABLE-ROW is considered special.
4398 INFO is a plist used as the communication channel.
4400 All special rows will be ignored during export."
4401 (when (eq (org-element-property :type table-row) 'standard)
4402 (let ((first-cell (org-element-contents
4403 (car (org-element-contents table-row)))))
4404 ;; A row is special either when...
4406 ;; ... it starts with a field only containing "/",
4407 (equal first-cell '("/"))
4408 ;; ... the table contains a special column and the row start
4409 ;; with a marking character among, "^", "_", "$" or "!",
4410 (and (org-export-table-has-special-column-p
4411 (org-export-get-parent table-row))
4412 (member first-cell '(("^") ("_") ("$") ("!"))))
4413 ;; ... it contains only alignment cookies and empty cells.
4414 (let ((special-row-p 'empty))
4415 (catch 'exit
4416 (mapc
4417 (lambda (cell)
4418 (let ((value (org-element-contents cell)))
4419 ;; Since VALUE is a secondary string, the following
4420 ;; checks avoid expanding it with `org-export-data'.
4421 (cond ((not value))
4422 ((and (not (cdr value))
4423 (stringp (car value))
4424 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'"
4425 (car value)))
4426 (setq special-row-p 'cookie))
4427 (t (throw 'exit nil)))))
4428 (org-element-contents table-row))
4429 (eq special-row-p 'cookie)))))))
4431 (defun org-export-table-row-group (table-row info)
4432 "Return TABLE-ROW's group number, as an integer.
4434 INFO is a plist used as the communication channel.
4436 Return value is the group number, as an integer, or nil for
4437 special rows and rows separators. First group is also table's
4438 header."
4439 (let ((cache (or (plist-get info :table-row-group-cache)
4440 (plist-get (setq info
4441 (plist-put info :table-row-group-cache
4442 (make-hash-table :test 'eq)))
4443 :table-row-group-cache))))
4444 (cond ((gethash table-row cache))
4445 ((eq (org-element-property :type table-row) 'rule) nil)
4446 (t (let ((group 0) row-flag)
4447 (org-element-map (org-export-get-parent table-row) 'table-row
4448 (lambda (row)
4449 (if (eq (org-element-property :type row) 'rule)
4450 (setq row-flag nil)
4451 (unless row-flag (incf group) (setq row-flag t)))
4452 (when (eq table-row row) (puthash table-row group cache)))
4453 info 'first-match))))))
4455 (defun org-export-table-cell-width (table-cell info)
4456 "Return TABLE-CELL contents width.
4458 INFO is a plist used as the communication channel.
4460 Return value is the width given by the last width cookie in the
4461 same column as TABLE-CELL, or nil."
4462 (let* ((row (org-export-get-parent table-cell))
4463 (table (org-export-get-parent row))
4464 (cells (org-element-contents row))
4465 (columns (length cells))
4466 (column (- columns (length (memq table-cell cells))))
4467 (cache (or (plist-get info :table-cell-width-cache)
4468 (plist-get (setq info
4469 (plist-put info :table-cell-width-cache
4470 (make-hash-table :test 'eq)))
4471 :table-cell-width-cache)))
4472 (width-vector (or (gethash table cache)
4473 (puthash table (make-vector columns 'empty) cache)))
4474 (value (aref width-vector column)))
4475 (if (not (eq value 'empty)) value
4476 (let (cookie-width)
4477 (dolist (row (org-element-contents table)
4478 (aset width-vector column cookie-width))
4479 (when (org-export-table-row-is-special-p row info)
4480 ;; In a special row, try to find a width cookie at COLUMN.
4481 (let* ((value (org-element-contents
4482 (elt (org-element-contents row) column)))
4483 (cookie (car value)))
4484 ;; The following checks avoid expanding unnecessarily
4485 ;; the cell with `org-export-data'.
4486 (when (and value
4487 (not (cdr value))
4488 (stringp cookie)
4489 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'" cookie)
4490 (match-string 1 cookie))
4491 (setq cookie-width
4492 (string-to-number (match-string 1 cookie)))))))))))
4494 (defun org-export-table-cell-alignment (table-cell info)
4495 "Return TABLE-CELL contents alignment.
4497 INFO is a plist used as the communication channel.
4499 Return alignment as specified by the last alignment cookie in the
4500 same column as TABLE-CELL. If no such cookie is found, a default
4501 alignment value will be deduced from fraction of numbers in the
4502 column (see `org-table-number-fraction' for more information).
4503 Possible values are `left', `right' and `center'."
4504 ;; Load `org-table-number-fraction' and `org-table-number-regexp'.
4505 (require 'org-table)
4506 (let* ((row (org-export-get-parent table-cell))
4507 (table (org-export-get-parent row))
4508 (cells (org-element-contents row))
4509 (columns (length cells))
4510 (column (- columns (length (memq table-cell cells))))
4511 (cache (or (plist-get info :table-cell-alignment-cache)
4512 (plist-get (setq info
4513 (plist-put info :table-cell-alignment-cache
4514 (make-hash-table :test 'eq)))
4515 :table-cell-alignment-cache)))
4516 (align-vector (or (gethash table cache)
4517 (puthash table (make-vector columns nil) cache))))
4518 (or (aref align-vector column)
4519 (let ((number-cells 0)
4520 (total-cells 0)
4521 cookie-align
4522 previous-cell-number-p)
4523 (dolist (row (org-element-contents (org-export-get-parent row)))
4524 (cond
4525 ;; In a special row, try to find an alignment cookie at
4526 ;; COLUMN.
4527 ((org-export-table-row-is-special-p row info)
4528 (let ((value (org-element-contents
4529 (elt (org-element-contents row) column))))
4530 ;; Since VALUE is a secondary string, the following
4531 ;; checks avoid useless expansion through
4532 ;; `org-export-data'.
4533 (when (and value
4534 (not (cdr value))
4535 (stringp (car value))
4536 (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'"
4537 (car value))
4538 (match-string 1 (car value)))
4539 (setq cookie-align (match-string 1 (car value))))))
4540 ;; Ignore table rules.
4541 ((eq (org-element-property :type row) 'rule))
4542 ;; In a standard row, check if cell's contents are
4543 ;; expressing some kind of number. Increase NUMBER-CELLS
4544 ;; accordingly. Though, don't bother if an alignment
4545 ;; cookie has already defined cell's alignment.
4546 ((not cookie-align)
4547 (let ((value (org-export-data
4548 (org-element-contents
4549 (elt (org-element-contents row) column))
4550 info)))
4551 (incf total-cells)
4552 ;; Treat an empty cell as a number if it follows
4553 ;; a number.
4554 (if (not (or (string-match org-table-number-regexp value)
4555 (and (string= value "") previous-cell-number-p)))
4556 (setq previous-cell-number-p nil)
4557 (setq previous-cell-number-p t)
4558 (incf number-cells))))))
4559 ;; Return value. Alignment specified by cookies has
4560 ;; precedence over alignment deduced from cell's contents.
4561 (aset align-vector
4562 column
4563 (cond ((equal cookie-align "l") 'left)
4564 ((equal cookie-align "r") 'right)
4565 ((equal cookie-align "c") 'center)
4566 ((>= (/ (float number-cells) total-cells)
4567 org-table-number-fraction)
4568 'right)
4569 (t 'left)))))))
4571 (defun org-export-table-cell-borders (table-cell info)
4572 "Return TABLE-CELL borders.
4574 INFO is a plist used as a communication channel.
4576 Return value is a list of symbols, or nil. Possible values are:
4577 `top', `bottom', `above', `below', `left' and `right'. Note:
4578 `top' (resp. `bottom') only happen for a cell in the first
4579 row (resp. last row) of the table, ignoring table rules, if any.
4581 Returned borders ignore special rows."
4582 (let* ((row (org-export-get-parent table-cell))
4583 (table (org-export-get-parent-table table-cell))
4584 borders)
4585 ;; Top/above border? TABLE-CELL has a border above when a rule
4586 ;; used to demarcate row groups can be found above. Hence,
4587 ;; finding a rule isn't sufficient to push `above' in BORDERS:
4588 ;; another regular row has to be found above that rule.
4589 (let (rule-flag)
4590 (catch 'exit
4591 (mapc (lambda (row)
4592 (cond ((eq (org-element-property :type row) 'rule)
4593 (setq rule-flag t))
4594 ((not (org-export-table-row-is-special-p row info))
4595 (if rule-flag (throw 'exit (push 'above borders))
4596 (throw 'exit nil)))))
4597 ;; Look at every row before the current one.
4598 (cdr (memq row (reverse (org-element-contents table)))))
4599 ;; No rule above, or rule found starts the table (ignoring any
4600 ;; special row): TABLE-CELL is at the top of the table.
4601 (when rule-flag (push 'above borders))
4602 (push 'top borders)))
4603 ;; Bottom/below border? TABLE-CELL has a border below when next
4604 ;; non-regular row below is a rule.
4605 (let (rule-flag)
4606 (catch 'exit
4607 (mapc (lambda (row)
4608 (cond ((eq (org-element-property :type row) 'rule)
4609 (setq rule-flag t))
4610 ((not (org-export-table-row-is-special-p row info))
4611 (if rule-flag (throw 'exit (push 'below borders))
4612 (throw 'exit nil)))))
4613 ;; Look at every row after the current one.
4614 (cdr (memq row (org-element-contents table))))
4615 ;; No rule below, or rule found ends the table (modulo some
4616 ;; special row): TABLE-CELL is at the bottom of the table.
4617 (when rule-flag (push 'below borders))
4618 (push 'bottom borders)))
4619 ;; Right/left borders? They can only be specified by column
4620 ;; groups. Column groups are defined in a row starting with "/".
4621 ;; Also a column groups row only contains "<", "<>", ">" or blank
4622 ;; cells.
4623 (catch 'exit
4624 (let ((column (let ((cells (org-element-contents row)))
4625 (- (length cells) (length (memq table-cell cells))))))
4626 (mapc
4627 (lambda (row)
4628 (unless (eq (org-element-property :type row) 'rule)
4629 (when (equal (org-element-contents
4630 (car (org-element-contents row)))
4631 '("/"))
4632 (let ((column-groups
4633 (mapcar
4634 (lambda (cell)
4635 (let ((value (org-element-contents cell)))
4636 (when (member value '(("<") ("<>") (">") nil))
4637 (car value))))
4638 (org-element-contents row))))
4639 ;; There's a left border when previous cell, if
4640 ;; any, ends a group, or current one starts one.
4641 (when (or (and (not (zerop column))
4642 (member (elt column-groups (1- column))
4643 '(">" "<>")))
4644 (member (elt column-groups column) '("<" "<>")))
4645 (push 'left borders))
4646 ;; There's a right border when next cell, if any,
4647 ;; starts a group, or current one ends one.
4648 (when (or (and (/= (1+ column) (length column-groups))
4649 (member (elt column-groups (1+ column))
4650 '("<" "<>")))
4651 (member (elt column-groups column) '(">" "<>")))
4652 (push 'right borders))
4653 (throw 'exit nil)))))
4654 ;; Table rows are read in reverse order so last column groups
4655 ;; row has precedence over any previous one.
4656 (reverse (org-element-contents table)))))
4657 ;; Return value.
4658 borders))
4660 (defun org-export-table-cell-starts-colgroup-p (table-cell info)
4661 "Non-nil when TABLE-CELL is at the beginning of a column group.
4662 INFO is a plist used as a communication channel."
4663 ;; A cell starts a column group either when it is at the beginning
4664 ;; of a row (or after the special column, if any) or when it has
4665 ;; a left border.
4666 (or (eq (org-element-map (org-export-get-parent table-cell) 'table-cell
4667 'identity info 'first-match)
4668 table-cell)
4669 (memq 'left (org-export-table-cell-borders table-cell info))))
4671 (defun org-export-table-cell-ends-colgroup-p (table-cell info)
4672 "Non-nil when TABLE-CELL is at the end of a column group.
4673 INFO is a plist used as a communication channel."
4674 ;; A cell ends a column group either when it is at the end of a row
4675 ;; or when it has a right border.
4676 (or (eq (car (last (org-element-contents
4677 (org-export-get-parent table-cell))))
4678 table-cell)
4679 (memq 'right (org-export-table-cell-borders table-cell info))))
4681 (defun org-export-table-row-starts-rowgroup-p (table-row info)
4682 "Non-nil when TABLE-ROW is at the beginning of a row group.
4683 INFO is a plist used as a communication channel."
4684 (unless (or (eq (org-element-property :type table-row) 'rule)
4685 (org-export-table-row-is-special-p table-row info))
4686 (let ((borders (org-export-table-cell-borders
4687 (car (org-element-contents table-row)) info)))
4688 (or (memq 'top borders) (memq 'above borders)))))
4690 (defun org-export-table-row-ends-rowgroup-p (table-row info)
4691 "Non-nil when TABLE-ROW is at the end of a row group.
4692 INFO is a plist used as a communication channel."
4693 (unless (or (eq (org-element-property :type table-row) 'rule)
4694 (org-export-table-row-is-special-p table-row info))
4695 (let ((borders (org-export-table-cell-borders
4696 (car (org-element-contents table-row)) info)))
4697 (or (memq 'bottom borders) (memq 'below borders)))))
4699 (defun org-export-table-row-starts-header-p (table-row info)
4700 "Non-nil when TABLE-ROW is the first table header's row.
4701 INFO is a plist used as a communication channel."
4702 (and (org-export-table-has-header-p
4703 (org-export-get-parent-table table-row) info)
4704 (org-export-table-row-starts-rowgroup-p table-row info)
4705 (= (org-export-table-row-group table-row info) 1)))
4707 (defun org-export-table-row-ends-header-p (table-row info)
4708 "Non-nil when TABLE-ROW is the last table header's row.
4709 INFO is a plist used as a communication channel."
4710 (and (org-export-table-has-header-p
4711 (org-export-get-parent-table table-row) info)
4712 (org-export-table-row-ends-rowgroup-p table-row info)
4713 (= (org-export-table-row-group table-row info) 1)))
4715 (defun org-export-table-row-number (table-row info)
4716 "Return TABLE-ROW number.
4717 INFO is a plist used as a communication channel. Return value is
4718 zero-based and ignores separators. The function returns nil for
4719 special colums and separators."
4720 (when (and (eq (org-element-property :type table-row) 'standard)
4721 (not (org-export-table-row-is-special-p table-row info)))
4722 (let ((number 0))
4723 (org-element-map (org-export-get-parent-table table-row) 'table-row
4724 (lambda (row)
4725 (cond ((eq row table-row) number)
4726 ((eq (org-element-property :type row) 'standard)
4727 (incf number) nil)))
4728 info 'first-match))))
4730 (defun org-export-table-dimensions (table info)
4731 "Return TABLE dimensions.
4733 INFO is a plist used as a communication channel.
4735 Return value is a CONS like (ROWS . COLUMNS) where
4736 ROWS (resp. COLUMNS) is the number of exportable
4737 rows (resp. columns)."
4738 (let (first-row (columns 0) (rows 0))
4739 ;; Set number of rows, and extract first one.
4740 (org-element-map table 'table-row
4741 (lambda (row)
4742 (when (eq (org-element-property :type row) 'standard)
4743 (incf rows)
4744 (unless first-row (setq first-row row)))) info)
4745 ;; Set number of columns.
4746 (org-element-map first-row 'table-cell (lambda (cell) (incf columns)) info)
4747 ;; Return value.
4748 (cons rows columns)))
4750 (defun org-export-table-cell-address (table-cell info)
4751 "Return address of a regular TABLE-CELL object.
4753 TABLE-CELL is the cell considered. INFO is a plist used as
4754 a communication channel.
4756 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4757 zero-based index. Only exportable cells are considered. The
4758 function returns nil for other cells."
4759 (let* ((table-row (org-export-get-parent table-cell))
4760 (row-number (org-export-table-row-number table-row info)))
4761 (when row-number
4762 (cons row-number
4763 (let ((col-count 0))
4764 (org-element-map table-row 'table-cell
4765 (lambda (cell)
4766 (if (eq cell table-cell) col-count (incf col-count) nil))
4767 info 'first-match))))))
4769 (defun org-export-get-table-cell-at (address table info)
4770 "Return regular table-cell object at ADDRESS in TABLE.
4772 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4773 zero-based index. TABLE is a table type element. INFO is
4774 a plist used as a communication channel.
4776 If no table-cell, among exportable cells, is found at ADDRESS,
4777 return nil."
4778 (let ((column-pos (cdr address)) (column-count 0))
4779 (org-element-map
4780 ;; Row at (car address) or nil.
4781 (let ((row-pos (car address)) (row-count 0))
4782 (org-element-map table 'table-row
4783 (lambda (row)
4784 (cond ((eq (org-element-property :type row) 'rule) nil)
4785 ((= row-count row-pos) row)
4786 (t (incf row-count) nil)))
4787 info 'first-match))
4788 'table-cell
4789 (lambda (cell)
4790 (if (= column-count column-pos) cell
4791 (incf column-count) nil))
4792 info 'first-match)))
4795 ;;;; For Tables Of Contents
4797 ;; `org-export-collect-headlines' builds a list of all exportable
4798 ;; headline elements, maybe limited to a certain depth. One can then
4799 ;; easily parse it and transcode it.
4801 ;; Building lists of tables, figures or listings is quite similar.
4802 ;; Once the generic function `org-export-collect-elements' is defined,
4803 ;; `org-export-collect-tables', `org-export-collect-figures' and
4804 ;; `org-export-collect-listings' can be derived from it.
4806 (defun org-export-collect-headlines (info &optional n)
4807 "Collect headlines in order to build a table of contents.
4809 INFO is a plist used as a communication channel.
4811 When optional argument N is an integer, it specifies the depth of
4812 the table of contents. Otherwise, it is set to the value of the
4813 last headline level. See `org-export-headline-levels' for more
4814 information.
4816 Return a list of all exportable headlines as parsed elements.
4817 Footnote sections, if any, will be ignored."
4818 (let ((limit (plist-get info :headline-levels)))
4819 (setq n (if (wholenump n) (min n limit) limit))
4820 (org-element-map (plist-get info :parse-tree) 'headline
4821 #'(lambda (headline)
4822 (unless (org-element-property :footnote-section-p headline)
4823 (let ((level (org-export-get-relative-level headline info)))
4824 (and (<= level n) headline))))
4825 info)))
4827 (defun org-export-collect-elements (type info &optional predicate)
4828 "Collect referenceable elements of a determined type.
4830 TYPE can be a symbol or a list of symbols specifying element
4831 types to search. Only elements with a caption are collected.
4833 INFO is a plist used as a communication channel.
4835 When non-nil, optional argument PREDICATE is a function accepting
4836 one argument, an element of type TYPE. It returns a non-nil
4837 value when that element should be collected.
4839 Return a list of all elements found, in order of appearance."
4840 (org-element-map (plist-get info :parse-tree) type
4841 (lambda (element)
4842 (and (org-element-property :caption element)
4843 (or (not predicate) (funcall predicate element))
4844 element))
4845 info))
4847 (defun org-export-collect-tables (info)
4848 "Build a list of tables.
4849 INFO is a plist used as a communication channel.
4851 Return a list of table elements with a caption."
4852 (org-export-collect-elements 'table info))
4854 (defun org-export-collect-figures (info predicate)
4855 "Build a list of figures.
4857 INFO is a plist used as a communication channel. PREDICATE is
4858 a function which accepts one argument: a paragraph element and
4859 whose return value is non-nil when that element should be
4860 collected.
4862 A figure is a paragraph type element, with a caption, verifying
4863 PREDICATE. The latter has to be provided since a \"figure\" is
4864 a vague concept that may depend on back-end.
4866 Return a list of elements recognized as figures."
4867 (org-export-collect-elements 'paragraph info predicate))
4869 (defun org-export-collect-listings (info)
4870 "Build a list of src blocks.
4872 INFO is a plist used as a communication channel.
4874 Return a list of src-block elements with a caption."
4875 (org-export-collect-elements 'src-block info))
4878 ;;;; Smart Quotes
4880 ;; The main function for the smart quotes sub-system is
4881 ;; `org-export-activate-smart-quotes', which replaces every quote in
4882 ;; a given string from the parse tree with its "smart" counterpart.
4884 ;; Dictionary for smart quotes is stored in
4885 ;; `org-export-smart-quotes-alist'.
4887 ;; Internally, regexps matching potential smart quotes (checks at
4888 ;; string boundaries are also necessary) are defined in
4889 ;; `org-export-smart-quotes-regexps'.
4891 (defconst org-export-smart-quotes-alist
4892 '(("da"
4893 ;; one may use: »...«, "...", ›...‹, or '...'.
4894 ;; http://sproget.dk/raad-og-regler/retskrivningsregler/retskrivningsregler/a7-40-60/a7-58-anforselstegn/
4895 ;; LaTeX quotes require Babel!
4896 (opening-double-quote :utf-8 "»" :html "&raquo;" :latex ">>"
4897 :texinfo "@guillemetright{}")
4898 (closing-double-quote :utf-8 "«" :html "&laquo;" :latex "<<"
4899 :texinfo "@guillemetleft{}")
4900 (opening-single-quote :utf-8 "›" :html "&rsaquo;" :latex "\\frq{}"
4901 :texinfo "@guilsinglright{}")
4902 (closing-single-quote :utf-8 "‹" :html "&lsaquo;" :latex "\\flq{}"
4903 :texinfo "@guilsingleft{}")
4904 (apostrophe :utf-8 "’" :html "&rsquo;"))
4905 ("de"
4906 (opening-double-quote :utf-8 "„" :html "&bdquo;" :latex "\"`"
4907 :texinfo "@quotedblbase{}")
4908 (closing-double-quote :utf-8 "“" :html "&ldquo;" :latex "\"'"
4909 :texinfo "@quotedblleft{}")
4910 (opening-single-quote :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}"
4911 :texinfo "@quotesinglbase{}")
4912 (closing-single-quote :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}"
4913 :texinfo "@quoteleft{}")
4914 (apostrophe :utf-8 "’" :html "&rsquo;"))
4915 ("en"
4916 (opening-double-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
4917 (closing-double-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
4918 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
4919 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
4920 (apostrophe :utf-8 "’" :html "&rsquo;"))
4921 ("es"
4922 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
4923 :texinfo "@guillemetleft{}")
4924 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
4925 :texinfo "@guillemetright{}")
4926 (opening-single-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
4927 (closing-single-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
4928 (apostrophe :utf-8 "’" :html "&rsquo;"))
4929 ("fr"
4930 (opening-double-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
4931 :texinfo "@guillemetleft{}@tie{}")
4932 (closing-double-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
4933 :texinfo "@tie{}@guillemetright{}")
4934 (opening-single-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
4935 :texinfo "@guillemetleft{}@tie{}")
4936 (closing-single-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
4937 :texinfo "@tie{}@guillemetright{}")
4938 (apostrophe :utf-8 "’" :html "&rsquo;"))
4939 ("no"
4940 ;; https://nn.wikipedia.org/wiki/Sitatteikn
4941 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
4942 :texinfo "@guillemetleft{}")
4943 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
4944 :texinfo "@guillemetright{}")
4945 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
4946 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
4947 (apostrophe :utf-8 "’" :html "&rsquo;"))
4948 ("nb"
4949 ;; https://nn.wikipedia.org/wiki/Sitatteikn
4950 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
4951 :texinfo "@guillemetleft{}")
4952 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
4953 :texinfo "@guillemetright{}")
4954 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
4955 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
4956 (apostrophe :utf-8 "’" :html "&rsquo;"))
4957 ("nn"
4958 ;; https://nn.wikipedia.org/wiki/Sitatteikn
4959 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
4960 :texinfo "@guillemetleft{}")
4961 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
4962 :texinfo "@guillemetright{}")
4963 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
4964 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
4965 (apostrophe :utf-8 "’" :html "&rsquo;"))
4966 ("sv"
4967 ;; based on https://sv.wikipedia.org/wiki/Citattecken
4968 (opening-double-quote :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
4969 (closing-double-quote :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
4970 (opening-single-quote :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "`")
4971 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "'")
4972 (apostrophe :utf-8 "’" :html "&rsquo;"))
4974 "Smart quotes translations.
4976 Alist whose CAR is a language string and CDR is an alist with
4977 quote type as key and a plist associating various encodings to
4978 their translation as value.
4980 A quote type can be any symbol among `opening-double-quote',
4981 `closing-double-quote', `opening-single-quote',
4982 `closing-single-quote' and `apostrophe'.
4984 Valid encodings include `:utf-8', `:html', `:latex' and
4985 `:texinfo'.
4987 If no translation is found, the quote character is left as-is.")
4989 (defconst org-export-smart-quotes-regexps
4990 (list
4991 ;; Possible opening quote at beginning of string.
4992 "\\`\\([\"']\\)\\(\\w\\|\\s.\\|\\s_\\)"
4993 ;; Possible closing quote at beginning of string.
4994 "\\`\\([\"']\\)\\(\\s-\\|\\s)\\|\\s.\\)"
4995 ;; Possible apostrophe at beginning of string.
4996 "\\`\\('\\)\\S-"
4997 ;; Opening single and double quotes.
4998 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\(?:\\w\\|\\s.\\|\\s_\\)"
4999 ;; Closing single and double quotes.
5000 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\(?:\\s-\\|\\s)\\|\\s.\\)"
5001 ;; Apostrophe.
5002 "\\S-\\('\\)\\S-"
5003 ;; Possible opening quote at end of string.
5004 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\'"
5005 ;; Possible closing quote at end of string.
5006 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\'"
5007 ;; Possible apostrophe at end of string.
5008 "\\S-\\('\\)\\'")
5009 "List of regexps matching a quote or an apostrophe.
5010 In every regexp, quote or apostrophe matched is put in group 1.")
5012 (defun org-export-activate-smart-quotes (s encoding info &optional original)
5013 "Replace regular quotes with \"smart\" quotes in string S.
5015 ENCODING is a symbol among `:html', `:latex', `:texinfo' and
5016 `:utf-8'. INFO is a plist used as a communication channel.
5018 The function has to retrieve information about string
5019 surroundings in parse tree. It can only happen with an
5020 unmodified string. Thus, if S has already been through another
5021 process, a non-nil ORIGINAL optional argument will provide that
5022 original string.
5024 Return the new string."
5025 (if (equal s "") ""
5026 (let* ((prev (org-export-get-previous-element (or original s) info))
5027 ;; Try to be flexible when computing number of blanks
5028 ;; before object. The previous object may be a string
5029 ;; introduced by the back-end and not completely parsed.
5030 (pre-blank (and prev
5031 (or (org-element-property :post-blank prev)
5032 ;; A string with missing `:post-blank'
5033 ;; property.
5034 (and (stringp prev)
5035 (string-match " *\\'" prev)
5036 (length (match-string 0 prev)))
5037 ;; Fallback value.
5038 0)))
5039 (next (org-export-get-next-element (or original s) info))
5040 (get-smart-quote
5041 (lambda (q type)
5042 ;; Return smart quote associated to a give quote Q, as
5043 ;; a string. TYPE is a symbol among `open', `close' and
5044 ;; `apostrophe'.
5045 (let ((key (case type
5046 (apostrophe 'apostrophe)
5047 (open (if (equal "'" q) 'opening-single-quote
5048 'opening-double-quote))
5049 (otherwise (if (equal "'" q) 'closing-single-quote
5050 'closing-double-quote)))))
5051 (or (plist-get
5052 (cdr (assq key
5053 (cdr (assoc (plist-get info :language)
5054 org-export-smart-quotes-alist))))
5055 encoding)
5056 q)))))
5057 (if (or (equal "\"" s) (equal "'" s))
5058 ;; Only a quote: no regexp can match. We have to check both
5059 ;; sides and decide what to do.
5060 (cond ((and (not prev) (not next)) s)
5061 ((not prev) (funcall get-smart-quote s 'open))
5062 ((and (not next) (zerop pre-blank))
5063 (funcall get-smart-quote s 'close))
5064 ((not next) s)
5065 ((zerop pre-blank) (funcall get-smart-quote s 'apostrophe))
5066 (t (funcall get-smart-quote 'open)))
5067 ;; 1. Replace quote character at the beginning of S.
5068 (cond
5069 ;; Apostrophe?
5070 ((and prev (zerop pre-blank)
5071 (string-match (nth 2 org-export-smart-quotes-regexps) s))
5072 (setq s (replace-match
5073 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
5074 nil t s 1)))
5075 ;; Closing quote?
5076 ((and prev (zerop pre-blank)
5077 (string-match (nth 1 org-export-smart-quotes-regexps) s))
5078 (setq s (replace-match
5079 (funcall get-smart-quote (match-string 1 s) 'close)
5080 nil t s 1)))
5081 ;; Opening quote?
5082 ((and (or (not prev) (> pre-blank 0))
5083 (string-match (nth 0 org-export-smart-quotes-regexps) s))
5084 (setq s (replace-match
5085 (funcall get-smart-quote (match-string 1 s) 'open)
5086 nil t s 1))))
5087 ;; 2. Replace quotes in the middle of the string.
5088 (setq s (replace-regexp-in-string
5089 ;; Opening quotes.
5090 (nth 3 org-export-smart-quotes-regexps)
5091 (lambda (text)
5092 (funcall get-smart-quote (match-string 1 text) 'open))
5093 s nil t 1))
5094 (setq s (replace-regexp-in-string
5095 ;; Closing quotes.
5096 (nth 4 org-export-smart-quotes-regexps)
5097 (lambda (text)
5098 (funcall get-smart-quote (match-string 1 text) 'close))
5099 s nil t 1))
5100 (setq s (replace-regexp-in-string
5101 ;; Apostrophes.
5102 (nth 5 org-export-smart-quotes-regexps)
5103 (lambda (text)
5104 (funcall get-smart-quote (match-string 1 text) 'apostrophe))
5105 s nil t 1))
5106 ;; 3. Replace quote character at the end of S.
5107 (cond
5108 ;; Apostrophe?
5109 ((and next (string-match (nth 8 org-export-smart-quotes-regexps) s))
5110 (setq s (replace-match
5111 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
5112 nil t s 1)))
5113 ;; Closing quote?
5114 ((and (not next)
5115 (string-match (nth 7 org-export-smart-quotes-regexps) s))
5116 (setq s (replace-match
5117 (funcall get-smart-quote (match-string 1 s) 'close)
5118 nil t s 1)))
5119 ;; Opening quote?
5120 ((and next (string-match (nth 6 org-export-smart-quotes-regexps) s))
5121 (setq s (replace-match
5122 (funcall get-smart-quote (match-string 1 s) 'open)
5123 nil t s 1))))
5124 ;; Return string with smart quotes.
5125 s))))
5127 ;;;; Topology
5129 ;; Here are various functions to retrieve information about the
5130 ;; neighbourhood of a given element or object. Neighbours of interest
5131 ;; are direct parent (`org-export-get-parent'), parent headline
5132 ;; (`org-export-get-parent-headline'), first element containing an
5133 ;; object, (`org-export-get-parent-element'), parent table
5134 ;; (`org-export-get-parent-table'), previous element or object
5135 ;; (`org-export-get-previous-element') and next element or object
5136 ;; (`org-export-get-next-element').
5138 ;; `org-export-get-genealogy' returns the full genealogy of a given
5139 ;; element or object, from closest parent to full parse tree.
5141 (defsubst org-export-get-parent (blob)
5142 "Return BLOB parent or nil.
5143 BLOB is the element or object considered."
5144 (org-element-property :parent blob))
5146 (defun org-export-get-genealogy (blob)
5147 "Return full genealogy relative to a given element or object.
5149 BLOB is the element or object being considered.
5151 Ancestors are returned from closest to farthest, the last one
5152 being the full parse tree."
5153 (let (genealogy (parent blob))
5154 (while (setq parent (org-element-property :parent parent))
5155 (push parent genealogy))
5156 (nreverse genealogy)))
5158 (defun org-export-get-parent-headline (blob)
5159 "Return BLOB parent headline or nil.
5160 BLOB is the element or object being considered."
5161 (let ((parent blob))
5162 (while (and (setq parent (org-element-property :parent parent))
5163 (not (eq (org-element-type parent) 'headline))))
5164 parent))
5166 (defun org-export-get-parent-element (object)
5167 "Return first element containing OBJECT or nil.
5168 OBJECT is the object to consider."
5169 (let ((parent object))
5170 (while (and (setq parent (org-element-property :parent parent))
5171 (memq (org-element-type parent) org-element-all-objects)))
5172 parent))
5174 (defun org-export-get-parent-table (object)
5175 "Return OBJECT parent table or nil.
5176 OBJECT is either a `table-cell' or `table-element' type object."
5177 (let ((parent object))
5178 (while (and (setq parent (org-element-property :parent parent))
5179 (not (eq (org-element-type parent) 'table))))
5180 parent))
5182 (defun org-export-get-previous-element (blob info &optional n)
5183 "Return previous element or object.
5185 BLOB is an element or object. INFO is a plist used as
5186 a communication channel. Return previous exportable element or
5187 object, a string, or nil.
5189 When optional argument N is a positive integer, return a list
5190 containing up to N siblings before BLOB, from farthest to
5191 closest. With any other non-nil value, return a list containing
5192 all of them."
5193 (let ((siblings
5194 ;; An object can belong to the contents of its parent or
5195 ;; to a secondary string. We check the latter option
5196 ;; first.
5197 (let ((parent (org-export-get-parent blob)))
5198 (or (and (not (memq (org-element-type blob)
5199 org-element-all-elements))
5200 (let ((sec-value
5201 (org-element-property
5202 (cdr (assq (org-element-type parent)
5203 org-element-secondary-value-alist))
5204 parent)))
5205 (and (memq blob sec-value) sec-value)))
5206 (org-element-contents parent))))
5207 prev)
5208 (catch 'exit
5209 (mapc (lambda (obj)
5210 (cond ((memq obj (plist-get info :ignore-list)))
5211 ((null n) (throw 'exit obj))
5212 ((not (wholenump n)) (push obj prev))
5213 ((zerop n) (throw 'exit prev))
5214 (t (decf n) (push obj prev))))
5215 (cdr (memq blob (reverse siblings))))
5216 prev)))
5218 (defun org-export-get-next-element (blob info &optional n)
5219 "Return next element or object.
5221 BLOB is an element or object. INFO is a plist used as
5222 a communication channel. Return next exportable element or
5223 object, a string, or nil.
5225 When optional argument N is a positive integer, return a list
5226 containing up to N siblings after BLOB, from closest to farthest.
5227 With any other non-nil value, return a list containing all of
5228 them."
5229 (let ((siblings
5230 ;; An object can belong to the contents of its parent or to
5231 ;; a secondary string. We check the latter option first.
5232 (let ((parent (org-export-get-parent blob)))
5233 (or (and (not (memq (org-element-type blob)
5234 org-element-all-objects))
5235 (let ((sec-value
5236 (org-element-property
5237 (cdr (assq (org-element-type parent)
5238 org-element-secondary-value-alist))
5239 parent)))
5240 (cdr (memq blob sec-value))))
5241 (cdr (memq blob (org-element-contents parent))))))
5242 next)
5243 (catch 'exit
5244 (mapc (lambda (obj)
5245 (cond ((memq obj (plist-get info :ignore-list)))
5246 ((null n) (throw 'exit obj))
5247 ((not (wholenump n)) (push obj next))
5248 ((zerop n) (throw 'exit (nreverse next)))
5249 (t (decf n) (push obj next))))
5250 siblings)
5251 (nreverse next))))
5254 ;;;; Translation
5256 ;; `org-export-translate' translates a string according to the language
5257 ;; specified by the LANGUAGE keyword. `org-export-dictionary' contains
5258 ;; the dictionary used for the translation.
5260 (defconst org-export-dictionary
5261 '(("%e %n: %c"
5262 ("fr" :default "%e %n : %c" :html "%e&nbsp;%n&nbsp;: %c"))
5263 ("Author"
5264 ("ca" :default "Autor")
5265 ("cs" :default "Autor")
5266 ("da" :default "Forfatter")
5267 ("de" :default "Autor")
5268 ("eo" :html "A&#365;toro")
5269 ("es" :default "Autor")
5270 ("et" :default "Autor")
5271 ("fi" :html "Tekij&auml;")
5272 ("fr" :default "Auteur")
5273 ("hu" :default "Szerz&otilde;")
5274 ("is" :html "H&ouml;fundur")
5275 ("it" :default "Autore")
5276 ("ja" :html "&#33879;&#32773;" :utf-8 "著者")
5277 ("nl" :default "Auteur")
5278 ("no" :default "Forfatter")
5279 ("nb" :default "Forfatter")
5280 ("nn" :default "Forfattar")
5281 ("pl" :default "Autor")
5282 ("ru" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5283 ("sv" :html "F&ouml;rfattare")
5284 ("uk" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5285 ("zh-CN" :html "&#20316;&#32773;" :utf-8 "作者")
5286 ("zh-TW" :html "&#20316;&#32773;" :utf-8 "作者"))
5287 ("Continued from previous page"
5288 ("de" :default "Fortsetzung von vorheriger Seite")
5289 ("es" :default "Continúa de la página anterior")
5290 ("fr" :default "Suite de la page précédente")
5291 ("it" :default "Continua da pagina precedente")
5292 ("ja" :utf-8 "前ページから続く")
5293 ("nl" :default "Vervolg van vorige pagina")
5294 ("pt" :default "Continuação da página anterior"))
5295 ("Continued on next page"
5296 ("de" :default "Fortsetzung nächste Seite")
5297 ("es" :default "Continúa en la siguiente página")
5298 ("fr" :default "Suite page suivante")
5299 ("it" :default "Continua alla pagina successiva")
5300 ("ja" :utf-8 "次ページに続く")
5301 ("nl" :default "Vervolg op volgende pagina")
5302 ("pt" :default "Continua na página seguinte"))
5303 ("Date"
5304 ("ca" :default "Data")
5305 ("cs" :default "Datum")
5306 ("da" :default "Dato")
5307 ("de" :default "Datum")
5308 ("eo" :default "Dato")
5309 ("es" :default "Fecha")
5310 ("et" :html "Kuup&#228;ev" :utf-8 "Kuupäev")
5311 ("fi" :html "P&auml;iv&auml;m&auml;&auml;r&auml;")
5312 ("hu" :html "D&aacute;tum")
5313 ("is" :default "Dagsetning")
5314 ("it" :default "Data")
5315 ("ja" :html "&#26085;&#20184;" :utf-8 "日付")
5316 ("nl" :default "Datum")
5317 ("no" :default "Dato")
5318 ("nb" :default "Dato")
5319 ("nn" :default "Dato")
5320 ("pl" :default "Data")
5321 ("ru" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5322 ("sv" :default "Datum")
5323 ("uk" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5324 ("zh-CN" :html "&#26085;&#26399;" :utf-8 "日期")
5325 ("zh-TW" :html "&#26085;&#26399;" :utf-8 "日期"))
5326 ("Equation"
5327 ("da" :default "Ligning")
5328 ("de" :default "Gleichung")
5329 ("es" :html "Ecuaci&oacute;n" :default "Ecuación")
5330 ("et" :html "V&#245;rrand" :utf-8 "Võrrand")
5331 ("fr" :ascii "Equation" :default "Équation")
5332 ("no" :default "Ligning")
5333 ("nb" :default "Ligning")
5334 ("nn" :default "Likning")
5335 ("sv" :default "Ekvation")
5336 ("zh-CN" :html "&#26041;&#31243;" :utf-8 "方程"))
5337 ("Figure"
5338 ("da" :default "Figur")
5339 ("de" :default "Abbildung")
5340 ("es" :default "Figura")
5341 ("et" :default "Joonis")
5342 ("ja" :html "&#22259;" :utf-8 "図")
5343 ("no" :default "Illustrasjon")
5344 ("nb" :default "Illustrasjon")
5345 ("nn" :default "Illustrasjon")
5346 ("sv" :default "Illustration")
5347 ("zh-CN" :html "&#22270;" :utf-8 "图"))
5348 ("Figure %d:"
5349 ("da" :default "Figur %d")
5350 ("de" :default "Abbildung %d:")
5351 ("es" :default "Figura %d:")
5352 ("et" :default "Joonis %d:")
5353 ("fr" :default "Figure %d :" :html "Figure&nbsp;%d&nbsp;:")
5354 ("ja" :html "&#22259;%d: " :utf-8 "図%d: ")
5355 ("no" :default "Illustrasjon %d")
5356 ("nb" :default "Illustrasjon %d")
5357 ("nn" :default "Illustrasjon %d")
5358 ("sv" :default "Illustration %d")
5359 ("zh-CN" :html "&#22270;%d&nbsp;" :utf-8 "图%d "))
5360 ("Footnotes"
5361 ("ca" :html "Peus de p&agrave;gina")
5362 ("cs" :default "Pozn\xe1mky pod carou")
5363 ("da" :default "Fodnoter")
5364 ("de" :html "Fu&szlig;noten" :default "Fußnoten")
5365 ("eo" :default "Piednotoj")
5366 ("es" :html "Nota al pie de p&aacute;gina" :default "Nota al pie de página")
5367 ("et" :html "Allm&#228;rkused" :utf-8 "Allmärkused")
5368 ("fi" :default "Alaviitteet")
5369 ("fr" :default "Notes de bas de page")
5370 ("hu" :html "L&aacute;bjegyzet")
5371 ("is" :html "Aftanm&aacute;lsgreinar")
5372 ("it" :html "Note a pi&egrave; di pagina")
5373 ("ja" :html "&#33050;&#27880;" :utf-8 "脚注")
5374 ("nl" :default "Voetnoten")
5375 ("no" :default "Fotnoter")
5376 ("nb" :default "Fotnoter")
5377 ("nn" :default "Fotnotar")
5378 ("pl" :default "Przypis")
5379 ("ru" :html "&#1057;&#1085;&#1086;&#1089;&#1082;&#1080;" :utf-8 "Сноски")
5380 ("sv" :default "Fotnoter")
5381 ("uk" :html "&#1055;&#1088;&#1080;&#1084;&#1110;&#1090;&#1082;&#1080;"
5382 :utf-8 "Примітки")
5383 ("zh-CN" :html "&#33050;&#27880;" :utf-8 "脚注")
5384 ("zh-TW" :html "&#33139;&#35387;" :utf-8 "腳註"))
5385 ("List of Listings"
5386 ("da" :default "Programmer")
5387 ("de" :default "Programmauflistungsverzeichnis")
5388 ("es" :default "Indice de Listados de programas")
5389 ("et" :default "Loendite nimekiri")
5390 ("fr" :default "Liste des programmes")
5391 ("no" :default "Dataprogrammer")
5392 ("nb" :default "Dataprogrammer")
5393 ("zh-CN" :html "&#20195;&#30721;&#30446;&#24405;" :utf-8 "代码目录"))
5394 ("List of Tables"
5395 ("da" :default "Tabeller")
5396 ("de" :default "Tabellenverzeichnis")
5397 ("es" :default "Indice de tablas")
5398 ("et" :default "Tabelite nimekiri")
5399 ("fr" :default "Liste des tableaux")
5400 ("no" :default "Tabeller")
5401 ("nb" :default "Tabeller")
5402 ("nn" :default "Tabeller")
5403 ("sv" :default "Tabeller")
5404 ("zh-CN" :html "&#34920;&#26684;&#30446;&#24405;" :utf-8 "表格目录"))
5405 ("Listing %d:"
5406 ("da" :default "Program %d")
5407 ("de" :default "Programmlisting %d")
5408 ("es" :default "Listado de programa %d")
5409 ("et" :default "Loend %d")
5410 ("fr" :default "Programme %d :" :html "Programme&nbsp;%d&nbsp;:")
5411 ("no" :default "Dataprogram %d")
5412 ("nb" :default "Dataprogram %d")
5413 ("zh-CN" :html "&#20195;&#30721;%d&nbsp;" :utf-8 "代码%d "))
5414 ("See section %s"
5415 ("da" :default "jævnfør afsnit %s")
5416 ("de" :default "siehe Abschnitt %s")
5417 ("es" :default "vea seccion %s")
5418 ("et" :html "Vaata peat&#252;kki %s" :utf-8 "Vaata peatükki %s")
5419 ("fr" :default "cf. section %s")
5420 ("zh-CN" :html "&#21442;&#35265;&#31532;%s&#33410;" :utf-8 "参见第%s节"))
5421 ("Table"
5422 ("de" :default "Tabelle")
5423 ("es" :default "Tabla")
5424 ("et" :default "Tabel")
5425 ("fr" :default "Tableau")
5426 ("ja" :html "&#34920;" :utf-8 "表")
5427 ("zh-CN" :html "&#34920;" :utf-8 "表"))
5428 ("Table %d:"
5429 ("da" :default "Tabel %d")
5430 ("de" :default "Tabelle %d")
5431 ("es" :default "Tabla %d")
5432 ("et" :default "Tabel %d")
5433 ("fr" :default "Tableau %d :")
5434 ("ja" :html "&#34920;%d:" :utf-8 "表%d:")
5435 ("no" :default "Tabell %d")
5436 ("nb" :default "Tabell %d")
5437 ("nn" :default "Tabell %d")
5438 ("sv" :default "Tabell %d")
5439 ("zh-CN" :html "&#34920;%d&nbsp;" :utf-8 "表%d "))
5440 ("Table of Contents"
5441 ("ca" :html "&Iacute;ndex")
5442 ("cs" :default "Obsah")
5443 ("da" :default "Indhold")
5444 ("de" :default "Inhaltsverzeichnis")
5445 ("eo" :default "Enhavo")
5446 ("es" :html "&Iacute;ndice")
5447 ("et" :default "Sisukord")
5448 ("fi" :html "Sis&auml;llysluettelo")
5449 ("fr" :ascii "Sommaire" :default "Table des matières")
5450 ("hu" :html "Tartalomjegyz&eacute;k")
5451 ("is" :default "Efnisyfirlit")
5452 ("it" :default "Indice")
5453 ("ja" :html "&#30446;&#27425;" :utf-8 "目次")
5454 ("nl" :default "Inhoudsopgave")
5455 ("no" :default "Innhold")
5456 ("nb" :default "Innhold")
5457 ("nn" :default "Innhald")
5458 ("pl" :html "Spis tre&#x015b;ci")
5459 ("ru" :html "&#1057;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1077;"
5460 :utf-8 "Содержание")
5461 ("sv" :html "Inneh&aring;ll")
5462 ("uk" :html "&#1047;&#1084;&#1110;&#1089;&#1090;" :utf-8 "Зміст")
5463 ("zh-CN" :html "&#30446;&#24405;" :utf-8 "目录")
5464 ("zh-TW" :html "&#30446;&#37636;" :utf-8 "目錄"))
5465 ("Unknown reference"
5466 ("da" :default "ukendt reference")
5467 ("de" :default "Unbekannter Verweis")
5468 ("es" :default "referencia desconocida")
5469 ("et" :default "Tundmatu viide")
5470 ("fr" :ascii "Destination inconnue" :default "Référence inconnue")
5471 ("zh-CN" :html "&#26410;&#30693;&#24341;&#29992;" :utf-8 "未知引用")))
5472 "Dictionary for export engine.
5474 Alist whose CAR is the string to translate and CDR is an alist
5475 whose CAR is the language string and CDR is a plist whose
5476 properties are possible charsets and values translated terms.
5478 It is used as a database for `org-export-translate'. Since this
5479 function returns the string as-is if no translation was found,
5480 the variable only needs to record values different from the
5481 entry.")
5483 (defun org-export-translate (s encoding info)
5484 "Translate string S according to language specification.
5486 ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1'
5487 and `:utf-8'. INFO is a plist used as a communication channel.
5489 Translation depends on `:language' property. Return the
5490 translated string. If no translation is found, try to fall back
5491 to `:default' encoding. If it fails, return S."
5492 (let* ((lang (plist-get info :language))
5493 (translations (cdr (assoc lang
5494 (cdr (assoc s org-export-dictionary))))))
5495 (or (plist-get translations encoding)
5496 (plist-get translations :default)
5497 s)))
5501 ;;; Asynchronous Export
5503 ;; `org-export-async-start' is the entry point for asynchronous
5504 ;; export. It recreates current buffer (including visibility,
5505 ;; narrowing and visited file) in an external Emacs process, and
5506 ;; evaluates a command there. It then applies a function on the
5507 ;; returned results in the current process.
5509 ;; At a higher level, `org-export-to-buffer' and `org-export-to-file'
5510 ;; allow to export to a buffer or a file, asynchronously or not.
5512 ;; `org-export-output-file-name' is an auxiliary function meant to be
5513 ;; used with `org-export-to-file'. With a given extension, it tries
5514 ;; to provide a canonical file name to write export output to.
5516 ;; Asynchronously generated results are never displayed directly.
5517 ;; Instead, they are stored in `org-export-stack-contents'. They can
5518 ;; then be retrieved by calling `org-export-stack'.
5520 ;; Export Stack is viewed through a dedicated major mode
5521 ;;`org-export-stack-mode' and tools: `org-export-stack-refresh',
5522 ;;`org-export-stack-delete', `org-export-stack-view' and
5523 ;;`org-export-stack-clear'.
5525 ;; For back-ends, `org-export-add-to-stack' add a new source to stack.
5526 ;; It should be used whenever `org-export-async-start' is called.
5528 (defmacro org-export-async-start (fun &rest body)
5529 "Call function FUN on the results returned by BODY evaluation.
5531 BODY evaluation happens in an asynchronous process, from a buffer
5532 which is an exact copy of the current one.
5534 Use `org-export-add-to-stack' in FUN in order to register results
5535 in the stack.
5537 This is a low level function. See also `org-export-to-buffer'
5538 and `org-export-to-file' for more specialized functions."
5539 (declare (indent 1) (debug t))
5540 (org-with-gensyms (process temp-file copy-fun proc-buffer coding)
5541 ;; Write the full sexp evaluating BODY in a copy of the current
5542 ;; buffer to a temporary file, as it may be too long for program
5543 ;; args in `start-process'.
5544 `(with-temp-message "Initializing asynchronous export process"
5545 (let ((,copy-fun (org-export--generate-copy-script (current-buffer)))
5546 (,temp-file (make-temp-file "org-export-process"))
5547 (,coding buffer-file-coding-system))
5548 (with-temp-file ,temp-file
5549 (insert
5550 ;; Null characters (from variable values) are inserted
5551 ;; within the file. As a consequence, coding system for
5552 ;; buffer contents will not be recognized properly. So,
5553 ;; we make sure it is the same as the one used to display
5554 ;; the original buffer.
5555 (format ";; -*- coding: %s; -*-\n%S"
5556 ,coding
5557 `(with-temp-buffer
5558 (when org-export-async-debug '(setq debug-on-error t))
5559 ;; Ignore `kill-emacs-hook' and code evaluation
5560 ;; queries from Babel as we need a truly
5561 ;; non-interactive process.
5562 (setq kill-emacs-hook nil
5563 org-babel-confirm-evaluate-answer-no t)
5564 ;; Initialize export framework.
5565 (require 'ox)
5566 ;; Re-create current buffer there.
5567 (funcall ,,copy-fun)
5568 (restore-buffer-modified-p nil)
5569 ;; Sexp to evaluate in the buffer.
5570 (print (progn ,,@body))))))
5571 ;; Start external process.
5572 (let* ((process-connection-type nil)
5573 (,proc-buffer (generate-new-buffer-name "*Org Export Process*"))
5574 (,process
5575 (apply
5576 #'start-process
5577 (append
5578 (list "org-export-process"
5579 ,proc-buffer
5580 (expand-file-name invocation-name invocation-directory)
5581 "--batch")
5582 (if org-export-async-init-file
5583 (list "-Q" "-l" org-export-async-init-file)
5584 (list "-l" user-init-file))
5585 (list "-l" ,temp-file)))))
5586 ;; Register running process in stack.
5587 (org-export-add-to-stack (get-buffer ,proc-buffer) nil ,process)
5588 ;; Set-up sentinel in order to catch results.
5589 (let ((handler ,fun))
5590 (set-process-sentinel
5591 ,process
5592 `(lambda (p status)
5593 (let ((proc-buffer (process-buffer p)))
5594 (when (eq (process-status p) 'exit)
5595 (unwind-protect
5596 (if (zerop (process-exit-status p))
5597 (unwind-protect
5598 (let ((results
5599 (with-current-buffer proc-buffer
5600 (goto-char (point-max))
5601 (backward-sexp)
5602 (read (current-buffer)))))
5603 (funcall ,handler results))
5604 (unless org-export-async-debug
5605 (and (get-buffer proc-buffer)
5606 (kill-buffer proc-buffer))))
5607 (org-export-add-to-stack proc-buffer nil p)
5608 (ding)
5609 (message "Process '%s' exited abnormally" p))
5610 (unless org-export-async-debug
5611 (delete-file ,,temp-file)))))))))))))
5613 ;;;###autoload
5614 (defun org-export-to-buffer
5615 (backend buffer
5616 &optional async subtreep visible-only body-only ext-plist
5617 post-process)
5618 "Call `org-export-as' with output to a specified buffer.
5620 BACKEND is either an export back-end, as returned by, e.g.,
5621 `org-export-create-backend', or a symbol referring to
5622 a registered back-end.
5624 BUFFER is the name of the output buffer. If it already exists,
5625 it will be erased first, otherwise, it will be created.
5627 A non-nil optional argument ASYNC means the process should happen
5628 asynchronously. The resulting buffer should then be accessible
5629 through the `org-export-stack' interface. When ASYNC is nil, the
5630 buffer is displayed if `org-export-show-temporary-export-buffer'
5631 is non-nil.
5633 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
5634 EXT-PLIST are similar to those used in `org-export-as', which
5635 see.
5637 Optional argument POST-PROCESS is a function which should accept
5638 no argument. It is always called within the current process,
5639 from BUFFER, with point at its beginning. Export back-ends can
5640 use it to set a major mode there, e.g,
5642 \(defun org-latex-export-as-latex
5643 \(&optional async subtreep visible-only body-only ext-plist)
5644 \(interactive)
5645 \(org-export-to-buffer 'latex \"*Org LATEX Export*\"
5646 async subtreep visible-only body-only ext-plist (lambda () (LaTeX-mode))))
5648 This function returns BUFFER."
5649 (declare (indent 2))
5650 (if async
5651 (org-export-async-start
5652 `(lambda (output)
5653 (with-current-buffer (get-buffer-create ,buffer)
5654 (erase-buffer)
5655 (setq buffer-file-coding-system ',buffer-file-coding-system)
5656 (insert output)
5657 (goto-char (point-min))
5658 (org-export-add-to-stack (current-buffer) ',backend)
5659 (ignore-errors (funcall ,post-process))))
5660 `(org-export-as
5661 ',backend ,subtreep ,visible-only ,body-only ',ext-plist))
5662 (let ((output
5663 (org-export-as backend subtreep visible-only body-only ext-plist))
5664 (buffer (get-buffer-create buffer))
5665 (encoding buffer-file-coding-system))
5666 (when (and (org-string-nw-p output) (org-export--copy-to-kill-ring-p))
5667 (org-kill-new output))
5668 (with-current-buffer buffer
5669 (erase-buffer)
5670 (setq buffer-file-coding-system encoding)
5671 (insert output)
5672 (goto-char (point-min))
5673 (and (functionp post-process) (funcall post-process)))
5674 (when org-export-show-temporary-export-buffer
5675 (switch-to-buffer-other-window buffer))
5676 buffer)))
5678 ;;;###autoload
5679 (defun org-export-to-file
5680 (backend file &optional async subtreep visible-only body-only ext-plist
5681 post-process)
5682 "Call `org-export-as' with output to a specified file.
5684 BACKEND is either an export back-end, as returned by, e.g.,
5685 `org-export-create-backend', or a symbol referring to
5686 a registered back-end. FILE is the name of the output file, as
5687 a string.
5689 A non-nil optional argument ASYNC means the process should happen
5690 asynchronously. The resulting buffer file then be accessible
5691 through the `org-export-stack' interface.
5693 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
5694 EXT-PLIST are similar to those used in `org-export-as', which
5695 see.
5697 Optional argument POST-PROCESS is called with FILE as its
5698 argument and happens asynchronously when ASYNC is non-nil. It
5699 has to return a file name, or nil. Export back-ends can use this
5700 to send the output file through additional processing, e.g,
5702 \(defun org-latex-export-to-latex
5703 \(&optional async subtreep visible-only body-only ext-plist)
5704 \(interactive)
5705 \(let ((outfile (org-export-output-file-name \".tex\" subtreep)))
5706 \(org-export-to-file 'latex outfile
5707 async subtreep visible-only body-only ext-plist
5708 \(lambda (file) (org-latex-compile file)))
5710 The function returns either a file name returned by POST-PROCESS,
5711 or FILE."
5712 (declare (indent 2))
5713 (if (not (file-writable-p file)) (error "Output file not writable")
5714 (let ((encoding (or org-export-coding-system buffer-file-coding-system)))
5715 (if async
5716 (org-export-async-start
5717 `(lambda (file)
5718 (org-export-add-to-stack (expand-file-name file) ',backend))
5719 `(let ((output
5720 (org-export-as
5721 ',backend ,subtreep ,visible-only ,body-only
5722 ',ext-plist)))
5723 (with-temp-buffer
5724 (insert output)
5725 (let ((coding-system-for-write ',encoding))
5726 (write-file ,file)))
5727 (or (ignore-errors (funcall ',post-process ,file)) ,file)))
5728 (let ((output (org-export-as
5729 backend subtreep visible-only body-only ext-plist)))
5730 (with-temp-buffer
5731 (insert output)
5732 (let ((coding-system-for-write encoding))
5733 (write-file file)))
5734 (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p output))
5735 (org-kill-new output))
5736 ;; Get proper return value.
5737 (or (and (functionp post-process) (funcall post-process file))
5738 file))))))
5740 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
5741 "Return output file's name according to buffer specifications.
5743 EXTENSION is a string representing the output file extension,
5744 with the leading dot.
5746 With a non-nil optional argument SUBTREEP, try to determine
5747 output file's name by looking for \"EXPORT_FILE_NAME\" property
5748 of subtree at point.
5750 When optional argument PUB-DIR is set, use it as the publishing
5751 directory.
5753 When optional argument VISIBLE-ONLY is non-nil, don't export
5754 contents of hidden elements.
5756 Return file name as a string."
5757 (let* ((visited-file (buffer-file-name (buffer-base-buffer)))
5758 (base-name
5759 ;; File name may come from EXPORT_FILE_NAME subtree
5760 ;; property, assuming point is at beginning of said
5761 ;; sub-tree.
5762 (file-name-sans-extension
5763 (or (and subtreep
5764 (org-entry-get
5765 (save-excursion
5766 (ignore-errors (org-back-to-heading) (point)))
5767 "EXPORT_FILE_NAME" t))
5768 ;; File name may be extracted from buffer's associated
5769 ;; file, if any.
5770 (and visited-file (file-name-nondirectory visited-file))
5771 ;; Can't determine file name on our own: Ask user.
5772 (let ((read-file-name-function
5773 (and org-completion-use-ido 'ido-read-file-name)))
5774 (read-file-name
5775 "Output file: " pub-dir nil nil nil
5776 (lambda (name)
5777 (string= (file-name-extension name t) extension)))))))
5778 (output-file
5779 ;; Build file name. Enforce EXTENSION over whatever user
5780 ;; may have come up with. PUB-DIR, if defined, always has
5781 ;; precedence over any provided path.
5782 (cond
5783 (pub-dir
5784 (concat (file-name-as-directory pub-dir)
5785 (file-name-nondirectory base-name)
5786 extension))
5787 ((file-name-absolute-p base-name) (concat base-name extension))
5788 (t (concat (file-name-as-directory ".") base-name extension)))))
5789 ;; If writing to OUTPUT-FILE would overwrite original file, append
5790 ;; EXTENSION another time to final name.
5791 (if (and visited-file (org-file-equal-p visited-file output-file))
5792 (concat output-file extension)
5793 output-file)))
5795 (defun org-export-add-to-stack (source backend &optional process)
5796 "Add a new result to export stack if not present already.
5798 SOURCE is a buffer or a file name containing export results.
5799 BACKEND is a symbol representing export back-end used to generate
5802 Entries already pointing to SOURCE and unavailable entries are
5803 removed beforehand. Return the new stack."
5804 (setq org-export-stack-contents
5805 (cons (list source backend (or process (current-time)))
5806 (org-export-stack-remove source))))
5808 (defun org-export-stack ()
5809 "Menu for asynchronous export results and running processes."
5810 (interactive)
5811 (let ((buffer (get-buffer-create "*Org Export Stack*")))
5812 (set-buffer buffer)
5813 (when (zerop (buffer-size)) (org-export-stack-mode))
5814 (org-export-stack-refresh)
5815 (pop-to-buffer buffer))
5816 (message "Type \"q\" to quit, \"?\" for help"))
5818 (defun org-export--stack-source-at-point ()
5819 "Return source from export results at point in stack."
5820 (let ((source (car (nth (1- (org-current-line)) org-export-stack-contents))))
5821 (if (not source) (error "Source unavailable, please refresh buffer")
5822 (let ((source-name (if (stringp source) source (buffer-name source))))
5823 (if (save-excursion
5824 (beginning-of-line)
5825 (looking-at (concat ".* +" (regexp-quote source-name) "$")))
5826 source
5827 ;; SOURCE is not consistent with current line. The stack
5828 ;; view is outdated.
5829 (error "Source unavailable; type `g' to update buffer"))))))
5831 (defun org-export-stack-clear ()
5832 "Remove all entries from export stack."
5833 (interactive)
5834 (setq org-export-stack-contents nil))
5836 (defun org-export-stack-refresh (&rest dummy)
5837 "Refresh the asynchronous export stack.
5838 DUMMY is ignored. Unavailable sources are removed from the list.
5839 Return the new stack."
5840 (let ((inhibit-read-only t))
5841 (org-preserve-lc
5842 (erase-buffer)
5843 (insert (concat
5844 (let ((counter 0))
5845 (mapconcat
5846 (lambda (entry)
5847 (let ((proc-p (processp (nth 2 entry))))
5848 (concat
5849 ;; Back-end.
5850 (format " %-12s " (or (nth 1 entry) ""))
5851 ;; Age.
5852 (let ((data (nth 2 entry)))
5853 (if proc-p (format " %6s " (process-status data))
5854 ;; Compute age of the results.
5855 (org-format-seconds
5856 "%4h:%.2m "
5857 (float-time (time-since data)))))
5858 ;; Source.
5859 (format " %s"
5860 (let ((source (car entry)))
5861 (if (stringp source) source
5862 (buffer-name source)))))))
5863 ;; Clear stack from exited processes, dead buffers or
5864 ;; non-existent files.
5865 (setq org-export-stack-contents
5866 (org-remove-if-not
5867 (lambda (el)
5868 (if (processp (nth 2 el))
5869 (buffer-live-p (process-buffer (nth 2 el)))
5870 (let ((source (car el)))
5871 (if (bufferp source) (buffer-live-p source)
5872 (file-exists-p source)))))
5873 org-export-stack-contents)) "\n")))))))
5875 (defun org-export-stack-remove (&optional source)
5876 "Remove export results at point from stack.
5877 If optional argument SOURCE is non-nil, remove it instead."
5878 (interactive)
5879 (let ((source (or source (org-export--stack-source-at-point))))
5880 (setq org-export-stack-contents
5881 (org-remove-if (lambda (el) (equal (car el) source))
5882 org-export-stack-contents))))
5884 (defun org-export-stack-view (&optional in-emacs)
5885 "View export results at point in stack.
5886 With an optional prefix argument IN-EMACS, force viewing files
5887 within Emacs."
5888 (interactive "P")
5889 (let ((source (org-export--stack-source-at-point)))
5890 (cond ((processp source)
5891 (org-switch-to-buffer-other-window (process-buffer source)))
5892 ((bufferp source) (org-switch-to-buffer-other-window source))
5893 (t (org-open-file source in-emacs)))))
5895 (defvar org-export-stack-mode-map
5896 (let ((km (make-sparse-keymap)))
5897 (define-key km " " 'next-line)
5898 (define-key km "n" 'next-line)
5899 (define-key km "\C-n" 'next-line)
5900 (define-key km [down] 'next-line)
5901 (define-key km "p" 'previous-line)
5902 (define-key km "\C-p" 'previous-line)
5903 (define-key km "\C-?" 'previous-line)
5904 (define-key km [up] 'previous-line)
5905 (define-key km "C" 'org-export-stack-clear)
5906 (define-key km "v" 'org-export-stack-view)
5907 (define-key km (kbd "RET") 'org-export-stack-view)
5908 (define-key km "d" 'org-export-stack-remove)
5910 "Keymap for Org Export Stack.")
5912 (define-derived-mode org-export-stack-mode special-mode "Org-Stack"
5913 "Mode for displaying asynchronous export stack.
5915 Type \\[org-export-stack] to visualize the asynchronous export
5916 stack.
5918 In an Org Export Stack buffer, use \\<org-export-stack-mode-map>\\[org-export-stack-view] to view export output
5919 on current line, \\[org-export-stack-remove] to remove it from the stack and \\[org-export-stack-clear] to clear
5920 stack completely.
5922 Removing entries in an Org Export Stack buffer doesn't affect
5923 files or buffers, only the display.
5925 \\{org-export-stack-mode-map}"
5926 (abbrev-mode 0)
5927 (auto-fill-mode 0)
5928 (setq buffer-read-only t
5929 buffer-undo-list t
5930 truncate-lines t
5931 header-line-format
5932 '(:eval
5933 (format " %-12s | %6s | %s" "Back-End" "Age" "Source")))
5934 (org-add-hook 'post-command-hook 'org-export-stack-refresh nil t)
5935 (set (make-local-variable 'revert-buffer-function)
5936 'org-export-stack-refresh))
5940 ;;; The Dispatcher
5942 ;; `org-export-dispatch' is the standard interactive way to start an
5943 ;; export process. It uses `org-export--dispatch-ui' as a subroutine
5944 ;; for its interface, which, in turn, delegates response to key
5945 ;; pressed to `org-export--dispatch-action'.
5947 ;;;###autoload
5948 (defun org-export-dispatch (&optional arg)
5949 "Export dispatcher for Org mode.
5951 It provides an access to common export related tasks in a buffer.
5952 Its interface comes in two flavours: standard and expert.
5954 While both share the same set of bindings, only the former
5955 displays the valid keys associations in a dedicated buffer.
5956 Scrolling (resp. line-wise motion) in this buffer is done with
5957 SPC and DEL (resp. C-n and C-p) keys.
5959 Set variable `org-export-dispatch-use-expert-ui' to switch to one
5960 flavour or the other.
5962 When ARG is \\[universal-argument], repeat the last export action, with the same set
5963 of options used back then, on the current buffer.
5965 When ARG is \\[universal-argument] \\[universal-argument], display the asynchronous export stack."
5966 (interactive "P")
5967 (let* ((input
5968 (cond ((equal arg '(16)) '(stack))
5969 ((and arg org-export-dispatch-last-action))
5970 (t (save-window-excursion
5971 (unwind-protect
5972 (progn
5973 ;; Remember where we are
5974 (move-marker org-export-dispatch-last-position
5975 (point)
5976 (org-base-buffer (current-buffer)))
5977 ;; Get and store an export command
5978 (setq org-export-dispatch-last-action
5979 (org-export--dispatch-ui
5980 (list org-export-initial-scope
5981 (and org-export-in-background 'async))
5983 org-export-dispatch-use-expert-ui)))
5984 (and (get-buffer "*Org Export Dispatcher*")
5985 (kill-buffer "*Org Export Dispatcher*")))))))
5986 (action (car input))
5987 (optns (cdr input)))
5988 (unless (memq 'subtree optns)
5989 (move-marker org-export-dispatch-last-position nil))
5990 (case action
5991 ;; First handle special hard-coded actions.
5992 (template (org-export-insert-default-template nil optns))
5993 (stack (org-export-stack))
5994 (publish-current-file
5995 (org-publish-current-file (memq 'force optns) (memq 'async optns)))
5996 (publish-current-project
5997 (org-publish-current-project (memq 'force optns) (memq 'async optns)))
5998 (publish-choose-project
5999 (org-publish (assoc (org-icompleting-read
6000 "Publish project: "
6001 org-publish-project-alist nil t)
6002 org-publish-project-alist)
6003 (memq 'force optns)
6004 (memq 'async optns)))
6005 (publish-all (org-publish-all (memq 'force optns) (memq 'async optns)))
6006 (otherwise
6007 (save-excursion
6008 (when arg
6009 ;; Repeating command, maybe move cursor to restore subtree
6010 ;; context.
6011 (if (eq (marker-buffer org-export-dispatch-last-position)
6012 (org-base-buffer (current-buffer)))
6013 (goto-char org-export-dispatch-last-position)
6014 ;; We are in a different buffer, forget position.
6015 (move-marker org-export-dispatch-last-position nil)))
6016 (funcall action
6017 ;; Return a symbol instead of a list to ease
6018 ;; asynchronous export macro use.
6019 (and (memq 'async optns) t)
6020 (and (memq 'subtree optns) t)
6021 (and (memq 'visible optns) t)
6022 (and (memq 'body optns) t)))))))
6024 (defun org-export--dispatch-ui (options first-key expertp)
6025 "Handle interface for `org-export-dispatch'.
6027 OPTIONS is a list containing current interactive options set for
6028 export. It can contain any of the following symbols:
6029 `body' toggles a body-only export
6030 `subtree' restricts export to current subtree
6031 `visible' restricts export to visible part of buffer.
6032 `force' force publishing files.
6033 `async' use asynchronous export process
6035 FIRST-KEY is the key pressed to select the first level menu. It
6036 is nil when this menu hasn't been selected yet.
6038 EXPERTP, when non-nil, triggers expert UI. In that case, no help
6039 buffer is provided, but indications about currently active
6040 options are given in the prompt. Moreover, \[?] allows to switch
6041 back to standard interface."
6042 (let* ((fontify-key
6043 (lambda (key &optional access-key)
6044 ;; Fontify KEY string. Optional argument ACCESS-KEY, when
6045 ;; non-nil is the required first-level key to activate
6046 ;; KEY. When its value is t, activate KEY independently
6047 ;; on the first key, if any. A nil value means KEY will
6048 ;; only be activated at first level.
6049 (if (or (eq access-key t) (eq access-key first-key))
6050 (org-propertize key 'face 'org-warning)
6051 key)))
6052 (fontify-value
6053 (lambda (value)
6054 ;; Fontify VALUE string.
6055 (org-propertize value 'face 'font-lock-variable-name-face)))
6056 ;; Prepare menu entries by extracting them from registered
6057 ;; back-ends and sorting them by access key and by ordinal,
6058 ;; if any.
6059 (entries
6060 (sort (sort (delq nil
6061 (mapcar 'org-export-backend-menu
6062 org-export--registered-backends))
6063 (lambda (a b)
6064 (let ((key-a (nth 1 a))
6065 (key-b (nth 1 b)))
6066 (cond ((and (numberp key-a) (numberp key-b))
6067 (< key-a key-b))
6068 ((numberp key-b) t)))))
6069 'car-less-than-car))
6070 ;; Compute a list of allowed keys based on the first key
6071 ;; pressed, if any. Some keys
6072 ;; (?^B, ?^V, ?^S, ?^F, ?^A, ?&, ?# and ?q) are always
6073 ;; available.
6074 (allowed-keys
6075 (nconc (list 2 22 19 6 1)
6076 (if (not first-key) (org-uniquify (mapcar 'car entries))
6077 (let (sub-menu)
6078 (dolist (entry entries (sort (mapcar 'car sub-menu) '<))
6079 (when (eq (car entry) first-key)
6080 (setq sub-menu (append (nth 2 entry) sub-menu))))))
6081 (cond ((eq first-key ?P) (list ?f ?p ?x ?a))
6082 ((not first-key) (list ?P)))
6083 (list ?& ?#)
6084 (when expertp (list ??))
6085 (list ?q)))
6086 ;; Build the help menu for standard UI.
6087 (help
6088 (unless expertp
6089 (concat
6090 ;; Options are hard-coded.
6091 (format "[%s] Body only: %s [%s] Visible only: %s
6092 \[%s] Export scope: %s [%s] Force publishing: %s
6093 \[%s] Async export: %s\n\n"
6094 (funcall fontify-key "C-b" t)
6095 (funcall fontify-value
6096 (if (memq 'body options) "On " "Off"))
6097 (funcall fontify-key "C-v" t)
6098 (funcall fontify-value
6099 (if (memq 'visible options) "On " "Off"))
6100 (funcall fontify-key "C-s" t)
6101 (funcall fontify-value
6102 (if (memq 'subtree options) "Subtree" "Buffer "))
6103 (funcall fontify-key "C-f" t)
6104 (funcall fontify-value
6105 (if (memq 'force options) "On " "Off"))
6106 (funcall fontify-key "C-a" t)
6107 (funcall fontify-value
6108 (if (memq 'async options) "On " "Off")))
6109 ;; Display registered back-end entries. When a key
6110 ;; appears for the second time, do not create another
6111 ;; entry, but append its sub-menu to existing menu.
6112 (let (last-key)
6113 (mapconcat
6114 (lambda (entry)
6115 (let ((top-key (car entry)))
6116 (concat
6117 (unless (eq top-key last-key)
6118 (setq last-key top-key)
6119 (format "\n[%s] %s\n"
6120 (funcall fontify-key (char-to-string top-key))
6121 (nth 1 entry)))
6122 (let ((sub-menu (nth 2 entry)))
6123 (unless (functionp sub-menu)
6124 ;; Split sub-menu into two columns.
6125 (let ((index -1))
6126 (concat
6127 (mapconcat
6128 (lambda (sub-entry)
6129 (incf index)
6130 (format
6131 (if (zerop (mod index 2)) " [%s] %-26s"
6132 "[%s] %s\n")
6133 (funcall fontify-key
6134 (char-to-string (car sub-entry))
6135 top-key)
6136 (nth 1 sub-entry)))
6137 sub-menu "")
6138 (when (zerop (mod index 2)) "\n"))))))))
6139 entries ""))
6140 ;; Publishing menu is hard-coded.
6141 (format "\n[%s] Publish
6142 [%s] Current file [%s] Current project
6143 [%s] Choose project [%s] All projects\n\n\n"
6144 (funcall fontify-key "P")
6145 (funcall fontify-key "f" ?P)
6146 (funcall fontify-key "p" ?P)
6147 (funcall fontify-key "x" ?P)
6148 (funcall fontify-key "a" ?P))
6149 (format "[%s] Export stack [%s] Insert template\n"
6150 (funcall fontify-key "&" t)
6151 (funcall fontify-key "#" t))
6152 (format "[%s] %s"
6153 (funcall fontify-key "q" t)
6154 (if first-key "Main menu" "Exit")))))
6155 ;; Build prompts for both standard and expert UI.
6156 (standard-prompt (unless expertp "Export command: "))
6157 (expert-prompt
6158 (when expertp
6159 (format
6160 "Export command (C-%s%s%s%s%s) [%s]: "
6161 (if (memq 'body options) (funcall fontify-key "b" t) "b")
6162 (if (memq 'visible options) (funcall fontify-key "v" t) "v")
6163 (if (memq 'subtree options) (funcall fontify-key "s" t) "s")
6164 (if (memq 'force options) (funcall fontify-key "f" t) "f")
6165 (if (memq 'async options) (funcall fontify-key "a" t) "a")
6166 (mapconcat (lambda (k)
6167 ;; Strip control characters.
6168 (unless (< k 27) (char-to-string k)))
6169 allowed-keys "")))))
6170 ;; With expert UI, just read key with a fancy prompt. In standard
6171 ;; UI, display an intrusive help buffer.
6172 (if expertp
6173 (org-export--dispatch-action
6174 expert-prompt allowed-keys entries options first-key expertp)
6175 ;; At first call, create frame layout in order to display menu.
6176 (unless (get-buffer "*Org Export Dispatcher*")
6177 (delete-other-windows)
6178 (org-switch-to-buffer-other-window
6179 (get-buffer-create "*Org Export Dispatcher*"))
6180 (setq cursor-type nil
6181 header-line-format "Use SPC, DEL, C-n or C-p to navigate.")
6182 ;; Make sure that invisible cursor will not highlight square
6183 ;; brackets.
6184 (set-syntax-table (copy-syntax-table))
6185 (modify-syntax-entry ?\[ "w"))
6186 ;; At this point, the buffer containing the menu exists and is
6187 ;; visible in the current window. So, refresh it.
6188 (with-current-buffer "*Org Export Dispatcher*"
6189 ;; Refresh help. Maintain display continuity by re-visiting
6190 ;; previous window position.
6191 (let ((pos (window-start)))
6192 (erase-buffer)
6193 (insert help)
6194 (set-window-start nil pos)))
6195 (org-fit-window-to-buffer)
6196 (org-export--dispatch-action
6197 standard-prompt allowed-keys entries options first-key expertp))))
6199 (defun org-export--dispatch-action
6200 (prompt allowed-keys entries options first-key expertp)
6201 "Read a character from command input and act accordingly.
6203 PROMPT is the displayed prompt, as a string. ALLOWED-KEYS is
6204 a list of characters available at a given step in the process.
6205 ENTRIES is a list of menu entries. OPTIONS, FIRST-KEY and
6206 EXPERTP are the same as defined in `org-export--dispatch-ui',
6207 which see.
6209 Toggle export options when required. Otherwise, return value is
6210 a list with action as CAR and a list of interactive export
6211 options as CDR."
6212 (let (key)
6213 ;; Scrolling: when in non-expert mode, act on motion keys (C-n,
6214 ;; C-p, SPC, DEL).
6215 (while (and (setq key (read-char-exclusive prompt))
6216 (not expertp)
6217 (memq key '(14 16 ?\s ?\d)))
6218 (case key
6219 (14 (if (not (pos-visible-in-window-p (point-max)))
6220 (ignore-errors (scroll-up 1))
6221 (message "End of buffer")
6222 (sit-for 1)))
6223 (16 (if (not (pos-visible-in-window-p (point-min)))
6224 (ignore-errors (scroll-down 1))
6225 (message "Beginning of buffer")
6226 (sit-for 1)))
6227 (?\s (if (not (pos-visible-in-window-p (point-max)))
6228 (scroll-up nil)
6229 (message "End of buffer")
6230 (sit-for 1)))
6231 (?\d (if (not (pos-visible-in-window-p (point-min)))
6232 (scroll-down nil)
6233 (message "Beginning of buffer")
6234 (sit-for 1)))))
6235 (cond
6236 ;; Ignore undefined associations.
6237 ((not (memq key allowed-keys))
6238 (ding)
6239 (unless expertp (message "Invalid key") (sit-for 1))
6240 (org-export--dispatch-ui options first-key expertp))
6241 ;; q key at first level aborts export. At second level, cancel
6242 ;; first key instead.
6243 ((eq key ?q) (if (not first-key) (error "Export aborted")
6244 (org-export--dispatch-ui options nil expertp)))
6245 ;; Help key: Switch back to standard interface if expert UI was
6246 ;; active.
6247 ((eq key ??) (org-export--dispatch-ui options first-key nil))
6248 ;; Send request for template insertion along with export scope.
6249 ((eq key ?#) (cons 'template (memq 'subtree options)))
6250 ;; Switch to asynchronous export stack.
6251 ((eq key ?&) '(stack))
6252 ;; Toggle options: C-b (2) C-v (22) C-s (19) C-f (6) C-a (1).
6253 ((memq key '(2 22 19 6 1))
6254 (org-export--dispatch-ui
6255 (let ((option (case key (2 'body) (22 'visible) (19 'subtree)
6256 (6 'force) (1 'async))))
6257 (if (memq option options) (remq option options)
6258 (cons option options)))
6259 first-key expertp))
6260 ;; Action selected: Send key and options back to
6261 ;; `org-export-dispatch'.
6262 ((or first-key (functionp (nth 2 (assq key entries))))
6263 (cons (cond
6264 ((not first-key) (nth 2 (assq key entries)))
6265 ;; Publishing actions are hard-coded. Send a special
6266 ;; signal to `org-export-dispatch'.
6267 ((eq first-key ?P)
6268 (case key
6269 (?f 'publish-current-file)
6270 (?p 'publish-current-project)
6271 (?x 'publish-choose-project)
6272 (?a 'publish-all)))
6273 ;; Return first action associated to FIRST-KEY + KEY
6274 ;; path. Indeed, derived backends can share the same
6275 ;; FIRST-KEY.
6276 (t (catch 'found
6277 (mapc (lambda (entry)
6278 (let ((match (assq key (nth 2 entry))))
6279 (when match (throw 'found (nth 2 match)))))
6280 (member (assq first-key entries) entries)))))
6281 options))
6282 ;; Otherwise, enter sub-menu.
6283 (t (org-export--dispatch-ui options key expertp)))))
6287 (provide 'ox)
6289 ;; Local variables:
6290 ;; generated-autoload-file: "org-loaddefs.el"
6291 ;; End:
6293 ;;; ox.el ends here