ox: Inhibit startup process when calling `org-mode'
[org-mode.git] / lisp / ox.el
blobcf569b5a5d70506c7ec43bc67decc26514ea3be3
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 ;; which defines one mandatory information: his translation table.
52 ;; Its value is an alist whose keys are elements and objects types and
53 ;; values translator functions. See function's docstring for more
54 ;; information about translators.
56 ;; Optionally, `org-export-define-backend' can also support specific
57 ;; buffer keywords, OPTION keyword's items and filters. Also refer to
58 ;; function documentation for more information.
60 ;; If the new back-end shares most properties with another one,
61 ;; `org-export-define-derived-backend' can be used to simplify the
62 ;; process.
64 ;; Any back-end can define its own variables. Among them, those
65 ;; customizable should belong to the `org-export-BACKEND' group.
67 ;; Tools for common tasks across back-ends are implemented in the
68 ;; following part of the file.
70 ;; Then, a wrapper macro for asynchronous export,
71 ;; `org-export-async-start', along with tools to display results. are
72 ;; given in the penultimate part.
74 ;; Eventually, a dispatcher (`org-export-dispatch') for standard
75 ;; back-ends is provided in the last one.
77 ;;; Code:
79 (eval-when-compile (require 'cl))
80 (require 'org-element)
81 (require 'org-macro)
82 (require 'ob-exp)
84 (declare-function org-publish "ox-publish" (project &optional force async))
85 (declare-function org-publish-all "ox-publish" (&optional force async))
86 (declare-function
87 org-publish-current-file "ox-publish" (&optional force async))
88 (declare-function org-publish-current-project "ox-publish"
89 (&optional force async))
91 (defvar org-publish-project-alist)
92 (defvar org-table-number-fraction)
93 (defvar org-table-number-regexp)
97 ;;; Internal Variables
99 ;; Among internal variables, the most important is
100 ;; `org-export-options-alist'. This variable define the global export
101 ;; options, shared between every exporter, and how they are acquired.
103 (defconst org-export-max-depth 19
104 "Maximum nesting depth for headlines, counting from 0.")
106 (defconst org-export-options-alist
107 '((:author "AUTHOR" nil user-full-name t)
108 (:creator "CREATOR" nil org-export-creator-string)
109 (:date "DATE" nil nil t)
110 (:description "DESCRIPTION" nil nil newline)
111 (:email "EMAIL" nil user-mail-address t)
112 (:exclude-tags "EXCLUDE_TAGS" nil org-export-exclude-tags split)
113 (:headline-levels nil "H" org-export-headline-levels)
114 (:keywords "KEYWORDS" nil nil space)
115 (:language "LANGUAGE" nil org-export-default-language t)
116 (:preserve-breaks nil "\\n" org-export-preserve-breaks)
117 (:section-numbers nil "num" org-export-with-section-numbers)
118 (:select-tags "SELECT_TAGS" nil org-export-select-tags split)
119 (:time-stamp-file nil "timestamp" org-export-time-stamp-file)
120 (:title "TITLE" nil nil space)
121 (:with-archived-trees nil "arch" org-export-with-archived-trees)
122 (:with-author nil "author" org-export-with-author)
123 (:with-clocks nil "c" org-export-with-clocks)
124 (:with-creator nil "creator" org-export-with-creator)
125 (:with-date nil "date" org-export-with-date)
126 (:with-drawers nil "d" org-export-with-drawers)
127 (:with-email nil "email" org-export-with-email)
128 (:with-emphasize nil "*" org-export-with-emphasize)
129 (:with-entities nil "e" org-export-with-entities)
130 (:with-fixed-width nil ":" org-export-with-fixed-width)
131 (:with-footnotes nil "f" org-export-with-footnotes)
132 (:with-inlinetasks nil "inline" org-export-with-inlinetasks)
133 (:with-latex nil "tex" org-export-with-latex)
134 (:with-plannings nil "p" org-export-with-planning)
135 (:with-priority nil "pri" org-export-with-priority)
136 (:with-smart-quotes nil "'" org-export-with-smart-quotes)
137 (:with-special-strings nil "-" org-export-with-special-strings)
138 (:with-statistics-cookies nil "stat" org-export-with-statistics-cookies)
139 (:with-sub-superscript nil "^" org-export-with-sub-superscripts)
140 (:with-toc nil "toc" org-export-with-toc)
141 (:with-tables nil "|" org-export-with-tables)
142 (:with-tags nil "tags" org-export-with-tags)
143 (:with-tasks nil "tasks" org-export-with-tasks)
144 (:with-timestamps nil "<" org-export-with-timestamps)
145 (:with-todo-keywords nil "todo" org-export-with-todo-keywords))
146 "Alist between export properties and ways to set them.
148 The CAR of the alist is the property name, and the CDR is a list
149 like (KEYWORD OPTION DEFAULT BEHAVIOUR) where:
151 KEYWORD is a string representing a buffer keyword, or nil. Each
152 property defined this way can also be set, during subtree
153 export, through a headline property named after the keyword
154 with the \"EXPORT_\" prefix (i.e. DATE keyword and EXPORT_DATE
155 property).
156 OPTION is a string that could be found in an #+OPTIONS: line.
157 DEFAULT is the default value for the property.
158 BEHAVIOUR determines how Org should handle multiple keywords for
159 the same property. It is a symbol among:
160 nil Keep old value and discard the new one.
161 t Replace old value with the new one.
162 `space' Concatenate the values, separating them with a space.
163 `newline' Concatenate the values, separating them with
164 a newline.
165 `split' Split values at white spaces, and cons them to the
166 previous list.
168 Values set through KEYWORD and OPTION have precedence over
169 DEFAULT.
171 All these properties should be back-end agnostic. Back-end
172 specific properties are set through `org-export-define-backend'.
173 Properties redefined there have precedence over these.")
175 (defconst org-export-special-keywords '("FILETAGS" "SETUPFILE" "OPTIONS")
176 "List of in-buffer keywords that require special treatment.
177 These keywords are not directly associated to a property. The
178 way they are handled must be hard-coded into
179 `org-export--get-inbuffer-options' function.")
181 (defconst org-export-filters-alist
182 '((:filter-bold . org-export-filter-bold-functions)
183 (:filter-babel-call . org-export-filter-babel-call-functions)
184 (:filter-center-block . org-export-filter-center-block-functions)
185 (:filter-clock . org-export-filter-clock-functions)
186 (:filter-code . org-export-filter-code-functions)
187 (:filter-comment . org-export-filter-comment-functions)
188 (:filter-comment-block . org-export-filter-comment-block-functions)
189 (:filter-diary-sexp . org-export-filter-diary-sexp-functions)
190 (:filter-drawer . org-export-filter-drawer-functions)
191 (:filter-dynamic-block . org-export-filter-dynamic-block-functions)
192 (:filter-entity . org-export-filter-entity-functions)
193 (:filter-example-block . org-export-filter-example-block-functions)
194 (:filter-export-block . org-export-filter-export-block-functions)
195 (:filter-export-snippet . org-export-filter-export-snippet-functions)
196 (:filter-final-output . org-export-filter-final-output-functions)
197 (:filter-fixed-width . org-export-filter-fixed-width-functions)
198 (:filter-footnote-definition . org-export-filter-footnote-definition-functions)
199 (:filter-footnote-reference . org-export-filter-footnote-reference-functions)
200 (:filter-headline . org-export-filter-headline-functions)
201 (:filter-horizontal-rule . org-export-filter-horizontal-rule-functions)
202 (:filter-inline-babel-call . org-export-filter-inline-babel-call-functions)
203 (:filter-inline-src-block . org-export-filter-inline-src-block-functions)
204 (:filter-inlinetask . org-export-filter-inlinetask-functions)
205 (:filter-italic . org-export-filter-italic-functions)
206 (:filter-item . org-export-filter-item-functions)
207 (:filter-keyword . org-export-filter-keyword-functions)
208 (:filter-latex-environment . org-export-filter-latex-environment-functions)
209 (:filter-latex-fragment . org-export-filter-latex-fragment-functions)
210 (:filter-line-break . org-export-filter-line-break-functions)
211 (:filter-link . org-export-filter-link-functions)
212 (:filter-macro . org-export-filter-macro-functions)
213 (:filter-node-property . org-export-filter-node-property-functions)
214 (:filter-options . org-export-filter-options-functions)
215 (:filter-paragraph . org-export-filter-paragraph-functions)
216 (:filter-parse-tree . org-export-filter-parse-tree-functions)
217 (:filter-plain-list . org-export-filter-plain-list-functions)
218 (:filter-plain-text . org-export-filter-plain-text-functions)
219 (:filter-planning . org-export-filter-planning-functions)
220 (:filter-property-drawer . org-export-filter-property-drawer-functions)
221 (:filter-quote-block . org-export-filter-quote-block-functions)
222 (:filter-quote-section . org-export-filter-quote-section-functions)
223 (:filter-radio-target . org-export-filter-radio-target-functions)
224 (:filter-section . org-export-filter-section-functions)
225 (:filter-special-block . org-export-filter-special-block-functions)
226 (:filter-src-block . org-export-filter-src-block-functions)
227 (:filter-statistics-cookie . org-export-filter-statistics-cookie-functions)
228 (:filter-strike-through . org-export-filter-strike-through-functions)
229 (:filter-subscript . org-export-filter-subscript-functions)
230 (:filter-superscript . org-export-filter-superscript-functions)
231 (:filter-table . org-export-filter-table-functions)
232 (:filter-table-cell . org-export-filter-table-cell-functions)
233 (:filter-table-row . org-export-filter-table-row-functions)
234 (:filter-target . org-export-filter-target-functions)
235 (:filter-timestamp . org-export-filter-timestamp-functions)
236 (:filter-underline . org-export-filter-underline-functions)
237 (:filter-verbatim . org-export-filter-verbatim-functions)
238 (:filter-verse-block . org-export-filter-verse-block-functions))
239 "Alist between filters properties and initial values.
241 The key of each association is a property name accessible through
242 the communication channel. Its value is a configurable global
243 variable defining initial filters.
245 This list is meant to install user specified filters. Back-end
246 developers may install their own filters using
247 `org-export-define-backend'. Filters defined there will always
248 be prepended to the current list, so they always get applied
249 first.")
251 (defconst org-export-default-inline-image-rule
252 `(("file" .
253 ,(format "\\.%s\\'"
254 (regexp-opt
255 '("png" "jpeg" "jpg" "gif" "tiff" "tif" "xbm"
256 "xpm" "pbm" "pgm" "ppm") t))))
257 "Default rule for link matching an inline image.
258 This rule applies to links with no description. By default, it
259 will be considered as an inline image if it targets a local file
260 whose extension is either \"png\", \"jpeg\", \"jpg\", \"gif\",
261 \"tiff\", \"tif\", \"xbm\", \"xpm\", \"pbm\", \"pgm\" or \"ppm\".
262 See `org-export-inline-image-p' for more information about
263 rules.")
265 (defvar org-export-async-debug nil
266 "Non-nil means asynchronous export process should leave data behind.
268 This data is found in the appropriate \"*Org Export Process*\"
269 buffer, and in files prefixed with \"org-export-process\" and
270 located in `temporary-file-directory'.
272 When non-nil, it will also set `debug-on-error' to a non-nil
273 value in the external process.")
275 (defvar org-export-stack-contents nil
276 "Record asynchronously generated export results and processes.
277 This is an alist: its CAR is the source of the
278 result (destination file or buffer for a finished process,
279 original buffer for a running one) and its CDR is a list
280 containing the back-end used, as a symbol, and either a process
281 or the time at which it finished. It is used to build the menu
282 from `org-export-stack'.")
284 (defvar org-export-registered-backends nil
285 "List of backends currently available in the exporter.
287 A backend is stored as a list where CAR is its name, as a symbol,
288 and CDR is a plist with the following properties:
289 `:filters-alist', `:menu-entry', `:options-alist' and
290 `:translate-alist'.
292 This variable is set with `org-export-define-backend' and
293 `org-export-define-derived-backend' functions.")
295 (defvar org-export-dispatch-last-action nil
296 "Last command called from the dispatcher.
297 The value should be a list. Its CAR is the action, as a symbol,
298 and its CDR is a list of export options.")
300 (defvar org-export-dispatch-last-position (make-marker)
301 "The position where the last export command was created using the dispatcher.
302 This marker will be used with `C-u C-c C-e' to make sure export repetition
303 uses the same subtree if the previous command was restricted to a subtree.")
306 ;;; User-configurable Variables
308 ;; Configuration for the masses.
310 ;; They should never be accessed directly, as their value is to be
311 ;; stored in a property list (cf. `org-export-options-alist').
312 ;; Back-ends will read their value from there instead.
314 (defgroup org-export nil
315 "Options for exporting Org mode files."
316 :tag "Org Export"
317 :group 'org)
319 (defgroup org-export-general nil
320 "General options for export engine."
321 :tag "Org Export General"
322 :group 'org-export)
324 (defcustom org-export-with-archived-trees 'headline
325 "Whether sub-trees with the ARCHIVE tag should be exported.
327 This can have three different values:
328 nil Do not export, pretend this tree is not present.
329 t Do export the entire tree.
330 `headline' Only export the headline, but skip the tree below it.
332 This option can also be set with the #+OPTIONS line,
333 e.g. \"arch:nil\"."
334 :group 'org-export-general
335 :type '(choice
336 (const :tag "Not at all" nil)
337 (const :tag "Headline only" 'headline)
338 (const :tag "Entirely" t)))
340 (defcustom org-export-with-author t
341 "Non-nil means insert author name into the exported file.
342 This option can also be set with the #+OPTIONS line,
343 e.g. \"author:nil\"."
344 :group 'org-export-general
345 :type 'boolean)
347 (defcustom org-export-with-clocks nil
348 "Non-nil means export CLOCK keywords.
349 This option can also be set with the #+OPTIONS line,
350 e.g. \"c:t\"."
351 :group 'org-export-general
352 :type 'boolean)
354 (defcustom org-export-with-creator 'comment
355 "Non-nil means the postamble should contain a creator sentence.
357 The sentence can be set in `org-export-creator-string' and
358 defaults to \"Generated by Org mode XX in Emacs XXX.\".
360 If the value is `comment' insert it as a comment."
361 :group 'org-export-general
362 :type '(choice
363 (const :tag "No creator sentence" nil)
364 (const :tag "Sentence as a comment" 'comment)
365 (const :tag "Insert the sentence" t)))
367 (defcustom org-export-with-date t
368 "Non-nil means insert date in the exported document.
369 This options can also be set with the OPTIONS keyword,
370 e.g. \"date:nil\".")
372 (defcustom org-export-date-timestamp-format nil
373 "Time-stamp format string to use for DATE keyword.
375 The format string, when specified, only applies if date consists
376 in a single time-stamp. Otherwise its value will be ignored.
378 See `format-time-string' for details on how to build this
379 string."
380 :group 'org-export-general
381 :type '(choice
382 (string :tag "Time-stamp format string")
383 (const :tag "No format string" nil)))
385 (defcustom org-export-creator-string
386 (format "Generated by Org mode %s in Emacs %s."
387 (if (fboundp 'org-version) (org-version) "(Unknown)")
388 emacs-version)
389 "String to insert at the end of the generated document."
390 :group 'org-export-general
391 :type '(string :tag "Creator string"))
393 (defcustom org-export-with-drawers '(not "LOGBOOK")
394 "Non-nil means export contents of standard drawers.
396 When t, all drawers are exported. This may also be a list of
397 drawer names to export. If that list starts with `not', only
398 drawers with such names will be ignored.
400 This variable doesn't apply to properties drawers.
402 This option can also be set with the #+OPTIONS line,
403 e.g. \"d:nil\"."
404 :group 'org-export-general
405 :version "24.4"
406 :package-version '(Org . "8.0")
407 :type '(choice
408 (const :tag "All drawers" t)
409 (const :tag "None" nil)
410 (repeat :tag "Selected drawers"
411 (string :tag "Drawer name"))
412 (list :tag "Ignored drawers"
413 (const :format "" not)
414 (repeat :tag "Specify names of drawers to ignore during export"
415 :inline t
416 (string :tag "Drawer name")))))
418 (defcustom org-export-with-email nil
419 "Non-nil means insert author email into the exported file.
420 This option can also be set with the #+OPTIONS line,
421 e.g. \"email:t\"."
422 :group 'org-export-general
423 :type 'boolean)
425 (defcustom org-export-with-emphasize t
426 "Non-nil means interpret *word*, /word/, _word_ and +word+.
428 If the export target supports emphasizing text, the word will be
429 typeset in bold, italic, with an underline or strike-through,
430 respectively.
432 This option can also be set with the #+OPTIONS line, e.g. \"*:nil\"."
433 :group 'org-export-general
434 :type 'boolean)
436 (defcustom org-export-exclude-tags '("noexport")
437 "Tags that exclude a tree from export.
439 All trees carrying any of these tags will be excluded from
440 export. This is without condition, so even subtrees inside that
441 carry one of the `org-export-select-tags' will be removed.
443 This option can also be set with the #+EXCLUDE_TAGS: keyword."
444 :group 'org-export-general
445 :type '(repeat (string :tag "Tag")))
447 (defcustom org-export-with-fixed-width t
448 "Non-nil means lines starting with \":\" will be in fixed width font.
450 This can be used to have pre-formatted text, fragments of code
451 etc. For example:
452 : ;; Some Lisp examples
453 : (while (defc cnt)
454 : (ding))
455 will be looking just like this in also HTML. See also the QUOTE
456 keyword. Not all export backends support this.
458 This option can also be set with the #+OPTIONS line, e.g. \"::nil\"."
459 :group 'org-export-general
460 :type 'boolean)
462 (defcustom org-export-with-footnotes t
463 "Non-nil means Org footnotes should be exported.
464 This option can also be set with the #+OPTIONS line,
465 e.g. \"f:nil\"."
466 :group 'org-export-general
467 :type 'boolean)
469 (defcustom org-export-with-latex t
470 "Non-nil means process LaTeX environments and fragments.
472 This option can also be set with the +OPTIONS line,
473 e.g. \"tex:verbatim\". Allowed values are:
475 nil Ignore math snippets.
476 `verbatim' Keep everything in verbatim.
477 t Allow export of math snippets."
478 :group 'org-export-general
479 :version "24.4"
480 :package-version '(Org . "8.0")
481 :type '(choice
482 (const :tag "Do not process math in any way" nil)
483 (const :tag "Interpret math snippets" t)
484 (const :tag "Leave math verbatim" verbatim)))
486 (defcustom org-export-headline-levels 3
487 "The last level which is still exported as a headline.
489 Inferior levels will produce itemize or enumerate lists when
490 exported.
492 This option can also be set with the #+OPTIONS line, e.g. \"H:2\"."
493 :group 'org-export-general
494 :type 'integer)
496 (defcustom org-export-default-language "en"
497 "The default language for export and clocktable translations, as a string.
498 This may have an association in
499 `org-clock-clocktable-language-setup'."
500 :group 'org-export-general
501 :type '(string :tag "Language"))
503 (defcustom org-export-preserve-breaks nil
504 "Non-nil means preserve all line breaks when exporting.
505 This option can also be set with the #+OPTIONS line,
506 e.g. \"\\n:t\"."
507 :group 'org-export-general
508 :type 'boolean)
510 (defcustom org-export-with-entities t
511 "Non-nil means interpret entities when exporting.
513 For example, HTML export converts \\alpha to &alpha; and \\AA to
514 &Aring;.
516 For a list of supported names, see the constant `org-entities'
517 and the user option `org-entities-user'.
519 This option can also be set with the #+OPTIONS line,
520 e.g. \"e:nil\"."
521 :group 'org-export-general
522 :type 'boolean)
524 (defcustom org-export-with-inlinetasks t
525 "Non-nil means inlinetasks should be exported.
526 This option can also be set with the #+OPTIONS line,
527 e.g. \"inline:nil\"."
528 :group 'org-export-general
529 :version "24.4"
530 :package-version '(Org . "8.0")
531 :type 'boolean)
533 (defcustom org-export-with-planning nil
534 "Non-nil means include planning info in export.
535 This option can also be set with the #+OPTIONS: line,
536 e.g. \"p:t\"."
537 :group 'org-export-general
538 :version "24.4"
539 :package-version '(Org . "8.0")
540 :type 'boolean)
542 (defcustom org-export-with-priority nil
543 "Non-nil means include priority cookies in export.
544 This option can also be set with the #+OPTIONS line,
545 e.g. \"pri:t\"."
546 :group 'org-export-general
547 :type 'boolean)
549 (defcustom org-export-with-section-numbers t
550 "Non-nil means add section numbers to headlines when exporting.
552 When set to an integer n, numbering will only happen for
553 headlines whose relative level is higher or equal to n.
555 This option can also be set with the #+OPTIONS line,
556 e.g. \"num:t\"."
557 :group 'org-export-general
558 :type 'boolean)
560 (defcustom org-export-select-tags '("export")
561 "Tags that select a tree for export.
563 If any such tag is found in a buffer, all trees that do not carry
564 one of these tags will be ignored during export. Inside trees
565 that are selected like this, you can still deselect a subtree by
566 tagging it with one of the `org-export-exclude-tags'.
568 This option can also be set with the #+SELECT_TAGS: keyword."
569 :group 'org-export-general
570 :type '(repeat (string :tag "Tag")))
572 (defcustom org-export-with-smart-quotes nil
573 "Non-nil means activate smart quotes during export.
574 This option can also be set with the #+OPTIONS: line,
575 e.g. \"':t\"."
576 :group 'org-export-general
577 :version "24.4"
578 :package-version '(Org . "8.0")
579 :type 'boolean)
581 (defcustom org-export-with-special-strings t
582 "Non-nil means interpret \"\\-\", \"--\" and \"---\" for export.
584 When this option is turned on, these strings will be exported as:
586 Org HTML LaTeX UTF-8
587 -----+----------+--------+-------
588 \\- &shy; \\-
589 -- &ndash; -- –
590 --- &mdash; --- —
591 ... &hellip; \\ldots …
593 This option can also be set with the #+OPTIONS line,
594 e.g. \"-:nil\"."
595 :group 'org-export-general
596 :type 'boolean)
598 (defcustom org-export-with-statistics-cookies t
599 "Non-nil means include statistics cookies in export.
600 This option can also be set with the #+OPTIONS: line,
601 e.g. \"stat:nil\""
602 :group 'org-export-general
603 :version "24.4"
604 :package-version '(Org . "8.0")
605 :type 'boolean)
607 (defcustom org-export-with-sub-superscripts t
608 "Non-nil means interpret \"_\" and \"^\" for export.
610 When this option is turned on, you can use TeX-like syntax for
611 sub- and superscripts. Several characters after \"_\" or \"^\"
612 will be considered as a single item - so grouping with {} is
613 normally not needed. For example, the following things will be
614 parsed as single sub- or superscripts.
616 10^24 or 10^tau several digits will be considered 1 item.
617 10^-12 or 10^-tau a leading sign with digits or a word
618 x^2-y^3 will be read as x^2 - y^3, because items are
619 terminated by almost any nonword/nondigit char.
620 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
622 Still, ambiguity is possible - so when in doubt use {} to enclose
623 the sub/superscript. If you set this variable to the symbol
624 `{}', the braces are *required* in order to trigger
625 interpretations as sub/superscript. This can be helpful in
626 documents that need \"_\" frequently in plain text.
628 This option can also be set with the #+OPTIONS line,
629 e.g. \"^:nil\"."
630 :group 'org-export-general
631 :type '(choice
632 (const :tag "Interpret them" t)
633 (const :tag "Curly brackets only" {})
634 (const :tag "Do not interpret them" nil)))
636 (defcustom org-export-with-toc t
637 "Non-nil means create a table of contents in exported files.
639 The TOC contains headlines with levels up
640 to`org-export-headline-levels'. When an integer, include levels
641 up to N in the toc, this may then be different from
642 `org-export-headline-levels', but it will not be allowed to be
643 larger than the number of headline levels. When nil, no table of
644 contents is made.
646 This option can also be set with the #+OPTIONS line,
647 e.g. \"toc:nil\" or \"toc:3\"."
648 :group 'org-export-general
649 :type '(choice
650 (const :tag "No Table of Contents" nil)
651 (const :tag "Full Table of Contents" t)
652 (integer :tag "TOC to level")))
654 (defcustom org-export-with-tables t
655 "If non-nil, lines starting with \"|\" define a table.
656 For example:
658 | Name | Address | Birthday |
659 |-------------+----------+-----------|
660 | Arthur Dent | England | 29.2.2100 |
662 This option can also be set with the #+OPTIONS line, e.g. \"|:nil\"."
663 :group 'org-export-general
664 :type 'boolean)
666 (defcustom org-export-with-tags t
667 "If nil, do not export tags, just remove them from headlines.
669 If this is the symbol `not-in-toc', tags will be removed from
670 table of contents entries, but still be shown in the headlines of
671 the document.
673 This option can also be set with the #+OPTIONS line,
674 e.g. \"tags:nil\"."
675 :group 'org-export-general
676 :type '(choice
677 (const :tag "Off" nil)
678 (const :tag "Not in TOC" not-in-toc)
679 (const :tag "On" t)))
681 (defcustom org-export-with-tasks t
682 "Non-nil means include TODO items for export.
684 This may have the following values:
685 t include tasks independent of state.
686 `todo' include only tasks that are not yet done.
687 `done' include only tasks that are already done.
688 nil ignore all tasks.
689 list of keywords include tasks with these keywords.
691 This option can also be set with the #+OPTIONS line,
692 e.g. \"tasks:nil\"."
693 :group 'org-export-general
694 :type '(choice
695 (const :tag "All tasks" t)
696 (const :tag "No tasks" nil)
697 (const :tag "Not-done tasks" todo)
698 (const :tag "Only done tasks" done)
699 (repeat :tag "Specific TODO keywords"
700 (string :tag "Keyword"))))
702 (defcustom org-export-time-stamp-file t
703 "Non-nil means insert a time stamp into the exported file.
704 The time stamp shows when the file was created.
706 This option can also be set with the #+OPTIONS line,
707 e.g. \"timestamp:nil\"."
708 :group 'org-export-general
709 :type 'boolean)
711 (defcustom org-export-with-timestamps t
712 "Non nil means allow timestamps in export.
714 It can be set to `active', `inactive', t or nil, in order to
715 export, respectively, only active timestamps, only inactive ones,
716 all of them or none.
718 This option can also be set with the #+OPTIONS line, e.g.
719 \"<:nil\"."
720 :group 'org-export-general
721 :type '(choice
722 (const :tag "All timestamps" t)
723 (const :tag "Only active timestamps" active)
724 (const :tag "Only inactive timestamps" inactive)
725 (const :tag "No timestamp" nil)))
727 (defcustom org-export-with-todo-keywords t
728 "Non-nil means include TODO keywords in export.
729 When nil, remove all these keywords from the export."
730 :group 'org-export-general
731 :type 'boolean)
733 (defcustom org-export-allow-bind-keywords nil
734 "Non-nil means BIND keywords can define local variable values.
735 This is a potential security risk, which is why the default value
736 is nil. You can also allow them through local buffer variables."
737 :group 'org-export-general
738 :version "24.4"
739 :package-version '(Org . "8.0")
740 :type 'boolean)
742 (defcustom org-export-snippet-translation-alist nil
743 "Alist between export snippets back-ends and exporter back-ends.
745 This variable allows to provide shortcuts for export snippets.
747 For example, with a value of '\(\(\"h\" . \"html\"\)\), the
748 HTML back-end will recognize the contents of \"@@h:<b>@@\" as
749 HTML code while every other back-end will ignore it."
750 :group 'org-export-general
751 :version "24.4"
752 :package-version '(Org . "8.0")
753 :type '(repeat
754 (cons (string :tag "Shortcut")
755 (string :tag "Back-end"))))
757 (defcustom org-export-coding-system nil
758 "Coding system for the exported file."
759 :group 'org-export-general
760 :version "24.4"
761 :package-version '(Org . "8.0")
762 :type 'coding-system)
764 (defcustom org-export-copy-to-kill-ring 'if-interactive
765 "Should we push exported content to the kill ring?"
766 :group 'org-export-general
767 :version "24.3"
768 :type '(choice
769 (const :tag "Always" t)
770 (const :tag "When export is done interactively" if-interactive)
771 (const :tag "Never" nil)))
773 (defcustom org-export-initial-scope 'buffer
774 "The initial scope when exporting with `org-export-dispatch'.
775 This variable can be either set to `buffer' or `subtree'."
776 :group 'org-export-general
777 :type '(choice
778 (const :tag "Export current buffer" 'buffer)
779 (const :tag "Export current subtree" 'subtree)))
781 (defcustom org-export-show-temporary-export-buffer t
782 "Non-nil means show buffer after exporting to temp buffer.
783 When Org exports to a file, the buffer visiting that file is ever
784 shown, but remains buried. However, when exporting to
785 a temporary buffer, that buffer is popped up in a second window.
786 When this variable is nil, the buffer remains buried also in
787 these cases."
788 :group 'org-export-general
789 :type 'boolean)
791 (defcustom org-export-in-background nil
792 "Non-nil means export and publishing commands will run in background.
793 Results from an asynchronous export are never displayed
794 automatically. But you can retrieve them with \\[org-export-stack]."
795 :group 'org-export-general
796 :version "24.4"
797 :package-version '(Org . "8.0")
798 :type 'boolean)
800 (defcustom org-export-async-init-file user-init-file
801 "File used to initialize external export process.
802 Value must be an absolute file name. It defaults to user's
803 initialization file. Though, a specific configuration makes the
804 process faster and the export more portable."
805 :group 'org-export-general
806 :version "24.4"
807 :package-version '(Org . "8.0")
808 :type '(file :must-match t))
810 (defcustom org-export-invisible-backends nil
811 "List of back-ends that shouldn't appear in the dispatcher.
813 Any back-end belonging to this list or derived from a back-end
814 belonging to it will not appear in the dispatcher menu.
816 Indeed, Org may require some export back-ends without notice. If
817 these modules are never to be used interactively, adding them
818 here will avoid cluttering the dispatcher menu."
819 :group 'org-export-general
820 :version "24.4"
821 :package-version '(Org . "8.0")
822 :type '(repeat (symbol :tag "Back-End")))
824 (defcustom org-export-dispatch-use-expert-ui nil
825 "Non-nil means using a non-intrusive `org-export-dispatch'.
826 In that case, no help buffer is displayed. Though, an indicator
827 for current export scope is added to the prompt (\"b\" when
828 output is restricted to body only, \"s\" when it is restricted to
829 the current subtree, \"v\" when only visible elements are
830 considered for export, \"f\" when publishing functions should be
831 passed the FORCE argument and \"a\" when the export should be
832 asynchronous). Also, \[?] allows to switch back to standard
833 mode."
834 :group 'org-export-general
835 :version "24.4"
836 :package-version '(Org . "8.0")
837 :type 'boolean)
841 ;;; Defining Back-ends
843 ;; `org-export-define-backend' is the standard way to define an export
844 ;; back-end. It allows to specify translators, filters, buffer
845 ;; options and a menu entry. If the new back-end shares translators
846 ;; with another back-end, `org-export-define-derived-backend' may be
847 ;; used instead.
849 ;; Internally, a back-end is stored as a list, of which CAR is the
850 ;; name of the back-end, as a symbol, and CDR a plist. Accessors to
851 ;; properties of a given back-end are: `org-export-backend-filters',
852 ;; `org-export-backend-menu', `org-export-backend-options' and
853 ;; `org-export-backend-translate-table'.
855 ;; Eventually `org-export-barf-if-invalid-backend' returns an error
856 ;; when a given back-end hasn't been registered yet.
858 (defun org-export-define-backend (backend translators &rest body)
859 "Define a new back-end BACKEND.
861 TRANSLATORS is an alist between object or element types and
862 functions handling them.
864 These functions should return a string without any trailing
865 space, or nil. They must accept three arguments: the object or
866 element itself, its contents or nil when it isn't recursive and
867 the property list used as a communication channel.
869 Contents, when not nil, are stripped from any global indentation
870 \(although the relative one is preserved). They also always end
871 with a single newline character.
873 If, for a given type, no function is found, that element or
874 object type will simply be ignored, along with any blank line or
875 white space at its end. The same will happen if the function
876 returns the nil value. If that function returns the empty
877 string, the type will be ignored, but the blank lines or white
878 spaces will be kept.
880 In addition to element and object types, one function can be
881 associated to the `template' (or `inner-template') symbol and
882 another one to the `plain-text' symbol.
884 The former returns the final transcoded string, and can be used
885 to add a preamble and a postamble to document's body. It must
886 accept two arguments: the transcoded string and the property list
887 containing export options. A function associated to `template'
888 will not be applied if export has option \"body-only\".
889 A function associated to `inner-template' is always applied.
891 The latter, when defined, is to be called on every text not
892 recognized as an element or an object. It must accept two
893 arguments: the text string and the information channel. It is an
894 appropriate place to protect special chars relative to the
895 back-end.
897 BODY can start with pre-defined keyword arguments. The following
898 keywords are understood:
900 :export-block
902 String, or list of strings, representing block names that
903 will not be parsed. This is used to specify blocks that will
904 contain raw code specific to the back-end. These blocks
905 still have to be handled by the relative `export-block' type
906 translator.
908 :filters-alist
910 Alist between filters and function, or list of functions,
911 specific to the back-end. See `org-export-filters-alist' for
912 a list of all allowed filters. Filters defined here
913 shouldn't make a back-end test, as it may prevent back-ends
914 derived from this one to behave properly.
916 :menu-entry
918 Menu entry for the export dispatcher. It should be a list
919 like:
921 '(KEY DESCRIPTION-OR-ORDINAL ACTION-OR-MENU)
923 where :
925 KEY is a free character selecting the back-end.
927 DESCRIPTION-OR-ORDINAL is either a string or a number.
929 If it is a string, is will be used to name the back-end in
930 its menu entry. If it is a number, the following menu will
931 be displayed as a sub-menu of the back-end with the same
932 KEY. Also, the number will be used to determine in which
933 order such sub-menus will appear (lowest first).
935 ACTION-OR-MENU is either a function or an alist.
937 If it is an action, it will be called with four
938 arguments (booleans): ASYNC, SUBTREEP, VISIBLE-ONLY and
939 BODY-ONLY. See `org-export-as' for further explanations on
940 some of them.
942 If it is an alist, associations should follow the
943 pattern:
945 '(KEY DESCRIPTION ACTION)
947 where KEY, DESCRIPTION and ACTION are described above.
949 Valid values include:
951 '(?m \"My Special Back-end\" my-special-export-function)
955 '(?l \"Export to LaTeX\"
956 \(?p \"As PDF file\" org-latex-export-to-pdf)
957 \(?o \"As PDF file and open\"
958 \(lambda (a s v b)
959 \(if a (org-latex-export-to-pdf t s v b)
960 \(org-open-file
961 \(org-latex-export-to-pdf nil s v b)))))))
963 or the following, which will be added to the previous
964 sub-menu,
966 '(?l 1
967 \((?B \"As TEX buffer (Beamer)\" org-beamer-export-as-latex)
968 \(?P \"As PDF file (Beamer)\" org-beamer-export-to-pdf)))
970 :options-alist
972 Alist between back-end specific properties introduced in
973 communication channel and how their value are acquired. See
974 `org-export-options-alist' for more information about
975 structure of the values."
976 (declare (indent 1))
977 (let (export-block filters menu-entry options contents)
978 (while (keywordp (car body))
979 (case (pop body)
980 (:export-block (let ((names (pop body)))
981 (setq export-block
982 (if (consp names) (mapcar 'upcase names)
983 (list (upcase names))))))
984 (:filters-alist (setq filters (pop body)))
985 (:menu-entry (setq menu-entry (pop body)))
986 (:options-alist (setq options (pop body)))
987 (t (pop body))))
988 (setq contents (append (list :translate-alist translators)
989 (and filters (list :filters-alist filters))
990 (and options (list :options-alist options))
991 (and menu-entry (list :menu-entry menu-entry))))
992 ;; Register back-end.
993 (let ((registeredp (assq backend org-export-registered-backends)))
994 (if registeredp (setcdr registeredp contents)
995 (push (cons backend contents) org-export-registered-backends)))
996 ;; Tell parser to not parse EXPORT-BLOCK blocks.
997 (when export-block
998 (mapc
999 (lambda (name)
1000 (add-to-list 'org-element-block-name-alist
1001 `(,name . org-element-export-block-parser)))
1002 export-block))))
1004 (defun org-export-define-derived-backend (child parent &rest body)
1005 "Create a new back-end as a variant of an existing one.
1007 CHILD is the name of the derived back-end. PARENT is the name of
1008 the parent back-end.
1010 BODY can start with pre-defined keyword arguments. The following
1011 keywords are understood:
1013 :export-block
1015 String, or list of strings, representing block names that
1016 will not be parsed. This is used to specify blocks that will
1017 contain raw code specific to the back-end. These blocks
1018 still have to be handled by the relative `export-block' type
1019 translator.
1021 :filters-alist
1023 Alist of filters that will overwrite or complete filters
1024 defined in PARENT back-end. See `org-export-filters-alist'
1025 for a list of allowed filters.
1027 :menu-entry
1029 Menu entry for the export dispatcher. See
1030 `org-export-define-backend' for more information about the
1031 expected value.
1033 :options-alist
1035 Alist of back-end specific properties that will overwrite or
1036 complete those defined in PARENT back-end. Refer to
1037 `org-export-options-alist' for more information about
1038 structure of the values.
1040 :translate-alist
1042 Alist of element and object types and transcoders that will
1043 overwrite or complete transcode table from PARENT back-end.
1044 Refer to `org-export-define-backend' for detailed information
1045 about transcoders.
1047 As an example, here is how one could define \"my-latex\" back-end
1048 as a variant of `latex' back-end with a custom template function:
1050 \(org-export-define-derived-backend 'my-latex 'latex
1051 :translate-alist '((template . my-latex-template-fun)))
1053 The back-end could then be called with, for example:
1055 \(org-export-to-buffer 'my-latex \"*Test my-latex*\")"
1056 (declare (indent 2))
1057 (let (export-block filters menu-entry options translators contents)
1058 (while (keywordp (car body))
1059 (case (pop body)
1060 (:export-block (let ((names (pop body)))
1061 (setq export-block
1062 (if (consp names) (mapcar 'upcase names)
1063 (list (upcase names))))))
1064 (:filters-alist (setq filters (pop body)))
1065 (:menu-entry (setq menu-entry (pop body)))
1066 (:options-alist (setq options (pop body)))
1067 (:translate-alist (setq translators (pop body)))
1068 (t (pop body))))
1069 (setq contents (append
1070 (list :parent parent)
1071 (let ((p-table (org-export-backend-translate-table parent)))
1072 (list :translate-alist (append translators p-table)))
1073 (let ((p-filters (org-export-backend-filters parent)))
1074 (list :filters-alist (append filters p-filters)))
1075 (let ((p-options (org-export-backend-options parent)))
1076 (list :options-alist (append options p-options)))
1077 (and menu-entry (list :menu-entry menu-entry))))
1078 (org-export-barf-if-invalid-backend parent)
1079 ;; Register back-end.
1080 (let ((registeredp (assq child org-export-registered-backends)))
1081 (if registeredp (setcdr registeredp contents)
1082 (push (cons child contents) org-export-registered-backends)))
1083 ;; Tell parser to not parse EXPORT-BLOCK blocks.
1084 (when export-block
1085 (mapc
1086 (lambda (name)
1087 (add-to-list 'org-element-block-name-alist
1088 `(,name . org-element-export-block-parser)))
1089 export-block))))
1091 (defun org-export-backend-parent (backend)
1092 "Return back-end from which BACKEND is derived, or nil."
1093 (plist-get (cdr (assq backend org-export-registered-backends)) :parent))
1095 (defun org-export-backend-filters (backend)
1096 "Return filters for BACKEND."
1097 (plist-get (cdr (assq backend org-export-registered-backends))
1098 :filters-alist))
1100 (defun org-export-backend-menu (backend)
1101 "Return menu entry for BACKEND."
1102 (plist-get (cdr (assq backend org-export-registered-backends))
1103 :menu-entry))
1105 (defun org-export-backend-options (backend)
1106 "Return export options for BACKEND."
1107 (plist-get (cdr (assq backend org-export-registered-backends))
1108 :options-alist))
1110 (defun org-export-backend-translate-table (backend)
1111 "Return translate table for BACKEND."
1112 (plist-get (cdr (assq backend org-export-registered-backends))
1113 :translate-alist))
1115 (defun org-export-barf-if-invalid-backend (backend)
1116 "Signal an error if BACKEND isn't defined."
1117 (unless (org-export-backend-translate-table backend)
1118 (error "Unknown \"%s\" back-end: Aborting export" backend)))
1120 (defun org-export-derived-backend-p (backend &rest backends)
1121 "Non-nil if BACKEND is derived from one of BACKENDS."
1122 (let ((parent backend))
1123 (while (and (not (memq parent backends))
1124 (setq parent (org-export-backend-parent parent))))
1125 parent))
1129 ;;; The Communication Channel
1131 ;; During export process, every function has access to a number of
1132 ;; properties. They are of two types:
1134 ;; 1. Environment options are collected once at the very beginning of
1135 ;; the process, out of the original buffer and configuration.
1136 ;; Collecting them is handled by `org-export-get-environment'
1137 ;; function.
1139 ;; Most environment options are defined through the
1140 ;; `org-export-options-alist' variable.
1142 ;; 2. Tree properties are extracted directly from the parsed tree,
1143 ;; just before export, by `org-export-collect-tree-properties'.
1145 ;; Here is the full list of properties available during transcode
1146 ;; process, with their category and their value type.
1148 ;; + `:author' :: Author's name.
1149 ;; - category :: option
1150 ;; - type :: string
1152 ;; + `:back-end' :: Current back-end used for transcoding.
1153 ;; - category :: tree
1154 ;; - type :: symbol
1156 ;; + `:creator' :: String to write as creation information.
1157 ;; - category :: option
1158 ;; - type :: string
1160 ;; + `:date' :: String to use as date.
1161 ;; - category :: option
1162 ;; - type :: string
1164 ;; + `:description' :: Description text for the current data.
1165 ;; - category :: option
1166 ;; - type :: string
1168 ;; + `:email' :: Author's email.
1169 ;; - category :: option
1170 ;; - type :: string
1172 ;; + `:exclude-tags' :: Tags for exclusion of subtrees from export
1173 ;; process.
1174 ;; - category :: option
1175 ;; - type :: list of strings
1177 ;; + `:export-options' :: List of export options available for current
1178 ;; process.
1179 ;; - category :: none
1180 ;; - type :: list of symbols, among `subtree', `body-only' and
1181 ;; `visible-only'.
1183 ;; + `:exported-data' :: Hash table used for memoizing
1184 ;; `org-export-data'.
1185 ;; - category :: tree
1186 ;; - type :: hash table
1188 ;; + `:filetags' :: List of global tags for buffer. Used by
1189 ;; `org-export-get-tags' to get tags with inheritance.
1190 ;; - category :: option
1191 ;; - type :: list of strings
1193 ;; + `:footnote-definition-alist' :: Alist between footnote labels and
1194 ;; their definition, as parsed data. Only non-inlined footnotes
1195 ;; are represented in this alist. Also, every definition isn't
1196 ;; guaranteed to be referenced in the parse tree. The purpose of
1197 ;; this property is to preserve definitions from oblivion
1198 ;; (i.e. when the parse tree comes from a part of the original
1199 ;; buffer), it isn't meant for direct use in a back-end. To
1200 ;; retrieve a definition relative to a reference, use
1201 ;; `org-export-get-footnote-definition' instead.
1202 ;; - category :: option
1203 ;; - type :: alist (STRING . LIST)
1205 ;; + `:headline-levels' :: Maximum level being exported as an
1206 ;; headline. Comparison is done with the relative level of
1207 ;; headlines in the parse tree, not necessarily with their
1208 ;; actual level.
1209 ;; - category :: option
1210 ;; - type :: integer
1212 ;; + `:headline-offset' :: Difference between relative and real level
1213 ;; of headlines in the parse tree. For example, a value of -1
1214 ;; means a level 2 headline should be considered as level
1215 ;; 1 (cf. `org-export-get-relative-level').
1216 ;; - category :: tree
1217 ;; - type :: integer
1219 ;; + `:headline-numbering' :: Alist between headlines and their
1220 ;; numbering, as a list of numbers
1221 ;; (cf. `org-export-get-headline-number').
1222 ;; - category :: tree
1223 ;; - type :: alist (INTEGER . LIST)
1225 ;; + `:id-alist' :: Alist between ID strings and destination file's
1226 ;; path, relative to current directory. It is used by
1227 ;; `org-export-resolve-id-link' to resolve ID links targeting an
1228 ;; external file.
1229 ;; - category :: option
1230 ;; - type :: alist (STRING . STRING)
1232 ;; + `:ignore-list' :: List of elements and objects that should be
1233 ;; ignored during export.
1234 ;; - category :: tree
1235 ;; - type :: list of elements and objects
1237 ;; + `:input-file' :: Full path to input file, if any.
1238 ;; - category :: option
1239 ;; - type :: string or nil
1241 ;; + `:keywords' :: List of keywords attached to data.
1242 ;; - category :: option
1243 ;; - type :: string
1245 ;; + `:language' :: Default language used for translations.
1246 ;; - category :: option
1247 ;; - type :: string
1249 ;; + `:parse-tree' :: Whole parse tree, available at any time during
1250 ;; transcoding.
1251 ;; - category :: option
1252 ;; - type :: list (as returned by `org-element-parse-buffer')
1254 ;; + `:preserve-breaks' :: Non-nil means transcoding should preserve
1255 ;; all line breaks.
1256 ;; - category :: option
1257 ;; - type :: symbol (nil, t)
1259 ;; + `:section-numbers' :: Non-nil means transcoding should add
1260 ;; section numbers to headlines.
1261 ;; - category :: option
1262 ;; - type :: symbol (nil, t)
1264 ;; + `:select-tags' :: List of tags enforcing inclusion of sub-trees
1265 ;; in transcoding. When such a tag is present, subtrees without
1266 ;; it are de facto excluded from the process. See
1267 ;; `use-select-tags'.
1268 ;; - category :: option
1269 ;; - type :: list of strings
1271 ;; + `:time-stamp-file' :: Non-nil means transcoding should insert
1272 ;; a time stamp in the output.
1273 ;; - category :: option
1274 ;; - type :: symbol (nil, t)
1276 ;; + `:translate-alist' :: Alist between element and object types and
1277 ;; transcoding functions relative to the current back-end.
1278 ;; Special keys `inner-template', `template' and `plain-text' are
1279 ;; also possible.
1280 ;; - category :: option
1281 ;; - type :: alist (SYMBOL . FUNCTION)
1283 ;; + `:with-archived-trees' :: Non-nil when archived subtrees should
1284 ;; also be transcoded. If it is set to the `headline' symbol,
1285 ;; only the archived headline's name is retained.
1286 ;; - category :: option
1287 ;; - type :: symbol (nil, t, `headline')
1289 ;; + `:with-author' :: Non-nil means author's name should be included
1290 ;; in the output.
1291 ;; - category :: option
1292 ;; - type :: symbol (nil, t)
1294 ;; + `:with-clocks' :: Non-nil means clock keywords should be exported.
1295 ;; - category :: option
1296 ;; - type :: symbol (nil, t)
1298 ;; + `:with-creator' :: Non-nil means a creation sentence should be
1299 ;; inserted at the end of the transcoded string. If the value
1300 ;; is `comment', it should be commented.
1301 ;; - category :: option
1302 ;; - type :: symbol (`comment', nil, t)
1304 ;; + `:with-date' :: Non-nil means output should contain a date.
1305 ;; - category :: option
1306 ;; - type :. symbol (nil, t)
1308 ;; + `:with-drawers' :: Non-nil means drawers should be exported. If
1309 ;; its value is a list of names, only drawers with such names
1310 ;; will be transcoded. If that list starts with `not', drawer
1311 ;; with these names will be skipped.
1312 ;; - category :: option
1313 ;; - type :: symbol (nil, t) or list of strings
1315 ;; + `:with-email' :: Non-nil means output should contain author's
1316 ;; email.
1317 ;; - category :: option
1318 ;; - type :: symbol (nil, t)
1320 ;; + `:with-emphasize' :: Non-nil means emphasized text should be
1321 ;; interpreted.
1322 ;; - category :: option
1323 ;; - type :: symbol (nil, t)
1325 ;; + `:with-fixed-width' :: Non-nil if transcoder should interpret
1326 ;; strings starting with a colon as a fixed-with (verbatim) area.
1327 ;; - category :: option
1328 ;; - type :: symbol (nil, t)
1330 ;; + `:with-footnotes' :: Non-nil if transcoder should interpret
1331 ;; footnotes.
1332 ;; - category :: option
1333 ;; - type :: symbol (nil, t)
1335 ;; + `:with-latex' :: Non-nil means `latex-environment' elements and
1336 ;; `latex-fragment' objects should appear in export output. When
1337 ;; this property is set to `verbatim', they will be left as-is.
1338 ;; - category :: option
1339 ;; - type :: symbol (`verbatim', nil, t)
1341 ;; + `:with-plannings' :: Non-nil means transcoding should include
1342 ;; planning info.
1343 ;; - category :: option
1344 ;; - type :: symbol (nil, t)
1346 ;; + `:with-priority' :: Non-nil means transcoding should include
1347 ;; priority cookies.
1348 ;; - category :: option
1349 ;; - type :: symbol (nil, t)
1351 ;; + `:with-smart-quotes' :: Non-nil means activate smart quotes in
1352 ;; plain text.
1353 ;; - category :: option
1354 ;; - type :: symbol (nil, t)
1356 ;; + `:with-special-strings' :: Non-nil means transcoding should
1357 ;; interpret special strings in plain text.
1358 ;; - category :: option
1359 ;; - type :: symbol (nil, t)
1361 ;; + `:with-sub-superscript' :: Non-nil means transcoding should
1362 ;; interpret subscript and superscript. With a value of "{}",
1363 ;; only interpret those using curly brackets.
1364 ;; - category :: option
1365 ;; - type :: symbol (nil, {}, t)
1367 ;; + `:with-tables' :: Non-nil means transcoding should interpret
1368 ;; tables.
1369 ;; - category :: option
1370 ;; - type :: symbol (nil, t)
1372 ;; + `:with-tags' :: Non-nil means transcoding should keep tags in
1373 ;; headlines. A `not-in-toc' value will remove them from the
1374 ;; table of contents, if any, nonetheless.
1375 ;; - category :: option
1376 ;; - type :: symbol (nil, t, `not-in-toc')
1378 ;; + `:with-tasks' :: Non-nil means transcoding should include
1379 ;; headlines with a TODO keyword. A `todo' value will only
1380 ;; include headlines with a todo type keyword while a `done'
1381 ;; value will do the contrary. If a list of strings is provided,
1382 ;; only tasks with keywords belonging to that list will be kept.
1383 ;; - category :: option
1384 ;; - type :: symbol (t, todo, done, nil) or list of strings
1386 ;; + `:with-timestamps' :: Non-nil means transcoding should include
1387 ;; time stamps. Special value `active' (resp. `inactive') ask to
1388 ;; export only active (resp. inactive) timestamps. Otherwise,
1389 ;; completely remove them.
1390 ;; - category :: option
1391 ;; - type :: symbol: (`active', `inactive', t, nil)
1393 ;; + `:with-toc' :: Non-nil means that a table of contents has to be
1394 ;; added to the output. An integer value limits its depth.
1395 ;; - category :: option
1396 ;; - type :: symbol (nil, t or integer)
1398 ;; + `:with-todo-keywords' :: Non-nil means transcoding should
1399 ;; include TODO keywords.
1400 ;; - category :: option
1401 ;; - type :: symbol (nil, t)
1404 ;;;; Environment Options
1406 ;; Environment options encompass all parameters defined outside the
1407 ;; scope of the parsed data. They come from five sources, in
1408 ;; increasing precedence order:
1410 ;; - Global variables,
1411 ;; - Buffer's attributes,
1412 ;; - Options keyword symbols,
1413 ;; - Buffer keywords,
1414 ;; - Subtree properties.
1416 ;; The central internal function with regards to environment options
1417 ;; is `org-export-get-environment'. It updates global variables with
1418 ;; "#+BIND:" keywords, then retrieve and prioritize properties from
1419 ;; the different sources.
1421 ;; The internal functions doing the retrieval are:
1422 ;; `org-export--get-global-options',
1423 ;; `org-export--get-buffer-attributes',
1424 ;; `org-export--parse-option-keyword',
1425 ;; `org-export--get-subtree-options' and
1426 ;; `org-export--get-inbuffer-options'
1428 ;; Also, `org-export--install-letbind-maybe' takes care of the part
1429 ;; relative to "#+BIND:" keywords.
1431 (defun org-export-get-environment (&optional backend subtreep ext-plist)
1432 "Collect export options from the current buffer.
1434 Optional argument BACKEND is a symbol specifying which back-end
1435 specific options to read, if any.
1437 When optional argument SUBTREEP is non-nil, assume the export is
1438 done against the current sub-tree.
1440 Third optional argument EXT-PLIST is a property list with
1441 external parameters overriding Org default settings, but still
1442 inferior to file-local settings."
1443 ;; First install #+BIND variables since these must be set before
1444 ;; global options are read.
1445 (dolist (pair (org-export--list-bound-variables))
1446 (org-set-local (car pair) (nth 1 pair)))
1447 ;; Get and prioritize export options...
1448 (org-combine-plists
1449 ;; ... from global variables...
1450 (org-export--get-global-options backend)
1451 ;; ... from an external property list...
1452 ext-plist
1453 ;; ... from in-buffer settings...
1454 (org-export--get-inbuffer-options backend)
1455 ;; ... and from subtree, when appropriate.
1456 (and subtreep (org-export--get-subtree-options backend))
1457 ;; Eventually add misc. properties.
1458 (list
1459 :back-end
1460 backend
1461 :translate-alist
1462 (org-export-backend-translate-table backend)
1463 :footnote-definition-alist
1464 ;; Footnotes definitions must be collected in the original
1465 ;; buffer, as there's no insurance that they will still be in
1466 ;; the parse tree, due to possible narrowing.
1467 (let (alist)
1468 (org-with-wide-buffer
1469 (goto-char (point-min))
1470 (while (re-search-forward org-footnote-definition-re nil t)
1471 (let ((def (save-match-data (org-element-at-point))))
1472 (when (eq (org-element-type def) 'footnote-definition)
1473 (push
1474 (cons (org-element-property :label def)
1475 (let ((cbeg (org-element-property :contents-begin def)))
1476 (when cbeg
1477 (org-element--parse-elements
1478 cbeg (org-element-property :contents-end def)
1479 nil nil nil nil (list 'org-data nil)))))
1480 alist))))
1481 alist))
1482 :id-alist
1483 ;; Collect id references.
1484 (let (alist)
1485 (org-with-wide-buffer
1486 (goto-char (point-min))
1487 (while (re-search-forward "\\[\\[id:\\S-+?\\]" nil t)
1488 (let ((link (org-element-context)))
1489 (when (eq (org-element-type link) 'link)
1490 (let* ((id (org-element-property :path link))
1491 (file (org-id-find-id-file id)))
1492 (when file
1493 (push (cons id (file-relative-name file)) alist)))))))
1494 alist))))
1496 (defun org-export--parse-option-keyword (options &optional backend)
1497 "Parse an OPTIONS line and return values as a plist.
1498 Optional argument BACKEND is a symbol specifying which back-end
1499 specific items to read, if any."
1500 (let* ((all
1501 ;; Priority is given to back-end specific options.
1502 (append (and backend (org-export-backend-options backend))
1503 org-export-options-alist))
1504 plist)
1505 (dolist (option all)
1506 (let ((property (car option))
1507 (item (nth 2 option)))
1508 (when (and item
1509 (not (plist-member plist property))
1510 (string-match (concat "\\(\\`\\|[ \t]\\)"
1511 (regexp-quote item)
1512 ":\\(([^)\n]+)\\|[^ \t\n\r;,.]*\\)")
1513 options))
1514 (setq plist (plist-put plist
1515 property
1516 (car (read-from-string
1517 (match-string 2 options))))))))
1518 plist))
1520 (defun org-export--get-subtree-options (&optional backend)
1521 "Get export options in subtree at point.
1522 Optional argument BACKEND is a symbol specifying back-end used
1523 for export. Return options as a plist."
1524 ;; For each buffer keyword, create a headline property setting the
1525 ;; same property in communication channel. The name for the property
1526 ;; is the keyword with "EXPORT_" appended to it.
1527 (org-with-wide-buffer
1528 (let (prop plist)
1529 ;; Make sure point is at an heading.
1530 (if (org-at-heading-p) (org-up-heading-safe) (org-back-to-heading t))
1531 ;; Take care of EXPORT_TITLE. If it isn't defined, use headline's
1532 ;; title as its fallback value.
1533 (when (setq prop (or (org-entry-get (point) "EXPORT_TITLE")
1534 (progn (looking-at org-todo-line-regexp)
1535 (org-match-string-no-properties 3))))
1536 (setq plist
1537 (plist-put
1538 plist :title
1539 (org-element-parse-secondary-string
1540 prop (org-element-restriction 'keyword)))))
1541 ;; EXPORT_OPTIONS are parsed in a non-standard way.
1542 (when (setq prop (org-entry-get (point) "EXPORT_OPTIONS"))
1543 (setq plist
1544 (nconc plist (org-export--parse-option-keyword prop backend))))
1545 ;; Handle other keywords. TITLE keyword is excluded as it has
1546 ;; been handled already.
1547 (let ((seen '("TITLE")))
1548 (mapc
1549 (lambda (option)
1550 (let ((property (car option))
1551 (keyword (nth 1 option)))
1552 (when (and keyword (not (member keyword seen)))
1553 (let* ((subtree-prop (concat "EXPORT_" keyword))
1554 ;; Export properties are not case-sensitive.
1555 (value (let ((case-fold-search t))
1556 (org-entry-get (point) subtree-prop))))
1557 (push keyword seen)
1558 (when (and value (not (plist-member plist property)))
1559 (setq plist
1560 (plist-put
1561 plist
1562 property
1563 (cond
1564 ;; Parse VALUE if required.
1565 ((member keyword org-element-document-properties)
1566 (org-element-parse-secondary-string
1567 value (org-element-restriction 'keyword)))
1568 ;; If BEHAVIOUR is `split' expected value is
1569 ;; a list of strings, not a string.
1570 ((eq (nth 4 option) 'split) (org-split-string value))
1571 (t value)))))))))
1572 ;; Look for both general keywords and back-end specific
1573 ;; options, with priority given to the latter.
1574 (append (and backend (org-export-backend-options backend))
1575 org-export-options-alist)))
1576 ;; Return value.
1577 plist)))
1579 (defun org-export--get-inbuffer-options (&optional backend)
1580 "Return current buffer export options, as a plist.
1582 Optional argument BACKEND, when non-nil, is a symbol specifying
1583 which back-end specific options should also be read in the
1584 process.
1586 Assume buffer is in Org mode. Narrowing, if any, is ignored."
1587 (let* (plist
1588 get-options ; For byte-compiler.
1589 (case-fold-search t)
1590 (options (append
1591 ;; Priority is given to back-end specific options.
1592 (and backend (org-export-backend-options backend))
1593 org-export-options-alist))
1594 (regexp (format "^[ \t]*#\\+%s:"
1595 (regexp-opt (nconc (delq nil (mapcar 'cadr options))
1596 org-export-special-keywords))))
1597 (find-opt
1598 (lambda (keyword)
1599 ;; Return property name associated to KEYWORD.
1600 (catch 'exit
1601 (mapc (lambda (option)
1602 (when (equal (nth 1 option) keyword)
1603 (throw 'exit (car option))))
1604 options))))
1605 (get-options
1606 (lambda (&optional files plist)
1607 ;; Recursively read keywords in buffer. FILES is a list
1608 ;; of files read so far. PLIST is the current property
1609 ;; list obtained.
1610 (org-with-wide-buffer
1611 (goto-char (point-min))
1612 (while (re-search-forward regexp nil t)
1613 (let ((element (org-element-at-point)))
1614 (when (eq (org-element-type element) 'keyword)
1615 (let ((key (org-element-property :key element))
1616 (val (org-element-property :value element)))
1617 (cond
1618 ;; Options in `org-export-special-keywords'.
1619 ((equal key "SETUPFILE")
1620 (let ((file (expand-file-name
1621 (org-remove-double-quotes (org-trim val)))))
1622 ;; Avoid circular dependencies.
1623 (unless (member file files)
1624 (with-temp-buffer
1625 (insert (org-file-contents file 'noerror))
1626 (let ((org-inhibit-startup t)) (org-mode))
1627 (setq plist (funcall get-options
1628 (cons file files) plist))))))
1629 ((equal key "OPTIONS")
1630 (setq plist
1631 (org-combine-plists
1632 plist
1633 (org-export--parse-option-keyword val backend))))
1634 ((equal key "FILETAGS")
1635 (setq plist
1636 (org-combine-plists
1637 plist
1638 (list :filetags
1639 (org-uniquify
1640 (append (org-split-string val ":")
1641 (plist-get plist :filetags)))))))
1643 ;; Options in `org-export-options-alist'.
1644 (let* ((prop (funcall find-opt key))
1645 (behaviour (nth 4 (assq prop options))))
1646 (setq plist
1647 (plist-put
1648 plist prop
1649 ;; Handle value depending on specified
1650 ;; BEHAVIOUR.
1651 (case behaviour
1652 (space
1653 (if (not (plist-get plist prop))
1654 (org-trim val)
1655 (concat (plist-get plist prop)
1657 (org-trim val))))
1658 (newline
1659 (org-trim (concat (plist-get plist prop)
1660 "\n"
1661 (org-trim val))))
1662 (split `(,@(plist-get plist prop)
1663 ,@(org-split-string val)))
1664 ('t val)
1665 (otherwise
1666 (if (not (plist-member plist prop)) val
1667 (plist-get plist prop)))))))))))))
1668 ;; Return final value.
1669 plist))))
1670 ;; Read options in the current buffer.
1671 (setq plist (funcall get-options buffer-file-name nil))
1672 ;; Parse keywords specified in `org-element-document-properties'.
1673 (mapc (lambda (keyword)
1674 ;; Find the property associated to the keyword.
1675 (let* ((prop (funcall find-opt keyword))
1676 (value (and prop (plist-get plist prop))))
1677 (when (stringp value)
1678 (setq plist
1679 (plist-put plist prop
1680 (org-element-parse-secondary-string
1681 value (org-element-restriction 'keyword)))))))
1682 org-element-document-properties)
1683 ;; Return value.
1684 plist))
1686 (defun org-export--get-buffer-attributes ()
1687 "Return properties related to buffer attributes, as a plist."
1688 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
1689 (list
1690 ;; Store full path of input file name, or nil. For internal use.
1691 :input-file visited-file
1692 :title (or (and visited-file
1693 (file-name-sans-extension
1694 (file-name-nondirectory visited-file)))
1695 (buffer-name (buffer-base-buffer))))))
1697 (defun org-export--get-global-options (&optional backend)
1698 "Return global export options as a plist.
1700 Optional argument BACKEND, if non-nil, is a symbol specifying
1701 which back-end specific export options should also be read in the
1702 process."
1703 (let ((all
1704 ;; Priority is given to back-end specific options.
1705 (append (and backend (org-export-backend-options backend))
1706 org-export-options-alist))
1707 plist)
1708 (mapc
1709 (lambda (cell)
1710 (let ((prop (car cell)))
1711 (unless (plist-member plist prop)
1712 (setq plist
1713 (plist-put
1714 plist
1715 prop
1716 ;; Eval default value provided. If keyword is a member
1717 ;; of `org-element-document-properties', parse it as
1718 ;; a secondary string before storing it.
1719 (let ((value (eval (nth 3 cell))))
1720 (if (not (stringp value)) value
1721 (let ((keyword (nth 1 cell)))
1722 (if (not (member keyword org-element-document-properties))
1723 value
1724 (org-element-parse-secondary-string
1725 value (org-element-restriction 'keyword)))))))))))
1726 all)
1727 ;; Return value.
1728 plist))
1730 (defun org-export--list-bound-variables ()
1731 "Return variables bound from BIND keywords in current buffer.
1732 Also look for BIND keywords in setup files. The return value is
1733 an alist where associations are (VARIABLE-NAME VALUE)."
1734 (when org-export-allow-bind-keywords
1735 (let* (collect-bind ; For byte-compiler.
1736 (collect-bind
1737 (lambda (files alist)
1738 ;; Return an alist between variable names and their
1739 ;; value. FILES is a list of setup files names read so
1740 ;; far, used to avoid circular dependencies. ALIST is
1741 ;; the alist collected so far.
1742 (let ((case-fold-search t))
1743 (org-with-wide-buffer
1744 (goto-char (point-min))
1745 (while (re-search-forward
1746 "^[ \t]*#\\+\\(BIND\\|SETUPFILE\\):" nil t)
1747 (let ((element (org-element-at-point)))
1748 (when (eq (org-element-type element) 'keyword)
1749 (let ((val (org-element-property :value element)))
1750 (if (equal (org-element-property :key element) "BIND")
1751 (push (read (format "(%s)" val)) alist)
1752 ;; Enter setup file.
1753 (let ((file (expand-file-name
1754 (org-remove-double-quotes val))))
1755 (unless (member file files)
1756 (with-temp-buffer
1757 (let ((org-inhibit-startup t)) (org-mode))
1758 (insert (org-file-contents file 'noerror))
1759 (setq alist
1760 (funcall collect-bind
1761 (cons file files)
1762 alist))))))))))
1763 alist)))))
1764 ;; Return value in appropriate order of appearance.
1765 (nreverse (funcall collect-bind nil nil)))))
1768 ;;;; Tree Properties
1770 ;; Tree properties are information extracted from parse tree. They
1771 ;; are initialized at the beginning of the transcoding process by
1772 ;; `org-export-collect-tree-properties'.
1774 ;; Dedicated functions focus on computing the value of specific tree
1775 ;; properties during initialization. Thus,
1776 ;; `org-export--populate-ignore-list' lists elements and objects that
1777 ;; should be skipped during export, `org-export--get-min-level' gets
1778 ;; the minimal exportable level, used as a basis to compute relative
1779 ;; level for headlines. Eventually
1780 ;; `org-export--collect-headline-numbering' builds an alist between
1781 ;; headlines and their numbering.
1783 (defun org-export-collect-tree-properties (data info)
1784 "Extract tree properties from parse tree.
1786 DATA is the parse tree from which information is retrieved. INFO
1787 is a list holding export options.
1789 Following tree properties are set or updated:
1791 `:exported-data' Hash table used to memoize results from
1792 `org-export-data'.
1794 `:footnote-definition-alist' List of footnotes definitions in
1795 original buffer and current parse tree.
1797 `:headline-offset' Offset between true level of headlines and
1798 local level. An offset of -1 means a headline
1799 of level 2 should be considered as a level
1800 1 headline in the context.
1802 `:headline-numbering' Alist of all headlines as key an the
1803 associated numbering as value.
1805 `:ignore-list' List of elements that should be ignored during
1806 export.
1808 Return updated plist."
1809 ;; Install the parse tree in the communication channel, in order to
1810 ;; use `org-export-get-genealogy' and al.
1811 (setq info (plist-put info :parse-tree data))
1812 ;; Get the list of elements and objects to ignore, and put it into
1813 ;; `:ignore-list'. Do not overwrite any user ignore that might have
1814 ;; been done during parse tree filtering.
1815 (setq info
1816 (plist-put info
1817 :ignore-list
1818 (append (org-export--populate-ignore-list data info)
1819 (plist-get info :ignore-list))))
1820 ;; Compute `:headline-offset' in order to be able to use
1821 ;; `org-export-get-relative-level'.
1822 (setq info
1823 (plist-put info
1824 :headline-offset
1825 (- 1 (org-export--get-min-level data info))))
1826 ;; Update footnotes definitions list with definitions in parse tree.
1827 ;; This is required since buffer expansion might have modified
1828 ;; boundaries of footnote definitions contained in the parse tree.
1829 ;; This way, definitions in `footnote-definition-alist' are bound to
1830 ;; match those in the parse tree.
1831 (let ((defs (plist-get info :footnote-definition-alist)))
1832 (org-element-map data 'footnote-definition
1833 (lambda (fn)
1834 (push (cons (org-element-property :label fn)
1835 `(org-data nil ,@(org-element-contents fn)))
1836 defs)))
1837 (setq info (plist-put info :footnote-definition-alist defs)))
1838 ;; Properties order doesn't matter: get the rest of the tree
1839 ;; properties.
1840 (nconc
1841 `(:headline-numbering ,(org-export--collect-headline-numbering data info)
1842 :exported-data ,(make-hash-table :test 'eq :size 4001))
1843 info))
1845 (defun org-export--get-min-level (data options)
1846 "Return minimum exportable headline's level in DATA.
1847 DATA is parsed tree as returned by `org-element-parse-buffer'.
1848 OPTIONS is a plist holding export options."
1849 (catch 'exit
1850 (let ((min-level 10000))
1851 (mapc
1852 (lambda (blob)
1853 (when (and (eq (org-element-type blob) 'headline)
1854 (not (org-element-property :footnote-section-p blob))
1855 (not (memq blob (plist-get options :ignore-list))))
1856 (setq min-level (min (org-element-property :level blob) min-level)))
1857 (when (= min-level 1) (throw 'exit 1)))
1858 (org-element-contents data))
1859 ;; If no headline was found, for the sake of consistency, set
1860 ;; minimum level to 1 nonetheless.
1861 (if (= min-level 10000) 1 min-level))))
1863 (defun org-export--collect-headline-numbering (data options)
1864 "Return numbering of all exportable headlines in a parse tree.
1866 DATA is the parse tree. OPTIONS is the plist holding export
1867 options.
1869 Return an alist whose key is a headline and value is its
1870 associated numbering \(in the shape of a list of numbers\) or nil
1871 for a footnotes section."
1872 (let ((numbering (make-vector org-export-max-depth 0)))
1873 (org-element-map data 'headline
1874 (lambda (headline)
1875 (unless (org-element-property :footnote-section-p headline)
1876 (let ((relative-level
1877 (1- (org-export-get-relative-level headline options))))
1878 (cons
1879 headline
1880 (loop for n across numbering
1881 for idx from 0 to org-export-max-depth
1882 when (< idx relative-level) collect n
1883 when (= idx relative-level) collect (aset numbering idx (1+ n))
1884 when (> idx relative-level) do (aset numbering idx 0))))))
1885 options)))
1887 (defun org-export--populate-ignore-list (data options)
1888 "Return list of elements and objects to ignore during export.
1889 DATA is the parse tree to traverse. OPTIONS is the plist holding
1890 export options."
1891 (let* (ignore
1892 walk-data
1893 ;; First find trees containing a select tag, if any.
1894 (selected (org-export--selected-trees data options))
1895 (walk-data
1896 (lambda (data)
1897 ;; Collect ignored elements or objects into IGNORE-LIST.
1898 (let ((type (org-element-type data)))
1899 (if (org-export--skip-p data options selected) (push data ignore)
1900 (if (and (eq type 'headline)
1901 (eq (plist-get options :with-archived-trees) 'headline)
1902 (org-element-property :archivedp data))
1903 ;; If headline is archived but tree below has
1904 ;; to be skipped, add it to ignore list.
1905 (mapc (lambda (e) (push e ignore))
1906 (org-element-contents data))
1907 ;; Move into secondary string, if any.
1908 (let ((sec-prop
1909 (cdr (assq type org-element-secondary-value-alist))))
1910 (when sec-prop
1911 (mapc walk-data (org-element-property sec-prop data))))
1912 ;; Move into recursive objects/elements.
1913 (mapc walk-data (org-element-contents data))))))))
1914 ;; Main call.
1915 (funcall walk-data data)
1916 ;; Return value.
1917 ignore))
1919 (defun org-export--selected-trees (data info)
1920 "Return list of headlines and inlinetasks with a select tag in their tree.
1921 DATA is parsed data as returned by `org-element-parse-buffer'.
1922 INFO is a plist holding export options."
1923 (let* (selected-trees
1924 walk-data ; For byte-compiler.
1925 (walk-data
1926 (function
1927 (lambda (data genealogy)
1928 (let ((type (org-element-type data)))
1929 (cond
1930 ((memq type '(headline inlinetask))
1931 (let ((tags (org-element-property :tags data)))
1932 (if (loop for tag in (plist-get info :select-tags)
1933 thereis (member tag tags))
1934 ;; When a select tag is found, mark full
1935 ;; genealogy and every headline within the tree
1936 ;; as acceptable.
1937 (setq selected-trees
1938 (append
1939 genealogy
1940 (org-element-map data '(headline inlinetask)
1941 'identity)
1942 selected-trees))
1943 ;; If at a headline, continue searching in tree,
1944 ;; recursively.
1945 (when (eq type 'headline)
1946 (mapc (lambda (el)
1947 (funcall walk-data el (cons data genealogy)))
1948 (org-element-contents data))))))
1949 ((or (eq type 'org-data)
1950 (memq type org-element-greater-elements))
1951 (mapc (lambda (el) (funcall walk-data el genealogy))
1952 (org-element-contents data)))))))))
1953 (funcall walk-data data nil)
1954 selected-trees))
1956 (defun org-export--skip-p (blob options selected)
1957 "Non-nil when element or object BLOB should be skipped during export.
1958 OPTIONS is the plist holding export options. SELECTED, when
1959 non-nil, is a list of headlines or inlinetasks belonging to
1960 a tree with a select tag."
1961 (case (org-element-type blob)
1962 (clock (not (plist-get options :with-clocks)))
1963 (drawer
1964 (let ((with-drawers-p (plist-get options :with-drawers)))
1965 (or (not with-drawers-p)
1966 (and (consp with-drawers-p)
1967 ;; If `:with-drawers' value starts with `not', ignore
1968 ;; every drawer whose name belong to that list.
1969 ;; Otherwise, ignore drawers whose name isn't in that
1970 ;; list.
1971 (let ((name (org-element-property :drawer-name blob)))
1972 (if (eq (car with-drawers-p) 'not)
1973 (member-ignore-case name (cdr with-drawers-p))
1974 (not (member-ignore-case name with-drawers-p))))))))
1975 ((headline inlinetask)
1976 (let ((with-tasks (plist-get options :with-tasks))
1977 (todo (org-element-property :todo-keyword blob))
1978 (todo-type (org-element-property :todo-type blob))
1979 (archived (plist-get options :with-archived-trees))
1980 (tags (org-element-property :tags blob)))
1982 (and (eq (org-element-type blob) 'inlinetask)
1983 (not (plist-get options :with-inlinetasks)))
1984 ;; Ignore subtrees with an exclude tag.
1985 (loop for k in (plist-get options :exclude-tags)
1986 thereis (member k tags))
1987 ;; When a select tag is present in the buffer, ignore any tree
1988 ;; without it.
1989 (and selected (not (memq blob selected)))
1990 ;; Ignore commented sub-trees.
1991 (org-element-property :commentedp blob)
1992 ;; Ignore archived subtrees if `:with-archived-trees' is nil.
1993 (and (not archived) (org-element-property :archivedp blob))
1994 ;; Ignore tasks, if specified by `:with-tasks' property.
1995 (and todo
1996 (or (not with-tasks)
1997 (and (memq with-tasks '(todo done))
1998 (not (eq todo-type with-tasks)))
1999 (and (consp with-tasks) (not (member todo with-tasks))))))))
2000 ((latex-environment latex-fragment) (not (plist-get options :with-latex)))
2001 (planning (not (plist-get options :with-plannings)))
2002 (statistics-cookie (not (plist-get options :with-statistics-cookies)))
2003 (table-cell
2004 (and (org-export-table-has-special-column-p
2005 (org-export-get-parent-table blob))
2006 (not (org-export-get-previous-element blob options))))
2007 (table-row (org-export-table-row-is-special-p blob options))
2008 (timestamp
2009 (case (plist-get options :with-timestamps)
2010 ;; No timestamp allowed.
2011 ('nil t)
2012 ;; Only active timestamps allowed and the current one isn't
2013 ;; active.
2014 (active
2015 (not (memq (org-element-property :type blob)
2016 '(active active-range))))
2017 ;; Only inactive timestamps allowed and the current one isn't
2018 ;; inactive.
2019 (inactive
2020 (not (memq (org-element-property :type blob)
2021 '(inactive inactive-range))))))))
2024 ;;; The Transcoder
2026 ;; `org-export-data' reads a parse tree (obtained with, i.e.
2027 ;; `org-element-parse-buffer') and transcodes it into a specified
2028 ;; back-end output. It takes care of filtering out elements or
2029 ;; objects according to export options and organizing the output blank
2030 ;; lines and white space are preserved. The function memoizes its
2031 ;; results, so it is cheap to call it within translators.
2033 ;; It is possible to modify locally the back-end used by
2034 ;; `org-export-data' or even use a temporary back-end by using
2035 ;; `org-export-data-with-translations' and
2036 ;; `org-export-data-with-backend'.
2038 ;; Internally, three functions handle the filtering of objects and
2039 ;; elements during the export. In particular,
2040 ;; `org-export-ignore-element' marks an element or object so future
2041 ;; parse tree traversals skip it, `org-export--interpret-p' tells which
2042 ;; elements or objects should be seen as real Org syntax and
2043 ;; `org-export-expand' transforms the others back into their original
2044 ;; shape
2046 ;; `org-export-transcoder' is an accessor returning appropriate
2047 ;; translator function for a given element or object.
2049 (defun org-export-transcoder (blob info)
2050 "Return appropriate transcoder for BLOB.
2051 INFO is a plist containing export directives."
2052 (let ((type (org-element-type blob)))
2053 ;; Return contents only for complete parse trees.
2054 (if (eq type 'org-data) (lambda (blob contents info) contents)
2055 (let ((transcoder (cdr (assq type (plist-get info :translate-alist)))))
2056 (and (functionp transcoder) transcoder)))))
2058 (defun org-export-data (data info)
2059 "Convert DATA into current back-end format.
2061 DATA is a parse tree, an element or an object or a secondary
2062 string. INFO is a plist holding export options.
2064 Return transcoded string."
2065 (let ((memo (gethash data (plist-get info :exported-data) 'no-memo)))
2066 (if (not (eq memo 'no-memo)) memo
2067 (let* ((type (org-element-type data))
2068 (results
2069 (cond
2070 ;; Ignored element/object.
2071 ((memq data (plist-get info :ignore-list)) nil)
2072 ;; Plain text.
2073 ((eq type 'plain-text)
2074 (org-export-filter-apply-functions
2075 (plist-get info :filter-plain-text)
2076 (let ((transcoder (org-export-transcoder data info)))
2077 (if transcoder (funcall transcoder data info) data))
2078 info))
2079 ;; Uninterpreted element/object: change it back to Org
2080 ;; syntax and export again resulting raw string.
2081 ((not (org-export--interpret-p data info))
2082 (org-export-data
2083 (org-export-expand
2084 data
2085 (mapconcat (lambda (blob) (org-export-data blob info))
2086 (org-element-contents data)
2087 ""))
2088 info))
2089 ;; Secondary string.
2090 ((not type)
2091 (mapconcat (lambda (obj) (org-export-data obj info)) data ""))
2092 ;; Element/Object without contents or, as a special case,
2093 ;; headline with archive tag and archived trees restricted
2094 ;; to title only.
2095 ((or (not (org-element-contents data))
2096 (and (eq type 'headline)
2097 (eq (plist-get info :with-archived-trees) 'headline)
2098 (org-element-property :archivedp data)))
2099 (let ((transcoder (org-export-transcoder data info)))
2100 (or (and (functionp transcoder)
2101 (funcall transcoder data nil info))
2102 ;; Export snippets never return a nil value so
2103 ;; that white spaces following them are never
2104 ;; ignored.
2105 (and (eq type 'export-snippet) ""))))
2106 ;; Element/Object with contents.
2108 (let ((transcoder (org-export-transcoder data info)))
2109 (when transcoder
2110 (let* ((greaterp (memq type org-element-greater-elements))
2111 (objectp
2112 (and (not greaterp)
2113 (memq type org-element-recursive-objects)))
2114 (contents
2115 (mapconcat
2116 (lambda (element) (org-export-data element info))
2117 (org-element-contents
2118 (if (or greaterp objectp) data
2119 ;; Elements directly containing objects
2120 ;; must have their indentation normalized
2121 ;; first.
2122 (org-element-normalize-contents
2123 data
2124 ;; When normalizing contents of the first
2125 ;; paragraph in an item or a footnote
2126 ;; definition, ignore first line's
2127 ;; indentation: there is none and it
2128 ;; might be misleading.
2129 (when (eq type 'paragraph)
2130 (let ((parent (org-export-get-parent data)))
2131 (and
2132 (eq (car (org-element-contents parent))
2133 data)
2134 (memq (org-element-type parent)
2135 '(footnote-definition item))))))))
2136 "")))
2137 (funcall transcoder data
2138 (if (not greaterp) contents
2139 (org-element-normalize-string contents))
2140 info))))))))
2141 ;; Final result will be memoized before being returned.
2142 (puthash
2143 data
2144 (cond
2145 ((not results) nil)
2146 ((memq type '(org-data plain-text nil)) results)
2147 ;; Append the same white space between elements or objects as in
2148 ;; the original buffer, and call appropriate filters.
2150 (let ((results
2151 (org-export-filter-apply-functions
2152 (plist-get info (intern (format ":filter-%s" type)))
2153 (let ((post-blank (or (org-element-property :post-blank data)
2154 0)))
2155 (if (memq type org-element-all-elements)
2156 (concat (org-element-normalize-string results)
2157 (make-string post-blank ?\n))
2158 (concat results (make-string post-blank ? ))))
2159 info)))
2160 results)))
2161 (plist-get info :exported-data))))))
2163 (defun org-export-data-with-translations (data translations info)
2164 "Convert DATA into another format using a given translation table.
2165 DATA is an element, an object, a secondary string or a string.
2166 TRANSLATIONS is an alist between element or object types and
2167 a functions handling them. See `org-export-define-backend' for
2168 more information. INFO is a plist used as a communication
2169 channel."
2170 (org-export-data
2171 data
2172 ;; Set-up a new communication channel with TRANSLATIONS as the
2173 ;; translate table and a new hash table for memoization.
2174 (org-combine-plists
2175 info
2176 (list :translate-alist translations
2177 ;; Size of the hash table is reduced since this function
2178 ;; will probably be used on short trees.
2179 :exported-data (make-hash-table :test 'eq :size 401)))))
2181 (defun org-export-data-with-backend (data backend info)
2182 "Convert DATA into BACKEND format.
2184 DATA is an element, an object, a secondary string or a string.
2185 BACKEND is a symbol. INFO is a plist used as a communication
2186 channel.
2188 Unlike to `org-export-with-backend', this function will
2189 recursively convert DATA using BACKEND translation table."
2190 (org-export-barf-if-invalid-backend backend)
2191 (org-export-data-with-translations
2192 data (org-export-backend-translate-table backend) info))
2194 (defun org-export--interpret-p (blob info)
2195 "Non-nil if element or object BLOB should be interpreted during export.
2196 If nil, BLOB will appear as raw Org syntax. Check is done
2197 according to export options INFO, stored as a plist."
2198 (case (org-element-type blob)
2199 ;; ... entities...
2200 (entity (plist-get info :with-entities))
2201 ;; ... emphasis...
2202 ((bold italic strike-through underline)
2203 (plist-get info :with-emphasize))
2204 ;; ... fixed-width areas.
2205 (fixed-width (plist-get info :with-fixed-width))
2206 ;; ... footnotes...
2207 ((footnote-definition footnote-reference)
2208 (plist-get info :with-footnotes))
2209 ;; ... LaTeX environments and fragments...
2210 ((latex-environment latex-fragment)
2211 (let ((with-latex-p (plist-get info :with-latex)))
2212 (and with-latex-p (not (eq with-latex-p 'verbatim)))))
2213 ;; ... sub/superscripts...
2214 ((subscript superscript)
2215 (let ((sub/super-p (plist-get info :with-sub-superscript)))
2216 (if (eq sub/super-p '{})
2217 (org-element-property :use-brackets-p blob)
2218 sub/super-p)))
2219 ;; ... tables...
2220 (table (plist-get info :with-tables))
2221 (otherwise t)))
2223 (defun org-export-expand (blob contents)
2224 "Expand a parsed element or object to its original state.
2225 BLOB is either an element or an object. CONTENTS is its
2226 contents, as a string or nil."
2227 (funcall
2228 (intern (format "org-element-%s-interpreter" (org-element-type blob)))
2229 blob contents))
2231 (defun org-export-ignore-element (element info)
2232 "Add ELEMENT to `:ignore-list' in INFO.
2234 Any element in `:ignore-list' will be skipped when using
2235 `org-element-map'. INFO is modified by side effects."
2236 (plist-put info :ignore-list (cons element (plist-get info :ignore-list))))
2240 ;;; The Filter System
2242 ;; Filters allow end-users to tweak easily the transcoded output.
2243 ;; They are the functional counterpart of hooks, as every filter in
2244 ;; a set is applied to the return value of the previous one.
2246 ;; Every set is back-end agnostic. Although, a filter is always
2247 ;; called, in addition to the string it applies to, with the back-end
2248 ;; used as argument, so it's easy for the end-user to add back-end
2249 ;; specific filters in the set. The communication channel, as
2250 ;; a plist, is required as the third argument.
2252 ;; From the developer side, filters sets can be installed in the
2253 ;; process with the help of `org-export-define-backend', which
2254 ;; internally stores filters as an alist. Each association has a key
2255 ;; among the following symbols and a function or a list of functions
2256 ;; as value.
2258 ;; - `:filter-options' applies to the property list containing export
2259 ;; options. Unlike to other filters, functions in this list accept
2260 ;; two arguments instead of three: the property list containing
2261 ;; export options and the back-end. Users can set its value through
2262 ;; `org-export-filter-options-functions' variable.
2264 ;; - `:filter-parse-tree' applies directly to the complete parsed
2265 ;; tree. Users can set it through
2266 ;; `org-export-filter-parse-tree-functions' variable.
2268 ;; - `:filter-final-output' applies to the final transcoded string.
2269 ;; Users can set it with `org-export-filter-final-output-functions'
2270 ;; variable
2272 ;; - `:filter-plain-text' applies to any string not recognized as Org
2273 ;; syntax. `org-export-filter-plain-text-functions' allows users to
2274 ;; configure it.
2276 ;; - `:filter-TYPE' applies on the string returned after an element or
2277 ;; object of type TYPE has been transcoded. An user can modify
2278 ;; `org-export-filter-TYPE-functions'
2280 ;; All filters sets are applied with
2281 ;; `org-export-filter-apply-functions' function. Filters in a set are
2282 ;; applied in a LIFO fashion. It allows developers to be sure that
2283 ;; their filters will be applied first.
2285 ;; Filters properties are installed in communication channel with
2286 ;; `org-export-install-filters' function.
2288 ;; Eventually, two hooks (`org-export-before-processing-hook' and
2289 ;; `org-export-before-parsing-hook') are run at the beginning of the
2290 ;; export process and just before parsing to allow for heavy structure
2291 ;; modifications.
2294 ;;;; Hooks
2296 (defvar org-export-before-processing-hook nil
2297 "Hook run at the beginning of the export process.
2299 This is run before include keywords and macros are expanded and
2300 Babel code blocks executed, on a copy of the original buffer
2301 being exported. Visibility and narrowing are preserved. Point
2302 is at the beginning of the buffer.
2304 Every function in this hook will be called with one argument: the
2305 back-end currently used, as a symbol.")
2307 (defvar org-export-before-parsing-hook nil
2308 "Hook run before parsing an export buffer.
2310 This is run after include keywords and macros have been expanded
2311 and Babel code blocks executed, on a copy of the original buffer
2312 being exported. Visibility and narrowing are preserved. Point
2313 is at the beginning of the buffer.
2315 Every function in this hook will be called with one argument: the
2316 back-end currently used, as a symbol.")
2319 ;;;; Special Filters
2321 (defvar org-export-filter-options-functions nil
2322 "List of functions applied to the export options.
2323 Each filter is called with two arguments: the export options, as
2324 a plist, and the back-end, as a symbol. It must return
2325 a property list containing export options.")
2327 (defvar org-export-filter-parse-tree-functions nil
2328 "List of functions applied to the parsed tree.
2329 Each filter is called with three arguments: the parse tree, as
2330 returned by `org-element-parse-buffer', the back-end, as
2331 a symbol, and the communication channel, as a plist. It must
2332 return the modified parse tree to transcode.")
2334 (defvar org-export-filter-plain-text-functions nil
2335 "List of functions applied to plain text.
2336 Each filter is called with three arguments: a string which
2337 contains no Org syntax, the back-end, as a symbol, and the
2338 communication channel, as a plist. It must return a string or
2339 nil.")
2341 (defvar org-export-filter-final-output-functions nil
2342 "List of functions applied to the transcoded string.
2343 Each filter is called with three arguments: the full transcoded
2344 string, the back-end, as a symbol, and the communication channel,
2345 as a plist. It must return a string that will be used as the
2346 final export output.")
2349 ;;;; Elements Filters
2351 (defvar org-export-filter-babel-call-functions nil
2352 "List of functions applied to a transcoded babel-call.
2353 Each filter is called with three arguments: the transcoded data,
2354 as a string, the back-end, as a symbol, and the communication
2355 channel, as a plist. It must return a string or nil.")
2357 (defvar org-export-filter-center-block-functions nil
2358 "List of functions applied to a transcoded center block.
2359 Each filter is called with three arguments: the transcoded data,
2360 as a string, the back-end, as a symbol, and the communication
2361 channel, as a plist. It must return a string or nil.")
2363 (defvar org-export-filter-clock-functions nil
2364 "List of functions applied to a transcoded clock.
2365 Each filter is called with three arguments: the transcoded data,
2366 as a string, the back-end, as a symbol, and the communication
2367 channel, as a plist. It must return a string or nil.")
2369 (defvar org-export-filter-comment-functions nil
2370 "List of functions applied to a transcoded comment.
2371 Each filter is called with three arguments: the transcoded data,
2372 as a string, the back-end, as a symbol, and the communication
2373 channel, as a plist. It must return a string or nil.")
2375 (defvar org-export-filter-comment-block-functions nil
2376 "List of functions applied to a transcoded comment-block.
2377 Each filter is called with three arguments: the transcoded data,
2378 as a string, the back-end, as a symbol, and the communication
2379 channel, as a plist. It must return a string or nil.")
2381 (defvar org-export-filter-diary-sexp-functions nil
2382 "List of functions applied to a transcoded diary-sexp.
2383 Each filter is called with three arguments: the transcoded data,
2384 as a string, the back-end, as a symbol, and the communication
2385 channel, as a plist. It must return a string or nil.")
2387 (defvar org-export-filter-drawer-functions nil
2388 "List of functions applied to a transcoded drawer.
2389 Each filter is called with three arguments: the transcoded data,
2390 as a string, the back-end, as a symbol, and the communication
2391 channel, as a plist. It must return a string or nil.")
2393 (defvar org-export-filter-dynamic-block-functions nil
2394 "List of functions applied to a transcoded dynamic-block.
2395 Each filter is called with three arguments: the transcoded data,
2396 as a string, the back-end, as a symbol, and the communication
2397 channel, as a plist. It must return a string or nil.")
2399 (defvar org-export-filter-example-block-functions nil
2400 "List of functions applied to a transcoded example-block.
2401 Each filter is called with three arguments: the transcoded data,
2402 as a string, the back-end, as a symbol, and the communication
2403 channel, as a plist. It must return a string or nil.")
2405 (defvar org-export-filter-export-block-functions nil
2406 "List of functions applied to a transcoded export-block.
2407 Each filter is called with three arguments: the transcoded data,
2408 as a string, the back-end, as a symbol, and the communication
2409 channel, as a plist. It must return a string or nil.")
2411 (defvar org-export-filter-fixed-width-functions nil
2412 "List of functions applied to a transcoded fixed-width.
2413 Each filter is called with three arguments: the transcoded data,
2414 as a string, the back-end, as a symbol, and the communication
2415 channel, as a plist. It must return a string or nil.")
2417 (defvar org-export-filter-footnote-definition-functions nil
2418 "List of functions applied to a transcoded footnote-definition.
2419 Each filter is called with three arguments: the transcoded data,
2420 as a string, the back-end, as a symbol, and the communication
2421 channel, as a plist. It must return a string or nil.")
2423 (defvar org-export-filter-headline-functions nil
2424 "List of functions applied to a transcoded headline.
2425 Each filter is called with three arguments: the transcoded data,
2426 as a string, the back-end, as a symbol, and the communication
2427 channel, as a plist. It must return a string or nil.")
2429 (defvar org-export-filter-horizontal-rule-functions nil
2430 "List of functions applied to a transcoded horizontal-rule.
2431 Each filter is called with three arguments: the transcoded data,
2432 as a string, the back-end, as a symbol, and the communication
2433 channel, as a plist. It must return a string or nil.")
2435 (defvar org-export-filter-inlinetask-functions nil
2436 "List of functions applied to a transcoded inlinetask.
2437 Each filter is called with three arguments: the transcoded data,
2438 as a string, the back-end, as a symbol, and the communication
2439 channel, as a plist. It must return a string or nil.")
2441 (defvar org-export-filter-item-functions nil
2442 "List of functions applied to a transcoded item.
2443 Each filter is called with three arguments: the transcoded data,
2444 as a string, the back-end, as a symbol, and the communication
2445 channel, as a plist. It must return a string or nil.")
2447 (defvar org-export-filter-keyword-functions nil
2448 "List of functions applied to a transcoded keyword.
2449 Each filter is called with three arguments: the transcoded data,
2450 as a string, the back-end, as a symbol, and the communication
2451 channel, as a plist. It must return a string or nil.")
2453 (defvar org-export-filter-latex-environment-functions nil
2454 "List of functions applied to a transcoded latex-environment.
2455 Each filter is called with three arguments: the transcoded data,
2456 as a string, the back-end, as a symbol, and the communication
2457 channel, as a plist. It must return a string or nil.")
2459 (defvar org-export-filter-node-property-functions nil
2460 "List of functions applied to a transcoded node-property.
2461 Each filter is called with three arguments: the transcoded data,
2462 as a string, the back-end, as a symbol, and the communication
2463 channel, as a plist. It must return a string or nil.")
2465 (defvar org-export-filter-paragraph-functions nil
2466 "List of functions applied to a transcoded paragraph.
2467 Each filter is called with three arguments: the transcoded data,
2468 as a string, the back-end, as a symbol, and the communication
2469 channel, as a plist. It must return a string or nil.")
2471 (defvar org-export-filter-plain-list-functions nil
2472 "List of functions applied to a transcoded plain-list.
2473 Each filter is called with three arguments: the transcoded data,
2474 as a string, the back-end, as a symbol, and the communication
2475 channel, as a plist. It must return a string or nil.")
2477 (defvar org-export-filter-planning-functions nil
2478 "List of functions applied to a transcoded planning.
2479 Each filter is called with three arguments: the transcoded data,
2480 as a string, the back-end, as a symbol, and the communication
2481 channel, as a plist. It must return a string or nil.")
2483 (defvar org-export-filter-property-drawer-functions nil
2484 "List of functions applied to a transcoded property-drawer.
2485 Each filter is called with three arguments: the transcoded data,
2486 as a string, the back-end, as a symbol, and the communication
2487 channel, as a plist. It must return a string or nil.")
2489 (defvar org-export-filter-quote-block-functions nil
2490 "List of functions applied to a transcoded quote block.
2491 Each filter is called with three arguments: the transcoded quote
2492 data, as a string, the back-end, as a symbol, and the
2493 communication channel, as a plist. It must return a string or
2494 nil.")
2496 (defvar org-export-filter-quote-section-functions nil
2497 "List of functions applied to a transcoded quote-section.
2498 Each filter is called with three arguments: the transcoded data,
2499 as a string, the back-end, as a symbol, and the communication
2500 channel, as a plist. It must return a string or nil.")
2502 (defvar org-export-filter-section-functions nil
2503 "List of functions applied to a transcoded section.
2504 Each filter is called with three arguments: the transcoded data,
2505 as a string, the back-end, as a symbol, and the communication
2506 channel, as a plist. It must return a string or nil.")
2508 (defvar org-export-filter-special-block-functions nil
2509 "List of functions applied to a transcoded special block.
2510 Each filter is called with three arguments: the transcoded data,
2511 as a string, the back-end, as a symbol, and the communication
2512 channel, as a plist. It must return a string or nil.")
2514 (defvar org-export-filter-src-block-functions nil
2515 "List of functions applied to a transcoded src-block.
2516 Each filter is called with three arguments: the transcoded data,
2517 as a string, the back-end, as a symbol, and the communication
2518 channel, as a plist. It must return a string or nil.")
2520 (defvar org-export-filter-table-functions nil
2521 "List of functions applied to a transcoded table.
2522 Each filter is called with three arguments: the transcoded data,
2523 as a string, the back-end, as a symbol, and the communication
2524 channel, as a plist. It must return a string or nil.")
2526 (defvar org-export-filter-table-cell-functions nil
2527 "List of functions applied to a transcoded table-cell.
2528 Each filter is called with three arguments: the transcoded data,
2529 as a string, the back-end, as a symbol, and the communication
2530 channel, as a plist. It must return a string or nil.")
2532 (defvar org-export-filter-table-row-functions nil
2533 "List of functions applied to a transcoded table-row.
2534 Each filter is called with three arguments: the transcoded data,
2535 as a string, the back-end, as a symbol, and the communication
2536 channel, as a plist. It must return a string or nil.")
2538 (defvar org-export-filter-verse-block-functions nil
2539 "List of functions applied to a transcoded verse block.
2540 Each filter is called with three arguments: the transcoded data,
2541 as a string, the back-end, as a symbol, and the communication
2542 channel, as a plist. It must return a string or nil.")
2545 ;;;; Objects Filters
2547 (defvar org-export-filter-bold-functions nil
2548 "List of functions applied to transcoded bold text.
2549 Each filter is called with three arguments: the transcoded data,
2550 as a string, the back-end, as a symbol, and the communication
2551 channel, as a plist. It must return a string or nil.")
2553 (defvar org-export-filter-code-functions nil
2554 "List of functions applied to transcoded code text.
2555 Each filter is called with three arguments: the transcoded data,
2556 as a string, the back-end, as a symbol, and the communication
2557 channel, as a plist. It must return a string or nil.")
2559 (defvar org-export-filter-entity-functions nil
2560 "List of functions applied to a transcoded entity.
2561 Each filter is called with three arguments: the transcoded data,
2562 as a string, the back-end, as a symbol, and the communication
2563 channel, as a plist. It must return a string or nil.")
2565 (defvar org-export-filter-export-snippet-functions nil
2566 "List of functions applied to a transcoded export-snippet.
2567 Each filter is called with three arguments: the transcoded data,
2568 as a string, the back-end, as a symbol, and the communication
2569 channel, as a plist. It must return a string or nil.")
2571 (defvar org-export-filter-footnote-reference-functions nil
2572 "List of functions applied to a transcoded footnote-reference.
2573 Each filter is called with three arguments: the transcoded data,
2574 as a string, the back-end, as a symbol, and the communication
2575 channel, as a plist. It must return a string or nil.")
2577 (defvar org-export-filter-inline-babel-call-functions nil
2578 "List of functions applied to a transcoded inline-babel-call.
2579 Each filter is called with three arguments: the transcoded data,
2580 as a string, the back-end, as a symbol, and the communication
2581 channel, as a plist. It must return a string or nil.")
2583 (defvar org-export-filter-inline-src-block-functions nil
2584 "List of functions applied to a transcoded inline-src-block.
2585 Each filter is called with three arguments: the transcoded data,
2586 as a string, the back-end, as a symbol, and the communication
2587 channel, as a plist. It must return a string or nil.")
2589 (defvar org-export-filter-italic-functions nil
2590 "List of functions applied to transcoded italic text.
2591 Each filter is called with three arguments: the transcoded data,
2592 as a string, the back-end, as a symbol, and the communication
2593 channel, as a plist. It must return a string or nil.")
2595 (defvar org-export-filter-latex-fragment-functions nil
2596 "List of functions applied to a transcoded latex-fragment.
2597 Each filter is called with three arguments: the transcoded data,
2598 as a string, the back-end, as a symbol, and the communication
2599 channel, as a plist. It must return a string or nil.")
2601 (defvar org-export-filter-line-break-functions nil
2602 "List of functions applied to a transcoded line-break.
2603 Each filter is called with three arguments: the transcoded data,
2604 as a string, the back-end, as a symbol, and the communication
2605 channel, as a plist. It must return a string or nil.")
2607 (defvar org-export-filter-link-functions nil
2608 "List of functions applied to a transcoded link.
2609 Each filter is called with three arguments: the transcoded data,
2610 as a string, the back-end, as a symbol, and the communication
2611 channel, as a plist. It must return a string or nil.")
2613 (defvar org-export-filter-macro-functions nil
2614 "List of functions applied to a transcoded macro.
2615 Each filter is called with three arguments: the transcoded data,
2616 as a string, the back-end, as a symbol, and the communication
2617 channel, as a plist. It must return a string or nil.")
2619 (defvar org-export-filter-radio-target-functions nil
2620 "List of functions applied to a transcoded radio-target.
2621 Each filter is called with three arguments: the transcoded data,
2622 as a string, the back-end, as a symbol, and the communication
2623 channel, as a plist. It must return a string or nil.")
2625 (defvar org-export-filter-statistics-cookie-functions nil
2626 "List of functions applied to a transcoded statistics-cookie.
2627 Each filter is called with three arguments: the transcoded data,
2628 as a string, the back-end, as a symbol, and the communication
2629 channel, as a plist. It must return a string or nil.")
2631 (defvar org-export-filter-strike-through-functions nil
2632 "List of functions applied to transcoded strike-through text.
2633 Each filter is called with three arguments: the transcoded data,
2634 as a string, the back-end, as a symbol, and the communication
2635 channel, as a plist. It must return a string or nil.")
2637 (defvar org-export-filter-subscript-functions nil
2638 "List of functions applied to a transcoded subscript.
2639 Each filter is called with three arguments: the transcoded data,
2640 as a string, the back-end, as a symbol, and the communication
2641 channel, as a plist. It must return a string or nil.")
2643 (defvar org-export-filter-superscript-functions nil
2644 "List of functions applied to a transcoded superscript.
2645 Each filter is called with three arguments: the transcoded data,
2646 as a string, the back-end, as a symbol, and the communication
2647 channel, as a plist. It must return a string or nil.")
2649 (defvar org-export-filter-target-functions nil
2650 "List of functions applied to a transcoded target.
2651 Each filter is called with three arguments: the transcoded data,
2652 as a string, the back-end, as a symbol, and the communication
2653 channel, as a plist. It must return a string or nil.")
2655 (defvar org-export-filter-timestamp-functions nil
2656 "List of functions applied to a transcoded timestamp.
2657 Each filter is called with three arguments: the transcoded data,
2658 as a string, the back-end, as a symbol, and the communication
2659 channel, as a plist. It must return a string or nil.")
2661 (defvar org-export-filter-underline-functions nil
2662 "List of functions applied to transcoded underline text.
2663 Each filter is called with three arguments: the transcoded data,
2664 as a string, the back-end, as a symbol, and the communication
2665 channel, as a plist. It must return a string or nil.")
2667 (defvar org-export-filter-verbatim-functions nil
2668 "List of functions applied to transcoded verbatim text.
2669 Each filter is called with three arguments: the transcoded data,
2670 as a string, the back-end, as a symbol, and the communication
2671 channel, as a plist. It must return a string or nil.")
2674 ;;;; Filters Tools
2676 ;; Internal function `org-export-install-filters' installs filters
2677 ;; hard-coded in back-ends (developer filters) and filters from global
2678 ;; variables (user filters) in the communication channel.
2680 ;; Internal function `org-export-filter-apply-functions' takes care
2681 ;; about applying each filter in order to a given data. It ignores
2682 ;; filters returning a nil value but stops whenever a filter returns
2683 ;; an empty string.
2685 (defun org-export-filter-apply-functions (filters value info)
2686 "Call every function in FILTERS.
2688 Functions are called with arguments VALUE, current export
2689 back-end and INFO. A function returning a nil value will be
2690 skipped. If it returns the empty string, the process ends and
2691 VALUE is ignored.
2693 Call is done in a LIFO fashion, to be sure that developer
2694 specified filters, if any, are called first."
2695 (catch 'exit
2696 (dolist (filter filters value)
2697 (let ((result (funcall filter value (plist-get info :back-end) info)))
2698 (cond ((not result) value)
2699 ((equal value "") (throw 'exit nil))
2700 (t (setq value result)))))))
2702 (defun org-export-install-filters (info)
2703 "Install filters properties in communication channel.
2704 INFO is a plist containing the current communication channel.
2705 Return the updated communication channel."
2706 (let (plist)
2707 ;; Install user-defined filters with `org-export-filters-alist'
2708 ;; and filters already in INFO (through ext-plist mechanism).
2709 (mapc (lambda (p)
2710 (let* ((prop (car p))
2711 (info-value (plist-get info prop))
2712 (default-value (symbol-value (cdr p))))
2713 (setq plist
2714 (plist-put plist prop
2715 ;; Filters in INFO will be called
2716 ;; before those user provided.
2717 (append (if (listp info-value) info-value
2718 (list info-value))
2719 default-value)))))
2720 org-export-filters-alist)
2721 ;; Prepend back-end specific filters to that list.
2722 (mapc (lambda (p)
2723 ;; Single values get consed, lists are appended.
2724 (let ((key (car p)) (value (cdr p)))
2725 (when value
2726 (setq plist
2727 (plist-put
2728 plist key
2729 (if (atom value) (cons value (plist-get plist key))
2730 (append value (plist-get plist key))))))))
2731 (org-export-backend-filters (plist-get info :back-end)))
2732 ;; Return new communication channel.
2733 (org-combine-plists info plist)))
2737 ;;; Core functions
2739 ;; This is the room for the main function, `org-export-as', along with
2740 ;; its derivatives, `org-export-to-buffer', `org-export-to-file' and
2741 ;; `org-export-string-as'. They differ either by the way they output
2742 ;; the resulting code (for the first two) or by the input type (for
2743 ;; the latter). `org-export--copy-to-kill-ring-p' determines if
2744 ;; output of these function should be added to kill ring.
2746 ;; `org-export-output-file-name' is an auxiliary function meant to be
2747 ;; used with `org-export-to-file'. With a given extension, it tries
2748 ;; to provide a canonical file name to write export output to.
2750 ;; Note that `org-export-as' doesn't really parse the current buffer,
2751 ;; but a copy of it (with the same buffer-local variables and
2752 ;; visibility), where macros and include keywords are expanded and
2753 ;; Babel blocks are executed, if appropriate.
2754 ;; `org-export-with-buffer-copy' macro prepares that copy.
2756 ;; File inclusion is taken care of by
2757 ;; `org-export-expand-include-keyword' and
2758 ;; `org-export--prepare-file-contents'. Structure wise, including
2759 ;; a whole Org file in a buffer often makes little sense. For
2760 ;; example, if the file contains a headline and the include keyword
2761 ;; was within an item, the item should contain the headline. That's
2762 ;; why file inclusion should be done before any structure can be
2763 ;; associated to the file, that is before parsing.
2765 ;; `org-export-insert-default-template' is a command to insert
2766 ;; a default template (or a back-end specific template) at point or in
2767 ;; current subtree.
2769 (defun org-export-copy-buffer ()
2770 "Return a copy of the current buffer.
2771 The copy preserves Org buffer-local variables, visibility and
2772 narrowing."
2773 (let ((copy-buffer-fun (org-export--generate-copy-script (current-buffer)))
2774 (new-buf (generate-new-buffer (buffer-name))))
2775 (with-current-buffer new-buf
2776 (funcall copy-buffer-fun)
2777 (set-buffer-modified-p nil))
2778 new-buf))
2780 (defmacro org-export-with-buffer-copy (&rest body)
2781 "Apply BODY in a copy of the current buffer.
2782 The copy preserves local variables, visibility and contents of
2783 the original buffer. Point is at the beginning of the buffer
2784 when BODY is applied."
2785 (declare (debug t))
2786 (org-with-gensyms (buf-copy)
2787 `(let ((,buf-copy (org-export-copy-buffer)))
2788 (unwind-protect
2789 (with-current-buffer ,buf-copy
2790 (goto-char (point-min))
2791 (progn ,@body))
2792 (and (buffer-live-p ,buf-copy)
2793 ;; Kill copy without confirmation.
2794 (progn (with-current-buffer ,buf-copy
2795 (restore-buffer-modified-p nil))
2796 (kill-buffer ,buf-copy)))))))
2798 (defun org-export--generate-copy-script (buffer)
2799 "Generate a function duplicating BUFFER.
2801 The copy will preserve local variables, visibility, contents and
2802 narrowing of the original buffer. If a region was active in
2803 BUFFER, contents will be narrowed to that region instead.
2805 The resulting function can be evaled at a later time, from
2806 another buffer, effectively cloning the original buffer there.
2808 The function assumes BUFFER's major mode is `org-mode'."
2809 (with-current-buffer buffer
2810 `(lambda ()
2811 (let ((inhibit-modification-hooks t))
2812 ;; Set major mode. Ignore `org-mode-hook' as it has been run
2813 ;; already in BUFFER.
2814 (let ((org-mode-hook nil) (org-inhibit-startup t)) (org-mode))
2815 ;; Copy specific buffer local variables and variables set
2816 ;; through BIND keywords.
2817 ,@(let ((bound-variables (org-export--list-bound-variables))
2818 vars)
2819 (dolist (entry (buffer-local-variables (buffer-base-buffer)) vars)
2820 (when (consp entry)
2821 (let ((var (car entry))
2822 (val (cdr entry)))
2823 (and (not (eq var 'org-font-lock-keywords))
2824 (or (memq var
2825 '(default-directory
2826 buffer-file-name
2827 buffer-file-coding-system))
2828 (assq var bound-variables)
2829 (string-match "^\\(org-\\|orgtbl-\\)"
2830 (symbol-name var)))
2831 ;; Skip unreadable values, as they cannot be
2832 ;; sent to external process.
2833 (or (not val) (ignore-errors (read (format "%S" val))))
2834 (push `(set (make-local-variable (quote ,var))
2835 (quote ,val))
2836 vars))))))
2837 ;; Whole buffer contents.
2838 (insert
2839 ,(org-with-wide-buffer
2840 (buffer-substring-no-properties
2841 (point-min) (point-max))))
2842 ;; Narrowing.
2843 ,(if (org-region-active-p)
2844 `(narrow-to-region ,(region-beginning) ,(region-end))
2845 `(narrow-to-region ,(point-min) ,(point-max)))
2846 ;; Current position of point.
2847 (goto-char ,(point))
2848 ;; Overlays with invisible property.
2849 ,@(let (ov-set)
2850 (mapc
2851 (lambda (ov)
2852 (let ((invis-prop (overlay-get ov 'invisible)))
2853 (when invis-prop
2854 (push `(overlay-put
2855 (make-overlay ,(overlay-start ov)
2856 ,(overlay-end ov))
2857 'invisible (quote ,invis-prop))
2858 ov-set))))
2859 (overlays-in (point-min) (point-max)))
2860 ov-set)))))
2862 ;;;###autoload
2863 (defun org-export-as
2864 (backend &optional subtreep visible-only body-only ext-plist)
2865 "Transcode current Org buffer into BACKEND code.
2867 If narrowing is active in the current buffer, only transcode its
2868 narrowed part.
2870 If a region is active, transcode that region.
2872 When optional argument SUBTREEP is non-nil, transcode the
2873 sub-tree at point, extracting information from the headline
2874 properties first.
2876 When optional argument VISIBLE-ONLY is non-nil, don't export
2877 contents of hidden elements.
2879 When optional argument BODY-ONLY is non-nil, only return body
2880 code, without surrounding template.
2882 Optional argument EXT-PLIST, when provided, is a property list
2883 with external parameters overriding Org default settings, but
2884 still inferior to file-local settings.
2886 Return code as a string."
2887 (org-export-barf-if-invalid-backend backend)
2888 (save-excursion
2889 (save-restriction
2890 ;; Narrow buffer to an appropriate region or subtree for
2891 ;; parsing. If parsing subtree, be sure to remove main headline
2892 ;; too.
2893 (cond ((org-region-active-p)
2894 (narrow-to-region (region-beginning) (region-end)))
2895 (subtreep
2896 (org-narrow-to-subtree)
2897 (goto-char (point-min))
2898 (forward-line)
2899 (narrow-to-region (point) (point-max))))
2900 ;; Initialize communication channel with original buffer
2901 ;; attributes, unavailable in its copy.
2902 (let ((info (org-combine-plists
2903 (list :export-options
2904 (delq nil
2905 (list (and subtreep 'subtree)
2906 (and visible-only 'visible-only)
2907 (and body-only 'body-only))))
2908 (org-export--get-buffer-attributes)))
2909 tree)
2910 ;; Update communication channel and get parse tree. Buffer
2911 ;; isn't parsed directly. Instead, a temporary copy is
2912 ;; created, where include keywords, macros are expanded and
2913 ;; code blocks are evaluated.
2914 (org-export-with-buffer-copy
2915 ;; Run first hook with current back-end as argument.
2916 (run-hook-with-args 'org-export-before-processing-hook backend)
2917 (org-export-expand-include-keyword)
2918 ;; Update macro templates since #+INCLUDE keywords might have
2919 ;; added some new ones.
2920 (org-macro-initialize-templates)
2921 (org-macro-replace-all org-macro-templates)
2922 (org-export-execute-babel-code)
2923 ;; Update radio targets since keyword inclusion might have
2924 ;; added some more.
2925 (org-update-radio-target-regexp)
2926 ;; Run last hook with current back-end as argument.
2927 (goto-char (point-min))
2928 (save-excursion
2929 (run-hook-with-args 'org-export-before-parsing-hook backend))
2930 ;; Update communication channel with environment. Also
2931 ;; install user's and developer's filters.
2932 (setq info
2933 (org-export-install-filters
2934 (org-combine-plists
2935 info (org-export-get-environment backend subtreep ext-plist))))
2936 ;; Expand export-specific set of macros: {{{author}}},
2937 ;; {{{date}}}, {{{email}}} and {{{title}}}. It must be done
2938 ;; once regular macros have been expanded, since document
2939 ;; keywords may contain one of them.
2940 (org-macro-replace-all
2941 (list (cons "author"
2942 (org-element-interpret-data (plist-get info :author)))
2943 (cons "date"
2944 (org-element-interpret-data (plist-get info :date)))
2945 ;; EMAIL is not a parsed keyword: store it as-is.
2946 (cons "email" (or (plist-get info :email) ""))
2947 (cons "title"
2948 (org-element-interpret-data (plist-get info :title)))))
2949 ;; Call options filters and update export options. We do not
2950 ;; use `org-export-filter-apply-functions' here since the
2951 ;; arity of such filters is different.
2952 (dolist (filter (plist-get info :filter-options))
2953 (let ((result (funcall filter info backend)))
2954 (when result (setq info result))))
2955 ;; Parse buffer and call parse-tree filter on it.
2956 (setq tree
2957 (org-export-filter-apply-functions
2958 (plist-get info :filter-parse-tree)
2959 (org-element-parse-buffer nil visible-only) info))
2960 ;; Now tree is complete, compute its properties and add them
2961 ;; to communication channel.
2962 (setq info
2963 (org-combine-plists
2964 info (org-export-collect-tree-properties tree info)))
2965 ;; Eventually transcode TREE. Wrap the resulting string into
2966 ;; a template.
2967 (let* ((body (org-element-normalize-string
2968 (or (org-export-data tree info) "")))
2969 (inner-template (cdr (assq 'inner-template
2970 (plist-get info :translate-alist))))
2971 (full-body (if (not (functionp inner-template)) body
2972 (funcall inner-template body info)))
2973 (template (cdr (assq 'template
2974 (plist-get info :translate-alist)))))
2975 ;; Remove all text properties since they cannot be
2976 ;; retrieved from an external process. Finally call
2977 ;; final-output filter and return result.
2978 (org-no-properties
2979 (org-export-filter-apply-functions
2980 (plist-get info :filter-final-output)
2981 (if (or (not (functionp template)) body-only) full-body
2982 (funcall template full-body info))
2983 info))))))))
2985 ;;;###autoload
2986 (defun org-export-to-buffer
2987 (backend buffer &optional subtreep visible-only body-only ext-plist)
2988 "Call `org-export-as' with output to a specified buffer.
2990 BACKEND is the back-end used for transcoding, as a symbol.
2992 BUFFER is the output buffer. If it already exists, it will be
2993 erased first, otherwise, it will be created.
2995 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
2996 EXT-PLIST are similar to those used in `org-export-as', which
2997 see.
2999 Depending on `org-export-copy-to-kill-ring', add buffer contents
3000 to kill ring. Return buffer."
3001 (let ((out (org-export-as backend subtreep visible-only body-only ext-plist))
3002 (buffer (get-buffer-create buffer)))
3003 (with-current-buffer buffer
3004 (erase-buffer)
3005 (insert out)
3006 (goto-char (point-min)))
3007 ;; Maybe add buffer contents to kill ring.
3008 (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p out))
3009 (org-kill-new out))
3010 ;; Return buffer.
3011 buffer))
3013 ;;;###autoload
3014 (defun org-export-to-file
3015 (backend file &optional subtreep visible-only body-only ext-plist)
3016 "Call `org-export-as' with output to a specified file.
3018 BACKEND is the back-end used for transcoding, as a symbol. FILE
3019 is the name of the output file, as a string.
3021 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
3022 EXT-PLIST are similar to those used in `org-export-as', which
3023 see.
3025 Depending on `org-export-copy-to-kill-ring', add file contents
3026 to kill ring. Return output file's name."
3027 ;; Checks for FILE permissions. `write-file' would do the same, but
3028 ;; we'd rather avoid needless transcoding of parse tree.
3029 (unless (file-writable-p file) (error "Output file not writable"))
3030 ;; Insert contents to a temporary buffer and write it to FILE.
3031 (let ((out (org-export-as backend subtreep visible-only body-only ext-plist)))
3032 (with-temp-buffer
3033 (insert out)
3034 (let ((coding-system-for-write org-export-coding-system))
3035 (write-file file)))
3036 ;; Maybe add file contents to kill ring.
3037 (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p out))
3038 (org-kill-new out)))
3039 ;; Return full path.
3040 file)
3042 ;;;###autoload
3043 (defun org-export-string-as (string backend &optional body-only ext-plist)
3044 "Transcode STRING into BACKEND code.
3046 When optional argument BODY-ONLY is non-nil, only return body
3047 code, without preamble nor postamble.
3049 Optional argument EXT-PLIST, when provided, is a property list
3050 with external parameters overriding Org default settings, but
3051 still inferior to file-local settings.
3053 Return code as a string."
3054 (with-temp-buffer
3055 (insert string)
3056 (let ((org-inhibit-startup t)) (org-mode))
3057 (org-export-as backend nil nil body-only ext-plist)))
3059 ;;;###autoload
3060 (defun org-export-insert-default-template (&optional backend subtreep)
3061 "Insert all export keywords with default values at beginning of line.
3063 BACKEND is a symbol representing the export back-end for which
3064 specific export options should be added to the template, or
3065 `default' for default template. When it is nil, the user will be
3066 prompted for a category.
3068 If SUBTREEP is non-nil, export configuration will be set up
3069 locally for the subtree through node properties."
3070 (interactive)
3071 (unless (derived-mode-p 'org-mode) (user-error "Not in an Org mode buffer"))
3072 (when (and subtreep (org-before-first-heading-p))
3073 (user-error "No subtree to set export options for"))
3074 (let ((node (and subtreep (save-excursion (org-back-to-heading t) (point))))
3075 (backend (or backend
3076 (intern
3077 (org-completing-read
3078 "Options category: "
3079 (cons "default"
3080 (mapcar (lambda (b) (symbol-name (car b)))
3081 org-export-registered-backends))))))
3082 options keywords)
3083 ;; Populate OPTIONS and KEYWORDS.
3084 (dolist (entry (if (eq backend 'default) org-export-options-alist
3085 (org-export-backend-options backend)))
3086 (let ((keyword (nth 1 entry))
3087 (option (nth 2 entry)))
3088 (cond
3089 (keyword (unless (assoc keyword keywords)
3090 (let ((value
3091 (if (eq (nth 4 entry) 'split)
3092 (mapconcat 'identity (eval (nth 3 entry)) " ")
3093 (eval (nth 3 entry)))))
3094 (push (cons keyword value) keywords))))
3095 (option (unless (assoc option options)
3096 (push (cons option (eval (nth 3 entry))) options))))))
3097 ;; Move to an appropriate location in order to insert options.
3098 (unless subtreep (beginning-of-line))
3099 ;; First get TITLE, DATE, AUTHOR and EMAIL if they belong to the
3100 ;; list of available keywords.
3101 (when (assoc "TITLE" keywords)
3102 (let ((title
3103 (or (let ((visited-file (buffer-file-name (buffer-base-buffer))))
3104 (and visited-file
3105 (file-name-sans-extension
3106 (file-name-nondirectory visited-file))))
3107 (buffer-name (buffer-base-buffer)))))
3108 (if (not subtreep) (insert (format "#+TITLE: %s\n" title))
3109 (org-entry-put node "EXPORT_TITLE" title))))
3110 (when (assoc "DATE" keywords)
3111 (let ((date (with-temp-buffer (org-insert-time-stamp (current-time)))))
3112 (if (not subtreep) (insert "#+DATE: " date "\n")
3113 (org-entry-put node "EXPORT_DATE" date))))
3114 (when (assoc "AUTHOR" keywords)
3115 (let ((author (cdr (assoc "AUTHOR" keywords))))
3116 (if subtreep (org-entry-put node "EXPORT_AUTHOR" author)
3117 (insert
3118 (format "#+AUTHOR:%s\n"
3119 (if (not (org-string-nw-p author)) ""
3120 (concat " " author)))))))
3121 (when (assoc "EMAIL" keywords)
3122 (let ((email (cdr (assoc "EMAIL" keywords))))
3123 (if subtreep (org-entry-put node "EXPORT_EMAIL" email)
3124 (insert
3125 (format "#+EMAIL:%s\n"
3126 (if (not (org-string-nw-p email)) ""
3127 (concat " " email)))))))
3128 ;; Then (multiple) OPTIONS lines. Never go past fill-column.
3129 (when options
3130 (let ((items
3131 (mapcar
3132 (lambda (opt)
3133 (format "%s:%s" (car opt) (format "%s" (cdr opt))))
3134 (sort options (lambda (k1 k2) (string< (car k1) (car k2)))))))
3135 (if subtreep
3136 (org-entry-put
3137 node "EXPORT_OPTIONS" (mapconcat 'identity items " "))
3138 (while items
3139 (insert "#+OPTIONS:")
3140 (let ((width 10))
3141 (while (and items
3142 (< (+ width (length (car items)) 1) fill-column))
3143 (let ((item (pop items)))
3144 (insert " " item)
3145 (incf width (1+ (length item))))))
3146 (insert "\n")))))
3147 ;; And the rest of keywords.
3148 (dolist (key (sort keywords (lambda (k1 k2) (string< (car k1) (car k2)))))
3149 (unless (member (car key) '("TITLE" "DATE" "AUTHOR" "EMAIL"))
3150 (let ((val (cdr key)))
3151 (if subtreep (org-entry-put node (concat "EXPORT_" (car key)) val)
3152 (insert
3153 (format "#+%s:%s\n"
3154 (car key)
3155 (if (org-string-nw-p val) (format " %s" val) "")))))))))
3157 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
3158 "Return output file's name according to buffer specifications.
3160 EXTENSION is a string representing the output file extension,
3161 with the leading dot.
3163 With a non-nil optional argument SUBTREEP, try to determine
3164 output file's name by looking for \"EXPORT_FILE_NAME\" property
3165 of subtree at point.
3167 When optional argument PUB-DIR is set, use it as the publishing
3168 directory.
3170 When optional argument VISIBLE-ONLY is non-nil, don't export
3171 contents of hidden elements.
3173 Return file name as a string."
3174 (let* ((visited-file (buffer-file-name (buffer-base-buffer)))
3175 (base-name
3176 ;; File name may come from EXPORT_FILE_NAME subtree
3177 ;; property, assuming point is at beginning of said
3178 ;; sub-tree.
3179 (file-name-sans-extension
3180 (or (and subtreep
3181 (org-entry-get
3182 (save-excursion
3183 (ignore-errors (org-back-to-heading) (point)))
3184 "EXPORT_FILE_NAME" t))
3185 ;; File name may be extracted from buffer's associated
3186 ;; file, if any.
3187 (and visited-file (file-name-nondirectory visited-file))
3188 ;; Can't determine file name on our own: Ask user.
3189 (let ((read-file-name-function
3190 (and org-completion-use-ido 'ido-read-file-name)))
3191 (read-file-name
3192 "Output file: " pub-dir nil nil nil
3193 (lambda (name)
3194 (string= (file-name-extension name t) extension)))))))
3195 (output-file
3196 ;; Build file name. Enforce EXTENSION over whatever user
3197 ;; may have come up with. PUB-DIR, if defined, always has
3198 ;; precedence over any provided path.
3199 (cond
3200 (pub-dir
3201 (concat (file-name-as-directory pub-dir)
3202 (file-name-nondirectory base-name)
3203 extension))
3204 ((file-name-absolute-p base-name) (concat base-name extension))
3205 (t (concat (file-name-as-directory ".") base-name extension)))))
3206 ;; If writing to OUTPUT-FILE would overwrite original file, append
3207 ;; EXTENSION another time to final name.
3208 (if (and visited-file (org-file-equal-p visited-file output-file))
3209 (concat output-file extension)
3210 output-file)))
3212 (defun org-export-expand-include-keyword (&optional included dir)
3213 "Expand every include keyword in buffer.
3214 Optional argument INCLUDED is a list of included file names along
3215 with their line restriction, when appropriate. It is used to
3216 avoid infinite recursion. Optional argument DIR is the current
3217 working directory. It is used to properly resolve relative
3218 paths."
3219 (let ((case-fold-search t))
3220 (goto-char (point-min))
3221 (while (re-search-forward "^[ \t]*#\\+INCLUDE: +\\(.*\\)[ \t]*$" nil t)
3222 (when (eq (org-element-type (save-match-data (org-element-at-point)))
3223 'keyword)
3224 (beginning-of-line)
3225 ;; Extract arguments from keyword's value.
3226 (let* ((value (match-string 1))
3227 (ind (org-get-indentation))
3228 (file (and (string-match "^\"\\(\\S-+\\)\"" value)
3229 (prog1 (expand-file-name (match-string 1 value) dir)
3230 (setq value (replace-match "" nil nil value)))))
3231 (lines
3232 (and (string-match
3233 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\"" value)
3234 (prog1 (match-string 1 value)
3235 (setq value (replace-match "" nil nil value)))))
3236 (env (cond ((string-match "\\<example\\>" value) 'example)
3237 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
3238 (match-string 1 value))))
3239 ;; Minimal level of included file defaults to the child
3240 ;; level of the current headline, if any, or one. It
3241 ;; only applies is the file is meant to be included as
3242 ;; an Org one.
3243 (minlevel
3244 (and (not env)
3245 (if (string-match ":minlevel +\\([0-9]+\\)" value)
3246 (prog1 (string-to-number (match-string 1 value))
3247 (setq value (replace-match "" nil nil value)))
3248 (let ((cur (org-current-level)))
3249 (if cur (1+ (org-reduced-level cur)) 1))))))
3250 ;; Remove keyword.
3251 (delete-region (point) (progn (forward-line) (point)))
3252 (cond
3253 ((not file) (error "Invalid syntax in INCLUDE keyword"))
3254 ((not (file-readable-p file)) (error "Cannot include file %s" file))
3255 ;; Check if files has already been parsed. Look after
3256 ;; inclusion lines too, as different parts of the same file
3257 ;; can be included too.
3258 ((member (list file lines) included)
3259 (error "Recursive file inclusion: %s" file))
3261 (cond
3262 ((eq env 'example)
3263 (insert
3264 (let ((ind-str (make-string ind ? ))
3265 (contents
3266 (org-escape-code-in-string
3267 (org-export--prepare-file-contents file lines))))
3268 (format "%s#+BEGIN_EXAMPLE\n%s%s#+END_EXAMPLE\n"
3269 ind-str contents ind-str))))
3270 ((stringp env)
3271 (insert
3272 (let ((ind-str (make-string ind ? ))
3273 (contents
3274 (org-escape-code-in-string
3275 (org-export--prepare-file-contents file lines))))
3276 (format "%s#+BEGIN_SRC %s\n%s%s#+END_SRC\n"
3277 ind-str env contents ind-str))))
3279 (insert
3280 (with-temp-buffer
3281 (let ((org-inhibit-startup t)) (org-mode))
3282 (insert
3283 (org-export--prepare-file-contents file lines ind minlevel))
3284 (org-export-expand-include-keyword
3285 (cons (list file lines) included)
3286 (file-name-directory file))
3287 (buffer-string))))))))))))
3289 (defun org-export--prepare-file-contents (file &optional lines ind minlevel)
3290 "Prepare the contents of FILE for inclusion and return them as a string.
3292 When optional argument LINES is a string specifying a range of
3293 lines, include only those lines.
3295 Optional argument IND, when non-nil, is an integer specifying the
3296 global indentation of returned contents. Since its purpose is to
3297 allow an included file to stay in the same environment it was
3298 created \(i.e. a list item), it doesn't apply past the first
3299 headline encountered.
3301 Optional argument MINLEVEL, when non-nil, is an integer
3302 specifying the level that any top-level headline in the included
3303 file should have."
3304 (with-temp-buffer
3305 (insert-file-contents file)
3306 (when lines
3307 (let* ((lines (split-string lines "-"))
3308 (lbeg (string-to-number (car lines)))
3309 (lend (string-to-number (cadr lines)))
3310 (beg (if (zerop lbeg) (point-min)
3311 (goto-char (point-min))
3312 (forward-line (1- lbeg))
3313 (point)))
3314 (end (if (zerop lend) (point-max)
3315 (goto-char (point-min))
3316 (forward-line (1- lend))
3317 (point))))
3318 (narrow-to-region beg end)))
3319 ;; Remove blank lines at beginning and end of contents. The logic
3320 ;; behind that removal is that blank lines around include keyword
3321 ;; override blank lines in included file.
3322 (goto-char (point-min))
3323 (org-skip-whitespace)
3324 (beginning-of-line)
3325 (delete-region (point-min) (point))
3326 (goto-char (point-max))
3327 (skip-chars-backward " \r\t\n")
3328 (forward-line)
3329 (delete-region (point) (point-max))
3330 ;; If IND is set, preserve indentation of include keyword until
3331 ;; the first headline encountered.
3332 (when ind
3333 (unless (eq major-mode 'org-mode)
3334 (let ((org-inhibit-startup t)) (org-mode)))
3335 (goto-char (point-min))
3336 (let ((ind-str (make-string ind ? )))
3337 (while (not (or (eobp) (looking-at org-outline-regexp-bol)))
3338 ;; Do not move footnote definitions out of column 0.
3339 (unless (and (looking-at org-footnote-definition-re)
3340 (eq (org-element-type (org-element-at-point))
3341 'footnote-definition))
3342 (insert ind-str))
3343 (forward-line))))
3344 ;; When MINLEVEL is specified, compute minimal level for headlines
3345 ;; in the file (CUR-MIN), and remove stars to each headline so
3346 ;; that headlines with minimal level have a level of MINLEVEL.
3347 (when minlevel
3348 (unless (eq major-mode 'org-mode)
3349 (let ((org-inhibit-startup t)) (org-mode)))
3350 (org-with-limited-levels
3351 (let ((levels (org-map-entries
3352 (lambda () (org-reduced-level (org-current-level))))))
3353 (when levels
3354 (let ((offset (- minlevel (apply 'min levels))))
3355 (unless (zerop offset)
3356 (when org-odd-levels-only (setq offset (* offset 2)))
3357 ;; Only change stars, don't bother moving whole
3358 ;; sections.
3359 (org-map-entries
3360 (lambda () (if (< offset 0) (delete-char (abs offset))
3361 (insert (make-string offset ?*)))))))))))
3362 (org-element-normalize-string (buffer-string))))
3364 (defun org-export-execute-babel-code ()
3365 "Execute every Babel code in the visible part of current buffer."
3366 ;; Get a pristine copy of current buffer so Babel references can be
3367 ;; properly resolved.
3368 (let ((reference (org-export-copy-buffer)))
3369 (unwind-protect (let ((org-current-export-file reference))
3370 (org-babel-exp-process-buffer))
3371 (kill-buffer reference))))
3373 (defun org-export--copy-to-kill-ring-p ()
3374 "Return a non-nil value when output should be added to the kill ring.
3375 See also `org-export-copy-to-kill-ring'."
3376 (if (eq org-export-copy-to-kill-ring 'if-interactive)
3377 (not (or executing-kbd-macro noninteractive))
3378 (eq org-export-copy-to-kill-ring t)))
3382 ;;; Tools For Back-Ends
3384 ;; A whole set of tools is available to help build new exporters. Any
3385 ;; function general enough to have its use across many back-ends
3386 ;; should be added here.
3388 ;;;; For Affiliated Keywords
3390 ;; `org-export-read-attribute' reads a property from a given element
3391 ;; as a plist. It can be used to normalize affiliated keywords'
3392 ;; syntax.
3394 ;; Since captions can span over multiple lines and accept dual values,
3395 ;; their internal representation is a bit tricky. Therefore,
3396 ;; `org-export-get-caption' transparently returns a given element's
3397 ;; caption as a secondary string.
3399 (defun org-export-read-attribute (attribute element &optional property)
3400 "Turn ATTRIBUTE property from ELEMENT into a plist.
3402 When optional argument PROPERTY is non-nil, return the value of
3403 that property within attributes.
3405 This function assumes attributes are defined as \":keyword
3406 value\" pairs. It is appropriate for `:attr_html' like
3407 properties. All values will become strings except the empty
3408 string and \"nil\", which will become nil."
3409 (let ((attributes
3410 (let ((value (org-element-property attribute element)))
3411 (when value
3412 (let ((s (mapconcat 'identity value " ")) result)
3413 (while (string-match
3414 "\\(?:^\\|[ \t]+\\)\\(:[-a-zA-Z0-9_]+\\)\\([ \t]+\\|$\\)"
3416 (let ((value (substring s 0 (match-beginning 0))))
3417 (push (and (not (member value '("nil" ""))) value) result))
3418 (push (intern (match-string 1 s)) result)
3419 (setq s (substring s (match-end 0))))
3420 ;; Ignore any string before the first property with `cdr'.
3421 (cdr (nreverse (cons (and (org-string-nw-p s)
3422 (not (equal s "nil"))
3424 result))))))))
3425 (if property (plist-get attributes property) attributes)))
3427 (defun org-export-get-caption (element &optional shortp)
3428 "Return caption from ELEMENT as a secondary string.
3430 When optional argument SHORTP is non-nil, return short caption,
3431 as a secondary string, instead.
3433 Caption lines are separated by a white space."
3434 (let ((full-caption (org-element-property :caption element)) caption)
3435 (dolist (line full-caption (cdr caption))
3436 (let ((cap (funcall (if shortp 'cdr 'car) line)))
3437 (when cap
3438 (setq caption (nconc (list " ") (copy-sequence cap) caption)))))))
3441 ;;;; For Derived Back-ends
3443 ;; `org-export-with-backend' is a function allowing to locally use
3444 ;; another back-end to transcode some object or element. In a derived
3445 ;; back-end, it may be used as a fall-back function once all specific
3446 ;; cases have been treated.
3448 (defun org-export-with-backend (back-end data &optional contents info)
3449 "Call a transcoder from BACK-END on DATA.
3450 CONTENTS, when non-nil, is the transcoded contents of DATA
3451 element, as a string. INFO, when non-nil, is the communication
3452 channel used for export, as a plist.."
3453 (org-export-barf-if-invalid-backend back-end)
3454 (let ((type (org-element-type data)))
3455 (if (memq type '(nil org-data)) (error "No foreign transcoder available")
3456 (let ((transcoder
3457 (cdr (assq type (org-export-backend-translate-table back-end)))))
3458 (if (functionp transcoder) (funcall transcoder data contents info)
3459 (error "No foreign transcoder available"))))))
3462 ;;;; For Export Snippets
3464 ;; Every export snippet is transmitted to the back-end. Though, the
3465 ;; latter will only retain one type of export-snippet, ignoring
3466 ;; others, based on the former's target back-end. The function
3467 ;; `org-export-snippet-backend' returns that back-end for a given
3468 ;; export-snippet.
3470 (defun org-export-snippet-backend (export-snippet)
3471 "Return EXPORT-SNIPPET targeted back-end as a symbol.
3472 Translation, with `org-export-snippet-translation-alist', is
3473 applied."
3474 (let ((back-end (org-element-property :back-end export-snippet)))
3475 (intern
3476 (or (cdr (assoc back-end org-export-snippet-translation-alist))
3477 back-end))))
3480 ;;;; For Footnotes
3482 ;; `org-export-collect-footnote-definitions' is a tool to list
3483 ;; actually used footnotes definitions in the whole parse tree, or in
3484 ;; a headline, in order to add footnote listings throughout the
3485 ;; transcoded data.
3487 ;; `org-export-footnote-first-reference-p' is a predicate used by some
3488 ;; back-ends, when they need to attach the footnote definition only to
3489 ;; the first occurrence of the corresponding label.
3491 ;; `org-export-get-footnote-definition' and
3492 ;; `org-export-get-footnote-number' provide easier access to
3493 ;; additional information relative to a footnote reference.
3495 (defun org-export-collect-footnote-definitions (data info)
3496 "Return an alist between footnote numbers, labels and definitions.
3498 DATA is the parse tree from which definitions are collected.
3499 INFO is the plist used as a communication channel.
3501 Definitions are sorted by order of references. They either
3502 appear as Org data or as a secondary string for inlined
3503 footnotes. Unreferenced definitions are ignored."
3504 (let* (num-alist
3505 collect-fn ; for byte-compiler.
3506 (collect-fn
3507 (function
3508 (lambda (data)
3509 ;; Collect footnote number, label and definition in DATA.
3510 (org-element-map data 'footnote-reference
3511 (lambda (fn)
3512 (when (org-export-footnote-first-reference-p fn info)
3513 (let ((def (org-export-get-footnote-definition fn info)))
3514 (push
3515 (list (org-export-get-footnote-number fn info)
3516 (org-element-property :label fn)
3517 def)
3518 num-alist)
3519 ;; Also search in definition for nested footnotes.
3520 (when (eq (org-element-property :type fn) 'standard)
3521 (funcall collect-fn def)))))
3522 ;; Don't enter footnote definitions since it will happen
3523 ;; when their first reference is found.
3524 info nil 'footnote-definition)))))
3525 (funcall collect-fn (plist-get info :parse-tree))
3526 (reverse num-alist)))
3528 (defun org-export-footnote-first-reference-p (footnote-reference info)
3529 "Non-nil when a footnote reference is the first one for its label.
3531 FOOTNOTE-REFERENCE is the footnote reference being considered.
3532 INFO is the plist used as a communication channel."
3533 (let ((label (org-element-property :label footnote-reference)))
3534 ;; Anonymous footnotes are always a first reference.
3535 (if (not label) t
3536 ;; Otherwise, return the first footnote with the same LABEL and
3537 ;; test if it is equal to FOOTNOTE-REFERENCE.
3538 (let* (search-refs ; for byte-compiler.
3539 (search-refs
3540 (function
3541 (lambda (data)
3542 (org-element-map data 'footnote-reference
3543 (lambda (fn)
3544 (cond
3545 ((string= (org-element-property :label fn) label)
3546 (throw 'exit fn))
3547 ;; If FN isn't inlined, be sure to traverse its
3548 ;; definition before resuming search. See
3549 ;; comments in `org-export-get-footnote-number'
3550 ;; for more information.
3551 ((eq (org-element-property :type fn) 'standard)
3552 (funcall search-refs
3553 (org-export-get-footnote-definition fn info)))))
3554 ;; Don't enter footnote definitions since it will
3555 ;; happen when their first reference is found.
3556 info 'first-match 'footnote-definition)))))
3557 (eq (catch 'exit (funcall search-refs (plist-get info :parse-tree)))
3558 footnote-reference)))))
3560 (defun org-export-get-footnote-definition (footnote-reference info)
3561 "Return definition of FOOTNOTE-REFERENCE as parsed data.
3562 INFO is the plist used as a communication channel. If no such
3563 definition can be found, return the \"DEFINITION NOT FOUND\"
3564 string."
3565 (let ((label (org-element-property :label footnote-reference)))
3566 (or (org-element-property :inline-definition footnote-reference)
3567 (cdr (assoc label (plist-get info :footnote-definition-alist)))
3568 "DEFINITION NOT FOUND.")))
3570 (defun org-export-get-footnote-number (footnote info)
3571 "Return number associated to a footnote.
3573 FOOTNOTE is either a footnote reference or a footnote definition.
3574 INFO is the plist used as a communication channel."
3575 (let* ((label (org-element-property :label footnote))
3576 seen-refs
3577 search-ref ; For byte-compiler.
3578 (search-ref
3579 (function
3580 (lambda (data)
3581 ;; Search footnote references through DATA, filling
3582 ;; SEEN-REFS along the way.
3583 (org-element-map data 'footnote-reference
3584 (lambda (fn)
3585 (let ((fn-lbl (org-element-property :label fn)))
3586 (cond
3587 ;; Anonymous footnote match: return number.
3588 ((and (not fn-lbl) (eq fn footnote))
3589 (throw 'exit (1+ (length seen-refs))))
3590 ;; Labels match: return number.
3591 ((and label (string= label fn-lbl))
3592 (throw 'exit (1+ (length seen-refs))))
3593 ;; Anonymous footnote: it's always a new one.
3594 ;; Also, be sure to return nil from the `cond' so
3595 ;; `first-match' doesn't get us out of the loop.
3596 ((not fn-lbl) (push 'inline seen-refs) nil)
3597 ;; Label not seen so far: add it so SEEN-REFS.
3599 ;; Also search for subsequent references in
3600 ;; footnote definition so numbering follows
3601 ;; reading logic. Note that we don't have to care
3602 ;; about inline definitions, since
3603 ;; `org-element-map' already traverses them at the
3604 ;; right time.
3606 ;; Once again, return nil to stay in the loop.
3607 ((not (member fn-lbl seen-refs))
3608 (push fn-lbl seen-refs)
3609 (funcall search-ref
3610 (org-export-get-footnote-definition fn info))
3611 nil))))
3612 ;; Don't enter footnote definitions since it will
3613 ;; happen when their first reference is found.
3614 info 'first-match 'footnote-definition)))))
3615 (catch 'exit (funcall search-ref (plist-get info :parse-tree)))))
3618 ;;;; For Headlines
3620 ;; `org-export-get-relative-level' is a shortcut to get headline
3621 ;; level, relatively to the lower headline level in the parsed tree.
3623 ;; `org-export-get-headline-number' returns the section number of an
3624 ;; headline, while `org-export-number-to-roman' allows to convert it
3625 ;; to roman numbers.
3627 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
3628 ;; `org-export-last-sibling-p' are three useful predicates when it
3629 ;; comes to fulfill the `:headline-levels' property.
3631 ;; `org-export-get-tags', `org-export-get-category' and
3632 ;; `org-export-get-node-property' extract useful information from an
3633 ;; headline or a parent headline. They all handle inheritance.
3635 ;; `org-export-get-alt-title' tries to retrieve an alternative title,
3636 ;; as a secondary string, suitable for table of contents. It falls
3637 ;; back onto default title.
3639 (defun org-export-get-relative-level (headline info)
3640 "Return HEADLINE relative level within current parsed tree.
3641 INFO is a plist holding contextual information."
3642 (+ (org-element-property :level headline)
3643 (or (plist-get info :headline-offset) 0)))
3645 (defun org-export-low-level-p (headline info)
3646 "Non-nil when HEADLINE is considered as low level.
3648 INFO is a plist used as a communication channel.
3650 A low level headlines has a relative level greater than
3651 `:headline-levels' property value.
3653 Return value is the difference between HEADLINE relative level
3654 and the last level being considered as high enough, or nil."
3655 (let ((limit (plist-get info :headline-levels)))
3656 (when (wholenump limit)
3657 (let ((level (org-export-get-relative-level headline info)))
3658 (and (> level limit) (- level limit))))))
3660 (defun org-export-get-headline-number (headline info)
3661 "Return HEADLINE numbering as a list of numbers.
3662 INFO is a plist holding contextual information."
3663 (cdr (assoc headline (plist-get info :headline-numbering))))
3665 (defun org-export-numbered-headline-p (headline info)
3666 "Return a non-nil value if HEADLINE element should be numbered.
3667 INFO is a plist used as a communication channel."
3668 (let ((sec-num (plist-get info :section-numbers))
3669 (level (org-export-get-relative-level headline info)))
3670 (if (wholenump sec-num) (<= level sec-num) sec-num)))
3672 (defun org-export-number-to-roman (n)
3673 "Convert integer N into a roman numeral."
3674 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
3675 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
3676 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
3677 ( 1 . "I")))
3678 (res ""))
3679 (if (<= n 0)
3680 (number-to-string n)
3681 (while roman
3682 (if (>= n (caar roman))
3683 (setq n (- n (caar roman))
3684 res (concat res (cdar roman)))
3685 (pop roman)))
3686 res)))
3688 (defun org-export-get-tags (element info &optional tags inherited)
3689 "Return list of tags associated to ELEMENT.
3691 ELEMENT has either an `headline' or an `inlinetask' type. INFO
3692 is a plist used as a communication channel.
3694 Select tags (see `org-export-select-tags') and exclude tags (see
3695 `org-export-exclude-tags') are removed from the list.
3697 When non-nil, optional argument TAGS should be a list of strings.
3698 Any tag belonging to this list will also be removed.
3700 When optional argument INHERITED is non-nil, tags can also be
3701 inherited from parent headlines and FILETAGS keywords."
3702 (org-remove-if
3703 (lambda (tag) (or (member tag (plist-get info :select-tags))
3704 (member tag (plist-get info :exclude-tags))
3705 (member tag tags)))
3706 (if (not inherited) (org-element-property :tags element)
3707 ;; Build complete list of inherited tags.
3708 (let ((current-tag-list (org-element-property :tags element)))
3709 (mapc
3710 (lambda (parent)
3711 (mapc
3712 (lambda (tag)
3713 (when (and (memq (org-element-type parent) '(headline inlinetask))
3714 (not (member tag current-tag-list)))
3715 (push tag current-tag-list)))
3716 (org-element-property :tags parent)))
3717 (org-export-get-genealogy element))
3718 ;; Add FILETAGS keywords and return results.
3719 (org-uniquify (append (plist-get info :filetags) current-tag-list))))))
3721 (defun org-export-get-node-property (property blob &optional inherited)
3722 "Return node PROPERTY value for BLOB.
3724 PROPERTY is an upcase symbol (i.e. `:COOKIE_DATA'). BLOB is an
3725 element or object.
3727 If optional argument INHERITED is non-nil, the value can be
3728 inherited from a parent headline.
3730 Return value is a string or nil."
3731 (let ((headline (if (eq (org-element-type blob) 'headline) blob
3732 (org-export-get-parent-headline blob))))
3733 (if (not inherited) (org-element-property property blob)
3734 (let ((parent headline) value)
3735 (catch 'found
3736 (while parent
3737 (when (plist-member (nth 1 parent) property)
3738 (throw 'found (org-element-property property parent)))
3739 (setq parent (org-element-property :parent parent))))))))
3741 (defun org-export-get-category (blob info)
3742 "Return category for element or object BLOB.
3744 INFO is a plist used as a communication channel.
3746 CATEGORY is automatically inherited from a parent headline, from
3747 #+CATEGORY: keyword or created out of original file name. If all
3748 fail, the fall-back value is \"???\"."
3749 (or (let ((headline (if (eq (org-element-type blob) 'headline) blob
3750 (org-export-get-parent-headline blob))))
3751 ;; Almost like `org-export-node-property', but we cannot trust
3752 ;; `plist-member' as every headline has a `:CATEGORY'
3753 ;; property, would it be nil or equal to "???" (which has the
3754 ;; same meaning).
3755 (let ((parent headline) value)
3756 (catch 'found
3757 (while parent
3758 (let ((category (org-element-property :CATEGORY parent)))
3759 (and category (not (equal "???" category))
3760 (throw 'found category)))
3761 (setq parent (org-element-property :parent parent))))))
3762 (org-element-map (plist-get info :parse-tree) 'keyword
3763 (lambda (kwd)
3764 (when (equal (org-element-property :key kwd) "CATEGORY")
3765 (org-element-property :value kwd)))
3766 info 'first-match)
3767 (let ((file (plist-get info :input-file)))
3768 (and file (file-name-sans-extension (file-name-nondirectory file))))
3769 "???"))
3771 (defun org-export-get-alt-title (headline info)
3772 "Return alternative title for HEADLINE, as a secondary string.
3773 INFO is a plist used as a communication channel. If no optional
3774 title is defined, fall-back to the regular title."
3775 (or (org-element-property :alt-title headline)
3776 (org-element-property :title headline)))
3778 (defun org-export-first-sibling-p (headline info)
3779 "Non-nil when HEADLINE is the first sibling in its sub-tree.
3780 INFO is a plist used as a communication channel."
3781 (not (eq (org-element-type (org-export-get-previous-element headline info))
3782 'headline)))
3784 (defun org-export-last-sibling-p (headline info)
3785 "Non-nil when HEADLINE is the last sibling in its sub-tree.
3786 INFO is a plist used as a communication channel."
3787 (not (org-export-get-next-element headline info)))
3790 ;;;; For Keywords
3792 ;; `org-export-get-date' returns a date appropriate for the document
3793 ;; to about to be exported. In particular, it takes care of
3794 ;; `org-export-date-timestamp-format'.
3796 (defun org-export-get-date (info &optional fmt)
3797 "Return date value for the current document.
3799 INFO is a plist used as a communication channel. FMT, when
3800 non-nil, is a time format string that will be applied on the date
3801 if it consists in a single timestamp object. It defaults to
3802 `org-export-date-timestamp-format' when nil.
3804 A proper date can be a secondary string, a string or nil. It is
3805 meant to be translated with `org-export-data' or alike."
3806 (let ((date (plist-get info :date))
3807 (fmt (or fmt org-export-date-timestamp-format)))
3808 (cond ((not date) nil)
3809 ((and fmt
3810 (not (cdr date))
3811 (eq (org-element-type (car date)) 'timestamp))
3812 (org-timestamp-format (car date) fmt))
3813 (t date))))
3816 ;;;; For Links
3818 ;; `org-export-solidify-link-text' turns a string into a safer version
3819 ;; for links, replacing most non-standard characters with hyphens.
3821 ;; `org-export-get-coderef-format' returns an appropriate format
3822 ;; string for coderefs.
3824 ;; `org-export-inline-image-p' returns a non-nil value when the link
3825 ;; provided should be considered as an inline image.
3827 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
3828 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
3829 ;; returns an appropriate unique identifier when found, or nil.
3831 ;; `org-export-resolve-id-link' returns the first headline with
3832 ;; specified id or custom-id in parse tree, the path to the external
3833 ;; file with the id or nil when neither was found.
3835 ;; `org-export-resolve-coderef' associates a reference to a line
3836 ;; number in the element it belongs, or returns the reference itself
3837 ;; when the element isn't numbered.
3839 (defun org-export-solidify-link-text (s)
3840 "Take link text S and make a safe target out of it."
3841 (save-match-data
3842 (mapconcat 'identity (org-split-string s "[^a-zA-Z0-9_.-:]+") "-")))
3844 (defun org-export-get-coderef-format (path desc)
3845 "Return format string for code reference link.
3846 PATH is the link path. DESC is its description."
3847 (save-match-data
3848 (cond ((not desc) "%s")
3849 ((string-match (regexp-quote (concat "(" path ")")) desc)
3850 (replace-match "%s" t t desc))
3851 (t desc))))
3853 (defun org-export-inline-image-p (link &optional rules)
3854 "Non-nil if LINK object points to an inline image.
3856 Optional argument is a set of RULES defining inline images. It
3857 is an alist where associations have the following shape:
3859 \(TYPE . REGEXP)
3861 Applying a rule means apply REGEXP against LINK's path when its
3862 type is TYPE. The function will return a non-nil value if any of
3863 the provided rules is non-nil. The default rule is
3864 `org-export-default-inline-image-rule'.
3866 This only applies to links without a description."
3867 (and (not (org-element-contents link))
3868 (let ((case-fold-search t)
3869 (rules (or rules org-export-default-inline-image-rule)))
3870 (catch 'exit
3871 (mapc
3872 (lambda (rule)
3873 (and (string= (org-element-property :type link) (car rule))
3874 (string-match (cdr rule)
3875 (org-element-property :path link))
3876 (throw 'exit t)))
3877 rules)
3878 ;; Return nil if no rule matched.
3879 nil))))
3881 (defun org-export-resolve-coderef (ref info)
3882 "Resolve a code reference REF.
3884 INFO is a plist used as a communication channel.
3886 Return associated line number in source code, or REF itself,
3887 depending on src-block or example element's switches."
3888 (org-element-map (plist-get info :parse-tree) '(example-block src-block)
3889 (lambda (el)
3890 (with-temp-buffer
3891 (insert (org-trim (org-element-property :value el)))
3892 (let* ((label-fmt (regexp-quote
3893 (or (org-element-property :label-fmt el)
3894 org-coderef-label-format)))
3895 (ref-re
3896 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
3897 (replace-regexp-in-string "%s" ref label-fmt nil t))))
3898 ;; Element containing REF is found. Resolve it to either
3899 ;; a label or a line number, as needed.
3900 (when (re-search-backward ref-re nil t)
3901 (cond
3902 ((org-element-property :use-labels el) ref)
3903 ((eq (org-element-property :number-lines el) 'continued)
3904 (+ (org-export-get-loc el info) (line-number-at-pos)))
3905 (t (line-number-at-pos)))))))
3906 info 'first-match))
3908 (defun org-export-resolve-fuzzy-link (link info)
3909 "Return LINK destination.
3911 INFO is a plist holding contextual information.
3913 Return value can be an object, an element, or nil:
3915 - If LINK path matches a target object (i.e. <<path>>) return it.
3917 - If LINK path exactly matches the name affiliated keyword
3918 \(i.e. #+NAME: path) of an element, return that element.
3920 - If LINK path exactly matches any headline name, return that
3921 element. If more than one headline share that name, priority
3922 will be given to the one with the closest common ancestor, if
3923 any, or the first one in the parse tree otherwise.
3925 - Otherwise, return nil.
3927 Assume LINK type is \"fuzzy\". White spaces are not
3928 significant."
3929 (let* ((raw-path (org-element-property :path link))
3930 (match-title-p (eq (aref raw-path 0) ?*))
3931 ;; Split PATH at white spaces so matches are space
3932 ;; insensitive.
3933 (path (org-split-string
3934 (if match-title-p (substring raw-path 1) raw-path))))
3935 (cond
3936 ;; First try to find a matching "<<path>>" unless user specified
3937 ;; he was looking for a headline (path starts with a "*"
3938 ;; character).
3939 ((and (not match-title-p)
3940 (org-element-map (plist-get info :parse-tree) 'target
3941 (lambda (blob)
3942 (and (equal (org-split-string (org-element-property :value blob))
3943 path)
3944 blob))
3945 info t)))
3946 ;; Then try to find an element with a matching "#+NAME: path"
3947 ;; affiliated keyword.
3948 ((and (not match-title-p)
3949 (org-element-map (plist-get info :parse-tree)
3950 org-element-all-elements
3951 (lambda (el)
3952 (let ((name (org-element-property :name el)))
3953 (when (and name (equal (org-split-string name) path)) el)))
3954 info 'first-match)))
3955 ;; Last case: link either points to a headline or to nothingness.
3956 ;; Try to find the source, with priority given to headlines with
3957 ;; the closest common ancestor. If such candidate is found,
3958 ;; return it, otherwise return nil.
3960 (let ((find-headline
3961 (function
3962 ;; Return first headline whose `:raw-value' property is
3963 ;; NAME in parse tree DATA, or nil. Statistics cookies
3964 ;; are ignored.
3965 (lambda (name data)
3966 (org-element-map data 'headline
3967 (lambda (headline)
3968 (when (equal (org-split-string
3969 (replace-regexp-in-string
3970 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
3971 (org-element-property :raw-value headline)))
3972 name)
3973 headline))
3974 info 'first-match)))))
3975 ;; Search among headlines sharing an ancestor with link, from
3976 ;; closest to farthest.
3977 (or (catch 'exit
3978 (mapc
3979 (lambda (parent)
3980 (when (eq (org-element-type parent) 'headline)
3981 (let ((foundp (funcall find-headline path parent)))
3982 (when foundp (throw 'exit foundp)))))
3983 (org-export-get-genealogy link)) nil)
3984 ;; No match with a common ancestor: try full parse-tree.
3985 (funcall find-headline path (plist-get info :parse-tree))))))))
3987 (defun org-export-resolve-id-link (link info)
3988 "Return headline referenced as LINK destination.
3990 INFO is a plist used as a communication channel.
3992 Return value can be the headline element matched in current parse
3993 tree, a file name or nil. Assume LINK type is either \"id\" or
3994 \"custom-id\"."
3995 (let ((id (org-element-property :path link)))
3996 ;; First check if id is within the current parse tree.
3997 (or (org-element-map (plist-get info :parse-tree) 'headline
3998 (lambda (headline)
3999 (when (or (string= (org-element-property :ID headline) id)
4000 (string= (org-element-property :CUSTOM_ID headline) id))
4001 headline))
4002 info 'first-match)
4003 ;; Otherwise, look for external files.
4004 (cdr (assoc id (plist-get info :id-alist))))))
4006 (defun org-export-resolve-radio-link (link info)
4007 "Return radio-target object referenced as LINK destination.
4009 INFO is a plist used as a communication channel.
4011 Return value can be a radio-target object or nil. Assume LINK
4012 has type \"radio\"."
4013 (let ((path (org-element-property :path link)))
4014 (org-element-map (plist-get info :parse-tree) 'radio-target
4015 (lambda (radio)
4016 (and (compare-strings
4017 (org-element-property :value radio) 0 nil path 0 nil t)
4018 radio))
4019 info 'first-match)))
4022 ;;;; For References
4024 ;; `org-export-get-ordinal' associates a sequence number to any object
4025 ;; or element.
4027 (defun org-export-get-ordinal (element info &optional types predicate)
4028 "Return ordinal number of an element or object.
4030 ELEMENT is the element or object considered. INFO is the plist
4031 used as a communication channel.
4033 Optional argument TYPES, when non-nil, is a list of element or
4034 object types, as symbols, that should also be counted in.
4035 Otherwise, only provided element's type is considered.
4037 Optional argument PREDICATE is a function returning a non-nil
4038 value if the current element or object should be counted in. It
4039 accepts two arguments: the element or object being considered and
4040 the plist used as a communication channel. This allows to count
4041 only a certain type of objects (i.e. inline images).
4043 Return value is a list of numbers if ELEMENT is a headline or an
4044 item. It is nil for keywords. It represents the footnote number
4045 for footnote definitions and footnote references. If ELEMENT is
4046 a target, return the same value as if ELEMENT was the closest
4047 table, item or headline containing the target. In any other
4048 case, return the sequence number of ELEMENT among elements or
4049 objects of the same type."
4050 ;; Ordinal of a target object refer to the ordinal of the closest
4051 ;; table, item, or headline containing the object.
4052 (when (eq (org-element-type element) 'target)
4053 (setq element
4054 (loop for parent in (org-export-get-genealogy element)
4055 when
4056 (memq
4057 (org-element-type parent)
4058 '(footnote-definition footnote-reference headline item
4059 table))
4060 return parent)))
4061 (case (org-element-type element)
4062 ;; Special case 1: A headline returns its number as a list.
4063 (headline (org-export-get-headline-number element info))
4064 ;; Special case 2: An item returns its number as a list.
4065 (item (let ((struct (org-element-property :structure element)))
4066 (org-list-get-item-number
4067 (org-element-property :begin element)
4068 struct
4069 (org-list-prevs-alist struct)
4070 (org-list-parents-alist struct))))
4071 ((footnote-definition footnote-reference)
4072 (org-export-get-footnote-number element info))
4073 (otherwise
4074 (let ((counter 0))
4075 ;; Increment counter until ELEMENT is found again.
4076 (org-element-map (plist-get info :parse-tree)
4077 (or types (org-element-type element))
4078 (lambda (el)
4079 (cond
4080 ((eq element el) (1+ counter))
4081 ((not predicate) (incf counter) nil)
4082 ((funcall predicate el info) (incf counter) nil)))
4083 info 'first-match)))))
4086 ;;;; For Src-Blocks
4088 ;; `org-export-get-loc' counts number of code lines accumulated in
4089 ;; src-block or example-block elements with a "+n" switch until
4090 ;; a given element, excluded. Note: "-n" switches reset that count.
4092 ;; `org-export-unravel-code' extracts source code (along with a code
4093 ;; references alist) from an `element-block' or `src-block' type
4094 ;; element.
4096 ;; `org-export-format-code' applies a formatting function to each line
4097 ;; of code, providing relative line number and code reference when
4098 ;; appropriate. Since it doesn't access the original element from
4099 ;; which the source code is coming, it expects from the code calling
4100 ;; it to know if lines should be numbered and if code references
4101 ;; should appear.
4103 ;; Eventually, `org-export-format-code-default' is a higher-level
4104 ;; function (it makes use of the two previous functions) which handles
4105 ;; line numbering and code references inclusion, and returns source
4106 ;; code in a format suitable for plain text or verbatim output.
4108 (defun org-export-get-loc (element info)
4109 "Return accumulated lines of code up to ELEMENT.
4111 INFO is the plist used as a communication channel.
4113 ELEMENT is excluded from count."
4114 (let ((loc 0))
4115 (org-element-map (plist-get info :parse-tree)
4116 `(src-block example-block ,(org-element-type element))
4117 (lambda (el)
4118 (cond
4119 ;; ELEMENT is reached: Quit the loop.
4120 ((eq el element))
4121 ;; Only count lines from src-block and example-block elements
4122 ;; with a "+n" or "-n" switch. A "-n" switch resets counter.
4123 ((not (memq (org-element-type el) '(src-block example-block))) nil)
4124 ((let ((linums (org-element-property :number-lines el)))
4125 (when linums
4126 ;; Accumulate locs or reset them.
4127 (let ((lines (org-count-lines
4128 (org-trim (org-element-property :value el)))))
4129 (setq loc (if (eq linums 'new) lines (+ loc lines))))))
4130 ;; Return nil to stay in the loop.
4131 nil)))
4132 info 'first-match)
4133 ;; Return value.
4134 loc))
4136 (defun org-export-unravel-code (element)
4137 "Clean source code and extract references out of it.
4139 ELEMENT has either a `src-block' an `example-block' type.
4141 Return a cons cell whose CAR is the source code, cleaned from any
4142 reference and protective comma and CDR is an alist between
4143 relative line number (integer) and name of code reference on that
4144 line (string)."
4145 (let* ((line 0) refs
4146 ;; Get code and clean it. Remove blank lines at its
4147 ;; beginning and end.
4148 (code (let ((c (replace-regexp-in-string
4149 "\\`\\([ \t]*\n\\)+" ""
4150 (replace-regexp-in-string
4151 "\\([ \t]*\n\\)*[ \t]*\\'" "\n"
4152 (org-element-property :value element)))))
4153 ;; If appropriate, remove global indentation.
4154 (if (or org-src-preserve-indentation
4155 (org-element-property :preserve-indent element))
4157 (org-remove-indentation c))))
4158 ;; Get format used for references.
4159 (label-fmt (regexp-quote
4160 (or (org-element-property :label-fmt element)
4161 org-coderef-label-format)))
4162 ;; Build a regexp matching a loc with a reference.
4163 (with-ref-re
4164 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)[ \t]*\\)$"
4165 (replace-regexp-in-string
4166 "%s" "\\([-a-zA-Z0-9_ ]+\\)" label-fmt nil t))))
4167 ;; Return value.
4168 (cons
4169 ;; Code with references removed.
4170 (org-element-normalize-string
4171 (mapconcat
4172 (lambda (loc)
4173 (incf line)
4174 (if (not (string-match with-ref-re loc)) loc
4175 ;; Ref line: remove ref, and signal its position in REFS.
4176 (push (cons line (match-string 3 loc)) refs)
4177 (replace-match "" nil nil loc 1)))
4178 (org-split-string code "\n") "\n"))
4179 ;; Reference alist.
4180 refs)))
4182 (defun org-export-format-code (code fun &optional num-lines ref-alist)
4183 "Format CODE by applying FUN line-wise and return it.
4185 CODE is a string representing the code to format. FUN is
4186 a function. It must accept three arguments: a line of
4187 code (string), the current line number (integer) or nil and the
4188 reference associated to the current line (string) or nil.
4190 Optional argument NUM-LINES can be an integer representing the
4191 number of code lines accumulated until the current code. Line
4192 numbers passed to FUN will take it into account. If it is nil,
4193 FUN's second argument will always be nil. This number can be
4194 obtained with `org-export-get-loc' function.
4196 Optional argument REF-ALIST can be an alist between relative line
4197 number (i.e. ignoring NUM-LINES) and the name of the code
4198 reference on it. If it is nil, FUN's third argument will always
4199 be nil. It can be obtained through the use of
4200 `org-export-unravel-code' function."
4201 (let ((--locs (org-split-string code "\n"))
4202 (--line 0))
4203 (org-element-normalize-string
4204 (mapconcat
4205 (lambda (--loc)
4206 (incf --line)
4207 (let ((--ref (cdr (assq --line ref-alist))))
4208 (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
4209 --locs "\n"))))
4211 (defun org-export-format-code-default (element info)
4212 "Return source code from ELEMENT, formatted in a standard way.
4214 ELEMENT is either a `src-block' or `example-block' element. INFO
4215 is a plist used as a communication channel.
4217 This function takes care of line numbering and code references
4218 inclusion. Line numbers, when applicable, appear at the
4219 beginning of the line, separated from the code by two white
4220 spaces. Code references, on the other hand, appear flushed to
4221 the right, separated by six white spaces from the widest line of
4222 code."
4223 ;; Extract code and references.
4224 (let* ((code-info (org-export-unravel-code element))
4225 (code (car code-info))
4226 (code-lines (org-split-string code "\n")))
4227 (if (null code-lines) ""
4228 (let* ((refs (and (org-element-property :retain-labels element)
4229 (cdr code-info)))
4230 ;; Handle line numbering.
4231 (num-start (case (org-element-property :number-lines element)
4232 (continued (org-export-get-loc element info))
4233 (new 0)))
4234 (num-fmt
4235 (and num-start
4236 (format "%%%ds "
4237 (length (number-to-string
4238 (+ (length code-lines) num-start))))))
4239 ;; Prepare references display, if required. Any reference
4240 ;; should start six columns after the widest line of code,
4241 ;; wrapped with parenthesis.
4242 (max-width
4243 (+ (apply 'max (mapcar 'length code-lines))
4244 (if (not num-start) 0 (length (format num-fmt num-start))))))
4245 (org-export-format-code
4246 code
4247 (lambda (loc line-num ref)
4248 (let ((number-str (and num-fmt (format num-fmt line-num))))
4249 (concat
4250 number-str
4252 (and ref
4253 (concat (make-string
4254 (- (+ 6 max-width)
4255 (+ (length loc) (length number-str))) ? )
4256 (format "(%s)" ref))))))
4257 num-start refs)))))
4260 ;;;; For Tables
4262 ;; `org-export-table-has-special-column-p' and and
4263 ;; `org-export-table-row-is-special-p' are predicates used to look for
4264 ;; meta-information about the table structure.
4266 ;; `org-table-has-header-p' tells when the rows before the first rule
4267 ;; should be considered as table's header.
4269 ;; `org-export-table-cell-width', `org-export-table-cell-alignment'
4270 ;; and `org-export-table-cell-borders' extract information from
4271 ;; a table-cell element.
4273 ;; `org-export-table-dimensions' gives the number on rows and columns
4274 ;; in the table, ignoring horizontal rules and special columns.
4275 ;; `org-export-table-cell-address', given a table-cell object, returns
4276 ;; the absolute address of a cell. On the other hand,
4277 ;; `org-export-get-table-cell-at' does the contrary.
4279 ;; `org-export-table-cell-starts-colgroup-p',
4280 ;; `org-export-table-cell-ends-colgroup-p',
4281 ;; `org-export-table-row-starts-rowgroup-p',
4282 ;; `org-export-table-row-ends-rowgroup-p',
4283 ;; `org-export-table-row-starts-header-p' and
4284 ;; `org-export-table-row-ends-header-p' indicate position of current
4285 ;; row or cell within the table.
4287 (defun org-export-table-has-special-column-p (table)
4288 "Non-nil when TABLE has a special column.
4289 All special columns will be ignored during export."
4290 ;; The table has a special column when every first cell of every row
4291 ;; has an empty value or contains a symbol among "/", "#", "!", "$",
4292 ;; "*" "_" and "^". Though, do not consider a first row containing
4293 ;; only empty cells as special.
4294 (let ((special-column-p 'empty))
4295 (catch 'exit
4296 (mapc
4297 (lambda (row)
4298 (when (eq (org-element-property :type row) 'standard)
4299 (let ((value (org-element-contents
4300 (car (org-element-contents row)))))
4301 (cond ((member value '(("/") ("#") ("!") ("$") ("*") ("_") ("^")))
4302 (setq special-column-p 'special))
4303 ((not value))
4304 (t (throw 'exit nil))))))
4305 (org-element-contents table))
4306 (eq special-column-p 'special))))
4308 (defun org-export-table-has-header-p (table info)
4309 "Non-nil when TABLE has an header.
4311 INFO is a plist used as a communication channel.
4313 A table has an header when it contains at least two row groups."
4314 (let ((rowgroup 1) row-flag)
4315 (org-element-map table 'table-row
4316 (lambda (row)
4317 (cond
4318 ((> rowgroup 1) t)
4319 ((and row-flag (eq (org-element-property :type row) 'rule))
4320 (incf rowgroup) (setq row-flag nil))
4321 ((and (not row-flag) (eq (org-element-property :type row) 'standard))
4322 (setq row-flag t) nil)))
4323 info)))
4325 (defun org-export-table-row-is-special-p (table-row info)
4326 "Non-nil if TABLE-ROW is considered special.
4328 INFO is a plist used as the communication channel.
4330 All special rows will be ignored during export."
4331 (when (eq (org-element-property :type table-row) 'standard)
4332 (let ((first-cell (org-element-contents
4333 (car (org-element-contents table-row)))))
4334 ;; A row is special either when...
4336 ;; ... it starts with a field only containing "/",
4337 (equal first-cell '("/"))
4338 ;; ... the table contains a special column and the row start
4339 ;; with a marking character among, "^", "_", "$" or "!",
4340 (and (org-export-table-has-special-column-p
4341 (org-export-get-parent table-row))
4342 (member first-cell '(("^") ("_") ("$") ("!"))))
4343 ;; ... it contains only alignment cookies and empty cells.
4344 (let ((special-row-p 'empty))
4345 (catch 'exit
4346 (mapc
4347 (lambda (cell)
4348 (let ((value (org-element-contents cell)))
4349 ;; Since VALUE is a secondary string, the following
4350 ;; checks avoid expanding it with `org-export-data'.
4351 (cond ((not value))
4352 ((and (not (cdr value))
4353 (stringp (car value))
4354 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'"
4355 (car value)))
4356 (setq special-row-p 'cookie))
4357 (t (throw 'exit nil)))))
4358 (org-element-contents table-row))
4359 (eq special-row-p 'cookie)))))))
4361 (defun org-export-table-row-group (table-row info)
4362 "Return TABLE-ROW's group.
4364 INFO is a plist used as the communication channel.
4366 Return value is the group number, as an integer, or nil special
4367 rows and table rules. Group 1 is also table's header."
4368 (unless (or (eq (org-element-property :type table-row) 'rule)
4369 (org-export-table-row-is-special-p table-row info))
4370 (let ((group 0) row-flag)
4371 (catch 'found
4372 (mapc
4373 (lambda (row)
4374 (cond
4375 ((and (eq (org-element-property :type row) 'standard)
4376 (not (org-export-table-row-is-special-p row info)))
4377 (unless row-flag (incf group) (setq row-flag t)))
4378 ((eq (org-element-property :type row) 'rule)
4379 (setq row-flag nil)))
4380 (when (eq table-row row) (throw 'found group)))
4381 (org-element-contents (org-export-get-parent table-row)))))))
4383 (defun org-export-table-cell-width (table-cell info)
4384 "Return TABLE-CELL contents width.
4386 INFO is a plist used as the communication channel.
4388 Return value is the width given by the last width cookie in the
4389 same column as TABLE-CELL, or nil."
4390 (let* ((row (org-export-get-parent table-cell))
4391 (column (let ((cells (org-element-contents row)))
4392 (- (length cells) (length (memq table-cell cells)))))
4393 (table (org-export-get-parent-table table-cell))
4394 cookie-width)
4395 (mapc
4396 (lambda (row)
4397 (cond
4398 ;; In a special row, try to find a width cookie at COLUMN.
4399 ((org-export-table-row-is-special-p row info)
4400 (let ((value (org-element-contents
4401 (elt (org-element-contents row) column))))
4402 ;; The following checks avoid expanding unnecessarily the
4403 ;; cell with `org-export-data'
4404 (when (and value
4405 (not (cdr value))
4406 (stringp (car value))
4407 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'" (car value))
4408 (match-string 1 (car value)))
4409 (setq cookie-width
4410 (string-to-number (match-string 1 (car value)))))))
4411 ;; Ignore table rules.
4412 ((eq (org-element-property :type row) 'rule))))
4413 (org-element-contents table))
4414 ;; Return value.
4415 cookie-width))
4417 (defun org-export-table-cell-alignment (table-cell info)
4418 "Return TABLE-CELL contents alignment.
4420 INFO is a plist used as the communication channel.
4422 Return alignment as specified by the last alignment cookie in the
4423 same column as TABLE-CELL. If no such cookie is found, a default
4424 alignment value will be deduced from fraction of numbers in the
4425 column (see `org-table-number-fraction' for more information).
4426 Possible values are `left', `right' and `center'."
4427 (let* ((row (org-export-get-parent table-cell))
4428 (column (let ((cells (org-element-contents row)))
4429 (- (length cells) (length (memq table-cell cells)))))
4430 (table (org-export-get-parent-table table-cell))
4431 (number-cells 0)
4432 (total-cells 0)
4433 cookie-align
4434 previous-cell-number-p)
4435 (mapc
4436 (lambda (row)
4437 (cond
4438 ;; In a special row, try to find an alignment cookie at
4439 ;; COLUMN.
4440 ((org-export-table-row-is-special-p row info)
4441 (let ((value (org-element-contents
4442 (elt (org-element-contents row) column))))
4443 ;; Since VALUE is a secondary string, the following checks
4444 ;; avoid useless expansion through `org-export-data'.
4445 (when (and value
4446 (not (cdr value))
4447 (stringp (car value))
4448 (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'"
4449 (car value))
4450 (match-string 1 (car value)))
4451 (setq cookie-align (match-string 1 (car value))))))
4452 ;; Ignore table rules.
4453 ((eq (org-element-property :type row) 'rule))
4454 ;; In a standard row, check if cell's contents are expressing
4455 ;; some kind of number. Increase NUMBER-CELLS accordingly.
4456 ;; Though, don't bother if an alignment cookie has already
4457 ;; defined cell's alignment.
4458 ((not cookie-align)
4459 (let ((value (org-export-data
4460 (org-element-contents
4461 (elt (org-element-contents row) column))
4462 info)))
4463 (incf total-cells)
4464 ;; Treat an empty cell as a number if it follows a number
4465 (if (not (or (string-match org-table-number-regexp value)
4466 (and (string= value "") previous-cell-number-p)))
4467 (setq previous-cell-number-p nil)
4468 (setq previous-cell-number-p t)
4469 (incf number-cells))))))
4470 (org-element-contents table))
4471 ;; Return value. Alignment specified by cookies has precedence
4472 ;; over alignment deduced from cells contents.
4473 (cond ((equal cookie-align "l") 'left)
4474 ((equal cookie-align "r") 'right)
4475 ((equal cookie-align "c") 'center)
4476 ((>= (/ (float number-cells) total-cells) org-table-number-fraction)
4477 'right)
4478 (t 'left))))
4480 (defun org-export-table-cell-borders (table-cell info)
4481 "Return TABLE-CELL borders.
4483 INFO is a plist used as a communication channel.
4485 Return value is a list of symbols, or nil. Possible values are:
4486 `top', `bottom', `above', `below', `left' and `right'. Note:
4487 `top' (resp. `bottom') only happen for a cell in the first
4488 row (resp. last row) of the table, ignoring table rules, if any.
4490 Returned borders ignore special rows."
4491 (let* ((row (org-export-get-parent table-cell))
4492 (table (org-export-get-parent-table table-cell))
4493 borders)
4494 ;; Top/above border? TABLE-CELL has a border above when a rule
4495 ;; used to demarcate row groups can be found above. Hence,
4496 ;; finding a rule isn't sufficient to push `above' in BORDERS:
4497 ;; another regular row has to be found above that rule.
4498 (let (rule-flag)
4499 (catch 'exit
4500 (mapc (lambda (row)
4501 (cond ((eq (org-element-property :type row) 'rule)
4502 (setq rule-flag t))
4503 ((not (org-export-table-row-is-special-p row info))
4504 (if rule-flag (throw 'exit (push 'above borders))
4505 (throw 'exit nil)))))
4506 ;; Look at every row before the current one.
4507 (cdr (memq row (reverse (org-element-contents table)))))
4508 ;; No rule above, or rule found starts the table (ignoring any
4509 ;; special row): TABLE-CELL is at the top of the table.
4510 (when rule-flag (push 'above borders))
4511 (push 'top borders)))
4512 ;; Bottom/below border? TABLE-CELL has a border below when next
4513 ;; non-regular row below is a rule.
4514 (let (rule-flag)
4515 (catch 'exit
4516 (mapc (lambda (row)
4517 (cond ((eq (org-element-property :type row) 'rule)
4518 (setq rule-flag t))
4519 ((not (org-export-table-row-is-special-p row info))
4520 (if rule-flag (throw 'exit (push 'below borders))
4521 (throw 'exit nil)))))
4522 ;; Look at every row after the current one.
4523 (cdr (memq row (org-element-contents table))))
4524 ;; No rule below, or rule found ends the table (modulo some
4525 ;; special row): TABLE-CELL is at the bottom of the table.
4526 (when rule-flag (push 'below borders))
4527 (push 'bottom borders)))
4528 ;; Right/left borders? They can only be specified by column
4529 ;; groups. Column groups are defined in a row starting with "/".
4530 ;; Also a column groups row only contains "<", "<>", ">" or blank
4531 ;; cells.
4532 (catch 'exit
4533 (let ((column (let ((cells (org-element-contents row)))
4534 (- (length cells) (length (memq table-cell cells))))))
4535 (mapc
4536 (lambda (row)
4537 (unless (eq (org-element-property :type row) 'rule)
4538 (when (equal (org-element-contents
4539 (car (org-element-contents row)))
4540 '("/"))
4541 (let ((column-groups
4542 (mapcar
4543 (lambda (cell)
4544 (let ((value (org-element-contents cell)))
4545 (when (member value '(("<") ("<>") (">") nil))
4546 (car value))))
4547 (org-element-contents row))))
4548 ;; There's a left border when previous cell, if
4549 ;; any, ends a group, or current one starts one.
4550 (when (or (and (not (zerop column))
4551 (member (elt column-groups (1- column))
4552 '(">" "<>")))
4553 (member (elt column-groups column) '("<" "<>")))
4554 (push 'left borders))
4555 ;; There's a right border when next cell, if any,
4556 ;; starts a group, or current one ends one.
4557 (when (or (and (/= (1+ column) (length column-groups))
4558 (member (elt column-groups (1+ column))
4559 '("<" "<>")))
4560 (member (elt column-groups column) '(">" "<>")))
4561 (push 'right borders))
4562 (throw 'exit nil)))))
4563 ;; Table rows are read in reverse order so last column groups
4564 ;; row has precedence over any previous one.
4565 (reverse (org-element-contents table)))))
4566 ;; Return value.
4567 borders))
4569 (defun org-export-table-cell-starts-colgroup-p (table-cell info)
4570 "Non-nil when TABLE-CELL is at the beginning of a row group.
4571 INFO is a plist used as a communication channel."
4572 ;; A cell starts a column group either when it is at the beginning
4573 ;; of a row (or after the special column, if any) or when it has
4574 ;; a left border.
4575 (or (eq (org-element-map (org-export-get-parent table-cell) 'table-cell
4576 'identity info 'first-match)
4577 table-cell)
4578 (memq 'left (org-export-table-cell-borders table-cell info))))
4580 (defun org-export-table-cell-ends-colgroup-p (table-cell info)
4581 "Non-nil when TABLE-CELL is at the end of a row group.
4582 INFO is a plist used as a communication channel."
4583 ;; A cell ends a column group either when it is at the end of a row
4584 ;; or when it has a right border.
4585 (or (eq (car (last (org-element-contents
4586 (org-export-get-parent table-cell))))
4587 table-cell)
4588 (memq 'right (org-export-table-cell-borders table-cell info))))
4590 (defun org-export-table-row-starts-rowgroup-p (table-row info)
4591 "Non-nil when TABLE-ROW is at the beginning of a column group.
4592 INFO is a plist used as a communication channel."
4593 (unless (or (eq (org-element-property :type table-row) 'rule)
4594 (org-export-table-row-is-special-p table-row info))
4595 (let ((borders (org-export-table-cell-borders
4596 (car (org-element-contents table-row)) info)))
4597 (or (memq 'top borders) (memq 'above borders)))))
4599 (defun org-export-table-row-ends-rowgroup-p (table-row info)
4600 "Non-nil when TABLE-ROW is at the end of a column group.
4601 INFO is a plist used as a communication channel."
4602 (unless (or (eq (org-element-property :type table-row) 'rule)
4603 (org-export-table-row-is-special-p table-row info))
4604 (let ((borders (org-export-table-cell-borders
4605 (car (org-element-contents table-row)) info)))
4606 (or (memq 'bottom borders) (memq 'below borders)))))
4608 (defun org-export-table-row-starts-header-p (table-row info)
4609 "Non-nil when TABLE-ROW is the first table header's row.
4610 INFO is a plist used as a communication channel."
4611 (and (org-export-table-has-header-p
4612 (org-export-get-parent-table table-row) info)
4613 (org-export-table-row-starts-rowgroup-p table-row info)
4614 (= (org-export-table-row-group table-row info) 1)))
4616 (defun org-export-table-row-ends-header-p (table-row info)
4617 "Non-nil when TABLE-ROW is the last table header's row.
4618 INFO is a plist used as a communication channel."
4619 (and (org-export-table-has-header-p
4620 (org-export-get-parent-table table-row) info)
4621 (org-export-table-row-ends-rowgroup-p table-row info)
4622 (= (org-export-table-row-group table-row info) 1)))
4624 (defun org-export-table-dimensions (table info)
4625 "Return TABLE dimensions.
4627 INFO is a plist used as a communication channel.
4629 Return value is a CONS like (ROWS . COLUMNS) where
4630 ROWS (resp. COLUMNS) is the number of exportable
4631 rows (resp. columns)."
4632 (let (first-row (columns 0) (rows 0))
4633 ;; Set number of rows, and extract first one.
4634 (org-element-map table 'table-row
4635 (lambda (row)
4636 (when (eq (org-element-property :type row) 'standard)
4637 (incf rows)
4638 (unless first-row (setq first-row row)))) info)
4639 ;; Set number of columns.
4640 (org-element-map first-row 'table-cell (lambda (cell) (incf columns)) info)
4641 ;; Return value.
4642 (cons rows columns)))
4644 (defun org-export-table-cell-address (table-cell info)
4645 "Return address of a regular TABLE-CELL object.
4647 TABLE-CELL is the cell considered. INFO is a plist used as
4648 a communication channel.
4650 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4651 zero-based index. Only exportable cells are considered. The
4652 function returns nil for other cells."
4653 (let* ((table-row (org-export-get-parent table-cell))
4654 (table (org-export-get-parent-table table-cell)))
4655 ;; Ignore cells in special rows or in special column.
4656 (unless (or (org-export-table-row-is-special-p table-row info)
4657 (and (org-export-table-has-special-column-p table)
4658 (eq (car (org-element-contents table-row)) table-cell)))
4659 (cons
4660 ;; Row number.
4661 (let ((row-count 0))
4662 (org-element-map table 'table-row
4663 (lambda (row)
4664 (cond ((eq (org-element-property :type row) 'rule) nil)
4665 ((eq row table-row) row-count)
4666 (t (incf row-count) nil)))
4667 info 'first-match))
4668 ;; Column number.
4669 (let ((col-count 0))
4670 (org-element-map table-row 'table-cell
4671 (lambda (cell)
4672 (if (eq cell table-cell) col-count (incf col-count) nil))
4673 info 'first-match))))))
4675 (defun org-export-get-table-cell-at (address table info)
4676 "Return regular table-cell object at ADDRESS in TABLE.
4678 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4679 zero-based index. TABLE is a table type element. INFO is
4680 a plist used as a communication channel.
4682 If no table-cell, among exportable cells, is found at ADDRESS,
4683 return nil."
4684 (let ((column-pos (cdr address)) (column-count 0))
4685 (org-element-map
4686 ;; Row at (car address) or nil.
4687 (let ((row-pos (car address)) (row-count 0))
4688 (org-element-map table 'table-row
4689 (lambda (row)
4690 (cond ((eq (org-element-property :type row) 'rule) nil)
4691 ((= row-count row-pos) row)
4692 (t (incf row-count) nil)))
4693 info 'first-match))
4694 'table-cell
4695 (lambda (cell)
4696 (if (= column-count column-pos) cell
4697 (incf column-count) nil))
4698 info 'first-match)))
4701 ;;;; For Tables Of Contents
4703 ;; `org-export-collect-headlines' builds a list of all exportable
4704 ;; headline elements, maybe limited to a certain depth. One can then
4705 ;; easily parse it and transcode it.
4707 ;; Building lists of tables, figures or listings is quite similar.
4708 ;; Once the generic function `org-export-collect-elements' is defined,
4709 ;; `org-export-collect-tables', `org-export-collect-figures' and
4710 ;; `org-export-collect-listings' can be derived from it.
4712 (defun org-export-collect-headlines (info &optional n)
4713 "Collect headlines in order to build a table of contents.
4715 INFO is a plist used as a communication channel.
4717 When optional argument N is an integer, it specifies the depth of
4718 the table of contents. Otherwise, it is set to the value of the
4719 last headline level. See `org-export-headline-levels' for more
4720 information.
4722 Return a list of all exportable headlines as parsed elements.
4723 Footnote sections, if any, will be ignored."
4724 (unless (wholenump n) (setq n (plist-get info :headline-levels)))
4725 (org-element-map (plist-get info :parse-tree) 'headline
4726 (lambda (headline)
4727 (unless (org-element-property :footnote-section-p headline)
4728 ;; Strip contents from HEADLINE.
4729 (let ((relative-level (org-export-get-relative-level headline info)))
4730 (unless (> relative-level n) headline))))
4731 info))
4733 (defun org-export-collect-elements (type info &optional predicate)
4734 "Collect referenceable elements of a determined type.
4736 TYPE can be a symbol or a list of symbols specifying element
4737 types to search. Only elements with a caption are collected.
4739 INFO is a plist used as a communication channel.
4741 When non-nil, optional argument PREDICATE is a function accepting
4742 one argument, an element of type TYPE. It returns a non-nil
4743 value when that element should be collected.
4745 Return a list of all elements found, in order of appearance."
4746 (org-element-map (plist-get info :parse-tree) type
4747 (lambda (element)
4748 (and (org-element-property :caption element)
4749 (or (not predicate) (funcall predicate element))
4750 element))
4751 info))
4753 (defun org-export-collect-tables (info)
4754 "Build a list of tables.
4755 INFO is a plist used as a communication channel.
4757 Return a list of table elements with a caption."
4758 (org-export-collect-elements 'table info))
4760 (defun org-export-collect-figures (info predicate)
4761 "Build a list of figures.
4763 INFO is a plist used as a communication channel. PREDICATE is
4764 a function which accepts one argument: a paragraph element and
4765 whose return value is non-nil when that element should be
4766 collected.
4768 A figure is a paragraph type element, with a caption, verifying
4769 PREDICATE. The latter has to be provided since a \"figure\" is
4770 a vague concept that may depend on back-end.
4772 Return a list of elements recognized as figures."
4773 (org-export-collect-elements 'paragraph info predicate))
4775 (defun org-export-collect-listings (info)
4776 "Build a list of src blocks.
4778 INFO is a plist used as a communication channel.
4780 Return a list of src-block elements with a caption."
4781 (org-export-collect-elements 'src-block info))
4784 ;;;; Smart Quotes
4786 ;; The main function for the smart quotes sub-system is
4787 ;; `org-export-activate-smart-quotes', which replaces every quote in
4788 ;; a given string from the parse tree with its "smart" counterpart.
4790 ;; Dictionary for smart quotes is stored in
4791 ;; `org-export-smart-quotes-alist'.
4793 ;; Internally, regexps matching potential smart quotes (checks at
4794 ;; string boundaries are also necessary) are defined in
4795 ;; `org-export-smart-quotes-regexps'.
4797 (defconst org-export-smart-quotes-alist
4798 '(("de"
4799 (opening-double-quote :utf-8 "„" :html "&bdquo;" :latex "\"`"
4800 :texinfo "@quotedblbase{}")
4801 (closing-double-quote :utf-8 "“" :html "&ldquo;" :latex "\"'"
4802 :texinfo "@quotedblleft{}")
4803 (opening-single-quote :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}"
4804 :texinfo "@quotesinglbase{}")
4805 (closing-single-quote :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}"
4806 :texinfo "@quoteleft{}")
4807 (apostrophe :utf-8 "’" :html "&rsquo;"))
4808 ("en"
4809 (opening-double-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
4810 (closing-double-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
4811 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
4812 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
4813 (apostrophe :utf-8 "’" :html "&rsquo;"))
4814 ("es"
4815 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
4816 :texinfo "@guillemetleft{}")
4817 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
4818 :texinfo "@guillemetright{}")
4819 (opening-single-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
4820 (closing-single-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
4821 (apostrophe :utf-8 "’" :html "&rsquo;"))
4822 ("fr"
4823 (opening-double-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
4824 :texinfo "@guillemetleft{}@tie{}")
4825 (closing-double-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
4826 :texinfo "@tie{}@guillemetright{}")
4827 (opening-single-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
4828 :texinfo "@guillemetleft{}@tie{}")
4829 (closing-single-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
4830 :texinfo "@tie{}@guillemetright{}")
4831 (apostrophe :utf-8 "’" :html "&rsquo;")))
4832 "Smart quotes translations.
4834 Alist whose CAR is a language string and CDR is an alist with
4835 quote type as key and a plist associating various encodings to
4836 their translation as value.
4838 A quote type can be any symbol among `opening-double-quote',
4839 `closing-double-quote', `opening-single-quote',
4840 `closing-single-quote' and `apostrophe'.
4842 Valid encodings include `:utf-8', `:html', `:latex' and
4843 `:texinfo'.
4845 If no translation is found, the quote character is left as-is.")
4847 (defconst org-export-smart-quotes-regexps
4848 (list
4849 ;; Possible opening quote at beginning of string.
4850 "\\`\\([\"']\\)\\(\\w\\|\\s.\\|\\s_\\)"
4851 ;; Possible closing quote at beginning of string.
4852 "\\`\\([\"']\\)\\(\\s-\\|\\s)\\|\\s.\\)"
4853 ;; Possible apostrophe at beginning of string.
4854 "\\`\\('\\)\\S-"
4855 ;; Opening single and double quotes.
4856 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\(?:\\w\\|\\s.\\|\\s_\\)"
4857 ;; Closing single and double quotes.
4858 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\(?:\\s-\\|\\s)\\|\\s.\\)"
4859 ;; Apostrophe.
4860 "\\S-\\('\\)\\S-"
4861 ;; Possible opening quote at end of string.
4862 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\'"
4863 ;; Possible closing quote at end of string.
4864 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\'"
4865 ;; Possible apostrophe at end of string.
4866 "\\S-\\('\\)\\'")
4867 "List of regexps matching a quote or an apostrophe.
4868 In every regexp, quote or apostrophe matched is put in group 1.")
4870 (defun org-export-activate-smart-quotes (s encoding info &optional original)
4871 "Replace regular quotes with \"smart\" quotes in string S.
4873 ENCODING is a symbol among `:html', `:latex', `:texinfo' and
4874 `:utf-8'. INFO is a plist used as a communication channel.
4876 The function has to retrieve information about string
4877 surroundings in parse tree. It can only happen with an
4878 unmodified string. Thus, if S has already been through another
4879 process, a non-nil ORIGINAL optional argument will provide that
4880 original string.
4882 Return the new string."
4883 (if (equal s "") ""
4884 (let* ((prev (org-export-get-previous-element (or original s) info))
4885 ;; Try to be flexible when computing number of blanks
4886 ;; before object. The previous object may be a string
4887 ;; introduced by the back-end and not completely parsed.
4888 (pre-blank (and prev
4889 (or (org-element-property :post-blank prev)
4890 ;; A string with missing `:post-blank'
4891 ;; property.
4892 (and (stringp prev)
4893 (string-match " *\\'" prev)
4894 (length (match-string 0 prev)))
4895 ;; Fallback value.
4896 0)))
4897 (next (org-export-get-next-element (or original s) info))
4898 (get-smart-quote
4899 (lambda (q type)
4900 ;; Return smart quote associated to a give quote Q, as
4901 ;; a string. TYPE is a symbol among `open', `close' and
4902 ;; `apostrophe'.
4903 (let ((key (case type
4904 (apostrophe 'apostrophe)
4905 (open (if (equal "'" q) 'opening-single-quote
4906 'opening-double-quote))
4907 (otherwise (if (equal "'" q) 'closing-single-quote
4908 'closing-double-quote)))))
4909 (or (plist-get
4910 (cdr (assq key
4911 (cdr (assoc (plist-get info :language)
4912 org-export-smart-quotes-alist))))
4913 encoding)
4914 q)))))
4915 (if (or (equal "\"" s) (equal "'" s))
4916 ;; Only a quote: no regexp can match. We have to check both
4917 ;; sides and decide what to do.
4918 (cond ((and (not prev) (not next)) s)
4919 ((not prev) (funcall get-smart-quote s 'open))
4920 ((and (not next) (zerop pre-blank))
4921 (funcall get-smart-quote s 'close))
4922 ((not next) s)
4923 ((zerop pre-blank) (funcall get-smart-quote s 'apostrophe))
4924 (t (funcall get-smart-quote 'open)))
4925 ;; 1. Replace quote character at the beginning of S.
4926 (cond
4927 ;; Apostrophe?
4928 ((and prev (zerop pre-blank)
4929 (string-match (nth 2 org-export-smart-quotes-regexps) s))
4930 (setq s (replace-match
4931 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
4932 nil t s 1)))
4933 ;; Closing quote?
4934 ((and prev (zerop pre-blank)
4935 (string-match (nth 1 org-export-smart-quotes-regexps) s))
4936 (setq s (replace-match
4937 (funcall get-smart-quote (match-string 1 s) 'close)
4938 nil t s 1)))
4939 ;; Opening quote?
4940 ((and (or (not prev) (> pre-blank 0))
4941 (string-match (nth 0 org-export-smart-quotes-regexps) s))
4942 (setq s (replace-match
4943 (funcall get-smart-quote (match-string 1 s) 'open)
4944 nil t s 1))))
4945 ;; 2. Replace quotes in the middle of the string.
4946 (setq s (replace-regexp-in-string
4947 ;; Opening quotes.
4948 (nth 3 org-export-smart-quotes-regexps)
4949 (lambda (text)
4950 (funcall get-smart-quote (match-string 1 text) 'open))
4951 s nil t 1))
4952 (setq s (replace-regexp-in-string
4953 ;; Closing quotes.
4954 (nth 4 org-export-smart-quotes-regexps)
4955 (lambda (text)
4956 (funcall get-smart-quote (match-string 1 text) 'close))
4957 s nil t 1))
4958 (setq s (replace-regexp-in-string
4959 ;; Apostrophes.
4960 (nth 5 org-export-smart-quotes-regexps)
4961 (lambda (text)
4962 (funcall get-smart-quote (match-string 1 text) 'apostrophe))
4963 s nil t 1))
4964 ;; 3. Replace quote character at the end of S.
4965 (cond
4966 ;; Apostrophe?
4967 ((and next (string-match (nth 8 org-export-smart-quotes-regexps) s))
4968 (setq s (replace-match
4969 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
4970 nil t s 1)))
4971 ;; Closing quote?
4972 ((and (not next)
4973 (string-match (nth 7 org-export-smart-quotes-regexps) s))
4974 (setq s (replace-match
4975 (funcall get-smart-quote (match-string 1 s) 'close)
4976 nil t s 1)))
4977 ;; Opening quote?
4978 ((and next (string-match (nth 6 org-export-smart-quotes-regexps) s))
4979 (setq s (replace-match
4980 (funcall get-smart-quote (match-string 1 s) 'open)
4981 nil t s 1))))
4982 ;; Return string with smart quotes.
4983 s))))
4985 ;;;; Topology
4987 ;; Here are various functions to retrieve information about the
4988 ;; neighbourhood of a given element or object. Neighbours of interest
4989 ;; are direct parent (`org-export-get-parent'), parent headline
4990 ;; (`org-export-get-parent-headline'), first element containing an
4991 ;; object, (`org-export-get-parent-element'), parent table
4992 ;; (`org-export-get-parent-table'), previous element or object
4993 ;; (`org-export-get-previous-element') and next element or object
4994 ;; (`org-export-get-next-element').
4996 ;; `org-export-get-genealogy' returns the full genealogy of a given
4997 ;; element or object, from closest parent to full parse tree.
4999 (defun org-export-get-parent (blob)
5000 "Return BLOB parent or nil.
5001 BLOB is the element or object considered."
5002 (org-element-property :parent blob))
5004 (defun org-export-get-genealogy (blob)
5005 "Return full genealogy relative to a given element or object.
5007 BLOB is the element or object being considered.
5009 Ancestors are returned from closest to farthest, the last one
5010 being the full parse tree."
5011 (let (genealogy (parent blob))
5012 (while (setq parent (org-element-property :parent parent))
5013 (push parent genealogy))
5014 (nreverse genealogy)))
5016 (defun org-export-get-parent-headline (blob)
5017 "Return BLOB parent headline or nil.
5018 BLOB is the element or object being considered."
5019 (let ((parent blob))
5020 (while (and (setq parent (org-element-property :parent parent))
5021 (not (eq (org-element-type parent) 'headline))))
5022 parent))
5024 (defun org-export-get-parent-element (object)
5025 "Return first element containing OBJECT or nil.
5026 OBJECT is the object to consider."
5027 (let ((parent object))
5028 (while (and (setq parent (org-element-property :parent parent))
5029 (memq (org-element-type parent) org-element-all-objects)))
5030 parent))
5032 (defun org-export-get-parent-table (object)
5033 "Return OBJECT parent table or nil.
5034 OBJECT is either a `table-cell' or `table-element' type object."
5035 (let ((parent object))
5036 (while (and (setq parent (org-element-property :parent parent))
5037 (not (eq (org-element-type parent) 'table))))
5038 parent))
5040 (defun org-export-get-previous-element (blob info &optional n)
5041 "Return previous element or object.
5043 BLOB is an element or object. INFO is a plist used as
5044 a communication channel. Return previous exportable element or
5045 object, a string, or nil.
5047 When optional argument N is a positive integer, return a list
5048 containing up to N siblings before BLOB, from farthest to
5049 closest. With any other non-nil value, return a list containing
5050 all of them."
5051 (let ((siblings
5052 ;; An object can belong to the contents of its parent or
5053 ;; to a secondary string. We check the latter option
5054 ;; first.
5055 (let ((parent (org-export-get-parent blob)))
5056 (or (and (not (memq (org-element-type blob)
5057 org-element-all-elements))
5058 (let ((sec-value
5059 (org-element-property
5060 (cdr (assq (org-element-type parent)
5061 org-element-secondary-value-alist))
5062 parent)))
5063 (and (memq blob sec-value) sec-value)))
5064 (org-element-contents parent))))
5065 prev)
5066 (catch 'exit
5067 (mapc (lambda (obj)
5068 (cond ((memq obj (plist-get info :ignore-list)))
5069 ((null n) (throw 'exit obj))
5070 ((not (wholenump n)) (push obj prev))
5071 ((zerop n) (throw 'exit prev))
5072 (t (decf n) (push obj prev))))
5073 (cdr (memq blob (reverse siblings))))
5074 prev)))
5076 (defun org-export-get-next-element (blob info &optional n)
5077 "Return next element or object.
5079 BLOB is an element or object. INFO is a plist used as
5080 a communication channel. Return next exportable element or
5081 object, a string, or nil.
5083 When optional argument N is a positive integer, return a list
5084 containing up to N siblings after BLOB, from closest to farthest.
5085 With any other non-nil value, return a list containing all of
5086 them."
5087 (let ((siblings
5088 ;; An object can belong to the contents of its parent or to
5089 ;; a secondary string. We check the latter option first.
5090 (let ((parent (org-export-get-parent blob)))
5091 (or (and (not (memq (org-element-type blob)
5092 org-element-all-objects))
5093 (let ((sec-value
5094 (org-element-property
5095 (cdr (assq (org-element-type parent)
5096 org-element-secondary-value-alist))
5097 parent)))
5098 (cdr (memq blob sec-value))))
5099 (cdr (memq blob (org-element-contents parent))))))
5100 next)
5101 (catch 'exit
5102 (mapc (lambda (obj)
5103 (cond ((memq obj (plist-get info :ignore-list)))
5104 ((null n) (throw 'exit obj))
5105 ((not (wholenump n)) (push obj next))
5106 ((zerop n) (throw 'exit (nreverse next)))
5107 (t (decf n) (push obj next))))
5108 siblings)
5109 (nreverse next))))
5112 ;;;; Translation
5114 ;; `org-export-translate' translates a string according to language
5115 ;; specified by LANGUAGE keyword or `org-export-language-setup'
5116 ;; variable and a specified charset. `org-export-dictionary' contains
5117 ;; the dictionary used for the translation.
5119 (defconst org-export-dictionary
5120 '(("Author"
5121 ("ca" :default "Autor")
5122 ("cs" :default "Autor")
5123 ("da" :default "Ophavsmand")
5124 ("de" :default "Autor")
5125 ("eo" :html "A&#365;toro")
5126 ("es" :default "Autor")
5127 ("fi" :html "Tekij&auml;")
5128 ("fr" :default "Auteur")
5129 ("hu" :default "Szerz&otilde;")
5130 ("is" :html "H&ouml;fundur")
5131 ("it" :default "Autore")
5132 ("ja" :html "&#33879;&#32773;" :utf-8 "著者")
5133 ("nl" :default "Auteur")
5134 ("no" :default "Forfatter")
5135 ("nb" :default "Forfatter")
5136 ("nn" :default "Forfattar")
5137 ("pl" :default "Autor")
5138 ("ru" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5139 ("sv" :html "F&ouml;rfattare")
5140 ("uk" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
5141 ("zh-CN" :html "&#20316;&#32773;" :utf-8 "作者")
5142 ("zh-TW" :html "&#20316;&#32773;" :utf-8 "作者"))
5143 ("Date"
5144 ("ca" :default "Data")
5145 ("cs" :default "Datum")
5146 ("da" :default "Dato")
5147 ("de" :default "Datum")
5148 ("eo" :default "Dato")
5149 ("es" :default "Fecha")
5150 ("fi" :html "P&auml;iv&auml;m&auml;&auml;r&auml;")
5151 ("hu" :html "D&aacute;tum")
5152 ("is" :default "Dagsetning")
5153 ("it" :default "Data")
5154 ("ja" :html "&#26085;&#20184;" :utf-8 "日付")
5155 ("nl" :default "Datum")
5156 ("no" :default "Dato")
5157 ("nb" :default "Dato")
5158 ("nn" :default "Dato")
5159 ("pl" :default "Data")
5160 ("ru" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5161 ("sv" :default "Datum")
5162 ("uk" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
5163 ("zh-CN" :html "&#26085;&#26399;" :utf-8 "日期")
5164 ("zh-TW" :html "&#26085;&#26399;" :utf-8 "日期"))
5165 ("Equation"
5166 ("fr" :ascii "Equation" :default "Équation"))
5167 ("Figure")
5168 ("Footnotes"
5169 ("ca" :html "Peus de p&agrave;gina")
5170 ("cs" :default "Pozn\xe1mky pod carou")
5171 ("da" :default "Fodnoter")
5172 ("de" :html "Fu&szlig;noten")
5173 ("eo" :default "Piednotoj")
5174 ("es" :html "Pies de p&aacute;gina")
5175 ("fi" :default "Alaviitteet")
5176 ("fr" :default "Notes de bas de page")
5177 ("hu" :html "L&aacute;bjegyzet")
5178 ("is" :html "Aftanm&aacute;lsgreinar")
5179 ("it" :html "Note a pi&egrave; di pagina")
5180 ("ja" :html "&#33050;&#27880;" :utf-8 "脚注")
5181 ("nl" :default "Voetnoten")
5182 ("no" :default "Fotnoter")
5183 ("nb" :default "Fotnoter")
5184 ("nn" :default "Fotnotar")
5185 ("pl" :default "Przypis")
5186 ("ru" :html "&#1057;&#1085;&#1086;&#1089;&#1082;&#1080;" :utf-8 "Сноски")
5187 ("sv" :default "Fotnoter")
5188 ("uk" :html "&#1055;&#1088;&#1080;&#1084;&#1110;&#1090;&#1082;&#1080;"
5189 :utf-8 "Примітки")
5190 ("zh-CN" :html "&#33050;&#27880;" :utf-8 "脚注")
5191 ("zh-TW" :html "&#33139;&#35387;" :utf-8 "腳註"))
5192 ("List of Listings"
5193 ("fr" :default "Liste des programmes"))
5194 ("List of Tables"
5195 ("fr" :default "Liste des tableaux"))
5196 ("Listing %d:"
5197 ("fr"
5198 :ascii "Programme %d :" :default "Programme nº %d :"
5199 :latin1 "Programme %d :"))
5200 ("Listing %d: %s"
5201 ("fr"
5202 :ascii "Programme %d : %s" :default "Programme nº %d : %s"
5203 :latin1 "Programme %d : %s"))
5204 ("See section %s"
5205 ("fr" :default "cf. section %s"))
5206 ("Table %d:"
5207 ("fr"
5208 :ascii "Tableau %d :" :default "Tableau nº %d :" :latin1 "Tableau %d :"))
5209 ("Table %d: %s"
5210 ("fr"
5211 :ascii "Tableau %d : %s" :default "Tableau nº %d : %s"
5212 :latin1 "Tableau %d : %s"))
5213 ("Table of Contents"
5214 ("ca" :html "&Iacute;ndex")
5215 ("cs" :default "Obsah")
5216 ("da" :default "Indhold")
5217 ("de" :default "Inhaltsverzeichnis")
5218 ("eo" :default "Enhavo")
5219 ("es" :html "&Iacute;ndice")
5220 ("fi" :html "Sis&auml;llysluettelo")
5221 ("fr" :ascii "Sommaire" :default "Table des matières")
5222 ("hu" :html "Tartalomjegyz&eacute;k")
5223 ("is" :default "Efnisyfirlit")
5224 ("it" :default "Indice")
5225 ("ja" :html "&#30446;&#27425;" :utf-8 "目次")
5226 ("nl" :default "Inhoudsopgave")
5227 ("no" :default "Innhold")
5228 ("nb" :default "Innhold")
5229 ("nn" :default "Innhald")
5230 ("pl" :html "Spis tre&#x015b;ci")
5231 ("ru" :html "&#1057;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1077;"
5232 :utf-8 "Содержание")
5233 ("sv" :html "Inneh&aring;ll")
5234 ("uk" :html "&#1047;&#1084;&#1110;&#1089;&#1090;" :utf-8 "Зміст")
5235 ("zh-CN" :html "&#30446;&#24405;" :utf-8 "目录")
5236 ("zh-TW" :html "&#30446;&#37636;" :utf-8 "目錄"))
5237 ("Unknown reference"
5238 ("fr" :ascii "Destination inconnue" :default "Référence inconnue")))
5239 "Dictionary for export engine.
5241 Alist whose CAR is the string to translate and CDR is an alist
5242 whose CAR is the language string and CDR is a plist whose
5243 properties are possible charsets and values translated terms.
5245 It is used as a database for `org-export-translate'. Since this
5246 function returns the string as-is if no translation was found,
5247 the variable only needs to record values different from the
5248 entry.")
5250 (defun org-export-translate (s encoding info)
5251 "Translate string S according to language specification.
5253 ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1'
5254 and `:utf-8'. INFO is a plist used as a communication channel.
5256 Translation depends on `:language' property. Return the
5257 translated string. If no translation is found, try to fall back
5258 to `:default' encoding. If it fails, return S."
5259 (let* ((lang (plist-get info :language))
5260 (translations (cdr (assoc lang
5261 (cdr (assoc s org-export-dictionary))))))
5262 (or (plist-get translations encoding)
5263 (plist-get translations :default)
5264 s)))
5268 ;;; Asynchronous Export
5270 ;; `org-export-async-start' is the entry point for asynchronous
5271 ;; export. It recreates current buffer (including visibility,
5272 ;; narrowing and visited file) in an external Emacs process, and
5273 ;; evaluates a command there. It then applies a function on the
5274 ;; returned results in the current process.
5276 ;; Asynchronously generated results are never displayed directly.
5277 ;; Instead, they are stored in `org-export-stack-contents'. They can
5278 ;; then be retrieved by calling `org-export-stack'.
5280 ;; Export Stack is viewed through a dedicated major mode
5281 ;;`org-export-stack-mode' and tools: `org-export-stack-refresh',
5282 ;;`org-export-stack-delete', `org-export-stack-view' and
5283 ;;`org-export-stack-clear'.
5285 ;; For back-ends, `org-export-add-to-stack' add a new source to stack.
5286 ;; It should used whenever `org-export-async-start' is called.
5288 (defmacro org-export-async-start (fun &rest body)
5289 "Call function FUN on the results returned by BODY evaluation.
5291 BODY evaluation happens in an asynchronous process, from a buffer
5292 which is an exact copy of the current one.
5294 Use `org-export-add-to-stack' in FUN in order to register results
5295 in the stack. Examples for, respectively a temporary buffer and
5296 a file are:
5298 \(org-export-async-start
5299 \(lambda (output)
5300 \(with-current-buffer (get-buffer-create \"*Org BACKEND Export*\")
5301 \(erase-buffer)
5302 \(insert output)
5303 \(goto-char (point-min))
5304 \(org-export-add-to-stack (current-buffer) 'backend)))
5305 `(org-export-as 'backend ,subtreep ,visible-only ,body-only ',ext-plist))
5309 \(org-export-async-start
5310 \(lambda (f) (org-export-add-to-stack f 'backend))
5311 `(expand-file-name
5312 \(org-export-to-file
5313 'backend ,outfile ,subtreep ,visible-only ,body-only ',ext-plist)))"
5314 (declare (indent 1) (debug t))
5315 (org-with-gensyms (process temp-file copy-fun proc-buffer handler coding)
5316 ;; Write the full sexp evaluating BODY in a copy of the current
5317 ;; buffer to a temporary file, as it may be too long for program
5318 ;; args in `start-process'.
5319 `(with-temp-message "Initializing asynchronous export process"
5320 (let ((,copy-fun (org-export--generate-copy-script (current-buffer)))
5321 (,temp-file (make-temp-file "org-export-process"))
5322 (,coding buffer-file-coding-system))
5323 (with-temp-file ,temp-file
5324 (insert
5325 ;; Null characters (from variable values) are inserted
5326 ;; within the file. As a consequence, coding system for
5327 ;; buffer contents will not be recognized properly. So,
5328 ;; we make sure it is the same as the one used to display
5329 ;; the original buffer.
5330 (format ";; -*- coding: %s; -*-\n%S"
5331 ,coding
5332 `(with-temp-buffer
5333 ,(when org-export-async-debug '(setq debug-on-error t))
5334 ;; Ignore `kill-emacs-hook' and code evaluation
5335 ;; queries from Babel as we need a truly
5336 ;; non-interactive process.
5337 (setq kill-emacs-hook nil
5338 org-babel-confirm-evaluate-answer-no t)
5339 ;; Initialize export framework.
5340 (require 'ox)
5341 ;; Re-create current buffer there.
5342 (funcall ,,copy-fun)
5343 (restore-buffer-modified-p nil)
5344 ;; Sexp to evaluate in the buffer.
5345 (print (progn ,,@body))))))
5346 ;; Start external process.
5347 (let* ((process-connection-type nil)
5348 (,proc-buffer (generate-new-buffer-name "*Org Export Process*"))
5349 (,process
5350 (start-process
5351 "org-export-process" ,proc-buffer
5352 (expand-file-name invocation-name invocation-directory)
5353 "-Q" "--batch"
5354 "-l" org-export-async-init-file
5355 "-l" ,temp-file)))
5356 ;; Register running process in stack.
5357 (org-export-add-to-stack (get-buffer ,proc-buffer) nil ,process)
5358 ;; Set-up sentinel in order to catch results.
5359 (set-process-sentinel
5360 ,process
5361 (let ((handler ',fun))
5362 `(lambda (p status)
5363 (let ((proc-buffer (process-buffer p)))
5364 (when (eq (process-status p) 'exit)
5365 (unwind-protect
5366 (if (zerop (process-exit-status p))
5367 (unwind-protect
5368 (let ((results
5369 (with-current-buffer proc-buffer
5370 (goto-char (point-max))
5371 (backward-sexp)
5372 (read (current-buffer)))))
5373 (funcall ,handler results))
5374 (unless org-export-async-debug
5375 (and (get-buffer proc-buffer)
5376 (kill-buffer proc-buffer))))
5377 (org-export-add-to-stack proc-buffer nil p)
5378 (ding)
5379 (message "Process '%s' exited abnormally" p))
5380 (unless org-export-async-debug
5381 (delete-file ,,temp-file)))))))))))))
5383 (defun org-export-add-to-stack (source backend &optional process)
5384 "Add a new result to export stack if not present already.
5386 SOURCE is a buffer or a file name containing export results.
5387 BACKEND is a symbol representing export back-end used to generate
5390 Entries already pointing to SOURCE and unavailable entries are
5391 removed beforehand. Return the new stack."
5392 (setq org-export-stack-contents
5393 (cons (list source backend (or process (current-time)))
5394 (org-export-stack-remove source))))
5396 (defun org-export-stack ()
5397 "Menu for asynchronous export results and running processes."
5398 (interactive)
5399 (let ((buffer (get-buffer-create "*Org Export Stack*")))
5400 (set-buffer buffer)
5401 (when (zerop (buffer-size)) (org-export-stack-mode))
5402 (org-export-stack-refresh)
5403 (pop-to-buffer buffer))
5404 (message "Type \"q\" to quit, \"?\" for help"))
5406 (defun org-export--stack-source-at-point ()
5407 "Return source from export results at point in stack."
5408 (let ((source (car (nth (1- (org-current-line)) org-export-stack-contents))))
5409 (if (not source) (error "Source unavailable, please refresh buffer")
5410 (let ((source-name (if (stringp source) source (buffer-name source))))
5411 (if (save-excursion
5412 (beginning-of-line)
5413 (looking-at (concat ".* +" (regexp-quote source-name) "$")))
5414 source
5415 ;; SOURCE is not consistent with current line. The stack
5416 ;; view is outdated.
5417 (error "Source unavailable; type `g' to update buffer"))))))
5419 (defun org-export-stack-clear ()
5420 "Remove all entries from export stack."
5421 (interactive)
5422 (setq org-export-stack-contents nil))
5424 (defun org-export-stack-refresh (&rest dummy)
5425 "Refresh the asynchronous export stack.
5426 DUMMY is ignored. Unavailable sources are removed from the list.
5427 Return the new stack."
5428 (let ((inhibit-read-only t))
5429 (org-preserve-lc
5430 (erase-buffer)
5431 (insert (concat
5432 (let ((counter 0))
5433 (mapconcat
5434 (lambda (entry)
5435 (let ((proc-p (processp (nth 2 entry))))
5436 (concat
5437 ;; Back-end.
5438 (format " %-12s " (or (nth 1 entry) ""))
5439 ;; Age.
5440 (let ((data (nth 2 entry)))
5441 (if proc-p (format " %6s " (process-status data))
5442 ;; Compute age of the results.
5443 (org-format-seconds
5444 "%4h:%.2m "
5445 (float-time (time-since data)))))
5446 ;; Source.
5447 (format " %s"
5448 (let ((source (car entry)))
5449 (if (stringp source) source
5450 (buffer-name source)))))))
5451 ;; Clear stack from exited processes, dead buffers or
5452 ;; non-existent files.
5453 (setq org-export-stack-contents
5454 (org-remove-if-not
5455 (lambda (el)
5456 (if (processp (nth 2 el))
5457 (buffer-live-p (process-buffer (nth 2 el)))
5458 (let ((source (car el)))
5459 (if (bufferp source) (buffer-live-p source)
5460 (file-exists-p source)))))
5461 org-export-stack-contents)) "\n")))))))
5463 (defun org-export-stack-remove (&optional source)
5464 "Remove export results at point from stack.
5465 If optional argument SOURCE is non-nil, remove it instead."
5466 (interactive)
5467 (let ((source (or source (org-export--stack-source-at-point))))
5468 (setq org-export-stack-contents
5469 (org-remove-if (lambda (el) (equal (car el) source))
5470 org-export-stack-contents))))
5472 (defun org-export-stack-view (&optional in-emacs)
5473 "View export results at point in stack.
5474 With an optional prefix argument IN-EMACS, force viewing files
5475 within Emacs."
5476 (interactive "P")
5477 (let ((source (org-export--stack-source-at-point)))
5478 (cond ((processp source)
5479 (org-switch-to-buffer-other-window (process-buffer source)))
5480 ((bufferp source) (org-switch-to-buffer-other-window source))
5481 (t (org-open-file source in-emacs)))))
5483 (defconst org-export-stack-mode-map
5484 (let ((km (make-sparse-keymap)))
5485 (define-key km " " 'next-line)
5486 (define-key km "n" 'next-line)
5487 (define-key km "\C-n" 'next-line)
5488 (define-key km [down] 'next-line)
5489 (define-key km "p" 'previous-line)
5490 (define-key km "\C-p" 'previous-line)
5491 (define-key km "\C-?" 'previous-line)
5492 (define-key km [up] 'previous-line)
5493 (define-key km "C" 'org-export-stack-clear)
5494 (define-key km "v" 'org-export-stack-view)
5495 (define-key km (kbd "RET") 'org-export-stack-view)
5496 (define-key km "d" 'org-export-stack-remove)
5498 "Keymap for Org Export Stack.")
5500 (define-derived-mode org-export-stack-mode special-mode "Org-Stack"
5501 "Mode for displaying asynchronous export stack.
5503 Type \\[org-export-stack] to visualize the asynchronous export
5504 stack.
5506 In an Org Export Stack buffer, use \\<org-export-stack-mode-map>\\[org-export-stack-view] to view export output
5507 on current line, \\[org-export-stack-remove] to remove it from the stack and \\[org-export-stack-clear] to clear
5508 stack completely.
5510 Removing entries in an Org Export Stack buffer doesn't affect
5511 files or buffers, only the display.
5513 \\{org-export-stack-mode-map}"
5514 (abbrev-mode 0)
5515 (auto-fill-mode 0)
5516 (setq buffer-read-only t
5517 buffer-undo-list t
5518 truncate-lines t
5519 header-line-format
5520 '(:eval
5521 (format " %-12s | %6s | %s" "Back-End" "Age" "Source")))
5522 (add-hook 'post-command-hook 'org-export-stack-refresh nil t)
5523 (set (make-local-variable 'revert-buffer-function)
5524 'org-export-stack-refresh))
5528 ;;; The Dispatcher
5530 ;; `org-export-dispatch' is the standard interactive way to start an
5531 ;; export process. It uses `org-export--dispatch-ui' as a subroutine
5532 ;; for its interface, which, in turn, delegates response to key
5533 ;; pressed to `org-export--dispatch-action'.
5535 ;;;###autoload
5536 (defun org-export-dispatch (&optional arg)
5537 "Export dispatcher for Org mode.
5539 It provides an access to common export related tasks in a buffer.
5540 Its interface comes in two flavours: standard and expert.
5542 While both share the same set of bindings, only the former
5543 displays the valid keys associations in a dedicated buffer.
5544 Scrolling (resp. line-wise motion) in this buffer is done with
5545 SPC and DEL (resp. C-n and C-p) keys.
5547 Set variable `org-export-dispatch-use-expert-ui' to switch to one
5548 flavour or the other.
5550 When ARG is \\[universal-argument], repeat the last export action, with the same set
5551 of options used back then, on the current buffer.
5553 When ARG is \\[universal-argument] \\[universal-argument], display the asynchronous export stack."
5554 (interactive "P")
5555 (let* ((input
5556 (cond ((equal arg '(16)) '(stack))
5557 ((and arg org-export-dispatch-last-action))
5558 (t (save-window-excursion
5559 (unwind-protect
5560 (progn
5561 ;; Remember where we are
5562 (move-marker org-export-dispatch-last-position
5563 (point)
5564 (org-base-buffer (current-buffer)))
5565 ;; Get and store an export command
5566 (setq org-export-dispatch-last-action
5567 (org-export--dispatch-ui
5568 (list org-export-initial-scope
5569 (and org-export-in-background 'async))
5571 org-export-dispatch-use-expert-ui)))
5572 (and (get-buffer "*Org Export Dispatcher*")
5573 (kill-buffer "*Org Export Dispatcher*")))))))
5574 (action (car input))
5575 (optns (cdr input)))
5576 (unless (memq 'subtree optns)
5577 (move-marker org-export-dispatch-last-position nil))
5578 (case action
5579 ;; First handle special hard-coded actions.
5580 (template (org-export-insert-default-template nil optns))
5581 (stack (org-export-stack))
5582 (publish-current-file
5583 (org-publish-current-file (memq 'force optns) (memq 'async optns)))
5584 (publish-current-project
5585 (org-publish-current-project (memq 'force optns) (memq 'async optns)))
5586 (publish-choose-project
5587 (org-publish (assoc (org-icompleting-read
5588 "Publish project: "
5589 org-publish-project-alist nil t)
5590 org-publish-project-alist)
5591 (memq 'force optns)
5592 (memq 'async optns)))
5593 (publish-all (org-publish-all (memq 'force optns) (memq 'async optns)))
5594 (otherwise
5595 (save-excursion
5596 (when arg
5597 ;; Repeating command, maybe move cursor to restore subtree
5598 ;; context.
5599 (if (eq (marker-buffer org-export-dispatch-last-position)
5600 (org-base-buffer (current-buffer)))
5601 (goto-char org-export-dispatch-last-position)
5602 ;; We are in a different buffer, forget position.
5603 (move-marker org-export-dispatch-last-position nil)))
5604 (funcall action
5605 ;; Return a symbol instead of a list to ease
5606 ;; asynchronous export macro use.
5607 (and (memq 'async optns) t)
5608 (and (memq 'subtree optns) t)
5609 (and (memq 'visible optns) t)
5610 (and (memq 'body optns) t)))))))
5612 (defun org-export--dispatch-ui (options first-key expertp)
5613 "Handle interface for `org-export-dispatch'.
5615 OPTIONS is a list containing current interactive options set for
5616 export. It can contain any of the following symbols:
5617 `body' toggles a body-only export
5618 `subtree' restricts export to current subtree
5619 `visible' restricts export to visible part of buffer.
5620 `force' force publishing files.
5621 `async' use asynchronous export process
5623 FIRST-KEY is the key pressed to select the first level menu. It
5624 is nil when this menu hasn't been selected yet.
5626 EXPERTP, when non-nil, triggers expert UI. In that case, no help
5627 buffer is provided, but indications about currently active
5628 options are given in the prompt. Moreover, \[?] allows to switch
5629 back to standard interface."
5630 (let* ((fontify-key
5631 (lambda (key &optional access-key)
5632 ;; Fontify KEY string. Optional argument ACCESS-KEY, when
5633 ;; non-nil is the required first-level key to activate
5634 ;; KEY. When its value is t, activate KEY independently
5635 ;; on the first key, if any. A nil value means KEY will
5636 ;; only be activated at first level.
5637 (if (or (eq access-key t) (eq access-key first-key))
5638 (org-propertize key 'face 'org-warning)
5639 key)))
5640 (fontify-value
5641 (lambda (value)
5642 ;; Fontify VALUE string.
5643 (org-propertize value 'face 'font-lock-variable-name-face)))
5644 ;; Prepare menu entries by extracting them from
5645 ;; `org-export-registered-backends', and sorting them by
5646 ;; access key and by ordinal, if any.
5647 (backends
5648 (sort
5649 (sort
5650 (delq nil
5651 (mapcar
5652 (lambda (b)
5653 (let ((name (car b)))
5654 (catch 'ignored
5655 ;; Ignore any back-end belonging to
5656 ;; `org-export-invisible-backends' or derived
5657 ;; from one of them.
5658 (dolist (ignored org-export-invisible-backends)
5659 (when (org-export-derived-backend-p name ignored)
5660 (throw 'ignored nil)))
5661 (org-export-backend-menu name))))
5662 org-export-registered-backends))
5663 (lambda (a b)
5664 (let ((key-a (nth 1 a))
5665 (key-b (nth 1 b)))
5666 (cond ((and (numberp key-a) (numberp key-b))
5667 (< key-a key-b))
5668 ((numberp key-b) t)))))
5669 (lambda (a b) (< (car a) (car b)))))
5670 ;; Compute a list of allowed keys based on the first key
5671 ;; pressed, if any. Some keys
5672 ;; (?^B, ?^V, ?^S, ?^F, ?^A, ?&, ?# and ?q) are always
5673 ;; available.
5674 (allowed-keys
5675 (nconc (list 2 22 19 6 1)
5676 (if (not first-key) (org-uniquify (mapcar 'car backends))
5677 (let (sub-menu)
5678 (dolist (backend backends (sort (mapcar 'car sub-menu) '<))
5679 (when (eq (car backend) first-key)
5680 (setq sub-menu (append (nth 2 backend) sub-menu))))))
5681 (cond ((eq first-key ?P) (list ?f ?p ?x ?a))
5682 ((not first-key) (list ?P)))
5683 (list ?& ?#)
5684 (when expertp (list ??))
5685 (list ?q)))
5686 ;; Build the help menu for standard UI.
5687 (help
5688 (unless expertp
5689 (concat
5690 ;; Options are hard-coded.
5691 (format "[%s] Body only: %s [%s] Visible only: %s
5692 \[%s] Export scope: %s [%s] Force publishing: %s
5693 \[%s] Async export: %s\n\n"
5694 (funcall fontify-key "C-b" t)
5695 (funcall fontify-value
5696 (if (memq 'body options) "On " "Off"))
5697 (funcall fontify-key "C-v" t)
5698 (funcall fontify-value
5699 (if (memq 'visible options) "On " "Off"))
5700 (funcall fontify-key "C-s" t)
5701 (funcall fontify-value
5702 (if (memq 'subtree options) "Subtree" "Buffer "))
5703 (funcall fontify-key "C-f" t)
5704 (funcall fontify-value
5705 (if (memq 'force options) "On " "Off"))
5706 (funcall fontify-key "C-a" t)
5707 (funcall fontify-value
5708 (if (memq 'async options) "On " "Off")))
5709 ;; Display registered back-end entries. When a key
5710 ;; appears for the second time, do not create another
5711 ;; entry, but append its sub-menu to existing menu.
5712 (let (last-key)
5713 (mapconcat
5714 (lambda (entry)
5715 (let ((top-key (car entry)))
5716 (concat
5717 (unless (eq top-key last-key)
5718 (setq last-key top-key)
5719 (format "\n[%s] %s\n"
5720 (funcall fontify-key (char-to-string top-key))
5721 (nth 1 entry)))
5722 (let ((sub-menu (nth 2 entry)))
5723 (unless (functionp sub-menu)
5724 ;; Split sub-menu into two columns.
5725 (let ((index -1))
5726 (concat
5727 (mapconcat
5728 (lambda (sub-entry)
5729 (incf index)
5730 (format
5731 (if (zerop (mod index 2)) " [%s] %-26s"
5732 "[%s] %s\n")
5733 (funcall fontify-key
5734 (char-to-string (car sub-entry))
5735 top-key)
5736 (nth 1 sub-entry)))
5737 sub-menu "")
5738 (when (zerop (mod index 2)) "\n"))))))))
5739 backends ""))
5740 ;; Publishing menu is hard-coded.
5741 (format "\n[%s] Publish
5742 [%s] Current file [%s] Current project
5743 [%s] Choose project [%s] All projects\n\n\n"
5744 (funcall fontify-key "P")
5745 (funcall fontify-key "f" ?P)
5746 (funcall fontify-key "p" ?P)
5747 (funcall fontify-key "x" ?P)
5748 (funcall fontify-key "a" ?P))
5749 (format "[%s] Export stack [%s] Insert template\n"
5750 (funcall fontify-key "&" t)
5751 (funcall fontify-key "#" t))
5752 (format "[%s] %s"
5753 (funcall fontify-key "q" t)
5754 (if first-key "Main menu" "Exit")))))
5755 ;; Build prompts for both standard and expert UI.
5756 (standard-prompt (unless expertp "Export command: "))
5757 (expert-prompt
5758 (when expertp
5759 (format
5760 "Export command (C-%s%s%s%s%s) [%s]: "
5761 (if (memq 'body options) (funcall fontify-key "b" t) "b")
5762 (if (memq 'visible options) (funcall fontify-key "v" t) "v")
5763 (if (memq 'subtree options) (funcall fontify-key "s" t) "s")
5764 (if (memq 'force options) (funcall fontify-key "f" t) "f")
5765 (if (memq 'async options) (funcall fontify-key "a" t) "a")
5766 (mapconcat (lambda (k)
5767 ;; Strip control characters.
5768 (unless (< k 27) (char-to-string k)))
5769 allowed-keys "")))))
5770 ;; With expert UI, just read key with a fancy prompt. In standard
5771 ;; UI, display an intrusive help buffer.
5772 (if expertp
5773 (org-export--dispatch-action
5774 expert-prompt allowed-keys backends options first-key expertp)
5775 ;; At first call, create frame layout in order to display menu.
5776 (unless (get-buffer "*Org Export Dispatcher*")
5777 (delete-other-windows)
5778 (org-switch-to-buffer-other-window
5779 (get-buffer-create "*Org Export Dispatcher*"))
5780 (setq cursor-type nil
5781 header-line-format "Use SPC, DEL, C-n or C-p to navigate.")
5782 ;; Make sure that invisible cursor will not highlight square
5783 ;; brackets.
5784 (set-syntax-table (copy-syntax-table))
5785 (modify-syntax-entry ?\[ "w"))
5786 ;; At this point, the buffer containing the menu exists and is
5787 ;; visible in the current window. So, refresh it.
5788 (with-current-buffer "*Org Export Dispatcher*"
5789 ;; Refresh help. Maintain display continuity by re-visiting
5790 ;; previous window position.
5791 (let ((pos (window-start)))
5792 (erase-buffer)
5793 (insert help)
5794 (set-window-start nil pos)))
5795 (org-fit-window-to-buffer)
5796 (org-export--dispatch-action
5797 standard-prompt allowed-keys backends options first-key expertp))))
5799 (defun org-export--dispatch-action
5800 (prompt allowed-keys backends options first-key expertp)
5801 "Read a character from command input and act accordingly.
5803 PROMPT is the displayed prompt, as a string. ALLOWED-KEYS is
5804 a list of characters available at a given step in the process.
5805 BACKENDS is a list of menu entries. OPTIONS, FIRST-KEY and
5806 EXPERTP are the same as defined in `org-export--dispatch-ui',
5807 which see.
5809 Toggle export options when required. Otherwise, return value is
5810 a list with action as CAR and a list of interactive export
5811 options as CDR."
5812 (let (key)
5813 ;; Scrolling: when in non-expert mode, act on motion keys (C-n,
5814 ;; C-p, SPC, DEL).
5815 (while (and (setq key (read-char-exclusive prompt))
5816 (not expertp)
5817 (memq key '(14 16 ?\s ?\d)))
5818 (case key
5819 (14 (if (not (pos-visible-in-window-p (point-max)))
5820 (ignore-errors (scroll-up-line))
5821 (message "End of buffer")
5822 (sit-for 1)))
5823 (16 (if (not (pos-visible-in-window-p (point-min)))
5824 (ignore-errors (scroll-down-line))
5825 (message "Beginning of buffer")
5826 (sit-for 1)))
5827 (?\s (if (not (pos-visible-in-window-p (point-max)))
5828 (scroll-up nil)
5829 (message "End of buffer")
5830 (sit-for 1)))
5831 (?\d (if (not (pos-visible-in-window-p (point-min)))
5832 (scroll-down nil)
5833 (message "Beginning of buffer")
5834 (sit-for 1)))))
5835 (cond
5836 ;; Ignore undefined associations.
5837 ((not (memq key allowed-keys))
5838 (ding)
5839 (unless expertp (message "Invalid key") (sit-for 1))
5840 (org-export--dispatch-ui options first-key expertp))
5841 ;; q key at first level aborts export. At second level, cancel
5842 ;; first key instead.
5843 ((eq key ?q) (if (not first-key) (error "Export aborted")
5844 (org-export--dispatch-ui options nil expertp)))
5845 ;; Help key: Switch back to standard interface if expert UI was
5846 ;; active.
5847 ((eq key ??) (org-export--dispatch-ui options first-key nil))
5848 ;; Send request for template insertion along with export scope.
5849 ((eq key ?#) (cons 'template (memq 'subtree options)))
5850 ;; Switch to asynchronous export stack.
5851 ((eq key ?&) '(stack))
5852 ;; Toggle options: C-b (2) C-v (22) C-s (19) C-f (6) C-a (1).
5853 ((memq key '(2 22 19 6 1))
5854 (org-export--dispatch-ui
5855 (let ((option (case key (2 'body) (22 'visible) (19 'subtree)
5856 (6 'force) (1 'async))))
5857 (if (memq option options) (remq option options)
5858 (cons option options)))
5859 first-key expertp))
5860 ;; Action selected: Send key and options back to
5861 ;; `org-export-dispatch'.
5862 ((or first-key (functionp (nth 2 (assq key backends))))
5863 (cons (cond
5864 ((not first-key) (nth 2 (assq key backends)))
5865 ;; Publishing actions are hard-coded. Send a special
5866 ;; signal to `org-export-dispatch'.
5867 ((eq first-key ?P)
5868 (case key
5869 (?f 'publish-current-file)
5870 (?p 'publish-current-project)
5871 (?x 'publish-choose-project)
5872 (?a 'publish-all)))
5873 ;; Return first action associated to FIRST-KEY + KEY
5874 ;; path. Indeed, derived backends can share the same
5875 ;; FIRST-KEY.
5876 (t (catch 'found
5877 (mapc (lambda (backend)
5878 (let ((match (assq key (nth 2 backend))))
5879 (when match (throw 'found (nth 2 match)))))
5880 (member (assq first-key backends) backends)))))
5881 options))
5882 ;; Otherwise, enter sub-menu.
5883 (t (org-export--dispatch-ui options key expertp)))))
5887 (provide 'ox)
5889 ;; Local variables:
5890 ;; generated-autoload-file: "org-loaddefs.el"
5891 ;; End:
5893 ;;; ox.el ends here