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