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