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