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