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