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