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