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