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