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