ox-latex: Format-spec for hyperref and title
[org-mode.git] / lisp / ox.el
blob6a169974b9d062b2a6862b68c1cafd0bc72d953d
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-get-footnote-definition (footnote-reference info)
3575 "Return definition of FOOTNOTE-REFERENCE as parsed data.
3576 INFO is the plist used as a communication channel. If no such
3577 definition can be found, raise an error."
3578 (let ((label (org-element-property :label footnote-reference)))
3579 (or (if label
3580 (cdr (assoc label (plist-get info :footnote-definition-alist)))
3581 (org-element-contents footnote-reference))
3582 (error "Definition not found for footnote %s" label))))
3584 (defun org-export--footnote-reference-map (function info &optional body-first)
3585 "Apply FUNCTION on every footnote reference in parse tree.
3586 INFO is a plist containing export state. By default, as soon as
3587 a new footnote reference is encountered, FUNCTION is called onto
3588 its definition. However, if BODY-FIRST is non-nil, this step is
3589 delayed until the end of the process."
3590 (let* ((definitions)
3591 (seen-refs)
3592 (search-ref) ; For byte-compiler.
3593 (search-ref
3594 (lambda (data delayp)
3595 ;; Search footnote references through DATA, filling
3596 ;; SEEN-REFS along the way. When DELAYP is non-nil, store
3597 ;; footnote definitions so they can be entered later.
3598 (org-element-map data 'footnote-reference
3599 (lambda (f)
3600 (funcall function f)
3601 (let ((--label (org-element-property :label f)))
3602 (unless (and --label (member --label seen-refs))
3603 (when --label (push --label seen-refs))
3604 ;; Search for subsequent references in footnote
3605 ;; definition so numbering follows reading logic,
3606 ;; unless DELAYP in non-nil.
3607 (cond
3608 (delayp
3609 (push (org-export-get-footnote-definition f info)
3610 definitions))
3611 ;; Do not force entering inline definitions,
3612 ;; since `org-element-map' already traverses them
3613 ;; at the right time.
3614 ((eq (org-element-property :type f) 'inline))
3615 (t (funcall search-ref
3616 (org-export-get-footnote-definition f info)
3617 nil))))))
3618 info nil
3619 ;; Don't enter footnote definitions since it will happen
3620 ;; when their first reference is found. Moreover, if
3621 ;; DELAYP is non-nil, make sure we postpone entering
3622 ;; definitions of inline references.
3623 (if delayp '(footnote-definition footnote-reference)
3624 'footnote-definition)))))
3625 (funcall search-ref (plist-get info :parse-tree) body-first)
3626 (funcall search-ref (nreverse definitions) nil)))
3628 (defun org-export-footnote-first-reference-p
3629 (footnote-reference info &optional body-first)
3630 "Non-nil when a footnote reference is the first one for its label.
3632 FOOTNOTE-REFERENCE is the footnote reference being considered.
3633 INFO is a plist containing current export state.
3635 By default, as soon as a new footnote reference is encountered,
3636 other references are searched within its definition. However, if
3637 BODY-FIRST is non-nil, this step is delayed after the whole tree
3638 is checked. This alters results when references are found in
3639 footnote definitions."
3640 (let ((label (org-element-property :label footnote-reference)))
3641 ;; Anonymous footnotes are always a first reference.
3642 (or (not label)
3643 (catch 'exit
3644 (org-export--footnote-reference-map
3645 (lambda (f)
3646 (let ((l (org-element-property :label f)))
3647 (when (and l label (string= label l))
3648 (throw 'exit (eq footnote-reference f)))))
3649 info body-first)))))
3651 (defun org-export-get-footnote-number (footnote info &optional body-first)
3652 "Return number associated to a footnote.
3654 FOOTNOTE is either a footnote reference or a footnote definition.
3655 INFO is the plist containing export state.
3657 By default, as soon as a new footnote reference is encountered,
3658 counting process moves into its definition. However, if
3659 BODY-FIRST is non-nil, this step is delayed until the end of the
3660 process, leading to a different order when footnotes are nested."
3661 (let ((count 0)
3662 (seen)
3663 (label (org-element-property :label footnote)))
3664 (catch 'exit
3665 (org-export--footnote-reference-map
3666 (lambda (f)
3667 (let ((l (org-element-property :label f)))
3668 (cond
3669 ;; Anonymous footnote match: return number.
3670 ((and (not l) (not label) (eq footnote f)) (throw 'exit (1+ count)))
3671 ;; Labels match: return number.
3672 ((and label l (string= label l)) (throw 'exit (1+ count)))
3673 ;; Otherwise store label and increase counter if label
3674 ;; wasn't encountered yet.
3675 ((not l) (incf count))
3676 ((not (member l seen)) (push l seen) (incf count)))))
3677 info body-first))))
3680 ;;;; For Headlines
3682 ;; `org-export-get-relative-level' is a shortcut to get headline
3683 ;; level, relatively to the lower headline level in the parsed tree.
3685 ;; `org-export-get-headline-number' returns the section number of an
3686 ;; headline, while `org-export-number-to-roman' allows to convert it
3687 ;; to roman numbers. With an optional argument,
3688 ;; `org-export-get-headline-number' returns a number to unnumbered
3689 ;; headlines (used for internal id).
3691 ;; `org-export-get-headline-id' returns the unique internal id of a
3692 ;; headline.
3694 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
3695 ;; `org-export-last-sibling-p' are three useful predicates when it
3696 ;; comes to fulfill the `:headline-levels' property.
3698 ;; `org-export-get-tags', `org-export-get-category' and
3699 ;; `org-export-get-node-property' extract useful information from an
3700 ;; headline or a parent headline. They all handle inheritance.
3702 ;; `org-export-get-alt-title' tries to retrieve an alternative title,
3703 ;; as a secondary string, suitable for table of contents. It falls
3704 ;; back onto default title.
3706 (defun org-export-get-relative-level (headline info)
3707 "Return HEADLINE relative level within current parsed tree.
3708 INFO is a plist holding contextual information."
3709 (+ (org-element-property :level headline)
3710 (or (plist-get info :headline-offset) 0)))
3712 (defun org-export-low-level-p (headline info)
3713 "Non-nil when HEADLINE is considered as low level.
3715 INFO is a plist used as a communication channel.
3717 A low level headlines has a relative level greater than
3718 `:headline-levels' property value.
3720 Return value is the difference between HEADLINE relative level
3721 and the last level being considered as high enough, or nil."
3722 (let ((limit (plist-get info :headline-levels)))
3723 (when (wholenump limit)
3724 (let ((level (org-export-get-relative-level headline info)))
3725 (and (> level limit) (- level limit))))))
3727 (defun org-export-get-headline-id (headline info)
3728 "Return a unique ID for HEADLINE.
3729 INFO is a plist holding contextual information."
3730 (let ((numbered (org-export-numbered-headline-p headline info)))
3731 (concat
3732 (if numbered "sec-" "unnumbered-")
3733 (mapconcat #'number-to-string
3734 (if numbered
3735 (org-export-get-headline-number headline info)
3736 (cdr (assq headline (plist-get info :unnumbered-headline-id)))) "-"))))
3738 (defun org-export-get-headline-number (headline info)
3739 "Return numbered HEADLINE numbering as a list of numbers.
3740 INFO is a plist holding contextual information."
3741 (and (org-export-numbered-headline-p headline info)
3742 (cdr (assq headline (plist-get info :headline-numbering)))))
3744 (defun org-export-numbered-headline-p (headline info)
3745 "Return a non-nil value if HEADLINE element should be numbered.
3746 INFO is a plist used as a communication channel."
3747 (unless (org-some
3748 (lambda (head) (org-not-nil (org-element-property :UNNUMBERED head)))
3749 (org-element-lineage headline nil t))
3750 (let ((sec-num (plist-get info :section-numbers))
3751 (level (org-export-get-relative-level headline info)))
3752 (if (wholenump sec-num) (<= level sec-num) sec-num))))
3754 (defun org-export-number-to-roman (n)
3755 "Convert integer N into a roman numeral."
3756 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
3757 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
3758 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
3759 ( 1 . "I")))
3760 (res ""))
3761 (if (<= n 0)
3762 (number-to-string n)
3763 (while roman
3764 (if (>= n (caar roman))
3765 (setq n (- n (caar roman))
3766 res (concat res (cdar roman)))
3767 (pop roman)))
3768 res)))
3770 (defun org-export-get-tags (element info &optional tags inherited)
3771 "Return list of tags associated to ELEMENT.
3773 ELEMENT has either an `headline' or an `inlinetask' type. INFO
3774 is a plist used as a communication channel.
3776 Select tags (see `org-export-select-tags') and exclude tags (see
3777 `org-export-exclude-tags') are removed from the list.
3779 When non-nil, optional argument TAGS should be a list of strings.
3780 Any tag belonging to this list will also be removed.
3782 When optional argument INHERITED is non-nil, tags can also be
3783 inherited from parent headlines and FILETAGS keywords."
3784 (org-remove-if
3785 (lambda (tag) (or (member tag (plist-get info :select-tags))
3786 (member tag (plist-get info :exclude-tags))
3787 (member tag tags)))
3788 (if (not inherited) (org-element-property :tags element)
3789 ;; Build complete list of inherited tags.
3790 (let ((current-tag-list (org-element-property :tags element)))
3791 (dolist (parent (org-element-lineage element))
3792 (dolist (tag (org-element-property :tags parent))
3793 (when (and (memq (org-element-type parent) '(headline inlinetask))
3794 (not (member tag current-tag-list)))
3795 (push tag current-tag-list))))
3796 ;; Add FILETAGS keywords and return results.
3797 (org-uniquify (append (plist-get info :filetags) current-tag-list))))))
3799 (defun org-export-get-node-property (property blob &optional inherited)
3800 "Return node PROPERTY value for BLOB.
3802 PROPERTY is an upcase symbol (i.e. `:COOKIE_DATA'). BLOB is an
3803 element or object.
3805 If optional argument INHERITED is non-nil, the value can be
3806 inherited from a parent headline.
3808 Return value is a string or nil."
3809 (let ((headline (if (eq (org-element-type blob) 'headline) blob
3810 (org-export-get-parent-headline blob))))
3811 (if (not inherited) (org-element-property property blob)
3812 (let ((parent headline) value)
3813 (catch 'found
3814 (while parent
3815 (when (plist-member (nth 1 parent) property)
3816 (throw 'found (org-element-property property parent)))
3817 (setq parent (org-element-property :parent parent))))))))
3819 (defun org-export-get-category (blob info)
3820 "Return category for element or object BLOB.
3822 INFO is a plist used as a communication channel.
3824 CATEGORY is automatically inherited from a parent headline, from
3825 #+CATEGORY: keyword or created out of original file name. If all
3826 fail, the fall-back value is \"???\"."
3827 (or (org-export-get-node-property :CATEGORY blob t)
3828 (org-element-map (plist-get info :parse-tree) 'keyword
3829 (lambda (kwd)
3830 (when (equal (org-element-property :key kwd) "CATEGORY")
3831 (org-element-property :value kwd)))
3832 info 'first-match)
3833 (let ((file (plist-get info :input-file)))
3834 (and file (file-name-sans-extension (file-name-nondirectory file))))
3835 "???"))
3837 (defun org-export-get-alt-title (headline info)
3838 "Return alternative title for HEADLINE, as a secondary string.
3839 INFO is a plist used as a communication channel. If no optional
3840 title is defined, fall-back to the regular title."
3841 (let ((alt (org-element-property :ALT_TITLE headline)))
3842 (if alt (org-element-parse-secondary-string
3843 alt (org-element-restriction 'headline) headline)
3844 (org-element-property :title headline))))
3846 (defun org-export-first-sibling-p (blob info)
3847 "Non-nil when BLOB is the first sibling in its parent.
3848 BLOB is an element or an object. If BLOB is a headline, non-nil
3849 means it is the first sibling in the sub-tree. INFO is a plist
3850 used as a communication channel."
3851 (memq (org-element-type (org-export-get-previous-element blob info))
3852 '(nil section)))
3854 (defun org-export-last-sibling-p (blob info)
3855 "Non-nil when BLOB is the last sibling in its parent.
3856 BLOB is an element or an object. INFO is a plist used as
3857 a communication channel."
3858 (not (org-export-get-next-element blob info)))
3861 ;;;; For Keywords
3863 ;; `org-export-get-date' returns a date appropriate for the document
3864 ;; to about to be exported. In particular, it takes care of
3865 ;; `org-export-date-timestamp-format'.
3867 (defun org-export-get-date (info &optional fmt)
3868 "Return date value for the current document.
3870 INFO is a plist used as a communication channel. FMT, when
3871 non-nil, is a time format string that will be applied on the date
3872 if it consists in a single timestamp object. It defaults to
3873 `org-export-date-timestamp-format' when nil.
3875 A proper date can be a secondary string, a string or nil. It is
3876 meant to be translated with `org-export-data' or alike."
3877 (let ((date (plist-get info :date))
3878 (fmt (or fmt org-export-date-timestamp-format)))
3879 (cond ((not date) nil)
3880 ((and fmt
3881 (not (cdr date))
3882 (eq (org-element-type (car date)) 'timestamp))
3883 (org-timestamp-format (car date) fmt))
3884 (t date))))
3887 ;;;; For Links
3889 ;; `org-export-custom-protocol-maybe' handles custom protocol defined
3890 ;; with `org-add-link-type', which see.
3892 ;; `org-export-solidify-link-text' turns a string into a safer version
3893 ;; for links, replacing most non-standard characters with hyphens.
3895 ;; `org-export-get-coderef-format' returns an appropriate format
3896 ;; string for coderefs.
3898 ;; `org-export-inline-image-p' returns a non-nil value when the link
3899 ;; provided should be considered as an inline image.
3901 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
3902 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
3903 ;; returns an appropriate unique identifier when found, or nil.
3905 ;; `org-export-resolve-id-link' returns the first headline with
3906 ;; specified id or custom-id in parse tree, the path to the external
3907 ;; file with the id or nil when neither was found.
3909 ;; `org-export-resolve-coderef' associates a reference to a line
3910 ;; number in the element it belongs, or returns the reference itself
3911 ;; when the element isn't numbered.
3913 (defun org-export-solidify-link-text (s)
3914 "Take link text S and make a safe target out of it."
3915 (save-match-data
3916 (mapconcat 'identity (org-split-string s "[^a-zA-Z0-9_.-:]+") "-")))
3918 (defun org-export-custom-protocol-maybe (link desc info)
3919 "Try exporting LINK with a dedicated function.
3921 DESC is its description, as a string, or nil. INFO is the plist
3922 containing export state. Return output as a string, or nil if no
3923 protocol handles LINK.
3925 A custom protocol is expected to have precedence over regular
3926 back-end export. The function ignores links with an implicit
3927 type (e.g., \"custom-id\")."
3928 (let ((type (org-element-property :type link))
3929 (backend (let ((b (plist-get info :back-end)))
3930 (and b (org-export-backend-name b)))))
3931 (unless (or (member type '("coderef" "custom-id" "fuzzy" "radio"))
3932 (not backend))
3933 (let ((protocol (nth 2 (assoc type org-link-protocols))))
3934 (and (functionp protocol)
3935 (funcall protocol
3936 (org-link-unescape (org-element-property :path link))
3937 desc
3938 backend))))))
3940 (defun org-export-get-coderef-format (path desc)
3941 "Return format string for code reference link.
3942 PATH is the link path. DESC is its description."
3943 (save-match-data
3944 (cond ((not desc) "%s")
3945 ((string-match (regexp-quote (concat "(" path ")")) desc)
3946 (replace-match "%s" t t desc))
3947 (t desc))))
3949 (defun org-export-inline-image-p (link &optional rules)
3950 "Non-nil if LINK object points to an inline image.
3952 Optional argument is a set of RULES defining inline images. It
3953 is an alist where associations have the following shape:
3955 \(TYPE . REGEXP)
3957 Applying a rule means apply REGEXP against LINK's path when its
3958 type is TYPE. The function will return a non-nil value if any of
3959 the provided rules is non-nil. The default rule is
3960 `org-export-default-inline-image-rule'.
3962 This only applies to links without a description."
3963 (and (not (org-element-contents link))
3964 (let ((case-fold-search t))
3965 (catch 'exit
3966 (dolist (rule (or rules org-export-default-inline-image-rule))
3967 (and (string= (org-element-property :type link) (car rule))
3968 (org-string-match-p (cdr rule)
3969 (org-element-property :path link))
3970 (throw 'exit t)))))))
3972 (defun org-export-resolve-coderef (ref info)
3973 "Resolve a code reference REF.
3975 INFO is a plist used as a communication channel.
3977 Return associated line number in source code, or REF itself,
3978 depending on src-block or example element's switches."
3979 (org-element-map (plist-get info :parse-tree) '(example-block src-block)
3980 (lambda (el)
3981 (with-temp-buffer
3982 (insert (org-trim (org-element-property :value el)))
3983 (let* ((label-fmt (regexp-quote
3984 (or (org-element-property :label-fmt el)
3985 org-coderef-label-format)))
3986 (ref-re
3987 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
3988 (replace-regexp-in-string "%s" ref label-fmt nil t))))
3989 ;; Element containing REF is found. Resolve it to either
3990 ;; a label or a line number, as needed.
3991 (when (re-search-backward ref-re nil t)
3992 (cond
3993 ((org-element-property :use-labels el) ref)
3994 ((eq (org-element-property :number-lines el) 'continued)
3995 (+ (org-export-get-loc el info) (line-number-at-pos)))
3996 (t (line-number-at-pos)))))))
3997 info 'first-match))
3999 (defun org-export-resolve-fuzzy-link (link info)
4000 "Return LINK destination.
4002 INFO is a plist holding contextual information.
4004 Return value can be an object, an element, or nil:
4006 - If LINK path matches a target object (i.e. <<path>>) return it.
4008 - If LINK path exactly matches the name affiliated keyword
4009 \(i.e. #+NAME: path) of an element, return that element.
4011 - If LINK path exactly matches any headline name, return that
4012 element. If more than one headline share that name, priority
4013 will be given to the one with the closest common ancestor, if
4014 any, or the first one in the parse tree otherwise.
4016 - Otherwise, return nil.
4018 Assume LINK type is \"fuzzy\". White spaces are not
4019 significant."
4020 (let* ((raw-path (org-element-property :path link))
4021 (match-title-p (eq (aref raw-path 0) ?*))
4022 ;; Split PATH at white spaces so matches are space
4023 ;; insensitive.
4024 (path (org-split-string
4025 (if match-title-p (substring raw-path 1) raw-path)))
4026 ;; Cache for destinations that are not position dependent.
4027 (link-cache
4028 (or (plist-get info :resolve-fuzzy-link-cache)
4029 (plist-get (setq info (plist-put info :resolve-fuzzy-link-cache
4030 (make-hash-table :test 'equal)))
4031 :resolve-fuzzy-link-cache)))
4032 (cached (gethash path link-cache 'not-found)))
4033 (cond
4034 ;; Destination is not position dependent: use cached value.
4035 ((and (not match-title-p) (not (eq cached 'not-found))) cached)
4036 ;; First try to find a matching "<<path>>" unless user specified
4037 ;; he was looking for a headline (path starts with a "*"
4038 ;; character).
4039 ((and (not match-title-p)
4040 (let ((match (org-element-map (plist-get info :parse-tree) 'target
4041 (lambda (blob)
4042 (and (equal (org-split-string
4043 (org-element-property :value blob))
4044 path)
4045 blob))
4046 info 'first-match)))
4047 (and match (puthash path match link-cache)))))
4048 ;; Then try to find an element with a matching "#+NAME: path"
4049 ;; affiliated keyword.
4050 ((and (not match-title-p)
4051 (let ((match (org-element-map (plist-get info :parse-tree)
4052 org-element-all-elements
4053 (lambda (el)
4054 (let ((name (org-element-property :name el)))
4055 (when (and name
4056 (equal (org-split-string name) path))
4057 el)))
4058 info 'first-match)))
4059 (and match (puthash path match link-cache)))))
4060 ;; Last case: link either points to a headline or to nothingness.
4061 ;; Try to find the source, with priority given to headlines with
4062 ;; the closest common ancestor. If such candidate is found,
4063 ;; return it, otherwise return nil.
4065 (let ((find-headline
4066 (function
4067 ;; Return first headline whose `:raw-value' property is
4068 ;; NAME in parse tree DATA, or nil. Statistics cookies
4069 ;; are ignored.
4070 (lambda (name data)
4071 (org-element-map data 'headline
4072 (lambda (headline)
4073 (when (equal (org-split-string
4074 (replace-regexp-in-string
4075 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
4076 (org-element-property :raw-value headline)))
4077 name)
4078 headline))
4079 info 'first-match)))))
4080 ;; Search among headlines sharing an ancestor with link, from
4081 ;; closest to farthest.
4082 (catch 'exit
4083 (dolist (parent
4084 (let ((parent-hl (org-export-get-parent-headline link)))
4085 (if (not parent-hl) (list (plist-get info :parse-tree))
4086 (org-element-lineage parent-hl nil t))))
4087 (let ((foundp (funcall find-headline path parent)))
4088 (when foundp (throw 'exit foundp))))
4089 ;; No destination found: return nil.
4090 (and (not match-title-p) (puthash path nil link-cache))))))))
4092 (defun org-export-resolve-id-link (link info)
4093 "Return headline referenced as LINK destination.
4095 INFO is a plist used as a communication channel.
4097 Return value can be the headline element matched in current parse
4098 tree, a file name or nil. Assume LINK type is either \"id\" or
4099 \"custom-id\"."
4100 (let ((id (org-element-property :path link)))
4101 ;; First check if id is within the current parse tree.
4102 (or (org-element-map (plist-get info :parse-tree) 'headline
4103 (lambda (headline)
4104 (when (or (string= (org-element-property :ID headline) id)
4105 (string= (org-element-property :CUSTOM_ID headline) id))
4106 headline))
4107 info 'first-match)
4108 ;; Otherwise, look for external files.
4109 (cdr (assoc id (plist-get info :id-alist))))))
4111 (defun org-export-resolve-radio-link (link info)
4112 "Return radio-target object referenced as LINK destination.
4114 INFO is a plist used as a communication channel.
4116 Return value can be a radio-target object or nil. Assume LINK
4117 has type \"radio\"."
4118 (let ((path (replace-regexp-in-string
4119 "[ \r\t\n]+" " " (org-element-property :path link))))
4120 (org-element-map (plist-get info :parse-tree) 'radio-target
4121 (lambda (radio)
4122 (and (eq (compare-strings
4123 (replace-regexp-in-string
4124 "[ \r\t\n]+" " " (org-element-property :value radio))
4125 nil nil path nil nil t)
4127 radio))
4128 info 'first-match)))
4131 ;;;; For References
4133 ;; `org-export-get-ordinal' associates a sequence number to any object
4134 ;; or element.
4136 (defun org-export-get-ordinal (element info &optional types predicate)
4137 "Return ordinal number of an element or object.
4139 ELEMENT is the element or object considered. INFO is the plist
4140 used as a communication channel.
4142 Optional argument TYPES, when non-nil, is a list of element or
4143 object types, as symbols, that should also be counted in.
4144 Otherwise, only provided element's type is considered.
4146 Optional argument PREDICATE is a function returning a non-nil
4147 value if the current element or object should be counted in. It
4148 accepts two arguments: the element or object being considered and
4149 the plist used as a communication channel. This allows to count
4150 only a certain type of objects (i.e. inline images).
4152 Return value is a list of numbers if ELEMENT is a headline or an
4153 item. It is nil for keywords. It represents the footnote number
4154 for footnote definitions and footnote references. If ELEMENT is
4155 a target, return the same value as if ELEMENT was the closest
4156 table, item or headline containing the target. In any other
4157 case, return the sequence number of ELEMENT among elements or
4158 objects of the same type."
4159 ;; Ordinal of a target object refer to the ordinal of the closest
4160 ;; table, item, or headline containing the object.
4161 (when (eq (org-element-type element) 'target)
4162 (setq element
4163 (org-element-lineage
4164 element
4165 '(footnote-definition footnote-reference headline item table))))
4166 (case (org-element-type element)
4167 ;; Special case 1: A headline returns its number as a list.
4168 (headline (org-export-get-headline-number element info))
4169 ;; Special case 2: An item returns its number as a list.
4170 (item (let ((struct (org-element-property :structure element)))
4171 (org-list-get-item-number
4172 (org-element-property :begin element)
4173 struct
4174 (org-list-prevs-alist struct)
4175 (org-list-parents-alist struct))))
4176 ((footnote-definition footnote-reference)
4177 (org-export-get-footnote-number element info))
4178 (otherwise
4179 (let ((counter 0))
4180 ;; Increment counter until ELEMENT is found again.
4181 (org-element-map (plist-get info :parse-tree)
4182 (or types (org-element-type element))
4183 (lambda (el)
4184 (cond
4185 ((eq element el) (1+ counter))
4186 ((not predicate) (incf counter) nil)
4187 ((funcall predicate el info) (incf counter) nil)))
4188 info 'first-match)))))
4191 ;;;; For Src-Blocks
4193 ;; `org-export-get-loc' counts number of code lines accumulated in
4194 ;; src-block or example-block elements with a "+n" switch until
4195 ;; a given element, excluded. Note: "-n" switches reset that count.
4197 ;; `org-export-unravel-code' extracts source code (along with a code
4198 ;; references alist) from an `element-block' or `src-block' type
4199 ;; element.
4201 ;; `org-export-format-code' applies a formatting function to each line
4202 ;; of code, providing relative line number and code reference when
4203 ;; appropriate. Since it doesn't access the original element from
4204 ;; which the source code is coming, it expects from the code calling
4205 ;; it to know if lines should be numbered and if code references
4206 ;; should appear.
4208 ;; Eventually, `org-export-format-code-default' is a higher-level
4209 ;; function (it makes use of the two previous functions) which handles
4210 ;; line numbering and code references inclusion, and returns source
4211 ;; code in a format suitable for plain text or verbatim output.
4213 (defun org-export-get-loc (element info)
4214 "Return accumulated lines of code up to ELEMENT.
4216 INFO is the plist used as a communication channel.
4218 ELEMENT is excluded from count."
4219 (let ((loc 0))
4220 (org-element-map (plist-get info :parse-tree)
4221 `(src-block example-block ,(org-element-type element))
4222 (lambda (el)
4223 (cond
4224 ;; ELEMENT is reached: Quit the loop.
4225 ((eq el element))
4226 ;; Only count lines from src-block and example-block elements
4227 ;; with a "+n" or "-n" switch. A "-n" switch resets counter.
4228 ((not (memq (org-element-type el) '(src-block example-block))) nil)
4229 ((let ((linums (org-element-property :number-lines el)))
4230 (when linums
4231 ;; Accumulate locs or reset them.
4232 (let ((lines (org-count-lines
4233 (org-trim (org-element-property :value el)))))
4234 (setq loc (if (eq linums 'new) lines (+ loc lines))))))
4235 ;; Return nil to stay in the loop.
4236 nil)))
4237 info 'first-match)
4238 ;; Return value.
4239 loc))
4241 (defun org-export-unravel-code (element)
4242 "Clean source code and extract references out of it.
4244 ELEMENT has either a `src-block' an `example-block' type.
4246 Return a cons cell whose CAR is the source code, cleaned from any
4247 reference, protective commas and spurious indentation, and CDR is
4248 an alist between relative line number (integer) and name of code
4249 reference on that line (string)."
4250 (let* ((line 0) refs
4251 (value (org-element-property :value element))
4252 ;; Get code and clean it. Remove blank lines at its
4253 ;; beginning and end.
4254 (code (replace-regexp-in-string
4255 "\\`\\([ \t]*\n\\)+" ""
4256 (replace-regexp-in-string
4257 "\\([ \t]*\n\\)*[ \t]*\\'" "\n"
4258 (if (or org-src-preserve-indentation
4259 (org-element-property :preserve-indent element))
4260 value
4261 (org-element-remove-indentation value)))))
4262 ;; Get format used for references.
4263 (label-fmt (regexp-quote
4264 (or (org-element-property :label-fmt element)
4265 org-coderef-label-format)))
4266 ;; Build a regexp matching a loc with a reference.
4267 (with-ref-re
4268 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)[ \t]*\\)$"
4269 (replace-regexp-in-string
4270 "%s" "\\([-a-zA-Z0-9_ ]+\\)" label-fmt nil t))))
4271 ;; Return value.
4272 (cons
4273 ;; Code with references removed.
4274 (org-element-normalize-string
4275 (mapconcat
4276 (lambda (loc)
4277 (incf line)
4278 (if (not (string-match with-ref-re loc)) loc
4279 ;; Ref line: remove ref, and signal its position in REFS.
4280 (push (cons line (match-string 3 loc)) refs)
4281 (replace-match "" nil nil loc 1)))
4282 (org-split-string code "\n") "\n"))
4283 ;; Reference alist.
4284 refs)))
4286 (defun org-export-format-code (code fun &optional num-lines ref-alist)
4287 "Format CODE by applying FUN line-wise and return it.
4289 CODE is a string representing the code to format. FUN is
4290 a function. It must accept three arguments: a line of
4291 code (string), the current line number (integer) or nil and the
4292 reference associated to the current line (string) or nil.
4294 Optional argument NUM-LINES can be an integer representing the
4295 number of code lines accumulated until the current code. Line
4296 numbers passed to FUN will take it into account. If it is nil,
4297 FUN's second argument will always be nil. This number can be
4298 obtained with `org-export-get-loc' function.
4300 Optional argument REF-ALIST can be an alist between relative line
4301 number (i.e. ignoring NUM-LINES) and the name of the code
4302 reference on it. If it is nil, FUN's third argument will always
4303 be nil. It can be obtained through the use of
4304 `org-export-unravel-code' function."
4305 (let ((--locs (org-split-string code "\n"))
4306 (--line 0))
4307 (org-element-normalize-string
4308 (mapconcat
4309 (lambda (--loc)
4310 (incf --line)
4311 (let ((--ref (cdr (assq --line ref-alist))))
4312 (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
4313 --locs "\n"))))
4315 (defun org-export-format-code-default (element info)
4316 "Return source code from ELEMENT, formatted in a standard way.
4318 ELEMENT is either a `src-block' or `example-block' element. INFO
4319 is a plist used as a communication channel.
4321 This function takes care of line numbering and code references
4322 inclusion. Line numbers, when applicable, appear at the
4323 beginning of the line, separated from the code by two white
4324 spaces. Code references, on the other hand, appear flushed to
4325 the right, separated by six white spaces from the widest line of
4326 code."
4327 ;; Extract code and references.
4328 (let* ((code-info (org-export-unravel-code element))
4329 (code (car code-info))
4330 (code-lines (org-split-string code "\n")))
4331 (if (null code-lines) ""
4332 (let* ((refs (and (org-element-property :retain-labels element)
4333 (cdr code-info)))
4334 ;; Handle line numbering.
4335 (num-start (case (org-element-property :number-lines element)
4336 (continued (org-export-get-loc element info))
4337 (new 0)))
4338 (num-fmt
4339 (and num-start
4340 (format "%%%ds "
4341 (length (number-to-string
4342 (+ (length code-lines) num-start))))))
4343 ;; Prepare references display, if required. Any reference
4344 ;; should start six columns after the widest line of code,
4345 ;; wrapped with parenthesis.
4346 (max-width
4347 (+ (apply 'max (mapcar 'length code-lines))
4348 (if (not num-start) 0 (length (format num-fmt num-start))))))
4349 (org-export-format-code
4350 code
4351 (lambda (loc line-num ref)
4352 (let ((number-str (and num-fmt (format num-fmt line-num))))
4353 (concat
4354 number-str
4356 (and ref
4357 (concat (make-string
4358 (- (+ 6 max-width)
4359 (+ (length loc) (length number-str))) ? )
4360 (format "(%s)" ref))))))
4361 num-start refs)))))
4364 ;;;; For Tables
4366 ;; `org-export-table-has-special-column-p' and and
4367 ;; `org-export-table-row-is-special-p' are predicates used to look for
4368 ;; meta-information about the table structure.
4370 ;; `org-table-has-header-p' tells when the rows before the first rule
4371 ;; should be considered as table's header.
4373 ;; `org-export-table-cell-width', `org-export-table-cell-alignment'
4374 ;; and `org-export-table-cell-borders' extract information from
4375 ;; a table-cell element.
4377 ;; `org-export-table-dimensions' gives the number on rows and columns
4378 ;; in the table, ignoring horizontal rules and special columns.
4379 ;; `org-export-table-cell-address', given a table-cell object, returns
4380 ;; the absolute address of a cell. On the other hand,
4381 ;; `org-export-get-table-cell-at' does the contrary.
4383 ;; `org-export-table-cell-starts-colgroup-p',
4384 ;; `org-export-table-cell-ends-colgroup-p',
4385 ;; `org-export-table-row-starts-rowgroup-p',
4386 ;; `org-export-table-row-ends-rowgroup-p',
4387 ;; `org-export-table-row-starts-header-p',
4388 ;; `org-export-table-row-ends-header-p' and
4389 ;; `org-export-table-row-in-header-p' indicate position of current row
4390 ;; or cell within the table.
4392 (defun org-export-table-has-special-column-p (table)
4393 "Non-nil when TABLE has a special column.
4394 All special columns will be ignored during export."
4395 ;; The table has a special column when every first cell of every row
4396 ;; has an empty value or contains a symbol among "/", "#", "!", "$",
4397 ;; "*" "_" and "^". Though, do not consider a first row containing
4398 ;; only empty cells as special.
4399 (let ((special-column-p 'empty))
4400 (catch 'exit
4401 (mapc
4402 (lambda (row)
4403 (when (eq (org-element-property :type row) 'standard)
4404 (let ((value (org-element-contents
4405 (car (org-element-contents row)))))
4406 (cond ((member value '(("/") ("#") ("!") ("$") ("*") ("_") ("^")))
4407 (setq special-column-p 'special))
4408 ((not value))
4409 (t (throw 'exit nil))))))
4410 (org-element-contents table))
4411 (eq special-column-p 'special))))
4413 (defun org-export-table-has-header-p (table info)
4414 "Non-nil when TABLE has a header.
4416 INFO is a plist used as a communication channel.
4418 A table has a header when it contains at least two row groups."
4419 (let ((cache (or (plist-get info :table-header-cache)
4420 (plist-get (setq info
4421 (plist-put info :table-header-cache
4422 (make-hash-table :test 'eq)))
4423 :table-header-cache))))
4424 (or (gethash table cache)
4425 (let ((rowgroup 1) row-flag)
4426 (puthash
4427 table
4428 (org-element-map table 'table-row
4429 (lambda (row)
4430 (cond
4431 ((> rowgroup 1) t)
4432 ((and row-flag (eq (org-element-property :type row) 'rule))
4433 (incf rowgroup) (setq row-flag nil))
4434 ((and (not row-flag) (eq (org-element-property :type row)
4435 'standard))
4436 (setq row-flag t) nil)))
4437 info 'first-match)
4438 cache)))))
4440 (defun org-export-table-row-is-special-p (table-row info)
4441 "Non-nil if TABLE-ROW is considered special.
4443 INFO is a plist used as the communication channel.
4445 All special rows will be ignored during export."
4446 (when (eq (org-element-property :type table-row) 'standard)
4447 (let ((first-cell (org-element-contents
4448 (car (org-element-contents table-row)))))
4449 ;; A row is special either when...
4451 ;; ... it starts with a field only containing "/",
4452 (equal first-cell '("/"))
4453 ;; ... the table contains a special column and the row start
4454 ;; with a marking character among, "^", "_", "$" or "!",
4455 (and (org-export-table-has-special-column-p
4456 (org-export-get-parent table-row))
4457 (member first-cell '(("^") ("_") ("$") ("!"))))
4458 ;; ... it contains only alignment cookies and empty cells.
4459 (let ((special-row-p 'empty))
4460 (catch 'exit
4461 (mapc
4462 (lambda (cell)
4463 (let ((value (org-element-contents cell)))
4464 ;; Since VALUE is a secondary string, the following
4465 ;; checks avoid expanding it with `org-export-data'.
4466 (cond ((not value))
4467 ((and (not (cdr value))
4468 (stringp (car value))
4469 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'"
4470 (car value)))
4471 (setq special-row-p 'cookie))
4472 (t (throw 'exit nil)))))
4473 (org-element-contents table-row))
4474 (eq special-row-p 'cookie)))))))
4476 (defun org-export-table-row-group (table-row info)
4477 "Return TABLE-ROW's group number, as an integer.
4479 INFO is a plist used as the communication channel.
4481 Return value is the group number, as an integer, or nil for
4482 special rows and rows separators. First group is also table's
4483 header."
4484 (let ((cache (or (plist-get info :table-row-group-cache)
4485 (plist-get (setq info
4486 (plist-put info :table-row-group-cache
4487 (make-hash-table :test 'eq)))
4488 :table-row-group-cache))))
4489 (cond ((gethash table-row cache))
4490 ((eq (org-element-property :type table-row) 'rule) nil)
4491 (t (let ((group 0) row-flag)
4492 (org-element-map (org-export-get-parent table-row) 'table-row
4493 (lambda (row)
4494 (if (eq (org-element-property :type row) 'rule)
4495 (setq row-flag nil)
4496 (unless row-flag (incf group) (setq row-flag t)))
4497 (when (eq table-row row) (puthash table-row group cache)))
4498 info 'first-match))))))
4500 (defun org-export-table-cell-width (table-cell info)
4501 "Return TABLE-CELL contents width.
4503 INFO is a plist used as the communication channel.
4505 Return value is the width given by the last width cookie in the
4506 same column as TABLE-CELL, or nil."
4507 (let* ((row (org-export-get-parent table-cell))
4508 (table (org-export-get-parent row))
4509 (cells (org-element-contents row))
4510 (columns (length cells))
4511 (column (- columns (length (memq table-cell cells))))
4512 (cache (or (plist-get info :table-cell-width-cache)
4513 (plist-get (setq info
4514 (plist-put info :table-cell-width-cache
4515 (make-hash-table :test 'eq)))
4516 :table-cell-width-cache)))
4517 (width-vector (or (gethash table cache)
4518 (puthash table (make-vector columns 'empty) cache)))
4519 (value (aref width-vector column)))
4520 (if (not (eq value 'empty)) value
4521 (let (cookie-width)
4522 (dolist (row (org-element-contents table)
4523 (aset width-vector column cookie-width))
4524 (when (org-export-table-row-is-special-p row info)
4525 ;; In a special row, try to find a width cookie at COLUMN.
4526 (let* ((value (org-element-contents
4527 (elt (org-element-contents row) column)))
4528 (cookie (car value)))
4529 ;; The following checks avoid expanding unnecessarily
4530 ;; the cell with `org-export-data'.
4531 (when (and value
4532 (not (cdr value))
4533 (stringp cookie)
4534 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'" cookie)
4535 (match-string 1 cookie))
4536 (setq cookie-width
4537 (string-to-number (match-string 1 cookie)))))))))))
4539 (defun org-export-table-cell-alignment (table-cell info)
4540 "Return TABLE-CELL contents alignment.
4542 INFO is a plist used as the communication channel.
4544 Return alignment as specified by the last alignment cookie in the
4545 same column as TABLE-CELL. If no such cookie is found, a default
4546 alignment value will be deduced from fraction of numbers in the
4547 column (see `org-table-number-fraction' for more information).
4548 Possible values are `left', `right' and `center'."
4549 ;; Load `org-table-number-fraction' and `org-table-number-regexp'.
4550 (require 'org-table)
4551 (let* ((row (org-export-get-parent table-cell))
4552 (table (org-export-get-parent row))
4553 (cells (org-element-contents row))
4554 (columns (length cells))
4555 (column (- columns (length (memq table-cell cells))))
4556 (cache (or (plist-get info :table-cell-alignment-cache)
4557 (plist-get (setq info
4558 (plist-put info :table-cell-alignment-cache
4559 (make-hash-table :test 'eq)))
4560 :table-cell-alignment-cache)))
4561 (align-vector (or (gethash table cache)
4562 (puthash table (make-vector columns nil) cache))))
4563 (or (aref align-vector column)
4564 (let ((number-cells 0)
4565 (total-cells 0)
4566 cookie-align
4567 previous-cell-number-p)
4568 (dolist (row (org-element-contents (org-export-get-parent row)))
4569 (cond
4570 ;; In a special row, try to find an alignment cookie at
4571 ;; COLUMN.
4572 ((org-export-table-row-is-special-p row info)
4573 (let ((value (org-element-contents
4574 (elt (org-element-contents row) column))))
4575 ;; Since VALUE is a secondary string, the following
4576 ;; checks avoid useless expansion through
4577 ;; `org-export-data'.
4578 (when (and value
4579 (not (cdr value))
4580 (stringp (car value))
4581 (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'"
4582 (car value))
4583 (match-string 1 (car value)))
4584 (setq cookie-align (match-string 1 (car value))))))
4585 ;; Ignore table rules.
4586 ((eq (org-element-property :type row) 'rule))
4587 ;; In a standard row, check if cell's contents are
4588 ;; expressing some kind of number. Increase NUMBER-CELLS
4589 ;; accordingly. Though, don't bother if an alignment
4590 ;; cookie has already defined cell's alignment.
4591 ((not cookie-align)
4592 (let ((value (org-export-data
4593 (org-element-contents
4594 (elt (org-element-contents row) column))
4595 info)))
4596 (incf total-cells)
4597 ;; Treat an empty cell as a number if it follows
4598 ;; a number.
4599 (if (not (or (string-match org-table-number-regexp value)
4600 (and (string= value "") previous-cell-number-p)))
4601 (setq previous-cell-number-p nil)
4602 (setq previous-cell-number-p t)
4603 (incf number-cells))))))
4604 ;; Return value. Alignment specified by cookies has
4605 ;; precedence over alignment deduced from cell's contents.
4606 (aset align-vector
4607 column
4608 (cond ((equal cookie-align "l") 'left)
4609 ((equal cookie-align "r") 'right)
4610 ((equal cookie-align "c") 'center)
4611 ((>= (/ (float number-cells) total-cells)
4612 org-table-number-fraction)
4613 'right)
4614 (t 'left)))))))
4616 (defun org-export-table-cell-borders (table-cell info)
4617 "Return TABLE-CELL borders.
4619 INFO is a plist used as a communication channel.
4621 Return value is a list of symbols, or nil. Possible values are:
4622 `top', `bottom', `above', `below', `left' and `right'. Note:
4623 `top' (resp. `bottom') only happen for a cell in the first
4624 row (resp. last row) of the table, ignoring table rules, if any.
4626 Returned borders ignore special rows."
4627 (let* ((row (org-export-get-parent table-cell))
4628 (table (org-export-get-parent-table table-cell))
4629 borders)
4630 ;; Top/above border? TABLE-CELL has a border above when a rule
4631 ;; used to demarcate row groups can be found above. Hence,
4632 ;; finding a rule isn't sufficient to push `above' in BORDERS:
4633 ;; another regular row has to be found above that 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 'above borders))
4641 (throw 'exit nil)))))
4642 ;; Look at every row before the current one.
4643 (cdr (memq row (reverse (org-element-contents table)))))
4644 ;; No rule above, or rule found starts the table (ignoring any
4645 ;; special row): TABLE-CELL is at the top of the table.
4646 (when rule-flag (push 'above borders))
4647 (push 'top borders)))
4648 ;; Bottom/below border? TABLE-CELL has a border below when next
4649 ;; non-regular row below is a rule.
4650 (let (rule-flag)
4651 (catch 'exit
4652 (mapc (lambda (row)
4653 (cond ((eq (org-element-property :type row) 'rule)
4654 (setq rule-flag t))
4655 ((not (org-export-table-row-is-special-p row info))
4656 (if rule-flag (throw 'exit (push 'below borders))
4657 (throw 'exit nil)))))
4658 ;; Look at every row after the current one.
4659 (cdr (memq row (org-element-contents table))))
4660 ;; No rule below, or rule found ends the table (modulo some
4661 ;; special row): TABLE-CELL is at the bottom of the table.
4662 (when rule-flag (push 'below borders))
4663 (push 'bottom borders)))
4664 ;; Right/left borders? They can only be specified by column
4665 ;; groups. Column groups are defined in a row starting with "/".
4666 ;; Also a column groups row only contains "<", "<>", ">" or blank
4667 ;; cells.
4668 (catch 'exit
4669 (let ((column (let ((cells (org-element-contents row)))
4670 (- (length cells) (length (memq table-cell cells))))))
4671 (mapc
4672 (lambda (row)
4673 (unless (eq (org-element-property :type row) 'rule)
4674 (when (equal (org-element-contents
4675 (car (org-element-contents row)))
4676 '("/"))
4677 (let ((column-groups
4678 (mapcar
4679 (lambda (cell)
4680 (let ((value (org-element-contents cell)))
4681 (when (member value '(("<") ("<>") (">") nil))
4682 (car value))))
4683 (org-element-contents row))))
4684 ;; There's a left border when previous cell, if
4685 ;; any, ends a group, or current one starts one.
4686 (when (or (and (not (zerop column))
4687 (member (elt column-groups (1- column))
4688 '(">" "<>")))
4689 (member (elt column-groups column) '("<" "<>")))
4690 (push 'left borders))
4691 ;; There's a right border when next cell, if any,
4692 ;; starts a group, or current one ends one.
4693 (when (or (and (/= (1+ column) (length column-groups))
4694 (member (elt column-groups (1+ column))
4695 '("<" "<>")))
4696 (member (elt column-groups column) '(">" "<>")))
4697 (push 'right borders))
4698 (throw 'exit nil)))))
4699 ;; Table rows are read in reverse order so last column groups
4700 ;; row has precedence over any previous one.
4701 (reverse (org-element-contents table)))))
4702 ;; Return value.
4703 borders))
4705 (defun org-export-table-cell-starts-colgroup-p (table-cell info)
4706 "Non-nil when TABLE-CELL is at the beginning of a column group.
4707 INFO is a plist used as a communication channel."
4708 ;; A cell starts a column group either when it is at the beginning
4709 ;; of a row (or after the special column, if any) or when it has
4710 ;; a left border.
4711 (or (eq (org-element-map (org-export-get-parent table-cell) 'table-cell
4712 'identity info 'first-match)
4713 table-cell)
4714 (memq 'left (org-export-table-cell-borders table-cell info))))
4716 (defun org-export-table-cell-ends-colgroup-p (table-cell info)
4717 "Non-nil when TABLE-CELL is at the end of a column group.
4718 INFO is a plist used as a communication channel."
4719 ;; A cell ends a column group either when it is at the end of a row
4720 ;; or when it has a right border.
4721 (or (eq (car (last (org-element-contents
4722 (org-export-get-parent table-cell))))
4723 table-cell)
4724 (memq 'right (org-export-table-cell-borders table-cell info))))
4726 (defun org-export-table-row-starts-rowgroup-p (table-row info)
4727 "Non-nil when TABLE-ROW is at the beginning of a row group.
4728 INFO is a plist used as a communication channel."
4729 (unless (or (eq (org-element-property :type table-row) 'rule)
4730 (org-export-table-row-is-special-p table-row info))
4731 (let ((borders (org-export-table-cell-borders
4732 (car (org-element-contents table-row)) info)))
4733 (or (memq 'top borders) (memq 'above borders)))))
4735 (defun org-export-table-row-ends-rowgroup-p (table-row info)
4736 "Non-nil when TABLE-ROW is at the end of a row group.
4737 INFO is a plist used as a communication channel."
4738 (unless (or (eq (org-element-property :type table-row) 'rule)
4739 (org-export-table-row-is-special-p table-row info))
4740 (let ((borders (org-export-table-cell-borders
4741 (car (org-element-contents table-row)) info)))
4742 (or (memq 'bottom borders) (memq 'below borders)))))
4744 (defun org-export-table-row-in-header-p (table-row info)
4745 "Non-nil when TABLE-ROW is located within table's header.
4746 INFO is a plist used as a communication channel. Always return
4747 nil for special rows and rows separators."
4748 (and (org-export-table-has-header-p
4749 (org-export-get-parent-table table-row) info)
4750 (eql (org-export-table-row-group table-row info) 1)))
4752 (defun org-export-table-row-starts-header-p (table-row info)
4753 "Non-nil when TABLE-ROW is the first table header's row.
4754 INFO is a plist used as a communication channel."
4755 (and (org-export-table-row-in-header-p table-row info)
4756 (org-export-table-row-starts-rowgroup-p table-row info)))
4758 (defun org-export-table-row-ends-header-p (table-row info)
4759 "Non-nil when TABLE-ROW is the last table header's row.
4760 INFO is a plist used as a communication channel."
4761 (and (org-export-table-row-in-header-p table-row info)
4762 (org-export-table-row-ends-rowgroup-p table-row info)))
4764 (defun org-export-table-row-number (table-row info)
4765 "Return TABLE-ROW number.
4766 INFO is a plist used as a communication channel. Return value is
4767 zero-based and ignores separators. The function returns nil for
4768 special columns and separators."
4769 (when (and (eq (org-element-property :type table-row) 'standard)
4770 (not (org-export-table-row-is-special-p table-row info)))
4771 (let ((number 0))
4772 (org-element-map (org-export-get-parent-table table-row) 'table-row
4773 (lambda (row)
4774 (cond ((eq row table-row) number)
4775 ((eq (org-element-property :type row) 'standard)
4776 (incf number) nil)))
4777 info 'first-match))))
4779 (defun org-export-table-dimensions (table info)
4780 "Return TABLE dimensions.
4782 INFO is a plist used as a communication channel.
4784 Return value is a CONS like (ROWS . COLUMNS) where
4785 ROWS (resp. COLUMNS) is the number of exportable
4786 rows (resp. columns)."
4787 (let (first-row (columns 0) (rows 0))
4788 ;; Set number of rows, and extract first one.
4789 (org-element-map table 'table-row
4790 (lambda (row)
4791 (when (eq (org-element-property :type row) 'standard)
4792 (incf rows)
4793 (unless first-row (setq first-row row)))) info)
4794 ;; Set number of columns.
4795 (org-element-map first-row 'table-cell (lambda (cell) (incf columns)) info)
4796 ;; Return value.
4797 (cons rows columns)))
4799 (defun org-export-table-cell-address (table-cell info)
4800 "Return address of a regular TABLE-CELL object.
4802 TABLE-CELL is the cell considered. INFO is a plist used as
4803 a communication channel.
4805 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4806 zero-based index. Only exportable cells are considered. The
4807 function returns nil for other cells."
4808 (let* ((table-row (org-export-get-parent table-cell))
4809 (row-number (org-export-table-row-number table-row info)))
4810 (when row-number
4811 (cons row-number
4812 (let ((col-count 0))
4813 (org-element-map table-row 'table-cell
4814 (lambda (cell)
4815 (if (eq cell table-cell) col-count (incf col-count) nil))
4816 info 'first-match))))))
4818 (defun org-export-get-table-cell-at (address table info)
4819 "Return regular table-cell object at ADDRESS in TABLE.
4821 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4822 zero-based index. TABLE is a table type element. INFO is
4823 a plist used as a communication channel.
4825 If no table-cell, among exportable cells, is found at ADDRESS,
4826 return nil."
4827 (let ((column-pos (cdr address)) (column-count 0))
4828 (org-element-map
4829 ;; Row at (car address) or nil.
4830 (let ((row-pos (car address)) (row-count 0))
4831 (org-element-map table 'table-row
4832 (lambda (row)
4833 (cond ((eq (org-element-property :type row) 'rule) nil)
4834 ((= row-count row-pos) row)
4835 (t (incf row-count) nil)))
4836 info 'first-match))
4837 'table-cell
4838 (lambda (cell)
4839 (if (= column-count column-pos) cell
4840 (incf column-count) nil))
4841 info 'first-match)))
4844 ;;;; For Tables Of Contents
4846 ;; `org-export-collect-headlines' builds a list of all exportable
4847 ;; headline elements, maybe limited to a certain depth. One can then
4848 ;; easily parse it and transcode it.
4850 ;; Building lists of tables, figures or listings is quite similar.
4851 ;; Once the generic function `org-export-collect-elements' is defined,
4852 ;; `org-export-collect-tables', `org-export-collect-figures' and
4853 ;; `org-export-collect-listings' can be derived from it.
4855 (defun org-export-collect-headlines (info &optional n scope)
4856 "Collect headlines in order to build a table of contents.
4858 INFO is a plist used as a communication channel.
4860 When optional argument N is an integer, it specifies the depth of
4861 the table of contents. Otherwise, it is set to the value of the
4862 last headline level. See `org-export-headline-levels' for more
4863 information.
4865 Optional argument SCOPE, when non-nil, is an element. If it is
4866 a headline, only children of SCOPE are collected. Otherwise,
4867 collect children of the headline containing provided element. If
4868 there is no such headline, collect all headlines. In any case,
4869 argument N becomes relative to the level of that headline.
4871 Return a list of all exportable headlines as parsed elements.
4872 Footnote sections are ignored."
4873 (let* ((scope (cond ((not scope) (plist-get info :parse-tree))
4874 ((eq (org-element-type scope) 'headline) scope)
4875 ((org-export-get-parent-headline scope))
4876 (t (plist-get info :parse-tree))))
4877 (limit (plist-get info :headline-levels))
4878 (n (if (not (wholenump n)) limit
4879 (min (if (eq (org-element-type scope) 'org-data) n
4880 (+ (org-export-get-relative-level scope info) n))
4881 limit))))
4882 (org-element-map (org-element-contents scope) 'headline
4883 (lambda (headline)
4884 (unless (org-element-property :footnote-section-p headline)
4885 (let ((level (org-export-get-relative-level headline info)))
4886 (and (<= level n) headline))))
4887 info)))
4889 (defun org-export-collect-elements (type info &optional predicate)
4890 "Collect referenceable elements of a determined type.
4892 TYPE can be a symbol or a list of symbols specifying element
4893 types to search. Only elements with a caption are collected.
4895 INFO is a plist used as a communication channel.
4897 When non-nil, optional argument PREDICATE is a function accepting
4898 one argument, an element of type TYPE. It returns a non-nil
4899 value when that element should be collected.
4901 Return a list of all elements found, in order of appearance."
4902 (org-element-map (plist-get info :parse-tree) type
4903 (lambda (element)
4904 (and (org-element-property :caption element)
4905 (or (not predicate) (funcall predicate element))
4906 element))
4907 info))
4909 (defun org-export-collect-tables (info)
4910 "Build a list of tables.
4911 INFO is a plist used as a communication channel.
4913 Return a list of table elements with a caption."
4914 (org-export-collect-elements 'table info))
4916 (defun org-export-collect-figures (info predicate)
4917 "Build a list of figures.
4919 INFO is a plist used as a communication channel. PREDICATE is
4920 a function which accepts one argument: a paragraph element and
4921 whose return value is non-nil when that element should be
4922 collected.
4924 A figure is a paragraph type element, with a caption, verifying
4925 PREDICATE. The latter has to be provided since a \"figure\" is
4926 a vague concept that may depend on back-end.
4928 Return a list of elements recognized as figures."
4929 (org-export-collect-elements 'paragraph info predicate))
4931 (defun org-export-collect-listings (info)
4932 "Build a list of src blocks.
4934 INFO is a plist used as a communication channel.
4936 Return a list of src-block elements with a caption."
4937 (org-export-collect-elements 'src-block info))
4940 ;;;; Smart Quotes
4942 ;; The main function for the smart quotes sub-system is
4943 ;; `org-export-activate-smart-quotes', which replaces every quote in
4944 ;; a given string from the parse tree with its "smart" counterpart.
4946 ;; Dictionary for smart quotes is stored in
4947 ;; `org-export-smart-quotes-alist'.
4949 ;; Internally, regexps matching potential smart quotes (checks at
4950 ;; string boundaries are also necessary) are defined in
4951 ;; `org-export-smart-quotes-regexps'.
4953 (defconst org-export-smart-quotes-alist
4954 '(("da"
4955 ;; one may use: »...«, "...", ›...‹, or '...'.
4956 ;; http://sproget.dk/raad-og-regler/retskrivningsregler/retskrivningsregler/a7-40-60/a7-58-anforselstegn/
4957 ;; LaTeX quotes require Babel!
4958 (opening-double-quote :utf-8 "»" :html "&raquo;" :latex ">>"
4959 :texinfo "@guillemetright{}")
4960 (closing-double-quote :utf-8 "«" :html "&laquo;" :latex "<<"
4961 :texinfo "@guillemetleft{}")
4962 (opening-single-quote :utf-8 "›" :html "&rsaquo;" :latex "\\frq{}"
4963 :texinfo "@guilsinglright{}")
4964 (closing-single-quote :utf-8 "‹" :html "&lsaquo;" :latex "\\flq{}"
4965 :texinfo "@guilsingleft{}")
4966 (apostrophe :utf-8 "’" :html "&rsquo;"))
4967 ("de"
4968 (opening-double-quote :utf-8 "„" :html "&bdquo;" :latex "\"`"
4969 :texinfo "@quotedblbase{}")
4970 (closing-double-quote :utf-8 "“" :html "&ldquo;" :latex "\"'"
4971 :texinfo "@quotedblleft{}")
4972 (opening-single-quote :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}"
4973 :texinfo "@quotesinglbase{}")
4974 (closing-single-quote :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}"
4975 :texinfo "@quoteleft{}")
4976 (apostrophe :utf-8 "’" :html "&rsquo;"))
4977 ("en"
4978 (opening-double-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
4979 (closing-double-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
4980 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
4981 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
4982 (apostrophe :utf-8 "’" :html "&rsquo;"))
4983 ("es"
4984 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
4985 :texinfo "@guillemetleft{}")
4986 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
4987 :texinfo "@guillemetright{}")
4988 (opening-single-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
4989 (closing-single-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
4990 (apostrophe :utf-8 "’" :html "&rsquo;"))
4991 ("fr"
4992 (opening-double-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
4993 :texinfo "@guillemetleft{}@tie{}")
4994 (closing-double-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
4995 :texinfo "@tie{}@guillemetright{}")
4996 (opening-single-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
4997 :texinfo "@guillemetleft{}@tie{}")
4998 (closing-single-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
4999 :texinfo "@tie{}@guillemetright{}")
5000 (apostrophe :utf-8 "’" :html "&rsquo;"))
5001 ("no"
5002 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5003 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5004 :texinfo "@guillemetleft{}")
5005 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5006 :texinfo "@guillemetright{}")
5007 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5008 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5009 (apostrophe :utf-8 "’" :html "&rsquo;"))
5010 ("nb"
5011 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5012 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5013 :texinfo "@guillemetleft{}")
5014 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5015 :texinfo "@guillemetright{}")
5016 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5017 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5018 (apostrophe :utf-8 "’" :html "&rsquo;"))
5019 ("nn"
5020 ;; https://nn.wikipedia.org/wiki/Sitatteikn
5021 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
5022 :texinfo "@guillemetleft{}")
5023 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
5024 :texinfo "@guillemetright{}")
5025 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
5026 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
5027 (apostrophe :utf-8 "’" :html "&rsquo;"))
5028 ("ru"
5029 ;; 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
5030 ;; http://www.artlebedev.ru/kovodstvo/sections/104/
5031 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "{}<<"
5032 :texinfo "@guillemetleft{}")
5033 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex ">>{}"
5034 :texinfo "@guillemetright{}")
5035 (opening-single-quote :utf-8 "„" :html "&bdquo;" :latex "\\glqq{}"
5036 :texinfo "@quotedblbase{}")
5037 (closing-single-quote :utf-8 "“" :html "&ldquo;" :latex "\\grqq{}"
5038 :texinfo "@quotedblleft{}")
5039 (apostrophe :utf-8 "’" :html: "&#39;"))
5040 ("sv"
5041 ;; based on https://sv.wikipedia.org/wiki/Citattecken
5042 (opening-double-quote :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
5043 (closing-double-quote :utf-8 "”" :html "&rdquo;" :latex "’’" :texinfo "’’")
5044 (opening-single-quote :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "`")
5045 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "’" :texinfo "'")
5046 (apostrophe :utf-8 "’" :html "&rsquo;"))
5048 "Smart quotes translations.
5050 Alist whose CAR is a language string and CDR is an alist with
5051 quote type as key and a plist associating various encodings to
5052 their translation as value.
5054 A quote type can be any symbol among `opening-double-quote',
5055 `closing-double-quote', `opening-single-quote',
5056 `closing-single-quote' and `apostrophe'.
5058 Valid encodings include `:utf-8', `:html', `:latex' and
5059 `:texinfo'.
5061 If no translation is found, the quote character is left as-is.")
5063 (defconst org-export-smart-quotes-regexps
5064 (list
5065 ;; Possible opening quote at beginning of string.
5066 "\\`\\([\"']\\)\\(\\w\\|\\s.\\|\\s_\\|\\s(\\)"
5067 ;; Possible closing quote at beginning of string.
5068 "\\`\\([\"']\\)\\(\\s-\\|\\s)\\|\\s.\\)"
5069 ;; Possible apostrophe at beginning of string.
5070 "\\`\\('\\)\\S-"
5071 ;; Opening single and double quotes.
5072 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\(?:\\w\\|\\s.\\|\\s_\\)"
5073 ;; Closing single and double quotes.
5074 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\(?:\\s-\\|\\s)\\|\\s.\\)"
5075 ;; Apostrophe.
5076 "\\S-\\('\\)\\S-"
5077 ;; Possible opening quote at end of string.
5078 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\'"
5079 ;; Possible closing quote at end of string.
5080 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\'"
5081 ;; Possible apostrophe at end of string.
5082 "\\S-\\('\\)\\'")
5083 "List of regexps matching a quote or an apostrophe.
5084 In every regexp, quote or apostrophe matched is put in group 1.")
5086 (defun org-export-activate-smart-quotes (s encoding info &optional original)
5087 "Replace regular quotes with \"smart\" quotes in string S.
5089 ENCODING is a symbol among `:html', `:latex', `:texinfo' and
5090 `:utf-8'. INFO is a plist used as a communication channel.
5092 The function has to retrieve information about string
5093 surroundings in parse tree. It can only happen with an
5094 unmodified string. Thus, if S has already been through another
5095 process, a non-nil ORIGINAL optional argument will provide that
5096 original string.
5098 Return the new string."
5099 (if (equal s "") ""
5100 (let* ((prev (org-export-get-previous-element (or original s) info))
5101 ;; Try to be flexible when computing number of blanks
5102 ;; before object. The previous object may be a string
5103 ;; introduced by the back-end and not completely parsed.
5104 (pre-blank (and prev
5105 (or (org-element-property :post-blank prev)
5106 ;; A string with missing `:post-blank'
5107 ;; property.
5108 (and (stringp prev)
5109 (string-match " *\\'" prev)
5110 (length (match-string 0 prev)))
5111 ;; Fallback value.
5112 0)))
5113 (next (org-export-get-next-element (or original s) info))
5114 (get-smart-quote
5115 (lambda (q type)
5116 ;; Return smart quote associated to a give quote Q, as
5117 ;; a string. TYPE is a symbol among `open', `close' and
5118 ;; `apostrophe'.
5119 (let ((key (case type
5120 (apostrophe 'apostrophe)
5121 (open (if (equal "'" q) 'opening-single-quote
5122 'opening-double-quote))
5123 (otherwise (if (equal "'" q) 'closing-single-quote
5124 'closing-double-quote)))))
5125 (or (plist-get
5126 (cdr (assq key
5127 (cdr (assoc (plist-get info :language)
5128 org-export-smart-quotes-alist))))
5129 encoding)
5130 q)))))
5131 (if (or (equal "\"" s) (equal "'" s))
5132 ;; Only a quote: no regexp can match. We have to check both
5133 ;; sides and decide what to do.
5134 (cond ((and (not prev) (not next)) s)
5135 ((not prev) (funcall get-smart-quote s 'open))
5136 ((and (not next) (zerop pre-blank))
5137 (funcall get-smart-quote s 'close))
5138 ((not next) s)
5139 ((zerop pre-blank) (funcall get-smart-quote s 'apostrophe))
5140 (t (funcall get-smart-quote 'open)))
5141 ;; 1. Replace quote character at the beginning of S.
5142 (cond
5143 ;; Apostrophe?
5144 ((and prev (zerop pre-blank)
5145 (string-match (nth 2 org-export-smart-quotes-regexps) s))
5146 (setq s (replace-match
5147 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
5148 nil t s 1)))
5149 ;; Closing quote?
5150 ((and prev (zerop pre-blank)
5151 (string-match (nth 1 org-export-smart-quotes-regexps) s))
5152 (setq s (replace-match
5153 (funcall get-smart-quote (match-string 1 s) 'close)
5154 nil t s 1)))
5155 ;; Opening quote?
5156 ((and (or (not prev) (> pre-blank 0))
5157 (string-match (nth 0 org-export-smart-quotes-regexps) s))
5158 (setq s (replace-match
5159 (funcall get-smart-quote (match-string 1 s) 'open)
5160 nil t s 1))))
5161 ;; 2. Replace quotes in the middle of the string.
5162 (setq s (replace-regexp-in-string
5163 ;; Opening quotes.
5164 (nth 3 org-export-smart-quotes-regexps)
5165 (lambda (text)
5166 (funcall get-smart-quote (match-string 1 text) 'open))
5167 s nil t 1))
5168 (setq s (replace-regexp-in-string
5169 ;; Closing quotes.
5170 (nth 4 org-export-smart-quotes-regexps)
5171 (lambda (text)
5172 (funcall get-smart-quote (match-string 1 text) 'close))
5173 s nil t 1))
5174 (setq s (replace-regexp-in-string
5175 ;; Apostrophes.
5176 (nth 5 org-export-smart-quotes-regexps)
5177 (lambda (text)
5178 (funcall get-smart-quote (match-string 1 text) 'apostrophe))
5179 s nil t 1))
5180 ;; 3. Replace quote character at the end of S.
5181 (cond
5182 ;; Apostrophe?
5183 ((and next (string-match (nth 8 org-export-smart-quotes-regexps) s))
5184 (setq s (replace-match
5185 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
5186 nil t s 1)))
5187 ;; Closing quote?
5188 ((and (not next)
5189 (string-match (nth 7 org-export-smart-quotes-regexps) s))
5190 (setq s (replace-match
5191 (funcall get-smart-quote (match-string 1 s) 'close)
5192 nil t s 1)))
5193 ;; Opening quote?
5194 ((and next (string-match (nth 6 org-export-smart-quotes-regexps) s))
5195 (setq s (replace-match
5196 (funcall get-smart-quote (match-string 1 s) 'open)
5197 nil t s 1))))
5198 ;; Return string with smart quotes.
5199 s))))
5201 ;;;; Topology
5203 ;; Here are various functions to retrieve information about the
5204 ;; neighborhood of a given element or object. Neighbors of interest
5205 ;; are direct parent (`org-export-get-parent'), parent headline
5206 ;; (`org-export-get-parent-headline'), first element containing an
5207 ;; object, (`org-export-get-parent-element'), parent table
5208 ;; (`org-export-get-parent-table'), previous element or object
5209 ;; (`org-export-get-previous-element') and next element or object
5210 ;; (`org-export-get-next-element').
5212 ;; defsubst org-export-get-parent must be defined before first use
5214 (define-obsolete-function-alias
5215 'org-export-get-genealogy 'org-element-lineage "25.1")
5217 (defun org-export-get-parent-headline (blob)
5218 "Return BLOB parent headline or nil.
5219 BLOB is the element or object being considered."
5220 (org-element-lineage blob '(headline)))
5222 (defun org-export-get-parent-element (object)
5223 "Return first element containing OBJECT or nil.
5224 OBJECT is the object to consider."
5225 (org-element-lineage object org-element-all-elements))
5227 (defun org-export-get-parent-table (object)
5228 "Return OBJECT parent table or nil.
5229 OBJECT is either a `table-cell' or `table-element' type object."
5230 (org-element-lineage object '(table)))
5232 (defun org-export-get-previous-element (blob info &optional n)
5233 "Return previous element or object.
5235 BLOB is an element or object. INFO is a plist used as
5236 a communication channel. Return previous exportable element or
5237 object, a string, or nil.
5239 When optional argument N is a positive integer, return a list
5240 containing up to N siblings before BLOB, from farthest to
5241 closest. With any other non-nil value, return a list containing
5242 all of them."
5243 (let* ((secondary (org-element-secondary-p blob))
5244 (parent (org-export-get-parent blob))
5245 (siblings
5246 (if secondary (org-element-property secondary parent)
5247 (org-element-contents parent)))
5248 prev)
5249 (catch 'exit
5250 (dolist (obj (cdr (memq blob (reverse siblings))) prev)
5251 (cond ((memq obj (plist-get info :ignore-list)))
5252 ((null n) (throw 'exit obj))
5253 ((not (wholenump n)) (push obj prev))
5254 ((zerop n) (throw 'exit prev))
5255 (t (decf n) (push obj prev)))))))
5257 (defun org-export-get-next-element (blob info &optional n)
5258 "Return next element or object.
5260 BLOB is an element or object. INFO is a plist used as
5261 a communication channel. Return next exportable element or
5262 object, a string, or nil.
5264 When optional argument N is a positive integer, return a list
5265 containing up to N siblings after BLOB, from closest to farthest.
5266 With any other non-nil value, return a list containing all of
5267 them."
5268 (let* ((secondary (org-element-secondary-p blob))
5269 (parent (org-export-get-parent blob))
5270 (siblings
5271 (cdr (memq blob
5272 (if secondary (org-element-property secondary parent)
5273 (org-element-contents parent)))))
5274 next)
5275 (catch 'exit
5276 (dolist (obj siblings (nreverse next))
5277 (cond ((memq obj (plist-get info :ignore-list)))
5278 ((null n) (throw 'exit obj))
5279 ((not (wholenump n)) (push obj next))
5280 ((zerop n) (throw 'exit (nreverse next)))
5281 (t (decf n) (push obj next)))))))
5284 ;;;; Translation
5286 ;; `org-export-translate' translates a string according to the language
5287 ;; specified by the LANGUAGE keyword. `org-export-dictionary' contains
5288 ;; the dictionary used for the translation.
5290 (defconst org-export-dictionary
5291 '(("%e %n: %c"
5292 ("fr" :default "%e %n : %c" :html "%e&nbsp;%n&nbsp;: %c"))
5293 ("Author"
5294 ("ca" :default "Autor")
5295 ("cs" :default "Autor")
5296 ("da" :default "Forfatter")
5297 ("de" :default "Autor")
5298 ("eo" :html "A&#365;toro")
5299 ("es" :default "Autor")
5300 ("et" :default "Autor")
5301 ("fi" :html "Tekij&auml;")
5302 ("fr" :default "Auteur")
5303 ("hu" :default "Szerz&otilde;")
5304 ("is" :html "H&ouml;fundur")
5305 ("it" :default "Autore")
5306 ("ja" :default "著者" :html "&#33879;&#32773;")
5307 ("nl" :default "Auteur")
5308 ("no" :default "Forfatter")
5309 ("nb" :default "Forfatter")
5310 ("nn" :default "Forfattar")
5311 ("pl" :default "Autor")
5312 ("pt_BR" :default "Autor")
5313 ("ru" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5314 ("sv" :html "F&ouml;rfattare")
5315 ("uk" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5316 ("zh-CN" :html "&#20316;&#32773;" :utf-8 "作者")
5317 ("zh-TW" :html "&#20316;&#32773;" :utf-8 "作者"))
5318 ("Continued from previous page"
5319 ("de" :default "Fortsetzung von vorheriger Seite")
5320 ("es" :default "Continúa de la página anterior")
5321 ("fr" :default "Suite de la page précédente")
5322 ("it" :default "Continua da pagina precedente")
5323 ("ja" :default "前ページからの続き")
5324 ("nl" :default "Vervolg van vorige pagina")
5325 ("pt" :default "Continuação da página anterior")
5326 ("ru" :html "(&#1055;&#1088;&#1086;&#1076;&#1086;&#1083;&#1078;&#1077;&#1085;&#1080;&#1077;)"
5327 :utf-8 "(Продолжение)"))
5328 ("Continued on next page"
5329 ("de" :default "Fortsetzung nächste Seite")
5330 ("es" :default "Continúa en la siguiente página")
5331 ("fr" :default "Suite page suivante")
5332 ("it" :default "Continua alla pagina successiva")
5333 ("ja" :default "次ページに続く")
5334 ("nl" :default "Vervolg op volgende pagina")
5335 ("pt" :default "Continua na página seguinte")
5336 ("ru" :html "(&#1055;&#1088;&#1086;&#1076;&#1086;&#1083;&#1078;&#1077;&#1085;&#1080;&#1077; &#1089;&#1083;&#1077;&#1076;&#1091;&#1077;&#1090;)"
5337 :utf-8 "(Продолжение следует)"))
5338 ("Date"
5339 ("ca" :default "Data")
5340 ("cs" :default "Datum")
5341 ("da" :default "Dato")
5342 ("de" :default "Datum")
5343 ("eo" :default "Dato")
5344 ("es" :default "Fecha")
5345 ("et" :html "Kuup&#228;ev" :utf-8 "Kuupäev")
5346 ("fi" :html "P&auml;iv&auml;m&auml;&auml;r&auml;")
5347 ("hu" :html "D&aacute;tum")
5348 ("is" :default "Dagsetning")
5349 ("it" :default "Data")
5350 ("ja" :default "日付" :html "&#26085;&#20184;")
5351 ("nl" :default "Datum")
5352 ("no" :default "Dato")
5353 ("nb" :default "Dato")
5354 ("nn" :default "Dato")
5355 ("pl" :default "Data")
5356 ("pt_BR" :default "Data")
5357 ("ru" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5358 ("sv" :default "Datum")
5359 ("uk" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5360 ("zh-CN" :html "&#26085;&#26399;" :utf-8 "日期")
5361 ("zh-TW" :html "&#26085;&#26399;" :utf-8 "日期"))
5362 ("Equation"
5363 ("da" :default "Ligning")
5364 ("de" :default "Gleichung")
5365 ("es" :html "Ecuaci&oacute;n" :default "Ecuación")
5366 ("et" :html "V&#245;rrand" :utf-8 "Võrrand")
5367 ("fr" :ascii "Equation" :default "Équation")
5368 ("ja" :default "方程式")
5369 ("no" :default "Ligning")
5370 ("nb" :default "Ligning")
5371 ("nn" :default "Likning")
5372 ("pt_BR" :html "Equa&ccedil;&atilde;o" :default "Equação" :ascii "Equacao")
5373 ("ru" :html "&#1059;&#1088;&#1072;&#1074;&#1085;&#1077;&#1085;&#1080;&#1077;"
5374 :utf-8 "Уравнение")
5375 ("sv" :default "Ekvation")
5376 ("zh-CN" :html "&#26041;&#31243;" :utf-8 "方程"))
5377 ("Figure"
5378 ("da" :default "Figur")
5379 ("de" :default "Abbildung")
5380 ("es" :default "Figura")
5381 ("et" :default "Joonis")
5382 ("ja" :default "図" :html "&#22259;")
5383 ("no" :default "Illustrasjon")
5384 ("nb" :default "Illustrasjon")
5385 ("nn" :default "Illustrasjon")
5386 ("pt_BR" :default "Figura")
5387 ("ru" :html "&#1056;&#1080;&#1089;&#1091;&#1085;&#1086;&#1082;" :utf-8 "Рисунок")
5388 ("sv" :default "Illustration")
5389 ("zh-CN" :html "&#22270;" :utf-8 "图"))
5390 ("Figure %d:"
5391 ("da" :default "Figur %d")
5392 ("de" :default "Abbildung %d:")
5393 ("es" :default "Figura %d:")
5394 ("et" :default "Joonis %d:")
5395 ("fr" :default "Figure %d :" :html "Figure&nbsp;%d&nbsp;:")
5396 ("ja" :default "図%d: " :html "&#22259;%d: ")
5397 ("no" :default "Illustrasjon %d")
5398 ("nb" :default "Illustrasjon %d")
5399 ("nn" :default "Illustrasjon %d")
5400 ("pt_BR" :default "Figura %d:")
5401 ("ru" :html "&#1056;&#1080;&#1089;. %d.:" :utf-8 "Рис. %d.:")
5402 ("sv" :default "Illustration %d")
5403 ("zh-CN" :html "&#22270;%d&nbsp;" :utf-8 "图%d "))
5404 ("Footnotes"
5405 ("ca" :html "Peus de p&agrave;gina")
5406 ("cs" :default "Pozn\xe1mky pod carou")
5407 ("da" :default "Fodnoter")
5408 ("de" :html "Fu&szlig;noten" :default "Fußnoten")
5409 ("eo" :default "Piednotoj")
5410 ("es" :html "Nota al pie de p&aacute;gina" :default "Nota al pie de página")
5411 ("et" :html "Allm&#228;rkused" :utf-8 "Allmärkused")
5412 ("fi" :default "Alaviitteet")
5413 ("fr" :default "Notes de bas de page")
5414 ("hu" :html "L&aacute;bjegyzet")
5415 ("is" :html "Aftanm&aacute;lsgreinar")
5416 ("it" :html "Note a pi&egrave; di pagina")
5417 ("ja" :default "脚注" :html "&#33050;&#27880;")
5418 ("nl" :default "Voetnoten")
5419 ("no" :default "Fotnoter")
5420 ("nb" :default "Fotnoter")
5421 ("nn" :default "Fotnotar")
5422 ("pl" :default "Przypis")
5423 ("pt_BR" :html "Notas de Rodap&eacute;" :default "Notas de Rodapé" :ascii "Notas de Rodape")
5424 ("ru" :html "&#1057;&#1085;&#1086;&#1089;&#1082;&#1080;" :utf-8 "Сноски")
5425 ("sv" :default "Fotnoter")
5426 ("uk" :html "&#1055;&#1088;&#1080;&#1084;&#1110;&#1090;&#1082;&#1080;"
5427 :utf-8 "Примітки")
5428 ("zh-CN" :html "&#33050;&#27880;" :utf-8 "脚注")
5429 ("zh-TW" :html "&#33139;&#35387;" :utf-8 "腳註"))
5430 ("List of Listings"
5431 ("da" :default "Programmer")
5432 ("de" :default "Programmauflistungsverzeichnis")
5433 ("es" :default "Indice de Listados de programas")
5434 ("et" :default "Loendite nimekiri")
5435 ("fr" :default "Liste des programmes")
5436 ("ja" :default "ソースコード目次")
5437 ("no" :default "Dataprogrammer")
5438 ("nb" :default "Dataprogrammer")
5439 ("ru" :html "&#1057;&#1087;&#1080;&#1089;&#1086;&#1082; &#1088;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1086;&#1082;"
5440 :utf-8 "Список распечаток")
5441 ("zh-CN" :html "&#20195;&#30721;&#30446;&#24405;" :utf-8 "代码目录"))
5442 ("List of Tables"
5443 ("da" :default "Tabeller")
5444 ("de" :default "Tabellenverzeichnis")
5445 ("es" :default "Indice de tablas")
5446 ("et" :default "Tabelite nimekiri")
5447 ("fr" :default "Liste des tableaux")
5448 ("ja" :default "表目次")
5449 ("no" :default "Tabeller")
5450 ("nb" :default "Tabeller")
5451 ("nn" :default "Tabeller")
5452 ("pt_BR" :default "Índice de Tabelas" :ascii "Indice de Tabelas")
5453 ("ru" :html "&#1057;&#1087;&#1080;&#1089;&#1086;&#1082; &#1090;&#1072;&#1073;&#1083;&#1080;&#1094;"
5454 :utf-8 "Список таблиц")
5455 ("sv" :default "Tabeller")
5456 ("zh-CN" :html "&#34920;&#26684;&#30446;&#24405;" :utf-8 "表格目录"))
5457 ("Listing %d:"
5458 ("da" :default "Program %d")
5459 ("de" :default "Programmlisting %d")
5460 ("es" :default "Listado de programa %d")
5461 ("et" :default "Loend %d")
5462 ("fr" :default "Programme %d :" :html "Programme&nbsp;%d&nbsp;:")
5463 ("ja" :default "ソースコード%d:")
5464 ("no" :default "Dataprogram %d")
5465 ("nb" :default "Dataprogram %d")
5466 ("pt_BR" :default "Listagem %d")
5467 ("ru" :html "&#1056;&#1072;&#1089;&#1087;&#1077;&#1095;&#1072;&#1090;&#1082;&#1072; %d.:"
5468 :utf-8 "Распечатка %d.:")
5469 ("zh-CN" :html "&#20195;&#30721;%d&nbsp;" :utf-8 "代码%d "))
5470 ("References"
5471 ("fr" :ascii "References" :default "Références")
5472 ("de" :default "Quellen"))
5473 ("See section %s"
5474 ("da" :default "jævnfør afsnit %s")
5475 ("de" :default "siehe Abschnitt %s")
5476 ("es" :default "vea seccion %s")
5477 ("et" :html "Vaata peat&#252;kki %s" :utf-8 "Vaata peatükki %s")
5478 ("fr" :default "cf. section %s")
5479 ("ja" :default "セクション %s を参照")
5480 ("pt_BR" :html "Veja a se&ccedil;&atilde;o %s" :default "Veja a seção %s"
5481 :ascii "Veja a secao %s")
5482 ("ru" :html "&#1057;&#1084;. &#1088;&#1072;&#1079;&#1076;&#1077;&#1083; %s"
5483 :utf-8 "См. раздел %s")
5484 ("zh-CN" :html "&#21442;&#35265;&#31532;%s&#33410;" :utf-8 "参见第%s节"))
5485 ("Table"
5486 ("de" :default "Tabelle")
5487 ("es" :default "Tabla")
5488 ("et" :default "Tabel")
5489 ("fr" :default "Tableau")
5490 ("ja" :default "表" :html "&#34920;")
5491 ("pt_BR" :default "Tabela")
5492 ("ru" :html "&#1058;&#1072;&#1073;&#1083;&#1080;&#1094;&#1072;"
5493 :utf-8 "Таблица")
5494 ("zh-CN" :html "&#34920;" :utf-8 "表"))
5495 ("Table %d:"
5496 ("da" :default "Tabel %d")
5497 ("de" :default "Tabelle %d")
5498 ("es" :default "Tabla %d")
5499 ("et" :default "Tabel %d")
5500 ("fr" :default "Tableau %d :")
5501 ("ja" :default "表%d:" :html "&#34920;%d:")
5502 ("no" :default "Tabell %d")
5503 ("nb" :default "Tabell %d")
5504 ("nn" :default "Tabell %d")
5505 ("pt_BR" :default "Tabela %d")
5506 ("ru" :html "&#1058;&#1072;&#1073;&#1083;&#1080;&#1094;&#1072; %d.:"
5507 :utf-8 "Таблица %d.:")
5508 ("sv" :default "Tabell %d")
5509 ("zh-CN" :html "&#34920;%d&nbsp;" :utf-8 "表%d "))
5510 ("Table of Contents"
5511 ("ca" :html "&Iacute;ndex")
5512 ("cs" :default "Obsah")
5513 ("da" :default "Indhold")
5514 ("de" :default "Inhaltsverzeichnis")
5515 ("eo" :default "Enhavo")
5516 ("es" :html "&Iacute;ndice")
5517 ("et" :default "Sisukord")
5518 ("fi" :html "Sis&auml;llysluettelo")
5519 ("fr" :ascii "Sommaire" :default "Table des matières")
5520 ("hu" :html "Tartalomjegyz&eacute;k")
5521 ("is" :default "Efnisyfirlit")
5522 ("it" :default "Indice")
5523 ("ja" :default "目次" :html "&#30446;&#27425;")
5524 ("nl" :default "Inhoudsopgave")
5525 ("no" :default "Innhold")
5526 ("nb" :default "Innhold")
5527 ("nn" :default "Innhald")
5528 ("pl" :html "Spis tre&#x015b;ci")
5529 ("pt_BR" :html "&Iacute;ndice" :utf8 "Índice" :ascii "Indice")
5530 ("ru" :html "&#1057;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1077;"
5531 :utf-8 "Содержание")
5532 ("sv" :html "Inneh&aring;ll")
5533 ("uk" :html "&#1047;&#1084;&#1110;&#1089;&#1090;" :utf-8 "Зміст")
5534 ("zh-CN" :html "&#30446;&#24405;" :utf-8 "目录")
5535 ("zh-TW" :html "&#30446;&#37636;" :utf-8 "目錄"))
5536 ("Unknown reference"
5537 ("da" :default "ukendt reference")
5538 ("de" :default "Unbekannter Verweis")
5539 ("es" :default "referencia desconocida")
5540 ("et" :default "Tundmatu viide")
5541 ("fr" :ascii "Destination inconnue" :default "Référence inconnue")
5542 ("ja" :default "不明な参照先")
5543 ("pt_BR" :default "Referência desconhecida"
5544 :ascii "Referencia desconhecida")
5545 ("ru" :html "&#1053;&#1077;&#1080;&#1079;&#1074;&#1077;&#1089;&#1090;&#1085;&#1072;&#1103; &#1089;&#1089;&#1099;&#1083;&#1082;&#1072;"
5546 :utf-8 "Неизвестная ссылка")
5547 ("zh-CN" :html "&#26410;&#30693;&#24341;&#29992;" :utf-8 "未知引用")))
5548 "Dictionary for export engine.
5550 Alist whose car is the string to translate and cdr is an alist
5551 whose car is the language string and cdr is a plist whose
5552 properties are possible charsets and values translated terms.
5554 It is used as a database for `org-export-translate'. Since this
5555 function returns the string as-is if no translation was found,
5556 the variable only needs to record values different from the
5557 entry.")
5559 (defun org-export-translate (s encoding info)
5560 "Translate string S according to language specification.
5562 ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1'
5563 and `:utf-8'. INFO is a plist used as a communication channel.
5565 Translation depends on `:language' property. Return the
5566 translated string. If no translation is found, try to fall back
5567 to `:default' encoding. If it fails, return S."
5568 (let* ((lang (plist-get info :language))
5569 (translations (cdr (assoc lang
5570 (cdr (assoc s org-export-dictionary))))))
5571 (or (plist-get translations encoding)
5572 (plist-get translations :default)
5573 s)))
5577 ;;; Asynchronous Export
5579 ;; `org-export-async-start' is the entry point for asynchronous
5580 ;; export. It recreates current buffer (including visibility,
5581 ;; narrowing and visited file) in an external Emacs process, and
5582 ;; evaluates a command there. It then applies a function on the
5583 ;; returned results in the current process.
5585 ;; At a higher level, `org-export-to-buffer' and `org-export-to-file'
5586 ;; allow to export to a buffer or a file, asynchronously or not.
5588 ;; `org-export-output-file-name' is an auxiliary function meant to be
5589 ;; used with `org-export-to-file'. With a given extension, it tries
5590 ;; to provide a canonical file name to write export output to.
5592 ;; Asynchronously generated results are never displayed directly.
5593 ;; Instead, they are stored in `org-export-stack-contents'. They can
5594 ;; then be retrieved by calling `org-export-stack'.
5596 ;; Export Stack is viewed through a dedicated major mode
5597 ;;`org-export-stack-mode' and tools: `org-export-stack-refresh',
5598 ;;`org-export-stack-delete', `org-export-stack-view' and
5599 ;;`org-export-stack-clear'.
5601 ;; For back-ends, `org-export-add-to-stack' add a new source to stack.
5602 ;; It should be used whenever `org-export-async-start' is called.
5604 (defmacro org-export-async-start (fun &rest body)
5605 "Call function FUN on the results returned by BODY evaluation.
5607 FUN is an anonymous function of one argument. BODY evaluation
5608 happens in an asynchronous process, from a buffer which is an
5609 exact copy of the current one.
5611 Use `org-export-add-to-stack' in FUN in order to register results
5612 in the stack.
5614 This is a low level function. See also `org-export-to-buffer'
5615 and `org-export-to-file' for more specialized functions."
5616 (declare (indent 1) (debug t))
5617 (org-with-gensyms (process temp-file copy-fun proc-buffer coding)
5618 ;; Write the full sexp evaluating BODY in a copy of the current
5619 ;; buffer to a temporary file, as it may be too long for program
5620 ;; args in `start-process'.
5621 `(with-temp-message "Initializing asynchronous export process"
5622 (let ((,copy-fun (org-export--generate-copy-script (current-buffer)))
5623 (,temp-file (make-temp-file "org-export-process"))
5624 (,coding buffer-file-coding-system))
5625 (with-temp-file ,temp-file
5626 (insert
5627 ;; Null characters (from variable values) are inserted
5628 ;; within the file. As a consequence, coding system for
5629 ;; buffer contents will not be recognized properly. So,
5630 ;; we make sure it is the same as the one used to display
5631 ;; the original buffer.
5632 (format ";; -*- coding: %s; -*-\n%S"
5633 ,coding
5634 `(with-temp-buffer
5635 (when org-export-async-debug '(setq debug-on-error t))
5636 ;; Ignore `kill-emacs-hook' and code evaluation
5637 ;; queries from Babel as we need a truly
5638 ;; non-interactive process.
5639 (setq kill-emacs-hook nil
5640 org-babel-confirm-evaluate-answer-no t)
5641 ;; Initialize export framework.
5642 (require 'ox)
5643 ;; Re-create current buffer there.
5644 (funcall ,,copy-fun)
5645 (restore-buffer-modified-p nil)
5646 ;; Sexp to evaluate in the buffer.
5647 (print (progn ,,@body))))))
5648 ;; Start external process.
5649 (let* ((process-connection-type nil)
5650 (,proc-buffer (generate-new-buffer-name "*Org Export Process*"))
5651 (,process
5652 (apply
5653 #'start-process
5654 (append
5655 (list "org-export-process"
5656 ,proc-buffer
5657 (expand-file-name invocation-name invocation-directory)
5658 "--batch")
5659 (if org-export-async-init-file
5660 (list "-Q" "-l" org-export-async-init-file)
5661 (list "-l" user-init-file))
5662 (list "-l" ,temp-file)))))
5663 ;; Register running process in stack.
5664 (org-export-add-to-stack (get-buffer ,proc-buffer) nil ,process)
5665 ;; Set-up sentinel in order to catch results.
5666 (let ((handler ,fun))
5667 (set-process-sentinel
5668 ,process
5669 `(lambda (p status)
5670 (let ((proc-buffer (process-buffer p)))
5671 (when (eq (process-status p) 'exit)
5672 (unwind-protect
5673 (if (zerop (process-exit-status p))
5674 (unwind-protect
5675 (let ((results
5676 (with-current-buffer proc-buffer
5677 (goto-char (point-max))
5678 (backward-sexp)
5679 (read (current-buffer)))))
5680 (funcall ,handler results))
5681 (unless org-export-async-debug
5682 (and (get-buffer proc-buffer)
5683 (kill-buffer proc-buffer))))
5684 (org-export-add-to-stack proc-buffer nil p)
5685 (ding)
5686 (message "Process '%s' exited abnormally" p))
5687 (unless org-export-async-debug
5688 (delete-file ,,temp-file)))))))))))))
5690 ;;;###autoload
5691 (defun org-export-to-buffer
5692 (backend buffer
5693 &optional async subtreep visible-only body-only ext-plist
5694 post-process)
5695 "Call `org-export-as' with output to a specified buffer.
5697 BACKEND is either an export back-end, as returned by, e.g.,
5698 `org-export-create-backend', or a symbol referring to
5699 a registered back-end.
5701 BUFFER is the name of the output buffer. If it already exists,
5702 it will be erased first, otherwise, it will be created.
5704 A non-nil optional argument ASYNC means the process should happen
5705 asynchronously. The resulting buffer should then be accessible
5706 through the `org-export-stack' interface. When ASYNC is nil, the
5707 buffer is displayed if `org-export-show-temporary-export-buffer'
5708 is non-nil.
5710 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
5711 EXT-PLIST are similar to those used in `org-export-as', which
5712 see.
5714 Optional argument POST-PROCESS is a function which should accept
5715 no argument. It is always called within the current process,
5716 from BUFFER, with point at its beginning. Export back-ends can
5717 use it to set a major mode there, e.g,
5719 \(defun org-latex-export-as-latex
5720 \(&optional async subtreep visible-only body-only ext-plist)
5721 \(interactive)
5722 \(org-export-to-buffer 'latex \"*Org LATEX Export*\"
5723 async subtreep visible-only body-only ext-plist (lambda () (LaTeX-mode))))
5725 This function returns BUFFER."
5726 (declare (indent 2))
5727 (if async
5728 (org-export-async-start
5729 `(lambda (output)
5730 (with-current-buffer (get-buffer-create ,buffer)
5731 (erase-buffer)
5732 (setq buffer-file-coding-system ',buffer-file-coding-system)
5733 (insert output)
5734 (goto-char (point-min))
5735 (org-export-add-to-stack (current-buffer) ',backend)
5736 (ignore-errors (funcall ,post-process))))
5737 `(org-export-as
5738 ',backend ,subtreep ,visible-only ,body-only ',ext-plist))
5739 (let ((output
5740 (org-export-as backend subtreep visible-only body-only ext-plist))
5741 (buffer (get-buffer-create buffer))
5742 (encoding buffer-file-coding-system))
5743 (when (and (org-string-nw-p output) (org-export--copy-to-kill-ring-p))
5744 (org-kill-new output))
5745 (with-current-buffer buffer
5746 (erase-buffer)
5747 (setq buffer-file-coding-system encoding)
5748 (insert output)
5749 (goto-char (point-min))
5750 (and (functionp post-process) (funcall post-process)))
5751 (when org-export-show-temporary-export-buffer
5752 (switch-to-buffer-other-window buffer))
5753 buffer)))
5755 ;;;###autoload
5756 (defun org-export-to-file
5757 (backend file &optional async subtreep visible-only body-only ext-plist
5758 post-process)
5759 "Call `org-export-as' with output to a specified file.
5761 BACKEND is either an export back-end, as returned by, e.g.,
5762 `org-export-create-backend', or a symbol referring to
5763 a registered back-end. FILE is the name of the output file, as
5764 a string.
5766 A non-nil optional argument ASYNC means the process should happen
5767 asynchronously. The resulting buffer will then be accessible
5768 through the `org-export-stack' interface.
5770 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
5771 EXT-PLIST are similar to those used in `org-export-as', which
5772 see.
5774 Optional argument POST-PROCESS is called with FILE as its
5775 argument and happens asynchronously when ASYNC is non-nil. It
5776 has to return a file name, or nil. Export back-ends can use this
5777 to send the output file through additional processing, e.g,
5779 \(defun org-latex-export-to-latex
5780 \(&optional async subtreep visible-only body-only ext-plist)
5781 \(interactive)
5782 \(let ((outfile (org-export-output-file-name \".tex\" subtreep)))
5783 \(org-export-to-file 'latex outfile
5784 async subtreep visible-only body-only ext-plist
5785 \(lambda (file) (org-latex-compile file)))
5787 The function returns either a file name returned by POST-PROCESS,
5788 or FILE."
5789 (declare (indent 2))
5790 (if (not (file-writable-p file)) (error "Output file not writable")
5791 (let ((ext-plist (org-combine-plists `(:output-file ,file) ext-plist))
5792 (encoding (or org-export-coding-system buffer-file-coding-system)))
5793 (if async
5794 (org-export-async-start
5795 `(lambda (file)
5796 (org-export-add-to-stack (expand-file-name file) ',backend))
5797 `(let ((output
5798 (org-export-as
5799 ',backend ,subtreep ,visible-only ,body-only
5800 ',ext-plist)))
5801 (with-temp-buffer
5802 (insert output)
5803 (let ((coding-system-for-write ',encoding))
5804 (write-file ,file)))
5805 (or (ignore-errors (funcall ',post-process ,file)) ,file)))
5806 (let ((output (org-export-as
5807 backend subtreep visible-only body-only ext-plist)))
5808 (with-temp-buffer
5809 (insert output)
5810 (let ((coding-system-for-write encoding))
5811 (write-file file)))
5812 (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p output))
5813 (org-kill-new output))
5814 ;; Get proper return value.
5815 (or (and (functionp post-process) (funcall post-process file))
5816 file))))))
5818 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
5819 "Return output file's name according to buffer specifications.
5821 EXTENSION is a string representing the output file extension,
5822 with the leading dot.
5824 With a non-nil optional argument SUBTREEP, try to determine
5825 output file's name by looking for \"EXPORT_FILE_NAME\" property
5826 of subtree at point.
5828 When optional argument PUB-DIR is set, use it as the publishing
5829 directory.
5831 When optional argument VISIBLE-ONLY is non-nil, don't export
5832 contents of hidden elements.
5834 Return file name as a string."
5835 (let* ((visited-file (buffer-file-name (buffer-base-buffer)))
5836 (base-name
5837 ;; File name may come from EXPORT_FILE_NAME subtree
5838 ;; property, assuming point is at beginning of said
5839 ;; sub-tree.
5840 (file-name-sans-extension
5841 (or (and subtreep
5842 (org-entry-get
5843 (save-excursion
5844 (ignore-errors (org-back-to-heading) (point)))
5845 "EXPORT_FILE_NAME" t))
5846 ;; File name may be extracted from buffer's associated
5847 ;; file, if any.
5848 (and visited-file (file-name-nondirectory visited-file))
5849 ;; Can't determine file name on our own: Ask user.
5850 (let ((read-file-name-function
5851 (and org-completion-use-ido 'ido-read-file-name)))
5852 (read-file-name
5853 "Output file: " pub-dir nil nil nil
5854 (lambda (name)
5855 (string= (file-name-extension name t) extension)))))))
5856 (output-file
5857 ;; Build file name. Enforce EXTENSION over whatever user
5858 ;; may have come up with. PUB-DIR, if defined, always has
5859 ;; precedence over any provided path.
5860 (cond
5861 (pub-dir
5862 (concat (file-name-as-directory pub-dir)
5863 (file-name-nondirectory base-name)
5864 extension))
5865 ((file-name-absolute-p base-name) (concat base-name extension))
5866 (t (concat (file-name-as-directory ".") base-name extension)))))
5867 ;; If writing to OUTPUT-FILE would overwrite original file, append
5868 ;; EXTENSION another time to final name.
5869 (if (and visited-file (org-file-equal-p visited-file output-file))
5870 (concat output-file extension)
5871 output-file)))
5873 (defun org-export-add-to-stack (source backend &optional process)
5874 "Add a new result to export stack if not present already.
5876 SOURCE is a buffer or a file name containing export results.
5877 BACKEND is a symbol representing export back-end used to generate
5880 Entries already pointing to SOURCE and unavailable entries are
5881 removed beforehand. Return the new stack."
5882 (setq org-export-stack-contents
5883 (cons (list source backend (or process (current-time)))
5884 (org-export-stack-remove source))))
5886 (defun org-export-stack ()
5887 "Menu for asynchronous export results and running processes."
5888 (interactive)
5889 (let ((buffer (get-buffer-create "*Org Export Stack*")))
5890 (set-buffer buffer)
5891 (when (zerop (buffer-size)) (org-export-stack-mode))
5892 (org-export-stack-refresh)
5893 (pop-to-buffer buffer))
5894 (message "Type \"q\" to quit, \"?\" for help"))
5896 (defun org-export--stack-source-at-point ()
5897 "Return source from export results at point in stack."
5898 (let ((source (car (nth (1- (org-current-line)) org-export-stack-contents))))
5899 (if (not source) (error "Source unavailable, please refresh buffer")
5900 (let ((source-name (if (stringp source) source (buffer-name source))))
5901 (if (save-excursion
5902 (beginning-of-line)
5903 (looking-at (concat ".* +" (regexp-quote source-name) "$")))
5904 source
5905 ;; SOURCE is not consistent with current line. The stack
5906 ;; view is outdated.
5907 (error "Source unavailable; type `g' to update buffer"))))))
5909 (defun org-export-stack-clear ()
5910 "Remove all entries from export stack."
5911 (interactive)
5912 (setq org-export-stack-contents nil))
5914 (defun org-export-stack-refresh (&rest dummy)
5915 "Refresh the asynchronous export stack.
5916 DUMMY is ignored. Unavailable sources are removed from the list.
5917 Return the new stack."
5918 (let ((inhibit-read-only t))
5919 (org-preserve-lc
5920 (erase-buffer)
5921 (insert (concat
5922 (let ((counter 0))
5923 (mapconcat
5924 (lambda (entry)
5925 (let ((proc-p (processp (nth 2 entry))))
5926 (concat
5927 ;; Back-end.
5928 (format " %-12s " (or (nth 1 entry) ""))
5929 ;; Age.
5930 (let ((data (nth 2 entry)))
5931 (if proc-p (format " %6s " (process-status data))
5932 ;; Compute age of the results.
5933 (org-format-seconds
5934 "%4h:%.2m "
5935 (float-time (time-since data)))))
5936 ;; Source.
5937 (format " %s"
5938 (let ((source (car entry)))
5939 (if (stringp source) source
5940 (buffer-name source)))))))
5941 ;; Clear stack from exited processes, dead buffers or
5942 ;; non-existent files.
5943 (setq org-export-stack-contents
5944 (org-remove-if-not
5945 (lambda (el)
5946 (if (processp (nth 2 el))
5947 (buffer-live-p (process-buffer (nth 2 el)))
5948 (let ((source (car el)))
5949 (if (bufferp source) (buffer-live-p source)
5950 (file-exists-p source)))))
5951 org-export-stack-contents)) "\n")))))))
5953 (defun org-export-stack-remove (&optional source)
5954 "Remove export results at point from stack.
5955 If optional argument SOURCE is non-nil, remove it instead."
5956 (interactive)
5957 (let ((source (or source (org-export--stack-source-at-point))))
5958 (setq org-export-stack-contents
5959 (org-remove-if (lambda (el) (equal (car el) source))
5960 org-export-stack-contents))))
5962 (defun org-export-stack-view (&optional in-emacs)
5963 "View export results at point in stack.
5964 With an optional prefix argument IN-EMACS, force viewing files
5965 within Emacs."
5966 (interactive "P")
5967 (let ((source (org-export--stack-source-at-point)))
5968 (cond ((processp source)
5969 (org-switch-to-buffer-other-window (process-buffer source)))
5970 ((bufferp source) (org-switch-to-buffer-other-window source))
5971 (t (org-open-file source in-emacs)))))
5973 (defvar org-export-stack-mode-map
5974 (let ((km (make-sparse-keymap)))
5975 (define-key km " " 'next-line)
5976 (define-key km "n" 'next-line)
5977 (define-key km "\C-n" 'next-line)
5978 (define-key km [down] 'next-line)
5979 (define-key km "p" 'previous-line)
5980 (define-key km "\C-p" 'previous-line)
5981 (define-key km "\C-?" 'previous-line)
5982 (define-key km [up] 'previous-line)
5983 (define-key km "C" 'org-export-stack-clear)
5984 (define-key km "v" 'org-export-stack-view)
5985 (define-key km (kbd "RET") 'org-export-stack-view)
5986 (define-key km "d" 'org-export-stack-remove)
5988 "Keymap for Org Export Stack.")
5990 (define-derived-mode org-export-stack-mode special-mode "Org-Stack"
5991 "Mode for displaying asynchronous export stack.
5993 Type \\[org-export-stack] to visualize the asynchronous export
5994 stack.
5996 In an Org Export Stack buffer, use \\<org-export-stack-mode-map>\\[org-export-stack-view] to view export output
5997 on current line, \\[org-export-stack-remove] to remove it from the stack and \\[org-export-stack-clear] to clear
5998 stack completely.
6000 Removing entries in an Org Export Stack buffer doesn't affect
6001 files or buffers, only the display.
6003 \\{org-export-stack-mode-map}"
6004 (abbrev-mode 0)
6005 (auto-fill-mode 0)
6006 (setq buffer-read-only t
6007 buffer-undo-list t
6008 truncate-lines t
6009 header-line-format
6010 '(:eval
6011 (format " %-12s | %6s | %s" "Back-End" "Age" "Source")))
6012 (org-add-hook 'post-command-hook 'org-export-stack-refresh nil t)
6013 (set (make-local-variable 'revert-buffer-function)
6014 'org-export-stack-refresh))
6018 ;;; The Dispatcher
6020 ;; `org-export-dispatch' is the standard interactive way to start an
6021 ;; export process. It uses `org-export--dispatch-ui' as a subroutine
6022 ;; for its interface, which, in turn, delegates response to key
6023 ;; pressed to `org-export--dispatch-action'.
6025 ;;;###autoload
6026 (defun org-export-dispatch (&optional arg)
6027 "Export dispatcher for Org mode.
6029 It provides an access to common export related tasks in a buffer.
6030 Its interface comes in two flavors: standard and expert.
6032 While both share the same set of bindings, only the former
6033 displays the valid keys associations in a dedicated buffer.
6034 Scrolling (resp. line-wise motion) in this buffer is done with
6035 SPC and DEL (resp. C-n and C-p) keys.
6037 Set variable `org-export-dispatch-use-expert-ui' to switch to one
6038 flavor or the other.
6040 When ARG is \\[universal-argument], repeat the last export action, with the same set
6041 of options used back then, on the current buffer.
6043 When ARG is \\[universal-argument] \\[universal-argument], display the asynchronous export stack."
6044 (interactive "P")
6045 (let* ((input
6046 (cond ((equal arg '(16)) '(stack))
6047 ((and arg org-export-dispatch-last-action))
6048 (t (save-window-excursion
6049 (unwind-protect
6050 (progn
6051 ;; Remember where we are
6052 (move-marker org-export-dispatch-last-position
6053 (point)
6054 (org-base-buffer (current-buffer)))
6055 ;; Get and store an export command
6056 (setq org-export-dispatch-last-action
6057 (org-export--dispatch-ui
6058 (list org-export-initial-scope
6059 (and org-export-in-background 'async))
6061 org-export-dispatch-use-expert-ui)))
6062 (and (get-buffer "*Org Export Dispatcher*")
6063 (kill-buffer "*Org Export Dispatcher*")))))))
6064 (action (car input))
6065 (optns (cdr input)))
6066 (unless (memq 'subtree optns)
6067 (move-marker org-export-dispatch-last-position nil))
6068 (case action
6069 ;; First handle special hard-coded actions.
6070 (template (org-export-insert-default-template nil optns))
6071 (stack (org-export-stack))
6072 (publish-current-file
6073 (org-publish-current-file (memq 'force optns) (memq 'async optns)))
6074 (publish-current-project
6075 (org-publish-current-project (memq 'force optns) (memq 'async optns)))
6076 (publish-choose-project
6077 (org-publish (assoc (org-icompleting-read
6078 "Publish project: "
6079 org-publish-project-alist nil t)
6080 org-publish-project-alist)
6081 (memq 'force optns)
6082 (memq 'async optns)))
6083 (publish-all (org-publish-all (memq 'force optns) (memq 'async optns)))
6084 (otherwise
6085 (save-excursion
6086 (when arg
6087 ;; Repeating command, maybe move cursor to restore subtree
6088 ;; context.
6089 (if (eq (marker-buffer org-export-dispatch-last-position)
6090 (org-base-buffer (current-buffer)))
6091 (goto-char org-export-dispatch-last-position)
6092 ;; We are in a different buffer, forget position.
6093 (move-marker org-export-dispatch-last-position nil)))
6094 (funcall action
6095 ;; Return a symbol instead of a list to ease
6096 ;; asynchronous export macro use.
6097 (and (memq 'async optns) t)
6098 (and (memq 'subtree optns) t)
6099 (and (memq 'visible optns) t)
6100 (and (memq 'body optns) t)))))))
6102 (defun org-export--dispatch-ui (options first-key expertp)
6103 "Handle interface for `org-export-dispatch'.
6105 OPTIONS is a list containing current interactive options set for
6106 export. It can contain any of the following symbols:
6107 `body' toggles a body-only export
6108 `subtree' restricts export to current subtree
6109 `visible' restricts export to visible part of buffer.
6110 `force' force publishing files.
6111 `async' use asynchronous export process
6113 FIRST-KEY is the key pressed to select the first level menu. It
6114 is nil when this menu hasn't been selected yet.
6116 EXPERTP, when non-nil, triggers expert UI. In that case, no help
6117 buffer is provided, but indications about currently active
6118 options are given in the prompt. Moreover, \[?] allows to switch
6119 back to standard interface."
6120 (let* ((fontify-key
6121 (lambda (key &optional access-key)
6122 ;; Fontify KEY string. Optional argument ACCESS-KEY, when
6123 ;; non-nil is the required first-level key to activate
6124 ;; KEY. When its value is t, activate KEY independently
6125 ;; on the first key, if any. A nil value means KEY will
6126 ;; only be activated at first level.
6127 (if (or (eq access-key t) (eq access-key first-key))
6128 (org-propertize key 'face 'org-warning)
6129 key)))
6130 (fontify-value
6131 (lambda (value)
6132 ;; Fontify VALUE string.
6133 (org-propertize value 'face 'font-lock-variable-name-face)))
6134 ;; Prepare menu entries by extracting them from registered
6135 ;; back-ends and sorting them by access key and by ordinal,
6136 ;; if any.
6137 (entries
6138 (sort (sort (delq nil
6139 (mapcar 'org-export-backend-menu
6140 org-export--registered-backends))
6141 (lambda (a b)
6142 (let ((key-a (nth 1 a))
6143 (key-b (nth 1 b)))
6144 (cond ((and (numberp key-a) (numberp key-b))
6145 (< key-a key-b))
6146 ((numberp key-b) t)))))
6147 'car-less-than-car))
6148 ;; Compute a list of allowed keys based on the first key
6149 ;; pressed, if any. Some keys
6150 ;; (?^B, ?^V, ?^S, ?^F, ?^A, ?&, ?# and ?q) are always
6151 ;; available.
6152 (allowed-keys
6153 (nconc (list 2 22 19 6 1)
6154 (if (not first-key) (org-uniquify (mapcar 'car entries))
6155 (let (sub-menu)
6156 (dolist (entry entries (sort (mapcar 'car sub-menu) '<))
6157 (when (eq (car entry) first-key)
6158 (setq sub-menu (append (nth 2 entry) sub-menu))))))
6159 (cond ((eq first-key ?P) (list ?f ?p ?x ?a))
6160 ((not first-key) (list ?P)))
6161 (list ?& ?#)
6162 (when expertp (list ??))
6163 (list ?q)))
6164 ;; Build the help menu for standard UI.
6165 (help
6166 (unless expertp
6167 (concat
6168 ;; Options are hard-coded.
6169 (format "[%s] Body only: %s [%s] Visible only: %s
6170 \[%s] Export scope: %s [%s] Force publishing: %s
6171 \[%s] Async export: %s\n\n"
6172 (funcall fontify-key "C-b" t)
6173 (funcall fontify-value
6174 (if (memq 'body options) "On " "Off"))
6175 (funcall fontify-key "C-v" t)
6176 (funcall fontify-value
6177 (if (memq 'visible options) "On " "Off"))
6178 (funcall fontify-key "C-s" t)
6179 (funcall fontify-value
6180 (if (memq 'subtree options) "Subtree" "Buffer "))
6181 (funcall fontify-key "C-f" t)
6182 (funcall fontify-value
6183 (if (memq 'force options) "On " "Off"))
6184 (funcall fontify-key "C-a" t)
6185 (funcall fontify-value
6186 (if (memq 'async options) "On " "Off")))
6187 ;; Display registered back-end entries. When a key
6188 ;; appears for the second time, do not create another
6189 ;; entry, but append its sub-menu to existing menu.
6190 (let (last-key)
6191 (mapconcat
6192 (lambda (entry)
6193 (let ((top-key (car entry)))
6194 (concat
6195 (unless (eq top-key last-key)
6196 (setq last-key top-key)
6197 (format "\n[%s] %s\n"
6198 (funcall fontify-key (char-to-string top-key))
6199 (nth 1 entry)))
6200 (let ((sub-menu (nth 2 entry)))
6201 (unless (functionp sub-menu)
6202 ;; Split sub-menu into two columns.
6203 (let ((index -1))
6204 (concat
6205 (mapconcat
6206 (lambda (sub-entry)
6207 (incf index)
6208 (format
6209 (if (zerop (mod index 2)) " [%s] %-26s"
6210 "[%s] %s\n")
6211 (funcall fontify-key
6212 (char-to-string (car sub-entry))
6213 top-key)
6214 (nth 1 sub-entry)))
6215 sub-menu "")
6216 (when (zerop (mod index 2)) "\n"))))))))
6217 entries ""))
6218 ;; Publishing menu is hard-coded.
6219 (format "\n[%s] Publish
6220 [%s] Current file [%s] Current project
6221 [%s] Choose project [%s] All projects\n\n\n"
6222 (funcall fontify-key "P")
6223 (funcall fontify-key "f" ?P)
6224 (funcall fontify-key "p" ?P)
6225 (funcall fontify-key "x" ?P)
6226 (funcall fontify-key "a" ?P))
6227 (format "[%s] Export stack [%s] Insert template\n"
6228 (funcall fontify-key "&" t)
6229 (funcall fontify-key "#" t))
6230 (format "[%s] %s"
6231 (funcall fontify-key "q" t)
6232 (if first-key "Main menu" "Exit")))))
6233 ;; Build prompts for both standard and expert UI.
6234 (standard-prompt (unless expertp "Export command: "))
6235 (expert-prompt
6236 (when expertp
6237 (format
6238 "Export command (C-%s%s%s%s%s) [%s]: "
6239 (if (memq 'body options) (funcall fontify-key "b" t) "b")
6240 (if (memq 'visible options) (funcall fontify-key "v" t) "v")
6241 (if (memq 'subtree options) (funcall fontify-key "s" t) "s")
6242 (if (memq 'force options) (funcall fontify-key "f" t) "f")
6243 (if (memq 'async options) (funcall fontify-key "a" t) "a")
6244 (mapconcat (lambda (k)
6245 ;; Strip control characters.
6246 (unless (< k 27) (char-to-string k)))
6247 allowed-keys "")))))
6248 ;; With expert UI, just read key with a fancy prompt. In standard
6249 ;; UI, display an intrusive help buffer.
6250 (if expertp
6251 (org-export--dispatch-action
6252 expert-prompt allowed-keys entries options first-key expertp)
6253 ;; At first call, create frame layout in order to display menu.
6254 (unless (get-buffer "*Org Export Dispatcher*")
6255 (delete-other-windows)
6256 (org-switch-to-buffer-other-window
6257 (get-buffer-create "*Org Export Dispatcher*"))
6258 (setq cursor-type nil
6259 header-line-format "Use SPC, DEL, C-n or C-p to navigate.")
6260 ;; Make sure that invisible cursor will not highlight square
6261 ;; brackets.
6262 (set-syntax-table (copy-syntax-table))
6263 (modify-syntax-entry ?\[ "w"))
6264 ;; At this point, the buffer containing the menu exists and is
6265 ;; visible in the current window. So, refresh it.
6266 (with-current-buffer "*Org Export Dispatcher*"
6267 ;; Refresh help. Maintain display continuity by re-visiting
6268 ;; previous window position.
6269 (let ((pos (window-start)))
6270 (erase-buffer)
6271 (insert help)
6272 (set-window-start nil pos)))
6273 (org-fit-window-to-buffer)
6274 (org-export--dispatch-action
6275 standard-prompt allowed-keys entries options first-key expertp))))
6277 (defun org-export--dispatch-action
6278 (prompt allowed-keys entries options first-key expertp)
6279 "Read a character from command input and act accordingly.
6281 PROMPT is the displayed prompt, as a string. ALLOWED-KEYS is
6282 a list of characters available at a given step in the process.
6283 ENTRIES is a list of menu entries. OPTIONS, FIRST-KEY and
6284 EXPERTP are the same as defined in `org-export--dispatch-ui',
6285 which see.
6287 Toggle export options when required. Otherwise, return value is
6288 a list with action as CAR and a list of interactive export
6289 options as CDR."
6290 (let (key)
6291 ;; Scrolling: when in non-expert mode, act on motion keys (C-n,
6292 ;; C-p, SPC, DEL).
6293 (while (and (setq key (read-char-exclusive prompt))
6294 (not expertp)
6295 (memq key '(14 16 ?\s ?\d)))
6296 (case key
6297 (14 (if (not (pos-visible-in-window-p (point-max)))
6298 (ignore-errors (scroll-up 1))
6299 (message "End of buffer")
6300 (sit-for 1)))
6301 (16 (if (not (pos-visible-in-window-p (point-min)))
6302 (ignore-errors (scroll-down 1))
6303 (message "Beginning of buffer")
6304 (sit-for 1)))
6305 (?\s (if (not (pos-visible-in-window-p (point-max)))
6306 (scroll-up nil)
6307 (message "End of buffer")
6308 (sit-for 1)))
6309 (?\d (if (not (pos-visible-in-window-p (point-min)))
6310 (scroll-down nil)
6311 (message "Beginning of buffer")
6312 (sit-for 1)))))
6313 (cond
6314 ;; Ignore undefined associations.
6315 ((not (memq key allowed-keys))
6316 (ding)
6317 (unless expertp (message "Invalid key") (sit-for 1))
6318 (org-export--dispatch-ui options first-key expertp))
6319 ;; q key at first level aborts export. At second level, cancel
6320 ;; first key instead.
6321 ((eq key ?q) (if (not first-key) (error "Export aborted")
6322 (org-export--dispatch-ui options nil expertp)))
6323 ;; Help key: Switch back to standard interface if expert UI was
6324 ;; active.
6325 ((eq key ??) (org-export--dispatch-ui options first-key nil))
6326 ;; Send request for template insertion along with export scope.
6327 ((eq key ?#) (cons 'template (memq 'subtree options)))
6328 ;; Switch to asynchronous export stack.
6329 ((eq key ?&) '(stack))
6330 ;; Toggle options: C-b (2) C-v (22) C-s (19) C-f (6) C-a (1).
6331 ((memq key '(2 22 19 6 1))
6332 (org-export--dispatch-ui
6333 (let ((option (case key (2 'body) (22 'visible) (19 'subtree)
6334 (6 'force) (1 'async))))
6335 (if (memq option options) (remq option options)
6336 (cons option options)))
6337 first-key expertp))
6338 ;; Action selected: Send key and options back to
6339 ;; `org-export-dispatch'.
6340 ((or first-key (functionp (nth 2 (assq key entries))))
6341 (cons (cond
6342 ((not first-key) (nth 2 (assq key entries)))
6343 ;; Publishing actions are hard-coded. Send a special
6344 ;; signal to `org-export-dispatch'.
6345 ((eq first-key ?P)
6346 (case key
6347 (?f 'publish-current-file)
6348 (?p 'publish-current-project)
6349 (?x 'publish-choose-project)
6350 (?a 'publish-all)))
6351 ;; Return first action associated to FIRST-KEY + KEY
6352 ;; path. Indeed, derived backends can share the same
6353 ;; FIRST-KEY.
6354 (t (catch 'found
6355 (mapc (lambda (entry)
6356 (let ((match (assq key (nth 2 entry))))
6357 (when match (throw 'found (nth 2 match)))))
6358 (member (assq first-key entries) entries)))))
6359 options))
6360 ;; Otherwise, enter sub-menu.
6361 (t (org-export--dispatch-ui options key expertp)))))
6365 (provide 'ox)
6367 ;; Local variables:
6368 ;; generated-autoload-file: "org-loaddefs.el"
6369 ;; End:
6371 ;;; ox.el ends here