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