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