ox: Title fallbacks to nil instead of file name
[org-mode.git] / lisp / ox.el
blobd47c2e69a021027401ae3317d70f14bc19407566
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 ;; + `:parse-tree' :: Whole parse tree, available at any time during
1356 ;; transcoding.
1357 ;; - category :: option
1358 ;; - type :: list (as returned by `org-element-parse-buffer')
1360 ;; + `:preserve-breaks' :: Non-nil means transcoding should preserve
1361 ;; all line breaks.
1362 ;; - category :: option
1363 ;; - type :: symbol (nil, t)
1365 ;; + `:section-numbers' :: Non-nil means transcoding should add
1366 ;; section numbers to headlines.
1367 ;; - category :: option
1368 ;; - type :: symbol (nil, t)
1370 ;; + `:select-tags' :: List of tags enforcing inclusion of sub-trees
1371 ;; in transcoding. When such a tag is present, subtrees without
1372 ;; it are de facto excluded from the process. See
1373 ;; `use-select-tags'.
1374 ;; - category :: option
1375 ;; - type :: list of strings
1377 ;; + `:time-stamp-file' :: Non-nil means transcoding should insert
1378 ;; a time stamp in the output.
1379 ;; - category :: option
1380 ;; - type :: symbol (nil, t)
1382 ;; + `:translate-alist' :: Alist between element and object types and
1383 ;; transcoding functions relative to the current back-end.
1384 ;; Special keys `inner-template', `template' and `plain-text' are
1385 ;; also possible.
1386 ;; - category :: option
1387 ;; - type :: alist (SYMBOL . FUNCTION)
1389 ;; + `:with-archived-trees' :: Non-nil when archived subtrees should
1390 ;; also be transcoded. If it is set to the `headline' symbol,
1391 ;; only the archived headline's name is retained.
1392 ;; - category :: option
1393 ;; - type :: symbol (nil, t, `headline')
1395 ;; + `:with-author' :: Non-nil means author's name should be included
1396 ;; in the output.
1397 ;; - category :: option
1398 ;; - type :: symbol (nil, t)
1400 ;; + `:with-clocks' :: Non-nil means clock keywords should be exported.
1401 ;; - category :: option
1402 ;; - type :: symbol (nil, t)
1404 ;; + `:with-creator' :: Non-nil means a creation sentence should be
1405 ;; inserted at the end of the transcoded string. If the value
1406 ;; is `comment', it should be commented.
1407 ;; - category :: option
1408 ;; - type :: symbol (`comment', nil, t)
1410 ;; + `:with-date' :: Non-nil means output should contain a date.
1411 ;; - category :: option
1412 ;; - type :. symbol (nil, t)
1414 ;; + `:with-drawers' :: Non-nil means drawers should be exported. If
1415 ;; its value is a list of names, only drawers with such names
1416 ;; will be transcoded. If that list starts with `not', drawer
1417 ;; with these names will be skipped.
1418 ;; - category :: option
1419 ;; - type :: symbol (nil, t) or list of strings
1421 ;; + `:with-email' :: Non-nil means output should contain author's
1422 ;; email.
1423 ;; - category :: option
1424 ;; - type :: symbol (nil, t)
1426 ;; + `:with-emphasize' :: Non-nil means emphasized text should be
1427 ;; interpreted.
1428 ;; - category :: option
1429 ;; - type :: symbol (nil, t)
1431 ;; + `:with-fixed-width' :: Non-nil if transcoder should export
1432 ;; strings starting with a colon as a fixed-with (verbatim) area.
1433 ;; - category :: option
1434 ;; - type :: symbol (nil, t)
1436 ;; + `:with-footnotes' :: Non-nil if transcoder should interpret
1437 ;; footnotes.
1438 ;; - category :: option
1439 ;; - type :: symbol (nil, t)
1441 ;; + `:with-latex' :: Non-nil means `latex-environment' elements and
1442 ;; `latex-fragment' objects should appear in export output. When
1443 ;; this property is set to `verbatim', they will be left as-is.
1444 ;; - category :: option
1445 ;; - type :: symbol (`verbatim', nil, t)
1447 ;; + `:with-planning' :: Non-nil means transcoding should include
1448 ;; planning info.
1449 ;; - category :: option
1450 ;; - type :: symbol (nil, t)
1452 ;; + `:with-priority' :: Non-nil means transcoding should include
1453 ;; priority cookies.
1454 ;; - category :: option
1455 ;; - type :: symbol (nil, t)
1457 ;; + `:with-smart-quotes' :: Non-nil means activate smart quotes in
1458 ;; plain text.
1459 ;; - category :: option
1460 ;; - type :: symbol (nil, t)
1462 ;; + `:with-special-strings' :: Non-nil means transcoding should
1463 ;; interpret special strings in plain text.
1464 ;; - category :: option
1465 ;; - type :: symbol (nil, t)
1467 ;; + `:with-sub-superscript' :: Non-nil means transcoding should
1468 ;; interpret subscript and superscript. With a value of "{}",
1469 ;; only interpret those using curly brackets.
1470 ;; - category :: option
1471 ;; - type :: symbol (nil, {}, t)
1473 ;; + `:with-tables' :: Non-nil means transcoding should export tables.
1474 ;; - category :: option
1475 ;; - type :: symbol (nil, t)
1477 ;; + `:with-tags' :: Non-nil means transcoding should keep tags in
1478 ;; headlines. A `not-in-toc' value will remove them from the
1479 ;; table of contents, if any, nonetheless.
1480 ;; - category :: option
1481 ;; - type :: symbol (nil, t, `not-in-toc')
1483 ;; + `:with-tasks' :: Non-nil means transcoding should include
1484 ;; headlines with a TODO keyword. A `todo' value will only
1485 ;; include headlines with a todo type keyword while a `done'
1486 ;; value will do the contrary. If a list of strings is provided,
1487 ;; only tasks with keywords belonging to that list will be kept.
1488 ;; - category :: option
1489 ;; - type :: symbol (t, todo, done, nil) or list of strings
1491 ;; + `:with-timestamps' :: Non-nil means transcoding should include
1492 ;; time stamps. Special value `active' (resp. `inactive') ask to
1493 ;; export only active (resp. inactive) timestamps. Otherwise,
1494 ;; completely remove them.
1495 ;; - category :: option
1496 ;; - type :: symbol: (`active', `inactive', t, nil)
1498 ;; + `:with-toc' :: Non-nil means that a table of contents has to be
1499 ;; added to the output. An integer value limits its depth.
1500 ;; - category :: option
1501 ;; - type :: symbol (nil, t or integer)
1503 ;; + `:with-todo-keywords' :: Non-nil means transcoding should
1504 ;; include TODO keywords.
1505 ;; - category :: option
1506 ;; - type :: symbol (nil, t)
1509 ;;;; Environment Options
1511 ;; Environment options encompass all parameters defined outside the
1512 ;; scope of the parsed data. They come from five sources, in
1513 ;; increasing precedence order:
1515 ;; - Global variables,
1516 ;; - Buffer's attributes,
1517 ;; - Options keyword symbols,
1518 ;; - Buffer keywords,
1519 ;; - Subtree properties.
1521 ;; The central internal function with regards to environment options
1522 ;; is `org-export-get-environment'. It updates global variables with
1523 ;; "#+BIND:" keywords, then retrieve and prioritize properties from
1524 ;; the different sources.
1526 ;; The internal functions doing the retrieval are:
1527 ;; `org-export--get-global-options',
1528 ;; `org-export--get-buffer-attributes',
1529 ;; `org-export--parse-option-keyword',
1530 ;; `org-export--get-subtree-options' and
1531 ;; `org-export--get-inbuffer-options'
1533 ;; Also, `org-export--list-bound-variables' collects bound variables
1534 ;; along with their value in order to set them as buffer local
1535 ;; variables later in the process.
1537 (defun org-export-get-environment (&optional backend subtreep ext-plist)
1538 "Collect export options from the current buffer.
1540 Optional argument BACKEND is an export back-end, as returned by
1541 `org-export-create-backend'.
1543 When optional argument SUBTREEP is non-nil, assume the export is
1544 done against the current sub-tree.
1546 Third optional argument EXT-PLIST is a property list with
1547 external parameters overriding Org default settings, but still
1548 inferior to file-local settings."
1549 ;; First install #+BIND variables since these must be set before
1550 ;; global options are read.
1551 (dolist (pair (org-export--list-bound-variables))
1552 (org-set-local (car pair) (nth 1 pair)))
1553 ;; Get and prioritize export options...
1554 (org-combine-plists
1555 ;; ... from global variables...
1556 (org-export--get-global-options backend)
1557 ;; ... from an external property list...
1558 ext-plist
1559 ;; ... from in-buffer settings...
1560 (org-export--get-inbuffer-options backend)
1561 ;; ... and from subtree, when appropriate.
1562 (and subtreep (org-export--get-subtree-options backend))
1563 ;; Eventually add misc. properties.
1564 (list
1565 :back-end
1566 backend
1567 :translate-alist (org-export-get-all-transcoders backend)
1568 :footnote-definition-alist
1569 ;; Footnotes definitions must be collected in the original
1570 ;; buffer, as there's no insurance that they will still be in
1571 ;; the parse tree, due to possible narrowing.
1572 (let (alist)
1573 (org-with-wide-buffer
1574 (goto-char (point-min))
1575 (while (re-search-forward org-footnote-re nil t)
1576 (backward-char)
1577 (let ((fn (save-match-data (org-element-context))))
1578 (case (org-element-type fn)
1579 (footnote-definition
1580 (push
1581 (cons (org-element-property :label fn)
1582 (let ((cbeg (org-element-property :contents-begin fn)))
1583 (when cbeg
1584 (org-element--parse-elements
1585 cbeg (org-element-property :contents-end fn)
1586 nil nil nil nil (list 'org-data nil)))))
1587 alist))
1588 (footnote-reference
1589 (let ((label (org-element-property :label fn))
1590 (cbeg (org-element-property :contents-begin fn)))
1591 (when (and label cbeg
1592 (eq (org-element-property :type fn) 'inline))
1593 (push
1594 (cons label
1595 (org-element-parse-secondary-string
1596 (buffer-substring
1597 cbeg (org-element-property :contents-end fn))
1598 (org-element-restriction 'footnote-reference)))
1599 alist)))))))
1600 alist))
1601 :id-alist
1602 ;; Collect id references.
1603 (let (alist)
1604 (org-with-wide-buffer
1605 (goto-char (point-min))
1606 (while (re-search-forward "\\[\\[id:\\S-+?\\]" nil t)
1607 (let ((link (org-element-context)))
1608 (when (eq (org-element-type link) 'link)
1609 (let* ((id (org-element-property :path link))
1610 (file (org-id-find-id-file id)))
1611 (when file
1612 (push (cons id (file-relative-name file)) alist)))))))
1613 alist))))
1615 (defun org-export--parse-option-keyword (options &optional backend)
1616 "Parse an OPTIONS line and return values as a plist.
1617 Optional argument BACKEND is an export back-end, as returned by,
1618 e.g., `org-export-create-backend'. It specifies which back-end
1619 specific items to read, if any."
1620 (let* ((all
1621 ;; Priority is given to back-end specific options.
1622 (append (and backend (org-export-get-all-options backend))
1623 org-export-options-alist))
1624 plist)
1625 (dolist (option all)
1626 (let ((property (car option))
1627 (item (nth 2 option)))
1628 (when (and item
1629 (not (plist-member plist property))
1630 (string-match (concat "\\(\\`\\|[ \t]\\)"
1631 (regexp-quote item)
1632 ":\\(([^)\n]+)\\|[^ \t\n\r;,.]*\\)")
1633 options))
1634 (setq plist (plist-put plist
1635 property
1636 (car (read-from-string
1637 (match-string 2 options))))))))
1638 plist))
1640 (defun org-export--get-subtree-options (&optional backend)
1641 "Get export options in subtree at point.
1642 Optional argument BACKEND is an export back-end, as returned by,
1643 e.g., `org-export-create-backend'. It specifies back-end used
1644 for export. Return options as a plist."
1645 ;; For each buffer keyword, create a headline property setting the
1646 ;; same property in communication channel. The name for the property
1647 ;; is the keyword with "EXPORT_" appended to it.
1648 (org-with-wide-buffer
1649 (let (prop plist)
1650 ;; Make sure point is at a heading.
1651 (if (org-at-heading-p) (org-up-heading-safe) (org-back-to-heading t))
1652 ;; Take care of EXPORT_TITLE. If it isn't defined, use headline's
1653 ;; title (with no todo keyword, priority cookie or tag) as its
1654 ;; fallback value.
1655 (when (setq prop (or (org-entry-get (point) "EXPORT_TITLE")
1656 (progn (looking-at org-complex-heading-regexp)
1657 (org-match-string-no-properties 4))))
1658 (setq plist
1659 (plist-put
1660 plist :title
1661 (org-element-parse-secondary-string
1662 prop (org-element-restriction 'keyword)))))
1663 ;; EXPORT_OPTIONS are parsed in a non-standard way.
1664 (when (setq prop (org-entry-get (point) "EXPORT_OPTIONS"))
1665 (setq plist
1666 (nconc plist (org-export--parse-option-keyword prop backend))))
1667 ;; Handle other keywords. TITLE keyword is excluded as it has
1668 ;; been handled already.
1669 (let ((seen '("TITLE")))
1670 (mapc
1671 (lambda (option)
1672 (let ((property (car option))
1673 (keyword (nth 1 option)))
1674 (when (and keyword (not (member keyword seen)))
1675 (let* ((subtree-prop (concat "EXPORT_" keyword))
1676 ;; Export properties are not case-sensitive.
1677 (value (let ((case-fold-search t))
1678 (org-entry-get (point) subtree-prop))))
1679 (push keyword seen)
1680 (when (and value (not (plist-member plist property)))
1681 (setq plist
1682 (plist-put
1683 plist
1684 property
1685 (cond
1686 ;; Parse VALUE if required.
1687 ((member keyword org-element-document-properties)
1688 (org-element-parse-secondary-string
1689 value (org-element-restriction 'keyword)))
1690 ;; If BEHAVIOR is `split' expected value is
1691 ;; a list of strings, not a string.
1692 ((eq (nth 4 option) 'split) (org-split-string value))
1693 (t value)))))))))
1694 ;; Look for both general keywords and back-end specific
1695 ;; options, with priority given to the latter.
1696 (append (and backend (org-export-get-all-options backend))
1697 org-export-options-alist)))
1698 ;; Return value.
1699 plist)))
1701 (defun org-export--get-inbuffer-options (&optional backend)
1702 "Return current buffer export options, as a plist.
1704 Optional argument BACKEND, when non-nil, is an export back-end,
1705 as returned by, e.g., `org-export-create-backend'. It specifies
1706 which back-end specific options should also be read in the
1707 process.
1709 Assume buffer is in Org mode. Narrowing, if any, is ignored."
1710 (let* (plist
1711 get-options ; For byte-compiler.
1712 (case-fold-search t)
1713 (options (append
1714 ;; Priority is given to back-end specific options.
1715 (and backend (org-export-get-all-options backend))
1716 org-export-options-alist))
1717 (regexp (format "^[ \t]*#\\+%s:"
1718 (regexp-opt (nconc (delq nil (mapcar 'cadr options))
1719 org-export-special-keywords))))
1720 (find-properties
1721 (lambda (keyword)
1722 ;; Return all properties associated to KEYWORD.
1723 (let (properties)
1724 (dolist (option options properties)
1725 (when (equal (nth 1 option) keyword)
1726 (pushnew (car option) properties))))))
1727 (get-options
1728 (lambda (&optional files plist)
1729 ;; Recursively read keywords in buffer. FILES is a list
1730 ;; of files read so far. PLIST is the current property
1731 ;; list obtained.
1732 (org-with-wide-buffer
1733 (goto-char (point-min))
1734 (while (re-search-forward regexp nil t)
1735 (let ((element (org-element-at-point)))
1736 (when (eq (org-element-type element) 'keyword)
1737 (let ((key (org-element-property :key element))
1738 (val (org-element-property :value element)))
1739 (cond
1740 ;; Options in `org-export-special-keywords'.
1741 ((equal key "SETUPFILE")
1742 (let ((file (expand-file-name
1743 (org-remove-double-quotes (org-trim val)))))
1744 ;; Avoid circular dependencies.
1745 (unless (member file files)
1746 (with-temp-buffer
1747 (insert (org-file-contents file 'noerror))
1748 (let ((org-inhibit-startup t)) (org-mode))
1749 (setq plist (funcall get-options
1750 (cons file files) plist))))))
1751 ((equal key "OPTIONS")
1752 (setq plist
1753 (org-combine-plists
1754 plist
1755 (org-export--parse-option-keyword val backend))))
1756 ((equal key "FILETAGS")
1757 (setq plist
1758 (org-combine-plists
1759 plist
1760 (list :filetags
1761 (org-uniquify
1762 (append (org-split-string val ":")
1763 (plist-get plist :filetags)))))))
1765 ;; Options in `org-export-options-alist'.
1766 (dolist (property (funcall find-properties key))
1767 (let ((behaviour (nth 4 (assq property options))))
1768 (setq plist
1769 (plist-put
1770 plist property
1771 ;; Handle value depending on specified
1772 ;; BEHAVIOR.
1773 (case behaviour
1774 (space
1775 (if (not (plist-get plist property))
1776 (org-trim val)
1777 (concat (plist-get plist property)
1779 (org-trim val))))
1780 (newline
1781 (org-trim
1782 (concat (plist-get plist property)
1783 "\n"
1784 (org-trim val))))
1785 (split `(,@(plist-get plist property)
1786 ,@(org-split-string val)))
1787 ('t val)
1788 (otherwise
1789 (if (not (plist-member plist property)) val
1790 (plist-get plist property))))))))))))))
1791 ;; Return final value.
1792 plist))))
1793 ;; Read options in the current buffer.
1794 (setq plist (funcall get-options
1795 (and buffer-file-name (list buffer-file-name)) nil))
1796 ;; Parse keywords specified in `org-element-document-properties'
1797 ;; and return PLIST.
1798 (dolist (keyword org-element-document-properties plist)
1799 (dolist (property (funcall find-properties keyword))
1800 (let ((value (plist-get plist property)))
1801 (when (stringp value)
1802 (setq plist
1803 (plist-put plist property
1804 (org-element-parse-secondary-string
1805 value (org-element-restriction 'keyword))))))))))
1807 (defun org-export--get-buffer-attributes ()
1808 "Return properties related to buffer attributes, as a plist."
1809 ;; Store full path of input file name, or nil. For internal use.
1810 (list :input-file (buffer-file-name (buffer-base-buffer))))
1812 (defun org-export--get-global-options (&optional backend)
1813 "Return global export options as a plist.
1814 Optional argument BACKEND, if non-nil, is an export back-end, as
1815 returned by, e.g., `org-export-create-backend'. It specifies
1816 which back-end specific export options should also be read in the
1817 process."
1818 (let (plist
1819 ;; Priority is given to back-end specific options.
1820 (all (append (and backend (org-export-get-all-options backend))
1821 org-export-options-alist)))
1822 (dolist (cell all plist)
1823 (let ((prop (car cell)))
1824 (unless (plist-member plist prop)
1825 (setq plist
1826 (plist-put
1827 plist
1828 prop
1829 ;; Evaluate default value provided. If keyword is
1830 ;; a member of `org-element-document-properties',
1831 ;; parse it as a secondary string before storing it.
1832 (let ((value (eval (nth 3 cell))))
1833 (if (and (stringp value)
1834 (member (nth 1 cell)
1835 org-element-document-properties))
1836 (org-element-parse-secondary-string
1837 value (org-element-restriction 'keyword))
1838 value)))))))))
1840 (defun org-export--list-bound-variables ()
1841 "Return variables bound from BIND keywords in current buffer.
1842 Also look for BIND keywords in setup files. The return value is
1843 an alist where associations are (VARIABLE-NAME VALUE)."
1844 (when org-export-allow-bind-keywords
1845 (let* (collect-bind ; For byte-compiler.
1846 (collect-bind
1847 (lambda (files alist)
1848 ;; Return an alist between variable names and their
1849 ;; value. FILES is a list of setup files names read so
1850 ;; far, used to avoid circular dependencies. ALIST is
1851 ;; the alist collected so far.
1852 (let ((case-fold-search t))
1853 (org-with-wide-buffer
1854 (goto-char (point-min))
1855 (while (re-search-forward
1856 "^[ \t]*#\\+\\(BIND\\|SETUPFILE\\):" nil t)
1857 (let ((element (org-element-at-point)))
1858 (when (eq (org-element-type element) 'keyword)
1859 (let ((val (org-element-property :value element)))
1860 (if (equal (org-element-property :key element) "BIND")
1861 (push (read (format "(%s)" val)) alist)
1862 ;; Enter setup file.
1863 (let ((file (expand-file-name
1864 (org-remove-double-quotes val))))
1865 (unless (member file files)
1866 (with-temp-buffer
1867 (let ((org-inhibit-startup t)) (org-mode))
1868 (insert (org-file-contents file 'noerror))
1869 (setq alist
1870 (funcall collect-bind
1871 (cons file files)
1872 alist))))))))))
1873 alist)))))
1874 ;; Return value in appropriate order of appearance.
1875 (nreverse (funcall collect-bind nil nil)))))
1877 ;; defsubst org-export-get-parent must be defined before first use,
1878 ;; was originally defined in the topology section
1880 (defsubst org-export-get-parent (blob)
1881 "Return BLOB parent or nil.
1882 BLOB is the element or object considered."
1883 (org-element-property :parent blob))
1885 ;;;; Tree Properties
1887 ;; Tree properties are information extracted from parse tree. They
1888 ;; are initialized at the beginning of the transcoding process by
1889 ;; `org-export-collect-tree-properties'.
1891 ;; Dedicated functions focus on computing the value of specific tree
1892 ;; properties during initialization. Thus,
1893 ;; `org-export--populate-ignore-list' lists elements and objects that
1894 ;; should be skipped during export, `org-export--get-min-level' gets
1895 ;; the minimal exportable level, used as a basis to compute relative
1896 ;; level for headlines. Eventually
1897 ;; `org-export--collect-headline-numbering' builds an alist between
1898 ;; headlines and their numbering.
1900 (defun org-export-collect-tree-properties (data info)
1901 "Extract tree properties from parse tree.
1903 DATA is the parse tree from which information is retrieved. INFO
1904 is a list holding export options.
1906 Following tree properties are set or updated:
1908 `:exported-data' Hash table used to memoize results from
1909 `org-export-data'.
1911 `:footnote-definition-alist' List of footnotes definitions in
1912 original buffer and current parse tree.
1914 `:headline-offset' Offset between true level of headlines and
1915 local level. An offset of -1 means a headline
1916 of level 2 should be considered as a level
1917 1 headline in the context.
1919 `:headline-numbering' Alist of all headlines as key an the
1920 associated numbering as value.
1922 `:ignore-list' List of elements that should be ignored during
1923 export.
1925 Return updated plist."
1926 ;; Install the parse tree in the communication channel, in order to
1927 ;; use `org-export-get-genealogy' and al.
1928 (setq info (plist-put info :parse-tree data))
1929 ;; Get the list of elements and objects to ignore, and put it into
1930 ;; `:ignore-list'. Do not overwrite any user ignore that might have
1931 ;; been done during parse tree filtering.
1932 (setq info
1933 (plist-put info
1934 :ignore-list
1935 (append (org-export--populate-ignore-list data info)
1936 (plist-get info :ignore-list))))
1937 ;; Compute `:headline-offset' in order to be able to use
1938 ;; `org-export-get-relative-level'.
1939 (setq info
1940 (plist-put info
1941 :headline-offset
1942 (- 1 (org-export--get-min-level data info))))
1943 ;; Footnote definitions in parse tree override those stored in
1944 ;; `:footnote-definition-alist'. This way, any change to
1945 ;; a definition in the parse tree (e.g., through a parse tree
1946 ;; filter) propagates into the alist.
1947 (let ((defs (plist-get info :footnote-definition-alist)))
1948 (org-element-map data '(footnote-definition footnote-reference)
1949 (lambda (fn)
1950 (cond ((eq (org-element-type fn) 'footnote-definition)
1951 (push (cons (org-element-property :label fn)
1952 (append '(org-data nil) (org-element-contents fn)))
1953 defs))
1954 ((eq (org-element-property :type fn) 'inline)
1955 (push (cons (org-element-property :label fn)
1956 (org-element-contents fn))
1957 defs)))))
1958 (setq info (plist-put info :footnote-definition-alist defs)))
1959 ;; Properties order doesn't matter: get the rest of the tree
1960 ;; properties.
1961 (nconc
1962 `(:headline-numbering ,(org-export--collect-headline-numbering data info)
1963 :exported-data ,(make-hash-table :test 'eq :size 4001))
1964 info))
1966 (defun org-export--get-min-level (data options)
1967 "Return minimum exportable headline's level in DATA.
1968 DATA is parsed tree as returned by `org-element-parse-buffer'.
1969 OPTIONS is a plist holding export options."
1970 (catch 'exit
1971 (let ((min-level 10000))
1972 (mapc
1973 (lambda (blob)
1974 (when (and (eq (org-element-type blob) 'headline)
1975 (not (org-element-property :footnote-section-p blob))
1976 (not (memq blob (plist-get options :ignore-list))))
1977 (setq min-level (min (org-element-property :level blob) min-level)))
1978 (when (= min-level 1) (throw 'exit 1)))
1979 (org-element-contents data))
1980 ;; If no headline was found, for the sake of consistency, set
1981 ;; minimum level to 1 nonetheless.
1982 (if (= min-level 10000) 1 min-level))))
1984 (defun org-export--collect-headline-numbering (data options)
1985 "Return numbering of all exportable headlines in a parse tree.
1987 DATA is the parse tree. OPTIONS is the plist holding export
1988 options.
1990 Return an alist whose key is a headline and value is its
1991 associated numbering \(in the shape of a list of numbers\) or nil
1992 for a footnotes section."
1993 (let ((numbering (make-vector org-export-max-depth 0)))
1994 (org-element-map data 'headline
1995 (lambda (headline)
1996 (unless (org-element-property :footnote-section-p headline)
1997 (let ((relative-level
1998 (1- (org-export-get-relative-level headline options))))
1999 (cons
2000 headline
2001 (loop for n across numbering
2002 for idx from 0 to org-export-max-depth
2003 when (< idx relative-level) collect n
2004 when (= idx relative-level) collect (aset numbering idx (1+ n))
2005 when (> idx relative-level) do (aset numbering idx 0))))))
2006 options)))
2008 (defun org-export--populate-ignore-list (data options)
2009 "Return list of elements and objects to ignore during export.
2010 DATA is the parse tree to traverse. OPTIONS is the plist holding
2011 export options."
2012 (let* (walk-data
2013 ;; First find trees containing a select tag, if any.
2014 (selected (org-export--selected-trees data options))
2015 ;; If a select tag is active, also ignore the section before
2016 ;; the first headline, if any.
2017 (ignore (and selected
2018 (let ((first-element (car (org-element-contents data))))
2019 (and (eq (org-element-type first-element) 'section)
2020 first-element))))
2021 (walk-data
2022 (lambda (data)
2023 ;; Collect ignored elements or objects into IGNORE-LIST.
2024 (let ((type (org-element-type data)))
2025 (if (org-export--skip-p data options selected) (push data ignore)
2026 (if (and (eq type 'headline)
2027 (eq (plist-get options :with-archived-trees) 'headline)
2028 (org-element-property :archivedp data))
2029 ;; If headline is archived but tree below has
2030 ;; to be skipped, add it to ignore list.
2031 (dolist (element (org-element-contents data))
2032 (push element ignore))
2033 ;; Move into secondary string, if any.
2034 (let ((sec-prop
2035 (cdr (assq type org-element-secondary-value-alist))))
2036 (when sec-prop
2037 (mapc walk-data (org-element-property sec-prop data))))
2038 ;; Move into recursive objects/elements.
2039 (mapc walk-data (org-element-contents data))))))))
2040 ;; Main call.
2041 (funcall walk-data data)
2042 ;; Return value.
2043 ignore))
2045 (defun org-export--selected-trees (data info)
2046 "Return list of headlines and inlinetasks with a select tag in their tree.
2047 DATA is parsed data as returned by `org-element-parse-buffer'.
2048 INFO is a plist holding export options."
2049 (let* (selected-trees
2050 walk-data ; For byte-compiler.
2051 (walk-data
2052 (function
2053 (lambda (data genealogy)
2054 (let ((type (org-element-type data)))
2055 (cond
2056 ((memq type '(headline inlinetask))
2057 (let ((tags (org-element-property :tags data)))
2058 (if (loop for tag in (plist-get info :select-tags)
2059 thereis (member tag tags))
2060 ;; When a select tag is found, mark full
2061 ;; genealogy and every headline within the tree
2062 ;; as acceptable.
2063 (setq selected-trees
2064 (append
2065 genealogy
2066 (org-element-map data '(headline inlinetask)
2067 'identity)
2068 selected-trees))
2069 ;; If at a headline, continue searching in tree,
2070 ;; recursively.
2071 (when (eq type 'headline)
2072 (mapc (lambda (el)
2073 (funcall walk-data el (cons data genealogy)))
2074 (org-element-contents data))))))
2075 ((or (eq type 'org-data)
2076 (memq type org-element-greater-elements))
2077 (mapc (lambda (el) (funcall walk-data el genealogy))
2078 (org-element-contents data)))))))))
2079 (funcall walk-data data nil)
2080 selected-trees))
2082 (defun org-export--skip-p (blob options selected)
2083 "Non-nil when element or object BLOB should be skipped during export.
2084 OPTIONS is the plist holding export options. SELECTED, when
2085 non-nil, is a list of headlines or inlinetasks belonging to
2086 a tree with a select tag."
2087 (case (org-element-type blob)
2088 (clock (not (plist-get options :with-clocks)))
2089 (drawer
2090 (let ((with-drawers-p (plist-get options :with-drawers)))
2091 (or (not with-drawers-p)
2092 (and (consp with-drawers-p)
2093 ;; If `:with-drawers' value starts with `not', ignore
2094 ;; every drawer whose name belong to that list.
2095 ;; Otherwise, ignore drawers whose name isn't in that
2096 ;; list.
2097 (let ((name (org-element-property :drawer-name blob)))
2098 (if (eq (car with-drawers-p) 'not)
2099 (member-ignore-case name (cdr with-drawers-p))
2100 (not (member-ignore-case name with-drawers-p))))))))
2101 (fixed-width (not (plist-get options :with-fixed-width)))
2102 ((footnote-definition footnote-reference)
2103 (not (plist-get options :with-footnotes)))
2104 ((headline inlinetask)
2105 (let ((with-tasks (plist-get options :with-tasks))
2106 (todo (org-element-property :todo-keyword blob))
2107 (todo-type (org-element-property :todo-type blob))
2108 (archived (plist-get options :with-archived-trees))
2109 (tags (org-element-property :tags blob)))
2111 (and (eq (org-element-type blob) 'inlinetask)
2112 (not (plist-get options :with-inlinetasks)))
2113 ;; Ignore subtrees with an exclude tag.
2114 (loop for k in (plist-get options :exclude-tags)
2115 thereis (member k tags))
2116 ;; When a select tag is present in the buffer, ignore any tree
2117 ;; without it.
2118 (and selected (not (memq blob selected)))
2119 ;; Ignore commented sub-trees.
2120 (org-element-property :commentedp blob)
2121 ;; Ignore archived subtrees if `:with-archived-trees' is nil.
2122 (and (not archived) (org-element-property :archivedp blob))
2123 ;; Ignore tasks, if specified by `:with-tasks' property.
2124 (and todo
2125 (or (not with-tasks)
2126 (and (memq with-tasks '(todo done))
2127 (not (eq todo-type with-tasks)))
2128 (and (consp with-tasks) (not (member todo with-tasks))))))))
2129 ((latex-environment latex-fragment) (not (plist-get options :with-latex)))
2130 (node-property
2131 (let ((properties-set (plist-get options :with-properties)))
2132 (cond ((null properties-set) t)
2133 ((consp properties-set)
2134 (not (member-ignore-case (org-element-property :key blob)
2135 properties-set))))))
2136 (planning (not (plist-get options :with-planning)))
2137 (property-drawer (not (plist-get options :with-properties)))
2138 (statistics-cookie (not (plist-get options :with-statistics-cookies)))
2139 (table (not (plist-get options :with-tables)))
2140 (table-cell
2141 (and (org-export-table-has-special-column-p
2142 (org-export-get-parent-table blob))
2143 (not (org-export-get-previous-element blob options))))
2144 (table-row (org-export-table-row-is-special-p blob options))
2145 (timestamp
2146 ;; `:with-timestamps' only applies to isolated timestamps
2147 ;; objects, i.e. timestamp objects in a paragraph containing only
2148 ;; timestamps and whitespaces.
2149 (when (let ((parent (org-export-get-parent-element blob)))
2150 (and (memq (org-element-type parent) '(paragraph verse-block))
2151 (not (org-element-map parent
2152 (cons 'plain-text
2153 (remq 'timestamp org-element-all-objects))
2154 (lambda (obj)
2155 (or (not (stringp obj)) (org-string-nw-p obj)))
2156 options t))))
2157 (case (plist-get options :with-timestamps)
2158 ('nil t)
2159 (active
2160 (not (memq (org-element-property :type blob) '(active active-range))))
2161 (inactive
2162 (not (memq (org-element-property :type blob)
2163 '(inactive inactive-range)))))))))
2166 ;;; The Transcoder
2168 ;; `org-export-data' reads a parse tree (obtained with, i.e.
2169 ;; `org-element-parse-buffer') and transcodes it into a specified
2170 ;; back-end output. It takes care of filtering out elements or
2171 ;; objects according to export options and organizing the output blank
2172 ;; lines and white space are preserved. The function memoizes its
2173 ;; results, so it is cheap to call it within transcoders.
2175 ;; It is possible to modify locally the back-end used by
2176 ;; `org-export-data' or even use a temporary back-end by using
2177 ;; `org-export-data-with-backend'.
2179 ;; Internally, three functions handle the filtering of objects and
2180 ;; elements during the export. In particular,
2181 ;; `org-export-ignore-element' marks an element or object so future
2182 ;; parse tree traversals skip it and `org-export-expand' transforms
2183 ;; the others back into their original shape.
2185 ;; `org-export-transcoder' is an accessor returning appropriate
2186 ;; translator function for a given element or object.
2188 (defun org-export-transcoder (blob info)
2189 "Return appropriate transcoder for BLOB.
2190 INFO is a plist containing export directives."
2191 (let ((type (org-element-type blob)))
2192 ;; Return contents only for complete parse trees.
2193 (if (eq type 'org-data) (lambda (blob contents info) contents)
2194 (let ((transcoder (cdr (assq type (plist-get info :translate-alist)))))
2195 (and (functionp transcoder) transcoder)))))
2197 (defun org-export-data (data info)
2198 "Convert DATA into current back-end format.
2200 DATA is a parse tree, an element or an object or a secondary
2201 string. INFO is a plist holding export options.
2203 Return a string."
2204 (or (gethash data (plist-get info :exported-data))
2205 (let* ((type (org-element-type data))
2206 (results
2207 (cond
2208 ;; Ignored element/object.
2209 ((memq data (plist-get info :ignore-list)) nil)
2210 ;; Plain text.
2211 ((eq type 'plain-text)
2212 (org-export-filter-apply-functions
2213 (plist-get info :filter-plain-text)
2214 (let ((transcoder (org-export-transcoder data info)))
2215 (if transcoder (funcall transcoder data info) data))
2216 info))
2217 ;; Secondary string.
2218 ((not type)
2219 (mapconcat (lambda (obj) (org-export-data obj info)) data ""))
2220 ;; Element/Object without contents or, as a special
2221 ;; case, headline with archive tag and archived trees
2222 ;; restricted to title only.
2223 ((or (not (org-element-contents data))
2224 (and (eq type 'headline)
2225 (eq (plist-get info :with-archived-trees) 'headline)
2226 (org-element-property :archivedp data)))
2227 (let ((transcoder (org-export-transcoder data info)))
2228 (or (and (functionp transcoder)
2229 (funcall transcoder data nil info))
2230 ;; Export snippets never return a nil value so
2231 ;; that white spaces following them are never
2232 ;; ignored.
2233 (and (eq type 'export-snippet) ""))))
2234 ;; Element/Object with contents.
2236 (let ((transcoder (org-export-transcoder data info)))
2237 (when transcoder
2238 (let* ((greaterp (memq type org-element-greater-elements))
2239 (objectp
2240 (and (not greaterp)
2241 (memq type org-element-recursive-objects)))
2242 (contents
2243 (mapconcat
2244 (lambda (element) (org-export-data element info))
2245 (org-element-contents
2246 (if (or greaterp objectp) data
2247 ;; Elements directly containing
2248 ;; objects must have their indentation
2249 ;; normalized first.
2250 (org-element-normalize-contents
2251 data
2252 ;; When normalizing contents of the
2253 ;; first paragraph in an item or
2254 ;; a footnote definition, ignore
2255 ;; first line's indentation: there is
2256 ;; none and it might be misleading.
2257 (when (eq type 'paragraph)
2258 (let ((parent (org-export-get-parent data)))
2259 (and
2260 (eq (car (org-element-contents parent))
2261 data)
2262 (memq (org-element-type parent)
2263 '(footnote-definition item))))))))
2264 "")))
2265 (funcall transcoder data
2266 (if (not greaterp) contents
2267 (org-element-normalize-string contents))
2268 info))))))))
2269 ;; Final result will be memoized before being returned.
2270 (puthash
2271 data
2272 (cond
2273 ((not results) "")
2274 ((memq type '(org-data plain-text nil)) results)
2275 ;; Append the same white space between elements or objects
2276 ;; as in the original buffer, and call appropriate filters.
2278 (let ((results
2279 (org-export-filter-apply-functions
2280 (plist-get info (intern (format ":filter-%s" type)))
2281 (let ((post-blank (or (org-element-property :post-blank data)
2282 0)))
2283 (if (memq type org-element-all-elements)
2284 (concat (org-element-normalize-string results)
2285 (make-string post-blank ?\n))
2286 (concat results (make-string post-blank ?\s))))
2287 info)))
2288 results)))
2289 (plist-get info :exported-data)))))
2291 (defun org-export-data-with-backend (data backend info)
2292 "Convert DATA into BACKEND format.
2294 DATA is an element, an object, a secondary string or a string.
2295 BACKEND is a symbol. INFO is a plist used as a communication
2296 channel.
2298 Unlike to `org-export-with-backend', this function will
2299 recursively convert DATA using BACKEND translation table."
2300 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
2301 (org-export-data
2302 data
2303 ;; Set-up a new communication channel with translations defined in
2304 ;; BACKEND as the translate table and a new hash table for
2305 ;; memoization.
2306 (org-combine-plists
2307 info
2308 (list :back-end backend
2309 :translate-alist (org-export-get-all-transcoders backend)
2310 ;; Size of the hash table is reduced since this function
2311 ;; will probably be used on small trees.
2312 :exported-data (make-hash-table :test 'eq :size 401)))))
2314 (defun org-export-remove-uninterpreted-data (data info)
2315 "Change uninterpreted elements back into Org syntax.
2316 DATA is the parse tree. INFO is a plist containing export
2317 options. Each uninterpreted element or object is changed back
2318 into a string. Contents, if any, are not modified. The parse
2319 tree is modified by side effect and returned by the function."
2320 (org-export--remove-uninterpreted-data-1 data info)
2321 (dolist (prop '(:author :date :title))
2322 (plist-put info
2323 prop
2324 (org-export--remove-uninterpreted-data-1
2325 (plist-get info prop)
2326 info))))
2328 (defun org-export--remove-uninterpreted-data-1 (data info)
2329 "Change uninterpreted elements back into Org syntax.
2330 DATA is a parse tree or a secondary string. INFO is a plist
2331 containing export options. It is modified by side effect and
2332 returned by the function."
2333 (org-element-map data
2334 '(entity bold italic latex-environment latex-fragment strike-through
2335 subscript superscript underline)
2336 #'(lambda (blob)
2337 (let ((new
2338 (case (org-element-type blob)
2339 ;; ... entities...
2340 (entity
2341 (and (not (plist-get info :with-entities))
2342 (list (concat
2343 (org-export-expand blob nil)
2344 (make-string
2345 (or (org-element-property :post-blank blob) 0)
2346 ?\s)))))
2347 ;; ... emphasis...
2348 ((bold italic strike-through underline)
2349 (and (not (plist-get info :with-emphasize))
2350 (let ((marker (case (org-element-type blob)
2351 (bold "*")
2352 (italic "/")
2353 (strike-through "+")
2354 (underline "_"))))
2355 (append
2356 (list marker)
2357 (org-element-contents blob)
2358 (list (concat
2359 marker
2360 (make-string
2361 (or (org-element-property :post-blank blob)
2363 ?\s)))))))
2364 ;; ... LaTeX environments and fragments...
2365 ((latex-environment latex-fragment)
2366 (and (eq (plist-get info :with-latex) 'verbatim)
2367 (list (org-export-expand blob nil))))
2368 ;; ... sub/superscripts...
2369 ((subscript superscript)
2370 (let ((sub/super-p (plist-get info :with-sub-superscript))
2371 (bracketp (org-element-property :use-brackets-p blob)))
2372 (and (or (not sub/super-p)
2373 (and (eq sub/super-p '{}) (not bracketp)))
2374 (append
2375 (list (concat
2376 (if (eq (org-element-type blob) 'subscript)
2378 "^")
2379 (and bracketp "{")))
2380 (org-element-contents blob)
2381 (list (concat
2382 (and bracketp "}")
2383 (and (org-element-property :post-blank blob)
2384 (make-string
2385 (org-element-property :post-blank blob)
2386 ?\s)))))))))))
2387 (when new
2388 ;; Splice NEW at BLOB location in parse tree.
2389 (dolist (e new (org-element-extract-element blob))
2390 (unless (string= e "") (org-element-insert-before e blob))))))
2391 info)
2392 ;; Return modified parse tree.
2393 data)
2395 (defun org-export-expand (blob contents &optional with-affiliated)
2396 "Expand a parsed element or object to its original state.
2398 BLOB is either an element or an object. CONTENTS is its
2399 contents, as a string or nil.
2401 When optional argument WITH-AFFILIATED is non-nil, add affiliated
2402 keywords before output."
2403 (let ((type (org-element-type blob)))
2404 (concat (and with-affiliated (memq type org-element-all-elements)
2405 (org-element--interpret-affiliated-keywords blob))
2406 (funcall (intern (format "org-element-%s-interpreter" type))
2407 blob contents))))
2409 (defun org-export-ignore-element (element info)
2410 "Add ELEMENT to `:ignore-list' in INFO.
2412 Any element in `:ignore-list' will be skipped when using
2413 `org-element-map'. INFO is modified by side effects."
2414 (plist-put info :ignore-list (cons element (plist-get info :ignore-list))))
2418 ;;; The Filter System
2420 ;; Filters allow end-users to tweak easily the transcoded output.
2421 ;; They are the functional counterpart of hooks, as every filter in
2422 ;; a set is applied to the return value of the previous one.
2424 ;; Every set is back-end agnostic. Although, a filter is always
2425 ;; called, in addition to the string it applies to, with the back-end
2426 ;; used as argument, so it's easy for the end-user to add back-end
2427 ;; specific filters in the set. The communication channel, as
2428 ;; a plist, is required as the third argument.
2430 ;; From the developer side, filters sets can be installed in the
2431 ;; process with the help of `org-export-define-backend', which
2432 ;; internally stores filters as an alist. Each association has a key
2433 ;; among the following symbols and a function or a list of functions
2434 ;; as value.
2436 ;; - `:filter-options' applies to the property list containing export
2437 ;; options. Unlike to other filters, functions in this list accept
2438 ;; two arguments instead of three: the property list containing
2439 ;; export options and the back-end. Users can set its value through
2440 ;; `org-export-filter-options-functions' variable.
2442 ;; - `:filter-parse-tree' applies directly to the complete parsed
2443 ;; tree. Users can set it through
2444 ;; `org-export-filter-parse-tree-functions' variable.
2446 ;; - `:filter-final-output' applies to the final transcoded string.
2447 ;; Users can set it with `org-export-filter-final-output-functions'
2448 ;; variable
2450 ;; - `:filter-plain-text' applies to any string not recognized as Org
2451 ;; syntax. `org-export-filter-plain-text-functions' allows users to
2452 ;; configure it.
2454 ;; - `:filter-TYPE' applies on the string returned after an element or
2455 ;; object of type TYPE has been transcoded. A user can modify
2456 ;; `org-export-filter-TYPE-functions'
2458 ;; All filters sets are applied with
2459 ;; `org-export-filter-apply-functions' function. Filters in a set are
2460 ;; applied in a LIFO fashion. It allows developers to be sure that
2461 ;; their filters will be applied first.
2463 ;; Filters properties are installed in communication channel with
2464 ;; `org-export-install-filters' function.
2466 ;; Eventually, two hooks (`org-export-before-processing-hook' and
2467 ;; `org-export-before-parsing-hook') are run at the beginning of the
2468 ;; export process and just before parsing to allow for heavy structure
2469 ;; modifications.
2472 ;;;; Hooks
2474 (defvar org-export-before-processing-hook nil
2475 "Hook run at the beginning of the export process.
2477 This is run before include keywords and macros are expanded and
2478 Babel code blocks executed, on a copy of the original buffer
2479 being exported. Visibility and narrowing are preserved. Point
2480 is at the beginning of the buffer.
2482 Every function in this hook will be called with one argument: the
2483 back-end currently used, as a symbol.")
2485 (defvar org-export-before-parsing-hook nil
2486 "Hook run before parsing an export buffer.
2488 This is run after include keywords and macros have been expanded
2489 and Babel code blocks executed, on a copy of the original buffer
2490 being exported. Visibility and narrowing are preserved. Point
2491 is at the beginning of the buffer.
2493 Every function in this hook will be called with one argument: the
2494 back-end currently used, as a symbol.")
2497 ;;;; Special Filters
2499 (defvar org-export-filter-options-functions nil
2500 "List of functions applied to the export options.
2501 Each filter is called with two arguments: the export options, as
2502 a plist, and the back-end, as a symbol. It must return
2503 a property list containing export options.")
2505 (defvar org-export-filter-parse-tree-functions nil
2506 "List of functions applied to the parsed tree.
2507 Each filter is called with three arguments: the parse tree, as
2508 returned by `org-element-parse-buffer', the back-end, as
2509 a symbol, and the communication channel, as a plist. It must
2510 return the modified parse tree to transcode.")
2512 (defvar org-export-filter-plain-text-functions nil
2513 "List of functions applied to plain text.
2514 Each filter is called with three arguments: a string which
2515 contains no Org syntax, the back-end, as a symbol, and the
2516 communication channel, as a plist. It must return a string or
2517 nil.")
2519 (defvar org-export-filter-final-output-functions nil
2520 "List of functions applied to the transcoded string.
2521 Each filter is called with three arguments: the full transcoded
2522 string, the back-end, as a symbol, and the communication channel,
2523 as a plist. It must return a string that will be used as the
2524 final export output.")
2527 ;;;; Elements Filters
2529 (defvar org-export-filter-babel-call-functions nil
2530 "List of functions applied to a transcoded babel-call.
2531 Each filter is called with three arguments: the transcoded data,
2532 as a string, the back-end, as a symbol, and the communication
2533 channel, as a plist. It must return a string or nil.")
2535 (defvar org-export-filter-center-block-functions nil
2536 "List of functions applied to a transcoded center block.
2537 Each filter is called with three arguments: the transcoded data,
2538 as a string, the back-end, as a symbol, and the communication
2539 channel, as a plist. It must return a string or nil.")
2541 (defvar org-export-filter-clock-functions nil
2542 "List of functions applied to a transcoded clock.
2543 Each filter is called with three arguments: the transcoded data,
2544 as a string, the back-end, as a symbol, and the communication
2545 channel, as a plist. It must return a string or nil.")
2547 (defvar org-export-filter-comment-functions nil
2548 "List of functions applied to a transcoded comment.
2549 Each filter is called with three arguments: the transcoded data,
2550 as a string, the back-end, as a symbol, and the communication
2551 channel, as a plist. It must return a string or nil.")
2553 (defvar org-export-filter-comment-block-functions nil
2554 "List of functions applied to a transcoded comment-block.
2555 Each filter is called with three arguments: the transcoded data,
2556 as a string, the back-end, as a symbol, and the communication
2557 channel, as a plist. It must return a string or nil.")
2559 (defvar org-export-filter-diary-sexp-functions nil
2560 "List of functions applied to a transcoded diary-sexp.
2561 Each filter is called with three arguments: the transcoded data,
2562 as a string, the back-end, as a symbol, and the communication
2563 channel, as a plist. It must return a string or nil.")
2565 (defvar org-export-filter-drawer-functions nil
2566 "List of functions applied to a transcoded drawer.
2567 Each filter is called with three arguments: the transcoded data,
2568 as a string, the back-end, as a symbol, and the communication
2569 channel, as a plist. It must return a string or nil.")
2571 (defvar org-export-filter-dynamic-block-functions nil
2572 "List of functions applied to a transcoded dynamic-block.
2573 Each filter is called with three arguments: the transcoded data,
2574 as a string, the back-end, as a symbol, and the communication
2575 channel, as a plist. It must return a string or nil.")
2577 (defvar org-export-filter-example-block-functions nil
2578 "List of functions applied to a transcoded example-block.
2579 Each filter is called with three arguments: the transcoded data,
2580 as a string, the back-end, as a symbol, and the communication
2581 channel, as a plist. It must return a string or nil.")
2583 (defvar org-export-filter-fixed-width-functions nil
2584 "List of functions applied to a transcoded fixed-width.
2585 Each filter is called with three arguments: the transcoded data,
2586 as a string, the back-end, as a symbol, and the communication
2587 channel, as a plist. It must return a string or nil.")
2589 (defvar org-export-filter-footnote-definition-functions nil
2590 "List of functions applied to a transcoded footnote-definition.
2591 Each filter is called with three arguments: the transcoded data,
2592 as a string, the back-end, as a symbol, and the communication
2593 channel, as a plist. It must return a string or nil.")
2595 (defvar org-export-filter-headline-functions nil
2596 "List of functions applied to a transcoded headline.
2597 Each filter is called with three arguments: the transcoded data,
2598 as a string, the back-end, as a symbol, and the communication
2599 channel, as a plist. It must return a string or nil.")
2601 (defvar org-export-filter-horizontal-rule-functions nil
2602 "List of functions applied to a transcoded horizontal-rule.
2603 Each filter is called with three arguments: the transcoded data,
2604 as a string, the back-end, as a symbol, and the communication
2605 channel, as a plist. It must return a string or nil.")
2607 (defvar org-export-filter-inlinetask-functions nil
2608 "List of functions applied to a transcoded inlinetask.
2609 Each filter is called with three arguments: the transcoded data,
2610 as a string, the back-end, as a symbol, and the communication
2611 channel, as a plist. It must return a string or nil.")
2613 (defvar org-export-filter-item-functions nil
2614 "List of functions applied to a transcoded item.
2615 Each filter is called with three arguments: the transcoded data,
2616 as a string, the back-end, as a symbol, and the communication
2617 channel, as a plist. It must return a string or nil.")
2619 (defvar org-export-filter-keyword-functions nil
2620 "List of functions applied to a transcoded keyword.
2621 Each filter is called with three arguments: the transcoded data,
2622 as a string, the back-end, as a symbol, and the communication
2623 channel, as a plist. It must return a string or nil.")
2625 (defvar org-export-filter-latex-environment-functions nil
2626 "List of functions applied to a transcoded latex-environment.
2627 Each filter is called with three arguments: the transcoded data,
2628 as a string, the back-end, as a symbol, and the communication
2629 channel, as a plist. It must return a string or nil.")
2631 (defvar org-export-filter-node-property-functions nil
2632 "List of functions applied to a transcoded node-property.
2633 Each filter is called with three arguments: the transcoded data,
2634 as a string, the back-end, as a symbol, and the communication
2635 channel, as a plist. It must return a string or nil.")
2637 (defvar org-export-filter-paragraph-functions nil
2638 "List of functions applied to a transcoded paragraph.
2639 Each filter is called with three arguments: the transcoded data,
2640 as a string, the back-end, as a symbol, and the communication
2641 channel, as a plist. It must return a string or nil.")
2643 (defvar org-export-filter-plain-list-functions nil
2644 "List of functions applied to a transcoded plain-list.
2645 Each filter is called with three arguments: the transcoded data,
2646 as a string, the back-end, as a symbol, and the communication
2647 channel, as a plist. It must return a string or nil.")
2649 (defvar org-export-filter-planning-functions nil
2650 "List of functions applied to a transcoded planning.
2651 Each filter is called with three arguments: the transcoded data,
2652 as a string, the back-end, as a symbol, and the communication
2653 channel, as a plist. It must return a string or nil.")
2655 (defvar org-export-filter-property-drawer-functions nil
2656 "List of functions applied to a transcoded property-drawer.
2657 Each filter is called with three arguments: the transcoded data,
2658 as a string, the back-end, as a symbol, and the communication
2659 channel, as a plist. It must return a string or nil.")
2661 (defvar org-export-filter-quote-block-functions nil
2662 "List of functions applied to a transcoded quote block.
2663 Each filter is called with three arguments: the transcoded quote
2664 data, as a string, the back-end, as a symbol, and the
2665 communication channel, as a plist. It must return a string or
2666 nil.")
2668 (defvar org-export-filter-section-functions nil
2669 "List of functions applied to a transcoded section.
2670 Each filter is called with three arguments: the transcoded data,
2671 as a string, the back-end, as a symbol, and the communication
2672 channel, as a plist. It must return a string or nil.")
2674 (defvar org-export-filter-special-block-functions nil
2675 "List of functions applied to a transcoded special block.
2676 Each filter is called with three arguments: the transcoded data,
2677 as a string, the back-end, as a symbol, and the communication
2678 channel, as a plist. It must return a string or nil.")
2680 (defvar org-export-filter-src-block-functions nil
2681 "List of functions applied to a transcoded src-block.
2682 Each filter is called with three arguments: the transcoded data,
2683 as a string, the back-end, as a symbol, and the communication
2684 channel, as a plist. It must return a string or nil.")
2686 (defvar org-export-filter-table-functions nil
2687 "List of functions applied to a transcoded table.
2688 Each filter is called with three arguments: the transcoded data,
2689 as a string, the back-end, as a symbol, and the communication
2690 channel, as a plist. It must return a string or nil.")
2692 (defvar org-export-filter-table-cell-functions nil
2693 "List of functions applied to a transcoded table-cell.
2694 Each filter is called with three arguments: the transcoded data,
2695 as a string, the back-end, as a symbol, and the communication
2696 channel, as a plist. It must return a string or nil.")
2698 (defvar org-export-filter-table-row-functions nil
2699 "List of functions applied to a transcoded table-row.
2700 Each filter is called with three arguments: the transcoded data,
2701 as a string, the back-end, as a symbol, and the communication
2702 channel, as a plist. It must return a string or nil.")
2704 (defvar org-export-filter-verse-block-functions nil
2705 "List of functions applied to a transcoded verse block.
2706 Each filter is called with three arguments: the transcoded data,
2707 as a string, the back-end, as a symbol, and the communication
2708 channel, as a plist. It must return a string or nil.")
2711 ;;;; Objects Filters
2713 (defvar org-export-filter-bold-functions nil
2714 "List of functions applied to transcoded bold text.
2715 Each filter is called with three arguments: the transcoded data,
2716 as a string, the back-end, as a symbol, and the communication
2717 channel, as a plist. It must return a string or nil.")
2719 (defvar org-export-filter-code-functions nil
2720 "List of functions applied to transcoded code text.
2721 Each filter is called with three arguments: the transcoded data,
2722 as a string, the back-end, as a symbol, and the communication
2723 channel, as a plist. It must return a string or nil.")
2725 (defvar org-export-filter-entity-functions nil
2726 "List of functions applied to a transcoded entity.
2727 Each filter is called with three arguments: the transcoded data,
2728 as a string, the back-end, as a symbol, and the communication
2729 channel, as a plist. It must return a string or nil.")
2731 (defvar org-export-filter-export-snippet-functions nil
2732 "List of functions applied to a transcoded export-snippet.
2733 Each filter is called with three arguments: the transcoded data,
2734 as a string, the back-end, as a symbol, and the communication
2735 channel, as a plist. It must return a string or nil.")
2737 (defvar org-export-filter-footnote-reference-functions nil
2738 "List of functions applied to a transcoded footnote-reference.
2739 Each filter is called with three arguments: the transcoded data,
2740 as a string, the back-end, as a symbol, and the communication
2741 channel, as a plist. It must return a string or nil.")
2743 (defvar org-export-filter-inline-babel-call-functions nil
2744 "List of functions applied to a transcoded inline-babel-call.
2745 Each filter is called with three arguments: the transcoded data,
2746 as a string, the back-end, as a symbol, and the communication
2747 channel, as a plist. It must return a string or nil.")
2749 (defvar org-export-filter-inline-src-block-functions nil
2750 "List of functions applied to a transcoded inline-src-block.
2751 Each filter is called with three arguments: the transcoded data,
2752 as a string, the back-end, as a symbol, and the communication
2753 channel, as a plist. It must return a string or nil.")
2755 (defvar org-export-filter-italic-functions nil
2756 "List of functions applied to transcoded italic text.
2757 Each filter is called with three arguments: the transcoded data,
2758 as a string, the back-end, as a symbol, and the communication
2759 channel, as a plist. It must return a string or nil.")
2761 (defvar org-export-filter-latex-fragment-functions nil
2762 "List of functions applied to a transcoded latex-fragment.
2763 Each filter is called with three arguments: the transcoded data,
2764 as a string, the back-end, as a symbol, and the communication
2765 channel, as a plist. It must return a string or nil.")
2767 (defvar org-export-filter-line-break-functions nil
2768 "List of functions applied to a transcoded line-break.
2769 Each filter is called with three arguments: the transcoded data,
2770 as a string, the back-end, as a symbol, and the communication
2771 channel, as a plist. It must return a string or nil.")
2773 (defvar org-export-filter-link-functions nil
2774 "List of functions applied to a transcoded link.
2775 Each filter is called with three arguments: the transcoded data,
2776 as a string, the back-end, as a symbol, and the communication
2777 channel, as a plist. It must return a string or nil.")
2779 (defvar org-export-filter-radio-target-functions nil
2780 "List of functions applied to a transcoded radio-target.
2781 Each filter is called with three arguments: the transcoded data,
2782 as a string, the back-end, as a symbol, and the communication
2783 channel, as a plist. It must return a string or nil.")
2785 (defvar org-export-filter-statistics-cookie-functions nil
2786 "List of functions applied to a transcoded statistics-cookie.
2787 Each filter is called with three arguments: the transcoded data,
2788 as a string, the back-end, as a symbol, and the communication
2789 channel, as a plist. It must return a string or nil.")
2791 (defvar org-export-filter-strike-through-functions nil
2792 "List of functions applied to transcoded strike-through text.
2793 Each filter is called with three arguments: the transcoded data,
2794 as a string, the back-end, as a symbol, and the communication
2795 channel, as a plist. It must return a string or nil.")
2797 (defvar org-export-filter-subscript-functions nil
2798 "List of functions applied to a transcoded subscript.
2799 Each filter is called with three arguments: the transcoded data,
2800 as a string, the back-end, as a symbol, and the communication
2801 channel, as a plist. It must return a string or nil.")
2803 (defvar org-export-filter-superscript-functions nil
2804 "List of functions applied to a transcoded superscript.
2805 Each filter is called with three arguments: the transcoded data,
2806 as a string, the back-end, as a symbol, and the communication
2807 channel, as a plist. It must return a string or nil.")
2809 (defvar org-export-filter-target-functions nil
2810 "List of functions applied to a transcoded target.
2811 Each filter is called with three arguments: the transcoded data,
2812 as a string, the back-end, as a symbol, and the communication
2813 channel, as a plist. It must return a string or nil.")
2815 (defvar org-export-filter-timestamp-functions nil
2816 "List of functions applied to a transcoded timestamp.
2817 Each filter is called with three arguments: the transcoded data,
2818 as a string, the back-end, as a symbol, and the communication
2819 channel, as a plist. It must return a string or nil.")
2821 (defvar org-export-filter-underline-functions nil
2822 "List of functions applied to transcoded underline text.
2823 Each filter is called with three arguments: the transcoded data,
2824 as a string, the back-end, as a symbol, and the communication
2825 channel, as a plist. It must return a string or nil.")
2827 (defvar org-export-filter-verbatim-functions nil
2828 "List of functions applied to transcoded verbatim text.
2829 Each filter is called with three arguments: the transcoded data,
2830 as a string, the back-end, as a symbol, and the communication
2831 channel, as a plist. It must return a string or nil.")
2834 ;;;; Filters Tools
2836 ;; Internal function `org-export-install-filters' installs filters
2837 ;; hard-coded in back-ends (developer filters) and filters from global
2838 ;; variables (user filters) in the communication channel.
2840 ;; Internal function `org-export-filter-apply-functions' takes care
2841 ;; about applying each filter in order to a given data. It ignores
2842 ;; filters returning a nil value but stops whenever a filter returns
2843 ;; an empty string.
2845 (defun org-export-filter-apply-functions (filters value info)
2846 "Call every function in FILTERS.
2848 Functions are called with arguments VALUE, current export
2849 back-end's name and INFO. A function returning a nil value will
2850 be skipped. If it returns the empty string, the process ends and
2851 VALUE is ignored.
2853 Call is done in a LIFO fashion, to be sure that developer
2854 specified filters, if any, are called first."
2855 (catch 'exit
2856 (let* ((backend (plist-get info :back-end))
2857 (backend-name (and backend (org-export-backend-name backend))))
2858 (dolist (filter filters value)
2859 (let ((result (funcall filter value backend-name info)))
2860 (cond ((not result) value)
2861 ((equal value "") (throw 'exit nil))
2862 (t (setq value result))))))))
2864 (defun org-export-install-filters (info)
2865 "Install filters properties in communication channel.
2866 INFO is a plist containing the current communication channel.
2867 Return the updated communication channel."
2868 (let (plist)
2869 ;; Install user-defined filters with `org-export-filters-alist'
2870 ;; and filters already in INFO (through ext-plist mechanism).
2871 (mapc (lambda (p)
2872 (let* ((prop (car p))
2873 (info-value (plist-get info prop))
2874 (default-value (symbol-value (cdr p))))
2875 (setq plist
2876 (plist-put plist prop
2877 ;; Filters in INFO will be called
2878 ;; before those user provided.
2879 (append (if (listp info-value) info-value
2880 (list info-value))
2881 default-value)))))
2882 org-export-filters-alist)
2883 ;; Prepend back-end specific filters to that list.
2884 (mapc (lambda (p)
2885 ;; Single values get consed, lists are appended.
2886 (let ((key (car p)) (value (cdr p)))
2887 (when value
2888 (setq plist
2889 (plist-put
2890 plist key
2891 (if (atom value) (cons value (plist-get plist key))
2892 (append value (plist-get plist key))))))))
2893 (org-export-get-all-filters (plist-get info :back-end)))
2894 ;; Return new communication channel.
2895 (org-combine-plists info plist)))
2899 ;;; Core functions
2901 ;; This is the room for the main function, `org-export-as', along with
2902 ;; its derivative, `org-export-string-as'.
2903 ;; `org-export--copy-to-kill-ring-p' determines if output of these
2904 ;; function should be added to kill ring.
2906 ;; Note that `org-export-as' doesn't really parse the current buffer,
2907 ;; but a copy of it (with the same buffer-local variables and
2908 ;; visibility), where macros and include keywords are expanded and
2909 ;; Babel blocks are executed, if appropriate.
2910 ;; `org-export-with-buffer-copy' macro prepares that copy.
2912 ;; File inclusion is taken care of by
2913 ;; `org-export-expand-include-keyword' and
2914 ;; `org-export--prepare-file-contents'. Structure wise, including
2915 ;; a whole Org file in a buffer often makes little sense. For
2916 ;; example, if the file contains a headline and the include keyword
2917 ;; was within an item, the item should contain the headline. That's
2918 ;; why file inclusion should be done before any structure can be
2919 ;; associated to the file, that is before parsing.
2921 ;; `org-export-insert-default-template' is a command to insert
2922 ;; a default template (or a back-end specific template) at point or in
2923 ;; current subtree.
2925 (defun org-export-copy-buffer ()
2926 "Return a copy of the current buffer.
2927 The copy preserves Org buffer-local variables, visibility and
2928 narrowing."
2929 (let ((copy-buffer-fun (org-export--generate-copy-script (current-buffer)))
2930 (new-buf (generate-new-buffer (buffer-name))))
2931 (with-current-buffer new-buf
2932 (funcall copy-buffer-fun)
2933 (set-buffer-modified-p nil))
2934 new-buf))
2936 (defmacro org-export-with-buffer-copy (&rest body)
2937 "Apply BODY in a copy of the current buffer.
2938 The copy preserves local variables, visibility and contents of
2939 the original buffer. Point is at the beginning of the buffer
2940 when BODY is applied."
2941 (declare (debug t))
2942 (org-with-gensyms (buf-copy)
2943 `(let ((,buf-copy (org-export-copy-buffer)))
2944 (unwind-protect
2945 (with-current-buffer ,buf-copy
2946 (goto-char (point-min))
2947 (progn ,@body))
2948 (and (buffer-live-p ,buf-copy)
2949 ;; Kill copy without confirmation.
2950 (progn (with-current-buffer ,buf-copy
2951 (restore-buffer-modified-p nil))
2952 (kill-buffer ,buf-copy)))))))
2954 (defun org-export--generate-copy-script (buffer)
2955 "Generate a function duplicating BUFFER.
2957 The copy will preserve local variables, visibility, contents and
2958 narrowing of the original buffer. If a region was active in
2959 BUFFER, contents will be narrowed to that region instead.
2961 The resulting function can be evaluated at a later time, from
2962 another buffer, effectively cloning the original buffer there.
2964 The function assumes BUFFER's major mode is `org-mode'."
2965 (with-current-buffer buffer
2966 `(lambda ()
2967 (let ((inhibit-modification-hooks t))
2968 ;; Set major mode. Ignore `org-mode-hook' as it has been run
2969 ;; already in BUFFER.
2970 (let ((org-mode-hook nil) (org-inhibit-startup t)) (org-mode))
2971 ;; Copy specific buffer local variables and variables set
2972 ;; through BIND keywords.
2973 ,@(let ((bound-variables (org-export--list-bound-variables))
2974 vars)
2975 (dolist (entry (buffer-local-variables (buffer-base-buffer)) vars)
2976 (when (consp entry)
2977 (let ((var (car entry))
2978 (val (cdr entry)))
2979 (and (not (memq var org-export-ignored-local-variables))
2980 (or (memq var
2981 '(default-directory
2982 buffer-file-name
2983 buffer-file-coding-system))
2984 (assq var bound-variables)
2985 (string-match "^\\(org-\\|orgtbl-\\)"
2986 (symbol-name var)))
2987 ;; Skip unreadable values, as they cannot be
2988 ;; sent to external process.
2989 (or (not val) (ignore-errors (read (format "%S" val))))
2990 (push `(set (make-local-variable (quote ,var))
2991 (quote ,val))
2992 vars))))))
2993 ;; Whole buffer contents.
2994 (insert
2995 ,(org-with-wide-buffer
2996 (buffer-substring-no-properties
2997 (point-min) (point-max))))
2998 ;; Narrowing.
2999 ,(if (org-region-active-p)
3000 `(narrow-to-region ,(region-beginning) ,(region-end))
3001 `(narrow-to-region ,(point-min) ,(point-max)))
3002 ;; Current position of point.
3003 (goto-char ,(point))
3004 ;; Overlays with invisible property.
3005 ,@(let (ov-set)
3006 (mapc
3007 (lambda (ov)
3008 (let ((invis-prop (overlay-get ov 'invisible)))
3009 (when invis-prop
3010 (push `(overlay-put
3011 (make-overlay ,(overlay-start ov)
3012 ,(overlay-end ov))
3013 'invisible (quote ,invis-prop))
3014 ov-set))))
3015 (overlays-in (point-min) (point-max)))
3016 ov-set)))))
3018 ;;;###autoload
3019 (defun org-export-as
3020 (backend &optional subtreep visible-only body-only ext-plist)
3021 "Transcode current Org buffer into BACKEND code.
3023 BACKEND is either an export back-end, as returned by, e.g.,
3024 `org-export-create-backend', or a symbol referring to
3025 a registered back-end.
3027 If narrowing is active in the current buffer, only transcode its
3028 narrowed part.
3030 If a region is active, transcode that region.
3032 When optional argument SUBTREEP is non-nil, transcode the
3033 sub-tree at point, extracting information from the headline
3034 properties first.
3036 When optional argument VISIBLE-ONLY is non-nil, don't export
3037 contents of hidden elements.
3039 When optional argument BODY-ONLY is non-nil, only return body
3040 code, without surrounding template.
3042 Optional argument EXT-PLIST, when provided, is a property list
3043 with external parameters overriding Org default settings, but
3044 still inferior to file-local settings.
3046 Return code as a string."
3047 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
3048 (org-export-barf-if-invalid-backend backend)
3049 (save-excursion
3050 (save-restriction
3051 ;; Narrow buffer to an appropriate region or subtree for
3052 ;; parsing. If parsing subtree, be sure to remove main headline
3053 ;; too.
3054 (cond ((org-region-active-p)
3055 (narrow-to-region (region-beginning) (region-end)))
3056 (subtreep
3057 (org-narrow-to-subtree)
3058 (goto-char (point-min))
3059 (forward-line)
3060 (narrow-to-region (point) (point-max))))
3061 ;; Initialize communication channel with original buffer
3062 ;; attributes, unavailable in its copy.
3063 (let* ((org-export-current-backend (org-export-backend-name backend))
3064 (info (org-combine-plists
3065 (list :export-options
3066 (delq nil
3067 (list (and subtreep 'subtree)
3068 (and visible-only 'visible-only)
3069 (and body-only 'body-only))))
3070 (org-export--get-buffer-attributes)))
3071 tree)
3072 ;; Update communication channel and get parse tree. Buffer
3073 ;; isn't parsed directly. Instead, a temporary copy is
3074 ;; created, where include keywords, macros are expanded and
3075 ;; code blocks are evaluated.
3076 (org-export-with-buffer-copy
3077 ;; Run first hook with current back-end's name as argument.
3078 (run-hook-with-args 'org-export-before-processing-hook
3079 (org-export-backend-name backend))
3080 (org-export-expand-include-keyword)
3081 ;; Update macro templates since #+INCLUDE keywords might have
3082 ;; added some new ones.
3083 (org-macro-initialize-templates)
3084 (org-macro-replace-all org-macro-templates)
3085 (org-export-execute-babel-code)
3086 ;; Update radio targets since keyword inclusion might have
3087 ;; added some more.
3088 (org-update-radio-target-regexp)
3089 ;; Run last hook with current back-end's name as argument.
3090 (goto-char (point-min))
3091 (save-excursion
3092 (run-hook-with-args 'org-export-before-parsing-hook
3093 (org-export-backend-name backend)))
3094 ;; Update communication channel with environment. Also
3095 ;; install user's and developer's filters.
3096 (setq info
3097 (org-export-install-filters
3098 (org-combine-plists
3099 info (org-export-get-environment backend subtreep ext-plist))))
3100 ;; Expand export-specific set of macros: {{{author}}},
3101 ;; {{{date}}}, {{{email}}} and {{{title}}}. It must be done
3102 ;; once regular macros have been expanded, since document
3103 ;; keywords may contain one of them.
3104 (org-macro-replace-all
3105 (list (cons "author"
3106 (org-element-interpret-data (plist-get info :author)))
3107 (cons "date"
3108 (org-element-interpret-data (plist-get info :date)))
3109 ;; EMAIL is not a parsed keyword: store it as-is.
3110 (cons "email" (or (plist-get info :email) ""))
3111 (cons "title"
3112 (org-element-interpret-data (plist-get info :title)))))
3113 ;; Parse buffer.
3114 (setq tree (org-element-parse-buffer nil visible-only))
3115 ;; Handle left-over uninterpreted elements or objects in
3116 ;; parse tree and communication channel.
3117 (org-export-remove-uninterpreted-data tree info)
3118 ;; Call options filters and update export options. We do not
3119 ;; use `org-export-filter-apply-functions' here since the
3120 ;; arity of such filters is different.
3121 (let ((backend-name (org-export-backend-name backend)))
3122 (dolist (filter (plist-get info :filter-options))
3123 (let ((result (funcall filter info backend-name)))
3124 (when result (setq info result)))))
3125 ;; Parse buffer, handle uninterpreted elements or objects,
3126 ;; then call parse-tree filters.
3127 (setq tree
3128 (org-export-filter-apply-functions
3129 (plist-get info :filter-parse-tree) tree info))
3130 ;; Now tree is complete, compute its properties and add them
3131 ;; to communication channel.
3132 (setq info
3133 (org-combine-plists
3134 info (org-export-collect-tree-properties tree info)))
3135 ;; Eventually transcode TREE. Wrap the resulting string into
3136 ;; a template.
3137 (let* ((body (org-element-normalize-string
3138 (or (org-export-data tree info) "")))
3139 (inner-template (cdr (assq 'inner-template
3140 (plist-get info :translate-alist))))
3141 (full-body (if (not (functionp inner-template)) body
3142 (funcall inner-template body info)))
3143 (template (cdr (assq 'template
3144 (plist-get info :translate-alist)))))
3145 ;; Remove all text properties since they cannot be
3146 ;; retrieved from an external process. Finally call
3147 ;; final-output filter and return result.
3148 (org-no-properties
3149 (org-export-filter-apply-functions
3150 (plist-get info :filter-final-output)
3151 (if (or (not (functionp template)) body-only) full-body
3152 (funcall template full-body info))
3153 info))))))))
3155 ;;;###autoload
3156 (defun org-export-string-as (string backend &optional body-only ext-plist)
3157 "Transcode STRING into BACKEND code.
3159 BACKEND is either an export back-end, as returned by, e.g.,
3160 `org-export-create-backend', or a symbol referring to
3161 a registered back-end.
3163 When optional argument BODY-ONLY is non-nil, only return body
3164 code, without preamble nor postamble.
3166 Optional argument EXT-PLIST, when provided, is a property list
3167 with external parameters overriding Org default settings, but
3168 still inferior to file-local settings.
3170 Return code as a string."
3171 (with-temp-buffer
3172 (insert string)
3173 (let ((org-inhibit-startup t)) (org-mode))
3174 (org-export-as backend nil nil body-only ext-plist)))
3176 ;;;###autoload
3177 (defun org-export-replace-region-by (backend)
3178 "Replace the active region by its export to BACKEND.
3179 BACKEND is either an export back-end, as returned by, e.g.,
3180 `org-export-create-backend', or a symbol referring to
3181 a registered back-end."
3182 (if (not (org-region-active-p))
3183 (user-error "No active region to replace")
3184 (let* ((beg (region-beginning))
3185 (end (region-end))
3186 (str (buffer-substring beg end)) rpl)
3187 (setq rpl (org-export-string-as str backend t))
3188 (delete-region beg end)
3189 (insert rpl))))
3191 ;;;###autoload
3192 (defun org-export-insert-default-template (&optional backend subtreep)
3193 "Insert all export keywords with default values at beginning of line.
3195 BACKEND is a symbol referring to the name of a registered export
3196 back-end, for which specific export options should be added to
3197 the template, or `default' for default template. When it is nil,
3198 the user will be prompted for a category.
3200 If SUBTREEP is non-nil, export configuration will be set up
3201 locally for the subtree through node properties."
3202 (interactive)
3203 (unless (derived-mode-p 'org-mode) (user-error "Not in an Org mode buffer"))
3204 (when (and subtreep (org-before-first-heading-p))
3205 (user-error "No subtree to set export options for"))
3206 (let ((node (and subtreep (save-excursion (org-back-to-heading t) (point))))
3207 (backend
3208 (or backend
3209 (intern
3210 (org-completing-read
3211 "Options category: "
3212 (cons "default"
3213 (mapcar #'(lambda (b)
3214 (symbol-name (org-export-backend-name b)))
3215 org-export--registered-backends))
3216 nil t))))
3217 options keywords)
3218 ;; Populate OPTIONS and KEYWORDS.
3219 (dolist (entry (cond ((eq backend 'default) org-export-options-alist)
3220 ((org-export-backend-p backend)
3221 (org-export-backend-options backend))
3222 (t (org-export-backend-options
3223 (org-export-get-backend backend)))))
3224 (let ((keyword (nth 1 entry))
3225 (option (nth 2 entry)))
3226 (cond
3227 (keyword (unless (assoc keyword keywords)
3228 (let ((value
3229 (if (eq (nth 4 entry) 'split)
3230 (mapconcat #'identity (eval (nth 3 entry)) " ")
3231 (eval (nth 3 entry)))))
3232 (push (cons keyword value) keywords))))
3233 (option (unless (assoc option options)
3234 (push (cons option (eval (nth 3 entry))) options))))))
3235 ;; Move to an appropriate location in order to insert options.
3236 (unless subtreep (beginning-of-line))
3237 ;; First (multiple) OPTIONS lines. Never go past fill-column.
3238 (when options
3239 (let ((items
3240 (mapcar
3241 #'(lambda (opt) (format "%s:%S" (car opt) (cdr opt)))
3242 (sort options (lambda (k1 k2) (string< (car k1) (car k2)))))))
3243 (if subtreep
3244 (org-entry-put
3245 node "EXPORT_OPTIONS" (mapconcat 'identity items " "))
3246 (while items
3247 (insert "#+OPTIONS:")
3248 (let ((width 10))
3249 (while (and items
3250 (< (+ width (length (car items)) 1) fill-column))
3251 (let ((item (pop items)))
3252 (insert " " item)
3253 (incf width (1+ (length item))))))
3254 (insert "\n")))))
3255 ;; Then the rest of keywords, in the order specified in either
3256 ;; `org-export-options-alist' or respective export back-ends.
3257 (dolist (key (nreverse keywords))
3258 (let ((val (cond ((equal (car key) "DATE")
3259 (or (cdr key)
3260 (with-temp-buffer
3261 (org-insert-time-stamp (current-time)))))
3262 ((equal (car key) "TITLE")
3263 (or (let ((visited-file
3264 (buffer-file-name (buffer-base-buffer))))
3265 (and visited-file
3266 (file-name-sans-extension
3267 (file-name-nondirectory visited-file))))
3268 (buffer-name (buffer-base-buffer))))
3269 (t (cdr key)))))
3270 (if subtreep (org-entry-put node (concat "EXPORT_" (car key)) val)
3271 (insert
3272 (format "#+%s:%s\n"
3273 (car key)
3274 (if (org-string-nw-p val) (format " %s" val) ""))))))))
3276 (defun org-export-expand-include-keyword (&optional included dir)
3277 "Expand every include keyword in buffer.
3278 Optional argument INCLUDED is a list of included file names along
3279 with their line restriction, when appropriate. It is used to
3280 avoid infinite recursion. Optional argument DIR is the current
3281 working directory. It is used to properly resolve relative
3282 paths."
3283 (let ((case-fold-search t)
3284 (file-prefix (make-hash-table :test #'equal))
3285 (current-prefix 0))
3286 (goto-char (point-min))
3287 (while (re-search-forward "^[ \t]*#\\+INCLUDE:" nil t)
3288 (let ((element (save-match-data (org-element-at-point))))
3289 (when (eq (org-element-type element) 'keyword)
3290 (beginning-of-line)
3291 ;; Extract arguments from keyword's value.
3292 (let* ((value (org-element-property :value element))
3293 (ind (org-get-indentation))
3294 (file (and (string-match
3295 "^\\(\".+?\"\\|\\S-+\\)\\(?:\\s-+\\|$\\)" value)
3296 (prog1 (expand-file-name
3297 (org-remove-double-quotes
3298 (match-string 1 value))
3299 dir)
3300 (setq value (replace-match "" nil nil value)))))
3301 (lines
3302 (and (string-match
3303 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\""
3304 value)
3305 (prog1 (match-string 1 value)
3306 (setq value (replace-match "" nil nil value)))))
3307 (env (cond ((string-match "\\<example\\>" value)
3308 'literal)
3309 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
3310 'literal)))
3311 ;; Minimal level of included file defaults to the child
3312 ;; level of the current headline, if any, or one. It
3313 ;; only applies is the file is meant to be included as
3314 ;; an Org one.
3315 (minlevel
3316 (and (not env)
3317 (if (string-match ":minlevel +\\([0-9]+\\)" value)
3318 (prog1 (string-to-number (match-string 1 value))
3319 (setq value (replace-match "" nil nil value)))
3320 (let ((cur (org-current-level)))
3321 (if cur (1+ (org-reduced-level cur)) 1)))))
3322 (src-args (and (eq env 'literal)
3323 (match-string 1 value)))
3324 (block (and (string-match "\\<\\(\\S-+\\)\\>" value)
3325 (match-string 1 value))))
3326 ;; Remove keyword.
3327 (delete-region (point) (progn (forward-line) (point)))
3328 (cond
3329 ((not file) nil)
3330 ((not (file-readable-p file))
3331 (error "Cannot include file %s" file))
3332 ;; Check if files has already been parsed. Look after
3333 ;; inclusion lines too, as different parts of the same file
3334 ;; can be included too.
3335 ((member (list file lines) included)
3336 (error "Recursive file inclusion: %s" file))
3338 (cond
3339 ((eq env 'literal)
3340 (insert
3341 (let ((ind-str (make-string ind ? ))
3342 (arg-str (if (stringp src-args)
3343 (format " %s" src-args)
3344 ""))
3345 (contents
3346 (org-escape-code-in-string
3347 (org-export--prepare-file-contents file lines))))
3348 (format "%s#+BEGIN_%s%s\n%s%s#+END_%s\n"
3349 ind-str block arg-str contents ind-str block))))
3350 ((stringp block)
3351 (insert
3352 (let ((ind-str (make-string ind ? ))
3353 (contents
3354 (org-export--prepare-file-contents file lines)))
3355 (format "%s#+BEGIN_%s\n%s%s#+END_%s\n"
3356 ind-str block contents ind-str block))))
3358 (insert
3359 (with-temp-buffer
3360 (let ((org-inhibit-startup t)) (org-mode))
3361 (insert
3362 (org-export--prepare-file-contents
3363 file lines ind minlevel
3364 (or (gethash file file-prefix)
3365 (puthash file (incf current-prefix) file-prefix))))
3366 (org-export-expand-include-keyword
3367 (cons (list file lines) included)
3368 (file-name-directory file))
3369 (buffer-string)))))))))))))
3371 (defun org-export--prepare-file-contents (file &optional lines ind minlevel id)
3372 "Prepare the contents of FILE for inclusion and return them as a string.
3374 When optional argument LINES is a string specifying a range of
3375 lines, include only those lines.
3377 Optional argument IND, when non-nil, is an integer specifying the
3378 global indentation of returned contents. Since its purpose is to
3379 allow an included file to stay in the same environment it was
3380 created \(i.e. a list item), it doesn't apply past the first
3381 headline encountered.
3383 Optional argument MINLEVEL, when non-nil, is an integer
3384 specifying the level that any top-level headline in the included
3385 file should have.
3387 Optional argument ID is an integer that will be inserted before
3388 each footnote definition and reference if FILE is an Org file.
3389 This is useful to avoid conflicts when more than one Org file
3390 with footnotes is included in a document."
3391 (with-temp-buffer
3392 (insert-file-contents file)
3393 (when lines
3394 (let* ((lines (split-string lines "-"))
3395 (lbeg (string-to-number (car lines)))
3396 (lend (string-to-number (cadr lines)))
3397 (beg (if (zerop lbeg) (point-min)
3398 (goto-char (point-min))
3399 (forward-line (1- lbeg))
3400 (point)))
3401 (end (if (zerop lend) (point-max)
3402 (goto-char (point-min))
3403 (forward-line (1- lend))
3404 (point))))
3405 (narrow-to-region beg end)))
3406 ;; Remove blank lines at beginning and end of contents. The logic
3407 ;; behind that removal is that blank lines around include keyword
3408 ;; override blank lines in included file.
3409 (goto-char (point-min))
3410 (org-skip-whitespace)
3411 (beginning-of-line)
3412 (delete-region (point-min) (point))
3413 (goto-char (point-max))
3414 (skip-chars-backward " \r\t\n")
3415 (forward-line)
3416 (delete-region (point) (point-max))
3417 ;; If IND is set, preserve indentation of include keyword until
3418 ;; the first headline encountered.
3419 (when ind
3420 (unless (eq major-mode 'org-mode)
3421 (let ((org-inhibit-startup t)) (org-mode)))
3422 (goto-char (point-min))
3423 (let ((ind-str (make-string ind ? )))
3424 (while (not (or (eobp) (looking-at org-outline-regexp-bol)))
3425 ;; Do not move footnote definitions out of column 0.
3426 (unless (and (looking-at org-footnote-definition-re)
3427 (eq (org-element-type (org-element-at-point))
3428 'footnote-definition))
3429 (insert ind-str))
3430 (forward-line))))
3431 ;; When MINLEVEL is specified, compute minimal level for headlines
3432 ;; in the file (CUR-MIN), and remove stars to each headline so
3433 ;; that headlines with minimal level have a level of MINLEVEL.
3434 (when minlevel
3435 (unless (eq major-mode 'org-mode)
3436 (let ((org-inhibit-startup t)) (org-mode)))
3437 (org-with-limited-levels
3438 (let ((levels (org-map-entries
3439 (lambda () (org-reduced-level (org-current-level))))))
3440 (when levels
3441 (let ((offset (- minlevel (apply 'min levels))))
3442 (unless (zerop offset)
3443 (when org-odd-levels-only (setq offset (* offset 2)))
3444 ;; Only change stars, don't bother moving whole
3445 ;; sections.
3446 (org-map-entries
3447 (lambda () (if (< offset 0) (delete-char (abs offset))
3448 (insert (make-string offset ?*)))))))))))
3449 ;; Append ID to all footnote references and definitions, so they
3450 ;; become file specific and cannot collide with footnotes in other
3451 ;; included files.
3452 (when id
3453 (goto-char (point-min))
3454 (while (re-search-forward org-footnote-re nil t)
3455 (let ((reference (org-element-context)))
3456 (when (memq (org-element-type reference)
3457 '(footnote-reference footnote-definition))
3458 (goto-char (org-element-property :begin reference))
3459 (forward-char)
3460 (let ((label (org-element-property :label reference)))
3461 (cond ((not label))
3462 ((org-string-match-p "\\`[0-9]+\\'" label)
3463 (insert (format "fn:%d-" id)))
3464 (t (forward-char 3) (insert (format "%d-" id)))))))))
3465 (org-element-normalize-string (buffer-string))))
3467 (defun org-export-execute-babel-code ()
3468 "Execute every Babel code in the visible part of current buffer."
3469 ;; Get a pristine copy of current buffer so Babel references can be
3470 ;; properly resolved.
3471 (let ((reference (org-export-copy-buffer)))
3472 (unwind-protect (org-babel-exp-process-buffer reference)
3473 (kill-buffer reference))))
3475 (defun org-export--copy-to-kill-ring-p ()
3476 "Return a non-nil value when output should be added to the kill ring.
3477 See also `org-export-copy-to-kill-ring'."
3478 (if (eq org-export-copy-to-kill-ring 'if-interactive)
3479 (not (or executing-kbd-macro noninteractive))
3480 (eq org-export-copy-to-kill-ring t)))
3484 ;;; Tools For Back-Ends
3486 ;; A whole set of tools is available to help build new exporters. Any
3487 ;; function general enough to have its use across many back-ends
3488 ;; should be added here.
3490 ;;;; For Affiliated Keywords
3492 ;; `org-export-read-attribute' reads a property from a given element
3493 ;; as a plist. It can be used to normalize affiliated keywords'
3494 ;; syntax.
3496 ;; Since captions can span over multiple lines and accept dual values,
3497 ;; their internal representation is a bit tricky. Therefore,
3498 ;; `org-export-get-caption' transparently returns a given element's
3499 ;; caption as a secondary string.
3501 (defun org-export-read-attribute (attribute element &optional property)
3502 "Turn ATTRIBUTE property from ELEMENT into a plist.
3504 When optional argument PROPERTY is non-nil, return the value of
3505 that property within attributes.
3507 This function assumes attributes are defined as \":keyword
3508 value\" pairs. It is appropriate for `:attr_html' like
3509 properties.
3511 All values will become strings except the empty string and
3512 \"nil\", which will become nil. Also, values containing only
3513 double quotes will be read as-is, which means that \"\" value
3514 will become the empty string."
3515 (let* ((prepare-value
3516 (lambda (str)
3517 (save-match-data
3518 (cond ((member str '(nil "" "nil")) nil)
3519 ((string-match "^\"\\(\"+\\)?\"$" str)
3520 (or (match-string 1 str) ""))
3521 (t str)))))
3522 (attributes
3523 (let ((value (org-element-property attribute element)))
3524 (when value
3525 (let ((s (mapconcat 'identity value " ")) result)
3526 (while (string-match
3527 "\\(?:^\\|[ \t]+\\)\\(:[-a-zA-Z0-9_]+\\)\\([ \t]+\\|$\\)"
3529 (let ((value (substring s 0 (match-beginning 0))))
3530 (push (funcall prepare-value value) result))
3531 (push (intern (match-string 1 s)) result)
3532 (setq s (substring s (match-end 0))))
3533 ;; Ignore any string before first property with `cdr'.
3534 (cdr (nreverse (cons (funcall prepare-value s) result))))))))
3535 (if property (plist-get attributes property) attributes)))
3537 (defun org-export-get-caption (element &optional shortp)
3538 "Return caption from ELEMENT as a secondary string.
3540 When optional argument SHORTP is non-nil, return short caption,
3541 as a secondary string, instead.
3543 Caption lines are separated by a white space."
3544 (let ((full-caption (org-element-property :caption element)) caption)
3545 (dolist (line full-caption (cdr caption))
3546 (let ((cap (funcall (if shortp 'cdr 'car) line)))
3547 (when cap
3548 (setq caption (nconc (list " ") (copy-sequence cap) caption)))))))
3551 ;;;; For Derived Back-ends
3553 ;; `org-export-with-backend' is a function allowing to locally use
3554 ;; another back-end to transcode some object or element. In a derived
3555 ;; back-end, it may be used as a fall-back function once all specific
3556 ;; cases have been treated.
3558 (defun org-export-with-backend (backend data &optional contents info)
3559 "Call a transcoder from BACKEND on DATA.
3560 BACKEND is an export back-end, as returned by, e.g.,
3561 `org-export-create-backend', or a symbol referring to
3562 a registered back-end. DATA is an Org element, object, secondary
3563 string or string. CONTENTS, when non-nil, is the transcoded
3564 contents of DATA element, as a string. INFO, when non-nil, is
3565 the communication channel used for export, as a plist."
3566 (when (symbolp backend) (setq backend (org-export-get-backend backend)))
3567 (org-export-barf-if-invalid-backend backend)
3568 (let ((type (org-element-type data)))
3569 (if (memq type '(nil org-data)) (error "No foreign transcoder available")
3570 (let* ((all-transcoders (org-export-get-all-transcoders backend))
3571 (transcoder (cdr (assq type all-transcoders))))
3572 (if (not (functionp transcoder))
3573 (error "No foreign transcoder available")
3574 (funcall
3575 transcoder data contents
3576 (org-combine-plists
3577 info (list :back-end backend
3578 :translate-alist all-transcoders
3579 :exported-data (make-hash-table :test 'eq :size 401)))))))))
3582 ;;;; For Export Snippets
3584 ;; Every export snippet is transmitted to the back-end. Though, the
3585 ;; latter will only retain one type of export-snippet, ignoring
3586 ;; others, based on the former's target back-end. The function
3587 ;; `org-export-snippet-backend' returns that back-end for a given
3588 ;; export-snippet.
3590 (defun org-export-snippet-backend (export-snippet)
3591 "Return EXPORT-SNIPPET targeted back-end as a symbol.
3592 Translation, with `org-export-snippet-translation-alist', is
3593 applied."
3594 (let ((back-end (org-element-property :back-end export-snippet)))
3595 (intern
3596 (or (cdr (assoc back-end org-export-snippet-translation-alist))
3597 back-end))))
3600 ;;;; For Footnotes
3602 ;; `org-export-collect-footnote-definitions' is a tool to list
3603 ;; actually used footnotes definitions in the whole parse tree, or in
3604 ;; a headline, in order to add footnote listings throughout the
3605 ;; transcoded data.
3607 ;; `org-export-footnote-first-reference-p' is a predicate used by some
3608 ;; back-ends, when they need to attach the footnote definition only to
3609 ;; the first occurrence of the corresponding label.
3611 ;; `org-export-get-footnote-definition' and
3612 ;; `org-export-get-footnote-number' provide easier access to
3613 ;; additional information relative to a footnote reference.
3615 (defun org-export-collect-footnote-definitions (data info)
3616 "Return an alist between footnote numbers, labels and definitions.
3618 DATA is the parse tree from which definitions are collected.
3619 INFO is the plist used as a communication channel.
3621 Definitions are sorted by order of references. They either
3622 appear as Org data or as a secondary string for inlined
3623 footnotes. Unreferenced definitions are ignored."
3624 (let* (num-alist
3625 collect-fn ; for byte-compiler.
3626 (collect-fn
3627 (function
3628 (lambda (data)
3629 ;; Collect footnote number, label and definition in DATA.
3630 (org-element-map data 'footnote-reference
3631 (lambda (fn)
3632 (when (org-export-footnote-first-reference-p fn info)
3633 (let ((def (org-export-get-footnote-definition fn info)))
3634 (push
3635 (list (org-export-get-footnote-number fn info)
3636 (org-element-property :label fn)
3637 def)
3638 num-alist)
3639 ;; Also search in definition for nested footnotes.
3640 (when (eq (org-element-property :type fn) 'standard)
3641 (funcall collect-fn def)))))
3642 ;; Don't enter footnote definitions since it will happen
3643 ;; when their first reference is found.
3644 info nil 'footnote-definition)))))
3645 (funcall collect-fn (plist-get info :parse-tree))
3646 (reverse num-alist)))
3648 (defun org-export-footnote-first-reference-p (footnote-reference info)
3649 "Non-nil when a footnote reference is the first one for its label.
3651 FOOTNOTE-REFERENCE is the footnote reference being considered.
3652 INFO is the plist used as a communication channel."
3653 (let ((label (org-element-property :label footnote-reference)))
3654 ;; Anonymous footnotes are always a first reference.
3655 (if (not label) t
3656 ;; Otherwise, return the first footnote with the same LABEL and
3657 ;; test if it is equal to FOOTNOTE-REFERENCE.
3658 (let* (search-refs ; for byte-compiler.
3659 (search-refs
3660 (function
3661 (lambda (data)
3662 (org-element-map data 'footnote-reference
3663 (lambda (fn)
3664 (cond
3665 ((string= (org-element-property :label fn) label)
3666 (throw 'exit fn))
3667 ;; If FN isn't inlined, be sure to traverse its
3668 ;; definition before resuming search. See
3669 ;; comments in `org-export-get-footnote-number'
3670 ;; for more information.
3671 ((eq (org-element-property :type fn) 'standard)
3672 (funcall search-refs
3673 (org-export-get-footnote-definition fn info)))))
3674 ;; Don't enter footnote definitions since it will
3675 ;; happen when their first reference is found.
3676 info 'first-match 'footnote-definition)))))
3677 (eq (catch 'exit (funcall search-refs (plist-get info :parse-tree)))
3678 footnote-reference)))))
3680 (defun org-export-get-footnote-definition (footnote-reference info)
3681 "Return definition of FOOTNOTE-REFERENCE as parsed data.
3682 INFO is the plist used as a communication channel. If no such
3683 definition can be found, return \"DEFINITION NOT FOUND\"."
3684 (let ((label (org-element-property :label footnote-reference)))
3685 (or (if label
3686 (cdr (assoc label (plist-get info :footnote-definition-alist)))
3687 (org-element-contents footnote-reference))
3688 "DEFINITION NOT FOUND.")))
3690 (defun org-export-get-footnote-number (footnote info)
3691 "Return number associated to a footnote.
3693 FOOTNOTE is either a footnote reference or a footnote definition.
3694 INFO is the plist used as a communication channel."
3695 (let* ((label (org-element-property :label footnote))
3696 seen-refs
3697 search-ref ; For byte-compiler.
3698 (search-ref
3699 (function
3700 (lambda (data)
3701 ;; Search footnote references through DATA, filling
3702 ;; SEEN-REFS along the way.
3703 (org-element-map data 'footnote-reference
3704 (lambda (fn)
3705 (let ((fn-lbl (org-element-property :label fn)))
3706 (cond
3707 ;; Anonymous footnote match: return number.
3708 ((and (not fn-lbl) (eq fn footnote))
3709 (throw 'exit (1+ (length seen-refs))))
3710 ;; Labels match: return number.
3711 ((and label (string= label fn-lbl))
3712 (throw 'exit (1+ (length seen-refs))))
3713 ;; Anonymous footnote: it's always a new one.
3714 ;; Also, be sure to return nil from the `cond' so
3715 ;; `first-match' doesn't get us out of the loop.
3716 ((not fn-lbl) (push 'inline seen-refs) nil)
3717 ;; Label not seen so far: add it so SEEN-REFS.
3719 ;; Also search for subsequent references in
3720 ;; footnote definition so numbering follows
3721 ;; reading logic. Note that we don't have to care
3722 ;; about inline definitions, since
3723 ;; `org-element-map' already traverses them at the
3724 ;; right time.
3726 ;; Once again, return nil to stay in the loop.
3727 ((not (member fn-lbl seen-refs))
3728 (push fn-lbl seen-refs)
3729 (funcall search-ref
3730 (org-export-get-footnote-definition fn info))
3731 nil))))
3732 ;; Don't enter footnote definitions since it will
3733 ;; happen when their first reference is found.
3734 info 'first-match 'footnote-definition)))))
3735 (catch 'exit (funcall search-ref (plist-get info :parse-tree)))))
3738 ;;;; For Headlines
3740 ;; `org-export-get-relative-level' is a shortcut to get headline
3741 ;; level, relatively to the lower headline level in the parsed tree.
3743 ;; `org-export-get-headline-number' returns the section number of an
3744 ;; headline, while `org-export-number-to-roman' allows to convert it
3745 ;; to roman numbers.
3747 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
3748 ;; `org-export-last-sibling-p' are three useful predicates when it
3749 ;; comes to fulfill the `:headline-levels' property.
3751 ;; `org-export-get-tags', `org-export-get-category' and
3752 ;; `org-export-get-node-property' extract useful information from an
3753 ;; headline or a parent headline. They all handle inheritance.
3755 ;; `org-export-get-alt-title' tries to retrieve an alternative title,
3756 ;; as a secondary string, suitable for table of contents. It falls
3757 ;; back onto default title.
3759 (defun org-export-get-relative-level (headline info)
3760 "Return HEADLINE relative level within current parsed tree.
3761 INFO is a plist holding contextual information."
3762 (+ (org-element-property :level headline)
3763 (or (plist-get info :headline-offset) 0)))
3765 (defun org-export-low-level-p (headline info)
3766 "Non-nil when HEADLINE is considered as low level.
3768 INFO is a plist used as a communication channel.
3770 A low level headlines has a relative level greater than
3771 `:headline-levels' property value.
3773 Return value is the difference between HEADLINE relative level
3774 and the last level being considered as high enough, or nil."
3775 (let ((limit (plist-get info :headline-levels)))
3776 (when (wholenump limit)
3777 (let ((level (org-export-get-relative-level headline info)))
3778 (and (> level limit) (- level limit))))))
3780 (defun org-export-get-headline-number (headline info)
3781 "Return HEADLINE numbering as a list of numbers.
3782 INFO is a plist holding contextual information."
3783 (cdr (assoc headline (plist-get info :headline-numbering))))
3785 (defun org-export-numbered-headline-p (headline info)
3786 "Return a non-nil value if HEADLINE element should be numbered.
3787 INFO is a plist used as a communication channel."
3788 (let ((sec-num (plist-get info :section-numbers))
3789 (level (org-export-get-relative-level headline info)))
3790 (if (wholenump sec-num) (<= level sec-num) sec-num)))
3792 (defun org-export-number-to-roman (n)
3793 "Convert integer N into a roman numeral."
3794 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
3795 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
3796 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
3797 ( 1 . "I")))
3798 (res ""))
3799 (if (<= n 0)
3800 (number-to-string n)
3801 (while roman
3802 (if (>= n (caar roman))
3803 (setq n (- n (caar roman))
3804 res (concat res (cdar roman)))
3805 (pop roman)))
3806 res)))
3808 (defun org-export-get-tags (element info &optional tags inherited)
3809 "Return list of tags associated to ELEMENT.
3811 ELEMENT has either an `headline' or an `inlinetask' type. INFO
3812 is a plist used as a communication channel.
3814 Select tags (see `org-export-select-tags') and exclude tags (see
3815 `org-export-exclude-tags') are removed from the list.
3817 When non-nil, optional argument TAGS should be a list of strings.
3818 Any tag belonging to this list will also be removed.
3820 When optional argument INHERITED is non-nil, tags can also be
3821 inherited from parent headlines and FILETAGS keywords."
3822 (org-remove-if
3823 (lambda (tag) (or (member tag (plist-get info :select-tags))
3824 (member tag (plist-get info :exclude-tags))
3825 (member tag tags)))
3826 (if (not inherited) (org-element-property :tags element)
3827 ;; Build complete list of inherited tags.
3828 (let ((current-tag-list (org-element-property :tags element)))
3829 (mapc
3830 (lambda (parent)
3831 (mapc
3832 (lambda (tag)
3833 (when (and (memq (org-element-type parent) '(headline inlinetask))
3834 (not (member tag current-tag-list)))
3835 (push tag current-tag-list)))
3836 (org-element-property :tags parent)))
3837 (org-export-get-genealogy element))
3838 ;; Add FILETAGS keywords and return results.
3839 (org-uniquify (append (plist-get info :filetags) current-tag-list))))))
3841 (defun org-export-get-node-property (property blob &optional inherited)
3842 "Return node PROPERTY value for BLOB.
3844 PROPERTY is an upcase symbol (i.e. `:COOKIE_DATA'). BLOB is an
3845 element or object.
3847 If optional argument INHERITED is non-nil, the value can be
3848 inherited from a parent headline.
3850 Return value is a string or nil."
3851 (let ((headline (if (eq (org-element-type blob) 'headline) blob
3852 (org-export-get-parent-headline blob))))
3853 (if (not inherited) (org-element-property property blob)
3854 (let ((parent headline) value)
3855 (catch 'found
3856 (while parent
3857 (when (plist-member (nth 1 parent) property)
3858 (throw 'found (org-element-property property parent)))
3859 (setq parent (org-element-property :parent parent))))))))
3861 (defun org-export-get-category (blob info)
3862 "Return category for element or object BLOB.
3864 INFO is a plist used as a communication channel.
3866 CATEGORY is automatically inherited from a parent headline, from
3867 #+CATEGORY: keyword or created out of original file name. If all
3868 fail, the fall-back value is \"???\"."
3869 (or (org-export-get-node-property :CATEGORY blob t)
3870 (org-element-map (plist-get info :parse-tree) 'keyword
3871 (lambda (kwd)
3872 (when (equal (org-element-property :key kwd) "CATEGORY")
3873 (org-element-property :value kwd)))
3874 info 'first-match)
3875 (let ((file (plist-get info :input-file)))
3876 (and file (file-name-sans-extension (file-name-nondirectory file))))
3877 "???"))
3879 (defun org-export-get-alt-title (headline info)
3880 "Return alternative title for HEADLINE, as a secondary string.
3881 INFO is a plist used as a communication channel. If no optional
3882 title is defined, fall-back to the regular title."
3883 (or (org-element-property :alt-title headline)
3884 (org-element-property :title headline)))
3886 (defun org-export-first-sibling-p (headline info)
3887 "Non-nil when HEADLINE is the first sibling in its sub-tree.
3888 INFO is a plist used as a communication channel."
3889 (not (eq (org-element-type (org-export-get-previous-element headline info))
3890 'headline)))
3892 (defun org-export-last-sibling-p (headline info)
3893 "Non-nil when HEADLINE is the last sibling in its sub-tree.
3894 INFO is a plist used as a communication channel."
3895 (not (org-export-get-next-element headline info)))
3898 ;;;; For Keywords
3900 ;; `org-export-get-date' returns a date appropriate for the document
3901 ;; to about to be exported. In particular, it takes care of
3902 ;; `org-export-date-timestamp-format'.
3904 (defun org-export-get-date (info &optional fmt)
3905 "Return date value for the current document.
3907 INFO is a plist used as a communication channel. FMT, when
3908 non-nil, is a time format string that will be applied on the date
3909 if it consists in a single timestamp object. It defaults to
3910 `org-export-date-timestamp-format' when nil.
3912 A proper date can be a secondary string, a string or nil. It is
3913 meant to be translated with `org-export-data' or alike."
3914 (let ((date (plist-get info :date))
3915 (fmt (or fmt org-export-date-timestamp-format)))
3916 (cond ((not date) nil)
3917 ((and fmt
3918 (not (cdr date))
3919 (eq (org-element-type (car date)) 'timestamp))
3920 (org-timestamp-format (car date) fmt))
3921 (t date))))
3924 ;;;; For Links
3926 ;; `org-export-solidify-link-text' turns a string into a safer version
3927 ;; for links, replacing most non-standard characters with hyphens.
3929 ;; `org-export-get-coderef-format' returns an appropriate format
3930 ;; string for coderefs.
3932 ;; `org-export-inline-image-p' returns a non-nil value when the link
3933 ;; provided should be considered as an inline image.
3935 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
3936 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
3937 ;; returns an appropriate unique identifier when found, or nil.
3939 ;; `org-export-resolve-id-link' returns the first headline with
3940 ;; specified id or custom-id in parse tree, the path to the external
3941 ;; file with the id or nil when neither was found.
3943 ;; `org-export-resolve-coderef' associates a reference to a line
3944 ;; number in the element it belongs, or returns the reference itself
3945 ;; when the element isn't numbered.
3947 (defun org-export-solidify-link-text (s)
3948 "Take link text S and make a safe target out of it."
3949 (save-match-data
3950 (mapconcat 'identity (org-split-string s "[^a-zA-Z0-9_.-:]+") "-")))
3952 (defun org-export-get-coderef-format (path desc)
3953 "Return format string for code reference link.
3954 PATH is the link path. DESC is its description."
3955 (save-match-data
3956 (cond ((not desc) "%s")
3957 ((string-match (regexp-quote (concat "(" path ")")) desc)
3958 (replace-match "%s" t t desc))
3959 (t desc))))
3961 (defun org-export-inline-image-p (link &optional rules)
3962 "Non-nil if LINK object points to an inline image.
3964 Optional argument is a set of RULES defining inline images. It
3965 is an alist where associations have the following shape:
3967 \(TYPE . REGEXP)
3969 Applying a rule means apply REGEXP against LINK's path when its
3970 type is TYPE. The function will return a non-nil value if any of
3971 the provided rules is non-nil. The default rule is
3972 `org-export-default-inline-image-rule'.
3974 This only applies to links without a description."
3975 (and (not (org-element-contents link))
3976 (let ((case-fold-search t)
3977 (rules (or rules org-export-default-inline-image-rule)))
3978 (catch 'exit
3979 (mapc
3980 (lambda (rule)
3981 (and (string= (org-element-property :type link) (car rule))
3982 (string-match (cdr rule)
3983 (org-element-property :path link))
3984 (throw 'exit t)))
3985 rules)
3986 ;; Return nil if no rule matched.
3987 nil))))
3989 (defun org-export-resolve-coderef (ref info)
3990 "Resolve a code reference REF.
3992 INFO is a plist used as a communication channel.
3994 Return associated line number in source code, or REF itself,
3995 depending on src-block or example element's switches."
3996 (org-element-map (plist-get info :parse-tree) '(example-block src-block)
3997 (lambda (el)
3998 (with-temp-buffer
3999 (insert (org-trim (org-element-property :value el)))
4000 (let* ((label-fmt (regexp-quote
4001 (or (org-element-property :label-fmt el)
4002 org-coderef-label-format)))
4003 (ref-re
4004 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
4005 (replace-regexp-in-string "%s" ref label-fmt nil t))))
4006 ;; Element containing REF is found. Resolve it to either
4007 ;; a label or a line number, as needed.
4008 (when (re-search-backward ref-re nil t)
4009 (cond
4010 ((org-element-property :use-labels el) ref)
4011 ((eq (org-element-property :number-lines el) 'continued)
4012 (+ (org-export-get-loc el info) (line-number-at-pos)))
4013 (t (line-number-at-pos)))))))
4014 info 'first-match))
4016 (defun org-export-resolve-fuzzy-link (link info)
4017 "Return LINK destination.
4019 INFO is a plist holding contextual information.
4021 Return value can be an object, an element, or nil:
4023 - If LINK path matches a target object (i.e. <<path>>) return it.
4025 - If LINK path exactly matches the name affiliated keyword
4026 \(i.e. #+NAME: path) of an element, return that element.
4028 - If LINK path exactly matches any headline name, return that
4029 element. If more than one headline share that name, priority
4030 will be given to the one with the closest common ancestor, if
4031 any, or the first one in the parse tree otherwise.
4033 - Otherwise, return nil.
4035 Assume LINK type is \"fuzzy\". White spaces are not
4036 significant."
4037 (let* ((raw-path (org-element-property :path link))
4038 (match-title-p (eq (aref raw-path 0) ?*))
4039 ;; Split PATH at white spaces so matches are space
4040 ;; insensitive.
4041 (path (org-split-string
4042 (if match-title-p (substring raw-path 1) raw-path)))
4043 ;; Cache for destinations that are not position dependent.
4044 (link-cache
4045 (or (plist-get info :resolve-fuzzy-link-cache)
4046 (plist-get (setq info (plist-put info :resolve-fuzzy-link-cache
4047 (make-hash-table :test 'equal)))
4048 :resolve-fuzzy-link-cache)))
4049 (cached (gethash path link-cache 'not-found)))
4050 (cond
4051 ;; Destination is not position dependent: use cached value.
4052 ((and (not match-title-p) (not (eq cached 'not-found))) cached)
4053 ;; First try to find a matching "<<path>>" unless user specified
4054 ;; he was looking for a headline (path starts with a "*"
4055 ;; character).
4056 ((and (not match-title-p)
4057 (let ((match (org-element-map (plist-get info :parse-tree) 'target
4058 (lambda (blob)
4059 (and (equal (org-split-string
4060 (org-element-property :value blob))
4061 path)
4062 blob))
4063 info 'first-match)))
4064 (and match (puthash path match link-cache)))))
4065 ;; Then try to find an element with a matching "#+NAME: path"
4066 ;; affiliated keyword.
4067 ((and (not match-title-p)
4068 (let ((match (org-element-map (plist-get info :parse-tree)
4069 org-element-all-elements
4070 (lambda (el)
4071 (let ((name (org-element-property :name el)))
4072 (when (and name
4073 (equal (org-split-string name) path))
4074 el)))
4075 info 'first-match)))
4076 (and match (puthash path match link-cache)))))
4077 ;; Last case: link either points to a headline or to nothingness.
4078 ;; Try to find the source, with priority given to headlines with
4079 ;; the closest common ancestor. If such candidate is found,
4080 ;; return it, otherwise return nil.
4082 (let ((find-headline
4083 (function
4084 ;; Return first headline whose `:raw-value' property is
4085 ;; NAME in parse tree DATA, or nil. Statistics cookies
4086 ;; are ignored.
4087 (lambda (name data)
4088 (org-element-map data 'headline
4089 (lambda (headline)
4090 (when (equal (org-split-string
4091 (replace-regexp-in-string
4092 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
4093 (org-element-property :raw-value headline)))
4094 name)
4095 headline))
4096 info 'first-match)))))
4097 ;; Search among headlines sharing an ancestor with link, from
4098 ;; closest to farthest.
4099 (catch 'exit
4100 (mapc
4101 (lambda (parent)
4102 (let ((foundp (funcall find-headline path parent)))
4103 (when foundp (throw 'exit foundp))))
4104 (let ((parent-hl (org-export-get-parent-headline link)))
4105 (if (not parent-hl) (list (plist-get info :parse-tree))
4106 (cons parent-hl (org-export-get-genealogy parent-hl)))))
4107 ;; No destination found: return nil.
4108 (and (not match-title-p) (puthash path nil link-cache))))))))
4110 (defun org-export-resolve-id-link (link info)
4111 "Return headline referenced as LINK destination.
4113 INFO is a plist used as a communication channel.
4115 Return value can be the headline element matched in current parse
4116 tree, a file name or nil. Assume LINK type is either \"id\" or
4117 \"custom-id\"."
4118 (let ((id (org-element-property :path link)))
4119 ;; First check if id is within the current parse tree.
4120 (or (org-element-map (plist-get info :parse-tree) 'headline
4121 (lambda (headline)
4122 (when (or (string= (org-element-property :ID headline) id)
4123 (string= (org-element-property :CUSTOM_ID headline) id))
4124 headline))
4125 info 'first-match)
4126 ;; Otherwise, look for external files.
4127 (cdr (assoc id (plist-get info :id-alist))))))
4129 (defun org-export-resolve-radio-link (link info)
4130 "Return radio-target object referenced as LINK destination.
4132 INFO is a plist used as a communication channel.
4134 Return value can be a radio-target object or nil. Assume LINK
4135 has type \"radio\"."
4136 (let ((path (replace-regexp-in-string
4137 "[ \r\t\n]+" " " (org-element-property :path link))))
4138 (org-element-map (plist-get info :parse-tree) 'radio-target
4139 (lambda (radio)
4140 (and (eq (compare-strings
4141 (replace-regexp-in-string
4142 "[ \r\t\n]+" " " (org-element-property :value radio))
4143 nil nil path nil nil t)
4145 radio))
4146 info 'first-match)))
4149 ;;;; For References
4151 ;; `org-export-get-ordinal' associates a sequence number to any object
4152 ;; or element.
4154 (defun org-export-get-ordinal (element info &optional types predicate)
4155 "Return ordinal number of an element or object.
4157 ELEMENT is the element or object considered. INFO is the plist
4158 used as a communication channel.
4160 Optional argument TYPES, when non-nil, is a list of element or
4161 object types, as symbols, that should also be counted in.
4162 Otherwise, only provided element's type is considered.
4164 Optional argument PREDICATE is a function returning a non-nil
4165 value if the current element or object should be counted in. It
4166 accepts two arguments: the element or object being considered and
4167 the plist used as a communication channel. This allows to count
4168 only a certain type of objects (i.e. inline images).
4170 Return value is a list of numbers if ELEMENT is a headline or an
4171 item. It is nil for keywords. It represents the footnote number
4172 for footnote definitions and footnote references. If ELEMENT is
4173 a target, return the same value as if ELEMENT was the closest
4174 table, item or headline containing the target. In any other
4175 case, return the sequence number of ELEMENT among elements or
4176 objects of the same type."
4177 ;; Ordinal of a target object refer to the ordinal of the closest
4178 ;; table, item, or headline containing the object.
4179 (when (eq (org-element-type element) 'target)
4180 (setq element
4181 (loop for parent in (org-export-get-genealogy element)
4182 when
4183 (memq
4184 (org-element-type parent)
4185 '(footnote-definition footnote-reference headline item
4186 table))
4187 return parent)))
4188 (case (org-element-type element)
4189 ;; Special case 1: A headline returns its number as a list.
4190 (headline (org-export-get-headline-number element info))
4191 ;; Special case 2: An item returns its number as a list.
4192 (item (let ((struct (org-element-property :structure element)))
4193 (org-list-get-item-number
4194 (org-element-property :begin element)
4195 struct
4196 (org-list-prevs-alist struct)
4197 (org-list-parents-alist struct))))
4198 ((footnote-definition footnote-reference)
4199 (org-export-get-footnote-number element info))
4200 (otherwise
4201 (let ((counter 0))
4202 ;; Increment counter until ELEMENT is found again.
4203 (org-element-map (plist-get info :parse-tree)
4204 (or types (org-element-type element))
4205 (lambda (el)
4206 (cond
4207 ((eq element el) (1+ counter))
4208 ((not predicate) (incf counter) nil)
4209 ((funcall predicate el info) (incf counter) nil)))
4210 info 'first-match)))))
4212 ;;;; For Special Blocks
4214 ;; `org-export-raw-special-block-p' check if current special block is
4215 ;; an "export block", i.e., a block whose contents should be inserted
4216 ;; as-is in the output. This should generally be the first check to
4217 ;; do when handling special blocks in the export back-end.
4219 (defun org-export-raw-special-block-p (element info &optional no-inheritance)
4220 "Non-nil if ELEMENT is an export block relatively to current back-end.
4221 An export block is a special block whose contents should be
4222 included as-is in the final output. Such blocks are defined
4223 through :export-block property in `org-export-define-backend',
4224 which see."
4225 (and (eq (org-element-type element) 'special-block)
4226 (let ((type (org-element-property :type element))
4227 (b (plist-get info :back-end)))
4228 (if no-inheritance (member type (org-export-backend-blocks b))
4229 (while (and b (not (member type (org-export-backend-blocks b))))
4230 (setq b (org-export-get-backend (org-export-backend-parent b))))
4231 b))))
4234 ;;;; For Src Blocks
4236 ;; `org-export-get-loc' counts number of code lines accumulated in
4237 ;; src-block or example-block elements with a "+n" switch until
4238 ;; a given element, excluded. Note: "-n" switches reset that count.
4240 ;; `org-export-unravel-code' extracts source code (along with a code
4241 ;; references alist) from an `element-block' or `src-block' type
4242 ;; element.
4244 ;; `org-export-format-code' applies a formatting function to each line
4245 ;; of code, providing relative line number and code reference when
4246 ;; appropriate. Since it doesn't access the original element from
4247 ;; which the source code is coming, it expects from the code calling
4248 ;; it to know if lines should be numbered and if code references
4249 ;; should appear.
4251 ;; Eventually, `org-export-format-code-default' is a higher-level
4252 ;; function (it makes use of the two previous functions) which handles
4253 ;; line numbering and code references inclusion, and returns source
4254 ;; code in a format suitable for plain text or verbatim output.
4256 (defun org-export-get-loc (element info)
4257 "Return accumulated lines of code up to ELEMENT.
4259 INFO is the plist used as a communication channel.
4261 ELEMENT is excluded from count."
4262 (let ((loc 0))
4263 (org-element-map (plist-get info :parse-tree)
4264 `(src-block example-block ,(org-element-type element))
4265 (lambda (el)
4266 (cond
4267 ;; ELEMENT is reached: Quit the loop.
4268 ((eq el element))
4269 ;; Only count lines from src-block and example-block elements
4270 ;; with a "+n" or "-n" switch. A "-n" switch resets counter.
4271 ((not (memq (org-element-type el) '(src-block example-block))) nil)
4272 ((let ((linums (org-element-property :number-lines el)))
4273 (when linums
4274 ;; Accumulate locs or reset them.
4275 (let ((lines (org-count-lines
4276 (org-trim (org-element-property :value el)))))
4277 (setq loc (if (eq linums 'new) lines (+ loc lines))))))
4278 ;; Return nil to stay in the loop.
4279 nil)))
4280 info 'first-match)
4281 ;; Return value.
4282 loc))
4284 (defun org-export-unravel-code (element)
4285 "Clean source code and extract references out of it.
4287 ELEMENT has either a `src-block' an `example-block' type.
4289 Return a cons cell whose CAR is the source code, cleaned from any
4290 reference, protective commas and spurious indentation, and CDR is
4291 an alist between relative line number (integer) and name of code
4292 reference on that line (string)."
4293 (let* ((line 0) refs
4294 (value (org-element-property :value element))
4295 ;; Get code and clean it. Remove blank lines at its
4296 ;; beginning and end.
4297 (code (replace-regexp-in-string
4298 "\\`\\([ \t]*\n\\)+" ""
4299 (replace-regexp-in-string
4300 "\\([ \t]*\n\\)*[ \t]*\\'" "\n"
4301 (if (or org-src-preserve-indentation
4302 (org-element-property :preserve-indent element))
4303 value
4304 (org-element-remove-indentation value)))))
4305 ;; Get format used for references.
4306 (label-fmt (regexp-quote
4307 (or (org-element-property :label-fmt element)
4308 org-coderef-label-format)))
4309 ;; Build a regexp matching a loc with a reference.
4310 (with-ref-re
4311 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)[ \t]*\\)$"
4312 (replace-regexp-in-string
4313 "%s" "\\([-a-zA-Z0-9_ ]+\\)" label-fmt nil t))))
4314 ;; Return value.
4315 (cons
4316 ;; Code with references removed.
4317 (org-element-normalize-string
4318 (mapconcat
4319 (lambda (loc)
4320 (incf line)
4321 (if (not (string-match with-ref-re loc)) loc
4322 ;; Ref line: remove ref, and signal its position in REFS.
4323 (push (cons line (match-string 3 loc)) refs)
4324 (replace-match "" nil nil loc 1)))
4325 (org-split-string code "\n") "\n"))
4326 ;; Reference alist.
4327 refs)))
4329 (defun org-export-format-code (code fun &optional num-lines ref-alist)
4330 "Format CODE by applying FUN line-wise and return it.
4332 CODE is a string representing the code to format. FUN is
4333 a function. It must accept three arguments: a line of
4334 code (string), the current line number (integer) or nil and the
4335 reference associated to the current line (string) or nil.
4337 Optional argument NUM-LINES can be an integer representing the
4338 number of code lines accumulated until the current code. Line
4339 numbers passed to FUN will take it into account. If it is nil,
4340 FUN's second argument will always be nil. This number can be
4341 obtained with `org-export-get-loc' function.
4343 Optional argument REF-ALIST can be an alist between relative line
4344 number (i.e. ignoring NUM-LINES) and the name of the code
4345 reference on it. If it is nil, FUN's third argument will always
4346 be nil. It can be obtained through the use of
4347 `org-export-unravel-code' function."
4348 (let ((--locs (org-split-string code "\n"))
4349 (--line 0))
4350 (org-element-normalize-string
4351 (mapconcat
4352 (lambda (--loc)
4353 (incf --line)
4354 (let ((--ref (cdr (assq --line ref-alist))))
4355 (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
4356 --locs "\n"))))
4358 (defun org-export-format-code-default (element info)
4359 "Return source code from ELEMENT, formatted in a standard way.
4361 ELEMENT is either a `src-block' or `example-block' element. INFO
4362 is a plist used as a communication channel.
4364 This function takes care of line numbering and code references
4365 inclusion. Line numbers, when applicable, appear at the
4366 beginning of the line, separated from the code by two white
4367 spaces. Code references, on the other hand, appear flushed to
4368 the right, separated by six white spaces from the widest line of
4369 code."
4370 ;; Extract code and references.
4371 (let* ((code-info (org-export-unravel-code element))
4372 (code (car code-info))
4373 (code-lines (org-split-string code "\n")))
4374 (if (null code-lines) ""
4375 (let* ((refs (and (org-element-property :retain-labels element)
4376 (cdr code-info)))
4377 ;; Handle line numbering.
4378 (num-start (case (org-element-property :number-lines element)
4379 (continued (org-export-get-loc element info))
4380 (new 0)))
4381 (num-fmt
4382 (and num-start
4383 (format "%%%ds "
4384 (length (number-to-string
4385 (+ (length code-lines) num-start))))))
4386 ;; Prepare references display, if required. Any reference
4387 ;; should start six columns after the widest line of code,
4388 ;; wrapped with parenthesis.
4389 (max-width
4390 (+ (apply 'max (mapcar 'length code-lines))
4391 (if (not num-start) 0 (length (format num-fmt num-start))))))
4392 (org-export-format-code
4393 code
4394 (lambda (loc line-num ref)
4395 (let ((number-str (and num-fmt (format num-fmt line-num))))
4396 (concat
4397 number-str
4399 (and ref
4400 (concat (make-string
4401 (- (+ 6 max-width)
4402 (+ (length loc) (length number-str))) ? )
4403 (format "(%s)" ref))))))
4404 num-start refs)))))
4407 ;;;; For Tables
4409 ;; `org-export-table-has-special-column-p' and and
4410 ;; `org-export-table-row-is-special-p' are predicates used to look for
4411 ;; meta-information about the table structure.
4413 ;; `org-table-has-header-p' tells when the rows before the first rule
4414 ;; should be considered as table's header.
4416 ;; `org-export-table-cell-width', `org-export-table-cell-alignment'
4417 ;; and `org-export-table-cell-borders' extract information from
4418 ;; a table-cell element.
4420 ;; `org-export-table-dimensions' gives the number on rows and columns
4421 ;; in the table, ignoring horizontal rules and special columns.
4422 ;; `org-export-table-cell-address', given a table-cell object, returns
4423 ;; the absolute address of a cell. On the other hand,
4424 ;; `org-export-get-table-cell-at' does the contrary.
4426 ;; `org-export-table-cell-starts-colgroup-p',
4427 ;; `org-export-table-cell-ends-colgroup-p',
4428 ;; `org-export-table-row-starts-rowgroup-p',
4429 ;; `org-export-table-row-ends-rowgroup-p',
4430 ;; `org-export-table-row-starts-header-p' and
4431 ;; `org-export-table-row-ends-header-p' indicate position of current
4432 ;; row or cell within the table.
4434 (defun org-export-table-has-special-column-p (table)
4435 "Non-nil when TABLE has a special column.
4436 All special columns will be ignored during export."
4437 ;; The table has a special column when every first cell of every row
4438 ;; has an empty value or contains a symbol among "/", "#", "!", "$",
4439 ;; "*" "_" and "^". Though, do not consider a first row containing
4440 ;; only empty cells as special.
4441 (let ((special-column-p 'empty))
4442 (catch 'exit
4443 (mapc
4444 (lambda (row)
4445 (when (eq (org-element-property :type row) 'standard)
4446 (let ((value (org-element-contents
4447 (car (org-element-contents row)))))
4448 (cond ((member value '(("/") ("#") ("!") ("$") ("*") ("_") ("^")))
4449 (setq special-column-p 'special))
4450 ((not value))
4451 (t (throw 'exit nil))))))
4452 (org-element-contents table))
4453 (eq special-column-p 'special))))
4455 (defun org-export-table-has-header-p (table info)
4456 "Non-nil when TABLE has a header.
4458 INFO is a plist used as a communication channel.
4460 A table has a header when it contains at least two row groups."
4461 (let ((cache (or (plist-get info :table-header-cache)
4462 (plist-get (setq info
4463 (plist-put info :table-header-cache
4464 (make-hash-table :test 'eq)))
4465 :table-header-cache))))
4466 (or (gethash table cache)
4467 (let ((rowgroup 1) row-flag)
4468 (puthash
4469 table
4470 (org-element-map table 'table-row
4471 (lambda (row)
4472 (cond
4473 ((> rowgroup 1) t)
4474 ((and row-flag (eq (org-element-property :type row) 'rule))
4475 (incf rowgroup) (setq row-flag nil))
4476 ((and (not row-flag) (eq (org-element-property :type row)
4477 'standard))
4478 (setq row-flag t) nil)))
4479 info 'first-match)
4480 cache)))))
4482 (defun org-export-table-row-is-special-p (table-row info)
4483 "Non-nil if TABLE-ROW is considered special.
4485 INFO is a plist used as the communication channel.
4487 All special rows will be ignored during export."
4488 (when (eq (org-element-property :type table-row) 'standard)
4489 (let ((first-cell (org-element-contents
4490 (car (org-element-contents table-row)))))
4491 ;; A row is special either when...
4493 ;; ... it starts with a field only containing "/",
4494 (equal first-cell '("/"))
4495 ;; ... the table contains a special column and the row start
4496 ;; with a marking character among, "^", "_", "$" or "!",
4497 (and (org-export-table-has-special-column-p
4498 (org-export-get-parent table-row))
4499 (member first-cell '(("^") ("_") ("$") ("!"))))
4500 ;; ... it contains only alignment cookies and empty cells.
4501 (let ((special-row-p 'empty))
4502 (catch 'exit
4503 (mapc
4504 (lambda (cell)
4505 (let ((value (org-element-contents cell)))
4506 ;; Since VALUE is a secondary string, the following
4507 ;; checks avoid expanding it with `org-export-data'.
4508 (cond ((not value))
4509 ((and (not (cdr value))
4510 (stringp (car value))
4511 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'"
4512 (car value)))
4513 (setq special-row-p 'cookie))
4514 (t (throw 'exit nil)))))
4515 (org-element-contents table-row))
4516 (eq special-row-p 'cookie)))))))
4518 (defun org-export-table-row-group (table-row info)
4519 "Return TABLE-ROW's group number, as an integer.
4521 INFO is a plist used as the communication channel.
4523 Return value is the group number, as an integer, or nil for
4524 special rows and rows separators. First group is also table's
4525 header."
4526 (let ((cache (or (plist-get info :table-row-group-cache)
4527 (plist-get (setq info
4528 (plist-put info :table-row-group-cache
4529 (make-hash-table :test 'eq)))
4530 :table-row-group-cache))))
4531 (cond ((gethash table-row cache))
4532 ((eq (org-element-property :type table-row) 'rule) nil)
4533 (t (let ((group 0) row-flag)
4534 (org-element-map (org-export-get-parent table-row) 'table-row
4535 (lambda (row)
4536 (if (eq (org-element-property :type row) 'rule)
4537 (setq row-flag nil)
4538 (unless row-flag (incf group) (setq row-flag t)))
4539 (when (eq table-row row) (puthash table-row group cache)))
4540 info 'first-match))))))
4542 (defun org-export-table-cell-width (table-cell info)
4543 "Return TABLE-CELL contents width.
4545 INFO is a plist used as the communication channel.
4547 Return value is the width given by the last width cookie in the
4548 same column as TABLE-CELL, or nil."
4549 (let* ((row (org-export-get-parent table-cell))
4550 (table (org-export-get-parent row))
4551 (cells (org-element-contents row))
4552 (columns (length cells))
4553 (column (- columns (length (memq table-cell cells))))
4554 (cache (or (plist-get info :table-cell-width-cache)
4555 (plist-get (setq info
4556 (plist-put info :table-cell-width-cache
4557 (make-hash-table :test 'eq)))
4558 :table-cell-width-cache)))
4559 (width-vector (or (gethash table cache)
4560 (puthash table (make-vector columns 'empty) cache)))
4561 (value (aref width-vector column)))
4562 (if (not (eq value 'empty)) value
4563 (let (cookie-width)
4564 (dolist (row (org-element-contents table)
4565 (aset width-vector column cookie-width))
4566 (when (org-export-table-row-is-special-p row info)
4567 ;; In a special row, try to find a width cookie at COLUMN.
4568 (let* ((value (org-element-contents
4569 (elt (org-element-contents row) column)))
4570 (cookie (car value)))
4571 ;; The following checks avoid expanding unnecessarily
4572 ;; the cell with `org-export-data'.
4573 (when (and value
4574 (not (cdr value))
4575 (stringp cookie)
4576 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'" cookie)
4577 (match-string 1 cookie))
4578 (setq cookie-width
4579 (string-to-number (match-string 1 cookie)))))))))))
4581 (defun org-export-table-cell-alignment (table-cell info)
4582 "Return TABLE-CELL contents alignment.
4584 INFO is a plist used as the communication channel.
4586 Return alignment as specified by the last alignment cookie in the
4587 same column as TABLE-CELL. If no such cookie is found, a default
4588 alignment value will be deduced from fraction of numbers in the
4589 column (see `org-table-number-fraction' for more information).
4590 Possible values are `left', `right' and `center'."
4591 ;; Load `org-table-number-fraction' and `org-table-number-regexp'.
4592 (require 'org-table)
4593 (let* ((row (org-export-get-parent table-cell))
4594 (table (org-export-get-parent row))
4595 (cells (org-element-contents row))
4596 (columns (length cells))
4597 (column (- columns (length (memq table-cell cells))))
4598 (cache (or (plist-get info :table-cell-alignment-cache)
4599 (plist-get (setq info
4600 (plist-put info :table-cell-alignment-cache
4601 (make-hash-table :test 'eq)))
4602 :table-cell-alignment-cache)))
4603 (align-vector (or (gethash table cache)
4604 (puthash table (make-vector columns nil) cache))))
4605 (or (aref align-vector column)
4606 (let ((number-cells 0)
4607 (total-cells 0)
4608 cookie-align
4609 previous-cell-number-p)
4610 (dolist (row (org-element-contents (org-export-get-parent row)))
4611 (cond
4612 ;; In a special row, try to find an alignment cookie at
4613 ;; COLUMN.
4614 ((org-export-table-row-is-special-p row info)
4615 (let ((value (org-element-contents
4616 (elt (org-element-contents row) column))))
4617 ;; Since VALUE is a secondary string, the following
4618 ;; checks avoid useless expansion through
4619 ;; `org-export-data'.
4620 (when (and value
4621 (not (cdr value))
4622 (stringp (car value))
4623 (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'"
4624 (car value))
4625 (match-string 1 (car value)))
4626 (setq cookie-align (match-string 1 (car value))))))
4627 ;; Ignore table rules.
4628 ((eq (org-element-property :type row) 'rule))
4629 ;; In a standard row, check if cell's contents are
4630 ;; expressing some kind of number. Increase NUMBER-CELLS
4631 ;; accordingly. Though, don't bother if an alignment
4632 ;; cookie has already defined cell's alignment.
4633 ((not cookie-align)
4634 (let ((value (org-export-data
4635 (org-element-contents
4636 (elt (org-element-contents row) column))
4637 info)))
4638 (incf total-cells)
4639 ;; Treat an empty cell as a number if it follows
4640 ;; a number.
4641 (if (not (or (string-match org-table-number-regexp value)
4642 (and (string= value "") previous-cell-number-p)))
4643 (setq previous-cell-number-p nil)
4644 (setq previous-cell-number-p t)
4645 (incf number-cells))))))
4646 ;; Return value. Alignment specified by cookies has
4647 ;; precedence over alignment deduced from cell's contents.
4648 (aset align-vector
4649 column
4650 (cond ((equal cookie-align "l") 'left)
4651 ((equal cookie-align "r") 'right)
4652 ((equal cookie-align "c") 'center)
4653 ((>= (/ (float number-cells) total-cells)
4654 org-table-number-fraction)
4655 'right)
4656 (t 'left)))))))
4658 (defun org-export-table-cell-borders (table-cell info)
4659 "Return TABLE-CELL borders.
4661 INFO is a plist used as a communication channel.
4663 Return value is a list of symbols, or nil. Possible values are:
4664 `top', `bottom', `above', `below', `left' and `right'. Note:
4665 `top' (resp. `bottom') only happen for a cell in the first
4666 row (resp. last row) of the table, ignoring table rules, if any.
4668 Returned borders ignore special rows."
4669 (let* ((row (org-export-get-parent table-cell))
4670 (table (org-export-get-parent-table table-cell))
4671 borders)
4672 ;; Top/above border? TABLE-CELL has a border above when a rule
4673 ;; used to demarcate row groups can be found above. Hence,
4674 ;; finding a rule isn't sufficient to push `above' in BORDERS:
4675 ;; another regular row has to be found above that rule.
4676 (let (rule-flag)
4677 (catch 'exit
4678 (mapc (lambda (row)
4679 (cond ((eq (org-element-property :type row) 'rule)
4680 (setq rule-flag t))
4681 ((not (org-export-table-row-is-special-p row info))
4682 (if rule-flag (throw 'exit (push 'above borders))
4683 (throw 'exit nil)))))
4684 ;; Look at every row before the current one.
4685 (cdr (memq row (reverse (org-element-contents table)))))
4686 ;; No rule above, or rule found starts the table (ignoring any
4687 ;; special row): TABLE-CELL is at the top of the table.
4688 (when rule-flag (push 'above borders))
4689 (push 'top borders)))
4690 ;; Bottom/below border? TABLE-CELL has a border below when next
4691 ;; non-regular row below is a rule.
4692 (let (rule-flag)
4693 (catch 'exit
4694 (mapc (lambda (row)
4695 (cond ((eq (org-element-property :type row) 'rule)
4696 (setq rule-flag t))
4697 ((not (org-export-table-row-is-special-p row info))
4698 (if rule-flag (throw 'exit (push 'below borders))
4699 (throw 'exit nil)))))
4700 ;; Look at every row after the current one.
4701 (cdr (memq row (org-element-contents table))))
4702 ;; No rule below, or rule found ends the table (modulo some
4703 ;; special row): TABLE-CELL is at the bottom of the table.
4704 (when rule-flag (push 'below borders))
4705 (push 'bottom borders)))
4706 ;; Right/left borders? They can only be specified by column
4707 ;; groups. Column groups are defined in a row starting with "/".
4708 ;; Also a column groups row only contains "<", "<>", ">" or blank
4709 ;; cells.
4710 (catch 'exit
4711 (let ((column (let ((cells (org-element-contents row)))
4712 (- (length cells) (length (memq table-cell cells))))))
4713 (mapc
4714 (lambda (row)
4715 (unless (eq (org-element-property :type row) 'rule)
4716 (when (equal (org-element-contents
4717 (car (org-element-contents row)))
4718 '("/"))
4719 (let ((column-groups
4720 (mapcar
4721 (lambda (cell)
4722 (let ((value (org-element-contents cell)))
4723 (when (member value '(("<") ("<>") (">") nil))
4724 (car value))))
4725 (org-element-contents row))))
4726 ;; There's a left border when previous cell, if
4727 ;; any, ends a group, or current one starts one.
4728 (when (or (and (not (zerop column))
4729 (member (elt column-groups (1- column))
4730 '(">" "<>")))
4731 (member (elt column-groups column) '("<" "<>")))
4732 (push 'left borders))
4733 ;; There's a right border when next cell, if any,
4734 ;; starts a group, or current one ends one.
4735 (when (or (and (/= (1+ column) (length column-groups))
4736 (member (elt column-groups (1+ column))
4737 '("<" "<>")))
4738 (member (elt column-groups column) '(">" "<>")))
4739 (push 'right borders))
4740 (throw 'exit nil)))))
4741 ;; Table rows are read in reverse order so last column groups
4742 ;; row has precedence over any previous one.
4743 (reverse (org-element-contents table)))))
4744 ;; Return value.
4745 borders))
4747 (defun org-export-table-cell-starts-colgroup-p (table-cell info)
4748 "Non-nil when TABLE-CELL is at the beginning of a column group.
4749 INFO is a plist used as a communication channel."
4750 ;; A cell starts a column group either when it is at the beginning
4751 ;; of a row (or after the special column, if any) or when it has
4752 ;; a left border.
4753 (or (eq (org-element-map (org-export-get-parent table-cell) 'table-cell
4754 'identity info 'first-match)
4755 table-cell)
4756 (memq 'left (org-export-table-cell-borders table-cell info))))
4758 (defun org-export-table-cell-ends-colgroup-p (table-cell info)
4759 "Non-nil when TABLE-CELL is at the end of a column group.
4760 INFO is a plist used as a communication channel."
4761 ;; A cell ends a column group either when it is at the end of a row
4762 ;; or when it has a right border.
4763 (or (eq (car (last (org-element-contents
4764 (org-export-get-parent table-cell))))
4765 table-cell)
4766 (memq 'right (org-export-table-cell-borders table-cell info))))
4768 (defun org-export-table-row-starts-rowgroup-p (table-row info)
4769 "Non-nil when TABLE-ROW is at the beginning of a row group.
4770 INFO is a plist used as a communication channel."
4771 (unless (or (eq (org-element-property :type table-row) 'rule)
4772 (org-export-table-row-is-special-p table-row info))
4773 (let ((borders (org-export-table-cell-borders
4774 (car (org-element-contents table-row)) info)))
4775 (or (memq 'top borders) (memq 'above borders)))))
4777 (defun org-export-table-row-ends-rowgroup-p (table-row info)
4778 "Non-nil when TABLE-ROW is at the end of a row group.
4779 INFO is a plist used as a communication channel."
4780 (unless (or (eq (org-element-property :type table-row) 'rule)
4781 (org-export-table-row-is-special-p table-row info))
4782 (let ((borders (org-export-table-cell-borders
4783 (car (org-element-contents table-row)) info)))
4784 (or (memq 'bottom borders) (memq 'below borders)))))
4786 (defun org-export-table-row-starts-header-p (table-row info)
4787 "Non-nil when TABLE-ROW is the first table header's row.
4788 INFO is a plist used as a communication channel."
4789 (and (org-export-table-has-header-p
4790 (org-export-get-parent-table table-row) info)
4791 (org-export-table-row-starts-rowgroup-p table-row info)
4792 (= (org-export-table-row-group table-row info) 1)))
4794 (defun org-export-table-row-ends-header-p (table-row info)
4795 "Non-nil when TABLE-ROW is the last table header's row.
4796 INFO is a plist used as a communication channel."
4797 (and (org-export-table-has-header-p
4798 (org-export-get-parent-table table-row) info)
4799 (org-export-table-row-ends-rowgroup-p table-row info)
4800 (= (org-export-table-row-group table-row info) 1)))
4802 (defun org-export-table-row-number (table-row info)
4803 "Return TABLE-ROW number.
4804 INFO is a plist used as a communication channel. Return value is
4805 zero-based and ignores separators. The function returns nil for
4806 special columns and separators."
4807 (when (and (eq (org-element-property :type table-row) 'standard)
4808 (not (org-export-table-row-is-special-p table-row info)))
4809 (let ((number 0))
4810 (org-element-map (org-export-get-parent-table table-row) 'table-row
4811 (lambda (row)
4812 (cond ((eq row table-row) number)
4813 ((eq (org-element-property :type row) 'standard)
4814 (incf number) nil)))
4815 info 'first-match))))
4817 (defun org-export-table-dimensions (table info)
4818 "Return TABLE dimensions.
4820 INFO is a plist used as a communication channel.
4822 Return value is a CONS like (ROWS . COLUMNS) where
4823 ROWS (resp. COLUMNS) is the number of exportable
4824 rows (resp. columns)."
4825 (let (first-row (columns 0) (rows 0))
4826 ;; Set number of rows, and extract first one.
4827 (org-element-map table 'table-row
4828 (lambda (row)
4829 (when (eq (org-element-property :type row) 'standard)
4830 (incf rows)
4831 (unless first-row (setq first-row row)))) info)
4832 ;; Set number of columns.
4833 (org-element-map first-row 'table-cell (lambda (cell) (incf columns)) info)
4834 ;; Return value.
4835 (cons rows columns)))
4837 (defun org-export-table-cell-address (table-cell info)
4838 "Return address of a regular TABLE-CELL object.
4840 TABLE-CELL is the cell considered. INFO is a plist used as
4841 a communication channel.
4843 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4844 zero-based index. Only exportable cells are considered. The
4845 function returns nil for other cells."
4846 (let* ((table-row (org-export-get-parent table-cell))
4847 (row-number (org-export-table-row-number table-row info)))
4848 (when row-number
4849 (cons row-number
4850 (let ((col-count 0))
4851 (org-element-map table-row 'table-cell
4852 (lambda (cell)
4853 (if (eq cell table-cell) col-count (incf col-count) nil))
4854 info 'first-match))))))
4856 (defun org-export-get-table-cell-at (address table info)
4857 "Return regular table-cell object at ADDRESS in TABLE.
4859 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4860 zero-based index. TABLE is a table type element. INFO is
4861 a plist used as a communication channel.
4863 If no table-cell, among exportable cells, is found at ADDRESS,
4864 return nil."
4865 (let ((column-pos (cdr address)) (column-count 0))
4866 (org-element-map
4867 ;; Row at (car address) or nil.
4868 (let ((row-pos (car address)) (row-count 0))
4869 (org-element-map table 'table-row
4870 (lambda (row)
4871 (cond ((eq (org-element-property :type row) 'rule) nil)
4872 ((= row-count row-pos) row)
4873 (t (incf row-count) nil)))
4874 info 'first-match))
4875 'table-cell
4876 (lambda (cell)
4877 (if (= column-count column-pos) cell
4878 (incf column-count) nil))
4879 info 'first-match)))
4882 ;;;; For Tables Of Contents
4884 ;; `org-export-collect-headlines' builds a list of all exportable
4885 ;; headline elements, maybe limited to a certain depth. One can then
4886 ;; easily parse it and transcode it.
4888 ;; Building lists of tables, figures or listings is quite similar.
4889 ;; Once the generic function `org-export-collect-elements' is defined,
4890 ;; `org-export-collect-tables', `org-export-collect-figures' and
4891 ;; `org-export-collect-listings' can be derived from it.
4893 (defun org-export-collect-headlines (info &optional n)
4894 "Collect headlines in order to build a table of contents.
4896 INFO is a plist used as a communication channel.
4898 When optional argument N is an integer, it specifies the depth of
4899 the table of contents. Otherwise, it is set to the value of the
4900 last headline level. See `org-export-headline-levels' for more
4901 information.
4903 Return a list of all exportable headlines as parsed elements.
4904 Footnote sections, if any, will be ignored."
4905 (let ((limit (plist-get info :headline-levels)))
4906 (setq n (if (wholenump n) (min n limit) limit))
4907 (org-element-map (plist-get info :parse-tree) 'headline
4908 #'(lambda (headline)
4909 (unless (org-element-property :footnote-section-p headline)
4910 (let ((level (org-export-get-relative-level headline info)))
4911 (and (<= level n) headline))))
4912 info)))
4914 (defun org-export-collect-elements (type info &optional predicate)
4915 "Collect referenceable elements of a determined type.
4917 TYPE can be a symbol or a list of symbols specifying element
4918 types to search. Only elements with a caption are collected.
4920 INFO is a plist used as a communication channel.
4922 When non-nil, optional argument PREDICATE is a function accepting
4923 one argument, an element of type TYPE. It returns a non-nil
4924 value when that element should be collected.
4926 Return a list of all elements found, in order of appearance."
4927 (org-element-map (plist-get info :parse-tree) type
4928 (lambda (element)
4929 (and (org-element-property :caption element)
4930 (or (not predicate) (funcall predicate element))
4931 element))
4932 info))
4934 (defun org-export-collect-tables (info)
4935 "Build a list of tables.
4936 INFO is a plist used as a communication channel.
4938 Return a list of table elements with a caption."
4939 (org-export-collect-elements 'table info))
4941 (defun org-export-collect-figures (info predicate)
4942 "Build a list of figures.
4944 INFO is a plist used as a communication channel. PREDICATE is
4945 a function which accepts one argument: a paragraph element and
4946 whose return value is non-nil when that element should be
4947 collected.
4949 A figure is a paragraph type element, with a caption, verifying
4950 PREDICATE. The latter has to be provided since a \"figure\" is
4951 a vague concept that may depend on back-end.
4953 Return a list of elements recognized as figures."
4954 (org-export-collect-elements 'paragraph info predicate))
4956 (defun org-export-collect-listings (info)
4957 "Build a list of src blocks.
4959 INFO is a plist used as a communication channel.
4961 Return a list of src-block elements with a caption."
4962 (org-export-collect-elements 'src-block info))
4965 ;;;; Smart Quotes
4967 ;; The main function for the smart quotes sub-system is
4968 ;; `org-export-activate-smart-quotes', which replaces every quote in
4969 ;; a given string from the parse tree with its "smart" counterpart.
4971 ;; Dictionary for smart quotes is stored in
4972 ;; `org-export-smart-quotes-alist'.
4974 ;; Internally, regexps matching potential smart quotes (checks at
4975 ;; string boundaries are also necessary) are defined in
4976 ;; `org-export-smart-quotes-regexps'.
4978 (defconst org-export-smart-quotes-alist
4979 '(("da"
4980 ;; one may use: »...«, "...", ›...‹, or '...'.
4981 ;; http://sproget.dk/raad-og-regler/retskrivningsregler/retskrivningsregler/a7-40-60/a7-58-anforselstegn/
4982 ;; LaTeX quotes require Babel!
4983 (opening-double-quote :utf-8 "»" :html "&raquo;" :latex ">>"
4984 :texinfo "@guillemetright{}")
4985 (closing-double-quote :utf-8 "«" :html "&laquo;" :latex "<<"
4986 :texinfo "@guillemetleft{}")
4987 (opening-single-quote :utf-8 "›" :html "&rsaquo;" :latex "\\frq{}"
4988 :texinfo "@guilsinglright{}")
4989 (closing-single-quote :utf-8 "‹" :html "&lsaquo;" :latex "\\flq{}"
4990 :texinfo "@guilsingleft{}")
4991 (apostrophe :utf-8 "’" :html "&rsquo;"))
4992 ("de"
4993 (opening-double-quote :utf-8 "„" :html "&bdquo;" :latex "\"`"
4994 :texinfo "@quotedblbase{}")
4995 (closing-double-quote :utf-8 "“" :html "&ldquo;" :latex "\"'"
4996 :texinfo "@quotedblleft{}")
4997 (opening-single-quote :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}"
4998 :texinfo "@quotesinglbase{}")
4999 (closing-single-quote :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}"
5000 :texinfo "@quoteleft{}")
5001 (apostrophe :utf-8 "’" :html "&rsquo;"))
5002 ("en"
5003 (opening-double-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
5004 (closing-double-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
5005 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5006 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5007 (apostrophe :utf-8 "’" :html "&rsquo;"))
5008 ("es"
5009 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5010 :texinfo "@guillemetleft{}")
5011 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5012 :texinfo "@guillemetright{}")
5013 (opening-single-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
5014 (closing-single-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
5015 (apostrophe :utf-8 "’" :html "&rsquo;"))
5016 ("fr"
5017 (opening-double-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
5018 :texinfo "@guillemetleft{}@tie{}")
5019 (closing-double-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
5020 :texinfo "@tie{}@guillemetright{}")
5021 (opening-single-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
5022 :texinfo "@guillemetleft{}@tie{}")
5023 (closing-single-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
5024 :texinfo "@tie{}@guillemetright{}")
5025 (apostrophe :utf-8 "’" :html "&rsquo;"))
5026 ("no"
5027 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5028 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5029 :texinfo "@guillemetleft{}")
5030 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5031 :texinfo "@guillemetright{}")
5032 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5033 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5034 (apostrophe :utf-8 "’" :html "&rsquo;"))
5035 ("nb"
5036 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5037 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5038 :texinfo "@guillemetleft{}")
5039 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5040 :texinfo "@guillemetright{}")
5041 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5042 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5043 (apostrophe :utf-8 "’" :html "&rsquo;"))
5044 ("nn"
5045 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5046 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5047 :texinfo "@guillemetleft{}")
5048 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5049 :texinfo "@guillemetright{}")
5050 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5051 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5052 (apostrophe :utf-8 "’" :html "&rsquo;"))
5053 ("ru"
5054 ;; 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
5055 ;; http://www.artlebedev.ru/kovodstvo/sections/104/
5056 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "{}<<"
5057 :texinfo "@guillemetleft{}")
5058 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex ">>{}"
5059 :texinfo "@guillemetright{}")
5060 (opening-single-quote :utf-8 "„" :html "&bdquo;" :latex "\\glqq{}"
5061 :texinfo "@quotedblbase{}")
5062 (closing-single-quote :utf-8 "“" :html "&ldquo;" :latex "\\grqq{}"
5063 :texinfo "@quotedblleft{}")
5064 (apostrophe :utf-8 "’" :html: "&#39;"))
5065 ("sv"
5066 ;; based on https://sv.wikipedia.org/wiki/Citattecken
5067 (opening-double-quote :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
5068 (closing-double-quote :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
5069 (opening-single-quote :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "`")
5070 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "'")
5071 (apostrophe :utf-8 "’" :html "&rsquo;"))
5073 "Smart quotes translations.
5075 Alist whose CAR is a language string and CDR is an alist with
5076 quote type as key and a plist associating various encodings to
5077 their translation as value.
5079 A quote type can be any symbol among `opening-double-quote',
5080 `closing-double-quote', `opening-single-quote',
5081 `closing-single-quote' and `apostrophe'.
5083 Valid encodings include `:utf-8', `:html', `:latex' and
5084 `:texinfo'.
5086 If no translation is found, the quote character is left as-is.")
5088 (defconst org-export-smart-quotes-regexps
5089 (list
5090 ;; Possible opening quote at beginning of string.
5091 "\\`\\([\"']\\)\\(\\w\\|\\s.\\|\\s_\\|\\s(\\)"
5092 ;; Possible closing quote at beginning of string.
5093 "\\`\\([\"']\\)\\(\\s-\\|\\s)\\|\\s.\\)"
5094 ;; Possible apostrophe at beginning of string.
5095 "\\`\\('\\)\\S-"
5096 ;; Opening single and double quotes.
5097 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\(?:\\w\\|\\s.\\|\\s_\\)"
5098 ;; Closing single and double quotes.
5099 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\(?:\\s-\\|\\s)\\|\\s.\\)"
5100 ;; Apostrophe.
5101 "\\S-\\('\\)\\S-"
5102 ;; Possible opening quote at end of string.
5103 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\'"
5104 ;; Possible closing quote at end of string.
5105 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\'"
5106 ;; Possible apostrophe at end of string.
5107 "\\S-\\('\\)\\'")
5108 "List of regexps matching a quote or an apostrophe.
5109 In every regexp, quote or apostrophe matched is put in group 1.")
5111 (defun org-export-activate-smart-quotes (s encoding info &optional original)
5112 "Replace regular quotes with \"smart\" quotes in string S.
5114 ENCODING is a symbol among `:html', `:latex', `:texinfo' and
5115 `:utf-8'. INFO is a plist used as a communication channel.
5117 The function has to retrieve information about string
5118 surroundings in parse tree. It can only happen with an
5119 unmodified string. Thus, if S has already been through another
5120 process, a non-nil ORIGINAL optional argument will provide that
5121 original string.
5123 Return the new string."
5124 (if (equal s "") ""
5125 (let* ((prev (org-export-get-previous-element (or original s) info))
5126 ;; Try to be flexible when computing number of blanks
5127 ;; before object. The previous object may be a string
5128 ;; introduced by the back-end and not completely parsed.
5129 (pre-blank (and prev
5130 (or (org-element-property :post-blank prev)
5131 ;; A string with missing `:post-blank'
5132 ;; property.
5133 (and (stringp prev)
5134 (string-match " *\\'" prev)
5135 (length (match-string 0 prev)))
5136 ;; Fallback value.
5137 0)))
5138 (next (org-export-get-next-element (or original s) info))
5139 (get-smart-quote
5140 (lambda (q type)
5141 ;; Return smart quote associated to a give quote Q, as
5142 ;; a string. TYPE is a symbol among `open', `close' and
5143 ;; `apostrophe'.
5144 (let ((key (case type
5145 (apostrophe 'apostrophe)
5146 (open (if (equal "'" q) 'opening-single-quote
5147 'opening-double-quote))
5148 (otherwise (if (equal "'" q) 'closing-single-quote
5149 'closing-double-quote)))))
5150 (or (plist-get
5151 (cdr (assq key
5152 (cdr (assoc (plist-get info :language)
5153 org-export-smart-quotes-alist))))
5154 encoding)
5155 q)))))
5156 (if (or (equal "\"" s) (equal "'" s))
5157 ;; Only a quote: no regexp can match. We have to check both
5158 ;; sides and decide what to do.
5159 (cond ((and (not prev) (not next)) s)
5160 ((not prev) (funcall get-smart-quote s 'open))
5161 ((and (not next) (zerop pre-blank))
5162 (funcall get-smart-quote s 'close))
5163 ((not next) s)
5164 ((zerop pre-blank) (funcall get-smart-quote s 'apostrophe))
5165 (t (funcall get-smart-quote 'open)))
5166 ;; 1. Replace quote character at the beginning of S.
5167 (cond
5168 ;; Apostrophe?
5169 ((and prev (zerop pre-blank)
5170 (string-match (nth 2 org-export-smart-quotes-regexps) s))
5171 (setq s (replace-match
5172 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
5173 nil t s 1)))
5174 ;; Closing quote?
5175 ((and prev (zerop pre-blank)
5176 (string-match (nth 1 org-export-smart-quotes-regexps) s))
5177 (setq s (replace-match
5178 (funcall get-smart-quote (match-string 1 s) 'close)
5179 nil t s 1)))
5180 ;; Opening quote?
5181 ((and (or (not prev) (> pre-blank 0))
5182 (string-match (nth 0 org-export-smart-quotes-regexps) s))
5183 (setq s (replace-match
5184 (funcall get-smart-quote (match-string 1 s) 'open)
5185 nil t s 1))))
5186 ;; 2. Replace quotes in the middle of the string.
5187 (setq s (replace-regexp-in-string
5188 ;; Opening quotes.
5189 (nth 3 org-export-smart-quotes-regexps)
5190 (lambda (text)
5191 (funcall get-smart-quote (match-string 1 text) 'open))
5192 s nil t 1))
5193 (setq s (replace-regexp-in-string
5194 ;; Closing quotes.
5195 (nth 4 org-export-smart-quotes-regexps)
5196 (lambda (text)
5197 (funcall get-smart-quote (match-string 1 text) 'close))
5198 s nil t 1))
5199 (setq s (replace-regexp-in-string
5200 ;; Apostrophes.
5201 (nth 5 org-export-smart-quotes-regexps)
5202 (lambda (text)
5203 (funcall get-smart-quote (match-string 1 text) 'apostrophe))
5204 s nil t 1))
5205 ;; 3. Replace quote character at the end of S.
5206 (cond
5207 ;; Apostrophe?
5208 ((and next (string-match (nth 8 org-export-smart-quotes-regexps) s))
5209 (setq s (replace-match
5210 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
5211 nil t s 1)))
5212 ;; Closing quote?
5213 ((and (not next)
5214 (string-match (nth 7 org-export-smart-quotes-regexps) s))
5215 (setq s (replace-match
5216 (funcall get-smart-quote (match-string 1 s) 'close)
5217 nil t s 1)))
5218 ;; Opening quote?
5219 ((and next (string-match (nth 6 org-export-smart-quotes-regexps) s))
5220 (setq s (replace-match
5221 (funcall get-smart-quote (match-string 1 s) 'open)
5222 nil t s 1))))
5223 ;; Return string with smart quotes.
5224 s))))
5226 ;;;; Topology
5228 ;; Here are various functions to retrieve information about the
5229 ;; neighborhood of a given element or object. Neighbors of interest
5230 ;; are direct parent (`org-export-get-parent'), parent headline
5231 ;; (`org-export-get-parent-headline'), first element containing an
5232 ;; object, (`org-export-get-parent-element'), parent table
5233 ;; (`org-export-get-parent-table'), previous element or object
5234 ;; (`org-export-get-previous-element') and next element or object
5235 ;; (`org-export-get-next-element').
5237 ;; `org-export-get-genealogy' returns the full genealogy of a given
5238 ;; element or object, from closest parent to full parse tree.
5240 ;; defsubst org-export-get-parent must be defined before first use
5242 (defun org-export-get-genealogy (blob)
5243 "Return full genealogy relative to a given element or object.
5245 BLOB is the element or object being considered.
5247 Ancestors are returned from closest to farthest, the last one
5248 being the full parse tree."
5249 (let (genealogy (parent blob))
5250 (while (setq parent (org-element-property :parent parent))
5251 (push parent genealogy))
5252 (nreverse genealogy)))
5254 (defun org-export-get-parent-headline (blob)
5255 "Return BLOB parent headline or nil.
5256 BLOB is the element or object being considered."
5257 (let ((parent blob))
5258 (while (and (setq parent (org-element-property :parent parent))
5259 (not (eq (org-element-type parent) 'headline))))
5260 parent))
5262 (defun org-export-get-parent-element (object)
5263 "Return first element containing OBJECT or nil.
5264 OBJECT is the object to consider."
5265 (let ((parent object))
5266 (while (and (setq parent (org-element-property :parent parent))
5267 (memq (org-element-type parent) org-element-all-objects)))
5268 parent))
5270 (defun org-export-get-parent-table (object)
5271 "Return OBJECT parent table or nil.
5272 OBJECT is either a `table-cell' or `table-element' type object."
5273 (let ((parent object))
5274 (while (and (setq parent (org-element-property :parent parent))
5275 (not (eq (org-element-type parent) 'table))))
5276 parent))
5278 (defun org-export-get-previous-element (blob info &optional n)
5279 "Return previous element or object.
5281 BLOB is an element or object. INFO is a plist used as
5282 a communication channel. Return previous exportable element or
5283 object, a string, or nil.
5285 When optional argument N is a positive integer, return a list
5286 containing up to N siblings before BLOB, from farthest to
5287 closest. With any other non-nil value, return a list containing
5288 all of them."
5289 (let* ((secondary (org-element-secondary-p blob))
5290 (parent (org-export-get-parent blob))
5291 (siblings
5292 (if secondary (org-element-property secondary parent)
5293 (org-element-contents parent)))
5294 prev)
5295 (catch 'exit
5296 (dolist (obj (cdr (memq blob (reverse siblings))) prev)
5297 (cond ((memq obj (plist-get info :ignore-list)))
5298 ((null n) (throw 'exit obj))
5299 ((not (wholenump n)) (push obj prev))
5300 ((zerop n) (throw 'exit prev))
5301 (t (decf n) (push obj prev)))))))
5303 (defun org-export-get-next-element (blob info &optional n)
5304 "Return next element or object.
5306 BLOB is an element or object. INFO is a plist used as
5307 a communication channel. Return next exportable element or
5308 object, a string, or nil.
5310 When optional argument N is a positive integer, return a list
5311 containing up to N siblings after BLOB, from closest to farthest.
5312 With any other non-nil value, return a list containing all of
5313 them."
5314 (let* ((secondary (org-element-secondary-p blob))
5315 (parent (org-export-get-parent blob))
5316 (siblings
5317 (cdr (memq blob
5318 (if secondary (org-element-property secondary parent)
5319 (org-element-contents parent)))))
5320 next)
5321 (catch 'exit
5322 (dolist (obj siblings (nreverse next))
5323 (cond ((memq obj (plist-get info :ignore-list)))
5324 ((null n) (throw 'exit obj))
5325 ((not (wholenump n)) (push obj next))
5326 ((zerop n) (throw 'exit (nreverse next)))
5327 (t (decf n) (push obj next)))))))
5330 ;;;; Translation
5332 ;; `org-export-translate' translates a string according to the language
5333 ;; specified by the LANGUAGE keyword. `org-export-dictionary' contains
5334 ;; the dictionary used for the translation.
5336 (defconst org-export-dictionary
5337 '(("%e %n: %c"
5338 ("fr" :default "%e %n : %c" :html "%e&nbsp;%n&nbsp;: %c"))
5339 ("Author"
5340 ("ca" :default "Autor")
5341 ("cs" :default "Autor")
5342 ("da" :default "Forfatter")
5343 ("de" :default "Autor")
5344 ("eo" :html "A&#365;toro")
5345 ("es" :default "Autor")
5346 ("et" :default "Autor")
5347 ("fi" :html "Tekij&auml;")
5348 ("fr" :default "Auteur")
5349 ("hu" :default "Szerz&otilde;")
5350 ("is" :html "H&ouml;fundur")
5351 ("it" :default "Autore")
5352 ("ja" :default "著者" :html "&#33879;&#32773;")
5353 ("nl" :default "Auteur")
5354 ("no" :default "Forfatter")
5355 ("nb" :default "Forfatter")
5356 ("nn" :default "Forfattar")
5357 ("pl" :default "Autor")
5358 ("ru" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5359 ("sv" :html "F&ouml;rfattare")
5360 ("uk" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5361 ("zh-CN" :html "&#20316;&#32773;" :utf-8 "作者")
5362 ("zh-TW" :html "&#20316;&#32773;" :utf-8 "作者"))
5363 ("Continued from previous page"
5364 ("de" :default "Fortsetzung von vorheriger Seite")
5365 ("es" :default "Continúa de la página anterior")
5366 ("fr" :default "Suite de la page précédente")
5367 ("it" :default "Continua da pagina precedente")
5368 ("ja" :default "前ページからの続き")
5369 ("nl" :default "Vervolg van vorige pagina")
5370 ("pt" :default "Continuação da página anterior")
5371 ("ru" :html "(&#1055;&#1088;&#1086;&#1076;&#1086;&#1083;&#1078;&#1077;&#1085;&#1080;&#1077;)"
5372 :utf-8 "(Продолжение)"))
5373 ("Continued on next page"
5374 ("de" :default "Fortsetzung nächste Seite")
5375 ("es" :default "Continúa en la siguiente página")
5376 ("fr" :default "Suite page suivante")
5377 ("it" :default "Continua alla pagina successiva")
5378 ("ja" :default "次ページに続く")
5379 ("nl" :default "Vervolg op volgende pagina")
5380 ("pt" :default "Continua na página seguinte")
5381 ("ru" :html "(&#1055;&#1088;&#1086;&#1076;&#1086;&#1083;&#1078;&#1077;&#1085;&#1080;&#1077; &#1089;&#1083;&#1077;&#1076;&#1091;&#1077;&#1090;)"
5382 :utf-8 "(Продолжение следует)"))
5383 ("Date"
5384 ("ca" :default "Data")
5385 ("cs" :default "Datum")
5386 ("da" :default "Dato")
5387 ("de" :default "Datum")
5388 ("eo" :default "Dato")
5389 ("es" :default "Fecha")
5390 ("et" :html "Kuup&#228;ev" :utf-8 "Kuupäev")
5391 ("fi" :html "P&auml;iv&auml;m&auml;&auml;r&auml;")
5392 ("hu" :html "D&aacute;tum")
5393 ("is" :default "Dagsetning")
5394 ("it" :default "Data")
5395 ("ja" :default "日付" :html "&#26085;&#20184;")
5396 ("nl" :default "Datum")
5397 ("no" :default "Dato")
5398 ("nb" :default "Dato")
5399 ("nn" :default "Dato")
5400 ("pl" :default "Data")
5401 ("ru" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5402 ("sv" :default "Datum")
5403 ("uk" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5404 ("zh-CN" :html "&#26085;&#26399;" :utf-8 "日期")
5405 ("zh-TW" :html "&#26085;&#26399;" :utf-8 "日期"))
5406 ("Equation"
5407 ("da" :default "Ligning")
5408 ("de" :default "Gleichung")
5409 ("es" :html "Ecuaci&oacute;n" :default "Ecuación")
5410 ("et" :html "V&#245;rrand" :utf-8 "Võrrand")
5411 ("fr" :ascii "Equation" :default "Équation")
5412 ("ja" :default "方程式")
5413 ("no" :default "Ligning")
5414 ("nb" :default "Ligning")
5415 ("nn" :default "Likning")
5416 ("ru" :html "&#1059;&#1088;&#1072;&#1074;&#1085;&#1077;&#1085;&#1080;&#1077;"
5417 :utf-8 "Уравнение")
5418 ("sv" :default "Ekvation")
5419 ("zh-CN" :html "&#26041;&#31243;" :utf-8 "方程"))
5420 ("Figure"
5421 ("da" :default "Figur")
5422 ("de" :default "Abbildung")
5423 ("es" :default "Figura")
5424 ("et" :default "Joonis")
5425 ("ja" :default "図" :html "&#22259;")
5426 ("no" :default "Illustrasjon")
5427 ("nb" :default "Illustrasjon")
5428 ("nn" :default "Illustrasjon")
5429 ("ru" :html "&#1056;&#1080;&#1089;&#1091;&#1085;&#1086;&#1082;" :utf-8 "Рисунок")
5430 ("sv" :default "Illustration")
5431 ("zh-CN" :html "&#22270;" :utf-8 "图"))
5432 ("Figure %d:"
5433 ("da" :default "Figur %d")
5434 ("de" :default "Abbildung %d:")
5435 ("es" :default "Figura %d:")
5436 ("et" :default "Joonis %d:")
5437 ("fr" :default "Figure %d :" :html "Figure&nbsp;%d&nbsp;:")
5438 ("ja" :default "図%d: " :html "&#22259;%d: ")
5439 ("no" :default "Illustrasjon %d")
5440 ("nb" :default "Illustrasjon %d")
5441 ("nn" :default "Illustrasjon %d")
5442 ("ru" :html "&#1056;&#1080;&#1089;. %d.:" :utf-8 "Рис. %d.:")
5443 ("sv" :default "Illustration %d")
5444 ("zh-CN" :html "&#22270;%d&nbsp;" :utf-8 "图%d "))
5445 ("Footnotes"
5446 ("ca" :html "Peus de p&agrave;gina")
5447 ("cs" :default "Pozn\xe1mky pod carou")
5448 ("da" :default "Fodnoter")
5449 ("de" :html "Fu&szlig;noten" :default "Fußnoten")
5450 ("eo" :default "Piednotoj")
5451 ("es" :html "Nota al pie de p&aacute;gina" :default "Nota al pie de página")
5452 ("et" :html "Allm&#228;rkused" :utf-8 "Allmärkused")
5453 ("fi" :default "Alaviitteet")
5454 ("fr" :default "Notes de bas de page")
5455 ("hu" :html "L&aacute;bjegyzet")
5456 ("is" :html "Aftanm&aacute;lsgreinar")
5457 ("it" :html "Note a pi&egrave; di pagina")
5458 ("ja" :default "脚注" :html "&#33050;&#27880;")
5459 ("nl" :default "Voetnoten")
5460 ("no" :default "Fotnoter")
5461 ("nb" :default "Fotnoter")
5462 ("nn" :default "Fotnotar")
5463 ("pl" :default "Przypis")
5464 ("ru" :html "&#1057;&#1085;&#1086;&#1089;&#1082;&#1080;" :utf-8 "Сноски")
5465 ("sv" :default "Fotnoter")
5466 ("uk" :html "&#1055;&#1088;&#1080;&#1084;&#1110;&#1090;&#1082;&#1080;"
5467 :utf-8 "Примітки")
5468 ("zh-CN" :html "&#33050;&#27880;" :utf-8 "脚注")
5469 ("zh-TW" :html "&#33139;&#35387;" :utf-8 "腳註"))
5470 ("List of Listings"
5471 ("da" :default "Programmer")
5472 ("de" :default "Programmauflistungsverzeichnis")
5473 ("es" :default "Indice de Listados de programas")
5474 ("et" :default "Loendite nimekiri")
5475 ("fr" :default "Liste des programmes")
5476 ("ja" :default "ソースコード目次")
5477 ("no" :default "Dataprogrammer")
5478 ("nb" :default "Dataprogrammer")
5479 ("ru" :html "&#1057;&#1087;&#1080;&#1089;&#1086;&#1082; &#1088;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1086;&#1082;"
5480 :utf-8 "Список распечаток")
5481 ("zh-CN" :html "&#20195;&#30721;&#30446;&#24405;" :utf-8 "代码目录"))
5482 ("List of Tables"
5483 ("da" :default "Tabeller")
5484 ("de" :default "Tabellenverzeichnis")
5485 ("es" :default "Indice de tablas")
5486 ("et" :default "Tabelite nimekiri")
5487 ("fr" :default "Liste des tableaux")
5488 ("ja" :default "表目次")
5489 ("no" :default "Tabeller")
5490 ("nb" :default "Tabeller")
5491 ("nn" :default "Tabeller")
5492 ("ru" :html "&#1057;&#1087;&#1080;&#1089;&#1086;&#1082; &#1090;&#1072;&#1073;&#1083;&#1080;&#1094;"
5493 :utf-8 "Список таблиц")
5494 ("sv" :default "Tabeller")
5495 ("zh-CN" :html "&#34920;&#26684;&#30446;&#24405;" :utf-8 "表格目录"))
5496 ("Listing %d:"
5497 ("da" :default "Program %d")
5498 ("de" :default "Programmlisting %d")
5499 ("es" :default "Listado de programa %d")
5500 ("et" :default "Loend %d")
5501 ("fr" :default "Programme %d :" :html "Programme&nbsp;%d&nbsp;:")
5502 ("ja" :default "ソースコード%d:")
5503 ("no" :default "Dataprogram %d")
5504 ("nb" :default "Dataprogram %d")
5505 ("ru" :html "&#1056;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1082;&#1072; %d.:"
5506 :utf-8 "Распечатка %d.:")
5507 ("zh-CN" :html "&#20195;&#30721;%d&nbsp;" :utf-8 "代码%d "))
5508 ("References"
5509 ("fr" :ascii "References" :default "Références")
5510 ("de" :default "Quellen"))
5511 ("See section %s"
5512 ("da" :default "jævnfør afsnit %s")
5513 ("de" :default "siehe Abschnitt %s")
5514 ("es" :default "vea seccion %s")
5515 ("et" :html "Vaata peat&#252;kki %s" :utf-8 "Vaata peatükki %s")
5516 ("fr" :default "cf. section %s")
5517 ("ja" :default "セクション %s を参照")
5518 ("ru" :html "&#1057;&#1084;. &#1088;&#1072;&#1079;&#1076;&#1077;&#1083; %s"
5519 :utf-8 "См. раздел %s")
5520 ("zh-CN" :html "&#21442;&#35265;&#31532;%s&#33410;" :utf-8 "参见第%s节"))
5521 ("Table"
5522 ("de" :default "Tabelle")
5523 ("es" :default "Tabla")
5524 ("et" :default "Tabel")
5525 ("fr" :default "Tableau")
5526 ("ja" :default "表" :html "&#34920;")
5527 ("ru" :html "&#1058;&#1072;&#1073;&#1083;&#1080;&#1094;&#1072;" :utf-8 "Таблица")
5528 ("zh-CN" :html "&#34920;" :utf-8 "表"))
5529 ("Table %d:"
5530 ("da" :default "Tabel %d")
5531 ("de" :default "Tabelle %d")
5532 ("es" :default "Tabla %d")
5533 ("et" :default "Tabel %d")
5534 ("fr" :default "Tableau %d :")
5535 ("ja" :default "表%d:" :html "&#34920;%d:")
5536 ("no" :default "Tabell %d")
5537 ("nb" :default "Tabell %d")
5538 ("nn" :default "Tabell %d")
5539 ("ru" :html "&#1058;&#1072;&#1073;&#1083;&#1080;&#1094;&#1072; %d.:"
5540 :utf-8 "Таблица %d.:")
5541 ("sv" :default "Tabell %d")
5542 ("zh-CN" :html "&#34920;%d&nbsp;" :utf-8 "表%d "))
5543 ("Table of Contents"
5544 ("ca" :html "&Iacute;ndex")
5545 ("cs" :default "Obsah")
5546 ("da" :default "Indhold")
5547 ("de" :default "Inhaltsverzeichnis")
5548 ("eo" :default "Enhavo")
5549 ("es" :html "&Iacute;ndice")
5550 ("et" :default "Sisukord")
5551 ("fi" :html "Sis&auml;llysluettelo")
5552 ("fr" :ascii "Sommaire" :default "Table des matières")
5553 ("hu" :html "Tartalomjegyz&eacute;k")
5554 ("is" :default "Efnisyfirlit")
5555 ("it" :default "Indice")
5556 ("ja" :default "目次" :html "&#30446;&#27425;")
5557 ("nl" :default "Inhoudsopgave")
5558 ("no" :default "Innhold")
5559 ("nb" :default "Innhold")
5560 ("nn" :default "Innhald")
5561 ("pl" :html "Spis tre&#x015b;ci")
5562 ("ru" :html "&#1057;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1077;"
5563 :utf-8 "Содержание")
5564 ("sv" :html "Inneh&aring;ll")
5565 ("uk" :html "&#1047;&#1084;&#1110;&#1089;&#1090;" :utf-8 "Зміст")
5566 ("zh-CN" :html "&#30446;&#24405;" :utf-8 "目录")
5567 ("zh-TW" :html "&#30446;&#37636;" :utf-8 "目錄"))
5568 ("Unknown reference"
5569 ("da" :default "ukendt reference")
5570 ("de" :default "Unbekannter Verweis")
5571 ("es" :default "referencia desconocida")
5572 ("et" :default "Tundmatu viide")
5573 ("fr" :ascii "Destination inconnue" :default "Référence inconnue")
5574 ("ja" :default "不明な参照先")
5575 ("ru" :html "&#1053;&#1077;&#1080;&#1079;&#1074;&#1077;&#1089;&#1090;&#1085;&#1072;&#1103; &#1089;&#1089;&#1099;&#1083;&#1082;&#1072;"
5576 :utf-8 "Неизвестная ссылка")
5577 ("zh-CN" :html "&#26410;&#30693;&#24341;&#29992;" :utf-8 "未知引用")))
5578 "Dictionary for export engine.
5580 Alist whose CAR is the string to translate and CDR is an alist
5581 whose CAR is the language string and CDR is a plist whose
5582 properties are possible charsets and values translated terms.
5584 It is used as a database for `org-export-translate'. Since this
5585 function returns the string as-is if no translation was found,
5586 the variable only needs to record values different from the
5587 entry.")
5589 (defun org-export-translate (s encoding info)
5590 "Translate string S according to language specification.
5592 ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1'
5593 and `:utf-8'. INFO is a plist used as a communication channel.
5595 Translation depends on `:language' property. Return the
5596 translated string. If no translation is found, try to fall back
5597 to `:default' encoding. If it fails, return S."
5598 (let* ((lang (plist-get info :language))
5599 (translations (cdr (assoc lang
5600 (cdr (assoc s org-export-dictionary))))))
5601 (or (plist-get translations encoding)
5602 (plist-get translations :default)
5603 s)))
5607 ;;; Asynchronous Export
5609 ;; `org-export-async-start' is the entry point for asynchronous
5610 ;; export. It recreates current buffer (including visibility,
5611 ;; narrowing and visited file) in an external Emacs process, and
5612 ;; evaluates a command there. It then applies a function on the
5613 ;; returned results in the current process.
5615 ;; At a higher level, `org-export-to-buffer' and `org-export-to-file'
5616 ;; allow to export to a buffer or a file, asynchronously or not.
5618 ;; `org-export-output-file-name' is an auxiliary function meant to be
5619 ;; used with `org-export-to-file'. With a given extension, it tries
5620 ;; to provide a canonical file name to write export output to.
5622 ;; Asynchronously generated results are never displayed directly.
5623 ;; Instead, they are stored in `org-export-stack-contents'. They can
5624 ;; then be retrieved by calling `org-export-stack'.
5626 ;; Export Stack is viewed through a dedicated major mode
5627 ;;`org-export-stack-mode' and tools: `org-export-stack-refresh',
5628 ;;`org-export-stack-delete', `org-export-stack-view' and
5629 ;;`org-export-stack-clear'.
5631 ;; For back-ends, `org-export-add-to-stack' add a new source to stack.
5632 ;; It should be used whenever `org-export-async-start' is called.
5634 (defmacro org-export-async-start (fun &rest body)
5635 "Call function FUN on the results returned by BODY evaluation.
5637 BODY evaluation happens in an asynchronous process, from a buffer
5638 which is an exact copy of the current one.
5640 Use `org-export-add-to-stack' in FUN in order to register results
5641 in the stack.
5643 This is a low level function. See also `org-export-to-buffer'
5644 and `org-export-to-file' for more specialized functions."
5645 (declare (indent 1) (debug t))
5646 (org-with-gensyms (process temp-file copy-fun proc-buffer coding)
5647 ;; Write the full sexp evaluating BODY in a copy of the current
5648 ;; buffer to a temporary file, as it may be too long for program
5649 ;; args in `start-process'.
5650 `(with-temp-message "Initializing asynchronous export process"
5651 (let ((,copy-fun (org-export--generate-copy-script (current-buffer)))
5652 (,temp-file (make-temp-file "org-export-process"))
5653 (,coding buffer-file-coding-system))
5654 (with-temp-file ,temp-file
5655 (insert
5656 ;; Null characters (from variable values) are inserted
5657 ;; within the file. As a consequence, coding system for
5658 ;; buffer contents will not be recognized properly. So,
5659 ;; we make sure it is the same as the one used to display
5660 ;; the original buffer.
5661 (format ";; -*- coding: %s; -*-\n%S"
5662 ,coding
5663 `(with-temp-buffer
5664 (when org-export-async-debug '(setq debug-on-error t))
5665 ;; Ignore `kill-emacs-hook' and code evaluation
5666 ;; queries from Babel as we need a truly
5667 ;; non-interactive process.
5668 (setq kill-emacs-hook nil
5669 org-babel-confirm-evaluate-answer-no t)
5670 ;; Initialize export framework.
5671 (require 'ox)
5672 ;; Re-create current buffer there.
5673 (funcall ,,copy-fun)
5674 (restore-buffer-modified-p nil)
5675 ;; Sexp to evaluate in the buffer.
5676 (print (progn ,,@body))))))
5677 ;; Start external process.
5678 (let* ((process-connection-type nil)
5679 (,proc-buffer (generate-new-buffer-name "*Org Export Process*"))
5680 (,process
5681 (apply
5682 #'start-process
5683 (append
5684 (list "org-export-process"
5685 ,proc-buffer
5686 (expand-file-name invocation-name invocation-directory)
5687 "--batch")
5688 (if org-export-async-init-file
5689 (list "-Q" "-l" org-export-async-init-file)
5690 (list "-l" user-init-file))
5691 (list "-l" ,temp-file)))))
5692 ;; Register running process in stack.
5693 (org-export-add-to-stack (get-buffer ,proc-buffer) nil ,process)
5694 ;; Set-up sentinel in order to catch results.
5695 (let ((handler ,fun))
5696 (set-process-sentinel
5697 ,process
5698 `(lambda (p status)
5699 (let ((proc-buffer (process-buffer p)))
5700 (when (eq (process-status p) 'exit)
5701 (unwind-protect
5702 (if (zerop (process-exit-status p))
5703 (unwind-protect
5704 (let ((results
5705 (with-current-buffer proc-buffer
5706 (goto-char (point-max))
5707 (backward-sexp)
5708 (read (current-buffer)))))
5709 (funcall ,handler results))
5710 (unless org-export-async-debug
5711 (and (get-buffer proc-buffer)
5712 (kill-buffer proc-buffer))))
5713 (org-export-add-to-stack proc-buffer nil p)
5714 (ding)
5715 (message "Process '%s' exited abnormally" p))
5716 (unless org-export-async-debug
5717 (delete-file ,,temp-file)))))))))))))
5719 ;;;###autoload
5720 (defun org-export-to-buffer
5721 (backend buffer
5722 &optional async subtreep visible-only body-only ext-plist
5723 post-process)
5724 "Call `org-export-as' with output to a specified buffer.
5726 BACKEND is either an export back-end, as returned by, e.g.,
5727 `org-export-create-backend', or a symbol referring to
5728 a registered back-end.
5730 BUFFER is the name of the output buffer. If it already exists,
5731 it will be erased first, otherwise, it will be created.
5733 A non-nil optional argument ASYNC means the process should happen
5734 asynchronously. The resulting buffer should then be accessible
5735 through the `org-export-stack' interface. When ASYNC is nil, the
5736 buffer is displayed if `org-export-show-temporary-export-buffer'
5737 is non-nil.
5739 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
5740 EXT-PLIST are similar to those used in `org-export-as', which
5741 see.
5743 Optional argument POST-PROCESS is a function which should accept
5744 no argument. It is always called within the current process,
5745 from BUFFER, with point at its beginning. Export back-ends can
5746 use it to set a major mode there, e.g,
5748 \(defun org-latex-export-as-latex
5749 \(&optional async subtreep visible-only body-only ext-plist)
5750 \(interactive)
5751 \(org-export-to-buffer 'latex \"*Org LATEX Export*\"
5752 async subtreep visible-only body-only ext-plist (lambda () (LaTeX-mode))))
5754 This function returns BUFFER."
5755 (declare (indent 2))
5756 (if async
5757 (org-export-async-start
5758 `(lambda (output)
5759 (with-current-buffer (get-buffer-create ,buffer)
5760 (erase-buffer)
5761 (setq buffer-file-coding-system ',buffer-file-coding-system)
5762 (insert output)
5763 (goto-char (point-min))
5764 (org-export-add-to-stack (current-buffer) ',backend)
5765 (ignore-errors (funcall ,post-process))))
5766 `(org-export-as
5767 ',backend ,subtreep ,visible-only ,body-only ',ext-plist))
5768 (let ((output
5769 (org-export-as backend subtreep visible-only body-only ext-plist))
5770 (buffer (get-buffer-create buffer))
5771 (encoding buffer-file-coding-system))
5772 (when (and (org-string-nw-p output) (org-export--copy-to-kill-ring-p))
5773 (org-kill-new output))
5774 (with-current-buffer buffer
5775 (erase-buffer)
5776 (setq buffer-file-coding-system encoding)
5777 (insert output)
5778 (goto-char (point-min))
5779 (and (functionp post-process) (funcall post-process)))
5780 (when org-export-show-temporary-export-buffer
5781 (switch-to-buffer-other-window buffer))
5782 buffer)))
5784 ;;;###autoload
5785 (defun org-export-to-file
5786 (backend file &optional async subtreep visible-only body-only ext-plist
5787 post-process)
5788 "Call `org-export-as' with output to a specified file.
5790 BACKEND is either an export back-end, as returned by, e.g.,
5791 `org-export-create-backend', or a symbol referring to
5792 a registered back-end. FILE is the name of the output file, as
5793 a string.
5795 A non-nil optional argument ASYNC means the process should happen
5796 asynchronously. The resulting buffer will then be accessible
5797 through the `org-export-stack' interface.
5799 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
5800 EXT-PLIST are similar to those used in `org-export-as', which
5801 see.
5803 Optional argument POST-PROCESS is called with FILE as its
5804 argument and happens asynchronously when ASYNC is non-nil. It
5805 has to return a file name, or nil. Export back-ends can use this
5806 to send the output file through additional processing, e.g,
5808 \(defun org-latex-export-to-latex
5809 \(&optional async subtreep visible-only body-only ext-plist)
5810 \(interactive)
5811 \(let ((outfile (org-export-output-file-name \".tex\" subtreep)))
5812 \(org-export-to-file 'latex outfile
5813 async subtreep visible-only body-only ext-plist
5814 \(lambda (file) (org-latex-compile file)))
5816 The function returns either a file name returned by POST-PROCESS,
5817 or FILE."
5818 (declare (indent 2))
5819 (if (not (file-writable-p file)) (error "Output file not writable")
5820 (let ((encoding (or org-export-coding-system buffer-file-coding-system)))
5821 (if async
5822 (org-export-async-start
5823 `(lambda (file)
5824 (org-export-add-to-stack (expand-file-name file) ',backend))
5825 `(let ((output
5826 (org-export-as
5827 ',backend ,subtreep ,visible-only ,body-only
5828 ',ext-plist)))
5829 (with-temp-buffer
5830 (insert output)
5831 (let ((coding-system-for-write ',encoding))
5832 (write-file ,file)))
5833 (or (ignore-errors (funcall ',post-process ,file)) ,file)))
5834 (let ((output (org-export-as
5835 backend subtreep visible-only body-only ext-plist)))
5836 (with-temp-buffer
5837 (insert output)
5838 (let ((coding-system-for-write encoding))
5839 (write-file file)))
5840 (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p output))
5841 (org-kill-new output))
5842 ;; Get proper return value.
5843 (or (and (functionp post-process) (funcall post-process file))
5844 file))))))
5846 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
5847 "Return output file's name according to buffer specifications.
5849 EXTENSION is a string representing the output file extension,
5850 with the leading dot.
5852 With a non-nil optional argument SUBTREEP, try to determine
5853 output file's name by looking for \"EXPORT_FILE_NAME\" property
5854 of subtree at point.
5856 When optional argument PUB-DIR is set, use it as the publishing
5857 directory.
5859 When optional argument VISIBLE-ONLY is non-nil, don't export
5860 contents of hidden elements.
5862 Return file name as a string."
5863 (let* ((visited-file (buffer-file-name (buffer-base-buffer)))
5864 (base-name
5865 ;; File name may come from EXPORT_FILE_NAME subtree
5866 ;; property, assuming point is at beginning of said
5867 ;; sub-tree.
5868 (file-name-sans-extension
5869 (or (and subtreep
5870 (org-entry-get
5871 (save-excursion
5872 (ignore-errors (org-back-to-heading) (point)))
5873 "EXPORT_FILE_NAME" t))
5874 ;; File name may be extracted from buffer's associated
5875 ;; file, if any.
5876 (and visited-file (file-name-nondirectory visited-file))
5877 ;; Can't determine file name on our own: Ask user.
5878 (let ((read-file-name-function
5879 (and org-completion-use-ido 'ido-read-file-name)))
5880 (read-file-name
5881 "Output file: " pub-dir nil nil nil
5882 (lambda (name)
5883 (string= (file-name-extension name t) extension)))))))
5884 (output-file
5885 ;; Build file name. Enforce EXTENSION over whatever user
5886 ;; may have come up with. PUB-DIR, if defined, always has
5887 ;; precedence over any provided path.
5888 (cond
5889 (pub-dir
5890 (concat (file-name-as-directory pub-dir)
5891 (file-name-nondirectory base-name)
5892 extension))
5893 ((file-name-absolute-p base-name) (concat base-name extension))
5894 (t (concat (file-name-as-directory ".") base-name extension)))))
5895 ;; If writing to OUTPUT-FILE would overwrite original file, append
5896 ;; EXTENSION another time to final name.
5897 (if (and visited-file (org-file-equal-p visited-file output-file))
5898 (concat output-file extension)
5899 output-file)))
5901 (defun org-export-add-to-stack (source backend &optional process)
5902 "Add a new result to export stack if not present already.
5904 SOURCE is a buffer or a file name containing export results.
5905 BACKEND is a symbol representing export back-end used to generate
5908 Entries already pointing to SOURCE and unavailable entries are
5909 removed beforehand. Return the new stack."
5910 (setq org-export-stack-contents
5911 (cons (list source backend (or process (current-time)))
5912 (org-export-stack-remove source))))
5914 (defun org-export-stack ()
5915 "Menu for asynchronous export results and running processes."
5916 (interactive)
5917 (let ((buffer (get-buffer-create "*Org Export Stack*")))
5918 (set-buffer buffer)
5919 (when (zerop (buffer-size)) (org-export-stack-mode))
5920 (org-export-stack-refresh)
5921 (pop-to-buffer buffer))
5922 (message "Type \"q\" to quit, \"?\" for help"))
5924 (defun org-export--stack-source-at-point ()
5925 "Return source from export results at point in stack."
5926 (let ((source (car (nth (1- (org-current-line)) org-export-stack-contents))))
5927 (if (not source) (error "Source unavailable, please refresh buffer")
5928 (let ((source-name (if (stringp source) source (buffer-name source))))
5929 (if (save-excursion
5930 (beginning-of-line)
5931 (looking-at (concat ".* +" (regexp-quote source-name) "$")))
5932 source
5933 ;; SOURCE is not consistent with current line. The stack
5934 ;; view is outdated.
5935 (error "Source unavailable; type `g' to update buffer"))))))
5937 (defun org-export-stack-clear ()
5938 "Remove all entries from export stack."
5939 (interactive)
5940 (setq org-export-stack-contents nil))
5942 (defun org-export-stack-refresh (&rest dummy)
5943 "Refresh the asynchronous export stack.
5944 DUMMY is ignored. Unavailable sources are removed from the list.
5945 Return the new stack."
5946 (let ((inhibit-read-only t))
5947 (org-preserve-lc
5948 (erase-buffer)
5949 (insert (concat
5950 (let ((counter 0))
5951 (mapconcat
5952 (lambda (entry)
5953 (let ((proc-p (processp (nth 2 entry))))
5954 (concat
5955 ;; Back-end.
5956 (format " %-12s " (or (nth 1 entry) ""))
5957 ;; Age.
5958 (let ((data (nth 2 entry)))
5959 (if proc-p (format " %6s " (process-status data))
5960 ;; Compute age of the results.
5961 (org-format-seconds
5962 "%4h:%.2m "
5963 (float-time (time-since data)))))
5964 ;; Source.
5965 (format " %s"
5966 (let ((source (car entry)))
5967 (if (stringp source) source
5968 (buffer-name source)))))))
5969 ;; Clear stack from exited processes, dead buffers or
5970 ;; non-existent files.
5971 (setq org-export-stack-contents
5972 (org-remove-if-not
5973 (lambda (el)
5974 (if (processp (nth 2 el))
5975 (buffer-live-p (process-buffer (nth 2 el)))
5976 (let ((source (car el)))
5977 (if (bufferp source) (buffer-live-p source)
5978 (file-exists-p source)))))
5979 org-export-stack-contents)) "\n")))))))
5981 (defun org-export-stack-remove (&optional source)
5982 "Remove export results at point from stack.
5983 If optional argument SOURCE is non-nil, remove it instead."
5984 (interactive)
5985 (let ((source (or source (org-export--stack-source-at-point))))
5986 (setq org-export-stack-contents
5987 (org-remove-if (lambda (el) (equal (car el) source))
5988 org-export-stack-contents))))
5990 (defun org-export-stack-view (&optional in-emacs)
5991 "View export results at point in stack.
5992 With an optional prefix argument IN-EMACS, force viewing files
5993 within Emacs."
5994 (interactive "P")
5995 (let ((source (org-export--stack-source-at-point)))
5996 (cond ((processp source)
5997 (org-switch-to-buffer-other-window (process-buffer source)))
5998 ((bufferp source) (org-switch-to-buffer-other-window source))
5999 (t (org-open-file source in-emacs)))))
6001 (defvar org-export-stack-mode-map
6002 (let ((km (make-sparse-keymap)))
6003 (define-key km " " 'next-line)
6004 (define-key km "n" 'next-line)
6005 (define-key km "\C-n" 'next-line)
6006 (define-key km [down] 'next-line)
6007 (define-key km "p" 'previous-line)
6008 (define-key km "\C-p" 'previous-line)
6009 (define-key km "\C-?" 'previous-line)
6010 (define-key km [up] 'previous-line)
6011 (define-key km "C" 'org-export-stack-clear)
6012 (define-key km "v" 'org-export-stack-view)
6013 (define-key km (kbd "RET") 'org-export-stack-view)
6014 (define-key km "d" 'org-export-stack-remove)
6016 "Keymap for Org Export Stack.")
6018 (define-derived-mode org-export-stack-mode special-mode "Org-Stack"
6019 "Mode for displaying asynchronous export stack.
6021 Type \\[org-export-stack] to visualize the asynchronous export
6022 stack.
6024 In an Org Export Stack buffer, use \\<org-export-stack-mode-map>\\[org-export-stack-view] to view export output
6025 on current line, \\[org-export-stack-remove] to remove it from the stack and \\[org-export-stack-clear] to clear
6026 stack completely.
6028 Removing entries in an Org Export Stack buffer doesn't affect
6029 files or buffers, only the display.
6031 \\{org-export-stack-mode-map}"
6032 (abbrev-mode 0)
6033 (auto-fill-mode 0)
6034 (setq buffer-read-only t
6035 buffer-undo-list t
6036 truncate-lines t
6037 header-line-format
6038 '(:eval
6039 (format " %-12s | %6s | %s" "Back-End" "Age" "Source")))
6040 (org-add-hook 'post-command-hook 'org-export-stack-refresh nil t)
6041 (set (make-local-variable 'revert-buffer-function)
6042 'org-export-stack-refresh))
6046 ;;; The Dispatcher
6048 ;; `org-export-dispatch' is the standard interactive way to start an
6049 ;; export process. It uses `org-export--dispatch-ui' as a subroutine
6050 ;; for its interface, which, in turn, delegates response to key
6051 ;; pressed to `org-export--dispatch-action'.
6053 ;;;###autoload
6054 (defun org-export-dispatch (&optional arg)
6055 "Export dispatcher for Org mode.
6057 It provides an access to common export related tasks in a buffer.
6058 Its interface comes in two flavors: standard and expert.
6060 While both share the same set of bindings, only the former
6061 displays the valid keys associations in a dedicated buffer.
6062 Scrolling (resp. line-wise motion) in this buffer is done with
6063 SPC and DEL (resp. C-n and C-p) keys.
6065 Set variable `org-export-dispatch-use-expert-ui' to switch to one
6066 flavor or the other.
6068 When ARG is \\[universal-argument], repeat the last export action, with the same set
6069 of options used back then, on the current buffer.
6071 When ARG is \\[universal-argument] \\[universal-argument], display the asynchronous export stack."
6072 (interactive "P")
6073 (let* ((input
6074 (cond ((equal arg '(16)) '(stack))
6075 ((and arg org-export-dispatch-last-action))
6076 (t (save-window-excursion
6077 (unwind-protect
6078 (progn
6079 ;; Remember where we are
6080 (move-marker org-export-dispatch-last-position
6081 (point)
6082 (org-base-buffer (current-buffer)))
6083 ;; Get and store an export command
6084 (setq org-export-dispatch-last-action
6085 (org-export--dispatch-ui
6086 (list org-export-initial-scope
6087 (and org-export-in-background 'async))
6089 org-export-dispatch-use-expert-ui)))
6090 (and (get-buffer "*Org Export Dispatcher*")
6091 (kill-buffer "*Org Export Dispatcher*")))))))
6092 (action (car input))
6093 (optns (cdr input)))
6094 (unless (memq 'subtree optns)
6095 (move-marker org-export-dispatch-last-position nil))
6096 (case action
6097 ;; First handle special hard-coded actions.
6098 (template (org-export-insert-default-template nil optns))
6099 (stack (org-export-stack))
6100 (publish-current-file
6101 (org-publish-current-file (memq 'force optns) (memq 'async optns)))
6102 (publish-current-project
6103 (org-publish-current-project (memq 'force optns) (memq 'async optns)))
6104 (publish-choose-project
6105 (org-publish (assoc (org-icompleting-read
6106 "Publish project: "
6107 org-publish-project-alist nil t)
6108 org-publish-project-alist)
6109 (memq 'force optns)
6110 (memq 'async optns)))
6111 (publish-all (org-publish-all (memq 'force optns) (memq 'async optns)))
6112 (otherwise
6113 (save-excursion
6114 (when arg
6115 ;; Repeating command, maybe move cursor to restore subtree
6116 ;; context.
6117 (if (eq (marker-buffer org-export-dispatch-last-position)
6118 (org-base-buffer (current-buffer)))
6119 (goto-char org-export-dispatch-last-position)
6120 ;; We are in a different buffer, forget position.
6121 (move-marker org-export-dispatch-last-position nil)))
6122 (funcall action
6123 ;; Return a symbol instead of a list to ease
6124 ;; asynchronous export macro use.
6125 (and (memq 'async optns) t)
6126 (and (memq 'subtree optns) t)
6127 (and (memq 'visible optns) t)
6128 (and (memq 'body optns) t)))))))
6130 (defun org-export--dispatch-ui (options first-key expertp)
6131 "Handle interface for `org-export-dispatch'.
6133 OPTIONS is a list containing current interactive options set for
6134 export. It can contain any of the following symbols:
6135 `body' toggles a body-only export
6136 `subtree' restricts export to current subtree
6137 `visible' restricts export to visible part of buffer.
6138 `force' force publishing files.
6139 `async' use asynchronous export process
6141 FIRST-KEY is the key pressed to select the first level menu. It
6142 is nil when this menu hasn't been selected yet.
6144 EXPERTP, when non-nil, triggers expert UI. In that case, no help
6145 buffer is provided, but indications about currently active
6146 options are given in the prompt. Moreover, \[?] allows to switch
6147 back to standard interface."
6148 (let* ((fontify-key
6149 (lambda (key &optional access-key)
6150 ;; Fontify KEY string. Optional argument ACCESS-KEY, when
6151 ;; non-nil is the required first-level key to activate
6152 ;; KEY. When its value is t, activate KEY independently
6153 ;; on the first key, if any. A nil value means KEY will
6154 ;; only be activated at first level.
6155 (if (or (eq access-key t) (eq access-key first-key))
6156 (org-propertize key 'face 'org-warning)
6157 key)))
6158 (fontify-value
6159 (lambda (value)
6160 ;; Fontify VALUE string.
6161 (org-propertize value 'face 'font-lock-variable-name-face)))
6162 ;; Prepare menu entries by extracting them from registered
6163 ;; back-ends and sorting them by access key and by ordinal,
6164 ;; if any.
6165 (entries
6166 (sort (sort (delq nil
6167 (mapcar 'org-export-backend-menu
6168 org-export--registered-backends))
6169 (lambda (a b)
6170 (let ((key-a (nth 1 a))
6171 (key-b (nth 1 b)))
6172 (cond ((and (numberp key-a) (numberp key-b))
6173 (< key-a key-b))
6174 ((numberp key-b) t)))))
6175 'car-less-than-car))
6176 ;; Compute a list of allowed keys based on the first key
6177 ;; pressed, if any. Some keys
6178 ;; (?^B, ?^V, ?^S, ?^F, ?^A, ?&, ?# and ?q) are always
6179 ;; available.
6180 (allowed-keys
6181 (nconc (list 2 22 19 6 1)
6182 (if (not first-key) (org-uniquify (mapcar 'car entries))
6183 (let (sub-menu)
6184 (dolist (entry entries (sort (mapcar 'car sub-menu) '<))
6185 (when (eq (car entry) first-key)
6186 (setq sub-menu (append (nth 2 entry) sub-menu))))))
6187 (cond ((eq first-key ?P) (list ?f ?p ?x ?a))
6188 ((not first-key) (list ?P)))
6189 (list ?& ?#)
6190 (when expertp (list ??))
6191 (list ?q)))
6192 ;; Build the help menu for standard UI.
6193 (help
6194 (unless expertp
6195 (concat
6196 ;; Options are hard-coded.
6197 (format "[%s] Body only: %s [%s] Visible only: %s
6198 \[%s] Export scope: %s [%s] Force publishing: %s
6199 \[%s] Async export: %s\n\n"
6200 (funcall fontify-key "C-b" t)
6201 (funcall fontify-value
6202 (if (memq 'body options) "On " "Off"))
6203 (funcall fontify-key "C-v" t)
6204 (funcall fontify-value
6205 (if (memq 'visible options) "On " "Off"))
6206 (funcall fontify-key "C-s" t)
6207 (funcall fontify-value
6208 (if (memq 'subtree options) "Subtree" "Buffer "))
6209 (funcall fontify-key "C-f" t)
6210 (funcall fontify-value
6211 (if (memq 'force options) "On " "Off"))
6212 (funcall fontify-key "C-a" t)
6213 (funcall fontify-value
6214 (if (memq 'async options) "On " "Off")))
6215 ;; Display registered back-end entries. When a key
6216 ;; appears for the second time, do not create another
6217 ;; entry, but append its sub-menu to existing menu.
6218 (let (last-key)
6219 (mapconcat
6220 (lambda (entry)
6221 (let ((top-key (car entry)))
6222 (concat
6223 (unless (eq top-key last-key)
6224 (setq last-key top-key)
6225 (format "\n[%s] %s\n"
6226 (funcall fontify-key (char-to-string top-key))
6227 (nth 1 entry)))
6228 (let ((sub-menu (nth 2 entry)))
6229 (unless (functionp sub-menu)
6230 ;; Split sub-menu into two columns.
6231 (let ((index -1))
6232 (concat
6233 (mapconcat
6234 (lambda (sub-entry)
6235 (incf index)
6236 (format
6237 (if (zerop (mod index 2)) " [%s] %-26s"
6238 "[%s] %s\n")
6239 (funcall fontify-key
6240 (char-to-string (car sub-entry))
6241 top-key)
6242 (nth 1 sub-entry)))
6243 sub-menu "")
6244 (when (zerop (mod index 2)) "\n"))))))))
6245 entries ""))
6246 ;; Publishing menu is hard-coded.
6247 (format "\n[%s] Publish
6248 [%s] Current file [%s] Current project
6249 [%s] Choose project [%s] All projects\n\n\n"
6250 (funcall fontify-key "P")
6251 (funcall fontify-key "f" ?P)
6252 (funcall fontify-key "p" ?P)
6253 (funcall fontify-key "x" ?P)
6254 (funcall fontify-key "a" ?P))
6255 (format "[%s] Export stack [%s] Insert template\n"
6256 (funcall fontify-key "&" t)
6257 (funcall fontify-key "#" t))
6258 (format "[%s] %s"
6259 (funcall fontify-key "q" t)
6260 (if first-key "Main menu" "Exit")))))
6261 ;; Build prompts for both standard and expert UI.
6262 (standard-prompt (unless expertp "Export command: "))
6263 (expert-prompt
6264 (when expertp
6265 (format
6266 "Export command (C-%s%s%s%s%s) [%s]: "
6267 (if (memq 'body options) (funcall fontify-key "b" t) "b")
6268 (if (memq 'visible options) (funcall fontify-key "v" t) "v")
6269 (if (memq 'subtree options) (funcall fontify-key "s" t) "s")
6270 (if (memq 'force options) (funcall fontify-key "f" t) "f")
6271 (if (memq 'async options) (funcall fontify-key "a" t) "a")
6272 (mapconcat (lambda (k)
6273 ;; Strip control characters.
6274 (unless (< k 27) (char-to-string k)))
6275 allowed-keys "")))))
6276 ;; With expert UI, just read key with a fancy prompt. In standard
6277 ;; UI, display an intrusive help buffer.
6278 (if expertp
6279 (org-export--dispatch-action
6280 expert-prompt allowed-keys entries options first-key expertp)
6281 ;; At first call, create frame layout in order to display menu.
6282 (unless (get-buffer "*Org Export Dispatcher*")
6283 (delete-other-windows)
6284 (org-switch-to-buffer-other-window
6285 (get-buffer-create "*Org Export Dispatcher*"))
6286 (setq cursor-type nil
6287 header-line-format "Use SPC, DEL, C-n or C-p to navigate.")
6288 ;; Make sure that invisible cursor will not highlight square
6289 ;; brackets.
6290 (set-syntax-table (copy-syntax-table))
6291 (modify-syntax-entry ?\[ "w"))
6292 ;; At this point, the buffer containing the menu exists and is
6293 ;; visible in the current window. So, refresh it.
6294 (with-current-buffer "*Org Export Dispatcher*"
6295 ;; Refresh help. Maintain display continuity by re-visiting
6296 ;; previous window position.
6297 (let ((pos (window-start)))
6298 (erase-buffer)
6299 (insert help)
6300 (set-window-start nil pos)))
6301 (org-fit-window-to-buffer)
6302 (org-export--dispatch-action
6303 standard-prompt allowed-keys entries options first-key expertp))))
6305 (defun org-export--dispatch-action
6306 (prompt allowed-keys entries options first-key expertp)
6307 "Read a character from command input and act accordingly.
6309 PROMPT is the displayed prompt, as a string. ALLOWED-KEYS is
6310 a list of characters available at a given step in the process.
6311 ENTRIES is a list of menu entries. OPTIONS, FIRST-KEY and
6312 EXPERTP are the same as defined in `org-export--dispatch-ui',
6313 which see.
6315 Toggle export options when required. Otherwise, return value is
6316 a list with action as CAR and a list of interactive export
6317 options as CDR."
6318 (let (key)
6319 ;; Scrolling: when in non-expert mode, act on motion keys (C-n,
6320 ;; C-p, SPC, DEL).
6321 (while (and (setq key (read-char-exclusive prompt))
6322 (not expertp)
6323 (memq key '(14 16 ?\s ?\d)))
6324 (case key
6325 (14 (if (not (pos-visible-in-window-p (point-max)))
6326 (ignore-errors (scroll-up 1))
6327 (message "End of buffer")
6328 (sit-for 1)))
6329 (16 (if (not (pos-visible-in-window-p (point-min)))
6330 (ignore-errors (scroll-down 1))
6331 (message "Beginning of buffer")
6332 (sit-for 1)))
6333 (?\s (if (not (pos-visible-in-window-p (point-max)))
6334 (scroll-up nil)
6335 (message "End of buffer")
6336 (sit-for 1)))
6337 (?\d (if (not (pos-visible-in-window-p (point-min)))
6338 (scroll-down nil)
6339 (message "Beginning of buffer")
6340 (sit-for 1)))))
6341 (cond
6342 ;; Ignore undefined associations.
6343 ((not (memq key allowed-keys))
6344 (ding)
6345 (unless expertp (message "Invalid key") (sit-for 1))
6346 (org-export--dispatch-ui options first-key expertp))
6347 ;; q key at first level aborts export. At second level, cancel
6348 ;; first key instead.
6349 ((eq key ?q) (if (not first-key) (error "Export aborted")
6350 (org-export--dispatch-ui options nil expertp)))
6351 ;; Help key: Switch back to standard interface if expert UI was
6352 ;; active.
6353 ((eq key ??) (org-export--dispatch-ui options first-key nil))
6354 ;; Send request for template insertion along with export scope.
6355 ((eq key ?#) (cons 'template (memq 'subtree options)))
6356 ;; Switch to asynchronous export stack.
6357 ((eq key ?&) '(stack))
6358 ;; Toggle options: C-b (2) C-v (22) C-s (19) C-f (6) C-a (1).
6359 ((memq key '(2 22 19 6 1))
6360 (org-export--dispatch-ui
6361 (let ((option (case key (2 'body) (22 'visible) (19 'subtree)
6362 (6 'force) (1 'async))))
6363 (if (memq option options) (remq option options)
6364 (cons option options)))
6365 first-key expertp))
6366 ;; Action selected: Send key and options back to
6367 ;; `org-export-dispatch'.
6368 ((or first-key (functionp (nth 2 (assq key entries))))
6369 (cons (cond
6370 ((not first-key) (nth 2 (assq key entries)))
6371 ;; Publishing actions are hard-coded. Send a special
6372 ;; signal to `org-export-dispatch'.
6373 ((eq first-key ?P)
6374 (case key
6375 (?f 'publish-current-file)
6376 (?p 'publish-current-project)
6377 (?x 'publish-choose-project)
6378 (?a 'publish-all)))
6379 ;; Return first action associated to FIRST-KEY + KEY
6380 ;; path. Indeed, derived backends can share the same
6381 ;; FIRST-KEY.
6382 (t (catch 'found
6383 (mapc (lambda (entry)
6384 (let ((match (assq key (nth 2 entry))))
6385 (when match (throw 'found (nth 2 match)))))
6386 (member (assq first-key entries) entries)))))
6387 options))
6388 ;; Otherwise, enter sub-menu.
6389 (t (org-export--dispatch-ui options key expertp)))))
6393 (provide 'ox)
6395 ;; Local variables:
6396 ;; generated-autoload-file: "org-loaddefs.el"
6397 ;; End:
6399 ;;; ox.el ends here