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