Fix storing link in edit buffer
[org-mode/org-tableheadings.git] / lisp / ox.el
blobfede7c98510d552185bc73a76ba12260e6661903
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 parse)
102 (:date "DATE" nil nil parse)
103 (:author "AUTHOR" nil user-full-name parse)
104 (:email "EMAIL" nil user-mail-address t)
105 (:language "LANGUAGE" nil org-export-default-language t)
106 (:select-tags "SELECT_TAGS" nil org-export-select-tags split)
107 (:exclude-tags "EXCLUDE_TAGS" nil org-export-exclude-tags split)
108 (:creator "CREATOR" nil org-export-creator-string)
109 (:headline-levels nil "H" org-export-headline-levels)
110 (:preserve-breaks nil "\\n" org-export-preserve-breaks)
111 (:section-numbers nil "num" org-export-with-section-numbers)
112 (:time-stamp-file nil "timestamp" org-export-time-stamp-file)
113 (:with-archived-trees nil "arch" org-export-with-archived-trees)
114 (:with-author nil "author" org-export-with-author)
115 (:with-clocks nil "c" org-export-with-clocks)
116 (:with-creator nil "creator" org-export-with-creator)
117 (:with-date nil "date" org-export-with-date)
118 (:with-drawers nil "d" org-export-with-drawers)
119 (:with-email nil "email" org-export-with-email)
120 (:with-emphasize nil "*" org-export-with-emphasize)
121 (:with-entities nil "e" org-export-with-entities)
122 (:with-fixed-width nil ":" org-export-with-fixed-width)
123 (:with-footnotes nil "f" org-export-with-footnotes)
124 (:with-inlinetasks nil "inline" org-export-with-inlinetasks)
125 (:with-latex nil "tex" org-export-with-latex)
126 (:with-planning nil "p" org-export-with-planning)
127 (:with-priority nil "pri" org-export-with-priority)
128 (:with-properties nil "prop" org-export-with-properties)
129 (:with-smart-quotes nil "'" org-export-with-smart-quotes)
130 (:with-special-strings nil "-" org-export-with-special-strings)
131 (:with-statistics-cookies nil "stat" org-export-with-statistics-cookies)
132 (:with-sub-superscript nil "^" org-export-with-sub-superscripts)
133 (:with-toc nil "toc" org-export-with-toc)
134 (:with-tables nil "|" org-export-with-tables)
135 (:with-tags nil "tags" org-export-with-tags)
136 (:with-tasks nil "tasks" org-export-with-tasks)
137 (:with-timestamps nil "<" org-export-with-timestamps)
138 (:with-title nil "title" org-export-with-title)
139 (:with-todo-keywords nil "todo" org-export-with-todo-keywords))
140 "Alist between export properties and ways to set them.
142 The key of the alist is the property name, and the value is a list
143 like (KEYWORD OPTION DEFAULT BEHAVIOR) where:
145 KEYWORD is a string representing a buffer keyword, or nil. Each
146 property defined this way can also be set, during subtree
147 export, through a headline property named after the keyword
148 with the \"EXPORT_\" prefix (i.e. DATE keyword and EXPORT_DATE
149 property).
150 OPTION is a string that could be found in an #+OPTIONS: line.
151 DEFAULT is the default value for the property.
152 BEHAVIOR determines how Org should handle multiple keywords for
153 the same property. It is a symbol among:
154 nil Keep old value and discard the new one.
155 t Replace old value with the new one.
156 `space' Concatenate the values, separating them with a space.
157 `newline' Concatenate the values, separating them with
158 a newline.
159 `split' Split values at white spaces, and cons them to the
160 previous list.
161 `parse' Parse value as a list of strings and Org objects,
162 which can then be transcoded with, e.g.,
163 `org-export-data'. It implies `space' behavior.
165 Values set through KEYWORD and OPTION have precedence over
166 DEFAULT.
168 All these properties should be back-end agnostic. Back-end
169 specific properties are set through `org-export-define-backend'.
170 Properties redefined there have precedence over these.")
172 (defconst org-export-special-keywords '("FILETAGS" "SETUPFILE" "OPTIONS")
173 "List of in-buffer keywords that require special treatment.
174 These keywords are not directly associated to a property. The
175 way they are handled must be hard-coded into
176 `org-export--get-inbuffer-options' function.")
178 (defconst org-export-filters-alist
179 '((:filter-body . org-export-filter-body-functions)
180 (:filter-bold . org-export-filter-bold-functions)
181 (:filter-babel-call . org-export-filter-babel-call-functions)
182 (:filter-center-block . org-export-filter-center-block-functions)
183 (:filter-clock . org-export-filter-clock-functions)
184 (:filter-code . org-export-filter-code-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 nil
365 "Non-nil means the postamble should contain a creator sentence.
367 The sentence can be set in `org-export-creator-string', which
368 see.
370 This option can also be set with the OPTIONS keyword, e.g.,
371 \"creator:t\"."
372 :group 'org-export-general
373 :version "25.1"
374 :package-version '(Org . "8.3")
375 :type 'boolean)
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-with-title t
747 "Non-nil means print title into the exported file.
748 This option can also be set with the OPTIONS keyword,
749 e.g. \"title:nil\"."
750 :group 'org-export-general
751 :version "25.1"
752 :package-version '(Org . "8.3")
753 :type 'boolean)
755 (defcustom org-export-time-stamp-file t
756 "Non-nil means insert a time stamp into the exported file.
757 The time stamp shows when the file was created. This option can
758 also be set with the OPTIONS keyword, e.g. \"timestamp:nil\"."
759 :group 'org-export-general
760 :type 'boolean)
762 (defcustom org-export-with-timestamps t
763 "Non nil means allow timestamps in export.
765 It can be set to any of the following values:
766 t export all timestamps.
767 `active' export active timestamps only.
768 `inactive' export inactive timestamps only.
769 nil do not export timestamps
771 This only applies to timestamps isolated in a paragraph
772 containing only timestamps. Other timestamps are always
773 exported.
775 This option can also be set with the OPTIONS keyword, e.g.
776 \"<:nil\"."
777 :group 'org-export-general
778 :type '(choice
779 (const :tag "All timestamps" t)
780 (const :tag "Only active timestamps" active)
781 (const :tag "Only inactive timestamps" inactive)
782 (const :tag "No timestamp" nil)))
784 (defcustom org-export-with-todo-keywords t
785 "Non-nil means include TODO keywords in export.
786 When nil, remove all these keywords from the export. This option
787 can also be set with the OPTIONS keyword, e.g. \"todo:nil\"."
788 :group 'org-export-general
789 :type 'boolean)
791 (defcustom org-export-allow-bind-keywords nil
792 "Non-nil means BIND keywords can define local variable values.
793 This is a potential security risk, which is why the default value
794 is nil. You can also allow them through local buffer variables."
795 :group 'org-export-general
796 :version "24.4"
797 :package-version '(Org . "8.0")
798 :type 'boolean)
800 (defcustom org-export-snippet-translation-alist nil
801 "Alist between export snippets back-ends and exporter back-ends.
803 This variable allows to provide shortcuts for export snippets.
805 For example, with a value of '\(\(\"h\" . \"html\"\)\), the
806 HTML back-end will recognize the contents of \"@@h:<b>@@\" as
807 HTML code while every other back-end will ignore it."
808 :group 'org-export-general
809 :version "24.4"
810 :package-version '(Org . "8.0")
811 :type '(repeat
812 (cons (string :tag "Shortcut")
813 (string :tag "Back-end"))))
815 (defcustom org-export-coding-system nil
816 "Coding system for the exported file."
817 :group 'org-export-general
818 :version "24.4"
819 :package-version '(Org . "8.0")
820 :type 'coding-system)
822 (defcustom org-export-copy-to-kill-ring nil
823 "Non-nil means pushing export output to the kill ring.
824 This variable is ignored during asynchronous export."
825 :group 'org-export-general
826 :version "25.1"
827 :package-version '(Org . "8.3")
828 :type '(choice
829 (const :tag "Always" t)
830 (const :tag "When export is done interactively" if-interactive)
831 (const :tag "Never" nil)))
833 (defcustom org-export-initial-scope 'buffer
834 "The initial scope when exporting with `org-export-dispatch'.
835 This variable can be either set to `buffer' or `subtree'."
836 :group 'org-export-general
837 :type '(choice
838 (const :tag "Export current buffer" buffer)
839 (const :tag "Export current subtree" subtree)))
841 (defcustom org-export-show-temporary-export-buffer t
842 "Non-nil means show buffer after exporting to temp buffer.
843 When Org exports to a file, the buffer visiting that file is never
844 shown, but remains buried. However, when exporting to
845 a temporary buffer, that buffer is popped up in a second window.
846 When this variable is nil, the buffer remains buried also in
847 these cases."
848 :group 'org-export-general
849 :type 'boolean)
851 (defcustom org-export-in-background nil
852 "Non-nil means export and publishing commands will run in background.
853 Results from an asynchronous export are never displayed
854 automatically. But you can retrieve them with \\[org-export-stack]."
855 :group 'org-export-general
856 :version "24.4"
857 :package-version '(Org . "8.0")
858 :type 'boolean)
860 (defcustom org-export-async-init-file nil
861 "File used to initialize external export process.
863 Value must be either nil or an absolute file name. When nil, the
864 external process is launched like a regular Emacs session,
865 loading user's initialization file and any site specific
866 configuration. If a file is provided, it, and only it, is loaded
867 at start-up.
869 Therefore, using a specific configuration makes the process to
870 load faster and the export more portable."
871 :group 'org-export-general
872 :version "24.4"
873 :package-version '(Org . "8.0")
874 :type '(choice
875 (const :tag "Regular startup" nil)
876 (file :tag "Specific start-up file" :must-match t)))
878 (defcustom org-export-dispatch-use-expert-ui nil
879 "Non-nil means using a non-intrusive `org-export-dispatch'.
880 In that case, no help buffer is displayed. Though, an indicator
881 for current export scope is added to the prompt (\"b\" when
882 output is restricted to body only, \"s\" when it is restricted to
883 the current subtree, \"v\" when only visible elements are
884 considered for export, \"f\" when publishing functions should be
885 passed the FORCE argument and \"a\" when the export should be
886 asynchronous). Also, \[?] allows to switch back to standard
887 mode."
888 :group 'org-export-general
889 :version "24.4"
890 :package-version '(Org . "8.0")
891 :type 'boolean)
895 ;;; Defining Back-ends
897 ;; An export back-end is a structure with `org-export-backend' type
898 ;; and `name', `parent', `transcoders', `options', `filters', `blocks'
899 ;; and `menu' slots.
901 ;; At the lowest level, a back-end is created with
902 ;; `org-export-create-backend' function.
904 ;; A named back-end can be registered with
905 ;; `org-export-register-backend' function. A registered back-end can
906 ;; later be referred to by its name, with `org-export-get-backend'
907 ;; function. Also, such a back-end can become the parent of a derived
908 ;; back-end from which slot values will be inherited by default.
909 ;; `org-export-derived-backend-p' can check if a given back-end is
910 ;; derived from a list of back-end names.
912 ;; `org-export-get-all-transcoders', `org-export-get-all-options' and
913 ;; `org-export-get-all-filters' return the full alist of transcoders,
914 ;; options and filters, including those inherited from ancestors.
916 ;; At a higher level, `org-export-define-backend' is the standard way
917 ;; to define an export back-end. If the new back-end is similar to
918 ;; a registered back-end, `org-export-define-derived-backend' may be
919 ;; used instead.
921 ;; Eventually `org-export-barf-if-invalid-backend' returns an error
922 ;; when a given back-end hasn't been registered yet.
924 (defstruct (org-export-backend (:constructor org-export-create-backend)
925 (:copier nil))
926 name parent transcoders options filters blocks menu)
928 (defun org-export-get-backend (name)
929 "Return export back-end named after NAME.
930 NAME is a symbol. Return nil if no such back-end is found."
931 (catch 'found
932 (dolist (b org-export-registered-backends)
933 (when (eq (org-export-backend-name b) name)
934 (throw 'found b)))))
936 (defun org-export-register-backend (backend)
937 "Register BACKEND as a known export back-end.
938 BACKEND is a structure with `org-export-backend' type."
939 ;; Refuse to register an unnamed back-end.
940 (unless (org-export-backend-name backend)
941 (error "Cannot register a unnamed export back-end"))
942 ;; Refuse to register a back-end with an unknown parent.
943 (let ((parent (org-export-backend-parent backend)))
944 (when (and parent (not (org-export-get-backend parent)))
945 (error "Cannot use unknown \"%s\" back-end as a parent" parent)))
946 ;; Register dedicated export blocks in the parser.
947 (dolist (name (org-export-backend-blocks backend))
948 (add-to-list 'org-element-block-name-alist
949 (cons name 'org-element-export-block-parser)))
950 ;; If a back-end with the same name as BACKEND is already
951 ;; registered, replace it with BACKEND. Otherwise, simply add
952 ;; BACKEND to the list of registered back-ends.
953 (let ((old (org-export-get-backend (org-export-backend-name backend))))
954 (if old (setcar (memq old org-export-registered-backends) backend)
955 (push backend org-export-registered-backends))))
957 (defun org-export-barf-if-invalid-backend (backend)
958 "Signal an error if BACKEND isn't defined."
959 (unless (org-export-backend-p backend)
960 (error "Unknown \"%s\" back-end: Aborting export" backend)))
962 (defun org-export-derived-backend-p (backend &rest backends)
963 "Non-nil if BACKEND is derived from one of BACKENDS.
964 BACKEND is an export back-end, as returned by, e.g.,
965 `org-export-create-backend', or a symbol referring to
966 a registered back-end. BACKENDS is constituted of symbols."
967 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
968 (when backend
969 (catch 'exit
970 (while (org-export-backend-parent backend)
971 (when (memq (org-export-backend-name backend) backends)
972 (throw 'exit t))
973 (setq backend
974 (org-export-get-backend (org-export-backend-parent backend))))
975 (memq (org-export-backend-name backend) backends))))
977 (defun org-export-get-all-transcoders (backend)
978 "Return full translation table for BACKEND.
980 BACKEND is an export back-end, as return by, e.g,,
981 `org-export-create-backend'. Return value is an alist where
982 keys are element or object types, as symbols, and values are
983 transcoders.
985 Unlike to `org-export-backend-transcoders', this function
986 also returns transcoders inherited from parent back-ends,
987 if any."
988 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
989 (when backend
990 (let ((transcoders (org-export-backend-transcoders backend))
991 parent)
992 (while (setq parent (org-export-backend-parent backend))
993 (setq backend (org-export-get-backend parent))
994 (setq transcoders
995 (append transcoders (org-export-backend-transcoders backend))))
996 transcoders)))
998 (defun org-export-get-all-options (backend)
999 "Return export options for BACKEND.
1001 BACKEND is an export back-end, as return by, e.g,,
1002 `org-export-create-backend'. See `org-export-options-alist'
1003 for the shape of the return value.
1005 Unlike to `org-export-backend-options', this function also
1006 returns options inherited from parent back-ends, if any."
1007 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
1008 (when backend
1009 (let ((options (org-export-backend-options backend))
1010 parent)
1011 (while (setq parent (org-export-backend-parent backend))
1012 (setq backend (org-export-get-backend parent))
1013 (setq options (append options (org-export-backend-options backend))))
1014 options)))
1016 (defun org-export-get-all-filters (backend)
1017 "Return complete list of filters for BACKEND.
1019 BACKEND is an export back-end, as return by, e.g,,
1020 `org-export-create-backend'. Return value is an alist where
1021 keys are symbols and values lists of functions.
1023 Unlike to `org-export-backend-filters', this function also
1024 returns filters inherited from parent back-ends, if any."
1025 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
1026 (when backend
1027 (let ((filters (org-export-backend-filters backend))
1028 parent)
1029 (while (setq parent (org-export-backend-parent backend))
1030 (setq backend (org-export-get-backend parent))
1031 (setq filters (append filters (org-export-backend-filters backend))))
1032 filters)))
1034 (defun org-export-define-backend (backend transcoders &rest body)
1035 "Define a new back-end BACKEND.
1037 TRANSCODERS is an alist between object or element types and
1038 functions handling them.
1040 These functions should return a string without any trailing
1041 space, or nil. They must accept three arguments: the object or
1042 element itself, its contents or nil when it isn't recursive and
1043 the property list used as a communication channel.
1045 Contents, when not nil, are stripped from any global indentation
1046 \(although the relative one is preserved). They also always end
1047 with a single newline character.
1049 If, for a given type, no function is found, that element or
1050 object type will simply be ignored, along with any blank line or
1051 white space at its end. The same will happen if the function
1052 returns the nil value. If that function returns the empty
1053 string, the type will be ignored, but the blank lines or white
1054 spaces will be kept.
1056 In addition to element and object types, one function can be
1057 associated to the `template' (or `inner-template') symbol and
1058 another one to the `plain-text' symbol.
1060 The former returns the final transcoded string, and can be used
1061 to add a preamble and a postamble to document's body. It must
1062 accept two arguments: the transcoded string and the property list
1063 containing export options. A function associated to `template'
1064 will not be applied if export has option \"body-only\".
1065 A function associated to `inner-template' is always applied.
1067 The latter, when defined, is to be called on every text not
1068 recognized as an element or an object. It must accept two
1069 arguments: the text string and the information channel. It is an
1070 appropriate place to protect special chars relative to the
1071 back-end.
1073 BODY can start with pre-defined keyword arguments. The following
1074 keywords are understood:
1076 :export-block
1078 String, or list of strings, representing block names that
1079 will not be parsed. This is used to specify blocks that will
1080 contain raw code specific to the back-end. These blocks
1081 still have to be handled by the relative `export-block' type
1082 translator.
1084 :filters-alist
1086 Alist between filters and function, or list of functions,
1087 specific to the back-end. See `org-export-filters-alist' for
1088 a list of all allowed filters. Filters defined here
1089 shouldn't make a back-end test, as it may prevent back-ends
1090 derived from this one to behave properly.
1092 :menu-entry
1094 Menu entry for the export dispatcher. It should be a list
1095 like:
1097 '(KEY DESCRIPTION-OR-ORDINAL ACTION-OR-MENU)
1099 where :
1101 KEY is a free character selecting the back-end.
1103 DESCRIPTION-OR-ORDINAL is either a string or a number.
1105 If it is a string, is will be used to name the back-end in
1106 its menu entry. If it is a number, the following menu will
1107 be displayed as a sub-menu of the back-end with the same
1108 KEY. Also, the number will be used to determine in which
1109 order such sub-menus will appear (lowest first).
1111 ACTION-OR-MENU is either a function or an alist.
1113 If it is an action, it will be called with four
1114 arguments (booleans): ASYNC, SUBTREEP, VISIBLE-ONLY and
1115 BODY-ONLY. See `org-export-as' for further explanations on
1116 some of them.
1118 If it is an alist, associations should follow the
1119 pattern:
1121 '(KEY DESCRIPTION ACTION)
1123 where KEY, DESCRIPTION and ACTION are described above.
1125 Valid values include:
1127 '(?m \"My Special Back-end\" my-special-export-function)
1131 '(?l \"Export to LaTeX\"
1132 \(?p \"As PDF file\" org-latex-export-to-pdf)
1133 \(?o \"As PDF file and open\"
1134 \(lambda (a s v b)
1135 \(if a (org-latex-export-to-pdf t s v b)
1136 \(org-open-file
1137 \(org-latex-export-to-pdf nil s v b)))))))
1139 or the following, which will be added to the previous
1140 sub-menu,
1142 '(?l 1
1143 \((?B \"As TEX buffer (Beamer)\" org-beamer-export-as-latex)
1144 \(?P \"As PDF file (Beamer)\" org-beamer-export-to-pdf)))
1146 :options-alist
1148 Alist between back-end specific properties introduced in
1149 communication channel and how their value are acquired. See
1150 `org-export-options-alist' for more information about
1151 structure of the values."
1152 (declare (indent 1))
1153 (let (blocks filters menu-entry options contents)
1154 (while (keywordp (car body))
1155 (let ((keyword (pop body)))
1156 (case keyword
1157 (:export-block (let ((names (pop body)))
1158 (setq blocks (if (consp names) (mapcar 'upcase names)
1159 (list (upcase names))))))
1160 (:filters-alist (setq filters (pop body)))
1161 (:menu-entry (setq menu-entry (pop body)))
1162 (:options-alist (setq options (pop body)))
1163 (t (error "Unknown keyword: %s" keyword)))))
1164 (org-export-register-backend
1165 (org-export-create-backend :name backend
1166 :transcoders transcoders
1167 :options options
1168 :filters filters
1169 :blocks blocks
1170 :menu menu-entry))))
1172 (defun org-export-define-derived-backend (child parent &rest body)
1173 "Create a new back-end as a variant of an existing one.
1175 CHILD is the name of the derived back-end. PARENT is the name of
1176 the parent back-end.
1178 BODY can start with pre-defined keyword arguments. The following
1179 keywords are understood:
1181 :export-block
1183 String, or list of strings, representing block names that
1184 will not be parsed. This is used to specify blocks that will
1185 contain raw code specific to the back-end. These blocks
1186 still have to be handled by the relative `export-block' type
1187 translator.
1189 :filters-alist
1191 Alist of filters that will overwrite or complete filters
1192 defined in PARENT back-end. See `org-export-filters-alist'
1193 for a list of allowed filters.
1195 :menu-entry
1197 Menu entry for the export dispatcher. See
1198 `org-export-define-backend' for more information about the
1199 expected value.
1201 :options-alist
1203 Alist of back-end specific properties that will overwrite or
1204 complete those defined in PARENT back-end. Refer to
1205 `org-export-options-alist' for more information about
1206 structure of the values.
1208 :translate-alist
1210 Alist of element and object types and transcoders that will
1211 overwrite or complete transcode table from PARENT back-end.
1212 Refer to `org-export-define-backend' for detailed information
1213 about transcoders.
1215 As an example, here is how one could define \"my-latex\" back-end
1216 as a variant of `latex' back-end with a custom template function:
1218 \(org-export-define-derived-backend 'my-latex 'latex
1219 :translate-alist '((template . my-latex-template-fun)))
1221 The back-end could then be called with, for example:
1223 \(org-export-to-buffer 'my-latex \"*Test my-latex*\")"
1224 (declare (indent 2))
1225 (let (blocks filters menu-entry options transcoders contents)
1226 (while (keywordp (car body))
1227 (let ((keyword (pop body)))
1228 (case keyword
1229 (:export-block (let ((names (pop body)))
1230 (setq blocks (if (consp names) (mapcar 'upcase names)
1231 (list (upcase names))))))
1232 (:filters-alist (setq filters (pop body)))
1233 (:menu-entry (setq menu-entry (pop body)))
1234 (:options-alist (setq options (pop body)))
1235 (:translate-alist (setq transcoders (pop body)))
1236 (t (error "Unknown keyword: %s" keyword)))))
1237 (org-export-register-backend
1238 (org-export-create-backend :name child
1239 :parent parent
1240 :transcoders transcoders
1241 :options options
1242 :filters filters
1243 :blocks blocks
1244 :menu menu-entry))))
1248 ;;; The Communication Channel
1250 ;; During export process, every function has access to a number of
1251 ;; properties. They are of two types:
1253 ;; 1. Environment options are collected once at the very beginning of
1254 ;; the process, out of the original buffer and configuration.
1255 ;; Collecting them is handled by `org-export-get-environment'
1256 ;; function.
1258 ;; Most environment options are defined through the
1259 ;; `org-export-options-alist' variable.
1261 ;; 2. Tree properties are extracted directly from the parsed tree,
1262 ;; just before export, by `org-export-collect-tree-properties'.
1264 ;;;; Environment Options
1266 ;; Environment options encompass all parameters defined outside the
1267 ;; scope of the parsed data. They come from five sources, in
1268 ;; increasing precedence order:
1270 ;; - Global variables,
1271 ;; - Buffer's attributes,
1272 ;; - Options keyword symbols,
1273 ;; - Buffer keywords,
1274 ;; - Subtree properties.
1276 ;; The central internal function with regards to environment options
1277 ;; is `org-export-get-environment'. It updates global variables with
1278 ;; "#+BIND:" keywords, then retrieve and prioritize properties from
1279 ;; the different sources.
1281 ;; The internal functions doing the retrieval are:
1282 ;; `org-export--get-global-options',
1283 ;; `org-export--get-buffer-attributes',
1284 ;; `org-export--parse-option-keyword',
1285 ;; `org-export--get-subtree-options' and
1286 ;; `org-export--get-inbuffer-options'
1288 ;; Also, `org-export--list-bound-variables' collects bound variables
1289 ;; along with their value in order to set them as buffer local
1290 ;; variables later in the process.
1292 (defun org-export-get-environment (&optional backend subtreep ext-plist)
1293 "Collect export options from the current buffer.
1295 Optional argument BACKEND is an export back-end, as returned by
1296 `org-export-create-backend'.
1298 When optional argument SUBTREEP is non-nil, assume the export is
1299 done against the current sub-tree.
1301 Third optional argument EXT-PLIST is a property list with
1302 external parameters overriding Org default settings, but still
1303 inferior to file-local settings."
1304 ;; First install #+BIND variables since these must be set before
1305 ;; global options are read.
1306 (dolist (pair (org-export--list-bound-variables))
1307 (org-set-local (car pair) (nth 1 pair)))
1308 ;; Get and prioritize export options...
1309 (org-combine-plists
1310 ;; ... from global variables...
1311 (org-export--get-global-options backend)
1312 ;; ... from an external property list...
1313 ext-plist
1314 ;; ... from in-buffer settings...
1315 (org-export--get-inbuffer-options backend)
1316 ;; ... and from subtree, when appropriate.
1317 (and subtreep (org-export--get-subtree-options backend))
1318 ;; Eventually add misc. properties.
1319 (list
1320 :back-end
1321 backend
1322 :translate-alist (org-export-get-all-transcoders backend)
1323 :footnote-definition-alist
1324 ;; Footnotes definitions must be collected in the original
1325 ;; buffer, as there's no insurance that they will still be in
1326 ;; the parse tree, due to possible narrowing.
1327 (let (alist)
1328 (org-with-wide-buffer
1329 (goto-char (point-min))
1330 (while (re-search-forward org-footnote-re nil t)
1331 (backward-char)
1332 (let ((fn (save-match-data (org-element-context))))
1333 (case (org-element-type fn)
1334 (footnote-definition
1335 (push
1336 (cons (org-element-property :label fn)
1337 (let ((cbeg (org-element-property :contents-begin fn)))
1338 (when cbeg
1339 (org-element--parse-elements
1340 cbeg (org-element-property :contents-end fn)
1341 nil nil nil nil (list 'org-data nil)))))
1342 alist))
1343 (footnote-reference
1344 (let ((label (org-element-property :label fn))
1345 (cbeg (org-element-property :contents-begin fn)))
1346 (when (and label cbeg
1347 (eq (org-element-property :type fn) 'inline))
1348 (push
1349 (cons label
1350 (org-element-parse-secondary-string
1351 (buffer-substring
1352 cbeg (org-element-property :contents-end fn))
1353 (org-element-restriction 'footnote-reference)))
1354 alist)))))))
1355 alist))
1356 :id-alist
1357 ;; Collect id references.
1358 (let (alist)
1359 (org-with-wide-buffer
1360 (goto-char (point-min))
1361 (while (re-search-forward "\\[\\[id:\\S-+?\\]" nil t)
1362 (let ((link (org-element-context)))
1363 (when (eq (org-element-type link) 'link)
1364 (let* ((id (org-element-property :path link))
1365 (file (car (org-id-find id))))
1366 (when file
1367 (push (cons id (file-relative-name file)) alist)))))))
1368 alist))))
1370 (defun org-export--parse-option-keyword (options &optional backend)
1371 "Parse an OPTIONS line and return values as a plist.
1372 Optional argument BACKEND is an export back-end, as returned by,
1373 e.g., `org-export-create-backend'. It specifies which back-end
1374 specific items to read, if any."
1375 (let ((all
1376 (mapcar
1377 (lambda (o) (cons (nth 2 o) (car o)))
1378 ;; Priority is given to back-end specific options.
1379 (append (and backend (org-export-get-all-options backend))
1380 org-export-options-alist)))
1381 (start)
1382 plist)
1383 (while (string-match "\\(.+?\\):\\((.*?)\\|\\S-*\\)[ \t\n]*" options start)
1384 (setq start (match-end 0))
1385 (let ((property (cdr (assoc-string (match-string 1 options) all t))))
1386 (when property
1387 (setq plist
1388 (plist-put plist property (read (match-string 2 options)))))))
1389 plist))
1391 (defun org-export--get-subtree-options (&optional backend)
1392 "Get export options in subtree at point.
1393 Optional argument BACKEND is an export back-end, as returned by,
1394 e.g., `org-export-create-backend'. It specifies back-end used
1395 for export. Return options as a plist."
1396 ;; For each buffer keyword, create a headline property setting the
1397 ;; same property in communication channel. The name for the
1398 ;; property is the keyword with "EXPORT_" appended to it.
1399 (org-with-wide-buffer
1400 (let (plist
1401 ;; Look for both general keywords and back-end specific
1402 ;; options, with priority given to the latter.
1403 (options (append (and backend (org-export-get-all-options backend))
1404 org-export-options-alist)))
1405 ;; Make sure point is at a heading.
1406 (if (org-at-heading-p) (org-up-heading-safe) (org-back-to-heading t))
1407 ;; Take care of EXPORT_TITLE. If it isn't defined, use
1408 ;; headline's title (with no todo keyword, priority cookie or
1409 ;; tag) as its fallback value.
1410 (let ((title (or (org-entry-get (point) "EXPORT_TITLE")
1411 (progn (looking-at org-complex-heading-regexp)
1412 (org-match-string-no-properties 4)))))
1413 (setq plist
1414 (plist-put
1415 plist :title
1416 (if (eq (nth 4 (assq :title options)) 'parse)
1417 (org-element-parse-secondary-string
1418 title (org-element-restriction 'keyword))
1419 title))))
1420 ;; EXPORT_OPTIONS are parsed in a non-standard way.
1421 (let ((o (org-entry-get (point) "EXPORT_OPTIONS")))
1422 (when o
1423 (setq plist
1424 (nconc plist (org-export--parse-option-keyword o backend)))))
1425 ;; Handle other keywords. TITLE keyword is excluded as it has
1426 ;; been handled already. Then return PLIST.
1427 (let ((seen '("TITLE")))
1428 (dolist (option options plist)
1429 (let ((property (car option))
1430 (keyword (nth 1 option)))
1431 (when (and keyword (not (member keyword seen)))
1432 (let* ((subtree-prop (concat "EXPORT_" keyword))
1433 (value (org-entry-get (point) subtree-prop)))
1434 (push keyword seen)
1435 (when (and value (not (plist-member plist property)))
1436 (setq plist
1437 (plist-put
1438 plist
1439 property
1440 (case (nth 4 option)
1441 (parse
1442 (org-element-parse-secondary-string
1443 value (org-element-restriction 'keyword)))
1444 (split (org-split-string value))
1445 (t value)))))))))))))
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 to-parse
1474 (get-options
1475 (lambda (&optional files plist)
1476 ;; Recursively read keywords in buffer. FILES is a list
1477 ;; of files read so far. PLIST is the current property
1478 ;; list obtained.
1479 (org-with-wide-buffer
1480 (goto-char (point-min))
1481 (while (re-search-forward regexp nil t)
1482 (let ((element (org-element-at-point)))
1483 (when (eq (org-element-type element) 'keyword)
1484 (let ((key (org-element-property :key element))
1485 (val (org-element-property :value element)))
1486 (cond
1487 ;; Options in `org-export-special-keywords'.
1488 ((equal key "SETUPFILE")
1489 (let ((file (expand-file-name
1490 (org-remove-double-quotes (org-trim val)))))
1491 ;; Avoid circular dependencies.
1492 (unless (member file files)
1493 (with-temp-buffer
1494 (insert (org-file-contents file 'noerror))
1495 (let ((org-inhibit-startup t)) (org-mode))
1496 (setq plist (funcall get-options
1497 (cons file files) plist))))))
1498 ((equal key "OPTIONS")
1499 (setq plist
1500 (org-combine-plists
1501 plist
1502 (org-export--parse-option-keyword val backend))))
1503 ((equal key "FILETAGS")
1504 (setq plist
1505 (org-combine-plists
1506 plist
1507 (list :filetags
1508 (org-uniquify
1509 (append (org-split-string val ":")
1510 (plist-get plist :filetags)))))))
1512 ;; Options in `org-export-options-alist'.
1513 (dolist (property (funcall find-properties key))
1514 (setq
1515 plist
1516 (plist-put
1517 plist property
1518 ;; Handle value depending on specified
1519 ;; BEHAVIOR.
1520 (case (nth 4 (assq property options))
1521 (parse
1522 (unless (memq property to-parse)
1523 (push property to-parse))
1524 ;; Even if `parse' implies `space'
1525 ;; behavior, we separate line with "\n"
1526 ;; so as to preserve line-breaks.
1527 ;; However, empty lines are forbidden
1528 ;; since `parse' doesn't allow more than
1529 ;; one paragraph.
1530 (let ((old (plist-get plist property)))
1531 (cond ((not (org-string-nw-p val)) old)
1532 (old (concat old "\n" val))
1533 (t val))))
1534 (space
1535 (if (not (plist-get plist property))
1536 (org-trim val)
1537 (concat (plist-get plist property)
1539 (org-trim val))))
1540 (newline
1541 (org-trim
1542 (concat (plist-get plist property)
1543 "\n"
1544 (org-trim val))))
1545 (split `(,@(plist-get plist property)
1546 ,@(org-split-string val)))
1547 ((t) val)
1548 (otherwise
1549 (if (not (plist-member plist property)) val
1550 (plist-get plist property)))))))))))))
1551 plist))))
1552 ;; Read options in the current buffer and return value.
1553 (let ((options (funcall get-options
1554 (and buffer-file-name (list buffer-file-name))
1555 nil)))
1556 ;; Parse properties in TO-PARSE. Remove newline characters not
1557 ;; involved in line breaks to simulate `space' behaviour.
1558 ;; Finally return options.
1559 (dolist (p to-parse options)
1560 (let ((value (org-element-parse-secondary-string
1561 (plist-get options p)
1562 (org-element-restriction 'keyword))))
1563 (org-element-map value 'plain-text
1564 (lambda (s)
1565 (org-element-set-element
1566 s (replace-regexp-in-string "\n" " " s))))
1567 (setq options (plist-put options p value)))))))
1569 (defun org-export--get-buffer-attributes ()
1570 "Return properties related to buffer attributes, as a plist."
1571 (list :input-buffer (buffer-name (buffer-base-buffer))
1572 :input-file (buffer-file-name (buffer-base-buffer))))
1574 (defun org-export--get-global-options (&optional backend)
1575 "Return global export options as a plist.
1576 Optional argument BACKEND, if non-nil, is an export back-end, as
1577 returned by, e.g., `org-export-create-backend'. It specifies
1578 which back-end specific export options should also be read in the
1579 process."
1580 (let (plist
1581 ;; Priority is given to back-end specific options.
1582 (all (append (and backend (org-export-get-all-options backend))
1583 org-export-options-alist)))
1584 (dolist (cell all plist)
1585 (let ((prop (car cell)))
1586 (unless (plist-member plist prop)
1587 (setq plist
1588 (plist-put
1589 plist
1590 prop
1591 ;; Evaluate default value provided.
1592 (let ((value (eval (nth 3 cell))))
1593 (if (eq (nth 4 cell) 'parse)
1594 (org-element-parse-secondary-string
1595 value (org-element-restriction 'keyword))
1596 value)))))))))
1598 (defun org-export--list-bound-variables ()
1599 "Return variables bound from BIND keywords in current buffer.
1600 Also look for BIND keywords in setup files. The return value is
1601 an alist where associations are (VARIABLE-NAME VALUE)."
1602 (when org-export-allow-bind-keywords
1603 (let* (collect-bind ; For byte-compiler.
1604 (collect-bind
1605 (lambda (files alist)
1606 ;; Return an alist between variable names and their
1607 ;; value. FILES is a list of setup files names read so
1608 ;; far, used to avoid circular dependencies. ALIST is
1609 ;; the alist collected so far.
1610 (let ((case-fold-search t))
1611 (org-with-wide-buffer
1612 (goto-char (point-min))
1613 (while (re-search-forward
1614 "^[ \t]*#\\+\\(BIND\\|SETUPFILE\\):" nil t)
1615 (let ((element (org-element-at-point)))
1616 (when (eq (org-element-type element) 'keyword)
1617 (let ((val (org-element-property :value element)))
1618 (if (equal (org-element-property :key element) "BIND")
1619 (push (read (format "(%s)" val)) alist)
1620 ;; Enter setup file.
1621 (let ((file (expand-file-name
1622 (org-remove-double-quotes val))))
1623 (unless (member file files)
1624 (with-temp-buffer
1625 (let ((org-inhibit-startup t)) (org-mode))
1626 (insert (org-file-contents file 'noerror))
1627 (setq alist
1628 (funcall collect-bind
1629 (cons file files)
1630 alist))))))))))
1631 alist)))))
1632 ;; Return value in appropriate order of appearance.
1633 (nreverse (funcall collect-bind nil nil)))))
1635 ;; defsubst org-export-get-parent must be defined before first use,
1636 ;; was originally defined in the topology section
1638 (defsubst org-export-get-parent (blob)
1639 "Return BLOB parent or nil.
1640 BLOB is the element or object considered."
1641 (org-element-property :parent blob))
1643 ;;;; Tree Properties
1645 ;; Tree properties are information extracted from parse tree. They
1646 ;; are initialized at the beginning of the transcoding process by
1647 ;; `org-export-collect-tree-properties'.
1649 ;; Dedicated functions focus on computing the value of specific tree
1650 ;; properties during initialization. Thus,
1651 ;; `org-export--populate-ignore-list' lists elements and objects that
1652 ;; should be skipped during export, `org-export--get-min-level' gets
1653 ;; the minimal exportable level, used as a basis to compute relative
1654 ;; level for headlines. Eventually
1655 ;; `org-export--collect-headline-numbering' builds an alist between
1656 ;; headlines and their numbering.
1658 (defun org-export-collect-tree-properties (data info)
1659 "Extract tree properties from parse tree.
1661 DATA is the parse tree from which information is retrieved. INFO
1662 is a list holding export options.
1664 Following tree properties are set or updated:
1666 `:exported-data' Hash table used to memoize results from
1667 `org-export-data'.
1669 `:footnote-definition-alist' List of footnotes definitions in
1670 original buffer and current parse tree.
1672 `:headline-offset' Offset between true level of headlines and
1673 local level. An offset of -1 means a headline
1674 of level 2 should be considered as a level
1675 1 headline in the context.
1677 `:headline-numbering' Alist of all headlines as key an the
1678 associated numbering as value.
1680 Return updated plist."
1681 ;; Install the parse tree in the communication channel.
1682 (setq info (plist-put info :parse-tree data))
1683 ;; Compute `:headline-offset' in order to be able to use
1684 ;; `org-export-get-relative-level'.
1685 (setq info
1686 (plist-put info
1687 :headline-offset
1688 (- 1 (org-export--get-min-level data info))))
1689 ;; Footnote definitions in parse tree override those stored in
1690 ;; `:footnote-definition-alist'. This way, any change to
1691 ;; a definition in the parse tree (e.g., through a parse tree
1692 ;; filter) propagates into the alist.
1693 (let ((defs (plist-get info :footnote-definition-alist)))
1694 (org-element-map data '(footnote-definition footnote-reference)
1695 (lambda (fn)
1696 (cond ((eq (org-element-type fn) 'footnote-definition)
1697 (push (cons (org-element-property :label fn)
1698 (append '(org-data nil) (org-element-contents fn)))
1699 defs))
1700 ((eq (org-element-property :type fn) 'inline)
1701 (push (cons (org-element-property :label fn)
1702 (org-element-contents fn))
1703 defs)))))
1704 (setq info (plist-put info :footnote-definition-alist defs)))
1705 ;; Properties order doesn't matter: get the rest of the tree
1706 ;; properties.
1707 (nconc
1708 `(:headline-numbering ,(org-export--collect-headline-numbering data info)
1709 :exported-data ,(make-hash-table :test 'eq :size 4001))
1710 info))
1712 (defun org-export--get-min-level (data options)
1713 "Return minimum exportable headline's level in DATA.
1714 DATA is parsed tree as returned by `org-element-parse-buffer'.
1715 OPTIONS is a plist holding export options."
1716 (catch 'exit
1717 (let ((min-level 10000))
1718 (mapc
1719 (lambda (blob)
1720 (when (and (eq (org-element-type blob) 'headline)
1721 (not (org-element-property :footnote-section-p blob))
1722 (not (memq blob (plist-get options :ignore-list))))
1723 (setq min-level (min (org-element-property :level blob) min-level)))
1724 (when (= min-level 1) (throw 'exit 1)))
1725 (org-element-contents data))
1726 ;; If no headline was found, for the sake of consistency, set
1727 ;; minimum level to 1 nonetheless.
1728 (if (= min-level 10000) 1 min-level))))
1730 (defun org-export--collect-headline-numbering (data options)
1731 "Return numbering of all exportable, numbered headlines in a parse tree.
1733 DATA is the parse tree. OPTIONS is the plist holding export
1734 options.
1736 Return an alist whose key is a headline and value is its
1737 associated numbering \(in the shape of a list of numbers\) or nil
1738 for a footnotes section."
1739 (let ((numbering (make-vector org-export-max-depth 0)))
1740 (org-element-map data 'headline
1741 (lambda (headline)
1742 (when (and (org-export-numbered-headline-p headline options)
1743 (not (org-element-property :footnote-section-p headline)))
1744 (let ((relative-level
1745 (1- (org-export-get-relative-level headline options))))
1746 (cons
1747 headline
1748 (loop for n across numbering
1749 for idx from 0 to org-export-max-depth
1750 when (< idx relative-level) collect n
1751 when (= idx relative-level) collect (aset numbering idx (1+ n))
1752 when (> idx relative-level) do (aset numbering idx 0))))))
1753 options)))
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-expand (blob contents &optional with-affiliated)
2018 "Expand a parsed element or object to its original state.
2020 BLOB is either an element or an object. CONTENTS is its
2021 contents, as a string or nil.
2023 When optional argument WITH-AFFILIATED is non-nil, add affiliated
2024 keywords before output."
2025 (let ((type (org-element-type blob)))
2026 (concat (and with-affiliated (memq type org-element-all-elements)
2027 (org-element--interpret-affiliated-keywords blob))
2028 (funcall (intern (format "org-element-%s-interpreter" type))
2029 blob contents))))
2033 ;;; The Filter System
2035 ;; Filters allow end-users to tweak easily the transcoded output.
2036 ;; They are the functional counterpart of hooks, as every filter in
2037 ;; a set is applied to the return value of the previous one.
2039 ;; Every set is back-end agnostic. Although, a filter is always
2040 ;; called, in addition to the string it applies to, with the back-end
2041 ;; used as argument, so it's easy for the end-user to add back-end
2042 ;; specific filters in the set. The communication channel, as
2043 ;; a plist, is required as the third argument.
2045 ;; From the developer side, filters sets can be installed in the
2046 ;; process with the help of `org-export-define-backend', which
2047 ;; internally stores filters as an alist. Each association has a key
2048 ;; among the following symbols and a function or a list of functions
2049 ;; as value.
2051 ;; - `:filter-options' applies to the property list containing export
2052 ;; options. Unlike to other filters, functions in this list accept
2053 ;; two arguments instead of three: the property list containing
2054 ;; export options and the back-end. Users can set its value through
2055 ;; `org-export-filter-options-functions' variable.
2057 ;; - `:filter-parse-tree' applies directly to the complete parsed
2058 ;; tree. Users can set it through
2059 ;; `org-export-filter-parse-tree-functions' variable.
2061 ;; - `:filter-body' applies to the body of the output, before template
2062 ;; translator chimes in. Users can set it through
2063 ;; `org-export-filter-body-functions' variable.
2065 ;; - `:filter-final-output' applies to the final transcoded string.
2066 ;; Users can set it with `org-export-filter-final-output-functions'
2067 ;; variable.
2069 ;; - `:filter-plain-text' applies to any string not recognized as Org
2070 ;; syntax. `org-export-filter-plain-text-functions' allows users to
2071 ;; configure it.
2073 ;; - `:filter-TYPE' applies on the string returned after an element or
2074 ;; object of type TYPE has been transcoded. A user can modify
2075 ;; `org-export-filter-TYPE-functions' to install these filters.
2077 ;; All filters sets are applied with
2078 ;; `org-export-filter-apply-functions' function. Filters in a set are
2079 ;; applied in a LIFO fashion. It allows developers to be sure that
2080 ;; their filters will be applied first.
2082 ;; Filters properties are installed in communication channel with
2083 ;; `org-export-install-filters' function.
2085 ;; Eventually, two hooks (`org-export-before-processing-hook' and
2086 ;; `org-export-before-parsing-hook') are run at the beginning of the
2087 ;; export process and just before parsing to allow for heavy structure
2088 ;; modifications.
2091 ;;;; Hooks
2093 (defvar org-export-before-processing-hook nil
2094 "Hook run at the beginning of the export process.
2096 This is run before include keywords and macros are expanded and
2097 Babel code blocks executed, on a copy of the original buffer
2098 being exported. Visibility and narrowing are preserved. Point
2099 is at the beginning of the buffer.
2101 Every function in this hook will be called with one argument: the
2102 back-end currently used, as a symbol.")
2104 (defvar org-export-before-parsing-hook nil
2105 "Hook run before parsing an export buffer.
2107 This is run after include keywords and macros have been expanded
2108 and Babel code blocks executed, on a copy of the original buffer
2109 being exported. Visibility and narrowing are preserved. Point
2110 is at the beginning of the buffer.
2112 Every function in this hook will be called with one argument: the
2113 back-end currently used, as a symbol.")
2116 ;;;; Special Filters
2118 (defvar org-export-filter-options-functions nil
2119 "List of functions applied to the export options.
2120 Each filter is called with two arguments: the export options, as
2121 a plist, and the back-end, as a symbol. It must return
2122 a property list containing export options.")
2124 (defvar org-export-filter-parse-tree-functions nil
2125 "List of functions applied to the parsed tree.
2126 Each filter is called with three arguments: the parse tree, as
2127 returned by `org-element-parse-buffer', the back-end, as
2128 a symbol, and the communication channel, as a plist. It must
2129 return the modified parse tree to transcode.")
2131 (defvar org-export-filter-plain-text-functions nil
2132 "List of functions applied to plain text.
2133 Each filter is called with three arguments: a string which
2134 contains no Org syntax, the back-end, as a symbol, and the
2135 communication channel, as a plist. It must return a string or
2136 nil.")
2138 (defvar org-export-filter-body-functions nil
2139 "List of functions applied to transcoded body.
2140 Each filter is called with three arguments: a string which
2141 contains no Org syntax, the back-end, as a symbol, and the
2142 communication channel, as a plist. It must return a string or
2143 nil.")
2145 (defvar org-export-filter-final-output-functions nil
2146 "List of functions applied to the transcoded string.
2147 Each filter is called with three arguments: the full transcoded
2148 string, the back-end, as a symbol, and the communication channel,
2149 as a plist. It must return a string that will be used as the
2150 final export output.")
2153 ;;;; Elements Filters
2155 (defvar org-export-filter-babel-call-functions nil
2156 "List of functions applied to a transcoded babel-call.
2157 Each filter is called with three arguments: the transcoded data,
2158 as a string, the back-end, as a symbol, and the communication
2159 channel, as a plist. It must return a string or nil.")
2161 (defvar org-export-filter-center-block-functions nil
2162 "List of functions applied to a transcoded center block.
2163 Each filter is called with three arguments: the transcoded data,
2164 as a string, the back-end, as a symbol, and the communication
2165 channel, as a plist. It must return a string or nil.")
2167 (defvar org-export-filter-clock-functions nil
2168 "List of functions applied to a transcoded clock.
2169 Each filter is called with three arguments: the transcoded data,
2170 as a string, the back-end, as a symbol, and the communication
2171 channel, as a plist. It must return a string or nil.")
2173 (defvar org-export-filter-diary-sexp-functions nil
2174 "List of functions applied to a transcoded diary-sexp.
2175 Each filter is called with three arguments: the transcoded data,
2176 as a string, the back-end, as a symbol, and the communication
2177 channel, as a plist. It must return a string or nil.")
2179 (defvar org-export-filter-drawer-functions nil
2180 "List of functions applied to a transcoded drawer.
2181 Each filter is called with three arguments: the transcoded data,
2182 as a string, the back-end, as a symbol, and the communication
2183 channel, as a plist. It must return a string or nil.")
2185 (defvar org-export-filter-dynamic-block-functions nil
2186 "List of functions applied to a transcoded dynamic-block.
2187 Each filter is called with three arguments: the transcoded data,
2188 as a string, the back-end, as a symbol, and the communication
2189 channel, as a plist. It must return a string or nil.")
2191 (defvar org-export-filter-example-block-functions nil
2192 "List of functions applied to a transcoded example-block.
2193 Each filter is called with three arguments: the transcoded data,
2194 as a string, the back-end, as a symbol, and the communication
2195 channel, as a plist. It must return a string or nil.")
2197 (defvar org-export-filter-export-block-functions nil
2198 "List of functions applied to a transcoded export-block.
2199 Each filter is called with three arguments: the transcoded data,
2200 as a string, the back-end, as a symbol, and the communication
2201 channel, as a plist. It must return a string or nil.")
2203 (defvar org-export-filter-fixed-width-functions nil
2204 "List of functions applied to a transcoded fixed-width.
2205 Each filter is called with three arguments: the transcoded data,
2206 as a string, the back-end, as a symbol, and the communication
2207 channel, as a plist. It must return a string or nil.")
2209 (defvar org-export-filter-footnote-definition-functions nil
2210 "List of functions applied to a transcoded footnote-definition.
2211 Each filter is called with three arguments: the transcoded data,
2212 as a string, the back-end, as a symbol, and the communication
2213 channel, as a plist. It must return a string or nil.")
2215 (defvar org-export-filter-headline-functions nil
2216 "List of functions applied to a transcoded headline.
2217 Each filter is called with three arguments: the transcoded data,
2218 as a string, the back-end, as a symbol, and the communication
2219 channel, as a plist. It must return a string or nil.")
2221 (defvar org-export-filter-horizontal-rule-functions nil
2222 "List of functions applied to a transcoded horizontal-rule.
2223 Each filter is called with three arguments: the transcoded data,
2224 as a string, the back-end, as a symbol, and the communication
2225 channel, as a plist. It must return a string or nil.")
2227 (defvar org-export-filter-inlinetask-functions nil
2228 "List of functions applied to a transcoded inlinetask.
2229 Each filter is called with three arguments: the transcoded data,
2230 as a string, the back-end, as a symbol, and the communication
2231 channel, as a plist. It must return a string or nil.")
2233 (defvar org-export-filter-item-functions nil
2234 "List of functions applied to a transcoded item.
2235 Each filter is called with three arguments: the transcoded data,
2236 as a string, the back-end, as a symbol, and the communication
2237 channel, as a plist. It must return a string or nil.")
2239 (defvar org-export-filter-keyword-functions nil
2240 "List of functions applied to a transcoded keyword.
2241 Each filter is called with three arguments: the transcoded data,
2242 as a string, the back-end, as a symbol, and the communication
2243 channel, as a plist. It must return a string or nil.")
2245 (defvar org-export-filter-latex-environment-functions nil
2246 "List of functions applied to a transcoded latex-environment.
2247 Each filter is called with three arguments: the transcoded data,
2248 as a string, the back-end, as a symbol, and the communication
2249 channel, as a plist. It must return a string or nil.")
2251 (defvar org-export-filter-node-property-functions nil
2252 "List of functions applied to a transcoded node-property.
2253 Each filter is called with three arguments: the transcoded data,
2254 as a string, the back-end, as a symbol, and the communication
2255 channel, as a plist. It must return a string or nil.")
2257 (defvar org-export-filter-paragraph-functions nil
2258 "List of functions applied to a transcoded paragraph.
2259 Each filter is called with three arguments: the transcoded data,
2260 as a string, the back-end, as a symbol, and the communication
2261 channel, as a plist. It must return a string or nil.")
2263 (defvar org-export-filter-plain-list-functions nil
2264 "List of functions applied to a transcoded plain-list.
2265 Each filter is called with three arguments: the transcoded data,
2266 as a string, the back-end, as a symbol, and the communication
2267 channel, as a plist. It must return a string or nil.")
2269 (defvar org-export-filter-planning-functions nil
2270 "List of functions applied to a transcoded planning.
2271 Each filter is called with three arguments: the transcoded data,
2272 as a string, the back-end, as a symbol, and the communication
2273 channel, as a plist. It must return a string or nil.")
2275 (defvar org-export-filter-property-drawer-functions nil
2276 "List of functions applied to a transcoded property-drawer.
2277 Each filter is called with three arguments: the transcoded data,
2278 as a string, the back-end, as a symbol, and the communication
2279 channel, as a plist. It must return a string or nil.")
2281 (defvar org-export-filter-quote-block-functions nil
2282 "List of functions applied to a transcoded quote block.
2283 Each filter is called with three arguments: the transcoded quote
2284 data, as a string, the back-end, as a symbol, and the
2285 communication channel, as a plist. It must return a string or
2286 nil.")
2288 (defvar org-export-filter-section-functions nil
2289 "List of functions applied to a transcoded section.
2290 Each filter is called with three arguments: the transcoded data,
2291 as a string, the back-end, as a symbol, and the communication
2292 channel, as a plist. It must return a string or nil.")
2294 (defvar org-export-filter-special-block-functions nil
2295 "List of functions applied to a transcoded special block.
2296 Each filter is called with three arguments: the transcoded data,
2297 as a string, the back-end, as a symbol, and the communication
2298 channel, as a plist. It must return a string or nil.")
2300 (defvar org-export-filter-src-block-functions nil
2301 "List of functions applied to a transcoded src-block.
2302 Each filter is called with three arguments: the transcoded data,
2303 as a string, the back-end, as a symbol, and the communication
2304 channel, as a plist. It must return a string or nil.")
2306 (defvar org-export-filter-table-functions nil
2307 "List of functions applied to a transcoded table.
2308 Each filter is called with three arguments: the transcoded data,
2309 as a string, the back-end, as a symbol, and the communication
2310 channel, as a plist. It must return a string or nil.")
2312 (defvar org-export-filter-table-cell-functions nil
2313 "List of functions applied to a transcoded table-cell.
2314 Each filter is called with three arguments: the transcoded data,
2315 as a string, the back-end, as a symbol, and the communication
2316 channel, as a plist. It must return a string or nil.")
2318 (defvar org-export-filter-table-row-functions nil
2319 "List of functions applied to a transcoded table-row.
2320 Each filter is called with three arguments: the transcoded data,
2321 as a string, the back-end, as a symbol, and the communication
2322 channel, as a plist. It must return a string or nil.")
2324 (defvar org-export-filter-verse-block-functions nil
2325 "List of functions applied to a transcoded verse block.
2326 Each filter is called with three arguments: the transcoded data,
2327 as a string, the back-end, as a symbol, and the communication
2328 channel, as a plist. It must return a string or nil.")
2331 ;;;; Objects Filters
2333 (defvar org-export-filter-bold-functions nil
2334 "List of functions applied to transcoded bold text.
2335 Each filter is called with three arguments: the transcoded data,
2336 as a string, the back-end, as a symbol, and the communication
2337 channel, as a plist. It must return a string or nil.")
2339 (defvar org-export-filter-code-functions nil
2340 "List of functions applied to transcoded code text.
2341 Each filter is called with three arguments: the transcoded data,
2342 as a string, the back-end, as a symbol, and the communication
2343 channel, as a plist. It must return a string or nil.")
2345 (defvar org-export-filter-entity-functions nil
2346 "List of functions applied to a transcoded entity.
2347 Each filter is called with three arguments: the transcoded data,
2348 as a string, the back-end, as a symbol, and the communication
2349 channel, as a plist. It must return a string or nil.")
2351 (defvar org-export-filter-export-snippet-functions nil
2352 "List of functions applied to a transcoded export-snippet.
2353 Each filter is called with three arguments: the transcoded data,
2354 as a string, the back-end, as a symbol, and the communication
2355 channel, as a plist. It must return a string or nil.")
2357 (defvar org-export-filter-footnote-reference-functions nil
2358 "List of functions applied to a transcoded footnote-reference.
2359 Each filter is called with three arguments: the transcoded data,
2360 as a string, the back-end, as a symbol, and the communication
2361 channel, as a plist. It must return a string or nil.")
2363 (defvar org-export-filter-inline-babel-call-functions nil
2364 "List of functions applied to a transcoded inline-babel-call.
2365 Each filter is called with three arguments: the transcoded data,
2366 as a string, the back-end, as a symbol, and the communication
2367 channel, as a plist. It must return a string or nil.")
2369 (defvar org-export-filter-inline-src-block-functions nil
2370 "List of functions applied to a transcoded inline-src-block.
2371 Each filter is called with three arguments: the transcoded data,
2372 as a string, the back-end, as a symbol, and the communication
2373 channel, as a plist. It must return a string or nil.")
2375 (defvar org-export-filter-italic-functions nil
2376 "List of functions applied to transcoded italic text.
2377 Each filter is called with three arguments: the transcoded data,
2378 as a string, the back-end, as a symbol, and the communication
2379 channel, as a plist. It must return a string or nil.")
2381 (defvar org-export-filter-latex-fragment-functions nil
2382 "List of functions applied to a transcoded latex-fragment.
2383 Each filter is called with three arguments: the transcoded data,
2384 as a string, the back-end, as a symbol, and the communication
2385 channel, as a plist. It must return a string or nil.")
2387 (defvar org-export-filter-line-break-functions nil
2388 "List of functions applied to a transcoded line-break.
2389 Each filter is called with three arguments: the transcoded data,
2390 as a string, the back-end, as a symbol, and the communication
2391 channel, as a plist. It must return a string or nil.")
2393 (defvar org-export-filter-link-functions nil
2394 "List of functions applied to a transcoded link.
2395 Each filter is called with three arguments: the transcoded data,
2396 as a string, the back-end, as a symbol, and the communication
2397 channel, as a plist. It must return a string or nil.")
2399 (defvar org-export-filter-radio-target-functions nil
2400 "List of functions applied to a transcoded radio-target.
2401 Each filter is called with three arguments: the transcoded data,
2402 as a string, the back-end, as a symbol, and the communication
2403 channel, as a plist. It must return a string or nil.")
2405 (defvar org-export-filter-statistics-cookie-functions nil
2406 "List of functions applied to a transcoded statistics-cookie.
2407 Each filter is called with three arguments: the transcoded data,
2408 as a string, the back-end, as a symbol, and the communication
2409 channel, as a plist. It must return a string or nil.")
2411 (defvar org-export-filter-strike-through-functions nil
2412 "List of functions applied to transcoded strike-through text.
2413 Each filter is called with three arguments: the transcoded data,
2414 as a string, the back-end, as a symbol, and the communication
2415 channel, as a plist. It must return a string or nil.")
2417 (defvar org-export-filter-subscript-functions nil
2418 "List of functions applied to a transcoded subscript.
2419 Each filter is called with three arguments: the transcoded data,
2420 as a string, the back-end, as a symbol, and the communication
2421 channel, as a plist. It must return a string or nil.")
2423 (defvar org-export-filter-superscript-functions nil
2424 "List of functions applied to a transcoded superscript.
2425 Each filter is called with three arguments: the transcoded data,
2426 as a string, the back-end, as a symbol, and the communication
2427 channel, as a plist. It must return a string or nil.")
2429 (defvar org-export-filter-target-functions nil
2430 "List of functions applied to a transcoded target.
2431 Each filter is called with three arguments: the transcoded data,
2432 as a string, the back-end, as a symbol, and the communication
2433 channel, as a plist. It must return a string or nil.")
2435 (defvar org-export-filter-timestamp-functions nil
2436 "List of functions applied to a transcoded timestamp.
2437 Each filter is called with three arguments: the transcoded data,
2438 as a string, the back-end, as a symbol, and the communication
2439 channel, as a plist. It must return a string or nil.")
2441 (defvar org-export-filter-underline-functions nil
2442 "List of functions applied to transcoded underline text.
2443 Each filter is called with three arguments: the transcoded data,
2444 as a string, the back-end, as a symbol, and the communication
2445 channel, as a plist. It must return a string or nil.")
2447 (defvar org-export-filter-verbatim-functions nil
2448 "List of functions applied to transcoded verbatim text.
2449 Each filter is called with three arguments: the transcoded data,
2450 as a string, the back-end, as a symbol, and the communication
2451 channel, as a plist. It must return a string or nil.")
2454 ;;;; Filters Tools
2456 ;; Internal function `org-export-install-filters' installs filters
2457 ;; hard-coded in back-ends (developer filters) and filters from global
2458 ;; variables (user filters) in the communication channel.
2460 ;; Internal function `org-export-filter-apply-functions' takes care
2461 ;; about applying each filter in order to a given data. It ignores
2462 ;; filters returning a nil value but stops whenever a filter returns
2463 ;; an empty string.
2465 (defun org-export-filter-apply-functions (filters value info)
2466 "Call every function in FILTERS.
2468 Functions are called with arguments VALUE, current export
2469 back-end's name and INFO. A function returning a nil value will
2470 be skipped. If it returns the empty string, the process ends and
2471 VALUE is ignored.
2473 Call is done in a LIFO fashion, to be sure that developer
2474 specified filters, if any, are called first."
2475 (catch 'exit
2476 (let* ((backend (plist-get info :back-end))
2477 (backend-name (and backend (org-export-backend-name backend))))
2478 (dolist (filter filters value)
2479 (let ((result (funcall filter value backend-name info)))
2480 (cond ((not result) value)
2481 ((equal value "") (throw 'exit nil))
2482 (t (setq value result))))))))
2484 (defun org-export-install-filters (info)
2485 "Install filters properties in communication channel.
2486 INFO is a plist containing the current communication channel.
2487 Return the updated communication channel."
2488 (let (plist)
2489 ;; Install user-defined filters with `org-export-filters-alist'
2490 ;; and filters already in INFO (through ext-plist mechanism).
2491 (mapc (lambda (p)
2492 (let* ((prop (car p))
2493 (info-value (plist-get info prop))
2494 (default-value (symbol-value (cdr p))))
2495 (setq plist
2496 (plist-put plist prop
2497 ;; Filters in INFO will be called
2498 ;; before those user provided.
2499 (append (if (listp info-value) info-value
2500 (list info-value))
2501 default-value)))))
2502 org-export-filters-alist)
2503 ;; Prepend back-end specific filters to that list.
2504 (mapc (lambda (p)
2505 ;; Single values get consed, lists are appended.
2506 (let ((key (car p)) (value (cdr p)))
2507 (when value
2508 (setq plist
2509 (plist-put
2510 plist key
2511 (if (atom value) (cons value (plist-get plist key))
2512 (append value (plist-get plist key))))))))
2513 (org-export-get-all-filters (plist-get info :back-end)))
2514 ;; Return new communication channel.
2515 (org-combine-plists info plist)))
2519 ;;; Core functions
2521 ;; This is the room for the main function, `org-export-as', along with
2522 ;; its derivative, `org-export-string-as'.
2523 ;; `org-export--copy-to-kill-ring-p' determines if output of these
2524 ;; function should be added to kill ring.
2526 ;; Note that `org-export-as' doesn't really parse the current buffer,
2527 ;; but a copy of it (with the same buffer-local variables and
2528 ;; visibility), where macros and include keywords are expanded and
2529 ;; Babel blocks are executed, if appropriate.
2530 ;; `org-export-with-buffer-copy' macro prepares that copy.
2532 ;; File inclusion is taken care of by
2533 ;; `org-export-expand-include-keyword' and
2534 ;; `org-export--prepare-file-contents'. Structure wise, including
2535 ;; a whole Org file in a buffer often makes little sense. For
2536 ;; example, if the file contains a headline and the include keyword
2537 ;; was within an item, the item should contain the headline. That's
2538 ;; why file inclusion should be done before any structure can be
2539 ;; associated to the file, that is before parsing.
2541 ;; `org-export-insert-default-template' is a command to insert
2542 ;; a default template (or a back-end specific template) at point or in
2543 ;; current subtree.
2545 (defun org-export-copy-buffer ()
2546 "Return a copy of the current buffer.
2547 The copy preserves Org buffer-local variables, visibility and
2548 narrowing."
2549 (let ((copy-buffer-fun (org-export--generate-copy-script (current-buffer)))
2550 (new-buf (generate-new-buffer (buffer-name))))
2551 (with-current-buffer new-buf
2552 (funcall copy-buffer-fun)
2553 (set-buffer-modified-p nil))
2554 new-buf))
2556 (defmacro org-export-with-buffer-copy (&rest body)
2557 "Apply BODY in a copy of the current buffer.
2558 The copy preserves local variables, visibility and contents of
2559 the original buffer. Point is at the beginning of the buffer
2560 when BODY is applied."
2561 (declare (debug t))
2562 (org-with-gensyms (buf-copy)
2563 `(let ((,buf-copy (org-export-copy-buffer)))
2564 (unwind-protect
2565 (with-current-buffer ,buf-copy
2566 (goto-char (point-min))
2567 (progn ,@body))
2568 (and (buffer-live-p ,buf-copy)
2569 ;; Kill copy without confirmation.
2570 (progn (with-current-buffer ,buf-copy
2571 (restore-buffer-modified-p nil))
2572 (kill-buffer ,buf-copy)))))))
2574 (defun org-export--generate-copy-script (buffer)
2575 "Generate a function duplicating BUFFER.
2577 The copy will preserve local variables, visibility, contents and
2578 narrowing of the original buffer. If a region was active in
2579 BUFFER, contents will be narrowed to that region instead.
2581 The resulting function can be evaluated at a later time, from
2582 another buffer, effectively cloning the original buffer there.
2584 The function assumes BUFFER's major mode is `org-mode'."
2585 (with-current-buffer buffer
2586 `(lambda ()
2587 (let ((inhibit-modification-hooks t))
2588 ;; Set major mode. Ignore `org-mode-hook' as it has been run
2589 ;; already in BUFFER.
2590 (let ((org-mode-hook nil) (org-inhibit-startup t)) (org-mode))
2591 ;; Copy specific buffer local variables and variables set
2592 ;; through BIND keywords.
2593 ,@(let ((bound-variables (org-export--list-bound-variables))
2594 vars)
2595 (dolist (entry (buffer-local-variables (buffer-base-buffer)) vars)
2596 (when (consp entry)
2597 (let ((var (car entry))
2598 (val (cdr entry)))
2599 (and (not (memq var org-export-ignored-local-variables))
2600 (or (memq var
2601 '(default-directory
2602 buffer-file-name
2603 buffer-file-coding-system))
2604 (assq var bound-variables)
2605 (string-match "^\\(org-\\|orgtbl-\\)"
2606 (symbol-name var)))
2607 ;; Skip unreadable values, as they cannot be
2608 ;; sent to external process.
2609 (or (not val) (ignore-errors (read (format "%S" val))))
2610 (push `(set (make-local-variable (quote ,var))
2611 (quote ,val))
2612 vars))))))
2613 ;; Whole buffer contents.
2614 (insert
2615 ,(org-with-wide-buffer
2616 (buffer-substring-no-properties
2617 (point-min) (point-max))))
2618 ;; Narrowing.
2619 ,(if (org-region-active-p)
2620 `(narrow-to-region ,(region-beginning) ,(region-end))
2621 `(narrow-to-region ,(point-min) ,(point-max)))
2622 ;; Current position of point.
2623 (goto-char ,(point))
2624 ;; Overlays with invisible property.
2625 ,@(let (ov-set)
2626 (mapc
2627 (lambda (ov)
2628 (let ((invis-prop (overlay-get ov 'invisible)))
2629 (when invis-prop
2630 (push `(overlay-put
2631 (make-overlay ,(overlay-start ov)
2632 ,(overlay-end ov))
2633 'invisible (quote ,invis-prop))
2634 ov-set))))
2635 (overlays-in (point-min) (point-max)))
2636 ov-set)))))
2638 (defun org-export--delete-comments ()
2639 "Delete commented areas in the buffer.
2640 Commented areas are comments, comment blocks, commented trees and
2641 inlinetasks. Trailing blank lines after a comment or a comment
2642 block are preserved. Narrowing, if any, is ignored."
2643 (org-with-wide-buffer
2644 (goto-char (point-min))
2645 (let ((regexp (concat org-outline-regexp-bol ".*" org-comment-string
2646 "\\|"
2647 "^[ \t]*#\\(?: \\|$\\|\\+begin_comment\\)"))
2648 (case-fold-search t))
2649 (while (re-search-forward regexp nil t)
2650 (let ((e (org-element-at-point)))
2651 (case (org-element-type e)
2652 ((comment comment-block)
2653 (delete-region (org-element-property :begin e)
2654 (progn (goto-char (org-element-property :end e))
2655 (skip-chars-backward " \r\t\n")
2656 (line-beginning-position 2))))
2657 ((headline inlinetask)
2658 (when (org-element-property :commentedp e)
2659 (delete-region (org-element-property :begin e)
2660 (org-element-property :end e))))))))))
2662 (defun org-export--prune-tree (data info)
2663 "Prune non exportable elements from DATA.
2664 DATA is the parse tree to traverse. INFO is the plist holding
2665 export info. Also set `:ignore-list' in INFO to a list of
2666 objects which should be ignored during export, but not removed
2667 from tree."
2668 (let* (walk-data
2669 ignore
2670 ;; First find trees containing a select tag, if any.
2671 (selected (org-export--selected-trees data info))
2672 (walk-data
2673 (lambda (data)
2674 ;; Prune non-exportable elements and objects from tree.
2675 ;; As a special case, special rows and cells from tables
2676 ;; are stored in IGNORE, as they still need to be accessed
2677 ;; during export.
2678 (when data
2679 (let ((type (org-element-type data)))
2680 (if (org-export--skip-p data info selected)
2681 (if (memq type '(table-cell table-row)) (push data ignore)
2682 (org-element-extract-element data))
2683 (if (and (eq type 'headline)
2684 (eq (plist-get info :with-archived-trees) 'headline)
2685 (org-element-property :archivedp data))
2686 ;; If headline is archived but tree below has to
2687 ;; be skipped, remove contents.
2688 (org-element-set-contents data)
2689 ;; Move into secondary string, if any.
2690 (let ((sec-prop
2691 (cdr (assq type org-element-secondary-value-alist))))
2692 (when sec-prop
2693 (mapc walk-data (org-element-property sec-prop data))))
2694 ;; Move into recursive objects/elements.
2695 (mapc walk-data (org-element-contents data)))))))))
2696 ;; If a select tag is active, also ignore the section before the
2697 ;; first headline, if any.
2698 (when selected
2699 (let ((first-element (car (org-element-contents data))))
2700 (when (eq (org-element-type first-element) 'section)
2701 (org-element-extract-element first-element))))
2702 ;; Prune tree and communication channel.
2703 (funcall walk-data data)
2704 (dolist (entry
2705 (append
2706 ;; Priority is given to back-end specific options.
2707 (org-export-get-all-options (plist-get info :back-end))
2708 org-export-options-alist))
2709 (when (eq (nth 4 entry) 'parse)
2710 (funcall walk-data (plist-get info (car entry)))))
2711 ;; Eventually set `:ignore-list'.
2712 (plist-put info :ignore-list ignore)))
2714 (defun org-export--remove-uninterpreted-data (data info)
2715 "Change uninterpreted elements back into Org syntax.
2716 DATA is the parse tree. INFO is a plist containing export
2717 options. Each uninterpreted element or object is changed back
2718 into a string. Contents, if any, are not modified. The parse
2719 tree is modified by side effect."
2720 (org-export--remove-uninterpreted-data-1 data info)
2721 (dolist (entry org-export-options-alist)
2722 (when (eq (nth 4 entry) 'parse)
2723 (let ((p (car entry)))
2724 (plist-put info
2726 (org-export--remove-uninterpreted-data-1
2727 (plist-get info p)
2728 info))))))
2730 (defun org-export--remove-uninterpreted-data-1 (data info)
2731 "Change uninterpreted elements back into Org syntax.
2732 DATA is a parse tree or a secondary string. INFO is a plist
2733 containing export options. It is modified by side effect and
2734 returned by the function."
2735 (org-element-map data
2736 '(entity bold italic latex-environment latex-fragment strike-through
2737 subscript superscript underline)
2738 (lambda (blob)
2739 (let ((new
2740 (case (org-element-type blob)
2741 ;; ... entities...
2742 (entity
2743 (and (not (plist-get info :with-entities))
2744 (list (concat
2745 (org-export-expand blob nil)
2746 (make-string
2747 (or (org-element-property :post-blank blob) 0)
2748 ?\s)))))
2749 ;; ... emphasis...
2750 ((bold italic strike-through underline)
2751 (and (not (plist-get info :with-emphasize))
2752 (let ((marker (case (org-element-type blob)
2753 (bold "*")
2754 (italic "/")
2755 (strike-through "+")
2756 (underline "_"))))
2757 (append
2758 (list marker)
2759 (org-element-contents blob)
2760 (list (concat
2761 marker
2762 (make-string
2763 (or (org-element-property :post-blank blob)
2765 ?\s)))))))
2766 ;; ... LaTeX environments and fragments...
2767 ((latex-environment latex-fragment)
2768 (and (eq (plist-get info :with-latex) 'verbatim)
2769 (list (org-export-expand blob nil))))
2770 ;; ... sub/superscripts...
2771 ((subscript superscript)
2772 (let ((sub/super-p (plist-get info :with-sub-superscript))
2773 (bracketp (org-element-property :use-brackets-p blob)))
2774 (and (or (not sub/super-p)
2775 (and (eq sub/super-p '{}) (not bracketp)))
2776 (append
2777 (list (concat
2778 (if (eq (org-element-type blob) 'subscript)
2780 "^")
2781 (and bracketp "{")))
2782 (org-element-contents blob)
2783 (list (concat
2784 (and bracketp "}")
2785 (and (org-element-property :post-blank blob)
2786 (make-string
2787 (org-element-property :post-blank blob)
2788 ?\s)))))))))))
2789 (when new
2790 ;; Splice NEW at BLOB location in parse tree.
2791 (dolist (e new (org-element-extract-element blob))
2792 (unless (string= e "") (org-element-insert-before e blob))))))
2793 info)
2794 ;; Return modified parse tree.
2795 data)
2797 ;;;###autoload
2798 (defun org-export-as
2799 (backend &optional subtreep visible-only body-only ext-plist)
2800 "Transcode current Org buffer into BACKEND code.
2802 BACKEND is either an export back-end, as returned by, e.g.,
2803 `org-export-create-backend', or a symbol referring to
2804 a registered back-end.
2806 If narrowing is active in the current buffer, only transcode its
2807 narrowed part.
2809 If a region is active, transcode that region.
2811 When optional argument SUBTREEP is non-nil, transcode the
2812 sub-tree at point, extracting information from the headline
2813 properties first.
2815 When optional argument VISIBLE-ONLY is non-nil, don't export
2816 contents of hidden elements.
2818 When optional argument BODY-ONLY is non-nil, only return body
2819 code, without surrounding template.
2821 Optional argument EXT-PLIST, when provided, is a property list
2822 with external parameters overriding Org default settings, but
2823 still inferior to file-local settings.
2825 Return code as a string."
2826 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
2827 (org-export-barf-if-invalid-backend backend)
2828 (save-excursion
2829 (save-restriction
2830 ;; Narrow buffer to an appropriate region or subtree for
2831 ;; parsing. If parsing subtree, be sure to remove main headline
2832 ;; too.
2833 (cond ((org-region-active-p)
2834 (narrow-to-region (region-beginning) (region-end)))
2835 (subtreep
2836 (org-narrow-to-subtree)
2837 (goto-char (point-min))
2838 (forward-line)
2839 (narrow-to-region (point) (point-max))))
2840 ;; Initialize communication channel with original buffer
2841 ;; attributes, unavailable in its copy.
2842 (let* ((org-export-current-backend (org-export-backend-name backend))
2843 (info (org-combine-plists
2844 (list :export-options
2845 (delq nil
2846 (list (and subtreep 'subtree)
2847 (and visible-only 'visible-only)
2848 (and body-only 'body-only))))
2849 (org-export--get-buffer-attributes)))
2850 (parsed-keywords
2851 (delq nil
2852 (mapcar (lambda (o) (and (eq (nth 4 o) 'parse) (nth 1 o)))
2853 (append (org-export-get-all-options backend)
2854 org-export-options-alist))))
2855 tree)
2856 ;; Update communication channel and get parse tree. Buffer
2857 ;; isn't parsed directly. Instead, a temporary copy is
2858 ;; created, where include keywords, macros are expanded and
2859 ;; code blocks are evaluated.
2860 (org-export-with-buffer-copy
2861 ;; Run first hook with current back-end's name as argument.
2862 (run-hook-with-args 'org-export-before-processing-hook
2863 (org-export-backend-name backend))
2864 (org-export-expand-include-keyword)
2865 (org-export--delete-comments)
2866 ;; Refresh buffer properties, radio targets and macros after
2867 ;; including files.
2868 (org-set-regexps-and-options)
2869 (org-update-radio-target-regexp)
2870 (org-macro-initialize-templates)
2871 (org-macro-replace-all org-macro-templates nil parsed-keywords)
2872 (org-export-execute-babel-code)
2873 ;; Run last hook with current back-end's name as argument.
2874 (goto-char (point-min))
2875 (save-excursion
2876 (run-hook-with-args 'org-export-before-parsing-hook
2877 (org-export-backend-name backend)))
2878 ;; Update communication channel with environment. Also
2879 ;; install user's and developer's filters.
2880 (setq info
2881 (org-export-install-filters
2882 (org-combine-plists
2883 info (org-export-get-environment backend subtreep ext-plist))))
2884 ;; Call options filters and update export options. We do not
2885 ;; use `org-export-filter-apply-functions' here since the
2886 ;; arity of such filters is different.
2887 (let ((backend-name (org-export-backend-name backend)))
2888 (dolist (filter (plist-get info :filter-options))
2889 (let ((result (funcall filter info backend-name)))
2890 (when result (setq info result)))))
2891 ;; Expand export-specific set of macros: {{{author}}},
2892 ;; {{{date(FORMAT)}}}, {{{email}}} and {{{title}}}. It must
2893 ;; be done once regular macros have been expanded, since
2894 ;; parsed keywords may contain one of them.
2895 (org-macro-replace-all
2896 (list
2897 (cons "author" (org-element-interpret-data (plist-get info :author)))
2898 (cons "date"
2899 (let* ((date (plist-get info :date))
2900 (value (or (org-element-interpret-data date) "")))
2901 (if (and (consp date)
2902 (not (cdr date))
2903 (eq (org-element-type (car date)) 'timestamp))
2904 (format "(eval (if (org-string-nw-p \"$1\") %s %S))"
2905 (format "(org-timestamp-format '%S \"$1\")"
2906 (org-element-copy (car date)))
2907 value)
2908 value)))
2909 (cons "email" (org-element-interpret-data (plist-get info :email)))
2910 (cons "title" (org-element-interpret-data (plist-get info :title)))
2911 (cons "results" "$1"))
2912 'finalize
2913 parsed-keywords)
2914 ;; Parse buffer.
2915 (setq tree (org-element-parse-buffer nil visible-only))
2916 ;; Prune tree from non-exported elements and transform
2917 ;; uninterpreted elements or objects in both parse tree and
2918 ;; communication channel.
2919 (org-export--prune-tree tree info)
2920 (org-export--remove-uninterpreted-data tree info)
2921 ;; Parse buffer, handle uninterpreted elements or objects,
2922 ;; then call parse-tree filters.
2923 (setq tree
2924 (org-export-filter-apply-functions
2925 (plist-get info :filter-parse-tree) tree info))
2926 ;; Now tree is complete, compute its properties and add them
2927 ;; to communication channel.
2928 (setq info
2929 (org-combine-plists
2930 info (org-export-collect-tree-properties tree info)))
2931 ;; Eventually transcode TREE. Wrap the resulting string into
2932 ;; a template.
2933 (let* ((body (org-element-normalize-string
2934 (or (org-export-data tree info) "")))
2935 (inner-template (cdr (assq 'inner-template
2936 (plist-get info :translate-alist))))
2937 (full-body (org-export-filter-apply-functions
2938 (plist-get info :filter-body)
2939 (if (not (functionp inner-template)) body
2940 (funcall inner-template body info))
2941 info))
2942 (template (cdr (assq 'template
2943 (plist-get info :translate-alist)))))
2944 ;; Remove all text properties since they cannot be
2945 ;; retrieved from an external process. Finally call
2946 ;; final-output filter and return result.
2947 (org-no-properties
2948 (org-export-filter-apply-functions
2949 (plist-get info :filter-final-output)
2950 (if (or (not (functionp template)) body-only) full-body
2951 (funcall template full-body info))
2952 info))))))))
2954 ;;;###autoload
2955 (defun org-export-string-as (string backend &optional body-only ext-plist)
2956 "Transcode STRING into BACKEND code.
2958 BACKEND is either an export back-end, as returned by, e.g.,
2959 `org-export-create-backend', or a symbol referring to
2960 a registered back-end.
2962 When optional argument BODY-ONLY is non-nil, only return body
2963 code, without preamble nor postamble.
2965 Optional argument EXT-PLIST, when provided, is a property list
2966 with external parameters overriding Org default settings, but
2967 still inferior to file-local settings.
2969 Return code as a string."
2970 (with-temp-buffer
2971 (insert string)
2972 (let ((org-inhibit-startup t)) (org-mode))
2973 (org-export-as backend nil nil body-only ext-plist)))
2975 ;;;###autoload
2976 (defun org-export-replace-region-by (backend)
2977 "Replace the active region by its export to BACKEND.
2978 BACKEND is either an export back-end, as returned by, e.g.,
2979 `org-export-create-backend', or a symbol referring to
2980 a registered back-end."
2981 (if (not (org-region-active-p))
2982 (user-error "No active region to replace")
2983 (let* ((beg (region-beginning))
2984 (end (region-end))
2985 (str (buffer-substring beg end)) rpl)
2986 (setq rpl (org-export-string-as str backend t))
2987 (delete-region beg end)
2988 (insert rpl))))
2990 ;;;###autoload
2991 (defun org-export-insert-default-template (&optional backend subtreep)
2992 "Insert all export keywords with default values at beginning of line.
2994 BACKEND is a symbol referring to the name of a registered export
2995 back-end, for which specific export options should be added to
2996 the template, or `default' for default template. When it is nil,
2997 the user will be prompted for a category.
2999 If SUBTREEP is non-nil, export configuration will be set up
3000 locally for the subtree through node properties."
3001 (interactive)
3002 (unless (derived-mode-p 'org-mode) (user-error "Not in an Org mode buffer"))
3003 (when (and subtreep (org-before-first-heading-p))
3004 (user-error "No subtree to set export options for"))
3005 (let ((node (and subtreep (save-excursion (org-back-to-heading t) (point))))
3006 (backend
3007 (or backend
3008 (intern
3009 (org-completing-read
3010 "Options category: "
3011 (cons "default"
3012 (mapcar (lambda (b)
3013 (symbol-name (org-export-backend-name b)))
3014 org-export-registered-backends))
3015 nil t))))
3016 options keywords)
3017 ;; Populate OPTIONS and KEYWORDS.
3018 (dolist (entry (cond ((eq backend 'default) org-export-options-alist)
3019 ((org-export-backend-p backend)
3020 (org-export-backend-options backend))
3021 (t (org-export-backend-options
3022 (org-export-get-backend backend)))))
3023 (let ((keyword (nth 1 entry))
3024 (option (nth 2 entry)))
3025 (cond
3026 (keyword (unless (assoc keyword keywords)
3027 (let ((value
3028 (if (eq (nth 4 entry) 'split)
3029 (mapconcat #'identity (eval (nth 3 entry)) " ")
3030 (eval (nth 3 entry)))))
3031 (push (cons keyword value) keywords))))
3032 (option (unless (assoc option options)
3033 (push (cons option (eval (nth 3 entry))) options))))))
3034 ;; Move to an appropriate location in order to insert options.
3035 (unless subtreep (beginning-of-line))
3036 ;; First (multiple) OPTIONS lines. Never go past fill-column.
3037 (when options
3038 (let ((items
3039 (mapcar
3040 #'(lambda (opt) (format "%s:%S" (car opt) (cdr opt)))
3041 (sort options (lambda (k1 k2) (string< (car k1) (car k2)))))))
3042 (if subtreep
3043 (org-entry-put
3044 node "EXPORT_OPTIONS" (mapconcat 'identity items " "))
3045 (while items
3046 (insert "#+OPTIONS:")
3047 (let ((width 10))
3048 (while (and items
3049 (< (+ width (length (car items)) 1) fill-column))
3050 (let ((item (pop items)))
3051 (insert " " item)
3052 (incf width (1+ (length item))))))
3053 (insert "\n")))))
3054 ;; Then the rest of keywords, in the order specified in either
3055 ;; `org-export-options-alist' or respective export back-ends.
3056 (dolist (key (nreverse keywords))
3057 (let ((val (cond ((equal (car key) "DATE")
3058 (or (cdr key)
3059 (with-temp-buffer
3060 (org-insert-time-stamp (current-time)))))
3061 ((equal (car key) "TITLE")
3062 (or (let ((visited-file
3063 (buffer-file-name (buffer-base-buffer))))
3064 (and visited-file
3065 (file-name-sans-extension
3066 (file-name-nondirectory visited-file))))
3067 (buffer-name (buffer-base-buffer))))
3068 (t (cdr key)))))
3069 (if subtreep (org-entry-put node (concat "EXPORT_" (car key)) val)
3070 (insert
3071 (format "#+%s:%s\n"
3072 (car key)
3073 (if (org-string-nw-p val) (format " %s" val) ""))))))))
3075 (defun org-export-expand-include-keyword (&optional included dir footnotes)
3076 "Expand every include keyword in buffer.
3077 Optional argument INCLUDED is a list of included file names along
3078 with their line restriction, when appropriate. It is used to
3079 avoid infinite recursion. Optional argument DIR is the current
3080 working directory. It is used to properly resolve relative
3081 paths. Optional argument FOOTNOTES is a hash-table used for
3082 storing and resolving footnotes. It is created automatically."
3083 (let ((case-fold-search t)
3084 (file-prefix (make-hash-table :test #'equal))
3085 (current-prefix 0)
3086 (footnotes (or footnotes (make-hash-table :test #'equal)))
3087 (include-re "^[ \t]*#\\+INCLUDE:"))
3088 ;; If :minlevel is not set the text-property
3089 ;; `:org-include-induced-level' will be used to determine the
3090 ;; relative level when expanding INCLUDE.
3091 ;; Only affects included Org documents.
3092 (goto-char (point-min))
3093 (while (re-search-forward include-re nil t)
3094 (put-text-property (line-beginning-position) (line-end-position)
3095 :org-include-induced-level
3096 (1+ (org-reduced-level (or (org-current-level) 0)))))
3097 ;; Expand INCLUDE keywords.
3098 (goto-char (point-min))
3099 (while (re-search-forward include-re nil t)
3100 (let ((element (save-match-data (org-element-at-point))))
3101 (when (eq (org-element-type element) 'keyword)
3102 (beginning-of-line)
3103 ;; Extract arguments from keyword's value.
3104 (let* ((value (org-element-property :value element))
3105 (ind (org-get-indentation))
3106 location
3107 (file
3108 (and (string-match
3109 "^\\(\".+?\"\\|\\S-+\\)\\(?:\\s-+\\|$\\)" value)
3110 (prog1
3111 (save-match-data
3112 (let ((matched (match-string 1 value)))
3113 (when (string-match "\\(::\\(.*?\\)\\)\"?\\'"
3114 matched)
3115 (setq location (match-string 2 matched))
3116 (setq matched
3117 (replace-match "" nil nil matched 1)))
3118 (expand-file-name
3119 (org-remove-double-quotes
3120 matched)
3121 dir)))
3122 (setq value (replace-match "" nil nil value)))))
3123 (only-contents
3124 (and (string-match ":only-contents *\\([^: \r\t\n]\\S-*\\)?"
3125 value)
3126 (prog1 (org-not-nil (match-string 1 value))
3127 (setq value (replace-match "" nil nil value)))))
3128 (lines
3129 (and (string-match
3130 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\""
3131 value)
3132 (prog1 (match-string 1 value)
3133 (setq value (replace-match "" nil nil value)))))
3134 (env (cond ((string-match "\\<example\\>" value)
3135 'literal)
3136 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
3137 'literal)))
3138 ;; Minimal level of included file defaults to the child
3139 ;; level of the current headline, if any, or one. It
3140 ;; only applies is the file is meant to be included as
3141 ;; an Org one.
3142 (minlevel
3143 (and (not env)
3144 (if (string-match ":minlevel +\\([0-9]+\\)" value)
3145 (prog1 (string-to-number (match-string 1 value))
3146 (setq value (replace-match "" nil nil value)))
3147 (get-text-property (point)
3148 :org-include-induced-level))))
3149 (src-args (and (eq env 'literal)
3150 (match-string 1 value)))
3151 (block (and (string-match "\\<\\(\\S-+\\)\\>" value)
3152 (match-string 1 value))))
3153 ;; Remove keyword.
3154 (delete-region (point) (progn (forward-line) (point)))
3155 (cond
3156 ((not file) nil)
3157 ((not (file-readable-p file))
3158 (error "Cannot include file %s" file))
3159 ;; Check if files has already been parsed. Look after
3160 ;; inclusion lines too, as different parts of the same file
3161 ;; can be included too.
3162 ((member (list file lines) included)
3163 (error "Recursive file inclusion: %s" file))
3165 (cond
3166 ((eq env 'literal)
3167 (insert
3168 (let ((ind-str (make-string ind ? ))
3169 (arg-str (if (stringp src-args)
3170 (format " %s" src-args)
3171 ""))
3172 (contents
3173 (org-escape-code-in-string
3174 (org-export--prepare-file-contents file lines))))
3175 (format "%s#+BEGIN_%s%s\n%s%s#+END_%s\n"
3176 ind-str block arg-str contents ind-str block))))
3177 ((stringp block)
3178 (insert
3179 (let ((ind-str (make-string ind ? ))
3180 (contents
3181 (org-export--prepare-file-contents file lines)))
3182 (format "%s#+BEGIN_%s\n%s%s#+END_%s\n"
3183 ind-str block contents ind-str block))))
3185 (insert
3186 (with-temp-buffer
3187 (let ((org-inhibit-startup t)
3188 (lines
3189 (if location
3190 (org-export--inclusion-absolute-lines
3191 file location only-contents lines)
3192 lines)))
3193 (org-mode)
3194 (insert
3195 (org-export--prepare-file-contents
3196 file lines ind minlevel
3197 (or (gethash file file-prefix)
3198 (puthash file (incf current-prefix) file-prefix))
3199 footnotes)))
3200 (org-export-expand-include-keyword
3201 (cons (list file lines) included)
3202 (file-name-directory file)
3203 footnotes)
3204 (buffer-string)))))
3205 ;; Expand footnotes after all files have been included.
3206 ;; Footnotes are stored at end of buffer.
3207 (unless included
3208 (org-with-wide-buffer
3209 (goto-char (point-max))
3210 (maphash (lambda (k v) (insert (format "\n[%s] %s\n" k v)))
3211 footnotes)))))))))))
3213 (defun org-export--inclusion-absolute-lines (file location only-contents lines)
3214 "Resolve absolute lines for an included file with file-link.
3216 FILE is string file-name of the file to include. LOCATION is a
3217 string name within FILE to be included (located via
3218 `org-link-search'). If ONLY-CONTENTS is non-nil only the
3219 contents of the named element will be included, as determined
3220 Org-Element. If LINES is non-nil only those lines are included.
3222 Return a string of lines to be included in the format expected by
3223 `org-export--prepare-file-contents'."
3224 (with-temp-buffer
3225 (insert-file-contents file)
3226 (unless (eq major-mode 'org-mode)
3227 (let ((org-inhibit-startup t)) (org-mode)))
3228 (condition-case err
3229 ;; Enforce consistent search.
3230 (let ((org-link-search-must-match-exact-headline t))
3231 (org-link-search location))
3232 (error
3233 (error "%s for %s::%s" (error-message-string err) file location)))
3234 (let* ((element (org-element-at-point))
3235 (contents-begin
3236 (and only-contents (org-element-property :contents-begin element))))
3237 (narrow-to-region
3238 (or contents-begin (org-element-property :begin element))
3239 (org-element-property (if contents-begin :contents-end :end) element))
3240 (when (and only-contents
3241 (memq (org-element-type element) '(headline inlinetask)))
3242 ;; Skip planning line and property-drawer.
3243 (goto-char (point-min))
3244 (when (org-looking-at-p org-planning-line-re) (forward-line))
3245 (when (looking-at org-property-drawer-re) (goto-char (match-end 0)))
3246 (unless (bolp) (forward-line))
3247 (narrow-to-region (point) (point-max))))
3248 (when lines
3249 (org-skip-whitespace)
3250 (beginning-of-line)
3251 (let* ((lines (split-string lines "-"))
3252 (lbeg (string-to-number (car lines)))
3253 (lend (string-to-number (cadr lines)))
3254 (beg (if (zerop lbeg) (point-min)
3255 (goto-char (point-min))
3256 (forward-line (1- lbeg))
3257 (point)))
3258 (end (if (zerop lend) (point-max)
3259 (goto-char beg)
3260 (forward-line (1- lend))
3261 (point))))
3262 (narrow-to-region beg end)))
3263 (let ((end (point-max)))
3264 (goto-char (point-min))
3265 (widen)
3266 (let ((start-line (line-number-at-pos)))
3267 (format "%d-%d"
3268 start-line
3269 (save-excursion
3270 (+ start-line
3271 (let ((counter 0))
3272 (while (< (point) end) (incf counter) (forward-line))
3273 counter))))))))
3275 (defun org-export--update-footnote-label (ref-begin digit-label id)
3276 "Prefix footnote-label at point REF-BEGIN in buffer with ID.
3278 REF-BEGIN corresponds to the property `:begin' of objects of type
3279 footnote-definition and footnote-reference.
3281 If DIGIT-LABEL is non-nil the label is assumed to be of the form
3282 \[N] where N is one or more numbers.
3284 Return the new label."
3285 (goto-char (1+ ref-begin))
3286 (buffer-substring (point)
3287 (progn
3288 (if digit-label (insert (format "fn:%d-" id))
3289 (forward-char 3)
3290 (insert (format "%d-" id)))
3291 (1- (search-forward "]")))))
3293 (defun org-export--prepare-file-contents
3294 (file &optional lines ind minlevel id footnotes)
3295 "Prepare contents of FILE for inclusion and return it as a string.
3297 When optional argument LINES is a string specifying a range of
3298 lines, include only those lines.
3300 Optional argument IND, when non-nil, is an integer specifying the
3301 global indentation of returned contents. Since its purpose is to
3302 allow an included file to stay in the same environment it was
3303 created \(i.e. a list item), it doesn't apply past the first
3304 headline encountered.
3306 Optional argument MINLEVEL, when non-nil, is an integer
3307 specifying the level that any top-level headline in the included
3308 file should have.
3309 Optional argument ID is an integer that will be inserted before
3310 each footnote definition and reference if FILE is an Org file.
3311 This is useful to avoid conflicts when more than one Org file
3312 with footnotes is included in a document.
3314 Optional argument FOOTNOTES is a hash-table to store footnotes in
3315 the included document.
3317 (with-temp-buffer
3318 (insert-file-contents file)
3319 (when lines
3320 (let* ((lines (split-string lines "-"))
3321 (lbeg (string-to-number (car lines)))
3322 (lend (string-to-number (cadr lines)))
3323 (beg (if (zerop lbeg) (point-min)
3324 (goto-char (point-min))
3325 (forward-line (1- lbeg))
3326 (point)))
3327 (end (if (zerop lend) (point-max)
3328 (goto-char (point-min))
3329 (forward-line (1- lend))
3330 (point))))
3331 (narrow-to-region beg end)))
3332 ;; Remove blank lines at beginning and end of contents. The logic
3333 ;; behind that removal is that blank lines around include keyword
3334 ;; override blank lines in included file.
3335 (goto-char (point-min))
3336 (org-skip-whitespace)
3337 (beginning-of-line)
3338 (delete-region (point-min) (point))
3339 (goto-char (point-max))
3340 (skip-chars-backward " \r\t\n")
3341 (forward-line)
3342 (delete-region (point) (point-max))
3343 ;; If IND is set, preserve indentation of include keyword until
3344 ;; the first headline encountered.
3345 (when ind
3346 (unless (eq major-mode 'org-mode)
3347 (let ((org-inhibit-startup t)) (org-mode)))
3348 (goto-char (point-min))
3349 (let ((ind-str (make-string ind ? )))
3350 (while (not (or (eobp) (looking-at org-outline-regexp-bol)))
3351 ;; Do not move footnote definitions out of column 0.
3352 (unless (and (looking-at org-footnote-definition-re)
3353 (eq (org-element-type (org-element-at-point))
3354 'footnote-definition))
3355 (insert ind-str))
3356 (forward-line))))
3357 ;; When MINLEVEL is specified, compute minimal level for headlines
3358 ;; in the file (CUR-MIN), and remove stars to each headline so
3359 ;; that headlines with minimal level have a level of MINLEVEL.
3360 (when minlevel
3361 (unless (eq major-mode 'org-mode)
3362 (let ((org-inhibit-startup t)) (org-mode)))
3363 (org-with-limited-levels
3364 (let ((levels (org-map-entries
3365 (lambda () (org-reduced-level (org-current-level))))))
3366 (when levels
3367 (let ((offset (- minlevel (apply 'min levels))))
3368 (unless (zerop offset)
3369 (when org-odd-levels-only (setq offset (* offset 2)))
3370 ;; Only change stars, don't bother moving whole
3371 ;; sections.
3372 (org-map-entries
3373 (lambda () (if (< offset 0) (delete-char (abs offset))
3374 (insert (make-string offset ?*)))))))))))
3375 ;; Append ID to all footnote references and definitions, so they
3376 ;; become file specific and cannot collide with footnotes in other
3377 ;; included files. Further, collect relevant footnotes outside of
3378 ;; LINES.
3379 (when id
3380 (let ((marker-min (point-min-marker))
3381 (marker-max (point-max-marker)))
3382 (goto-char (point-min))
3383 (while (re-search-forward org-footnote-re nil t)
3384 (let ((reference (org-element-context)))
3385 (when (eq (org-element-type reference) 'footnote-reference)
3386 (let* ((label (org-element-property :label reference))
3387 (digit-label
3388 (and label (org-string-match-p "\\`[0-9]+\\'" label))))
3389 ;; Update the footnote-reference at point and collect
3390 ;; the new label, which is only used for footnotes
3391 ;; outsides LINES.
3392 (when label
3393 ;; If label is akin to [1] convert it to [fn:ID-1].
3394 ;; Otherwise add "ID-" after "fn:".
3395 (let ((new-label (org-export--update-footnote-label
3396 (org-element-property :begin reference)
3397 digit-label id)))
3398 (unless (eq (org-element-property :type reference) 'inline)
3399 (org-with-wide-buffer
3400 (let* ((definition (org-footnote-get-definition label))
3401 (beginning (nth 1 definition)))
3402 (unless definition
3403 (error
3404 "Definition not found for footnote %s in file %s"
3405 label file))
3406 (if (or (< beginning marker-min)
3407 (> beginning marker-max))
3408 ;; Store since footnote-definition is
3409 ;; outside of LINES.
3410 (puthash new-label
3411 (org-element-normalize-string
3412 (nth 3 definition))
3413 footnotes)
3414 ;; Update label of definition since it is
3415 ;; included directly.
3416 (org-export--update-footnote-label
3417 beginning digit-label id)))))))))))
3418 (set-marker marker-min nil)
3419 (set-marker marker-max nil)))
3420 (org-element-normalize-string (buffer-string))))
3422 (defun org-export-execute-babel-code ()
3423 "Execute every Babel code in the visible part of current buffer."
3424 ;; Get a pristine copy of current buffer so Babel references can be
3425 ;; properly resolved.
3426 (let ((reference (org-export-copy-buffer)))
3427 (unwind-protect (org-babel-exp-process-buffer reference)
3428 (kill-buffer reference))))
3430 (defun org-export--copy-to-kill-ring-p ()
3431 "Return a non-nil value when output should be added to the kill ring.
3432 See also `org-export-copy-to-kill-ring'."
3433 (if (eq org-export-copy-to-kill-ring 'if-interactive)
3434 (not (or executing-kbd-macro noninteractive))
3435 (eq org-export-copy-to-kill-ring t)))
3439 ;;; Tools For Back-Ends
3441 ;; A whole set of tools is available to help build new exporters. Any
3442 ;; function general enough to have its use across many back-ends
3443 ;; should be added here.
3445 ;;;; For Affiliated Keywords
3447 ;; `org-export-read-attribute' reads a property from a given element
3448 ;; as a plist. It can be used to normalize affiliated keywords'
3449 ;; syntax.
3451 ;; Since captions can span over multiple lines and accept dual values,
3452 ;; their internal representation is a bit tricky. Therefore,
3453 ;; `org-export-get-caption' transparently returns a given element's
3454 ;; caption as a secondary string.
3456 (defun org-export-read-attribute (attribute element &optional property)
3457 "Turn ATTRIBUTE property from ELEMENT into a plist.
3459 When optional argument PROPERTY is non-nil, return the value of
3460 that property within attributes.
3462 This function assumes attributes are defined as \":keyword
3463 value\" pairs. It is appropriate for `:attr_html' like
3464 properties.
3466 All values will become strings except the empty string and
3467 \"nil\", which will become nil. Also, values containing only
3468 double quotes will be read as-is, which means that \"\" value
3469 will become the empty string."
3470 (let* ((prepare-value
3471 (lambda (str)
3472 (save-match-data
3473 (cond ((member str '(nil "" "nil")) nil)
3474 ((string-match "^\"\\(\"+\\)?\"$" str)
3475 (or (match-string 1 str) ""))
3476 (t str)))))
3477 (attributes
3478 (let ((value (org-element-property attribute element)))
3479 (when value
3480 (let ((s (mapconcat 'identity value " ")) result)
3481 (while (string-match
3482 "\\(?:^\\|[ \t]+\\)\\(:[-a-zA-Z0-9_]+\\)\\([ \t]+\\|$\\)"
3484 (let ((value (substring s 0 (match-beginning 0))))
3485 (push (funcall prepare-value value) result))
3486 (push (intern (match-string 1 s)) result)
3487 (setq s (substring s (match-end 0))))
3488 ;; Ignore any string before first property with `cdr'.
3489 (cdr (nreverse (cons (funcall prepare-value s) result))))))))
3490 (if property (plist-get attributes property) attributes)))
3492 (defun org-export-get-caption (element &optional shortp)
3493 "Return caption from ELEMENT as a secondary string.
3495 When optional argument SHORTP is non-nil, return short caption,
3496 as a secondary string, instead.
3498 Caption lines are separated by a white space."
3499 (let ((full-caption (org-element-property :caption element)) caption)
3500 (dolist (line full-caption (cdr caption))
3501 (let ((cap (funcall (if shortp 'cdr 'car) line)))
3502 (when cap
3503 (setq caption (nconc (list " ") (copy-sequence cap) caption)))))))
3506 ;;;; For Derived Back-ends
3508 ;; `org-export-with-backend' is a function allowing to locally use
3509 ;; another back-end to transcode some object or element. In a derived
3510 ;; back-end, it may be used as a fall-back function once all specific
3511 ;; cases have been treated.
3513 (defun org-export-with-backend (backend data &optional contents info)
3514 "Call a transcoder from BACKEND on DATA.
3515 BACKEND is an export back-end, as returned by, e.g.,
3516 `org-export-create-backend', or a symbol referring to
3517 a registered back-end. DATA is an Org element, object, secondary
3518 string or string. CONTENTS, when non-nil, is the transcoded
3519 contents of DATA element, as a string. INFO, when non-nil, is
3520 the communication channel used for export, as a plist."
3521 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
3522 (org-export-barf-if-invalid-backend backend)
3523 (let ((type (org-element-type data)))
3524 (if (memq type '(nil org-data)) (error "No foreign transcoder available")
3525 (let* ((all-transcoders (org-export-get-all-transcoders backend))
3526 (transcoder (cdr (assq type all-transcoders))))
3527 (if (not (functionp transcoder))
3528 (error "No foreign transcoder available")
3529 (funcall
3530 transcoder data contents
3531 (org-combine-plists
3532 info (list
3533 :back-end backend
3534 :translate-alist all-transcoders
3535 :exported-data (make-hash-table :test #'eq :size 401)))))))))
3538 ;;;; For Export Snippets
3540 ;; Every export snippet is transmitted to the back-end. Though, the
3541 ;; latter will only retain one type of export-snippet, ignoring
3542 ;; others, based on the former's target back-end. The function
3543 ;; `org-export-snippet-backend' returns that back-end for a given
3544 ;; export-snippet.
3546 (defun org-export-snippet-backend (export-snippet)
3547 "Return EXPORT-SNIPPET targeted back-end as a symbol.
3548 Translation, with `org-export-snippet-translation-alist', is
3549 applied."
3550 (let ((back-end (org-element-property :back-end export-snippet)))
3551 (intern
3552 (or (cdr (assoc back-end org-export-snippet-translation-alist))
3553 back-end))))
3556 ;;;; For Footnotes
3558 ;; `org-export-collect-footnote-definitions' is a tool to list
3559 ;; actually used footnotes definitions in the whole parse tree, or in
3560 ;; a headline, in order to add footnote listings throughout the
3561 ;; transcoded data.
3563 ;; `org-export-footnote-first-reference-p' is a predicate used by some
3564 ;; back-ends, when they need to attach the footnote definition only to
3565 ;; the first occurrence of the corresponding label.
3567 ;; `org-export-get-footnote-definition' and
3568 ;; `org-export-get-footnote-number' provide easier access to
3569 ;; additional information relative to a footnote reference.
3571 (defun org-export-get-footnote-definition (footnote-reference info)
3572 "Return definition of FOOTNOTE-REFERENCE as parsed data.
3573 INFO is the plist used as a communication channel. If no such
3574 definition can be found, raise an error."
3575 (let ((label (org-element-property :label footnote-reference)))
3576 (or (if label
3577 (cdr (assoc label (plist-get info :footnote-definition-alist)))
3578 (org-element-contents footnote-reference))
3579 (error "Definition not found for footnote %s" label))))
3581 (defun org-export--footnote-reference-map
3582 (function data info &optional body-first)
3583 "Apply FUNCTION on every footnote reference in DATA.
3584 INFO is a plist containing export state. By default, as soon as
3585 a new footnote reference is encountered, FUNCTION is called onto
3586 its definition. However, if BODY-FIRST is non-nil, this step is
3587 delayed until the end of the process."
3588 (let* ((definitions)
3589 (seen-refs)
3590 (search-ref) ; For byte-compiler.
3591 (search-ref
3592 (lambda (data delayp)
3593 ;; Search footnote references through DATA, filling
3594 ;; SEEN-REFS along the way. When DELAYP is non-nil, store
3595 ;; footnote definitions so they can be entered later.
3596 (org-element-map data 'footnote-reference
3597 (lambda (f)
3598 (funcall function f)
3599 (let ((--label (org-element-property :label f)))
3600 (unless (and --label (member --label seen-refs))
3601 (when --label (push --label seen-refs))
3602 ;; Search for subsequent references in footnote
3603 ;; definition so numbering follows reading logic,
3604 ;; unless DELAYP in non-nil.
3605 (cond
3606 (delayp
3607 (push (org-export-get-footnote-definition f info)
3608 definitions))
3609 ;; Do not force entering inline definitions,
3610 ;; since `org-element-map' already traverses them
3611 ;; at the right time.
3612 ((eq (org-element-property :type f) 'inline))
3613 (t (funcall search-ref
3614 (org-export-get-footnote-definition f info)
3615 nil))))))
3616 info nil
3617 ;; Don't enter footnote definitions since it will happen
3618 ;; when their first reference is found. Moreover, if
3619 ;; DELAYP is non-nil, make sure we postpone entering
3620 ;; definitions of inline references.
3621 (if delayp '(footnote-definition footnote-reference)
3622 'footnote-definition)))))
3623 (funcall search-ref data body-first)
3624 (funcall search-ref (nreverse definitions) nil)))
3626 (defun org-export-collect-footnote-definitions (info &optional data body-first)
3627 "Return an alist between footnote numbers, labels and definitions.
3629 INFO is the current export state, as a plist.
3631 Definitions are collected throughout the whole parse tree, or
3632 DATA when non-nil.
3634 Sorting is done by order of references. As soon as a new
3635 reference is encountered, other references are searched within
3636 its definition. However, if BODY-FIRST is non-nil, this step is
3637 delayed after the whole tree is checked. This alters results
3638 when references are found in footnote definitions.
3640 Definitions either appear as Org data or as a secondary string
3641 for inlined footnotes. Unreferenced definitions are ignored."
3642 (let ((n 0) labels alist)
3643 (org-export--footnote-reference-map
3644 (lambda (f)
3645 ;; Collect footnote number, label and definition.
3646 (let ((l (org-element-property :label f)))
3647 (unless (and l (member l labels))
3648 (incf n)
3649 (push (list n l (org-export-get-footnote-definition f info)) alist))
3650 (when l (push l labels))))
3651 (or data (plist-get info :parse-tree)) info body-first)
3652 (nreverse alist)))
3654 (defun org-export-footnote-first-reference-p
3655 (footnote-reference info &optional data body-first)
3656 "Non-nil when a footnote reference is the first one for its label.
3658 FOOTNOTE-REFERENCE is the footnote reference being considered.
3659 INFO is a plist containing current export state.
3661 Search is done throughout the whole parse tree, or DATA when
3662 non-nil.
3664 By default, as soon as a new footnote reference is encountered,
3665 other references are searched within its definition. However, if
3666 BODY-FIRST is non-nil, this step is delayed after the whole tree
3667 is checked. This alters results when references are found in
3668 footnote definitions."
3669 (let ((label (org-element-property :label footnote-reference)))
3670 ;; Anonymous footnotes are always a first reference.
3671 (or (not label)
3672 (catch 'exit
3673 (org-export--footnote-reference-map
3674 (lambda (f)
3675 (let ((l (org-element-property :label f)))
3676 (when (and l label (string= label l))
3677 (throw 'exit (eq footnote-reference f)))))
3678 (or data (plist-get info :parse-tree)) info body-first)))))
3680 (defun org-export-get-footnote-number (footnote info &optional data body-first)
3681 "Return number associated to a footnote.
3683 FOOTNOTE is either a footnote reference or a footnote definition.
3684 INFO is the plist containing export state.
3686 Number is unique throughout the whole parse tree, or DATA, when
3687 non-nil.
3689 By default, as soon as a new footnote reference is encountered,
3690 counting process moves into its definition. However, if
3691 BODY-FIRST is non-nil, this step is delayed until the end of the
3692 process, leading to a different order when footnotes are nested."
3693 (let ((count 0)
3694 (seen)
3695 (label (org-element-property :label footnote)))
3696 (catch 'exit
3697 (org-export--footnote-reference-map
3698 (lambda (f)
3699 (let ((l (org-element-property :label f)))
3700 (cond
3701 ;; Anonymous footnote match: return number.
3702 ((and (not l) (not label) (eq footnote f)) (throw 'exit (1+ count)))
3703 ;; Labels match: return number.
3704 ((and label l (string= label l)) (throw 'exit (1+ count)))
3705 ;; Otherwise store label and increase counter if label
3706 ;; wasn't encountered yet.
3707 ((not l) (incf count))
3708 ((not (member l seen)) (push l seen) (incf count)))))
3709 (or data (plist-get info :parse-tree)) info body-first))))
3712 ;;;; For Headlines
3714 ;; `org-export-get-relative-level' is a shortcut to get headline
3715 ;; level, relatively to the lower headline level in the parsed tree.
3717 ;; `org-export-get-headline-number' returns the section number of an
3718 ;; headline, while `org-export-number-to-roman' allows to convert it
3719 ;; to roman numbers. With an optional argument,
3720 ;; `org-export-get-headline-number' returns a number to unnumbered
3721 ;; headlines (used for internal id).
3723 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
3724 ;; `org-export-last-sibling-p' are three useful predicates when it
3725 ;; comes to fulfill the `:headline-levels' property.
3727 ;; `org-export-get-tags', `org-export-get-category' and
3728 ;; `org-export-get-node-property' extract useful information from an
3729 ;; headline or a parent headline. They all handle inheritance.
3731 ;; `org-export-get-alt-title' tries to retrieve an alternative title,
3732 ;; as a secondary string, suitable for table of contents. It falls
3733 ;; back onto default title.
3735 (defun org-export-get-relative-level (headline info)
3736 "Return HEADLINE relative level within current parsed tree.
3737 INFO is a plist holding contextual information."
3738 (+ (org-element-property :level headline)
3739 (or (plist-get info :headline-offset) 0)))
3741 (defun org-export-low-level-p (headline info)
3742 "Non-nil when HEADLINE is considered as low level.
3744 INFO is a plist used as a communication channel.
3746 A low level headlines has a relative level greater than
3747 `:headline-levels' property value.
3749 Return value is the difference between HEADLINE relative level
3750 and the last level being considered as high enough, or nil."
3751 (let ((limit (plist-get info :headline-levels)))
3752 (when (wholenump limit)
3753 (let ((level (org-export-get-relative-level headline info)))
3754 (and (> level limit) (- level limit))))))
3756 (defun org-export-get-headline-number (headline info)
3757 "Return numbered HEADLINE numbering as a list of numbers.
3758 INFO is a plist holding contextual information."
3759 (and (org-export-numbered-headline-p headline info)
3760 (cdr (assq headline (plist-get info :headline-numbering)))))
3762 (defun org-export-numbered-headline-p (headline info)
3763 "Return a non-nil value if HEADLINE element should be numbered.
3764 INFO is a plist used as a communication channel."
3765 (unless (org-some
3766 (lambda (head) (org-not-nil (org-element-property :UNNUMBERED head)))
3767 (org-element-lineage headline nil t))
3768 (let ((sec-num (plist-get info :section-numbers))
3769 (level (org-export-get-relative-level headline info)))
3770 (if (wholenump sec-num) (<= level sec-num) sec-num))))
3772 (defun org-export-number-to-roman (n)
3773 "Convert integer N into a roman numeral."
3774 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
3775 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
3776 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
3777 ( 1 . "I")))
3778 (res ""))
3779 (if (<= n 0)
3780 (number-to-string n)
3781 (while roman
3782 (if (>= n (caar roman))
3783 (setq n (- n (caar roman))
3784 res (concat res (cdar roman)))
3785 (pop roman)))
3786 res)))
3788 (defun org-export-get-tags (element info &optional tags inherited)
3789 "Return list of tags associated to ELEMENT.
3791 ELEMENT has either an `headline' or an `inlinetask' type. INFO
3792 is a plist used as a communication channel.
3794 Select tags (see `org-export-select-tags') and exclude tags (see
3795 `org-export-exclude-tags') are removed from the list.
3797 When non-nil, optional argument TAGS should be a list of strings.
3798 Any tag belonging to this list will also be removed.
3800 When optional argument INHERITED is non-nil, tags can also be
3801 inherited from parent headlines and FILETAGS keywords."
3802 (org-remove-if
3803 (lambda (tag) (or (member tag (plist-get info :select-tags))
3804 (member tag (plist-get info :exclude-tags))
3805 (member tag tags)))
3806 (if (not inherited) (org-element-property :tags element)
3807 ;; Build complete list of inherited tags.
3808 (let ((current-tag-list (org-element-property :tags element)))
3809 (dolist (parent (org-element-lineage element))
3810 (dolist (tag (org-element-property :tags parent))
3811 (when (and (memq (org-element-type parent) '(headline inlinetask))
3812 (not (member tag current-tag-list)))
3813 (push tag current-tag-list))))
3814 ;; Add FILETAGS keywords and return results.
3815 (org-uniquify (append (plist-get info :filetags) current-tag-list))))))
3817 (defun org-export-get-node-property (property blob &optional inherited)
3818 "Return node PROPERTY value for BLOB.
3820 PROPERTY is an upcase symbol (i.e. `:COOKIE_DATA'). BLOB is an
3821 element or object.
3823 If optional argument INHERITED is non-nil, the value can be
3824 inherited from a parent headline.
3826 Return value is a string or nil."
3827 (let ((headline (if (eq (org-element-type blob) 'headline) blob
3828 (org-export-get-parent-headline blob))))
3829 (if (not inherited) (org-element-property property blob)
3830 (let ((parent headline) value)
3831 (catch 'found
3832 (while parent
3833 (when (plist-member (nth 1 parent) property)
3834 (throw 'found (org-element-property property parent)))
3835 (setq parent (org-element-property :parent parent))))))))
3837 (defun org-export-get-category (blob info)
3838 "Return category for element or object BLOB.
3840 INFO is a plist used as a communication channel.
3842 CATEGORY is automatically inherited from a parent headline, from
3843 #+CATEGORY: keyword or created out of original file name. If all
3844 fail, the fall-back value is \"???\"."
3845 (or (org-export-get-node-property :CATEGORY blob t)
3846 (org-element-map (plist-get info :parse-tree) 'keyword
3847 (lambda (kwd)
3848 (when (equal (org-element-property :key kwd) "CATEGORY")
3849 (org-element-property :value kwd)))
3850 info 'first-match)
3851 (let ((file (plist-get info :input-file)))
3852 (and file (file-name-sans-extension (file-name-nondirectory file))))
3853 "???"))
3855 (defun org-export-get-alt-title (headline info)
3856 "Return alternative title for HEADLINE, as a secondary string.
3857 INFO is a plist used as a communication channel. If no optional
3858 title is defined, fall-back to the regular title."
3859 (let ((alt (org-element-property :ALT_TITLE headline)))
3860 (if alt (org-element-parse-secondary-string
3861 alt (org-element-restriction 'headline) headline)
3862 (org-element-property :title headline))))
3864 (defun org-export-first-sibling-p (blob info)
3865 "Non-nil when BLOB is the first sibling in its parent.
3866 BLOB is an element or an object. If BLOB is a headline, non-nil
3867 means it is the first sibling in the sub-tree. INFO is a plist
3868 used as a communication channel."
3869 (memq (org-element-type (org-export-get-previous-element blob info))
3870 '(nil section)))
3872 (defun org-export-last-sibling-p (blob info)
3873 "Non-nil when BLOB is the last sibling in its parent.
3874 BLOB is an element or an object. INFO is a plist used as
3875 a communication channel."
3876 (not (org-export-get-next-element blob info)))
3879 ;;;; For Keywords
3881 ;; `org-export-get-date' returns a date appropriate for the document
3882 ;; to about to be exported. In particular, it takes care of
3883 ;; `org-export-date-timestamp-format'.
3885 (defun org-export-get-date (info &optional fmt)
3886 "Return date value for the current document.
3888 INFO is a plist used as a communication channel. FMT, when
3889 non-nil, is a time format string that will be applied on the date
3890 if it consists in a single timestamp object. It defaults to
3891 `org-export-date-timestamp-format' when nil.
3893 A proper date can be a secondary string, a string or nil. It is
3894 meant to be translated with `org-export-data' or alike."
3895 (let ((date (plist-get info :date))
3896 (fmt (or fmt org-export-date-timestamp-format)))
3897 (cond ((not date) nil)
3898 ((and fmt
3899 (not (cdr date))
3900 (eq (org-element-type (car date)) 'timestamp))
3901 (org-timestamp-format (car date) fmt))
3902 (t date))))
3905 ;;;; For Links
3907 ;; `org-export-custom-protocol-maybe' handles custom protocol defined
3908 ;; with `org-add-link-type', which see.
3910 ;; `org-export-get-coderef-format' returns an appropriate format
3911 ;; string for coderefs.
3913 ;; `org-export-inline-image-p' returns a non-nil value when the link
3914 ;; provided should be considered as an inline image.
3916 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
3917 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
3918 ;; returns an appropriate unique identifier when found, or nil.
3920 ;; `org-export-resolve-id-link' returns the first headline with
3921 ;; specified id or custom-id in parse tree, the path to the external
3922 ;; file with the id or nil when neither was found.
3924 ;; `org-export-resolve-coderef' associates a reference to a line
3925 ;; number in the element it belongs, or returns the reference itself
3926 ;; when the element isn't numbered.
3928 ;; `org-export-file-uri' expands a filename as stored in :path value
3929 ;; of a "file" link into a file URI.
3931 (defun org-export-custom-protocol-maybe (link desc backend)
3932 "Try exporting LINK with a dedicated function.
3934 DESC is its description, as a string, or nil. BACKEND is the
3935 back-end used for export, as a symbol.
3937 Return output as a string, or nil if no protocol handles LINK.
3939 A custom protocol has precedence over regular back-end export.
3940 The function ignores links with an implicit type (e.g.,
3941 \"custom-id\")."
3942 (let ((type (org-element-property :type link)))
3943 (unless (or (member type '("coderef" "custom-id" "fuzzy" "radio"))
3944 (not backend))
3945 (let ((protocol (nth 2 (assoc type org-link-protocols))))
3946 (and (functionp protocol)
3947 (funcall protocol
3948 (org-link-unescape (org-element-property :path link))
3949 desc
3950 backend))))))
3952 (defun org-export-get-coderef-format (path desc)
3953 "Return format string for code reference link.
3954 PATH is the link path. DESC is its description."
3955 (save-match-data
3956 (cond ((not desc) "%s")
3957 ((string-match (regexp-quote (concat "(" path ")")) desc)
3958 (replace-match "%s" t t desc))
3959 (t desc))))
3961 (defun org-export-inline-image-p (link &optional rules)
3962 "Non-nil if LINK object points to an inline image.
3964 Optional argument is a set of RULES defining inline images. It
3965 is an alist where associations have the following shape:
3967 \(TYPE . REGEXP)
3969 Applying a rule means apply REGEXP against LINK's path when its
3970 type is TYPE. The function will return a non-nil value if any of
3971 the provided rules is non-nil. The default rule is
3972 `org-export-default-inline-image-rule'.
3974 This only applies to links without a description."
3975 (and (not (org-element-contents link))
3976 (let ((case-fold-search t))
3977 (catch 'exit
3978 (dolist (rule (or rules org-export-default-inline-image-rule))
3979 (and (string= (org-element-property :type link) (car rule))
3980 (org-string-match-p (cdr rule)
3981 (org-element-property :path link))
3982 (throw 'exit t)))))))
3984 (defun org-export-resolve-coderef (ref info)
3985 "Resolve a code reference REF.
3987 INFO is a plist used as a communication channel.
3989 Return associated line number in source code, or REF itself,
3990 depending on src-block or example element's switches. Throw an
3991 error if no block contains REF."
3992 (or (org-element-map (plist-get info :parse-tree) '(example-block src-block)
3993 (lambda (el)
3994 (with-temp-buffer
3995 (insert (org-trim (org-element-property :value el)))
3996 (let* ((label-fmt (regexp-quote
3997 (or (org-element-property :label-fmt el)
3998 org-coderef-label-format)))
3999 (ref-re
4000 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
4001 (format label-fmt ref))))
4002 ;; Element containing REF is found. Resolve it to
4003 ;; either a label or a line number, as needed.
4004 (when (re-search-backward ref-re nil t)
4005 (cond
4006 ((org-element-property :use-labels el) ref)
4007 ((eq (org-element-property :number-lines el) 'continued)
4008 (+ (org-export-get-loc el info) (line-number-at-pos)))
4009 (t (line-number-at-pos)))))))
4010 info 'first-match)
4011 (user-error "Unable to resolve code reference: %s" ref)))
4013 (defun org-export-resolve-fuzzy-link (link info)
4014 "Return LINK destination.
4016 INFO is a plist holding contextual information.
4018 Return value can be an object, an element, or nil:
4020 - If LINK path matches a target object (i.e. <<path>>) return it.
4022 - If LINK path exactly matches the name affiliated keyword
4023 \(i.e. #+NAME: path) of an element, return that element.
4025 - If LINK path exactly matches any headline name, return that
4026 element. If more than one headline share that name, priority
4027 will be given to the one with the closest common ancestor, if
4028 any, or the first one in the parse tree otherwise.
4030 - Otherwise, throw an error.
4032 Assume LINK type is \"fuzzy\". White spaces are not
4033 significant."
4034 (let* ((raw-path (org-element-property :path link))
4035 (match-title-p (eq (string-to-char raw-path) ?*))
4036 ;; Split PATH at white spaces so matches are space
4037 ;; insensitive.
4038 (path (org-split-string
4039 (if match-title-p (substring raw-path 1) raw-path)))
4040 ;; Cache for destinations that are not position dependent.
4041 (link-cache
4042 (or (plist-get info :resolve-fuzzy-link-cache)
4043 (plist-get (setq info (plist-put info :resolve-fuzzy-link-cache
4044 (make-hash-table :test 'equal)))
4045 :resolve-fuzzy-link-cache)))
4046 (cached (gethash path link-cache 'not-found)))
4047 (cond
4048 ;; Destination is not position dependent: use cached value.
4049 ((and (not match-title-p) (not (eq cached 'not-found))) cached)
4050 ;; First try to find a matching "<<path>>" unless user specified
4051 ;; he was looking for a headline (path starts with a "*"
4052 ;; character).
4053 ((and (not match-title-p)
4054 (let ((match (org-element-map (plist-get info :parse-tree) 'target
4055 (lambda (blob)
4056 (and (equal (org-split-string
4057 (org-element-property :value blob))
4058 path)
4059 blob))
4060 info 'first-match)))
4061 (and match (puthash path match link-cache)))))
4062 ;; Then try to find an element with a matching "#+NAME: path"
4063 ;; affiliated keyword.
4064 ((and (not match-title-p)
4065 (let ((match (org-element-map (plist-get info :parse-tree)
4066 org-element-all-elements
4067 (lambda (el)
4068 (let ((name (org-element-property :name el)))
4069 (when (and name
4070 (equal (org-split-string name) path))
4071 el)))
4072 info 'first-match)))
4073 (and match (puthash path match link-cache)))))
4074 ;; Last case: link either points to a headline or to nothingness.
4075 ;; Try to find the source, with priority given to headlines with
4076 ;; the closest common ancestor. If such candidate is found,
4077 ;; return it, otherwise signal an error.
4079 (let ((find-headline
4080 (function
4081 ;; Return first headline whose `:raw-value' property is
4082 ;; NAME in parse tree DATA, or nil. Statistics cookies
4083 ;; are ignored.
4084 (lambda (name data)
4085 (org-element-map data 'headline
4086 (lambda (headline)
4087 (when (equal (org-split-string
4088 (replace-regexp-in-string
4089 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
4090 (org-element-property :raw-value headline)))
4091 name)
4092 headline))
4093 info 'first-match)))))
4094 ;; Search among headlines sharing an ancestor with link, from
4095 ;; closest to farthest.
4096 (catch 'exit
4097 (dolist (parent
4098 (let ((parent-hl (org-export-get-parent-headline link)))
4099 (if (not parent-hl) (list (plist-get info :parse-tree))
4100 (org-element-lineage parent-hl nil t))))
4101 (let ((foundp (funcall find-headline path parent)))
4102 (when foundp (throw 'exit foundp))))
4103 ;; No destination found: error.
4104 (user-error "Unable to resolve link \"%s\"" raw-path)))))))
4106 (defun org-export-resolve-id-link (link info)
4107 "Return headline referenced as LINK destination.
4109 INFO is a plist used as a communication channel.
4111 Return value can be the headline element matched in current parse
4112 tree or a file name. Assume LINK type is either \"id\" or
4113 \"custom-id\". Throw an error if no match is found."
4114 (let ((id (org-element-property :path link)))
4115 ;; First check if id is within the current parse tree.
4116 (or (org-element-map (plist-get info :parse-tree) 'headline
4117 (lambda (headline)
4118 (when (or (equal (org-element-property :ID headline) id)
4119 (equal (org-element-property :CUSTOM_ID headline) id))
4120 headline))
4121 info 'first-match)
4122 ;; Otherwise, look for external files.
4123 (cdr (assoc id (plist-get info :id-alist)))
4124 (user-error "Unable to resolve ID \"%s\"" id))))
4126 (defun org-export-resolve-radio-link (link info)
4127 "Return radio-target object referenced as LINK destination.
4129 INFO is a plist used as a communication channel.
4131 Return value can be a radio-target object or nil. Assume LINK
4132 has type \"radio\"."
4133 (let ((path (replace-regexp-in-string
4134 "[ \r\t\n]+" " " (org-element-property :path link))))
4135 (org-element-map (plist-get info :parse-tree) 'radio-target
4136 (lambda (radio)
4137 (and (eq (compare-strings
4138 (replace-regexp-in-string
4139 "[ \r\t\n]+" " " (org-element-property :value radio))
4140 nil nil path nil nil t)
4142 radio))
4143 info 'first-match)))
4145 (defun org-export-file-uri (filename)
4146 "Return file URI associated to FILENAME."
4147 (if (not (file-name-absolute-p filename)) filename
4148 (concat "file:/"
4149 (and (not (org-file-remote-p filename)) "/")
4150 (if (org-string-match-p "\\`~" filename)
4151 (expand-file-name filename)
4152 filename))))
4155 ;;;; For References
4157 ;; `org-export-get-reference' associate a unique reference for any
4158 ;; object or element.
4160 ;; `org-export-get-ordinal' associates a sequence number to any object
4161 ;; or element.
4163 (defun org-export-get-reference (datum info)
4164 "Return a unique reference for DATUM, as a string.
4165 DATUM is either an element or an object. INFO is the current
4166 export state, as a plist. Returned reference consists of
4167 alphanumeric characters only."
4168 (let ((type (org-element-type datum))
4169 (cache (or (plist-get info :internal-references)
4170 (let ((h (make-hash-table :test #'eq)))
4171 (plist-put info :internal-references h)
4172 h))))
4173 (or (gethash datum cache)
4174 (puthash datum
4175 (format "org%s%d"
4176 (if type
4177 (replace-regexp-in-string "-" "" (symbol-name type))
4178 "secondarystring")
4179 (incf (gethash type cache 0)))
4180 cache))))
4182 (defun org-export-get-ordinal (element info &optional types predicate)
4183 "Return ordinal number of an element or object.
4185 ELEMENT is the element or object considered. INFO is the plist
4186 used as a communication channel.
4188 Optional argument TYPES, when non-nil, is a list of element or
4189 object types, as symbols, that should also be counted in.
4190 Otherwise, only provided element's type is considered.
4192 Optional argument PREDICATE is a function returning a non-nil
4193 value if the current element or object should be counted in. It
4194 accepts two arguments: the element or object being considered and
4195 the plist used as a communication channel. This allows to count
4196 only a certain type of objects (i.e. inline images).
4198 Return value is a list of numbers if ELEMENT is a headline or an
4199 item. It is nil for keywords. It represents the footnote number
4200 for footnote definitions and footnote references. If ELEMENT is
4201 a target, return the same value as if ELEMENT was the closest
4202 table, item or headline containing the target. In any other
4203 case, return the sequence number of ELEMENT among elements or
4204 objects of the same type."
4205 ;; Ordinal of a target object refer to the ordinal of the closest
4206 ;; table, item, or headline containing the object.
4207 (when (eq (org-element-type element) 'target)
4208 (setq element
4209 (org-element-lineage
4210 element
4211 '(footnote-definition footnote-reference headline item table))))
4212 (case (org-element-type element)
4213 ;; Special case 1: A headline returns its number as a list.
4214 (headline (org-export-get-headline-number element info))
4215 ;; Special case 2: An item returns its number as a list.
4216 (item (let ((struct (org-element-property :structure element)))
4217 (org-list-get-item-number
4218 (org-element-property :begin element)
4219 struct
4220 (org-list-prevs-alist struct)
4221 (org-list-parents-alist struct))))
4222 ((footnote-definition footnote-reference)
4223 (org-export-get-footnote-number element info))
4224 (otherwise
4225 (let ((counter 0))
4226 ;; Increment counter until ELEMENT is found again.
4227 (org-element-map (plist-get info :parse-tree)
4228 (or types (org-element-type element))
4229 (lambda (el)
4230 (cond
4231 ((eq element el) (1+ counter))
4232 ((not predicate) (incf counter) nil)
4233 ((funcall predicate el info) (incf counter) nil)))
4234 info 'first-match)))))
4237 ;;;; For Src-Blocks
4239 ;; `org-export-get-loc' counts number of code lines accumulated in
4240 ;; src-block or example-block elements with a "+n" switch until
4241 ;; a given element, excluded. Note: "-n" switches reset that count.
4243 ;; `org-export-unravel-code' extracts source code (along with a code
4244 ;; references alist) from an `element-block' or `src-block' type
4245 ;; element.
4247 ;; `org-export-format-code' applies a formatting function to each line
4248 ;; of code, providing relative line number and code reference when
4249 ;; appropriate. Since it doesn't access the original element from
4250 ;; which the source code is coming, it expects from the code calling
4251 ;; it to know if lines should be numbered and if code references
4252 ;; should appear.
4254 ;; Eventually, `org-export-format-code-default' is a higher-level
4255 ;; function (it makes use of the two previous functions) which handles
4256 ;; line numbering and code references inclusion, and returns source
4257 ;; code in a format suitable for plain text or verbatim output.
4259 (defun org-export-get-loc (element info)
4260 "Return accumulated lines of code up to ELEMENT.
4262 INFO is the plist used as a communication channel.
4264 ELEMENT is excluded from count."
4265 (let ((loc 0))
4266 (org-element-map (plist-get info :parse-tree)
4267 `(src-block example-block ,(org-element-type element))
4268 (lambda (el)
4269 (cond
4270 ;; ELEMENT is reached: Quit the loop.
4271 ((eq el element))
4272 ;; Only count lines from src-block and example-block elements
4273 ;; with a "+n" or "-n" switch. A "-n" switch resets counter.
4274 ((not (memq (org-element-type el) '(src-block example-block))) nil)
4275 ((let ((linums (org-element-property :number-lines el)))
4276 (when linums
4277 ;; Accumulate locs or reset them.
4278 (let ((lines (org-count-lines
4279 (org-trim (org-element-property :value el)))))
4280 (setq loc (if (eq linums 'new) lines (+ loc lines))))))
4281 ;; Return nil to stay in the loop.
4282 nil)))
4283 info 'first-match)
4284 ;; Return value.
4285 loc))
4287 (defun org-export-unravel-code (element)
4288 "Clean source code and extract references out of it.
4290 ELEMENT has either a `src-block' an `example-block' type.
4292 Return a cons cell whose CAR is the source code, cleaned from any
4293 reference, protective commas and spurious indentation, and CDR is
4294 an alist between relative line number (integer) and name of code
4295 reference on that line (string)."
4296 (let* ((line 0) refs
4297 (value (org-element-property :value element))
4298 ;; Get code and clean it. Remove blank lines at its
4299 ;; beginning and end.
4300 (code (replace-regexp-in-string
4301 "\\`\\([ \t]*\n\\)+" ""
4302 (replace-regexp-in-string
4303 "\\([ \t]*\n\\)*[ \t]*\\'" "\n"
4304 (if (or org-src-preserve-indentation
4305 (org-element-property :preserve-indent element))
4306 value
4307 (org-element-remove-indentation value)))))
4308 ;; Get format used for references.
4309 (label-fmt (regexp-quote
4310 (or (org-element-property :label-fmt element)
4311 org-coderef-label-format)))
4312 ;; Build a regexp matching a loc with a reference.
4313 (with-ref-re
4314 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)[ \t]*\\)$"
4315 (replace-regexp-in-string
4316 "%s" "\\([-a-zA-Z0-9_ ]+\\)" label-fmt nil t))))
4317 ;; Return value.
4318 (cons
4319 ;; Code with references removed.
4320 (org-element-normalize-string
4321 (mapconcat
4322 (lambda (loc)
4323 (incf line)
4324 (if (not (string-match with-ref-re loc)) loc
4325 ;; Ref line: remove ref, and signal its position in REFS.
4326 (push (cons line (match-string 3 loc)) refs)
4327 (replace-match "" nil nil loc 1)))
4328 (org-split-string code "\n") "\n"))
4329 ;; Reference alist.
4330 refs)))
4332 (defun org-export-format-code (code fun &optional num-lines ref-alist)
4333 "Format CODE by applying FUN line-wise and return it.
4335 CODE is a string representing the code to format. FUN is
4336 a function. It must accept three arguments: a line of
4337 code (string), the current line number (integer) or nil and the
4338 reference associated to the current line (string) or nil.
4340 Optional argument NUM-LINES can be an integer representing the
4341 number of code lines accumulated until the current code. Line
4342 numbers passed to FUN will take it into account. If it is nil,
4343 FUN's second argument will always be nil. This number can be
4344 obtained with `org-export-get-loc' function.
4346 Optional argument REF-ALIST can be an alist between relative line
4347 number (i.e. ignoring NUM-LINES) and the name of the code
4348 reference on it. If it is nil, FUN's third argument will always
4349 be nil. It can be obtained through the use of
4350 `org-export-unravel-code' function."
4351 (let ((--locs (org-split-string code "\n"))
4352 (--line 0))
4353 (org-element-normalize-string
4354 (mapconcat
4355 (lambda (--loc)
4356 (incf --line)
4357 (let ((--ref (cdr (assq --line ref-alist))))
4358 (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
4359 --locs "\n"))))
4361 (defun org-export-format-code-default (element info)
4362 "Return source code from ELEMENT, formatted in a standard way.
4364 ELEMENT is either a `src-block' or `example-block' element. INFO
4365 is a plist used as a communication channel.
4367 This function takes care of line numbering and code references
4368 inclusion. Line numbers, when applicable, appear at the
4369 beginning of the line, separated from the code by two white
4370 spaces. Code references, on the other hand, appear flushed to
4371 the right, separated by six white spaces from the widest line of
4372 code."
4373 ;; Extract code and references.
4374 (let* ((code-info (org-export-unravel-code element))
4375 (code (car code-info))
4376 (code-lines (org-split-string code "\n")))
4377 (if (null code-lines) ""
4378 (let* ((refs (and (org-element-property :retain-labels element)
4379 (cdr code-info)))
4380 ;; Handle line numbering.
4381 (num-start (case (org-element-property :number-lines element)
4382 (continued (org-export-get-loc element info))
4383 (new 0)))
4384 (num-fmt
4385 (and num-start
4386 (format "%%%ds "
4387 (length (number-to-string
4388 (+ (length code-lines) num-start))))))
4389 ;; Prepare references display, if required. Any reference
4390 ;; should start six columns after the widest line of code,
4391 ;; wrapped with parenthesis.
4392 (max-width
4393 (+ (apply 'max (mapcar 'length code-lines))
4394 (if (not num-start) 0 (length (format num-fmt num-start))))))
4395 (org-export-format-code
4396 code
4397 (lambda (loc line-num ref)
4398 (let ((number-str (and num-fmt (format num-fmt line-num))))
4399 (concat
4400 number-str
4402 (and ref
4403 (concat (make-string
4404 (- (+ 6 max-width)
4405 (+ (length loc) (length number-str))) ? )
4406 (format "(%s)" ref))))))
4407 num-start refs)))))
4410 ;;;; For Tables
4412 ;; `org-export-table-has-special-column-p' and and
4413 ;; `org-export-table-row-is-special-p' are predicates used to look for
4414 ;; meta-information about the table structure.
4416 ;; `org-table-has-header-p' tells when the rows before the first rule
4417 ;; should be considered as table's header.
4419 ;; `org-export-table-cell-width', `org-export-table-cell-alignment'
4420 ;; and `org-export-table-cell-borders' extract information from
4421 ;; a table-cell element.
4423 ;; `org-export-table-dimensions' gives the number on rows and columns
4424 ;; in the table, ignoring horizontal rules and special columns.
4425 ;; `org-export-table-cell-address', given a table-cell object, returns
4426 ;; the absolute address of a cell. On the other hand,
4427 ;; `org-export-get-table-cell-at' does the contrary.
4429 ;; `org-export-table-cell-starts-colgroup-p',
4430 ;; `org-export-table-cell-ends-colgroup-p',
4431 ;; `org-export-table-row-starts-rowgroup-p',
4432 ;; `org-export-table-row-ends-rowgroup-p',
4433 ;; `org-export-table-row-starts-header-p',
4434 ;; `org-export-table-row-ends-header-p' and
4435 ;; `org-export-table-row-in-header-p' indicate position of current row
4436 ;; or cell within the table.
4438 (defun org-export-table-has-special-column-p (table)
4439 "Non-nil when TABLE has a special column.
4440 All special columns will be ignored during export."
4441 ;; The table has a special column when every first cell of every row
4442 ;; has an empty value or contains a symbol among "/", "#", "!", "$",
4443 ;; "*" "_" and "^". Though, do not consider a first row containing
4444 ;; only empty cells as special.
4445 (let ((special-column-p 'empty))
4446 (catch 'exit
4447 (mapc
4448 (lambda (row)
4449 (when (eq (org-element-property :type row) 'standard)
4450 (let ((value (org-element-contents
4451 (car (org-element-contents row)))))
4452 (cond ((member value '(("/") ("#") ("!") ("$") ("*") ("_") ("^")))
4453 (setq special-column-p 'special))
4454 ((not value))
4455 (t (throw 'exit nil))))))
4456 (org-element-contents table))
4457 (eq special-column-p 'special))))
4459 (defun org-export-table-has-header-p (table info)
4460 "Non-nil when TABLE has a header.
4462 INFO is a plist used as a communication channel.
4464 A table has a header when it contains at least two row groups."
4465 (let ((cache (or (plist-get info :table-header-cache)
4466 (plist-get (setq info
4467 (plist-put info :table-header-cache
4468 (make-hash-table :test 'eq)))
4469 :table-header-cache))))
4470 (or (gethash table cache)
4471 (let ((rowgroup 1) row-flag)
4472 (puthash
4473 table
4474 (org-element-map table 'table-row
4475 (lambda (row)
4476 (cond
4477 ((> rowgroup 1) t)
4478 ((and row-flag (eq (org-element-property :type row) 'rule))
4479 (incf rowgroup) (setq row-flag nil))
4480 ((and (not row-flag) (eq (org-element-property :type row)
4481 'standard))
4482 (setq row-flag t) nil)))
4483 info 'first-match)
4484 cache)))))
4486 (defun org-export-table-row-is-special-p (table-row info)
4487 "Non-nil if TABLE-ROW is considered special.
4489 INFO is a plist used as the communication channel.
4491 All special rows will be ignored during export."
4492 (when (eq (org-element-property :type table-row) 'standard)
4493 (let ((first-cell (org-element-contents
4494 (car (org-element-contents table-row)))))
4495 ;; A row is special either when...
4497 ;; ... it starts with a field only containing "/",
4498 (equal first-cell '("/"))
4499 ;; ... the table contains a special column and the row start
4500 ;; with a marking character among, "^", "_", "$" or "!",
4501 (and (org-export-table-has-special-column-p
4502 (org-export-get-parent table-row))
4503 (member first-cell '(("^") ("_") ("$") ("!"))))
4504 ;; ... it contains only alignment cookies and empty cells.
4505 (let ((special-row-p 'empty))
4506 (catch 'exit
4507 (mapc
4508 (lambda (cell)
4509 (let ((value (org-element-contents cell)))
4510 ;; Since VALUE is a secondary string, the following
4511 ;; checks avoid expanding it with `org-export-data'.
4512 (cond ((not value))
4513 ((and (not (cdr value))
4514 (stringp (car value))
4515 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'"
4516 (car value)))
4517 (setq special-row-p 'cookie))
4518 (t (throw 'exit nil)))))
4519 (org-element-contents table-row))
4520 (eq special-row-p 'cookie)))))))
4522 (defun org-export-table-row-group (table-row info)
4523 "Return TABLE-ROW's group number, as an integer.
4525 INFO is a plist used as the communication channel.
4527 Return value is the group number, as an integer, or nil for
4528 special rows and rows separators. First group is also table's
4529 header."
4530 (let ((cache (or (plist-get info :table-row-group-cache)
4531 (plist-get (setq info
4532 (plist-put info :table-row-group-cache
4533 (make-hash-table :test 'eq)))
4534 :table-row-group-cache))))
4535 (cond ((gethash table-row cache))
4536 ((eq (org-element-property :type table-row) 'rule) nil)
4537 (t (let ((group 0) row-flag)
4538 (org-element-map (org-export-get-parent table-row) 'table-row
4539 (lambda (row)
4540 (if (eq (org-element-property :type row) 'rule)
4541 (setq row-flag nil)
4542 (unless row-flag (incf group) (setq row-flag t)))
4543 (when (eq table-row row) (puthash table-row group cache)))
4544 info 'first-match))))))
4546 (defun org-export-table-cell-width (table-cell info)
4547 "Return TABLE-CELL contents width.
4549 INFO is a plist used as the communication channel.
4551 Return value is the width given by the last width cookie in the
4552 same column as TABLE-CELL, or nil."
4553 (let* ((row (org-export-get-parent table-cell))
4554 (table (org-export-get-parent row))
4555 (cells (org-element-contents row))
4556 (columns (length cells))
4557 (column (- columns (length (memq table-cell cells))))
4558 (cache (or (plist-get info :table-cell-width-cache)
4559 (plist-get (setq info
4560 (plist-put info :table-cell-width-cache
4561 (make-hash-table :test 'eq)))
4562 :table-cell-width-cache)))
4563 (width-vector (or (gethash table cache)
4564 (puthash table (make-vector columns 'empty) cache)))
4565 (value (aref width-vector column)))
4566 (if (not (eq value 'empty)) value
4567 (let (cookie-width)
4568 (dolist (row (org-element-contents table)
4569 (aset width-vector column cookie-width))
4570 (when (org-export-table-row-is-special-p row info)
4571 ;; In a special row, try to find a width cookie at COLUMN.
4572 (let* ((value (org-element-contents
4573 (elt (org-element-contents row) column)))
4574 (cookie (car value)))
4575 ;; The following checks avoid expanding unnecessarily
4576 ;; the cell with `org-export-data'.
4577 (when (and value
4578 (not (cdr value))
4579 (stringp cookie)
4580 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'" cookie)
4581 (match-string 1 cookie))
4582 (setq cookie-width
4583 (string-to-number (match-string 1 cookie)))))))))))
4585 (defun org-export-table-cell-alignment (table-cell info)
4586 "Return TABLE-CELL contents alignment.
4588 INFO is a plist used as the communication channel.
4590 Return alignment as specified by the last alignment cookie in the
4591 same column as TABLE-CELL. If no such cookie is found, a default
4592 alignment value will be deduced from fraction of numbers in the
4593 column (see `org-table-number-fraction' for more information).
4594 Possible values are `left', `right' and `center'."
4595 ;; Load `org-table-number-fraction' and `org-table-number-regexp'.
4596 (require 'org-table)
4597 (let* ((row (org-export-get-parent table-cell))
4598 (table (org-export-get-parent row))
4599 (cells (org-element-contents row))
4600 (columns (length cells))
4601 (column (- columns (length (memq table-cell cells))))
4602 (cache (or (plist-get info :table-cell-alignment-cache)
4603 (plist-get (setq info
4604 (plist-put info :table-cell-alignment-cache
4605 (make-hash-table :test 'eq)))
4606 :table-cell-alignment-cache)))
4607 (align-vector (or (gethash table cache)
4608 (puthash table (make-vector columns nil) cache))))
4609 (or (aref align-vector column)
4610 (let ((number-cells 0)
4611 (total-cells 0)
4612 cookie-align
4613 previous-cell-number-p)
4614 (dolist (row (org-element-contents (org-export-get-parent row)))
4615 (cond
4616 ;; In a special row, try to find an alignment cookie at
4617 ;; COLUMN.
4618 ((org-export-table-row-is-special-p row info)
4619 (let ((value (org-element-contents
4620 (elt (org-element-contents row) column))))
4621 ;; Since VALUE is a secondary string, the following
4622 ;; checks avoid useless expansion through
4623 ;; `org-export-data'.
4624 (when (and value
4625 (not (cdr value))
4626 (stringp (car value))
4627 (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'"
4628 (car value))
4629 (match-string 1 (car value)))
4630 (setq cookie-align (match-string 1 (car value))))))
4631 ;; Ignore table rules.
4632 ((eq (org-element-property :type row) 'rule))
4633 ;; In a standard row, check if cell's contents are
4634 ;; expressing some kind of number. Increase NUMBER-CELLS
4635 ;; accordingly. Though, don't bother if an alignment
4636 ;; cookie has already defined cell's alignment.
4637 ((not cookie-align)
4638 (let ((value (org-export-data
4639 (org-element-contents
4640 (elt (org-element-contents row) column))
4641 info)))
4642 (incf total-cells)
4643 ;; Treat an empty cell as a number if it follows
4644 ;; a number.
4645 (if (not (or (string-match org-table-number-regexp value)
4646 (and (string= value "") previous-cell-number-p)))
4647 (setq previous-cell-number-p nil)
4648 (setq previous-cell-number-p t)
4649 (incf number-cells))))))
4650 ;; Return value. Alignment specified by cookies has
4651 ;; precedence over alignment deduced from cell's contents.
4652 (aset align-vector
4653 column
4654 (cond ((equal cookie-align "l") 'left)
4655 ((equal cookie-align "r") 'right)
4656 ((equal cookie-align "c") 'center)
4657 ((>= (/ (float number-cells) total-cells)
4658 org-table-number-fraction)
4659 'right)
4660 (t 'left)))))))
4662 (defun org-export-table-cell-borders (table-cell info)
4663 "Return TABLE-CELL borders.
4665 INFO is a plist used as a communication channel.
4667 Return value is a list of symbols, or nil. Possible values are:
4668 `top', `bottom', `above', `below', `left' and `right'. Note:
4669 `top' (resp. `bottom') only happen for a cell in the first
4670 row (resp. last row) of the table, ignoring table rules, if any.
4672 Returned borders ignore special rows."
4673 (let* ((row (org-export-get-parent table-cell))
4674 (table (org-export-get-parent-table table-cell))
4675 borders)
4676 ;; Top/above border? TABLE-CELL has a border above when a rule
4677 ;; used to demarcate row groups can be found above. Hence,
4678 ;; finding a rule isn't sufficient to push `above' in BORDERS:
4679 ;; another regular row has to be found above that rule.
4680 (let (rule-flag)
4681 (catch 'exit
4682 (mapc (lambda (row)
4683 (cond ((eq (org-element-property :type row) 'rule)
4684 (setq rule-flag t))
4685 ((not (org-export-table-row-is-special-p row info))
4686 (if rule-flag (throw 'exit (push 'above borders))
4687 (throw 'exit nil)))))
4688 ;; Look at every row before the current one.
4689 (cdr (memq row (reverse (org-element-contents table)))))
4690 ;; No rule above, or rule found starts the table (ignoring any
4691 ;; special row): TABLE-CELL is at the top of the table.
4692 (when rule-flag (push 'above borders))
4693 (push 'top borders)))
4694 ;; Bottom/below border? TABLE-CELL has a border below when next
4695 ;; non-regular row below is a rule.
4696 (let (rule-flag)
4697 (catch 'exit
4698 (mapc (lambda (row)
4699 (cond ((eq (org-element-property :type row) 'rule)
4700 (setq rule-flag t))
4701 ((not (org-export-table-row-is-special-p row info))
4702 (if rule-flag (throw 'exit (push 'below borders))
4703 (throw 'exit nil)))))
4704 ;; Look at every row after the current one.
4705 (cdr (memq row (org-element-contents table))))
4706 ;; No rule below, or rule found ends the table (modulo some
4707 ;; special row): TABLE-CELL is at the bottom of the table.
4708 (when rule-flag (push 'below borders))
4709 (push 'bottom borders)))
4710 ;; Right/left borders? They can only be specified by column
4711 ;; groups. Column groups are defined in a row starting with "/".
4712 ;; Also a column groups row only contains "<", "<>", ">" or blank
4713 ;; cells.
4714 (catch 'exit
4715 (let ((column (let ((cells (org-element-contents row)))
4716 (- (length cells) (length (memq table-cell cells))))))
4717 (mapc
4718 (lambda (row)
4719 (unless (eq (org-element-property :type row) 'rule)
4720 (when (equal (org-element-contents
4721 (car (org-element-contents row)))
4722 '("/"))
4723 (let ((column-groups
4724 (mapcar
4725 (lambda (cell)
4726 (let ((value (org-element-contents cell)))
4727 (when (member value '(("<") ("<>") (">") nil))
4728 (car value))))
4729 (org-element-contents row))))
4730 ;; There's a left border when previous cell, if
4731 ;; any, ends a group, or current one starts one.
4732 (when (or (and (not (zerop column))
4733 (member (elt column-groups (1- column))
4734 '(">" "<>")))
4735 (member (elt column-groups column) '("<" "<>")))
4736 (push 'left borders))
4737 ;; There's a right border when next cell, if any,
4738 ;; starts a group, or current one ends one.
4739 (when (or (and (/= (1+ column) (length column-groups))
4740 (member (elt column-groups (1+ column))
4741 '("<" "<>")))
4742 (member (elt column-groups column) '(">" "<>")))
4743 (push 'right borders))
4744 (throw 'exit nil)))))
4745 ;; Table rows are read in reverse order so last column groups
4746 ;; row has precedence over any previous one.
4747 (reverse (org-element-contents table)))))
4748 ;; Return value.
4749 borders))
4751 (defun org-export-table-cell-starts-colgroup-p (table-cell info)
4752 "Non-nil when TABLE-CELL is at the beginning of a column group.
4753 INFO is a plist used as a communication channel."
4754 ;; A cell starts a column group either when it is at the beginning
4755 ;; of a row (or after the special column, if any) or when it has
4756 ;; a left border.
4757 (or (eq (org-element-map (org-export-get-parent table-cell) 'table-cell
4758 'identity info 'first-match)
4759 table-cell)
4760 (memq 'left (org-export-table-cell-borders table-cell info))))
4762 (defun org-export-table-cell-ends-colgroup-p (table-cell info)
4763 "Non-nil when TABLE-CELL is at the end of a column group.
4764 INFO is a plist used as a communication channel."
4765 ;; A cell ends a column group either when it is at the end of a row
4766 ;; or when it has a right border.
4767 (or (eq (car (last (org-element-contents
4768 (org-export-get-parent table-cell))))
4769 table-cell)
4770 (memq 'right (org-export-table-cell-borders table-cell info))))
4772 (defun org-export-table-row-starts-rowgroup-p (table-row info)
4773 "Non-nil when TABLE-ROW is at the beginning of a row group.
4774 INFO is a plist used as a communication channel."
4775 (unless (or (eq (org-element-property :type table-row) 'rule)
4776 (org-export-table-row-is-special-p table-row info))
4777 (let ((borders (org-export-table-cell-borders
4778 (car (org-element-contents table-row)) info)))
4779 (or (memq 'top borders) (memq 'above borders)))))
4781 (defun org-export-table-row-ends-rowgroup-p (table-row info)
4782 "Non-nil when TABLE-ROW is at the end of a row group.
4783 INFO is a plist used as a communication channel."
4784 (unless (or (eq (org-element-property :type table-row) 'rule)
4785 (org-export-table-row-is-special-p table-row info))
4786 (let ((borders (org-export-table-cell-borders
4787 (car (org-element-contents table-row)) info)))
4788 (or (memq 'bottom borders) (memq 'below borders)))))
4790 (defun org-export-table-row-in-header-p (table-row info)
4791 "Non-nil when TABLE-ROW is located within table's header.
4792 INFO is a plist used as a communication channel. Always return
4793 nil for special rows and rows separators."
4794 (and (org-export-table-has-header-p
4795 (org-export-get-parent-table table-row) info)
4796 (eql (org-export-table-row-group table-row info) 1)))
4798 (defun org-export-table-row-starts-header-p (table-row info)
4799 "Non-nil when TABLE-ROW is the first table header's row.
4800 INFO is a plist used as a communication channel."
4801 (and (org-export-table-row-in-header-p table-row info)
4802 (org-export-table-row-starts-rowgroup-p table-row info)))
4804 (defun org-export-table-row-ends-header-p (table-row info)
4805 "Non-nil when TABLE-ROW is the last table header's row.
4806 INFO is a plist used as a communication channel."
4807 (and (org-export-table-row-in-header-p table-row info)
4808 (org-export-table-row-ends-rowgroup-p table-row info)))
4810 (defun org-export-table-row-number (table-row info)
4811 "Return TABLE-ROW number.
4812 INFO is a plist used as a communication channel. Return value is
4813 zero-based and ignores separators. The function returns nil for
4814 special columns and separators."
4815 (when (and (eq (org-element-property :type table-row) 'standard)
4816 (not (org-export-table-row-is-special-p table-row info)))
4817 (let ((number 0))
4818 (org-element-map (org-export-get-parent-table table-row) 'table-row
4819 (lambda (row)
4820 (cond ((eq row table-row) number)
4821 ((eq (org-element-property :type row) 'standard)
4822 (incf number) nil)))
4823 info 'first-match))))
4825 (defun org-export-table-dimensions (table info)
4826 "Return TABLE dimensions.
4828 INFO is a plist used as a communication channel.
4830 Return value is a CONS like (ROWS . COLUMNS) where
4831 ROWS (resp. COLUMNS) is the number of exportable
4832 rows (resp. columns)."
4833 (let (first-row (columns 0) (rows 0))
4834 ;; Set number of rows, and extract first one.
4835 (org-element-map table 'table-row
4836 (lambda (row)
4837 (when (eq (org-element-property :type row) 'standard)
4838 (incf rows)
4839 (unless first-row (setq first-row row)))) info)
4840 ;; Set number of columns.
4841 (org-element-map first-row 'table-cell (lambda (cell) (incf columns)) info)
4842 ;; Return value.
4843 (cons rows columns)))
4845 (defun org-export-table-cell-address (table-cell info)
4846 "Return address of a regular TABLE-CELL object.
4848 TABLE-CELL is the cell considered. INFO is a plist used as
4849 a communication channel.
4851 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4852 zero-based index. Only exportable cells are considered. The
4853 function returns nil for other cells."
4854 (let* ((table-row (org-export-get-parent table-cell))
4855 (row-number (org-export-table-row-number table-row info)))
4856 (when row-number
4857 (cons row-number
4858 (let ((col-count 0))
4859 (org-element-map table-row 'table-cell
4860 (lambda (cell)
4861 (if (eq cell table-cell) col-count (incf col-count) nil))
4862 info 'first-match))))))
4864 (defun org-export-get-table-cell-at (address table info)
4865 "Return regular table-cell object at ADDRESS in TABLE.
4867 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4868 zero-based index. TABLE is a table type element. INFO is
4869 a plist used as a communication channel.
4871 If no table-cell, among exportable cells, is found at ADDRESS,
4872 return nil."
4873 (let ((column-pos (cdr address)) (column-count 0))
4874 (org-element-map
4875 ;; Row at (car address) or nil.
4876 (let ((row-pos (car address)) (row-count 0))
4877 (org-element-map table 'table-row
4878 (lambda (row)
4879 (cond ((eq (org-element-property :type row) 'rule) nil)
4880 ((= row-count row-pos) row)
4881 (t (incf row-count) nil)))
4882 info 'first-match))
4883 'table-cell
4884 (lambda (cell)
4885 (if (= column-count column-pos) cell
4886 (incf column-count) nil))
4887 info 'first-match)))
4890 ;;;; For Tables Of Contents
4892 ;; `org-export-collect-headlines' builds a list of all exportable
4893 ;; headline elements, maybe limited to a certain depth. One can then
4894 ;; easily parse it and transcode it.
4896 ;; Building lists of tables, figures or listings is quite similar.
4897 ;; Once the generic function `org-export-collect-elements' is defined,
4898 ;; `org-export-collect-tables', `org-export-collect-figures' and
4899 ;; `org-export-collect-listings' can be derived from it.
4901 (defun org-export-collect-headlines (info &optional n scope)
4902 "Collect headlines in order to build a table of contents.
4904 INFO is a plist used as a communication channel.
4906 When optional argument N is an integer, it specifies the depth of
4907 the table of contents. Otherwise, it is set to the value of the
4908 last headline level. See `org-export-headline-levels' for more
4909 information.
4911 Optional argument SCOPE, when non-nil, is an element. If it is
4912 a headline, only children of SCOPE are collected. Otherwise,
4913 collect children of the headline containing provided element. If
4914 there is no such headline, collect all headlines. In any case,
4915 argument N becomes relative to the level of that headline.
4917 Return a list of all exportable headlines as parsed elements.
4918 Footnote sections are ignored."
4919 (let* ((scope (cond ((not scope) (plist-get info :parse-tree))
4920 ((eq (org-element-type scope) 'headline) scope)
4921 ((org-export-get-parent-headline scope))
4922 (t (plist-get info :parse-tree))))
4923 (limit (plist-get info :headline-levels))
4924 (n (if (not (wholenump n)) limit
4925 (min (if (eq (org-element-type scope) 'org-data) n
4926 (+ (org-export-get-relative-level scope info) n))
4927 limit))))
4928 (org-element-map (org-element-contents scope) 'headline
4929 (lambda (headline)
4930 (unless (org-element-property :footnote-section-p headline)
4931 (let ((level (org-export-get-relative-level headline info)))
4932 (and (<= level n) headline))))
4933 info)))
4935 (defun org-export-collect-elements (type info &optional predicate)
4936 "Collect referenceable elements of a determined type.
4938 TYPE can be a symbol or a list of symbols specifying element
4939 types to search. Only elements with a caption are collected.
4941 INFO is a plist used as a communication channel.
4943 When non-nil, optional argument PREDICATE is a function accepting
4944 one argument, an element of type TYPE. It returns a non-nil
4945 value when that element should be collected.
4947 Return a list of all elements found, in order of appearance."
4948 (org-element-map (plist-get info :parse-tree) type
4949 (lambda (element)
4950 (and (org-element-property :caption element)
4951 (or (not predicate) (funcall predicate element))
4952 element))
4953 info))
4955 (defun org-export-collect-tables (info)
4956 "Build a list of tables.
4957 INFO is a plist used as a communication channel.
4959 Return a list of table elements with a caption."
4960 (org-export-collect-elements 'table info))
4962 (defun org-export-collect-figures (info predicate)
4963 "Build a list of figures.
4965 INFO is a plist used as a communication channel. PREDICATE is
4966 a function which accepts one argument: a paragraph element and
4967 whose return value is non-nil when that element should be
4968 collected.
4970 A figure is a paragraph type element, with a caption, verifying
4971 PREDICATE. The latter has to be provided since a \"figure\" is
4972 a vague concept that may depend on back-end.
4974 Return a list of elements recognized as figures."
4975 (org-export-collect-elements 'paragraph info predicate))
4977 (defun org-export-collect-listings (info)
4978 "Build a list of src blocks.
4980 INFO is a plist used as a communication channel.
4982 Return a list of src-block elements with a caption."
4983 (org-export-collect-elements 'src-block info))
4986 ;;;; Smart Quotes
4988 ;; The main function for the smart quotes sub-system is
4989 ;; `org-export-activate-smart-quotes', which replaces every quote in
4990 ;; a given string from the parse tree with its "smart" counterpart.
4992 ;; Dictionary for smart quotes is stored in
4993 ;; `org-export-smart-quotes-alist'.
4995 ;; Internally, regexps matching potential smart quotes (checks at
4996 ;; string boundaries are also necessary) are defined in
4997 ;; `org-export-smart-quotes-regexps'.
4999 (defconst org-export-smart-quotes-alist
5000 '(("da"
5001 ;; one may use: »...«, "...", ›...‹, or '...'.
5002 ;; http://sproget.dk/raad-og-regler/retskrivningsregler/retskrivningsregler/a7-40-60/a7-58-anforselstegn/
5003 ;; LaTeX quotes require Babel!
5004 (opening-double-quote :utf-8 "»" :html "&raquo;" :latex ">>"
5005 :texinfo "@guillemetright{}")
5006 (closing-double-quote :utf-8 "«" :html "&laquo;" :latex "<<"
5007 :texinfo "@guillemetleft{}")
5008 (opening-single-quote :utf-8 "›" :html "&rsaquo;" :latex "\\frq{}"
5009 :texinfo "@guilsinglright{}")
5010 (closing-single-quote :utf-8 "‹" :html "&lsaquo;" :latex "\\flq{}"
5011 :texinfo "@guilsingleft{}")
5012 (apostrophe :utf-8 "’" :html "&rsquo;"))
5013 ("de"
5014 (opening-double-quote :utf-8 "„" :html "&bdquo;" :latex "\"`"
5015 :texinfo "@quotedblbase{}")
5016 (closing-double-quote :utf-8 "“" :html "&ldquo;" :latex "\"'"
5017 :texinfo "@quotedblleft{}")
5018 (opening-single-quote :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}"
5019 :texinfo "@quotesinglbase{}")
5020 (closing-single-quote :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}"
5021 :texinfo "@quoteleft{}")
5022 (apostrophe :utf-8 "’" :html "&rsquo;"))
5023 ("en"
5024 (opening-double-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
5025 (closing-double-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
5026 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5027 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5028 (apostrophe :utf-8 "’" :html "&rsquo;"))
5029 ("es"
5030 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5031 :texinfo "@guillemetleft{}")
5032 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5033 :texinfo "@guillemetright{}")
5034 (opening-single-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
5035 (closing-single-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
5036 (apostrophe :utf-8 "’" :html "&rsquo;"))
5037 ("fr"
5038 (opening-double-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
5039 :texinfo "@guillemetleft{}@tie{}")
5040 (closing-double-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
5041 :texinfo "@tie{}@guillemetright{}")
5042 (opening-single-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
5043 :texinfo "@guillemetleft{}@tie{}")
5044 (closing-single-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
5045 :texinfo "@tie{}@guillemetright{}")
5046 (apostrophe :utf-8 "’" :html "&rsquo;"))
5047 ("no"
5048 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5049 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5050 :texinfo "@guillemetleft{}")
5051 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5052 :texinfo "@guillemetright{}")
5053 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5054 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5055 (apostrophe :utf-8 "’" :html "&rsquo;"))
5056 ("nb"
5057 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5058 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5059 :texinfo "@guillemetleft{}")
5060 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5061 :texinfo "@guillemetright{}")
5062 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5063 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5064 (apostrophe :utf-8 "’" :html "&rsquo;"))
5065 ("nn"
5066 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5067 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5068 :texinfo "@guillemetleft{}")
5069 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5070 :texinfo "@guillemetright{}")
5071 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5072 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5073 (apostrophe :utf-8 "’" :html "&rsquo;"))
5074 ("ru"
5075 ;; 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
5076 ;; http://www.artlebedev.ru/kovodstvo/sections/104/
5077 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "{}<<"
5078 :texinfo "@guillemetleft{}")
5079 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex ">>{}"
5080 :texinfo "@guillemetright{}")
5081 (opening-single-quote :utf-8 "„" :html "&bdquo;" :latex "\\glqq{}"
5082 :texinfo "@quotedblbase{}")
5083 (closing-single-quote :utf-8 "“" :html "&ldquo;" :latex "\\grqq{}"
5084 :texinfo "@quotedblleft{}")
5085 (apostrophe :utf-8 "’" :html: "&#39;"))
5086 ("sv"
5087 ;; based on https://sv.wikipedia.org/wiki/Citattecken
5088 (opening-double-quote :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
5089 (closing-double-quote :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
5090 (opening-single-quote :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "`")
5091 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "'")
5092 (apostrophe :utf-8 "’" :html "&rsquo;"))
5094 "Smart quotes translations.
5096 Alist whose CAR is a language string and CDR is an alist with
5097 quote type as key and a plist associating various encodings to
5098 their translation as value.
5100 A quote type can be any symbol among `opening-double-quote',
5101 `closing-double-quote', `opening-single-quote',
5102 `closing-single-quote' and `apostrophe'.
5104 Valid encodings include `:utf-8', `:html', `:latex' and
5105 `:texinfo'.
5107 If no translation is found, the quote character is left as-is.")
5109 (defun org-export--smart-quote-status (s info)
5110 "Return smart quote status at the beginning of string S.
5111 INFO is the current export state, as a plist."
5112 (let* ((parent (org-element-property :parent s))
5113 (cache (or (plist-get info :smart-quote-cache)
5114 (let ((table (make-hash-table :test #'eq)))
5115 (plist-put info :smart-quote-cache table)
5116 table)))
5117 (value (gethash parent cache 'missing-data)))
5118 (if (not (eq value 'missing-data)) (cdr (assq s value))
5119 (let (level1-open level2-open full-status)
5120 (org-element-map parent 'plain-text
5121 (lambda (text)
5122 (let ((start 0) current-status)
5123 (while (setq start (string-match "['\"]" text start))
5124 (incf start)
5125 (push
5126 (cond
5127 ((equal (match-string 0 text) "\"")
5128 (setf level1-open (not level1-open))
5129 (setf level2-open nil)
5130 (if level1-open 'opening-double-quote 'closing-double-quote))
5131 ;; Not already in a level 1 quote: this is an
5132 ;; apostrophe.
5133 ((not level1-open) 'apostrophe)
5134 ;; Apostrophe.
5135 ((org-string-match-p "\\S-'\\S-" text) 'apostrophe)
5136 ;; Apostrophe at the beginning of a string. Check
5137 ;; white space at the end of the last object.
5138 ((and (org-string-match-p "\\`'\\S-" text)
5139 (let ((p (org-export-get-previous-element text info)))
5140 (and p
5141 (if (stringp p)
5142 (not (org-string-match-p "[ \t]\\'" p))
5143 (memq (org-element-property :post-blank p)
5144 '(0 nil))))))
5145 'apostrophe)
5146 ;; Apostrophe at the end of a string. Check white
5147 ;; space at the beginning of the next object, which
5148 ;; can only happen if that object is a string.
5149 ((and (org-string-match-p "\\S-'\\'" text)
5150 (let ((n (org-export-get-next-element text info)))
5151 (and n
5152 (not (and (stringp n)
5153 (org-string-match-p "\\`[ \t]" n))))))
5154 'apostrophe)
5155 ;; Lonesome apostrophe. Check white space around
5156 ;; both ends.
5157 ((and (equal text "'")
5158 (let ((p (org-export-get-previous-element text info)))
5159 (and p
5160 (if (stringp p)
5161 (not (org-string-match-p "[ \t]\\'" p))
5162 (memq (org-element-property :post-blank p)
5163 '(0 nil)))
5164 (let ((n (org-export-get-next-element text info)))
5165 (and n
5166 (not (and (stringp n)
5167 (org-string-match-p "\\`[ \t]"
5168 n))))))))
5169 'apostrophe)
5170 ;; Else, consider it as a level 2 quote.
5171 (t (setf level2-open (not level2-open))
5172 (if level2-open 'opening-single-quote
5173 'closing-single-quote)))
5174 current-status))
5175 (when current-status
5176 (push (cons text (nreverse current-status)) full-status))))
5177 info nil org-element-recursive-objects)
5178 (puthash parent full-status cache)
5179 (cdr (assq s full-status))))))
5181 (defun org-export-activate-smart-quotes (s encoding info &optional original)
5182 "Replace regular quotes with \"smart\" quotes in string S.
5184 ENCODING is a symbol among `:html', `:latex', `:texinfo' and
5185 `:utf-8'. INFO is a plist used as a communication channel.
5187 The function has to retrieve information about string
5188 surroundings in parse tree. It can only happen with an
5189 unmodified string. Thus, if S has already been through another
5190 process, a non-nil ORIGINAL optional argument will provide that
5191 original string.
5193 Return the new string."
5194 (let ((quote-status
5195 (copy-sequence (org-export--smart-quote-status (or original s) info))))
5196 (replace-regexp-in-string
5197 "['\"]"
5198 (lambda (match)
5199 (or (plist-get
5200 (cdr (assq (pop quote-status)
5201 (cdr (assoc (plist-get info :language)
5202 org-export-smart-quotes-alist))))
5203 encoding)
5204 match))
5205 s nil t)))
5207 ;;;; Topology
5209 ;; Here are various functions to retrieve information about the
5210 ;; neighborhood of a given element or object. Neighbors of interest
5211 ;; are direct parent (`org-export-get-parent'), parent headline
5212 ;; (`org-export-get-parent-headline'), first element containing an
5213 ;; object, (`org-export-get-parent-element'), parent table
5214 ;; (`org-export-get-parent-table'), previous element or object
5215 ;; (`org-export-get-previous-element') and next element or object
5216 ;; (`org-export-get-next-element').
5218 ;; defsubst org-export-get-parent must be defined before first use
5220 (define-obsolete-function-alias
5221 'org-export-get-genealogy 'org-element-lineage "25.1")
5223 (defun org-export-get-parent-headline (blob)
5224 "Return BLOB parent headline or nil.
5225 BLOB is the element or object being considered."
5226 (org-element-lineage blob '(headline)))
5228 (defun org-export-get-parent-element (object)
5229 "Return first element containing OBJECT or nil.
5230 OBJECT is the object to consider."
5231 (org-element-lineage object org-element-all-elements))
5233 (defun org-export-get-parent-table (object)
5234 "Return OBJECT parent table or nil.
5235 OBJECT is either a `table-cell' or `table-element' type object."
5236 (org-element-lineage object '(table)))
5238 (defun org-export-get-previous-element (blob info &optional n)
5239 "Return previous element or object.
5241 BLOB is an element or object. INFO is a plist used as
5242 a communication channel. Return previous exportable element or
5243 object, a string, or nil.
5245 When optional argument N is a positive integer, return a list
5246 containing up to N siblings before BLOB, from farthest to
5247 closest. With any other non-nil value, return a list containing
5248 all of them."
5249 (let* ((secondary (org-element-secondary-p blob))
5250 (parent (org-export-get-parent blob))
5251 (siblings
5252 (if secondary (org-element-property secondary parent)
5253 (org-element-contents parent)))
5254 prev)
5255 (catch 'exit
5256 (dolist (obj (cdr (memq blob (reverse siblings))) prev)
5257 (cond ((memq obj (plist-get info :ignore-list)))
5258 ((null n) (throw 'exit obj))
5259 ((not (wholenump n)) (push obj prev))
5260 ((zerop n) (throw 'exit prev))
5261 (t (decf n) (push obj prev)))))))
5263 (defun org-export-get-next-element (blob info &optional n)
5264 "Return next element or object.
5266 BLOB is an element or object. INFO is a plist used as
5267 a communication channel. Return next exportable element or
5268 object, a string, or nil.
5270 When optional argument N is a positive integer, return a list
5271 containing up to N siblings after BLOB, from closest to farthest.
5272 With any other non-nil value, return a list containing all of
5273 them."
5274 (let* ((secondary (org-element-secondary-p blob))
5275 (parent (org-export-get-parent blob))
5276 (siblings
5277 (cdr (memq blob
5278 (if secondary (org-element-property secondary parent)
5279 (org-element-contents parent)))))
5280 next)
5281 (catch 'exit
5282 (dolist (obj siblings (nreverse next))
5283 (cond ((memq obj (plist-get info :ignore-list)))
5284 ((null n) (throw 'exit obj))
5285 ((not (wholenump n)) (push obj next))
5286 ((zerop n) (throw 'exit (nreverse next)))
5287 (t (decf n) (push obj next)))))))
5290 ;;;; Translation
5292 ;; `org-export-translate' translates a string according to the language
5293 ;; specified by the LANGUAGE keyword. `org-export-dictionary' contains
5294 ;; the dictionary used for the translation.
5296 (defconst org-export-dictionary
5297 '(("%e %n: %c"
5298 ("fr" :default "%e %n : %c" :html "%e&nbsp;%n&nbsp;: %c"))
5299 ("Author"
5300 ("ca" :default "Autor")
5301 ("cs" :default "Autor")
5302 ("da" :default "Forfatter")
5303 ("de" :default "Autor")
5304 ("eo" :html "A&#365;toro")
5305 ("es" :default "Autor")
5306 ("et" :default "Autor")
5307 ("fi" :html "Tekij&auml;")
5308 ("fr" :default "Auteur")
5309 ("hu" :default "Szerz&otilde;")
5310 ("is" :html "H&ouml;fundur")
5311 ("it" :default "Autore")
5312 ("ja" :default "著者" :html "&#33879;&#32773;")
5313 ("nl" :default "Auteur")
5314 ("no" :default "Forfatter")
5315 ("nb" :default "Forfatter")
5316 ("nn" :default "Forfattar")
5317 ("pl" :default "Autor")
5318 ("pt_BR" :default "Autor")
5319 ("ru" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5320 ("sv" :html "F&ouml;rfattare")
5321 ("uk" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5322 ("zh-CN" :html "&#20316;&#32773;" :utf-8 "作者")
5323 ("zh-TW" :html "&#20316;&#32773;" :utf-8 "作者"))
5324 ("Continued from previous page"
5325 ("de" :default "Fortsetzung von vorheriger Seite")
5326 ("es" :html "Contin&uacute;a de la p&aacute;gina anterior" :ascii "Continua de la pagina anterior" :default "Continúa de la página anterior")
5327 ("fr" :default "Suite de la page précédente")
5328 ("it" :default "Continua da pagina precedente")
5329 ("ja" :default "前ページからの続き")
5330 ("nl" :default "Vervolg van vorige pagina")
5331 ("pt" :default "Continuação da página anterior")
5332 ("ru" :html "(&#1055;&#1088;&#1086;&#1076;&#1086;&#1083;&#1078;&#1077;&#1085;&#1080;&#1077;)"
5333 :utf-8 "(Продолжение)"))
5334 ("Continued on next page"
5335 ("de" :default "Fortsetzung nächste Seite")
5336 ("es" :html "Contin&uacute;a en la siguiente p&aacute;gina" :ascii "Continua en la siguiente pagina" :default "Continúa en la siguiente página")
5337 ("fr" :default "Suite page suivante")
5338 ("it" :default "Continua alla pagina successiva")
5339 ("ja" :default "次ページに続く")
5340 ("nl" :default "Vervolg op volgende pagina")
5341 ("pt" :default "Continua na página seguinte")
5342 ("ru" :html "(&#1055;&#1088;&#1086;&#1076;&#1086;&#1083;&#1078;&#1077;&#1085;&#1080;&#1077; &#1089;&#1083;&#1077;&#1076;&#1091;&#1077;&#1090;)"
5343 :utf-8 "(Продолжение следует)"))
5344 ("Date"
5345 ("ca" :default "Data")
5346 ("cs" :default "Datum")
5347 ("da" :default "Dato")
5348 ("de" :default "Datum")
5349 ("eo" :default "Dato")
5350 ("es" :default "Fecha")
5351 ("et" :html "Kuup&#228;ev" :utf-8 "Kuupäev")
5352 ("fi" :html "P&auml;iv&auml;m&auml;&auml;r&auml;")
5353 ("hu" :html "D&aacute;tum")
5354 ("is" :default "Dagsetning")
5355 ("it" :default "Data")
5356 ("ja" :default "日付" :html "&#26085;&#20184;")
5357 ("nl" :default "Datum")
5358 ("no" :default "Dato")
5359 ("nb" :default "Dato")
5360 ("nn" :default "Dato")
5361 ("pl" :default "Data")
5362 ("pt_BR" :default "Data")
5363 ("ru" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5364 ("sv" :default "Datum")
5365 ("uk" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5366 ("zh-CN" :html "&#26085;&#26399;" :utf-8 "日期")
5367 ("zh-TW" :html "&#26085;&#26399;" :utf-8 "日期"))
5368 ("Equation"
5369 ("da" :default "Ligning")
5370 ("de" :default "Gleichung")
5371 ("es" :ascii "Ecuacion" :html "Ecuaci&oacute;n" :default "Ecuación")
5372 ("et" :html "V&#245;rrand" :utf-8 "Võrrand")
5373 ("fr" :ascii "Equation" :default "Équation")
5374 ("ja" :default "方程式")
5375 ("no" :default "Ligning")
5376 ("nb" :default "Ligning")
5377 ("nn" :default "Likning")
5378 ("pt_BR" :html "Equa&ccedil;&atilde;o" :default "Equação" :ascii "Equacao")
5379 ("ru" :html "&#1059;&#1088;&#1072;&#1074;&#1085;&#1077;&#1085;&#1080;&#1077;"
5380 :utf-8 "Уравнение")
5381 ("sv" :default "Ekvation")
5382 ("zh-CN" :html "&#26041;&#31243;" :utf-8 "方程"))
5383 ("Figure"
5384 ("da" :default "Figur")
5385 ("de" :default "Abbildung")
5386 ("es" :default "Figura")
5387 ("et" :default "Joonis")
5388 ("ja" :default "図" :html "&#22259;")
5389 ("no" :default "Illustrasjon")
5390 ("nb" :default "Illustrasjon")
5391 ("nn" :default "Illustrasjon")
5392 ("pt_BR" :default "Figura")
5393 ("ru" :html "&#1056;&#1080;&#1089;&#1091;&#1085;&#1086;&#1082;" :utf-8 "Рисунок")
5394 ("sv" :default "Illustration")
5395 ("zh-CN" :html "&#22270;" :utf-8 "图"))
5396 ("Figure %d:"
5397 ("da" :default "Figur %d")
5398 ("de" :default "Abbildung %d:")
5399 ("es" :default "Figura %d:")
5400 ("et" :default "Joonis %d:")
5401 ("fr" :default "Figure %d :" :html "Figure&nbsp;%d&nbsp;:")
5402 ("ja" :default "図%d: " :html "&#22259;%d: ")
5403 ("no" :default "Illustrasjon %d")
5404 ("nb" :default "Illustrasjon %d")
5405 ("nn" :default "Illustrasjon %d")
5406 ("pt_BR" :default "Figura %d:")
5407 ("ru" :html "&#1056;&#1080;&#1089;. %d.:" :utf-8 "Рис. %d.:")
5408 ("sv" :default "Illustration %d")
5409 ("zh-CN" :html "&#22270;%d&nbsp;" :utf-8 "图%d "))
5410 ("Footnotes"
5411 ("ca" :html "Peus de p&agrave;gina")
5412 ("cs" :default "Pozn\xe1mky pod carou")
5413 ("da" :default "Fodnoter")
5414 ("de" :html "Fu&szlig;noten" :default "Fußnoten")
5415 ("eo" :default "Piednotoj")
5416 ("es" :ascii "Nota al pie de pagina" :html "Nota al pie de p&aacute;gina" :default "Nota al pie de página")
5417 ("et" :html "Allm&#228;rkused" :utf-8 "Allmärkused")
5418 ("fi" :default "Alaviitteet")
5419 ("fr" :default "Notes de bas de page")
5420 ("hu" :html "L&aacute;bjegyzet")
5421 ("is" :html "Aftanm&aacute;lsgreinar")
5422 ("it" :html "Note a pi&egrave; di pagina")
5423 ("ja" :default "脚注" :html "&#33050;&#27880;")
5424 ("nl" :default "Voetnoten")
5425 ("no" :default "Fotnoter")
5426 ("nb" :default "Fotnoter")
5427 ("nn" :default "Fotnotar")
5428 ("pl" :default "Przypis")
5429 ("pt_BR" :html "Notas de Rodap&eacute;" :default "Notas de Rodapé" :ascii "Notas de Rodape")
5430 ("ru" :html "&#1057;&#1085;&#1086;&#1089;&#1082;&#1080;" :utf-8 "Сноски")
5431 ("sv" :default "Fotnoter")
5432 ("uk" :html "&#1055;&#1088;&#1080;&#1084;&#1110;&#1090;&#1082;&#1080;"
5433 :utf-8 "Примітки")
5434 ("zh-CN" :html "&#33050;&#27880;" :utf-8 "脚注")
5435 ("zh-TW" :html "&#33139;&#35387;" :utf-8 "腳註"))
5436 ("List of Listings"
5437 ("da" :default "Programmer")
5438 ("de" :default "Programmauflistungsverzeichnis")
5439 ("es" :ascii "Indice de Listados de programas" :html "&Iacute;ndice de Listados de programas" :default "Índice de Listados de programas")
5440 ("et" :default "Loendite nimekiri")
5441 ("fr" :default "Liste des programmes")
5442 ("ja" :default "ソースコード目次")
5443 ("no" :default "Dataprogrammer")
5444 ("nb" :default "Dataprogrammer")
5445 ("ru" :html "&#1057;&#1087;&#1080;&#1089;&#1086;&#1082; &#1088;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1086;&#1082;"
5446 :utf-8 "Список распечаток")
5447 ("zh-CN" :html "&#20195;&#30721;&#30446;&#24405;" :utf-8 "代码目录"))
5448 ("List of Tables"
5449 ("da" :default "Tabeller")
5450 ("de" :default "Tabellenverzeichnis")
5451 ("es" :ascii "Indice de tablas" :html "&Iacute;ndice de tablas" :default "Índice de tablas")
5452 ("et" :default "Tabelite nimekiri")
5453 ("fr" :default "Liste des tableaux")
5454 ("ja" :default "表目次")
5455 ("no" :default "Tabeller")
5456 ("nb" :default "Tabeller")
5457 ("nn" :default "Tabeller")
5458 ("pt_BR" :default "Índice de Tabelas" :ascii "Indice de Tabelas")
5459 ("ru" :html "&#1057;&#1087;&#1080;&#1089;&#1086;&#1082; &#1090;&#1072;&#1073;&#1083;&#1080;&#1094;"
5460 :utf-8 "Список таблиц")
5461 ("sv" :default "Tabeller")
5462 ("zh-CN" :html "&#34920;&#26684;&#30446;&#24405;" :utf-8 "表格目录"))
5463 ("Listing"
5464 ("da" :default "Program")
5465 ("de" :default "Programmlisting")
5466 ("es" :default "Listado de programa")
5467 ("et" :default "Loend")
5468 ("fr" :default "Programme" :html "Programme")
5469 ("ja" :default "ソースコード")
5470 ("no" :default "Dataprogram")
5471 ("nb" :default "Dataprogram")
5472 ("pt_BR" :default "Listagem")
5473 ("ru" :html "&#1056;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1082;&#1072;"
5474 :utf-8 "Распечатка")
5475 ("zh-CN" :html "&#20195;&#30721;" :utf-8 "代码"))
5476 ("Listing %d:"
5477 ("da" :default "Program %d")
5478 ("de" :default "Programmlisting %d")
5479 ("es" :default "Listado de programa %d")
5480 ("et" :default "Loend %d")
5481 ("fr" :default "Programme %d :" :html "Programme&nbsp;%d&nbsp;:")
5482 ("ja" :default "ソースコード%d:")
5483 ("no" :default "Dataprogram %d")
5484 ("nb" :default "Dataprogram %d")
5485 ("pt_BR" :default "Listagem %d")
5486 ("ru" :html "&#1056;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1082;&#1072; %d.:"
5487 :utf-8 "Распечатка %d.:")
5488 ("zh-CN" :html "&#20195;&#30721;%d&nbsp;" :utf-8 "代码%d "))
5489 ("References"
5490 ("fr" :ascii "References" :default "Références")
5491 ("de" :default "Quellen")
5492 ("es" :default "Referencias"))
5493 ("See section %s"
5494 ("da" :default "jævnfør afsnit %s")
5495 ("de" :default "siehe Abschnitt %s")
5496 ("es" :ascii "Vea seccion %s" :html "Vea secci&oacute;n %s" :default "Vea sección %s")
5497 ("et" :html "Vaata peat&#252;kki %s" :utf-8 "Vaata peatükki %s")
5498 ("fr" :default "cf. section %s")
5499 ("ja" :default "セクション %s を参照")
5500 ("pt_BR" :html "Veja a se&ccedil;&atilde;o %s" :default "Veja a seção %s"
5501 :ascii "Veja a secao %s")
5502 ("ru" :html "&#1057;&#1084;. &#1088;&#1072;&#1079;&#1076;&#1077;&#1083; %s"
5503 :utf-8 "См. раздел %s")
5504 ("zh-CN" :html "&#21442;&#35265;&#31532;%s&#33410;" :utf-8 "参见第%s节"))
5505 ("Table"
5506 ("de" :default "Tabelle")
5507 ("es" :default "Tabla")
5508 ("et" :default "Tabel")
5509 ("fr" :default "Tableau")
5510 ("ja" :default "表" :html "&#34920;")
5511 ("pt_BR" :default "Tabela")
5512 ("ru" :html "&#1058;&#1072;&#1073;&#1083;&#1080;&#1094;&#1072;"
5513 :utf-8 "Таблица")
5514 ("zh-CN" :html "&#34920;" :utf-8 "表"))
5515 ("Table %d:"
5516 ("da" :default "Tabel %d")
5517 ("de" :default "Tabelle %d")
5518 ("es" :default "Tabla %d")
5519 ("et" :default "Tabel %d")
5520 ("fr" :default "Tableau %d :")
5521 ("ja" :default "表%d:" :html "&#34920;%d:")
5522 ("no" :default "Tabell %d")
5523 ("nb" :default "Tabell %d")
5524 ("nn" :default "Tabell %d")
5525 ("pt_BR" :default "Tabela %d")
5526 ("ru" :html "&#1058;&#1072;&#1073;&#1083;&#1080;&#1094;&#1072; %d.:"
5527 :utf-8 "Таблица %d.:")
5528 ("sv" :default "Tabell %d")
5529 ("zh-CN" :html "&#34920;%d&nbsp;" :utf-8 "表%d "))
5530 ("Table of Contents"
5531 ("ca" :html "&Iacute;ndex")
5532 ("cs" :default "Obsah")
5533 ("da" :default "Indhold")
5534 ("de" :default "Inhaltsverzeichnis")
5535 ("eo" :default "Enhavo")
5536 ("es" :ascii "Indice" :html "&Iacute;ndice" :default "Índice")
5537 ("et" :default "Sisukord")
5538 ("fi" :html "Sis&auml;llysluettelo")
5539 ("fr" :ascii "Sommaire" :default "Table des matières")
5540 ("hu" :html "Tartalomjegyz&eacute;k")
5541 ("is" :default "Efnisyfirlit")
5542 ("it" :default "Indice")
5543 ("ja" :default "目次" :html "&#30446;&#27425;")
5544 ("nl" :default "Inhoudsopgave")
5545 ("no" :default "Innhold")
5546 ("nb" :default "Innhold")
5547 ("nn" :default "Innhald")
5548 ("pl" :html "Spis tre&#x015b;ci")
5549 ("pt_BR" :html "&Iacute;ndice" :utf8 "Índice" :ascii "Indice")
5550 ("ru" :html "&#1057;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1077;"
5551 :utf-8 "Содержание")
5552 ("sv" :html "Inneh&aring;ll")
5553 ("uk" :html "&#1047;&#1084;&#1110;&#1089;&#1090;" :utf-8 "Зміст")
5554 ("zh-CN" :html "&#30446;&#24405;" :utf-8 "目录")
5555 ("zh-TW" :html "&#30446;&#37636;" :utf-8 "目錄"))
5556 ("Unknown reference"
5557 ("da" :default "ukendt reference")
5558 ("de" :default "Unbekannter Verweis")
5559 ("es" :default "Referencia desconocida")
5560 ("et" :default "Tundmatu viide")
5561 ("fr" :ascii "Destination inconnue" :default "Référence inconnue")
5562 ("ja" :default "不明な参照先")
5563 ("pt_BR" :default "Referência desconhecida"
5564 :ascii "Referencia desconhecida")
5565 ("ru" :html "&#1053;&#1077;&#1080;&#1079;&#1074;&#1077;&#1089;&#1090;&#1085;&#1072;&#1103; &#1089;&#1089;&#1099;&#1083;&#1082;&#1072;"
5566 :utf-8 "Неизвестная ссылка")
5567 ("zh-CN" :html "&#26410;&#30693;&#24341;&#29992;" :utf-8 "未知引用")))
5568 "Dictionary for export engine.
5570 Alist whose car is the string to translate and cdr is an alist
5571 whose car is the language string and cdr is a plist whose
5572 properties are possible charsets and values translated terms.
5574 It is used as a database for `org-export-translate'. Since this
5575 function returns the string as-is if no translation was found,
5576 the variable only needs to record values different from the
5577 entry.")
5579 (defun org-export-translate (s encoding info)
5580 "Translate string S according to language specification.
5582 ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1'
5583 and `:utf-8'. INFO is a plist used as a communication channel.
5585 Translation depends on `:language' property. Return the
5586 translated string. If no translation is found, try to fall back
5587 to `:default' encoding. If it fails, return S."
5588 (let* ((lang (plist-get info :language))
5589 (translations (cdr (assoc lang
5590 (cdr (assoc s org-export-dictionary))))))
5591 (or (plist-get translations encoding)
5592 (plist-get translations :default)
5593 s)))
5597 ;;; Asynchronous Export
5599 ;; `org-export-async-start' is the entry point for asynchronous
5600 ;; export. It recreates current buffer (including visibility,
5601 ;; narrowing and visited file) in an external Emacs process, and
5602 ;; evaluates a command there. It then applies a function on the
5603 ;; returned results in the current process.
5605 ;; At a higher level, `org-export-to-buffer' and `org-export-to-file'
5606 ;; allow to export to a buffer or a file, asynchronously or not.
5608 ;; `org-export-output-file-name' is an auxiliary function meant to be
5609 ;; used with `org-export-to-file'. With a given extension, it tries
5610 ;; to provide a canonical file name to write export output to.
5612 ;; Asynchronously generated results are never displayed directly.
5613 ;; Instead, they are stored in `org-export-stack-contents'. They can
5614 ;; then be retrieved by calling `org-export-stack'.
5616 ;; Export Stack is viewed through a dedicated major mode
5617 ;;`org-export-stack-mode' and tools: `org-export-stack-refresh',
5618 ;;`org-export-stack-delete', `org-export-stack-view' and
5619 ;;`org-export-stack-clear'.
5621 ;; For back-ends, `org-export-add-to-stack' add a new source to stack.
5622 ;; It should be used whenever `org-export-async-start' is called.
5624 (defmacro org-export-async-start (fun &rest body)
5625 "Call function FUN on the results returned by BODY evaluation.
5627 FUN is an anonymous function of one argument. BODY evaluation
5628 happens in an asynchronous process, from a buffer which is an
5629 exact copy of the current one.
5631 Use `org-export-add-to-stack' in FUN in order to register results
5632 in the stack.
5634 This is a low level function. See also `org-export-to-buffer'
5635 and `org-export-to-file' for more specialized functions."
5636 (declare (indent 1) (debug t))
5637 (org-with-gensyms (process temp-file copy-fun proc-buffer coding)
5638 ;; Write the full sexp evaluating BODY in a copy of the current
5639 ;; buffer to a temporary file, as it may be too long for program
5640 ;; args in `start-process'.
5641 `(with-temp-message "Initializing asynchronous export process"
5642 (let ((,copy-fun (org-export--generate-copy-script (current-buffer)))
5643 (,temp-file (make-temp-file "org-export-process"))
5644 (,coding buffer-file-coding-system))
5645 (with-temp-file ,temp-file
5646 (insert
5647 ;; Null characters (from variable values) are inserted
5648 ;; within the file. As a consequence, coding system for
5649 ;; buffer contents will not be recognized properly. So,
5650 ;; we make sure it is the same as the one used to display
5651 ;; the original buffer.
5652 (format ";; -*- coding: %s; -*-\n%S"
5653 ,coding
5654 `(with-temp-buffer
5655 (when org-export-async-debug '(setq debug-on-error t))
5656 ;; Ignore `kill-emacs-hook' and code evaluation
5657 ;; queries from Babel as we need a truly
5658 ;; non-interactive process.
5659 (setq kill-emacs-hook nil
5660 org-babel-confirm-evaluate-answer-no t)
5661 ;; Initialize export framework.
5662 (require 'ox)
5663 ;; Re-create current buffer there.
5664 (funcall ,,copy-fun)
5665 (restore-buffer-modified-p nil)
5666 ;; Sexp to evaluate in the buffer.
5667 (print (progn ,,@body))))))
5668 ;; Start external process.
5669 (let* ((process-connection-type nil)
5670 (,proc-buffer (generate-new-buffer-name "*Org Export Process*"))
5671 (,process
5672 (apply
5673 #'start-process
5674 (append
5675 (list "org-export-process"
5676 ,proc-buffer
5677 (expand-file-name invocation-name invocation-directory)
5678 "--batch")
5679 (if org-export-async-init-file
5680 (list "-Q" "-l" org-export-async-init-file)
5681 (list "-l" user-init-file))
5682 (list "-l" ,temp-file)))))
5683 ;; Register running process in stack.
5684 (org-export-add-to-stack (get-buffer ,proc-buffer) nil ,process)
5685 ;; Set-up sentinel in order to catch results.
5686 (let ((handler ,fun))
5687 (set-process-sentinel
5688 ,process
5689 `(lambda (p status)
5690 (let ((proc-buffer (process-buffer p)))
5691 (when (eq (process-status p) 'exit)
5692 (unwind-protect
5693 (if (zerop (process-exit-status p))
5694 (unwind-protect
5695 (let ((results
5696 (with-current-buffer proc-buffer
5697 (goto-char (point-max))
5698 (backward-sexp)
5699 (read (current-buffer)))))
5700 (funcall ,handler results))
5701 (unless org-export-async-debug
5702 (and (get-buffer proc-buffer)
5703 (kill-buffer proc-buffer))))
5704 (org-export-add-to-stack proc-buffer nil p)
5705 (ding)
5706 (message "Process '%s' exited abnormally" p))
5707 (unless org-export-async-debug
5708 (delete-file ,,temp-file)))))))))))))
5710 ;;;###autoload
5711 (defun org-export-to-buffer
5712 (backend buffer
5713 &optional async subtreep visible-only body-only ext-plist
5714 post-process)
5715 "Call `org-export-as' with output to a specified buffer.
5717 BACKEND is either an export back-end, as returned by, e.g.,
5718 `org-export-create-backend', or a symbol referring to
5719 a registered back-end.
5721 BUFFER is the name of the output buffer. If it already exists,
5722 it will be erased first, otherwise, it will be created.
5724 A non-nil optional argument ASYNC means the process should happen
5725 asynchronously. The resulting buffer should then be accessible
5726 through the `org-export-stack' interface. When ASYNC is nil, the
5727 buffer is displayed if `org-export-show-temporary-export-buffer'
5728 is non-nil.
5730 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
5731 EXT-PLIST are similar to those used in `org-export-as', which
5732 see.
5734 Optional argument POST-PROCESS is a function which should accept
5735 no argument. It is always called within the current process,
5736 from BUFFER, with point at its beginning. Export back-ends can
5737 use it to set a major mode there, e.g,
5739 \(defun org-latex-export-as-latex
5740 \(&optional async subtreep visible-only body-only ext-plist)
5741 \(interactive)
5742 \(org-export-to-buffer 'latex \"*Org LATEX Export*\"
5743 async subtreep visible-only body-only ext-plist (lambda () (LaTeX-mode))))
5745 This function returns BUFFER."
5746 (declare (indent 2))
5747 (if async
5748 (org-export-async-start
5749 `(lambda (output)
5750 (with-current-buffer (get-buffer-create ,buffer)
5751 (erase-buffer)
5752 (setq buffer-file-coding-system ',buffer-file-coding-system)
5753 (insert output)
5754 (goto-char (point-min))
5755 (org-export-add-to-stack (current-buffer) ',backend)
5756 (ignore-errors (funcall ,post-process))))
5757 `(org-export-as
5758 ',backend ,subtreep ,visible-only ,body-only ',ext-plist))
5759 (let ((output
5760 (org-export-as backend subtreep visible-only body-only ext-plist))
5761 (buffer (get-buffer-create buffer))
5762 (encoding buffer-file-coding-system))
5763 (when (and (org-string-nw-p output) (org-export--copy-to-kill-ring-p))
5764 (org-kill-new output))
5765 (with-current-buffer buffer
5766 (erase-buffer)
5767 (setq buffer-file-coding-system encoding)
5768 (insert output)
5769 (goto-char (point-min))
5770 (and (functionp post-process) (funcall post-process)))
5771 (when org-export-show-temporary-export-buffer
5772 (switch-to-buffer-other-window buffer))
5773 buffer)))
5775 ;;;###autoload
5776 (defun org-export-to-file
5777 (backend file &optional async subtreep visible-only body-only ext-plist
5778 post-process)
5779 "Call `org-export-as' with output to a specified file.
5781 BACKEND is either an export back-end, as returned by, e.g.,
5782 `org-export-create-backend', or a symbol referring to
5783 a registered back-end. FILE is the name of the output file, as
5784 a string.
5786 A non-nil optional argument ASYNC means the process should happen
5787 asynchronously. The resulting buffer will then be accessible
5788 through the `org-export-stack' interface.
5790 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
5791 EXT-PLIST are similar to those used in `org-export-as', which
5792 see.
5794 Optional argument POST-PROCESS is called with FILE as its
5795 argument and happens asynchronously when ASYNC is non-nil. It
5796 has to return a file name, or nil. Export back-ends can use this
5797 to send the output file through additional processing, e.g,
5799 \(defun org-latex-export-to-latex
5800 \(&optional async subtreep visible-only body-only ext-plist)
5801 \(interactive)
5802 \(let ((outfile (org-export-output-file-name \".tex\" subtreep)))
5803 \(org-export-to-file 'latex outfile
5804 async subtreep visible-only body-only ext-plist
5805 \(lambda (file) (org-latex-compile file)))
5807 The function returns either a file name returned by POST-PROCESS,
5808 or FILE."
5809 (declare (indent 2))
5810 (if (not (file-writable-p file)) (error "Output file not writable")
5811 (let ((ext-plist (org-combine-plists `(:output-file ,file) ext-plist))
5812 (encoding (or org-export-coding-system buffer-file-coding-system)))
5813 (if async
5814 (org-export-async-start
5815 `(lambda (file)
5816 (org-export-add-to-stack (expand-file-name file) ',backend))
5817 `(let ((output
5818 (org-export-as
5819 ',backend ,subtreep ,visible-only ,body-only
5820 ',ext-plist)))
5821 (with-temp-buffer
5822 (insert output)
5823 (let ((coding-system-for-write ',encoding))
5824 (write-file ,file)))
5825 (or (ignore-errors (funcall ',post-process ,file)) ,file)))
5826 (let ((output (org-export-as
5827 backend subtreep visible-only body-only ext-plist)))
5828 (with-temp-buffer
5829 (insert output)
5830 (let ((coding-system-for-write encoding))
5831 (write-file file)))
5832 (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p output))
5833 (org-kill-new output))
5834 ;; Get proper return value.
5835 (or (and (functionp post-process) (funcall post-process file))
5836 file))))))
5838 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
5839 "Return output file's name according to buffer specifications.
5841 EXTENSION is a string representing the output file extension,
5842 with the leading dot.
5844 With a non-nil optional argument SUBTREEP, try to determine
5845 output file's name by looking for \"EXPORT_FILE_NAME\" property
5846 of subtree at point.
5848 When optional argument PUB-DIR is set, use it as the publishing
5849 directory.
5851 When optional argument VISIBLE-ONLY is non-nil, don't export
5852 contents of hidden elements.
5854 Return file name as a string."
5855 (let* ((visited-file (buffer-file-name (buffer-base-buffer)))
5856 (base-name
5857 ;; File name may come from EXPORT_FILE_NAME subtree
5858 ;; property, assuming point is at beginning of said
5859 ;; sub-tree.
5860 (file-name-sans-extension
5861 (or (and subtreep
5862 (org-entry-get
5863 (save-excursion
5864 (ignore-errors (org-back-to-heading) (point)))
5865 "EXPORT_FILE_NAME" t))
5866 ;; File name may be extracted from buffer's associated
5867 ;; file, if any.
5868 (and visited-file (file-name-nondirectory visited-file))
5869 ;; Can't determine file name on our own: Ask user.
5870 (let ((read-file-name-function
5871 (and org-completion-use-ido 'ido-read-file-name)))
5872 (read-file-name
5873 "Output file: " pub-dir nil nil nil
5874 (lambda (name)
5875 (string= (file-name-extension name t) extension)))))))
5876 (output-file
5877 ;; Build file name. Enforce EXTENSION over whatever user
5878 ;; may have come up with. PUB-DIR, if defined, always has
5879 ;; precedence over any provided path.
5880 (cond
5881 (pub-dir
5882 (concat (file-name-as-directory pub-dir)
5883 (file-name-nondirectory base-name)
5884 extension))
5885 ((file-name-absolute-p base-name) (concat base-name extension))
5886 (t (concat (file-name-as-directory ".") base-name extension)))))
5887 ;; If writing to OUTPUT-FILE would overwrite original file, append
5888 ;; EXTENSION another time to final name.
5889 (if (and visited-file (org-file-equal-p visited-file output-file))
5890 (concat output-file extension)
5891 output-file)))
5893 (defun org-export-add-to-stack (source backend &optional process)
5894 "Add a new result to export stack if not present already.
5896 SOURCE is a buffer or a file name containing export results.
5897 BACKEND is a symbol representing export back-end used to generate
5900 Entries already pointing to SOURCE and unavailable entries are
5901 removed beforehand. Return the new stack."
5902 (setq org-export-stack-contents
5903 (cons (list source backend (or process (current-time)))
5904 (org-export-stack-remove source))))
5906 (defun org-export-stack ()
5907 "Menu for asynchronous export results and running processes."
5908 (interactive)
5909 (let ((buffer (get-buffer-create "*Org Export Stack*")))
5910 (set-buffer buffer)
5911 (when (zerop (buffer-size)) (org-export-stack-mode))
5912 (org-export-stack-refresh)
5913 (pop-to-buffer buffer))
5914 (message "Type \"q\" to quit, \"?\" for help"))
5916 (defun org-export--stack-source-at-point ()
5917 "Return source from export results at point in stack."
5918 (let ((source (car (nth (1- (org-current-line)) org-export-stack-contents))))
5919 (if (not source) (error "Source unavailable, please refresh buffer")
5920 (let ((source-name (if (stringp source) source (buffer-name source))))
5921 (if (save-excursion
5922 (beginning-of-line)
5923 (looking-at (concat ".* +" (regexp-quote source-name) "$")))
5924 source
5925 ;; SOURCE is not consistent with current line. The stack
5926 ;; view is outdated.
5927 (error "Source unavailable; type `g' to update buffer"))))))
5929 (defun org-export-stack-clear ()
5930 "Remove all entries from export stack."
5931 (interactive)
5932 (setq org-export-stack-contents nil))
5934 (defun org-export-stack-refresh (&rest dummy)
5935 "Refresh the asynchronous export stack.
5936 DUMMY is ignored. Unavailable sources are removed from the list.
5937 Return the new stack."
5938 (let ((inhibit-read-only t))
5939 (org-preserve-lc
5940 (erase-buffer)
5941 (insert (concat
5942 (let ((counter 0))
5943 (mapconcat
5944 (lambda (entry)
5945 (let ((proc-p (processp (nth 2 entry))))
5946 (concat
5947 ;; Back-end.
5948 (format " %-12s " (or (nth 1 entry) ""))
5949 ;; Age.
5950 (let ((data (nth 2 entry)))
5951 (if proc-p (format " %6s " (process-status data))
5952 ;; Compute age of the results.
5953 (org-format-seconds
5954 "%4h:%.2m "
5955 (float-time (time-since data)))))
5956 ;; Source.
5957 (format " %s"
5958 (let ((source (car entry)))
5959 (if (stringp source) source
5960 (buffer-name source)))))))
5961 ;; Clear stack from exited processes, dead buffers or
5962 ;; non-existent files.
5963 (setq org-export-stack-contents
5964 (org-remove-if-not
5965 (lambda (el)
5966 (if (processp (nth 2 el))
5967 (buffer-live-p (process-buffer (nth 2 el)))
5968 (let ((source (car el)))
5969 (if (bufferp source) (buffer-live-p source)
5970 (file-exists-p source)))))
5971 org-export-stack-contents)) "\n")))))))
5973 (defun org-export-stack-remove (&optional source)
5974 "Remove export results at point from stack.
5975 If optional argument SOURCE is non-nil, remove it instead."
5976 (interactive)
5977 (let ((source (or source (org-export--stack-source-at-point))))
5978 (setq org-export-stack-contents
5979 (org-remove-if (lambda (el) (equal (car el) source))
5980 org-export-stack-contents))))
5982 (defun org-export-stack-view (&optional in-emacs)
5983 "View export results at point in stack.
5984 With an optional prefix argument IN-EMACS, force viewing files
5985 within Emacs."
5986 (interactive "P")
5987 (let ((source (org-export--stack-source-at-point)))
5988 (cond ((processp source)
5989 (org-switch-to-buffer-other-window (process-buffer source)))
5990 ((bufferp source) (org-switch-to-buffer-other-window source))
5991 (t (org-open-file source in-emacs)))))
5993 (defvar org-export-stack-mode-map
5994 (let ((km (make-sparse-keymap)))
5995 (define-key km " " 'next-line)
5996 (define-key km "n" 'next-line)
5997 (define-key km "\C-n" 'next-line)
5998 (define-key km [down] 'next-line)
5999 (define-key km "p" 'previous-line)
6000 (define-key km "\C-p" 'previous-line)
6001 (define-key km "\C-?" 'previous-line)
6002 (define-key km [up] 'previous-line)
6003 (define-key km "C" 'org-export-stack-clear)
6004 (define-key km "v" 'org-export-stack-view)
6005 (define-key km (kbd "RET") 'org-export-stack-view)
6006 (define-key km "d" 'org-export-stack-remove)
6008 "Keymap for Org Export Stack.")
6010 (define-derived-mode org-export-stack-mode special-mode "Org-Stack"
6011 "Mode for displaying asynchronous export stack.
6013 Type \\[org-export-stack] to visualize the asynchronous export
6014 stack.
6016 In an Org Export Stack buffer, use \\<org-export-stack-mode-map>\\[org-export-stack-view] to view export output
6017 on current line, \\[org-export-stack-remove] to remove it from the stack and \\[org-export-stack-clear] to clear
6018 stack completely.
6020 Removing entries in an Org Export Stack buffer doesn't affect
6021 files or buffers, only the display.
6023 \\{org-export-stack-mode-map}"
6024 (abbrev-mode 0)
6025 (auto-fill-mode 0)
6026 (setq buffer-read-only t
6027 buffer-undo-list t
6028 truncate-lines t
6029 header-line-format
6030 '(:eval
6031 (format " %-12s | %6s | %s" "Back-End" "Age" "Source")))
6032 (org-add-hook 'post-command-hook 'org-export-stack-refresh nil t)
6033 (set (make-local-variable 'revert-buffer-function)
6034 'org-export-stack-refresh))
6038 ;;; The Dispatcher
6040 ;; `org-export-dispatch' is the standard interactive way to start an
6041 ;; export process. It uses `org-export--dispatch-ui' as a subroutine
6042 ;; for its interface, which, in turn, delegates response to key
6043 ;; pressed to `org-export--dispatch-action'.
6045 ;;;###autoload
6046 (defun org-export-dispatch (&optional arg)
6047 "Export dispatcher for Org mode.
6049 It provides an access to common export related tasks in a buffer.
6050 Its interface comes in two flavors: standard and expert.
6052 While both share the same set of bindings, only the former
6053 displays the valid keys associations in a dedicated buffer.
6054 Scrolling (resp. line-wise motion) in this buffer is done with
6055 SPC and DEL (resp. C-n and C-p) keys.
6057 Set variable `org-export-dispatch-use-expert-ui' to switch to one
6058 flavor or the other.
6060 When ARG is \\[universal-argument], repeat the last export action, with the same set
6061 of options used back then, on the current buffer.
6063 When ARG is \\[universal-argument] \\[universal-argument], display the asynchronous export stack."
6064 (interactive "P")
6065 (let* ((input
6066 (cond ((equal arg '(16)) '(stack))
6067 ((and arg org-export-dispatch-last-action))
6068 (t (save-window-excursion
6069 (unwind-protect
6070 (progn
6071 ;; Remember where we are
6072 (move-marker org-export-dispatch-last-position
6073 (point)
6074 (org-base-buffer (current-buffer)))
6075 ;; Get and store an export command
6076 (setq org-export-dispatch-last-action
6077 (org-export--dispatch-ui
6078 (list org-export-initial-scope
6079 (and org-export-in-background 'async))
6081 org-export-dispatch-use-expert-ui)))
6082 (and (get-buffer "*Org Export Dispatcher*")
6083 (kill-buffer "*Org Export Dispatcher*")))))))
6084 (action (car input))
6085 (optns (cdr input)))
6086 (unless (memq 'subtree optns)
6087 (move-marker org-export-dispatch-last-position nil))
6088 (case action
6089 ;; First handle special hard-coded actions.
6090 (template (org-export-insert-default-template nil optns))
6091 (stack (org-export-stack))
6092 (publish-current-file
6093 (org-publish-current-file (memq 'force optns) (memq 'async optns)))
6094 (publish-current-project
6095 (org-publish-current-project (memq 'force optns) (memq 'async optns)))
6096 (publish-choose-project
6097 (org-publish (assoc (org-icompleting-read
6098 "Publish project: "
6099 org-publish-project-alist nil t)
6100 org-publish-project-alist)
6101 (memq 'force optns)
6102 (memq 'async optns)))
6103 (publish-all (org-publish-all (memq 'force optns) (memq 'async optns)))
6104 (otherwise
6105 (save-excursion
6106 (when arg
6107 ;; Repeating command, maybe move cursor to restore subtree
6108 ;; context.
6109 (if (eq (marker-buffer org-export-dispatch-last-position)
6110 (org-base-buffer (current-buffer)))
6111 (goto-char org-export-dispatch-last-position)
6112 ;; We are in a different buffer, forget position.
6113 (move-marker org-export-dispatch-last-position nil)))
6114 (funcall action
6115 ;; Return a symbol instead of a list to ease
6116 ;; asynchronous export macro use.
6117 (and (memq 'async optns) t)
6118 (and (memq 'subtree optns) t)
6119 (and (memq 'visible optns) t)
6120 (and (memq 'body optns) t)))))))
6122 (defun org-export--dispatch-ui (options first-key expertp)
6123 "Handle interface for `org-export-dispatch'.
6125 OPTIONS is a list containing current interactive options set for
6126 export. It can contain any of the following symbols:
6127 `body' toggles a body-only export
6128 `subtree' restricts export to current subtree
6129 `visible' restricts export to visible part of buffer.
6130 `force' force publishing files.
6131 `async' use asynchronous export process
6133 FIRST-KEY is the key pressed to select the first level menu. It
6134 is nil when this menu hasn't been selected yet.
6136 EXPERTP, when non-nil, triggers expert UI. In that case, no help
6137 buffer is provided, but indications about currently active
6138 options are given in the prompt. Moreover, \[?] allows to switch
6139 back to standard interface."
6140 (let* ((fontify-key
6141 (lambda (key &optional access-key)
6142 ;; Fontify KEY string. Optional argument ACCESS-KEY, when
6143 ;; non-nil is the required first-level key to activate
6144 ;; KEY. When its value is t, activate KEY independently
6145 ;; on the first key, if any. A nil value means KEY will
6146 ;; only be activated at first level.
6147 (if (or (eq access-key t) (eq access-key first-key))
6148 (org-propertize key 'face 'org-warning)
6149 key)))
6150 (fontify-value
6151 (lambda (value)
6152 ;; Fontify VALUE string.
6153 (org-propertize value 'face 'font-lock-variable-name-face)))
6154 ;; Prepare menu entries by extracting them from registered
6155 ;; back-ends and sorting them by access key and by ordinal,
6156 ;; if any.
6157 (entries
6158 (sort (sort (delq nil
6159 (mapcar #'org-export-backend-menu
6160 org-export-registered-backends))
6161 (lambda (a b)
6162 (let ((key-a (nth 1 a))
6163 (key-b (nth 1 b)))
6164 (cond ((and (numberp key-a) (numberp key-b))
6165 (< key-a key-b))
6166 ((numberp key-b) t)))))
6167 'car-less-than-car))
6168 ;; Compute a list of allowed keys based on the first key
6169 ;; pressed, if any. Some keys
6170 ;; (?^B, ?^V, ?^S, ?^F, ?^A, ?&, ?# and ?q) are always
6171 ;; available.
6172 (allowed-keys
6173 (nconc (list 2 22 19 6 1)
6174 (if (not first-key) (org-uniquify (mapcar 'car entries))
6175 (let (sub-menu)
6176 (dolist (entry entries (sort (mapcar 'car sub-menu) '<))
6177 (when (eq (car entry) first-key)
6178 (setq sub-menu (append (nth 2 entry) sub-menu))))))
6179 (cond ((eq first-key ?P) (list ?f ?p ?x ?a))
6180 ((not first-key) (list ?P)))
6181 (list ?& ?#)
6182 (when expertp (list ??))
6183 (list ?q)))
6184 ;; Build the help menu for standard UI.
6185 (help
6186 (unless expertp
6187 (concat
6188 ;; Options are hard-coded.
6189 (format "[%s] Body only: %s [%s] Visible only: %s
6190 \[%s] Export scope: %s [%s] Force publishing: %s
6191 \[%s] Async export: %s\n\n"
6192 (funcall fontify-key "C-b" t)
6193 (funcall fontify-value
6194 (if (memq 'body options) "On " "Off"))
6195 (funcall fontify-key "C-v" t)
6196 (funcall fontify-value
6197 (if (memq 'visible options) "On " "Off"))
6198 (funcall fontify-key "C-s" t)
6199 (funcall fontify-value
6200 (if (memq 'subtree options) "Subtree" "Buffer "))
6201 (funcall fontify-key "C-f" t)
6202 (funcall fontify-value
6203 (if (memq 'force options) "On " "Off"))
6204 (funcall fontify-key "C-a" t)
6205 (funcall fontify-value
6206 (if (memq 'async options) "On " "Off")))
6207 ;; Display registered back-end entries. When a key
6208 ;; appears for the second time, do not create another
6209 ;; entry, but append its sub-menu to existing menu.
6210 (let (last-key)
6211 (mapconcat
6212 (lambda (entry)
6213 (let ((top-key (car entry)))
6214 (concat
6215 (unless (eq top-key last-key)
6216 (setq last-key top-key)
6217 (format "\n[%s] %s\n"
6218 (funcall fontify-key (char-to-string top-key))
6219 (nth 1 entry)))
6220 (let ((sub-menu (nth 2 entry)))
6221 (unless (functionp sub-menu)
6222 ;; Split sub-menu into two columns.
6223 (let ((index -1))
6224 (concat
6225 (mapconcat
6226 (lambda (sub-entry)
6227 (incf index)
6228 (format
6229 (if (zerop (mod index 2)) " [%s] %-26s"
6230 "[%s] %s\n")
6231 (funcall fontify-key
6232 (char-to-string (car sub-entry))
6233 top-key)
6234 (nth 1 sub-entry)))
6235 sub-menu "")
6236 (when (zerop (mod index 2)) "\n"))))))))
6237 entries ""))
6238 ;; Publishing menu is hard-coded.
6239 (format "\n[%s] Publish
6240 [%s] Current file [%s] Current project
6241 [%s] Choose project [%s] All projects\n\n\n"
6242 (funcall fontify-key "P")
6243 (funcall fontify-key "f" ?P)
6244 (funcall fontify-key "p" ?P)
6245 (funcall fontify-key "x" ?P)
6246 (funcall fontify-key "a" ?P))
6247 (format "[%s] Export stack [%s] Insert template\n"
6248 (funcall fontify-key "&" t)
6249 (funcall fontify-key "#" t))
6250 (format "[%s] %s"
6251 (funcall fontify-key "q" t)
6252 (if first-key "Main menu" "Exit")))))
6253 ;; Build prompts for both standard and expert UI.
6254 (standard-prompt (unless expertp "Export command: "))
6255 (expert-prompt
6256 (when expertp
6257 (format
6258 "Export command (C-%s%s%s%s%s) [%s]: "
6259 (if (memq 'body options) (funcall fontify-key "b" t) "b")
6260 (if (memq 'visible options) (funcall fontify-key "v" t) "v")
6261 (if (memq 'subtree options) (funcall fontify-key "s" t) "s")
6262 (if (memq 'force options) (funcall fontify-key "f" t) "f")
6263 (if (memq 'async options) (funcall fontify-key "a" t) "a")
6264 (mapconcat (lambda (k)
6265 ;; Strip control characters.
6266 (unless (< k 27) (char-to-string k)))
6267 allowed-keys "")))))
6268 ;; With expert UI, just read key with a fancy prompt. In standard
6269 ;; UI, display an intrusive help buffer.
6270 (if expertp
6271 (org-export--dispatch-action
6272 expert-prompt allowed-keys entries options first-key expertp)
6273 ;; At first call, create frame layout in order to display menu.
6274 (unless (get-buffer "*Org Export Dispatcher*")
6275 (delete-other-windows)
6276 (org-switch-to-buffer-other-window
6277 (get-buffer-create "*Org Export Dispatcher*"))
6278 (setq cursor-type nil
6279 header-line-format "Use SPC, DEL, C-n or C-p to navigate.")
6280 ;; Make sure that invisible cursor will not highlight square
6281 ;; brackets.
6282 (set-syntax-table (copy-syntax-table))
6283 (modify-syntax-entry ?\[ "w"))
6284 ;; At this point, the buffer containing the menu exists and is
6285 ;; visible in the current window. So, refresh it.
6286 (with-current-buffer "*Org Export Dispatcher*"
6287 ;; Refresh help. Maintain display continuity by re-visiting
6288 ;; previous window position.
6289 (let ((pos (window-start)))
6290 (erase-buffer)
6291 (insert help)
6292 (set-window-start nil pos)))
6293 (org-fit-window-to-buffer)
6294 (org-export--dispatch-action
6295 standard-prompt allowed-keys entries options first-key expertp))))
6297 (defun org-export--dispatch-action
6298 (prompt allowed-keys entries options first-key expertp)
6299 "Read a character from command input and act accordingly.
6301 PROMPT is the displayed prompt, as a string. ALLOWED-KEYS is
6302 a list of characters available at a given step in the process.
6303 ENTRIES is a list of menu entries. OPTIONS, FIRST-KEY and
6304 EXPERTP are the same as defined in `org-export--dispatch-ui',
6305 which see.
6307 Toggle export options when required. Otherwise, return value is
6308 a list with action as CAR and a list of interactive export
6309 options as CDR."
6310 (let (key)
6311 ;; Scrolling: when in non-expert mode, act on motion keys (C-n,
6312 ;; C-p, SPC, DEL).
6313 (while (and (setq key (read-char-exclusive prompt))
6314 (not expertp)
6315 (memq key '(14 16 ?\s ?\d)))
6316 (case key
6317 (14 (if (not (pos-visible-in-window-p (point-max)))
6318 (ignore-errors (scroll-up 1))
6319 (message "End of buffer")
6320 (sit-for 1)))
6321 (16 (if (not (pos-visible-in-window-p (point-min)))
6322 (ignore-errors (scroll-down 1))
6323 (message "Beginning of buffer")
6324 (sit-for 1)))
6325 (?\s (if (not (pos-visible-in-window-p (point-max)))
6326 (scroll-up nil)
6327 (message "End of buffer")
6328 (sit-for 1)))
6329 (?\d (if (not (pos-visible-in-window-p (point-min)))
6330 (scroll-down nil)
6331 (message "Beginning of buffer")
6332 (sit-for 1)))))
6333 (cond
6334 ;; Ignore undefined associations.
6335 ((not (memq key allowed-keys))
6336 (ding)
6337 (unless expertp (message "Invalid key") (sit-for 1))
6338 (org-export--dispatch-ui options first-key expertp))
6339 ;; q key at first level aborts export. At second level, cancel
6340 ;; first key instead.
6341 ((eq key ?q) (if (not first-key) (error "Export aborted")
6342 (org-export--dispatch-ui options nil expertp)))
6343 ;; Help key: Switch back to standard interface if expert UI was
6344 ;; active.
6345 ((eq key ??) (org-export--dispatch-ui options first-key nil))
6346 ;; Send request for template insertion along with export scope.
6347 ((eq key ?#) (cons 'template (memq 'subtree options)))
6348 ;; Switch to asynchronous export stack.
6349 ((eq key ?&) '(stack))
6350 ;; Toggle options: C-b (2) C-v (22) C-s (19) C-f (6) C-a (1).
6351 ((memq key '(2 22 19 6 1))
6352 (org-export--dispatch-ui
6353 (let ((option (case key (2 'body) (22 'visible) (19 'subtree)
6354 (6 'force) (1 'async))))
6355 (if (memq option options) (remq option options)
6356 (cons option options)))
6357 first-key expertp))
6358 ;; Action selected: Send key and options back to
6359 ;; `org-export-dispatch'.
6360 ((or first-key (functionp (nth 2 (assq key entries))))
6361 (cons (cond
6362 ((not first-key) (nth 2 (assq key entries)))
6363 ;; Publishing actions are hard-coded. Send a special
6364 ;; signal to `org-export-dispatch'.
6365 ((eq first-key ?P)
6366 (case key
6367 (?f 'publish-current-file)
6368 (?p 'publish-current-project)
6369 (?x 'publish-choose-project)
6370 (?a 'publish-all)))
6371 ;; Return first action associated to FIRST-KEY + KEY
6372 ;; path. Indeed, derived backends can share the same
6373 ;; FIRST-KEY.
6374 (t (catch 'found
6375 (mapc (lambda (entry)
6376 (let ((match (assq key (nth 2 entry))))
6377 (when match (throw 'found (nth 2 match)))))
6378 (member (assq first-key entries) entries)))))
6379 options))
6380 ;; Otherwise, enter sub-menu.
6381 (t (org-export--dispatch-ui options key expertp)))))
6385 (provide 'ox)
6387 ;; Local variables:
6388 ;; generated-autoload-file: "org-loaddefs.el"
6389 ;; End:
6391 ;;; ox.el ends here