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