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