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