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