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