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