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