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