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