ox.el (org-export-define-backend, org-export-define-derived-backend): Use defuns
[org-mode.git] / lisp / ox.el
blob5e1d2e756e926c3ad38e5261ecbf902aa422775c
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.")
300 (defvar org-export-dispatch-last-position (make-marker)
301 "The position where the last export command was created using the dispatcher.
302 This marker will be used with `C-u C-c C-e' to make sure export repetition
303 uses the same subtree if the previous command was restricted to a subtree.")
306 ;;; User-configurable Variables
308 ;; Configuration for the masses.
310 ;; They should never be accessed directly, as their value is to be
311 ;; stored in a property list (cf. `org-export-options-alist').
312 ;; Back-ends will read their value from there instead.
314 (defgroup org-export nil
315 "Options for exporting Org mode files."
316 :tag "Org Export"
317 :group 'org)
319 (defgroup org-export-general nil
320 "General options for export engine."
321 :tag "Org Export General"
322 :group 'org-export)
324 (defcustom org-export-with-archived-trees 'headline
325 "Whether sub-trees with the ARCHIVE tag should be exported.
327 This can have three different values:
328 nil Do not export, pretend this tree is not present.
329 t Do export the entire tree.
330 `headline' Only export the headline, but skip the tree below it.
332 This option can also be set with the #+OPTIONS line,
333 e.g. \"arch:nil\"."
334 :group 'org-export-general
335 :type '(choice
336 (const :tag "Not at all" nil)
337 (const :tag "Headline only" 'headline)
338 (const :tag "Entirely" t)))
340 (defcustom org-export-with-author t
341 "Non-nil means insert author name into the exported file.
342 This option can also be set with the #+OPTIONS line,
343 e.g. \"author:nil\"."
344 :group 'org-export-general
345 :type 'boolean)
347 (defcustom org-export-with-clocks nil
348 "Non-nil means export CLOCK keywords.
349 This option can also be set with the #+OPTIONS line,
350 e.g. \"c:t\"."
351 :group 'org-export-general
352 :type 'boolean)
354 (defcustom org-export-with-creator 'comment
355 "Non-nil means the postamble should contain a creator sentence.
357 The sentence can be set in `org-export-creator-string' and
358 defaults to \"Generated by Org mode XX in Emacs XXX.\".
360 If the value is `comment' insert it as a comment."
361 :group 'org-export-general
362 :type '(choice
363 (const :tag "No creator sentence" nil)
364 (const :tag "Sentence as a comment" 'comment)
365 (const :tag "Insert the sentence" t)))
367 (defcustom org-export-with-date t
368 "Non-nil means insert date in the exported document.
369 This options can also be set with the OPTIONS keyword,
370 e.g. \"date:nil\".")
372 (defcustom org-export-creator-string
373 (format "Generated by Org mode %s in Emacs %s."
374 (if (fboundp 'org-version) (org-version) "(Unknown)")
375 emacs-version)
376 "String to insert at the end of the generated document."
377 :group 'org-export-general
378 :type '(string :tag "Creator string"))
380 (defcustom org-export-with-drawers '(not "LOGBOOK")
381 "Non-nil means export contents of standard drawers.
383 When t, all drawers are exported. This may also be a list of
384 drawer names to export. If that list starts with `not', only
385 drawers with such names will be ignored.
387 This variable doesn't apply to properties drawers.
389 This option can also be set with the #+OPTIONS line,
390 e.g. \"d:nil\"."
391 :group 'org-export-general
392 :version "24.4"
393 :package-version '(Org . "8.0")
394 :type '(choice
395 (const :tag "All drawers" t)
396 (const :tag "None" nil)
397 (repeat :tag "Selected drawers"
398 (string :tag "Drawer name"))
399 (list :tag "Ignored drawers"
400 (const :format "" not)
401 (repeat :tag "Specify names of drawers to ignore during export"
402 :inline t
403 (string :tag "Drawer name")))))
405 (defcustom org-export-with-email nil
406 "Non-nil means insert author email into the exported file.
407 This option can also be set with the #+OPTIONS line,
408 e.g. \"email:t\"."
409 :group 'org-export-general
410 :type 'boolean)
412 (defcustom org-export-with-emphasize t
413 "Non-nil means interpret *word*, /word/, _word_ and +word+.
415 If the export target supports emphasizing text, the word will be
416 typeset in bold, italic, with an underline or strike-through,
417 respectively.
419 This option can also be set with the #+OPTIONS line, e.g. \"*:nil\"."
420 :group 'org-export-general
421 :type 'boolean)
423 (defcustom org-export-exclude-tags '("noexport")
424 "Tags that exclude a tree from export.
426 All trees carrying any of these tags will be excluded from
427 export. This is without condition, so even subtrees inside that
428 carry one of the `org-export-select-tags' will be removed.
430 This option can also be set with the #+EXCLUDE_TAGS: keyword."
431 :group 'org-export-general
432 :type '(repeat (string :tag "Tag")))
434 (defcustom org-export-with-fixed-width t
435 "Non-nil means lines starting with \":\" will be in fixed width font.
437 This can be used to have pre-formatted text, fragments of code
438 etc. For example:
439 : ;; Some Lisp examples
440 : (while (defc cnt)
441 : (ding))
442 will be looking just like this in also HTML. See also the QUOTE
443 keyword. Not all export backends support this.
445 This option can also be set with the #+OPTIONS line, e.g. \"::nil\"."
446 :group 'org-export-general
447 :type 'boolean)
449 (defcustom org-export-with-footnotes t
450 "Non-nil means Org footnotes should be exported.
451 This option can also be set with the #+OPTIONS line,
452 e.g. \"f:nil\"."
453 :group 'org-export-general
454 :type 'boolean)
456 (defcustom org-export-with-latex t
457 "Non-nil means process LaTeX environments and fragments.
459 This option can also be set with the +OPTIONS line,
460 e.g. \"tex:verbatim\". Allowed values are:
462 nil Ignore math snippets.
463 `verbatim' Keep everything in verbatim.
464 t Allow export of math snippets."
465 :group 'org-export-general
466 :version "24.4"
467 :package-version '(Org . "8.0")
468 :type '(choice
469 (const :tag "Do not process math in any way" nil)
470 (const :tag "Interpret math snippets" t)
471 (const :tag "Leave math verbatim" verbatim)))
473 (defcustom org-export-headline-levels 3
474 "The last level which is still exported as a headline.
476 Inferior levels will produce itemize or enumerate lists when
477 exported.
479 This option can also be set with the #+OPTIONS line, e.g. \"H:2\"."
480 :group 'org-export-general
481 :type 'integer)
483 (defcustom org-export-default-language "en"
484 "The default language for export and clocktable translations, as a string.
485 This may have an association in
486 `org-clock-clocktable-language-setup'."
487 :group 'org-export-general
488 :type '(string :tag "Language"))
490 (defcustom org-export-preserve-breaks nil
491 "Non-nil means preserve all line breaks when exporting.
492 This option can also be set with the #+OPTIONS line,
493 e.g. \"\\n:t\"."
494 :group 'org-export-general
495 :type 'boolean)
497 (defcustom org-export-with-entities t
498 "Non-nil means interpret entities when exporting.
500 For example, HTML export converts \\alpha to &alpha; and \\AA to
501 &Aring;.
503 For a list of supported names, see the constant `org-entities'
504 and the user option `org-entities-user'.
506 This option can also be set with the #+OPTIONS line,
507 e.g. \"e:nil\"."
508 :group 'org-export-general
509 :type 'boolean)
511 (defcustom org-export-with-inlinetasks t
512 "Non-nil means inlinetasks should be exported.
513 This option can also be set with the #+OPTIONS line,
514 e.g. \"inline:nil\"."
515 :group 'org-export-general
516 :version "24.4"
517 :package-version '(Org . "8.0")
518 :type 'boolean)
520 (defcustom org-export-with-planning nil
521 "Non-nil means include planning info in export.
522 This option can also be set with the #+OPTIONS: line,
523 e.g. \"p:t\"."
524 :group 'org-export-general
525 :version "24.4"
526 :package-version '(Org . "8.0")
527 :type 'boolean)
529 (defcustom org-export-with-priority nil
530 "Non-nil means include priority cookies in export.
531 This option can also be set with the #+OPTIONS line,
532 e.g. \"pri:t\"."
533 :group 'org-export-general
534 :type 'boolean)
536 (defcustom org-export-with-section-numbers t
537 "Non-nil means add section numbers to headlines when exporting.
539 When set to an integer n, numbering will only happen for
540 headlines whose relative level is higher or equal to n.
542 This option can also be set with the #+OPTIONS line,
543 e.g. \"num:t\"."
544 :group 'org-export-general
545 :type 'boolean)
547 (defcustom org-export-select-tags '("export")
548 "Tags that select a tree for export.
550 If any such tag is found in a buffer, all trees that do not carry
551 one of these tags will be ignored during export. Inside trees
552 that are selected like this, you can still deselect a subtree by
553 tagging it with one of the `org-export-exclude-tags'.
555 This option can also be set with the #+SELECT_TAGS: keyword."
556 :group 'org-export-general
557 :type '(repeat (string :tag "Tag")))
559 (defcustom org-export-with-smart-quotes nil
560 "Non-nil means activate smart quotes during export.
561 This option can also be set with the #+OPTIONS: line,
562 e.g. \"':t\"."
563 :group 'org-export-general
564 :version "24.4"
565 :package-version '(Org . "8.0")
566 :type 'boolean)
568 (defcustom org-export-with-special-strings t
569 "Non-nil means interpret \"\\-\", \"--\" and \"---\" for export.
571 When this option is turned on, these strings will be exported as:
573 Org HTML LaTeX UTF-8
574 -----+----------+--------+-------
575 \\- &shy; \\-
576 -- &ndash; -- –
577 --- &mdash; --- —
578 ... &hellip; \\ldots …
580 This option can also be set with the #+OPTIONS line,
581 e.g. \"-:nil\"."
582 :group 'org-export-general
583 :type 'boolean)
585 (defcustom org-export-with-statistics-cookies t
586 "Non-nil means include statistics cookies in export.
587 This option can also be set with the #+OPTIONS: line,
588 e.g. \"stat:nil\""
589 :group 'org-export-general
590 :version "24.4"
591 :package-version '(Org . "8.0")
592 :type 'boolean)
594 (defcustom org-export-with-sub-superscripts t
595 "Non-nil means interpret \"_\" and \"^\" for export.
597 When this option is turned on, you can use TeX-like syntax for
598 sub- and superscripts. Several characters after \"_\" or \"^\"
599 will be considered as a single item - so grouping with {} is
600 normally not needed. For example, the following things will be
601 parsed as single sub- or superscripts.
603 10^24 or 10^tau several digits will be considered 1 item.
604 10^-12 or 10^-tau a leading sign with digits or a word
605 x^2-y^3 will be read as x^2 - y^3, because items are
606 terminated by almost any nonword/nondigit char.
607 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
609 Still, ambiguity is possible - so when in doubt use {} to enclose
610 the sub/superscript. If you set this variable to the symbol
611 `{}', the braces are *required* in order to trigger
612 interpretations as sub/superscript. This can be helpful in
613 documents that need \"_\" frequently in plain text.
615 This option can also be set with the #+OPTIONS line,
616 e.g. \"^:nil\"."
617 :group 'org-export-general
618 :type '(choice
619 (const :tag "Interpret them" t)
620 (const :tag "Curly brackets only" {})
621 (const :tag "Do not interpret them" nil)))
623 (defcustom org-export-with-toc t
624 "Non-nil means create a table of contents in exported files.
626 The TOC contains headlines with levels up
627 to`org-export-headline-levels'. When an integer, include levels
628 up to N in the toc, this may then be different from
629 `org-export-headline-levels', but it will not be allowed to be
630 larger than the number of headline levels. When nil, no table of
631 contents is made.
633 This option can also be set with the #+OPTIONS line,
634 e.g. \"toc:nil\" or \"toc:3\"."
635 :group 'org-export-general
636 :type '(choice
637 (const :tag "No Table of Contents" nil)
638 (const :tag "Full Table of Contents" t)
639 (integer :tag "TOC to level")))
641 (defcustom org-export-with-tables t
642 "If non-nil, lines starting with \"|\" define a table.
643 For example:
645 | Name | Address | Birthday |
646 |-------------+----------+-----------|
647 | Arthur Dent | England | 29.2.2100 |
649 This option can also be set with the #+OPTIONS line, e.g. \"|:nil\"."
650 :group 'org-export-general
651 :type 'boolean)
653 (defcustom org-export-with-tags t
654 "If nil, do not export tags, just remove them from headlines.
656 If this is the symbol `not-in-toc', tags will be removed from
657 table of contents entries, but still be shown in the headlines of
658 the document.
660 This option can also be set with the #+OPTIONS line,
661 e.g. \"tags:nil\"."
662 :group 'org-export-general
663 :type '(choice
664 (const :tag "Off" nil)
665 (const :tag "Not in TOC" not-in-toc)
666 (const :tag "On" t)))
668 (defcustom org-export-with-tasks t
669 "Non-nil means include TODO items for export.
671 This may have the following values:
672 t include tasks independent of state.
673 `todo' include only tasks that are not yet done.
674 `done' include only tasks that are already done.
675 nil ignore all tasks.
676 list of keywords include tasks with these keywords.
678 This option can also be set with the #+OPTIONS line,
679 e.g. \"tasks:nil\"."
680 :group 'org-export-general
681 :type '(choice
682 (const :tag "All tasks" t)
683 (const :tag "No tasks" nil)
684 (const :tag "Not-done tasks" todo)
685 (const :tag "Only done tasks" done)
686 (repeat :tag "Specific TODO keywords"
687 (string :tag "Keyword"))))
689 (defcustom org-export-time-stamp-file t
690 "Non-nil means insert a time stamp into the exported file.
691 The time stamp shows when the file was created.
693 This option can also be set with the #+OPTIONS line,
694 e.g. \"timestamp:nil\"."
695 :group 'org-export-general
696 :type 'boolean)
698 (defcustom org-export-with-timestamps t
699 "Non nil means allow timestamps in export.
701 It can be set to `active', `inactive', t or nil, in order to
702 export, respectively, only active timestamps, only inactive ones,
703 all of them or none.
705 This option can also be set with the #+OPTIONS line, e.g.
706 \"<:nil\"."
707 :group 'org-export-general
708 :type '(choice
709 (const :tag "All timestamps" t)
710 (const :tag "Only active timestamps" active)
711 (const :tag "Only inactive timestamps" inactive)
712 (const :tag "No timestamp" nil)))
714 (defcustom org-export-with-todo-keywords t
715 "Non-nil means include TODO keywords in export.
716 When nil, remove all these keywords from the export."
717 :group 'org-export-general
718 :type 'boolean)
720 (defcustom org-export-allow-bind-keywords nil
721 "Non-nil means BIND keywords can define local variable values.
722 This is a potential security risk, which is why the default value
723 is nil. You can also allow them through local buffer variables."
724 :group 'org-export-general
725 :version "24.4"
726 :package-version '(Org . "8.0")
727 :type 'boolean)
729 (defcustom org-export-snippet-translation-alist nil
730 "Alist between export snippets back-ends and exporter back-ends.
732 This variable allows to provide shortcuts for export snippets.
734 For example, with a value of '\(\(\"h\" . \"html\"\)\), the
735 HTML back-end will recognize the contents of \"@@h:<b>@@\" as
736 HTML code while every other back-end will ignore it."
737 :group 'org-export-general
738 :version "24.4"
739 :package-version '(Org . "8.0")
740 :type '(repeat
741 (cons (string :tag "Shortcut")
742 (string :tag "Back-end"))))
744 (defcustom org-export-coding-system nil
745 "Coding system for the exported file."
746 :group 'org-export-general
747 :version "24.4"
748 :package-version '(Org . "8.0")
749 :type 'coding-system)
751 (defcustom org-export-copy-to-kill-ring 'if-interactive
752 "Should we push exported content to the kill ring?"
753 :group 'org-export-general
754 :version "24.3"
755 :type '(choice
756 (const :tag "Always" t)
757 (const :tag "When export is done interactively" if-interactive)
758 (const :tag "Never" nil)))
760 (defcustom org-export-initial-scope 'buffer
761 "The initial scope when exporting with `org-export-dispatch'.
762 This variable can be either set to `buffer' or `subtree'."
763 :group 'org-export-general
764 :type '(choice
765 (const :tag "Export current buffer" 'buffer)
766 (const :tag "Export current subtree" 'subtree)))
768 (defcustom org-export-show-temporary-export-buffer t
769 "Non-nil means show buffer after exporting to temp buffer.
770 When Org exports to a file, the buffer visiting that file is ever
771 shown, but remains buried. However, when exporting to
772 a temporary buffer, that buffer is popped up in a second window.
773 When this variable is nil, the buffer remains buried also in
774 these cases."
775 :group 'org-export-general
776 :type 'boolean)
778 (defcustom org-export-in-background nil
779 "Non-nil means export and publishing commands will run in background.
780 Results from an asynchronous export are never displayed
781 automatically. But you can retrieve them with \\[org-export-stack]."
782 :group 'org-export-general
783 :version "24.4"
784 :package-version '(Org . "8.0")
785 :type 'boolean)
787 (defcustom org-export-async-init-file user-init-file
788 "File used to initialize external export process.
789 Value must be an absolute file name. It defaults to user's
790 initialization file. Though, a specific configuration makes the
791 process faster and the export more portable."
792 :group 'org-export-general
793 :version "24.4"
794 :package-version '(Org . "8.0")
795 :type '(file :must-match t))
797 (defcustom org-export-invisible-backends nil
798 "List of back-ends that shouldn't appear in the dispatcher.
800 Any back-end belonging to this list or derived from a back-end
801 belonging to it will not appear in the dispatcher menu.
803 Indeed, Org may require some export back-ends without notice. If
804 these modules are never to be used interactively, adding them
805 here will avoid cluttering the dispatcher menu."
806 :group 'org-export-general
807 :version "24.4"
808 :package-version '(Org . "8.0")
809 :type '(repeat (symbol :tag "Back-End")))
811 (defcustom org-export-dispatch-use-expert-ui nil
812 "Non-nil means using a non-intrusive `org-export-dispatch'.
813 In that case, no help buffer is displayed. Though, an indicator
814 for current export scope is added to the prompt (\"b\" when
815 output is restricted to body only, \"s\" when it is restricted to
816 the current subtree, \"v\" when only visible elements are
817 considered for export, \"f\" when publishing functions should be
818 passed the FORCE argument and \"a\" when the export should be
819 asynchronous). Also, \[?] allows to switch back to standard
820 mode."
821 :group 'org-export-general
822 :version "24.4"
823 :package-version '(Org . "8.0")
824 :type 'boolean)
828 ;;; Defining Back-ends
830 ;; `org-export-define-backend' is the standard way to define an export
831 ;; back-end. It allows to specify translators, filters, buffer
832 ;; options and a menu entry. If the new back-end shares translators
833 ;; with another back-end, `org-export-define-derived-backend' may be
834 ;; used instead.
836 ;; Internally, a back-end is stored as a list, of which CAR is the
837 ;; name of the back-end, as a symbol, and CDR a plist. Accessors to
838 ;; properties of a given back-end are: `org-export-backend-filters',
839 ;; `org-export-backend-menu', `org-export-backend-options' and
840 ;; `org-export-backend-translate-table'.
842 ;; Eventually `org-export-barf-if-invalid-backend' returns an error
843 ;; when a given back-end hasn't been registered yet.
845 (defun org-export-define-backend (backend translators &rest body)
846 "Define a new back-end BACKEND.
848 TRANSLATORS is an alist between object or element types and
849 functions handling them.
851 These functions should return a string without any trailing
852 space, or nil. They must accept three arguments: the object or
853 element itself, its contents or nil when it isn't recursive and
854 the property list used as a communication channel.
856 Contents, when not nil, are stripped from any global indentation
857 \(although the relative one is preserved). They also always end
858 with a single newline character.
860 If, for a given type, no function is found, that element or
861 object type will simply be ignored, along with any blank line or
862 white space at its end. The same will happen if the function
863 returns the nil value. If that function returns the empty
864 string, the type will be ignored, but the blank lines or white
865 spaces will be kept.
867 In addition to element and object types, one function can be
868 associated to the `template' (or `inner-template') symbol and
869 another one to the `plain-text' symbol.
871 The former returns the final transcoded string, and can be used
872 to add a preamble and a postamble to document's body. It must
873 accept two arguments: the transcoded string and the property list
874 containing export options. A function associated to `template'
875 will not be applied if export has option \"body-only\".
876 A function associated to `inner-template' is always applied.
878 The latter, when defined, is to be called on every text not
879 recognized as an element or an object. It must accept two
880 arguments: the text string and the information channel. It is an
881 appropriate place to protect special chars relative to the
882 back-end.
884 BODY can start with pre-defined keyword arguments. The following
885 keywords are understood:
887 :export-block
889 String, or list of strings, representing block names that
890 will not be parsed. This is used to specify blocks that will
891 contain raw code specific to the back-end. These blocks
892 still have to be handled by the relative `export-block' type
893 translator.
895 :filters-alist
897 Alist between filters and function, or list of functions,
898 specific to the back-end. See `org-export-filters-alist' for
899 a list of all allowed filters. Filters defined here
900 shouldn't make a back-end test, as it may prevent back-ends
901 derived from this one to behave properly.
903 :menu-entry
905 Menu entry for the export dispatcher. It should be a list
906 like:
908 '(KEY DESCRIPTION-OR-ORDINAL ACTION-OR-MENU)
910 where :
912 KEY is a free character selecting the back-end.
914 DESCRIPTION-OR-ORDINAL is either a string or a number.
916 If it is a string, is will be used to name the back-end in
917 its menu entry. If it is a number, the following menu will
918 be displayed as a sub-menu of the back-end with the same
919 KEY. Also, the number will be used to determine in which
920 order such sub-menus will appear (lowest first).
922 ACTION-OR-MENU is either a function or an alist.
924 If it is an action, it will be called with four
925 arguments (booleans): ASYNC, SUBTREEP, VISIBLE-ONLY and
926 BODY-ONLY. See `org-export-as' for further explanations on
927 some of them.
929 If it is an alist, associations should follow the
930 pattern:
932 '(KEY DESCRIPTION ACTION)
934 where KEY, DESCRIPTION and ACTION are described above.
936 Valid values include:
938 '(?m \"My Special Back-end\" my-special-export-function)
942 '(?l \"Export to LaTeX\"
943 \(?p \"As PDF file\" org-latex-export-to-pdf)
944 \(?o \"As PDF file and open\"
945 \(lambda (a s v b)
946 \(if a (org-latex-export-to-pdf t s v b)
947 \(org-open-file
948 \(org-latex-export-to-pdf nil s v b)))))))
950 or the following, which will be added to the previous
951 sub-menu,
953 '(?l 1
954 \((?B \"As TEX buffer (Beamer)\" org-beamer-export-as-latex)
955 \(?P \"As PDF file (Beamer)\" org-beamer-export-to-pdf)))
957 :options-alist
959 Alist between back-end specific properties introduced in
960 communication channel and how their value are acquired. See
961 `org-export-options-alist' for more information about
962 structure of the values."
963 (declare (indent 1))
964 (let (export-block filters menu-entry options contents)
965 (while (keywordp (car body))
966 (case (pop body)
967 (:export-block (let ((names (pop body)))
968 (setq export-block
969 (if (consp names) (mapcar 'upcase names)
970 (list (upcase names))))))
971 (:filters-alist (setq filters (pop body)))
972 (:menu-entry (setq menu-entry (pop body)))
973 (:options-alist (setq options (pop body)))
974 (t (pop body))))
975 (setq contents (append (list :translate-alist translators)
976 (and filters (list :filters-alist filters))
977 (and options (list :options-alist options))
978 (and menu-entry (list :menu-entry menu-entry))))
979 ;; Register back-end.
980 (let ((registeredp (assq backend org-export-registered-backends)))
981 (if registeredp (setcdr registeredp contents)
982 (push (cons backend contents) org-export-registered-backends)))
983 ;; Tell parser to not parse EXPORT-BLOCK blocks.
984 (when export-block
985 (mapc
986 (lambda (name)
987 (add-to-list 'org-element-block-name-alist
988 `(,name . org-element-export-block-parser)))
989 export-block))))
991 (defun org-export-define-derived-backend (child parent &rest body)
992 "Create a new back-end as a variant of an existing one.
994 CHILD is the name of the derived back-end. PARENT is the name of
995 the parent back-end.
997 BODY can start with pre-defined keyword arguments. The following
998 keywords are understood:
1000 :export-block
1002 String, or list of strings, representing block names that
1003 will not be parsed. This is used to specify blocks that will
1004 contain raw code specific to the back-end. These blocks
1005 still have to be handled by the relative `export-block' type
1006 translator.
1008 :filters-alist
1010 Alist of filters that will overwrite or complete filters
1011 defined in PARENT back-end. See `org-export-filters-alist'
1012 for a list of allowed filters.
1014 :menu-entry
1016 Menu entry for the export dispatcher. See
1017 `org-export-define-backend' for more information about the
1018 expected value.
1020 :options-alist
1022 Alist of back-end specific properties that will overwrite or
1023 complete those defined in PARENT back-end. Refer to
1024 `org-export-options-alist' for more information about
1025 structure of the values.
1027 :translate-alist
1029 Alist of element and object types and transcoders that will
1030 overwrite or complete transcode table from PARENT back-end.
1031 Refer to `org-export-define-backend' for detailed information
1032 about transcoders.
1034 As an example, here is how one could define \"my-latex\" back-end
1035 as a variant of `latex' back-end with a custom template function:
1037 \(org-export-define-derived-backend 'my-latex 'latex
1038 :translate-alist '((template . my-latex-template-fun)))
1040 The back-end could then be called with, for example:
1042 \(org-export-to-buffer 'my-latex \"*Test my-latex*\")"
1043 (declare (indent 2))
1044 (let (export-block filters menu-entry options translators contents)
1045 (while (keywordp (car body))
1046 (case (pop body)
1047 (:export-block (let ((names (pop body)))
1048 (setq export-block
1049 (if (consp names) (mapcar 'upcase names)
1050 (list (upcase names))))))
1051 (:filters-alist (setq filters (pop body)))
1052 (:menu-entry (setq menu-entry (pop body)))
1053 (:options-alist (setq options (pop body)))
1054 (:translate-alist (setq translators (pop body)))
1055 (t (pop body))))
1056 (setq contents (append
1057 (list :parent parent)
1058 (let ((p-table (org-export-backend-translate-table parent)))
1059 (list :translate-alist (append translators p-table)))
1060 (let ((p-filters (org-export-backend-filters parent)))
1061 (list :filters-alist (append filters p-filters)))
1062 (let ((p-options (org-export-backend-options parent)))
1063 (list :options-alist (append options p-options)))
1064 (and menu-entry (list :menu-entry menu-entry))))
1065 (org-export-barf-if-invalid-backend parent)
1066 ;; Register back-end.
1067 (let ((registeredp (assq child org-export-registered-backends)))
1068 (if registeredp (setcdr registeredp contents)
1069 (push (cons child contents) org-export-registered-backends)))
1070 ;; Tell parser to not parse EXPORT-BLOCK blocks.
1071 (when export-block
1072 (mapc
1073 (lambda (name)
1074 (add-to-list org-element-block-name-alist
1075 `(,name . org-element-export-block-parser)))
1076 export-block))))
1078 (defun org-export-backend-parent (backend)
1079 "Return back-end from which BACKEND is derived, or nil."
1080 (plist-get (cdr (assq backend org-export-registered-backends)) :parent))
1082 (defun org-export-backend-filters (backend)
1083 "Return filters for BACKEND."
1084 (plist-get (cdr (assq backend org-export-registered-backends))
1085 :filters-alist))
1087 (defun org-export-backend-menu (backend)
1088 "Return menu entry for BACKEND."
1089 (plist-get (cdr (assq backend org-export-registered-backends))
1090 :menu-entry))
1092 (defun org-export-backend-options (backend)
1093 "Return export options for BACKEND."
1094 (plist-get (cdr (assq backend org-export-registered-backends))
1095 :options-alist))
1097 (defun org-export-backend-translate-table (backend)
1098 "Return translate table for BACKEND."
1099 (plist-get (cdr (assq backend org-export-registered-backends))
1100 :translate-alist))
1102 (defun org-export-barf-if-invalid-backend (backend)
1103 "Signal an error if BACKEND isn't defined."
1104 (unless (org-export-backend-translate-table backend)
1105 (error "Unknown \"%s\" back-end: Aborting export" backend)))
1107 (defun org-export-derived-backend-p (backend &rest backends)
1108 "Non-nil if BACKEND is derived from one of BACKENDS."
1109 (let ((parent backend))
1110 (while (and (not (memq parent backends))
1111 (setq parent (org-export-backend-parent parent))))
1112 parent))
1116 ;;; The Communication Channel
1118 ;; During export process, every function has access to a number of
1119 ;; properties. They are of two types:
1121 ;; 1. Environment options are collected once at the very beginning of
1122 ;; the process, out of the original buffer and configuration.
1123 ;; Collecting them is handled by `org-export-get-environment'
1124 ;; function.
1126 ;; Most environment options are defined through the
1127 ;; `org-export-options-alist' variable.
1129 ;; 2. Tree properties are extracted directly from the parsed tree,
1130 ;; just before export, by `org-export-collect-tree-properties'.
1132 ;; Here is the full list of properties available during transcode
1133 ;; process, with their category and their value type.
1135 ;; + `:author' :: Author's name.
1136 ;; - category :: option
1137 ;; - type :: string
1139 ;; + `:back-end' :: Current back-end used for transcoding.
1140 ;; - category :: tree
1141 ;; - type :: symbol
1143 ;; + `:creator' :: String to write as creation information.
1144 ;; - category :: option
1145 ;; - type :: string
1147 ;; + `:date' :: String to use as date.
1148 ;; - category :: option
1149 ;; - type :: string
1151 ;; + `:description' :: Description text for the current data.
1152 ;; - category :: option
1153 ;; - type :: string
1155 ;; + `:email' :: Author's email.
1156 ;; - category :: option
1157 ;; - type :: string
1159 ;; + `:exclude-tags' :: Tags for exclusion of subtrees from export
1160 ;; process.
1161 ;; - category :: option
1162 ;; - type :: list of strings
1164 ;; + `:export-options' :: List of export options available for current
1165 ;; process.
1166 ;; - category :: none
1167 ;; - type :: list of symbols, among `subtree', `body-only' and
1168 ;; `visible-only'.
1170 ;; + `:exported-data' :: Hash table used for memoizing
1171 ;; `org-export-data'.
1172 ;; - category :: tree
1173 ;; - type :: hash table
1175 ;; + `:filetags' :: List of global tags for buffer. Used by
1176 ;; `org-export-get-tags' to get tags with inheritance.
1177 ;; - category :: option
1178 ;; - type :: list of strings
1180 ;; + `:footnote-definition-alist' :: Alist between footnote labels and
1181 ;; their definition, as parsed data. Only non-inlined footnotes
1182 ;; are represented in this alist. Also, every definition isn't
1183 ;; guaranteed to be referenced in the parse tree. The purpose of
1184 ;; this property is to preserve definitions from oblivion
1185 ;; (i.e. when the parse tree comes from a part of the original
1186 ;; buffer), it isn't meant for direct use in a back-end. To
1187 ;; retrieve a definition relative to a reference, use
1188 ;; `org-export-get-footnote-definition' instead.
1189 ;; - category :: option
1190 ;; - type :: alist (STRING . LIST)
1192 ;; + `:headline-levels' :: Maximum level being exported as an
1193 ;; headline. Comparison is done with the relative level of
1194 ;; headlines in the parse tree, not necessarily with their
1195 ;; actual level.
1196 ;; - category :: option
1197 ;; - type :: integer
1199 ;; + `:headline-offset' :: Difference between relative and real level
1200 ;; of headlines in the parse tree. For example, a value of -1
1201 ;; means a level 2 headline should be considered as level
1202 ;; 1 (cf. `org-export-get-relative-level').
1203 ;; - category :: tree
1204 ;; - type :: integer
1206 ;; + `:headline-numbering' :: Alist between headlines and their
1207 ;; numbering, as a list of numbers
1208 ;; (cf. `org-export-get-headline-number').
1209 ;; - category :: tree
1210 ;; - type :: alist (INTEGER . LIST)
1212 ;; + `:id-alist' :: Alist between ID strings and destination file's
1213 ;; path, relative to current directory. It is used by
1214 ;; `org-export-resolve-id-link' to resolve ID links targeting an
1215 ;; external file.
1216 ;; - category :: option
1217 ;; - type :: alist (STRING . STRING)
1219 ;; + `:ignore-list' :: List of elements and objects that should be
1220 ;; ignored during export.
1221 ;; - category :: tree
1222 ;; - type :: list of elements and objects
1224 ;; + `:input-file' :: Full path to input file, if any.
1225 ;; - category :: option
1226 ;; - type :: string or nil
1228 ;; + `:keywords' :: List of keywords attached to data.
1229 ;; - category :: option
1230 ;; - type :: string
1232 ;; + `:language' :: Default language used for translations.
1233 ;; - category :: option
1234 ;; - type :: string
1236 ;; + `:parse-tree' :: Whole parse tree, available at any time during
1237 ;; transcoding.
1238 ;; - category :: option
1239 ;; - type :: list (as returned by `org-element-parse-buffer')
1241 ;; + `:preserve-breaks' :: Non-nil means transcoding should preserve
1242 ;; all line breaks.
1243 ;; - category :: option
1244 ;; - type :: symbol (nil, t)
1246 ;; + `:section-numbers' :: Non-nil means transcoding should add
1247 ;; section numbers to headlines.
1248 ;; - category :: option
1249 ;; - type :: symbol (nil, t)
1251 ;; + `:select-tags' :: List of tags enforcing inclusion of sub-trees
1252 ;; in transcoding. When such a tag is present, subtrees without
1253 ;; it are de facto excluded from the process. See
1254 ;; `use-select-tags'.
1255 ;; - category :: option
1256 ;; - type :: list of strings
1258 ;; + `:time-stamp-file' :: Non-nil means transcoding should insert
1259 ;; a time stamp in the output.
1260 ;; - category :: option
1261 ;; - type :: symbol (nil, t)
1263 ;; + `:translate-alist' :: Alist between element and object types and
1264 ;; transcoding functions relative to the current back-end.
1265 ;; Special keys `inner-template', `template' and `plain-text' are
1266 ;; also possible.
1267 ;; - category :: option
1268 ;; - type :: alist (SYMBOL . FUNCTION)
1270 ;; + `:with-archived-trees' :: Non-nil when archived subtrees should
1271 ;; also be transcoded. If it is set to the `headline' symbol,
1272 ;; only the archived headline's name is retained.
1273 ;; - category :: option
1274 ;; - type :: symbol (nil, t, `headline')
1276 ;; + `:with-author' :: Non-nil means author's name should be included
1277 ;; in the output.
1278 ;; - category :: option
1279 ;; - type :: symbol (nil, t)
1281 ;; + `:with-clocks' :: Non-nil means clock keywords should be exported.
1282 ;; - category :: option
1283 ;; - type :: symbol (nil, t)
1285 ;; + `:with-creator' :: Non-nil means a creation sentence should be
1286 ;; inserted at the end of the transcoded string. If the value
1287 ;; is `comment', it should be commented.
1288 ;; - category :: option
1289 ;; - type :: symbol (`comment', nil, t)
1291 ;; + `:with-date' :: Non-nil means output should contain a date.
1292 ;; - category :: option
1293 ;; - type :. symbol (nil, t)
1295 ;; + `:with-drawers' :: Non-nil means drawers should be exported. If
1296 ;; its value is a list of names, only drawers with such names
1297 ;; will be transcoded. If that list starts with `not', drawer
1298 ;; with these names will be skipped.
1299 ;; - category :: option
1300 ;; - type :: symbol (nil, t) or list of strings
1302 ;; + `:with-email' :: Non-nil means output should contain author's
1303 ;; email.
1304 ;; - category :: option
1305 ;; - type :: symbol (nil, t)
1307 ;; + `:with-emphasize' :: Non-nil means emphasized text should be
1308 ;; interpreted.
1309 ;; - category :: option
1310 ;; - type :: symbol (nil, t)
1312 ;; + `:with-fixed-width' :: Non-nil if transcoder should interpret
1313 ;; strings starting with a colon as a fixed-with (verbatim) area.
1314 ;; - category :: option
1315 ;; - type :: symbol (nil, t)
1317 ;; + `:with-footnotes' :: Non-nil if transcoder should interpret
1318 ;; footnotes.
1319 ;; - category :: option
1320 ;; - type :: symbol (nil, t)
1322 ;; + `:with-latex' :: Non-nil means `latex-environment' elements and
1323 ;; `latex-fragment' objects should appear in export output. When
1324 ;; this property is set to `verbatim', they will be left as-is.
1325 ;; - category :: option
1326 ;; - type :: symbol (`verbatim', nil, t)
1328 ;; + `:with-plannings' :: Non-nil means transcoding should include
1329 ;; planning info.
1330 ;; - category :: option
1331 ;; - type :: symbol (nil, t)
1333 ;; + `:with-priority' :: Non-nil means transcoding should include
1334 ;; priority cookies.
1335 ;; - category :: option
1336 ;; - type :: symbol (nil, t)
1338 ;; + `:with-smart-quotes' :: Non-nil means activate smart quotes in
1339 ;; plain text.
1340 ;; - category :: option
1341 ;; - type :: symbol (nil, t)
1343 ;; + `:with-special-strings' :: Non-nil means transcoding should
1344 ;; interpret special strings in plain text.
1345 ;; - category :: option
1346 ;; - type :: symbol (nil, t)
1348 ;; + `:with-sub-superscript' :: Non-nil means transcoding should
1349 ;; interpret subscript and superscript. With a value of "{}",
1350 ;; only interpret those using curly brackets.
1351 ;; - category :: option
1352 ;; - type :: symbol (nil, {}, t)
1354 ;; + `:with-tables' :: Non-nil means transcoding should interpret
1355 ;; tables.
1356 ;; - category :: option
1357 ;; - type :: symbol (nil, t)
1359 ;; + `:with-tags' :: Non-nil means transcoding should keep tags in
1360 ;; headlines. A `not-in-toc' value will remove them from the
1361 ;; table of contents, if any, nonetheless.
1362 ;; - category :: option
1363 ;; - type :: symbol (nil, t, `not-in-toc')
1365 ;; + `:with-tasks' :: Non-nil means transcoding should include
1366 ;; headlines with a TODO keyword. A `todo' value will only
1367 ;; include headlines with a todo type keyword while a `done'
1368 ;; value will do the contrary. If a list of strings is provided,
1369 ;; only tasks with keywords belonging to that list will be kept.
1370 ;; - category :: option
1371 ;; - type :: symbol (t, todo, done, nil) or list of strings
1373 ;; + `:with-timestamps' :: Non-nil means transcoding should include
1374 ;; time stamps. Special value `active' (resp. `inactive') ask to
1375 ;; export only active (resp. inactive) timestamps. Otherwise,
1376 ;; completely remove them.
1377 ;; - category :: option
1378 ;; - type :: symbol: (`active', `inactive', t, nil)
1380 ;; + `:with-toc' :: Non-nil means that a table of contents has to be
1381 ;; added to the output. An integer value limits its depth.
1382 ;; - category :: option
1383 ;; - type :: symbol (nil, t or integer)
1385 ;; + `:with-todo-keywords' :: Non-nil means transcoding should
1386 ;; include TODO keywords.
1387 ;; - category :: option
1388 ;; - type :: symbol (nil, t)
1391 ;;;; Environment Options
1393 ;; Environment options encompass all parameters defined outside the
1394 ;; scope of the parsed data. They come from five sources, in
1395 ;; increasing precedence order:
1397 ;; - Global variables,
1398 ;; - Buffer's attributes,
1399 ;; - Options keyword symbols,
1400 ;; - Buffer keywords,
1401 ;; - Subtree properties.
1403 ;; The central internal function with regards to environment options
1404 ;; is `org-export-get-environment'. It updates global variables with
1405 ;; "#+BIND:" keywords, then retrieve and prioritize properties from
1406 ;; the different sources.
1408 ;; The internal functions doing the retrieval are:
1409 ;; `org-export--get-global-options',
1410 ;; `org-export--get-buffer-attributes',
1411 ;; `org-export--parse-option-keyword',
1412 ;; `org-export--get-subtree-options' and
1413 ;; `org-export--get-inbuffer-options'
1415 ;; Also, `org-export--install-letbind-maybe' takes care of the part
1416 ;; relative to "#+BIND:" keywords.
1418 (defun org-export-get-environment (&optional backend subtreep ext-plist)
1419 "Collect export options from the current buffer.
1421 Optional argument BACKEND is a symbol specifying which back-end
1422 specific options to read, if any.
1424 When optional argument SUBTREEP is non-nil, assume the export is
1425 done against the current sub-tree.
1427 Third optional argument EXT-PLIST is a property list with
1428 external parameters overriding Org default settings, but still
1429 inferior to file-local settings."
1430 ;; First install #+BIND variables.
1431 (org-export--install-letbind-maybe)
1432 ;; Get and prioritize export options...
1433 (org-combine-plists
1434 ;; ... from global variables...
1435 (org-export--get-global-options backend)
1436 ;; ... from an external property list...
1437 ext-plist
1438 ;; ... from in-buffer settings...
1439 (org-export--get-inbuffer-options backend)
1440 ;; ... and from subtree, when appropriate.
1441 (and subtreep (org-export--get-subtree-options backend))
1442 ;; Eventually add misc. properties.
1443 (list
1444 :back-end
1445 backend
1446 :translate-alist
1447 (org-export-backend-translate-table backend)
1448 :footnote-definition-alist
1449 ;; Footnotes definitions must be collected in the original
1450 ;; buffer, as there's no insurance that they will still be in
1451 ;; the parse tree, due to possible narrowing.
1452 (let (alist)
1453 (org-with-wide-buffer
1454 (goto-char (point-min))
1455 (while (re-search-forward org-footnote-definition-re nil t)
1456 (let ((def (save-match-data (org-element-at-point))))
1457 (when (eq (org-element-type def) 'footnote-definition)
1458 (push
1459 (cons (org-element-property :label def)
1460 (let ((cbeg (org-element-property :contents-begin def)))
1461 (when cbeg
1462 (org-element--parse-elements
1463 cbeg (org-element-property :contents-end def)
1464 nil nil nil nil (list 'org-data nil)))))
1465 alist))))
1466 alist))
1467 :id-alist
1468 ;; Collect id references.
1469 (let (alist)
1470 (org-with-wide-buffer
1471 (goto-char (point-min))
1472 (while (re-search-forward "\\[\\[id:\\S-+?\\]" nil t)
1473 (let ((link (org-element-context)))
1474 (when (eq (org-element-type link) 'link)
1475 (let* ((id (org-element-property :path link))
1476 (file (org-id-find-id-file id)))
1477 (when file
1478 (push (cons id (file-relative-name file)) alist)))))))
1479 alist))))
1481 (defun org-export--parse-option-keyword (options &optional backend)
1482 "Parse an OPTIONS line and return values as a plist.
1483 Optional argument BACKEND is a symbol specifying which back-end
1484 specific items to read, if any."
1485 (let* ((all
1486 ;; Priority is given to back-end specific options.
1487 (append (and backend (org-export-backend-options backend))
1488 org-export-options-alist))
1489 plist)
1490 (dolist (option all)
1491 (let ((property (car option))
1492 (item (nth 2 option)))
1493 (when (and item
1494 (not (plist-member plist property))
1495 (string-match (concat "\\(\\`\\|[ \t]\\)"
1496 (regexp-quote item)
1497 ":\\(([^)\n]+)\\|[^ \t\n\r;,.]*\\)")
1498 options))
1499 (setq plist (plist-put plist
1500 property
1501 (car (read-from-string
1502 (match-string 2 options))))))))
1503 plist))
1505 (defun org-export--get-subtree-options (&optional backend)
1506 "Get export options in subtree at point.
1507 Optional argument BACKEND is a symbol specifying back-end used
1508 for export. Return options as a plist."
1509 ;; For each buffer keyword, create a headline property setting the
1510 ;; same property in communication channel. The name for the property
1511 ;; is the keyword with "EXPORT_" appended to it.
1512 (org-with-wide-buffer
1513 (let (prop plist)
1514 ;; Make sure point is at an heading.
1515 (if (org-at-heading-p) (org-up-heading-safe) (org-back-to-heading t))
1516 ;; Take care of EXPORT_TITLE. If it isn't defined, use headline's
1517 ;; title as its fallback value.
1518 (when (setq prop (or (org-entry-get (point) "EXPORT_TITLE")
1519 (progn (looking-at org-todo-line-regexp)
1520 (org-match-string-no-properties 3))))
1521 (setq plist
1522 (plist-put
1523 plist :title
1524 (org-element-parse-secondary-string
1525 prop (org-element-restriction 'keyword)))))
1526 ;; EXPORT_OPTIONS are parsed in a non-standard way.
1527 (when (setq prop (org-entry-get (point) "EXPORT_OPTIONS"))
1528 (setq plist
1529 (nconc plist (org-export--parse-option-keyword prop backend))))
1530 ;; Handle other keywords. TITLE keyword is excluded as it has
1531 ;; been handled already.
1532 (let ((seen '("TITLE")))
1533 (mapc
1534 (lambda (option)
1535 (let ((property (car option))
1536 (keyword (nth 1 option)))
1537 (when (and keyword (not (member keyword seen)))
1538 (let* ((subtree-prop (concat "EXPORT_" keyword))
1539 ;; Export properties are not case-sensitive.
1540 (value (let ((case-fold-search t))
1541 (org-entry-get (point) subtree-prop))))
1542 (push keyword seen)
1543 (when (and value (not (plist-member plist property)))
1544 (setq plist
1545 (plist-put
1546 plist
1547 property
1548 (cond
1549 ;; Parse VALUE if required.
1550 ((member keyword org-element-document-properties)
1551 (org-element-parse-secondary-string
1552 value (org-element-restriction 'keyword)))
1553 ;; If BEHAVIOUR is `split' expected value is
1554 ;; a list of strings, not a string.
1555 ((eq (nth 4 option) 'split) (org-split-string value))
1556 (t value)))))))))
1557 ;; Look for both general keywords and back-end specific
1558 ;; options, with priority given to the latter.
1559 (append (and backend (org-export-backend-options backend))
1560 org-export-options-alist)))
1561 ;; Return value.
1562 plist)))
1564 (defun org-export--get-inbuffer-options (&optional backend)
1565 "Return current buffer export options, as a plist.
1567 Optional argument BACKEND, when non-nil, is a symbol specifying
1568 which back-end specific options should also be read in the
1569 process.
1571 Assume buffer is in Org mode. Narrowing, if any, is ignored."
1572 (let* (plist
1573 get-options ; For byte-compiler.
1574 (case-fold-search t)
1575 (options (append
1576 ;; Priority is given to back-end specific options.
1577 (and backend (org-export-backend-options backend))
1578 org-export-options-alist))
1579 (regexp (format "^[ \t]*#\\+%s:"
1580 (regexp-opt (nconc (delq nil (mapcar 'cadr options))
1581 org-export-special-keywords))))
1582 (find-opt
1583 (lambda (keyword)
1584 ;; Return property name associated to KEYWORD.
1585 (catch 'exit
1586 (mapc (lambda (option)
1587 (when (equal (nth 1 option) keyword)
1588 (throw 'exit (car option))))
1589 options))))
1590 (get-options
1591 (lambda (&optional files plist)
1592 ;; Recursively read keywords in buffer. FILES is a list
1593 ;; of files read so far. PLIST is the current property
1594 ;; list obtained.
1595 (org-with-wide-buffer
1596 (goto-char (point-min))
1597 (while (re-search-forward regexp nil t)
1598 (let ((element (org-element-at-point)))
1599 (when (eq (org-element-type element) 'keyword)
1600 (let ((key (org-element-property :key element))
1601 (val (org-element-property :value element)))
1602 (cond
1603 ;; Options in `org-export-special-keywords'.
1604 ((equal key "SETUPFILE")
1605 (let ((file (expand-file-name
1606 (org-remove-double-quotes (org-trim val)))))
1607 ;; Avoid circular dependencies.
1608 (unless (member file files)
1609 (with-temp-buffer
1610 (insert (org-file-contents file 'noerror))
1611 (org-mode)
1612 (setq plist (funcall get-options
1613 (cons file files) plist))))))
1614 ((equal key "OPTIONS")
1615 (setq plist
1616 (org-combine-plists
1617 plist
1618 (org-export--parse-option-keyword val backend))))
1619 ((equal key "FILETAGS")
1620 (setq plist
1621 (org-combine-plists
1622 plist
1623 (list :filetags
1624 (org-uniquify
1625 (append (org-split-string val ":")
1626 (plist-get plist :filetags)))))))
1628 ;; Options in `org-export-options-alist'.
1629 (let* ((prop (funcall find-opt key))
1630 (behaviour (nth 4 (assq prop options))))
1631 (setq plist
1632 (plist-put
1633 plist prop
1634 ;; Handle value depending on specified
1635 ;; BEHAVIOUR.
1636 (case behaviour
1637 (space
1638 (if (not (plist-get plist prop))
1639 (org-trim val)
1640 (concat (plist-get plist prop)
1642 (org-trim val))))
1643 (newline
1644 (org-trim (concat (plist-get plist prop)
1645 "\n"
1646 (org-trim val))))
1647 (split `(,@(plist-get plist prop)
1648 ,@(org-split-string val)))
1649 ('t val)
1650 (otherwise
1651 (if (not (plist-member plist prop)) val
1652 (plist-get plist prop)))))))))))))
1653 ;; Return final value.
1654 plist))))
1655 ;; Read options in the current buffer.
1656 (setq plist (funcall get-options buffer-file-name nil))
1657 ;; Parse keywords specified in `org-element-document-properties'.
1658 (mapc (lambda (keyword)
1659 ;; Find the property associated to the keyword.
1660 (let* ((prop (funcall find-opt keyword))
1661 (value (and prop (plist-get plist prop))))
1662 (when (stringp value)
1663 (setq plist
1664 (plist-put plist prop
1665 (org-element-parse-secondary-string
1666 value (org-element-restriction 'keyword)))))))
1667 org-element-document-properties)
1668 ;; Return value.
1669 plist))
1671 (defun org-export--get-buffer-attributes ()
1672 "Return properties related to buffer attributes, as a plist."
1673 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
1674 (list
1675 ;; Store full path of input file name, or nil. For internal use.
1676 :input-file visited-file
1677 :title (or (and visited-file
1678 (file-name-sans-extension
1679 (file-name-nondirectory visited-file)))
1680 (buffer-name (buffer-base-buffer))))))
1682 (defun org-export--get-global-options (&optional backend)
1683 "Return global export options as a plist.
1685 Optional argument BACKEND, if non-nil, is a symbol specifying
1686 which back-end specific export options should also be read in the
1687 process."
1688 (let ((all
1689 ;; Priority is given to back-end specific options.
1690 (append (and backend (org-export-backend-options backend))
1691 org-export-options-alist))
1692 plist)
1693 (mapc
1694 (lambda (cell)
1695 (let ((prop (car cell)))
1696 (unless (plist-member plist prop)
1697 (setq plist
1698 (plist-put
1699 plist
1700 prop
1701 ;; Eval default value provided. If keyword is a member
1702 ;; of `org-element-document-properties', parse it as
1703 ;; a secondary string before storing it.
1704 (let ((value (eval (nth 3 cell))))
1705 (if (not (stringp value)) value
1706 (let ((keyword (nth 1 cell)))
1707 (if (not (member keyword org-element-document-properties))
1708 value
1709 (org-element-parse-secondary-string
1710 value (org-element-restriction 'keyword)))))))))))
1711 all)
1712 ;; Return value.
1713 plist))
1715 (defun org-export--install-letbind-maybe ()
1716 "Install the values from #+BIND lines as local variables.
1717 Variables must be installed before in-buffer options are
1718 retrieved."
1719 (when org-export-allow-bind-keywords
1720 (let ((case-fold-search t) letbind)
1721 (org-with-wide-buffer
1722 (goto-char (point-min))
1723 (while (re-search-forward "^[ \t]*#\\+BIND:" nil t)
1724 (let* ((element (org-element-at-point))
1725 (value (org-element-property :value element)))
1726 (when (and (eq (org-element-type element) 'keyword)
1727 (not (equal value "")))
1728 (push (read (format "(%s)" value)) letbind)))))
1729 (dolist (pair (nreverse letbind))
1730 (org-set-local (car pair) (nth 1 pair))))))
1733 ;;;; Tree Properties
1735 ;; Tree properties are information extracted from parse tree. They
1736 ;; are initialized at the beginning of the transcoding process by
1737 ;; `org-export-collect-tree-properties'.
1739 ;; Dedicated functions focus on computing the value of specific tree
1740 ;; properties during initialization. Thus,
1741 ;; `org-export--populate-ignore-list' lists elements and objects that
1742 ;; should be skipped during export, `org-export--get-min-level' gets
1743 ;; the minimal exportable level, used as a basis to compute relative
1744 ;; level for headlines. Eventually
1745 ;; `org-export--collect-headline-numbering' builds an alist between
1746 ;; headlines and their numbering.
1748 (defun org-export-collect-tree-properties (data info)
1749 "Extract tree properties from parse tree.
1751 DATA is the parse tree from which information is retrieved. INFO
1752 is a list holding export options.
1754 Following tree properties are set or updated:
1756 `:exported-data' Hash table used to memoize results from
1757 `org-export-data'.
1759 `:footnote-definition-alist' List of footnotes definitions in
1760 original buffer and current parse tree.
1762 `:headline-offset' Offset between true level of headlines and
1763 local level. An offset of -1 means a headline
1764 of level 2 should be considered as a level
1765 1 headline in the context.
1767 `:headline-numbering' Alist of all headlines as key an the
1768 associated numbering as value.
1770 `:ignore-list' List of elements that should be ignored during
1771 export.
1773 Return updated plist."
1774 ;; Install the parse tree in the communication channel, in order to
1775 ;; use `org-export-get-genealogy' and al.
1776 (setq info (plist-put info :parse-tree data))
1777 ;; Get the list of elements and objects to ignore, and put it into
1778 ;; `:ignore-list'. Do not overwrite any user ignore that might have
1779 ;; been done during parse tree filtering.
1780 (setq info
1781 (plist-put info
1782 :ignore-list
1783 (append (org-export--populate-ignore-list data info)
1784 (plist-get info :ignore-list))))
1785 ;; Compute `:headline-offset' in order to be able to use
1786 ;; `org-export-get-relative-level'.
1787 (setq info
1788 (plist-put info
1789 :headline-offset
1790 (- 1 (org-export--get-min-level data info))))
1791 ;; Update footnotes definitions list with definitions in parse tree.
1792 ;; This is required since buffer expansion might have modified
1793 ;; boundaries of footnote definitions contained in the parse tree.
1794 ;; This way, definitions in `footnote-definition-alist' are bound to
1795 ;; match those in the parse tree.
1796 (let ((defs (plist-get info :footnote-definition-alist)))
1797 (org-element-map data 'footnote-definition
1798 (lambda (fn)
1799 (push (cons (org-element-property :label fn)
1800 `(org-data nil ,@(org-element-contents fn)))
1801 defs)))
1802 (setq info (plist-put info :footnote-definition-alist defs)))
1803 ;; Properties order doesn't matter: get the rest of the tree
1804 ;; properties.
1805 (nconc
1806 `(:headline-numbering ,(org-export--collect-headline-numbering data info)
1807 :exported-data ,(make-hash-table :test 'eq :size 4001))
1808 info))
1810 (defun org-export--get-min-level (data options)
1811 "Return minimum exportable headline's level in DATA.
1812 DATA is parsed tree as returned by `org-element-parse-buffer'.
1813 OPTIONS is a plist holding export options."
1814 (catch 'exit
1815 (let ((min-level 10000))
1816 (mapc
1817 (lambda (blob)
1818 (when (and (eq (org-element-type blob) 'headline)
1819 (not (org-element-property :footnote-section-p blob))
1820 (not (memq blob (plist-get options :ignore-list))))
1821 (setq min-level (min (org-element-property :level blob) min-level)))
1822 (when (= min-level 1) (throw 'exit 1)))
1823 (org-element-contents data))
1824 ;; If no headline was found, for the sake of consistency, set
1825 ;; minimum level to 1 nonetheless.
1826 (if (= min-level 10000) 1 min-level))))
1828 (defun org-export--collect-headline-numbering (data options)
1829 "Return numbering of all exportable headlines in a parse tree.
1831 DATA is the parse tree. OPTIONS is the plist holding export
1832 options.
1834 Return an alist whose key is a headline and value is its
1835 associated numbering \(in the shape of a list of numbers\) or nil
1836 for a footnotes section."
1837 (let ((numbering (make-vector org-export-max-depth 0)))
1838 (org-element-map data 'headline
1839 (lambda (headline)
1840 (unless (org-element-property :footnote-section-p headline)
1841 (let ((relative-level
1842 (1- (org-export-get-relative-level headline options))))
1843 (cons
1844 headline
1845 (loop for n across numbering
1846 for idx from 0 to org-export-max-depth
1847 when (< idx relative-level) collect n
1848 when (= idx relative-level) collect (aset numbering idx (1+ n))
1849 when (> idx relative-level) do (aset numbering idx 0))))))
1850 options)))
1852 (defun org-export--populate-ignore-list (data options)
1853 "Return list of elements and objects to ignore during export.
1854 DATA is the parse tree to traverse. OPTIONS is the plist holding
1855 export options."
1856 (let* (ignore
1857 walk-data
1858 ;; First find trees containing a select tag, if any.
1859 (selected (org-export--selected-trees data options))
1860 (walk-data
1861 (lambda (data)
1862 ;; Collect ignored elements or objects into IGNORE-LIST.
1863 (let ((type (org-element-type data)))
1864 (if (org-export--skip-p data options selected) (push data ignore)
1865 (if (and (eq type 'headline)
1866 (eq (plist-get options :with-archived-trees) 'headline)
1867 (org-element-property :archivedp data))
1868 ;; If headline is archived but tree below has
1869 ;; to be skipped, add it to ignore list.
1870 (mapc (lambda (e) (push e ignore))
1871 (org-element-contents data))
1872 ;; Move into secondary string, if any.
1873 (let ((sec-prop
1874 (cdr (assq type org-element-secondary-value-alist))))
1875 (when sec-prop
1876 (mapc walk-data (org-element-property sec-prop data))))
1877 ;; Move into recursive objects/elements.
1878 (mapc walk-data (org-element-contents data))))))))
1879 ;; Main call.
1880 (funcall walk-data data)
1881 ;; Return value.
1882 ignore))
1884 (defun org-export--selected-trees (data info)
1885 "Return list of headlines and inlinetasks with a select tag in their tree.
1886 DATA is parsed data as returned by `org-element-parse-buffer'.
1887 INFO is a plist holding export options."
1888 (let* (selected-trees
1889 walk-data ; For byte-compiler.
1890 (walk-data
1891 (function
1892 (lambda (data genealogy)
1893 (let ((type (org-element-type data)))
1894 (cond
1895 ((memq type '(headline inlinetask))
1896 (let ((tags (org-element-property :tags data)))
1897 (if (loop for tag in (plist-get info :select-tags)
1898 thereis (member tag tags))
1899 ;; When a select tag is found, mark full
1900 ;; genealogy and every headline within the tree
1901 ;; as acceptable.
1902 (setq selected-trees
1903 (append
1904 genealogy
1905 (org-element-map data '(headline inlinetask)
1906 'identity)
1907 selected-trees))
1908 ;; If at a headline, continue searching in tree,
1909 ;; recursively.
1910 (when (eq type 'headline)
1911 (mapc (lambda (el)
1912 (funcall walk-data el (cons data genealogy)))
1913 (org-element-contents data))))))
1914 ((or (eq type 'org-data)
1915 (memq type org-element-greater-elements))
1916 (mapc (lambda (el) (funcall walk-data el genealogy))
1917 (org-element-contents data)))))))))
1918 (funcall walk-data data nil)
1919 selected-trees))
1921 (defun org-export--skip-p (blob options selected)
1922 "Non-nil when element or object BLOB should be skipped during export.
1923 OPTIONS is the plist holding export options. SELECTED, when
1924 non-nil, is a list of headlines or inlinetasks belonging to
1925 a tree with a select tag."
1926 (case (org-element-type blob)
1927 (clock (not (plist-get options :with-clocks)))
1928 (drawer
1929 (let ((with-drawers-p (plist-get options :with-drawers)))
1930 (or (not with-drawers-p)
1931 (and (consp with-drawers-p)
1932 ;; If `:with-drawers' value starts with `not', ignore
1933 ;; every drawer whose name belong to that list.
1934 ;; Otherwise, ignore drawers whose name isn't in that
1935 ;; list.
1936 (let ((name (org-element-property :drawer-name blob)))
1937 (if (eq (car with-drawers-p) 'not)
1938 (member-ignore-case name (cdr with-drawers-p))
1939 (not (member-ignore-case name with-drawers-p))))))))
1940 ((headline inlinetask)
1941 (let ((with-tasks (plist-get options :with-tasks))
1942 (todo (org-element-property :todo-keyword blob))
1943 (todo-type (org-element-property :todo-type blob))
1944 (archived (plist-get options :with-archived-trees))
1945 (tags (org-element-property :tags blob)))
1947 (and (eq (org-element-type blob) 'inlinetask)
1948 (not (plist-get options :with-inlinetasks)))
1949 ;; Ignore subtrees with an exclude tag.
1950 (loop for k in (plist-get options :exclude-tags)
1951 thereis (member k tags))
1952 ;; When a select tag is present in the buffer, ignore any tree
1953 ;; without it.
1954 (and selected (not (memq blob selected)))
1955 ;; Ignore commented sub-trees.
1956 (org-element-property :commentedp blob)
1957 ;; Ignore archived subtrees if `:with-archived-trees' is nil.
1958 (and (not archived) (org-element-property :archivedp blob))
1959 ;; Ignore tasks, if specified by `:with-tasks' property.
1960 (and todo
1961 (or (not with-tasks)
1962 (and (memq with-tasks '(todo done))
1963 (not (eq todo-type with-tasks)))
1964 (and (consp with-tasks) (not (member todo with-tasks))))))))
1965 ((latex-environment latex-fragment) (not (plist-get options :with-latex)))
1966 (planning (not (plist-get options :with-plannings)))
1967 (statistics-cookie (not (plist-get options :with-statistics-cookies)))
1968 (table-cell
1969 (and (org-export-table-has-special-column-p
1970 (org-export-get-parent-table blob))
1971 (not (org-export-get-previous-element blob options))))
1972 (table-row (org-export-table-row-is-special-p blob options))
1973 (timestamp
1974 (case (plist-get options :with-timestamps)
1975 ;; No timestamp allowed.
1976 ('nil t)
1977 ;; Only active timestamps allowed and the current one isn't
1978 ;; active.
1979 (active
1980 (not (memq (org-element-property :type blob)
1981 '(active active-range))))
1982 ;; Only inactive timestamps allowed and the current one isn't
1983 ;; inactive.
1984 (inactive
1985 (not (memq (org-element-property :type blob)
1986 '(inactive inactive-range))))))))
1989 ;;; The Transcoder
1991 ;; `org-export-data' reads a parse tree (obtained with, i.e.
1992 ;; `org-element-parse-buffer') and transcodes it into a specified
1993 ;; back-end output. It takes care of filtering out elements or
1994 ;; objects according to export options and organizing the output blank
1995 ;; lines and white space are preserved. The function memoizes its
1996 ;; results, so it is cheap to call it within translators.
1998 ;; It is possible to modify locally the back-end used by
1999 ;; `org-export-data' or even use a temporary back-end by using
2000 ;; `org-export-data-with-translations' and
2001 ;; `org-export-data-with-backend'.
2003 ;; Internally, three functions handle the filtering of objects and
2004 ;; elements during the export. In particular,
2005 ;; `org-export-ignore-element' marks an element or object so future
2006 ;; parse tree traversals skip it, `org-export--interpret-p' tells which
2007 ;; elements or objects should be seen as real Org syntax and
2008 ;; `org-export-expand' transforms the others back into their original
2009 ;; shape
2011 ;; `org-export-transcoder' is an accessor returning appropriate
2012 ;; translator function for a given element or object.
2014 (defun org-export-transcoder (blob info)
2015 "Return appropriate transcoder for BLOB.
2016 INFO is a plist containing export directives."
2017 (let ((type (org-element-type blob)))
2018 ;; Return contents only for complete parse trees.
2019 (if (eq type 'org-data) (lambda (blob contents info) contents)
2020 (let ((transcoder (cdr (assq type (plist-get info :translate-alist)))))
2021 (and (functionp transcoder) transcoder)))))
2023 (defun org-export-data (data info)
2024 "Convert DATA into current back-end format.
2026 DATA is a parse tree, an element or an object or a secondary
2027 string. INFO is a plist holding export options.
2029 Return transcoded string."
2030 (let ((memo (gethash data (plist-get info :exported-data) 'no-memo)))
2031 (if (not (eq memo 'no-memo)) memo
2032 (let* ((type (org-element-type data))
2033 (results
2034 (cond
2035 ;; Ignored element/object.
2036 ((memq data (plist-get info :ignore-list)) nil)
2037 ;; Plain text.
2038 ((eq type 'plain-text)
2039 (org-export-filter-apply-functions
2040 (plist-get info :filter-plain-text)
2041 (let ((transcoder (org-export-transcoder data info)))
2042 (if transcoder (funcall transcoder data info) data))
2043 info))
2044 ;; Uninterpreted element/object: change it back to Org
2045 ;; syntax and export again resulting raw string.
2046 ((not (org-export--interpret-p data info))
2047 (org-export-data
2048 (org-export-expand
2049 data
2050 (mapconcat (lambda (blob) (org-export-data blob info))
2051 (org-element-contents data)
2052 ""))
2053 info))
2054 ;; Secondary string.
2055 ((not type)
2056 (mapconcat (lambda (obj) (org-export-data obj info)) data ""))
2057 ;; Element/Object without contents or, as a special case,
2058 ;; headline with archive tag and archived trees restricted
2059 ;; to title only.
2060 ((or (not (org-element-contents data))
2061 (and (eq type 'headline)
2062 (eq (plist-get info :with-archived-trees) 'headline)
2063 (org-element-property :archivedp data)))
2064 (let ((transcoder (org-export-transcoder data info)))
2065 (and (functionp transcoder)
2066 (funcall transcoder data nil info))))
2067 ;; Element/Object with contents.
2069 (let ((transcoder (org-export-transcoder data info)))
2070 (when transcoder
2071 (let* ((greaterp (memq type org-element-greater-elements))
2072 (objectp
2073 (and (not greaterp)
2074 (memq type org-element-recursive-objects)))
2075 (contents
2076 (mapconcat
2077 (lambda (element) (org-export-data element info))
2078 (org-element-contents
2079 (if (or greaterp objectp) data
2080 ;; Elements directly containing objects
2081 ;; must have their indentation normalized
2082 ;; first.
2083 (org-element-normalize-contents
2084 data
2085 ;; When normalizing contents of the first
2086 ;; paragraph in an item or a footnote
2087 ;; definition, ignore first line's
2088 ;; indentation: there is none and it
2089 ;; might be misleading.
2090 (when (eq type 'paragraph)
2091 (let ((parent (org-export-get-parent data)))
2092 (and
2093 (eq (car (org-element-contents parent))
2094 data)
2095 (memq (org-element-type parent)
2096 '(footnote-definition item))))))))
2097 "")))
2098 (funcall transcoder data
2099 (if (not greaterp) contents
2100 (org-element-normalize-string contents))
2101 info))))))))
2102 ;; Final result will be memoized before being returned.
2103 (puthash
2104 data
2105 (cond
2106 ((not results) nil)
2107 ((memq type '(org-data plain-text nil)) results)
2108 ;; Append the same white space between elements or objects as in
2109 ;; the original buffer, and call appropriate filters.
2111 (let ((results
2112 (org-export-filter-apply-functions
2113 (plist-get info (intern (format ":filter-%s" type)))
2114 (let ((post-blank (or (org-element-property :post-blank data)
2115 0)))
2116 (if (memq type org-element-all-elements)
2117 (concat (org-element-normalize-string results)
2118 (make-string post-blank ?\n))
2119 (concat results (make-string post-blank ? ))))
2120 info)))
2121 results)))
2122 (plist-get info :exported-data))))))
2124 (defun org-export-data-with-translations (data translations info)
2125 "Convert DATA into another format using a given translation table.
2126 DATA is an element, an object, a secondary string or a string.
2127 TRANSLATIONS is an alist between element or object types and
2128 a functions handling them. See `org-export-define-backend' for
2129 more information. INFO is a plist used as a communication
2130 channel."
2131 (org-export-data
2132 data
2133 ;; Set-up a new communication channel with TRANSLATIONS as the
2134 ;; translate table and a new hash table for memoization.
2135 (org-combine-plists
2136 info
2137 (list :translate-alist translations
2138 ;; Size of the hash table is reduced since this function
2139 ;; will probably be used on short trees.
2140 :exported-data (make-hash-table :test 'eq :size 401)))))
2142 (defun org-export-data-with-backend (data backend info)
2143 "Convert DATA into BACKEND format.
2145 DATA is an element, an object, a secondary string or a string.
2146 BACKEND is a symbol. INFO is a plist used as a communication
2147 channel.
2149 Unlike to `org-export-with-backend', this function will
2150 recursively convert DATA using BACKEND translation table."
2151 (org-export-barf-if-invalid-backend backend)
2152 (org-export-data-with-translations
2153 data (org-export-backend-translate-table backend) info))
2155 (defun org-export--interpret-p (blob info)
2156 "Non-nil if element or object BLOB should be interpreted during export.
2157 If nil, BLOB will appear as raw Org syntax. Check is done
2158 according to export options INFO, stored as a plist."
2159 (case (org-element-type blob)
2160 ;; ... entities...
2161 (entity (plist-get info :with-entities))
2162 ;; ... emphasis...
2163 ((bold italic strike-through underline)
2164 (plist-get info :with-emphasize))
2165 ;; ... fixed-width areas.
2166 (fixed-width (plist-get info :with-fixed-width))
2167 ;; ... footnotes...
2168 ((footnote-definition footnote-reference)
2169 (plist-get info :with-footnotes))
2170 ;; ... LaTeX environments and fragments...
2171 ((latex-environment latex-fragment)
2172 (let ((with-latex-p (plist-get info :with-latex)))
2173 (and with-latex-p (not (eq with-latex-p 'verbatim)))))
2174 ;; ... sub/superscripts...
2175 ((subscript superscript)
2176 (let ((sub/super-p (plist-get info :with-sub-superscript)))
2177 (if (eq sub/super-p '{})
2178 (org-element-property :use-brackets-p blob)
2179 sub/super-p)))
2180 ;; ... tables...
2181 (table (plist-get info :with-tables))
2182 (otherwise t)))
2184 (defun org-export-expand (blob contents)
2185 "Expand a parsed element or object to its original state.
2186 BLOB is either an element or an object. CONTENTS is its
2187 contents, as a string or nil."
2188 (funcall
2189 (intern (format "org-element-%s-interpreter" (org-element-type blob)))
2190 blob contents))
2192 (defun org-export-ignore-element (element info)
2193 "Add ELEMENT to `:ignore-list' in INFO.
2195 Any element in `:ignore-list' will be skipped when using
2196 `org-element-map'. INFO is modified by side effects."
2197 (plist-put info :ignore-list (cons element (plist-get info :ignore-list))))
2201 ;;; The Filter System
2203 ;; Filters allow end-users to tweak easily the transcoded output.
2204 ;; They are the functional counterpart of hooks, as every filter in
2205 ;; a set is applied to the return value of the previous one.
2207 ;; Every set is back-end agnostic. Although, a filter is always
2208 ;; called, in addition to the string it applies to, with the back-end
2209 ;; used as argument, so it's easy for the end-user to add back-end
2210 ;; specific filters in the set. The communication channel, as
2211 ;; a plist, is required as the third argument.
2213 ;; From the developer side, filters sets can be installed in the
2214 ;; process with the help of `org-export-define-backend', which
2215 ;; internally stores filters as an alist. Each association has a key
2216 ;; among the following symbols and a function or a list of functions
2217 ;; as value.
2219 ;; - `:filter-options' applies to the property list containing export
2220 ;; options. Unlike to other filters, functions in this list accept
2221 ;; two arguments instead of three: the property list containing
2222 ;; export options and the back-end. Users can set its value through
2223 ;; `org-export-filter-options-functions' variable.
2225 ;; - `:filter-parse-tree' applies directly to the complete parsed
2226 ;; tree. Users can set it through
2227 ;; `org-export-filter-parse-tree-functions' variable.
2229 ;; - `:filter-final-output' applies to the final transcoded string.
2230 ;; Users can set it with `org-export-filter-final-output-functions'
2231 ;; variable
2233 ;; - `:filter-plain-text' applies to any string not recognized as Org
2234 ;; syntax. `org-export-filter-plain-text-functions' allows users to
2235 ;; configure it.
2237 ;; - `:filter-TYPE' applies on the string returned after an element or
2238 ;; object of type TYPE has been transcoded. An user can modify
2239 ;; `org-export-filter-TYPE-functions'
2241 ;; All filters sets are applied with
2242 ;; `org-export-filter-apply-functions' function. Filters in a set are
2243 ;; applied in a LIFO fashion. It allows developers to be sure that
2244 ;; their filters will be applied first.
2246 ;; Filters properties are installed in communication channel with
2247 ;; `org-export-install-filters' function.
2249 ;; Eventually, two hooks (`org-export-before-processing-hook' and
2250 ;; `org-export-before-parsing-hook') are run at the beginning of the
2251 ;; export process and just before parsing to allow for heavy structure
2252 ;; modifications.
2255 ;;;; Hooks
2257 (defvar org-export-before-processing-hook nil
2258 "Hook run at the beginning of the export process.
2260 This is run before include keywords and macros are expanded and
2261 Babel code blocks executed, on a copy of the original buffer
2262 being exported. Visibility and narrowing are preserved. Point
2263 is at the beginning of the buffer.
2265 Every function in this hook will be called with one argument: the
2266 back-end currently used, as a symbol.")
2268 (defvar org-export-before-parsing-hook nil
2269 "Hook run before parsing an export buffer.
2271 This is run after include keywords and macros have been expanded
2272 and Babel code blocks executed, on a copy of the original buffer
2273 being exported. Visibility and narrowing are preserved. Point
2274 is at the beginning of the buffer.
2276 Every function in this hook will be called with one argument: the
2277 back-end currently used, as a symbol.")
2280 ;;;; Special Filters
2282 (defvar org-export-filter-options-functions nil
2283 "List of functions applied to the export options.
2284 Each filter is called with two arguments: the export options, as
2285 a plist, and the back-end, as a symbol. It must return
2286 a property list containing export options.")
2288 (defvar org-export-filter-parse-tree-functions nil
2289 "List of functions applied to the parsed tree.
2290 Each filter is called with three arguments: the parse tree, as
2291 returned by `org-element-parse-buffer', the back-end, as
2292 a symbol, and the communication channel, as a plist. It must
2293 return the modified parse tree to transcode.")
2295 (defvar org-export-filter-plain-text-functions nil
2296 "List of functions applied to plain text.
2297 Each filter is called with three arguments: a string which
2298 contains no Org syntax, the back-end, as a symbol, and the
2299 communication channel, as a plist. It must return a string or
2300 nil.")
2302 (defvar org-export-filter-final-output-functions nil
2303 "List of functions applied to the transcoded string.
2304 Each filter is called with three arguments: the full transcoded
2305 string, the back-end, as a symbol, and the communication channel,
2306 as a plist. It must return a string that will be used as the
2307 final export output.")
2310 ;;;; Elements Filters
2312 (defvar org-export-filter-babel-call-functions nil
2313 "List of functions applied to a transcoded babel-call.
2314 Each filter is called with three arguments: the transcoded data,
2315 as a string, the back-end, as a symbol, and the communication
2316 channel, as a plist. It must return a string or nil.")
2318 (defvar org-export-filter-center-block-functions nil
2319 "List of functions applied to a transcoded center block.
2320 Each filter is called with three arguments: the transcoded data,
2321 as a string, the back-end, as a symbol, and the communication
2322 channel, as a plist. It must return a string or nil.")
2324 (defvar org-export-filter-clock-functions nil
2325 "List of functions applied to a transcoded clock.
2326 Each filter is called with three arguments: the transcoded data,
2327 as a string, the back-end, as a symbol, and the communication
2328 channel, as a plist. It must return a string or nil.")
2330 (defvar org-export-filter-comment-functions nil
2331 "List of functions applied to a transcoded comment.
2332 Each filter is called with three arguments: the transcoded data,
2333 as a string, the back-end, as a symbol, and the communication
2334 channel, as a plist. It must return a string or nil.")
2336 (defvar org-export-filter-comment-block-functions nil
2337 "List of functions applied to a transcoded comment-block.
2338 Each filter is called with three arguments: the transcoded data,
2339 as a string, the back-end, as a symbol, and the communication
2340 channel, as a plist. It must return a string or nil.")
2342 (defvar org-export-filter-diary-sexp-functions nil
2343 "List of functions applied to a transcoded diary-sexp.
2344 Each filter is called with three arguments: the transcoded data,
2345 as a string, the back-end, as a symbol, and the communication
2346 channel, as a plist. It must return a string or nil.")
2348 (defvar org-export-filter-drawer-functions nil
2349 "List of functions applied to a transcoded drawer.
2350 Each filter is called with three arguments: the transcoded data,
2351 as a string, the back-end, as a symbol, and the communication
2352 channel, as a plist. It must return a string or nil.")
2354 (defvar org-export-filter-dynamic-block-functions nil
2355 "List of functions applied to a transcoded dynamic-block.
2356 Each filter is called with three arguments: the transcoded data,
2357 as a string, the back-end, as a symbol, and the communication
2358 channel, as a plist. It must return a string or nil.")
2360 (defvar org-export-filter-example-block-functions nil
2361 "List of functions applied to a transcoded example-block.
2362 Each filter is called with three arguments: the transcoded data,
2363 as a string, the back-end, as a symbol, and the communication
2364 channel, as a plist. It must return a string or nil.")
2366 (defvar org-export-filter-export-block-functions nil
2367 "List of functions applied to a transcoded export-block.
2368 Each filter is called with three arguments: the transcoded data,
2369 as a string, the back-end, as a symbol, and the communication
2370 channel, as a plist. It must return a string or nil.")
2372 (defvar org-export-filter-fixed-width-functions nil
2373 "List of functions applied to a transcoded fixed-width.
2374 Each filter is called with three arguments: the transcoded data,
2375 as a string, the back-end, as a symbol, and the communication
2376 channel, as a plist. It must return a string or nil.")
2378 (defvar org-export-filter-footnote-definition-functions nil
2379 "List of functions applied to a transcoded footnote-definition.
2380 Each filter is called with three arguments: the transcoded data,
2381 as a string, the back-end, as a symbol, and the communication
2382 channel, as a plist. It must return a string or nil.")
2384 (defvar org-export-filter-headline-functions nil
2385 "List of functions applied to a transcoded headline.
2386 Each filter is called with three arguments: the transcoded data,
2387 as a string, the back-end, as a symbol, and the communication
2388 channel, as a plist. It must return a string or nil.")
2390 (defvar org-export-filter-horizontal-rule-functions nil
2391 "List of functions applied to a transcoded horizontal-rule.
2392 Each filter is called with three arguments: the transcoded data,
2393 as a string, the back-end, as a symbol, and the communication
2394 channel, as a plist. It must return a string or nil.")
2396 (defvar org-export-filter-inlinetask-functions nil
2397 "List of functions applied to a transcoded inlinetask.
2398 Each filter is called with three arguments: the transcoded data,
2399 as a string, the back-end, as a symbol, and the communication
2400 channel, as a plist. It must return a string or nil.")
2402 (defvar org-export-filter-item-functions nil
2403 "List of functions applied to a transcoded item.
2404 Each filter is called with three arguments: the transcoded data,
2405 as a string, the back-end, as a symbol, and the communication
2406 channel, as a plist. It must return a string or nil.")
2408 (defvar org-export-filter-keyword-functions nil
2409 "List of functions applied to a transcoded keyword.
2410 Each filter is called with three arguments: the transcoded data,
2411 as a string, the back-end, as a symbol, and the communication
2412 channel, as a plist. It must return a string or nil.")
2414 (defvar org-export-filter-latex-environment-functions nil
2415 "List of functions applied to a transcoded latex-environment.
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-node-property-functions nil
2421 "List of functions applied to a transcoded node-property.
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-paragraph-functions nil
2427 "List of functions applied to a transcoded paragraph.
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-plain-list-functions nil
2433 "List of functions applied to a transcoded plain-list.
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-planning-functions nil
2439 "List of functions applied to a transcoded planning.
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-property-drawer-functions nil
2445 "List of functions applied to a transcoded property-drawer.
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-quote-block-functions nil
2451 "List of functions applied to a transcoded quote block.
2452 Each filter is called with three arguments: the transcoded quote
2453 data, as a string, the back-end, as a symbol, and the
2454 communication channel, as a plist. It must return a string or
2455 nil.")
2457 (defvar org-export-filter-quote-section-functions nil
2458 "List of functions applied to a transcoded quote-section.
2459 Each filter is called with three arguments: the transcoded data,
2460 as a string, the back-end, as a symbol, and the communication
2461 channel, as a plist. It must return a string or nil.")
2463 (defvar org-export-filter-section-functions nil
2464 "List of functions applied to a transcoded section.
2465 Each filter is called with three arguments: the transcoded data,
2466 as a string, the back-end, as a symbol, and the communication
2467 channel, as a plist. It must return a string or nil.")
2469 (defvar org-export-filter-special-block-functions nil
2470 "List of functions applied to a transcoded special block.
2471 Each filter is called with three arguments: the transcoded data,
2472 as a string, the back-end, as a symbol, and the communication
2473 channel, as a plist. It must return a string or nil.")
2475 (defvar org-export-filter-src-block-functions nil
2476 "List of functions applied to a transcoded src-block.
2477 Each filter is called with three arguments: the transcoded data,
2478 as a string, the back-end, as a symbol, and the communication
2479 channel, as a plist. It must return a string or nil.")
2481 (defvar org-export-filter-table-functions nil
2482 "List of functions applied to a transcoded table.
2483 Each filter is called with three arguments: the transcoded data,
2484 as a string, the back-end, as a symbol, and the communication
2485 channel, as a plist. It must return a string or nil.")
2487 (defvar org-export-filter-table-cell-functions nil
2488 "List of functions applied to a transcoded table-cell.
2489 Each filter is called with three arguments: the transcoded data,
2490 as a string, the back-end, as a symbol, and the communication
2491 channel, as a plist. It must return a string or nil.")
2493 (defvar org-export-filter-table-row-functions nil
2494 "List of functions applied to a transcoded table-row.
2495 Each filter is called with three arguments: the transcoded data,
2496 as a string, the back-end, as a symbol, and the communication
2497 channel, as a plist. It must return a string or nil.")
2499 (defvar org-export-filter-verse-block-functions nil
2500 "List of functions applied to a transcoded verse block.
2501 Each filter is called with three arguments: the transcoded data,
2502 as a string, the back-end, as a symbol, and the communication
2503 channel, as a plist. It must return a string or nil.")
2506 ;;;; Objects Filters
2508 (defvar org-export-filter-bold-functions nil
2509 "List of functions applied to transcoded bold text.
2510 Each filter is called with three arguments: the transcoded data,
2511 as a string, the back-end, as a symbol, and the communication
2512 channel, as a plist. It must return a string or nil.")
2514 (defvar org-export-filter-code-functions nil
2515 "List of functions applied to transcoded code text.
2516 Each filter is called with three arguments: the transcoded data,
2517 as a string, the back-end, as a symbol, and the communication
2518 channel, as a plist. It must return a string or nil.")
2520 (defvar org-export-filter-entity-functions nil
2521 "List of functions applied to a transcoded entity.
2522 Each filter is called with three arguments: the transcoded data,
2523 as a string, the back-end, as a symbol, and the communication
2524 channel, as a plist. It must return a string or nil.")
2526 (defvar org-export-filter-export-snippet-functions nil
2527 "List of functions applied to a transcoded export-snippet.
2528 Each filter is called with three arguments: the transcoded data,
2529 as a string, the back-end, as a symbol, and the communication
2530 channel, as a plist. It must return a string or nil.")
2532 (defvar org-export-filter-footnote-reference-functions nil
2533 "List of functions applied to a transcoded footnote-reference.
2534 Each filter is called with three arguments: the transcoded data,
2535 as a string, the back-end, as a symbol, and the communication
2536 channel, as a plist. It must return a string or nil.")
2538 (defvar org-export-filter-inline-babel-call-functions nil
2539 "List of functions applied to a transcoded inline-babel-call.
2540 Each filter is called with three arguments: the transcoded data,
2541 as a string, the back-end, as a symbol, and the communication
2542 channel, as a plist. It must return a string or nil.")
2544 (defvar org-export-filter-inline-src-block-functions nil
2545 "List of functions applied to a transcoded inline-src-block.
2546 Each filter is called with three arguments: the transcoded data,
2547 as a string, the back-end, as a symbol, and the communication
2548 channel, as a plist. It must return a string or nil.")
2550 (defvar org-export-filter-italic-functions nil
2551 "List of functions applied to transcoded italic text.
2552 Each filter is called with three arguments: the transcoded data,
2553 as a string, the back-end, as a symbol, and the communication
2554 channel, as a plist. It must return a string or nil.")
2556 (defvar org-export-filter-latex-fragment-functions nil
2557 "List of functions applied to a transcoded latex-fragment.
2558 Each filter is called with three arguments: the transcoded data,
2559 as a string, the back-end, as a symbol, and the communication
2560 channel, as a plist. It must return a string or nil.")
2562 (defvar org-export-filter-line-break-functions nil
2563 "List of functions applied to a transcoded line-break.
2564 Each filter is called with three arguments: the transcoded data,
2565 as a string, the back-end, as a symbol, and the communication
2566 channel, as a plist. It must return a string or nil.")
2568 (defvar org-export-filter-link-functions nil
2569 "List of functions applied to a transcoded link.
2570 Each filter is called with three arguments: the transcoded data,
2571 as a string, the back-end, as a symbol, and the communication
2572 channel, as a plist. It must return a string or nil.")
2574 (defvar org-export-filter-macro-functions nil
2575 "List of functions applied to a transcoded macro.
2576 Each filter is called with three arguments: the transcoded data,
2577 as a string, the back-end, as a symbol, and the communication
2578 channel, as a plist. It must return a string or nil.")
2580 (defvar org-export-filter-radio-target-functions nil
2581 "List of functions applied to a transcoded radio-target.
2582 Each filter is called with three arguments: the transcoded data,
2583 as a string, the back-end, as a symbol, and the communication
2584 channel, as a plist. It must return a string or nil.")
2586 (defvar org-export-filter-statistics-cookie-functions nil
2587 "List of functions applied to a transcoded statistics-cookie.
2588 Each filter is called with three arguments: the transcoded data,
2589 as a string, the back-end, as a symbol, and the communication
2590 channel, as a plist. It must return a string or nil.")
2592 (defvar org-export-filter-strike-through-functions nil
2593 "List of functions applied to transcoded strike-through text.
2594 Each filter is called with three arguments: the transcoded data,
2595 as a string, the back-end, as a symbol, and the communication
2596 channel, as a plist. It must return a string or nil.")
2598 (defvar org-export-filter-subscript-functions nil
2599 "List of functions applied to a transcoded subscript.
2600 Each filter is called with three arguments: the transcoded data,
2601 as a string, the back-end, as a symbol, and the communication
2602 channel, as a plist. It must return a string or nil.")
2604 (defvar org-export-filter-superscript-functions nil
2605 "List of functions applied to a transcoded superscript.
2606 Each filter is called with three arguments: the transcoded data,
2607 as a string, the back-end, as a symbol, and the communication
2608 channel, as a plist. It must return a string or nil.")
2610 (defvar org-export-filter-target-functions nil
2611 "List of functions applied to a transcoded target.
2612 Each filter is called with three arguments: the transcoded data,
2613 as a string, the back-end, as a symbol, and the communication
2614 channel, as a plist. It must return a string or nil.")
2616 (defvar org-export-filter-timestamp-functions nil
2617 "List of functions applied to a transcoded timestamp.
2618 Each filter is called with three arguments: the transcoded data,
2619 as a string, the back-end, as a symbol, and the communication
2620 channel, as a plist. It must return a string or nil.")
2622 (defvar org-export-filter-underline-functions nil
2623 "List of functions applied to transcoded underline text.
2624 Each filter is called with three arguments: the transcoded data,
2625 as a string, the back-end, as a symbol, and the communication
2626 channel, as a plist. It must return a string or nil.")
2628 (defvar org-export-filter-verbatim-functions nil
2629 "List of functions applied to transcoded verbatim text.
2630 Each filter is called with three arguments: the transcoded data,
2631 as a string, the back-end, as a symbol, and the communication
2632 channel, as a plist. It must return a string or nil.")
2635 ;;;; Filters Tools
2637 ;; Internal function `org-export-install-filters' installs filters
2638 ;; hard-coded in back-ends (developer filters) and filters from global
2639 ;; variables (user filters) in the communication channel.
2641 ;; Internal function `org-export-filter-apply-functions' takes care
2642 ;; about applying each filter in order to a given data. It ignores
2643 ;; filters returning a nil value but stops whenever a filter returns
2644 ;; an empty string.
2646 (defun org-export-filter-apply-functions (filters value info)
2647 "Call every function in FILTERS.
2649 Functions are called with arguments VALUE, current export
2650 back-end and INFO. A function returning a nil value will be
2651 skipped. If it returns the empty string, the process ends and
2652 VALUE is ignored.
2654 Call is done in a LIFO fashion, to be sure that developer
2655 specified filters, if any, are called first."
2656 (catch 'exit
2657 (dolist (filter filters value)
2658 (let ((result (funcall filter value (plist-get info :back-end) info)))
2659 (cond ((not result) value)
2660 ((equal value "") (throw 'exit nil))
2661 (t (setq value result)))))))
2663 (defun org-export-install-filters (info)
2664 "Install filters properties in communication channel.
2665 INFO is a plist containing the current communication channel.
2666 Return the updated communication channel."
2667 (let (plist)
2668 ;; Install user-defined filters with `org-export-filters-alist'
2669 ;; and filters already in INFO (through ext-plist mechanism).
2670 (mapc (lambda (p)
2671 (let* ((prop (car p))
2672 (info-value (plist-get info prop))
2673 (default-value (symbol-value (cdr p))))
2674 (setq plist
2675 (plist-put plist prop
2676 ;; Filters in INFO will be called
2677 ;; before those user provided.
2678 (append (if (listp info-value) info-value
2679 (list info-value))
2680 default-value)))))
2681 org-export-filters-alist)
2682 ;; Prepend back-end specific filters to that list.
2683 (mapc (lambda (p)
2684 ;; Single values get consed, lists are appended.
2685 (let ((key (car p)) (value (cdr p)))
2686 (when value
2687 (setq plist
2688 (plist-put
2689 plist key
2690 (if (atom value) (cons value (plist-get plist key))
2691 (append value (plist-get plist key))))))))
2692 (org-export-backend-filters (plist-get info :back-end)))
2693 ;; Return new communication channel.
2694 (org-combine-plists info plist)))
2698 ;;; Core functions
2700 ;; This is the room for the main function, `org-export-as', along with
2701 ;; its derivatives, `org-export-to-buffer', `org-export-to-file' and
2702 ;; `org-export-string-as'. They differ either by the way they output
2703 ;; the resulting code (for the first two) or by the input type (for
2704 ;; the latter).
2706 ;; `org-export-output-file-name' is an auxiliary function meant to be
2707 ;; used with `org-export-to-file'. With a given extension, it tries
2708 ;; to provide a canonical file name to write export output to.
2710 ;; Note that `org-export-as' doesn't really parse the current buffer,
2711 ;; but a copy of it (with the same buffer-local variables and
2712 ;; visibility), where macros and include keywords are expanded and
2713 ;; Babel blocks are executed, if appropriate.
2714 ;; `org-export-with-buffer-copy' macro prepares that copy.
2716 ;; File inclusion is taken care of by
2717 ;; `org-export-expand-include-keyword' and
2718 ;; `org-export--prepare-file-contents'. Structure wise, including
2719 ;; a whole Org file in a buffer often makes little sense. For
2720 ;; example, if the file contains a headline and the include keyword
2721 ;; was within an item, the item should contain the headline. That's
2722 ;; why file inclusion should be done before any structure can be
2723 ;; associated to the file, that is before parsing.
2725 (defun org-export-copy-buffer ()
2726 "Return a copy of the current buffer.
2727 The copy preserves Org buffer-local variables, visibility and
2728 narrowing."
2729 (let ((copy-buffer-fun (org-export--generate-copy-script (current-buffer)))
2730 (new-buf (generate-new-buffer (buffer-name))))
2731 (with-current-buffer new-buf
2732 (funcall copy-buffer-fun)
2733 (set-buffer-modified-p nil))
2734 new-buf))
2736 (defmacro org-export-with-buffer-copy (&rest body)
2737 "Apply BODY in a copy of the current buffer.
2738 The copy preserves local variables, visibility and contents of
2739 the original buffer. Point is at the beginning of the buffer
2740 when BODY is applied."
2741 (declare (debug t))
2742 (org-with-gensyms (buf-copy)
2743 `(let ((,buf-copy (org-export-copy-buffer)))
2744 (unwind-protect
2745 (with-current-buffer ,buf-copy
2746 (goto-char (point-min))
2747 (progn ,@body))
2748 (and (buffer-live-p ,buf-copy)
2749 ;; Kill copy without confirmation.
2750 (progn (with-current-buffer ,buf-copy
2751 (restore-buffer-modified-p nil))
2752 (kill-buffer ,buf-copy)))))))
2754 (defun org-export--generate-copy-script (buffer)
2755 "Generate a function duplicating BUFFER.
2757 The copy will preserve local variables, visibility, contents and
2758 narrowing of the original buffer. If a region was active in
2759 BUFFER, contents will be narrowed to that region instead.
2761 The resulting function can be evaled at a later time, from
2762 another buffer, effectively cloning the original buffer there.
2764 The function assumes BUFFER's major mode is `org-mode'."
2765 (with-current-buffer buffer
2766 `(lambda ()
2767 (let ((inhibit-modification-hooks t))
2768 ;; Set major mode. Ignore `org-mode-hook' as it has been run
2769 ;; already in BUFFER.
2770 (let ((org-mode-hook nil)) (org-mode))
2771 ;; Buffer local variables.
2772 ,@(let (local-vars)
2773 (mapc
2774 (lambda (entry)
2775 (when (consp entry)
2776 (let ((var (car entry))
2777 (val (cdr entry)))
2778 (and (not (eq var 'org-font-lock-keywords))
2779 (or (memq var
2780 '(default-directory
2781 buffer-file-name
2782 buffer-file-coding-system))
2783 (string-match "^\\(org-\\|orgtbl-\\)"
2784 (symbol-name var)))
2785 ;; Skip unreadable values, as they cannot be
2786 ;; sent to external process.
2787 (or (not val) (ignore-errors (read (format "%S" val))))
2788 (push `(set (make-local-variable (quote ,var))
2789 (quote ,val))
2790 local-vars)))))
2791 (buffer-local-variables (buffer-base-buffer)))
2792 local-vars)
2793 ;; Whole buffer contents.
2794 (insert
2795 ,(org-with-wide-buffer
2796 (buffer-substring-no-properties
2797 (point-min) (point-max))))
2798 ;; Narrowing.
2799 ,(if (org-region-active-p)
2800 `(narrow-to-region ,(region-beginning) ,(region-end))
2801 `(narrow-to-region ,(point-min) ,(point-max)))
2802 ;; Current position of point.
2803 (goto-char ,(point))
2804 ;; Overlays with invisible property.
2805 ,@(let (ov-set)
2806 (mapc
2807 (lambda (ov)
2808 (let ((invis-prop (overlay-get ov 'invisible)))
2809 (when invis-prop
2810 (push `(overlay-put
2811 (make-overlay ,(overlay-start ov)
2812 ,(overlay-end ov))
2813 'invisible (quote ,invis-prop))
2814 ov-set))))
2815 (overlays-in (point-min) (point-max)))
2816 ov-set)))))
2818 ;;;###autoload
2819 (defun org-export-as
2820 (backend &optional subtreep visible-only body-only ext-plist)
2821 "Transcode current Org buffer into BACKEND code.
2823 If narrowing is active in the current buffer, only transcode its
2824 narrowed part.
2826 If a region is active, transcode that region.
2828 When optional argument SUBTREEP is non-nil, transcode the
2829 sub-tree at point, extracting information from the headline
2830 properties first.
2832 When optional argument VISIBLE-ONLY is non-nil, don't export
2833 contents of hidden elements.
2835 When optional argument BODY-ONLY is non-nil, only return body
2836 code, without surrounding template.
2838 Optional argument EXT-PLIST, when provided, is a property list
2839 with external parameters overriding Org default settings, but
2840 still inferior to file-local settings.
2842 Return code as a string."
2843 (org-export-barf-if-invalid-backend backend)
2844 (save-excursion
2845 (save-restriction
2846 ;; Narrow buffer to an appropriate region or subtree for
2847 ;; parsing. If parsing subtree, be sure to remove main headline
2848 ;; too.
2849 (cond ((org-region-active-p)
2850 (narrow-to-region (region-beginning) (region-end)))
2851 (subtreep
2852 (org-narrow-to-subtree)
2853 (goto-char (point-min))
2854 (forward-line)
2855 (narrow-to-region (point) (point-max))))
2856 ;; Initialize communication channel with original buffer
2857 ;; attributes, unavailable in its copy.
2858 (let ((info (org-combine-plists
2859 (list :export-options
2860 (delq nil
2861 (list (and subtreep 'subtree)
2862 (and visible-only 'visible-only)
2863 (and body-only 'body-only))))
2864 (org-export--get-buffer-attributes)))
2865 tree)
2866 ;; Update communication channel and get parse tree. Buffer
2867 ;; isn't parsed directly. Instead, a temporary copy is
2868 ;; created, where include keywords, macros are expanded and
2869 ;; code blocks are evaluated.
2870 (org-export-with-buffer-copy
2871 ;; Run first hook with current back-end as argument.
2872 (run-hook-with-args 'org-export-before-processing-hook backend)
2873 (org-export-expand-include-keyword)
2874 ;; Update macro templates since #+INCLUDE keywords might have
2875 ;; added some new ones.
2876 (org-macro-initialize-templates)
2877 (org-macro-replace-all org-macro-templates)
2878 (org-export-execute-babel-code)
2879 ;; Update radio targets since keyword inclusion might have
2880 ;; added some more.
2881 (org-update-radio-target-regexp)
2882 ;; Run last hook with current back-end as argument.
2883 (goto-char (point-min))
2884 (run-hook-with-args 'org-export-before-parsing-hook backend)
2885 ;; Update communication channel with environment. Also
2886 ;; install user's and developer's filters.
2887 (setq info
2888 (org-export-install-filters
2889 (org-combine-plists
2890 info (org-export-get-environment backend subtreep ext-plist))))
2891 ;; Expand export-specific set of macros: {{{author}}},
2892 ;; {{{date}}}, {{{email}}} and {{{title}}}. It must be done
2893 ;; once regular macros have been expanded, since document
2894 ;; keywords may contain one of them.
2895 (org-macro-replace-all
2896 (list (cons "author"
2897 (org-element-interpret-data (plist-get info :author)))
2898 (cons "date"
2899 (org-element-interpret-data (plist-get info :date)))
2900 ;; EMAIL is not a parsed keyword: store it as-is.
2901 (cons "email" (or (plist-get info :email) ""))
2902 (cons "title"
2903 (org-element-interpret-data (plist-get info :title)))))
2904 ;; Call options filters and update export options. We do not
2905 ;; use `org-export-filter-apply-functions' here since the
2906 ;; arity of such filters is different.
2907 (dolist (filter (plist-get info :filter-options))
2908 (let ((result (funcall filter info backend)))
2909 (when result (setq info result))))
2910 ;; Parse buffer and call parse-tree filter on it.
2911 (setq tree
2912 (org-export-filter-apply-functions
2913 (plist-get info :filter-parse-tree)
2914 (org-element-parse-buffer nil visible-only) info))
2915 ;; Now tree is complete, compute its properties and add them
2916 ;; to communication channel.
2917 (setq info
2918 (org-combine-plists
2919 info (org-export-collect-tree-properties tree info)))
2920 ;; Eventually transcode TREE. Wrap the resulting string into
2921 ;; a template.
2922 (let* ((body (org-element-normalize-string
2923 (or (org-export-data tree info) "")))
2924 (inner-template (cdr (assq 'inner-template
2925 (plist-get info :translate-alist))))
2926 (full-body (if (not (functionp inner-template)) body
2927 (funcall inner-template body info)))
2928 (template (cdr (assq 'template
2929 (plist-get info :translate-alist)))))
2930 ;; Remove all text properties since they cannot be
2931 ;; retrieved from an external process. Finally call
2932 ;; final-output filter and return result.
2933 (org-no-properties
2934 (org-export-filter-apply-functions
2935 (plist-get info :filter-final-output)
2936 (if (or (not (functionp template)) body-only) full-body
2937 (funcall template full-body info))
2938 info))))))))
2940 ;;;###autoload
2941 (defun org-export-to-buffer
2942 (backend buffer &optional subtreep visible-only body-only ext-plist)
2943 "Call `org-export-as' with output to a specified buffer.
2945 BACKEND is the back-end used for transcoding, as a symbol.
2947 BUFFER is the output buffer. If it already exists, it will be
2948 erased first, otherwise, it will be created.
2950 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
2951 EXT-PLIST are similar to those used in `org-export-as', which
2952 see.
2954 Depending on `org-export-copy-to-kill-ring', add buffer contents
2955 to kill ring. Return buffer."
2956 (let ((out (org-export-as backend subtreep visible-only body-only ext-plist))
2957 (buffer (get-buffer-create buffer)))
2958 (with-current-buffer buffer
2959 (erase-buffer)
2960 (insert out)
2961 (goto-char (point-min)))
2962 ;; Maybe add buffer contents to kill ring.
2963 (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p out))
2964 (org-kill-new out))
2965 ;; Return buffer.
2966 buffer))
2968 ;;;###autoload
2969 (defun org-export-to-file
2970 (backend file &optional subtreep visible-only body-only ext-plist)
2971 "Call `org-export-as' with output to a specified file.
2973 BACKEND is the back-end used for transcoding, as a symbol. FILE
2974 is the name of the output file, as a string.
2976 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
2977 EXT-PLIST are similar to those used in `org-export-as', which
2978 see.
2980 Depending on `org-export-copy-to-kill-ring', add file contents
2981 to kill ring. Return output file's name."
2982 ;; Checks for FILE permissions. `write-file' would do the same, but
2983 ;; we'd rather avoid needless transcoding of parse tree.
2984 (unless (file-writable-p file) (error "Output file not writable"))
2985 ;; Insert contents to a temporary buffer and write it to FILE.
2986 (let ((out (org-export-as backend subtreep visible-only body-only ext-plist)))
2987 (with-temp-buffer
2988 (insert out)
2989 (let ((coding-system-for-write org-export-coding-system))
2990 (write-file file)))
2991 ;; Maybe add file contents to kill ring.
2992 (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p out))
2993 (org-kill-new out)))
2994 ;; Return full path.
2995 file)
2997 ;;;###autoload
2998 (defun org-export-string-as (string backend &optional body-only ext-plist)
2999 "Transcode STRING into BACKEND code.
3001 When optional argument BODY-ONLY is non-nil, only return body
3002 code, without preamble nor postamble.
3004 Optional argument EXT-PLIST, when provided, is a property list
3005 with external parameters overriding Org default settings, but
3006 still inferior to file-local settings.
3008 Return code as a string."
3009 (with-temp-buffer
3010 (insert string)
3011 (org-mode)
3012 (org-export-as backend nil nil body-only ext-plist)))
3014 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
3015 "Return output file's name according to buffer specifications.
3017 EXTENSION is a string representing the output file extension,
3018 with the leading dot.
3020 With a non-nil optional argument SUBTREEP, try to determine
3021 output file's name by looking for \"EXPORT_FILE_NAME\" property
3022 of subtree at point.
3024 When optional argument PUB-DIR is set, use it as the publishing
3025 directory.
3027 When optional argument VISIBLE-ONLY is non-nil, don't export
3028 contents of hidden elements.
3030 Return file name as a string."
3031 (let* ((visited-file (buffer-file-name (buffer-base-buffer)))
3032 (base-name
3033 ;; File name may come from EXPORT_FILE_NAME subtree
3034 ;; property, assuming point is at beginning of said
3035 ;; sub-tree.
3036 (file-name-sans-extension
3037 (or (and subtreep
3038 (org-entry-get
3039 (save-excursion
3040 (ignore-errors (org-back-to-heading) (point)))
3041 "EXPORT_FILE_NAME" t))
3042 ;; File name may be extracted from buffer's associated
3043 ;; file, if any.
3044 (and visited-file (file-name-nondirectory visited-file))
3045 ;; Can't determine file name on our own: Ask user.
3046 (let ((read-file-name-function
3047 (and org-completion-use-ido 'ido-read-file-name)))
3048 (read-file-name
3049 "Output file: " pub-dir nil nil nil
3050 (lambda (name)
3051 (string= (file-name-extension name t) extension)))))))
3052 (output-file
3053 ;; Build file name. Enforce EXTENSION over whatever user
3054 ;; may have come up with. PUB-DIR, if defined, always has
3055 ;; precedence over any provided path.
3056 (cond
3057 (pub-dir
3058 (concat (file-name-as-directory pub-dir)
3059 (file-name-nondirectory base-name)
3060 extension))
3061 ((file-name-absolute-p base-name) (concat base-name extension))
3062 (t (concat (file-name-as-directory ".") base-name extension)))))
3063 ;; If writing to OUTPUT-FILE would overwrite original file, append
3064 ;; EXTENSION another time to final name.
3065 (if (and visited-file (org-file-equal-p visited-file output-file))
3066 (concat output-file extension)
3067 output-file)))
3069 (defun org-export-expand-include-keyword (&optional included dir)
3070 "Expand every include keyword in buffer.
3071 Optional argument INCLUDED is a list of included file names along
3072 with their line restriction, when appropriate. It is used to
3073 avoid infinite recursion. Optional argument DIR is the current
3074 working directory. It is used to properly resolve relative
3075 paths."
3076 (let ((case-fold-search t))
3077 (goto-char (point-min))
3078 (while (re-search-forward "^[ \t]*#\\+INCLUDE: +\\(.*\\)[ \t]*$" nil t)
3079 (when (eq (org-element-type (save-match-data (org-element-at-point)))
3080 'keyword)
3081 (beginning-of-line)
3082 ;; Extract arguments from keyword's value.
3083 (let* ((value (match-string 1))
3084 (ind (org-get-indentation))
3085 (file (and (string-match "^\"\\(\\S-+\\)\"" value)
3086 (prog1 (expand-file-name (match-string 1 value) dir)
3087 (setq value (replace-match "" nil nil value)))))
3088 (lines
3089 (and (string-match
3090 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\"" value)
3091 (prog1 (match-string 1 value)
3092 (setq value (replace-match "" nil nil value)))))
3093 (env (cond ((string-match "\\<example\\>" value) 'example)
3094 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
3095 (match-string 1 value))))
3096 ;; Minimal level of included file defaults to the child
3097 ;; level of the current headline, if any, or one. It
3098 ;; only applies is the file is meant to be included as
3099 ;; an Org one.
3100 (minlevel
3101 (and (not env)
3102 (if (string-match ":minlevel +\\([0-9]+\\)" value)
3103 (prog1 (string-to-number (match-string 1 value))
3104 (setq value (replace-match "" nil nil value)))
3105 (let ((cur (org-current-level)))
3106 (if cur (1+ (org-reduced-level cur)) 1))))))
3107 ;; Remove keyword.
3108 (delete-region (point) (progn (forward-line) (point)))
3109 (cond
3110 ((not file) (error "Invalid syntax in INCLUDE keyword"))
3111 ((not (file-readable-p file)) (error "Cannot include file %s" file))
3112 ;; Check if files has already been parsed. Look after
3113 ;; inclusion lines too, as different parts of the same file
3114 ;; can be included too.
3115 ((member (list file lines) included)
3116 (error "Recursive file inclusion: %s" file))
3118 (cond
3119 ((eq env 'example)
3120 (insert
3121 (let ((ind-str (make-string ind ? ))
3122 (contents
3123 (org-escape-code-in-string
3124 (org-export--prepare-file-contents file lines))))
3125 (format "%s#+BEGIN_EXAMPLE\n%s%s#+END_EXAMPLE\n"
3126 ind-str contents ind-str))))
3127 ((stringp env)
3128 (insert
3129 (let ((ind-str (make-string ind ? ))
3130 (contents
3131 (org-escape-code-in-string
3132 (org-export--prepare-file-contents file lines))))
3133 (format "%s#+BEGIN_SRC %s\n%s%s#+END_SRC\n"
3134 ind-str env contents ind-str))))
3136 (insert
3137 (with-temp-buffer
3138 (org-mode)
3139 (insert
3140 (org-export--prepare-file-contents file lines ind minlevel))
3141 (org-export-expand-include-keyword
3142 (cons (list file lines) included)
3143 (file-name-directory file))
3144 (buffer-string))))))))))))
3146 (defun org-export--prepare-file-contents (file &optional lines ind minlevel)
3147 "Prepare the contents of FILE for inclusion and return them as a string.
3149 When optional argument LINES is a string specifying a range of
3150 lines, include only those lines.
3152 Optional argument IND, when non-nil, is an integer specifying the
3153 global indentation of returned contents. Since its purpose is to
3154 allow an included file to stay in the same environment it was
3155 created \(i.e. a list item), it doesn't apply past the first
3156 headline encountered.
3158 Optional argument MINLEVEL, when non-nil, is an integer
3159 specifying the level that any top-level headline in the included
3160 file should have."
3161 (with-temp-buffer
3162 (insert-file-contents file)
3163 (when lines
3164 (let* ((lines (split-string lines "-"))
3165 (lbeg (string-to-number (car lines)))
3166 (lend (string-to-number (cadr lines)))
3167 (beg (if (zerop lbeg) (point-min)
3168 (goto-char (point-min))
3169 (forward-line (1- lbeg))
3170 (point)))
3171 (end (if (zerop lend) (point-max)
3172 (goto-char (point-min))
3173 (forward-line (1- lend))
3174 (point))))
3175 (narrow-to-region beg end)))
3176 ;; Remove blank lines at beginning and end of contents. The logic
3177 ;; behind that removal is that blank lines around include keyword
3178 ;; override blank lines in included file.
3179 (goto-char (point-min))
3180 (org-skip-whitespace)
3181 (beginning-of-line)
3182 (delete-region (point-min) (point))
3183 (goto-char (point-max))
3184 (skip-chars-backward " \r\t\n")
3185 (forward-line)
3186 (delete-region (point) (point-max))
3187 ;; If IND is set, preserve indentation of include keyword until
3188 ;; the first headline encountered.
3189 (when ind
3190 (unless (eq major-mode 'org-mode) (org-mode))
3191 (goto-char (point-min))
3192 (let ((ind-str (make-string ind ? )))
3193 (while (not (or (eobp) (looking-at org-outline-regexp-bol)))
3194 ;; Do not move footnote definitions out of column 0.
3195 (unless (and (looking-at org-footnote-definition-re)
3196 (eq (org-element-type (org-element-at-point))
3197 'footnote-definition))
3198 (insert ind-str))
3199 (forward-line))))
3200 ;; When MINLEVEL is specified, compute minimal level for headlines
3201 ;; in the file (CUR-MIN), and remove stars to each headline so
3202 ;; that headlines with minimal level have a level of MINLEVEL.
3203 (when minlevel
3204 (unless (eq major-mode 'org-mode) (org-mode))
3205 (org-with-limited-levels
3206 (let ((levels (org-map-entries
3207 (lambda () (org-reduced-level (org-current-level))))))
3208 (when levels
3209 (let ((offset (- minlevel (apply 'min levels))))
3210 (unless (zerop offset)
3211 (when org-odd-levels-only (setq offset (* offset 2)))
3212 ;; Only change stars, don't bother moving whole
3213 ;; sections.
3214 (org-map-entries
3215 (lambda () (if (< offset 0) (delete-char (abs offset))
3216 (insert (make-string offset ?*)))))))))))
3217 (org-element-normalize-string (buffer-string))))
3219 (defun org-export-execute-babel-code ()
3220 "Execute every Babel code in the visible part of current buffer."
3221 ;; Get a pristine copy of current buffer so Babel references can be
3222 ;; properly resolved.
3223 (let ((reference (org-export-copy-buffer)))
3224 (unwind-protect (let ((org-current-export-file reference))
3225 (org-babel-exp-process-buffer))
3226 (kill-buffer reference))))
3230 ;;; Tools For Back-Ends
3232 ;; A whole set of tools is available to help build new exporters. Any
3233 ;; function general enough to have its use across many back-ends
3234 ;; should be added here.
3236 ;;;; For Affiliated Keywords
3238 ;; `org-export-read-attribute' reads a property from a given element
3239 ;; as a plist. It can be used to normalize affiliated keywords'
3240 ;; syntax.
3242 ;; Since captions can span over multiple lines and accept dual values,
3243 ;; their internal representation is a bit tricky. Therefore,
3244 ;; `org-export-get-caption' transparently returns a given element's
3245 ;; caption as a secondary string.
3247 (defun org-export-read-attribute (attribute element &optional property)
3248 "Turn ATTRIBUTE property from ELEMENT into a plist.
3250 When optional argument PROPERTY is non-nil, return the value of
3251 that property within attributes.
3253 This function assumes attributes are defined as \":keyword
3254 value\" pairs. It is appropriate for `:attr_html' like
3255 properties. All values will become strings except the empty
3256 string and \"nil\", which will become nil."
3257 (let ((attributes
3258 (let ((value (org-element-property attribute element)))
3259 (when value
3260 (let ((s (mapconcat 'identity value " ")) result)
3261 (while (string-match
3262 "\\(?:^\\|[ \t]+\\)\\(:[-a-zA-Z0-9_]+\\)\\([ \t]+\\|$\\)"
3264 (let ((value (substring s 0 (match-beginning 0))))
3265 (push (and (not (member value '("nil" ""))) value) result))
3266 (push (intern (match-string 1 s)) result)
3267 (setq s (substring s (match-end 0))))
3268 ;; Ignore any string before the first property with `cdr'.
3269 (cdr (nreverse (cons (and (org-string-nw-p s)
3270 (not (equal s "nil"))
3272 result))))))))
3273 (if property (plist-get attributes property) attributes)))
3275 (defun org-export-get-caption (element &optional shortp)
3276 "Return caption from ELEMENT as a secondary string.
3278 When optional argument SHORTP is non-nil, return short caption,
3279 as a secondary string, instead.
3281 Caption lines are separated by a white space."
3282 (let ((full-caption (org-element-property :caption element)) caption)
3283 (dolist (line full-caption (cdr caption))
3284 (let ((cap (funcall (if shortp 'cdr 'car) line)))
3285 (when cap
3286 (setq caption (nconc (list " ") (copy-sequence cap) caption)))))))
3289 ;;;; For Derived Back-ends
3291 ;; `org-export-with-backend' is a function allowing to locally use
3292 ;; another back-end to transcode some object or element. In a derived
3293 ;; back-end, it may be used as a fall-back function once all specific
3294 ;; cases have been treated.
3296 (defun org-export-with-backend (back-end data &optional contents info)
3297 "Call a transcoder from BACK-END on DATA.
3298 CONTENTS, when non-nil, is the transcoded contents of DATA
3299 element, as a string. INFO, when non-nil, is the communication
3300 channel used for export, as a plist.."
3301 (org-export-barf-if-invalid-backend back-end)
3302 (let ((type (org-element-type data)))
3303 (if (memq type '(nil org-data)) (error "No foreign transcoder available")
3304 (let ((transcoder
3305 (cdr (assq type (org-export-backend-translate-table back-end)))))
3306 (if (functionp transcoder) (funcall transcoder data contents info)
3307 (error "No foreign transcoder available"))))))
3310 ;;;; For Export Snippets
3312 ;; Every export snippet is transmitted to the back-end. Though, the
3313 ;; latter will only retain one type of export-snippet, ignoring
3314 ;; others, based on the former's target back-end. The function
3315 ;; `org-export-snippet-backend' returns that back-end for a given
3316 ;; export-snippet.
3318 (defun org-export-snippet-backend (export-snippet)
3319 "Return EXPORT-SNIPPET targeted back-end as a symbol.
3320 Translation, with `org-export-snippet-translation-alist', is
3321 applied."
3322 (let ((back-end (org-element-property :back-end export-snippet)))
3323 (intern
3324 (or (cdr (assoc back-end org-export-snippet-translation-alist))
3325 back-end))))
3328 ;;;; For Footnotes
3330 ;; `org-export-collect-footnote-definitions' is a tool to list
3331 ;; actually used footnotes definitions in the whole parse tree, or in
3332 ;; a headline, in order to add footnote listings throughout the
3333 ;; transcoded data.
3335 ;; `org-export-footnote-first-reference-p' is a predicate used by some
3336 ;; back-ends, when they need to attach the footnote definition only to
3337 ;; the first occurrence of the corresponding label.
3339 ;; `org-export-get-footnote-definition' and
3340 ;; `org-export-get-footnote-number' provide easier access to
3341 ;; additional information relative to a footnote reference.
3343 (defun org-export-collect-footnote-definitions (data info)
3344 "Return an alist between footnote numbers, labels and definitions.
3346 DATA is the parse tree from which definitions are collected.
3347 INFO is the plist used as a communication channel.
3349 Definitions are sorted by order of references. They either
3350 appear as Org data or as a secondary string for inlined
3351 footnotes. Unreferenced definitions are ignored."
3352 (let* (num-alist
3353 collect-fn ; for byte-compiler.
3354 (collect-fn
3355 (function
3356 (lambda (data)
3357 ;; Collect footnote number, label and definition in DATA.
3358 (org-element-map data 'footnote-reference
3359 (lambda (fn)
3360 (when (org-export-footnote-first-reference-p fn info)
3361 (let ((def (org-export-get-footnote-definition fn info)))
3362 (push
3363 (list (org-export-get-footnote-number fn info)
3364 (org-element-property :label fn)
3365 def)
3366 num-alist)
3367 ;; Also search in definition for nested footnotes.
3368 (when (eq (org-element-property :type fn) 'standard)
3369 (funcall collect-fn def)))))
3370 ;; Don't enter footnote definitions since it will happen
3371 ;; when their first reference is found.
3372 info nil 'footnote-definition)))))
3373 (funcall collect-fn (plist-get info :parse-tree))
3374 (reverse num-alist)))
3376 (defun org-export-footnote-first-reference-p (footnote-reference info)
3377 "Non-nil when a footnote reference is the first one for its label.
3379 FOOTNOTE-REFERENCE is the footnote reference being considered.
3380 INFO is the plist used as a communication channel."
3381 (let ((label (org-element-property :label footnote-reference)))
3382 ;; Anonymous footnotes are always a first reference.
3383 (if (not label) t
3384 ;; Otherwise, return the first footnote with the same LABEL and
3385 ;; test if it is equal to FOOTNOTE-REFERENCE.
3386 (let* (search-refs ; for byte-compiler.
3387 (search-refs
3388 (function
3389 (lambda (data)
3390 (org-element-map data 'footnote-reference
3391 (lambda (fn)
3392 (cond
3393 ((string= (org-element-property :label fn) label)
3394 (throw 'exit fn))
3395 ;; If FN isn't inlined, be sure to traverse its
3396 ;; definition before resuming search. See
3397 ;; comments in `org-export-get-footnote-number'
3398 ;; for more information.
3399 ((eq (org-element-property :type fn) 'standard)
3400 (funcall search-refs
3401 (org-export-get-footnote-definition fn info)))))
3402 ;; Don't enter footnote definitions since it will
3403 ;; happen when their first reference is found.
3404 info 'first-match 'footnote-definition)))))
3405 (eq (catch 'exit (funcall search-refs (plist-get info :parse-tree)))
3406 footnote-reference)))))
3408 (defun org-export-get-footnote-definition (footnote-reference info)
3409 "Return definition of FOOTNOTE-REFERENCE as parsed data.
3410 INFO is the plist used as a communication channel. If no such
3411 definition can be found, return the \"DEFINITION NOT FOUND\"
3412 string."
3413 (let ((label (org-element-property :label footnote-reference)))
3414 (or (org-element-property :inline-definition footnote-reference)
3415 (cdr (assoc label (plist-get info :footnote-definition-alist)))
3416 "DEFINITION NOT FOUND.")))
3418 (defun org-export-get-footnote-number (footnote info)
3419 "Return number associated to a footnote.
3421 FOOTNOTE is either a footnote reference or a footnote definition.
3422 INFO is the plist used as a communication channel."
3423 (let* ((label (org-element-property :label footnote))
3424 seen-refs
3425 search-ref ; For byte-compiler.
3426 (search-ref
3427 (function
3428 (lambda (data)
3429 ;; Search footnote references through DATA, filling
3430 ;; SEEN-REFS along the way.
3431 (org-element-map data 'footnote-reference
3432 (lambda (fn)
3433 (let ((fn-lbl (org-element-property :label fn)))
3434 (cond
3435 ;; Anonymous footnote match: return number.
3436 ((and (not fn-lbl) (eq fn footnote))
3437 (throw 'exit (1+ (length seen-refs))))
3438 ;; Labels match: return number.
3439 ((and label (string= label fn-lbl))
3440 (throw 'exit (1+ (length seen-refs))))
3441 ;; Anonymous footnote: it's always a new one.
3442 ;; Also, be sure to return nil from the `cond' so
3443 ;; `first-match' doesn't get us out of the loop.
3444 ((not fn-lbl) (push 'inline seen-refs) nil)
3445 ;; Label not seen so far: add it so SEEN-REFS.
3447 ;; Also search for subsequent references in
3448 ;; footnote definition so numbering follows
3449 ;; reading logic. Note that we don't have to care
3450 ;; about inline definitions, since
3451 ;; `org-element-map' already traverses them at the
3452 ;; right time.
3454 ;; Once again, return nil to stay in the loop.
3455 ((not (member fn-lbl seen-refs))
3456 (push fn-lbl seen-refs)
3457 (funcall search-ref
3458 (org-export-get-footnote-definition fn info))
3459 nil))))
3460 ;; Don't enter footnote definitions since it will
3461 ;; happen when their first reference is found.
3462 info 'first-match 'footnote-definition)))))
3463 (catch 'exit (funcall search-ref (plist-get info :parse-tree)))))
3466 ;;;; For Headlines
3468 ;; `org-export-get-relative-level' is a shortcut to get headline
3469 ;; level, relatively to the lower headline level in the parsed tree.
3471 ;; `org-export-get-headline-number' returns the section number of an
3472 ;; headline, while `org-export-number-to-roman' allows to convert it
3473 ;; to roman numbers.
3475 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
3476 ;; `org-export-last-sibling-p' are three useful predicates when it
3477 ;; comes to fulfill the `:headline-levels' property.
3479 ;; `org-export-get-tags', `org-export-get-category' and
3480 ;; `org-export-get-node-property' extract useful information from an
3481 ;; headline or a parent headline. They all handle inheritance.
3483 ;; `org-export-get-alt-title' tries to retrieve an alternative title,
3484 ;; as a secondary string, suitable for table of contents. It falls
3485 ;; back onto default title.
3487 (defun org-export-get-relative-level (headline info)
3488 "Return HEADLINE relative level within current parsed tree.
3489 INFO is a plist holding contextual information."
3490 (+ (org-element-property :level headline)
3491 (or (plist-get info :headline-offset) 0)))
3493 (defun org-export-low-level-p (headline info)
3494 "Non-nil when HEADLINE is considered as low level.
3496 INFO is a plist used as a communication channel.
3498 A low level headlines has a relative level greater than
3499 `:headline-levels' property value.
3501 Return value is the difference between HEADLINE relative level
3502 and the last level being considered as high enough, or nil."
3503 (let ((limit (plist-get info :headline-levels)))
3504 (when (wholenump limit)
3505 (let ((level (org-export-get-relative-level headline info)))
3506 (and (> level limit) (- level limit))))))
3508 (defun org-export-get-headline-number (headline info)
3509 "Return HEADLINE numbering as a list of numbers.
3510 INFO is a plist holding contextual information."
3511 (cdr (assoc headline (plist-get info :headline-numbering))))
3513 (defun org-export-numbered-headline-p (headline info)
3514 "Return a non-nil value if HEADLINE element should be numbered.
3515 INFO is a plist used as a communication channel."
3516 (let ((sec-num (plist-get info :section-numbers))
3517 (level (org-export-get-relative-level headline info)))
3518 (if (wholenump sec-num) (<= level sec-num) sec-num)))
3520 (defun org-export-number-to-roman (n)
3521 "Convert integer N into a roman numeral."
3522 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
3523 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
3524 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
3525 ( 1 . "I")))
3526 (res ""))
3527 (if (<= n 0)
3528 (number-to-string n)
3529 (while roman
3530 (if (>= n (caar roman))
3531 (setq n (- n (caar roman))
3532 res (concat res (cdar roman)))
3533 (pop roman)))
3534 res)))
3536 (defun org-export-get-tags (element info &optional tags inherited)
3537 "Return list of tags associated to ELEMENT.
3539 ELEMENT has either an `headline' or an `inlinetask' type. INFO
3540 is a plist used as a communication channel.
3542 Select tags (see `org-export-select-tags') and exclude tags (see
3543 `org-export-exclude-tags') are removed from the list.
3545 When non-nil, optional argument TAGS should be a list of strings.
3546 Any tag belonging to this list will also be removed.
3548 When optional argument INHERITED is non-nil, tags can also be
3549 inherited from parent headlines and FILETAGS keywords."
3550 (org-remove-if
3551 (lambda (tag) (or (member tag (plist-get info :select-tags))
3552 (member tag (plist-get info :exclude-tags))
3553 (member tag tags)))
3554 (if (not inherited) (org-element-property :tags element)
3555 ;; Build complete list of inherited tags.
3556 (let ((current-tag-list (org-element-property :tags element)))
3557 (mapc
3558 (lambda (parent)
3559 (mapc
3560 (lambda (tag)
3561 (when (and (memq (org-element-type parent) '(headline inlinetask))
3562 (not (member tag current-tag-list)))
3563 (push tag current-tag-list)))
3564 (org-element-property :tags parent)))
3565 (org-export-get-genealogy element))
3566 ;; Add FILETAGS keywords and return results.
3567 (org-uniquify (append (plist-get info :filetags) current-tag-list))))))
3569 (defun org-export-get-node-property (property blob &optional inherited)
3570 "Return node PROPERTY value for BLOB.
3572 PROPERTY is an upcase symbol (i.e. `:COOKIE_DATA'). BLOB is an
3573 element or object.
3575 If optional argument INHERITED is non-nil, the value can be
3576 inherited from a parent headline.
3578 Return value is a string or nil."
3579 (let ((headline (if (eq (org-element-type blob) 'headline) blob
3580 (org-export-get-parent-headline blob))))
3581 (if (not inherited) (org-element-property property blob)
3582 (let ((parent headline) value)
3583 (catch 'found
3584 (while parent
3585 (when (plist-member (nth 1 parent) property)
3586 (throw 'found (org-element-property property parent)))
3587 (setq parent (org-element-property :parent parent))))))))
3589 (defun org-export-get-category (blob info)
3590 "Return category for element or object BLOB.
3592 INFO is a plist used as a communication channel.
3594 CATEGORY is automatically inherited from a parent headline, from
3595 #+CATEGORY: keyword or created out of original file name. If all
3596 fail, the fall-back value is \"???\"."
3597 (or (let ((headline (if (eq (org-element-type blob) 'headline) blob
3598 (org-export-get-parent-headline blob))))
3599 ;; Almost like `org-export-node-property', but we cannot trust
3600 ;; `plist-member' as every headline has a `:CATEGORY'
3601 ;; property, would it be nil or equal to "???" (which has the
3602 ;; same meaning).
3603 (let ((parent headline) value)
3604 (catch 'found
3605 (while parent
3606 (let ((category (org-element-property :CATEGORY parent)))
3607 (and category (not (equal "???" category))
3608 (throw 'found category)))
3609 (setq parent (org-element-property :parent parent))))))
3610 (org-element-map (plist-get info :parse-tree) 'keyword
3611 (lambda (kwd)
3612 (when (equal (org-element-property :key kwd) "CATEGORY")
3613 (org-element-property :value kwd)))
3614 info 'first-match)
3615 (let ((file (plist-get info :input-file)))
3616 (and file (file-name-sans-extension (file-name-nondirectory file))))
3617 "???"))
3619 (defun org-export-get-alt-title (headline info)
3620 "Return alternative title for HEADLINE, as a secondary string.
3621 INFO is a plist used as a communication channel. If no optional
3622 title is defined, fall-back to the regular title."
3623 (or (org-element-property :alt-title headline)
3624 (org-element-property :title headline)))
3626 (defun org-export-first-sibling-p (headline info)
3627 "Non-nil when HEADLINE is the first sibling in its sub-tree.
3628 INFO is a plist used as a communication channel."
3629 (not (eq (org-element-type (org-export-get-previous-element headline info))
3630 'headline)))
3632 (defun org-export-last-sibling-p (headline info)
3633 "Non-nil when HEADLINE is the last sibling in its sub-tree.
3634 INFO is a plist used as a communication channel."
3635 (not (org-export-get-next-element headline info)))
3638 ;;;; For Links
3640 ;; `org-export-solidify-link-text' turns a string into a safer version
3641 ;; for links, replacing most non-standard characters with hyphens.
3643 ;; `org-export-get-coderef-format' returns an appropriate format
3644 ;; string for coderefs.
3646 ;; `org-export-inline-image-p' returns a non-nil value when the link
3647 ;; provided should be considered as an inline image.
3649 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
3650 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
3651 ;; returns an appropriate unique identifier when found, or nil.
3653 ;; `org-export-resolve-id-link' returns the first headline with
3654 ;; specified id or custom-id in parse tree, the path to the external
3655 ;; file with the id or nil when neither was found.
3657 ;; `org-export-resolve-coderef' associates a reference to a line
3658 ;; number in the element it belongs, or returns the reference itself
3659 ;; when the element isn't numbered.
3661 (defun org-export-solidify-link-text (s)
3662 "Take link text S and make a safe target out of it."
3663 (save-match-data
3664 (mapconcat 'identity (org-split-string s "[^a-zA-Z0-9_.-:]+") "-")))
3666 (defun org-export-get-coderef-format (path desc)
3667 "Return format string for code reference link.
3668 PATH is the link path. DESC is its description."
3669 (save-match-data
3670 (cond ((not desc) "%s")
3671 ((string-match (regexp-quote (concat "(" path ")")) desc)
3672 (replace-match "%s" t t desc))
3673 (t desc))))
3675 (defun org-export-inline-image-p (link &optional rules)
3676 "Non-nil if LINK object points to an inline image.
3678 Optional argument is a set of RULES defining inline images. It
3679 is an alist where associations have the following shape:
3681 \(TYPE . REGEXP)
3683 Applying a rule means apply REGEXP against LINK's path when its
3684 type is TYPE. The function will return a non-nil value if any of
3685 the provided rules is non-nil. The default rule is
3686 `org-export-default-inline-image-rule'.
3688 This only applies to links without a description."
3689 (and (not (org-element-contents link))
3690 (let ((case-fold-search t)
3691 (rules (or rules org-export-default-inline-image-rule)))
3692 (catch 'exit
3693 (mapc
3694 (lambda (rule)
3695 (and (string= (org-element-property :type link) (car rule))
3696 (string-match (cdr rule)
3697 (org-element-property :path link))
3698 (throw 'exit t)))
3699 rules)
3700 ;; Return nil if no rule matched.
3701 nil))))
3703 (defun org-export-resolve-coderef (ref info)
3704 "Resolve a code reference REF.
3706 INFO is a plist used as a communication channel.
3708 Return associated line number in source code, or REF itself,
3709 depending on src-block or example element's switches."
3710 (org-element-map (plist-get info :parse-tree) '(example-block src-block)
3711 (lambda (el)
3712 (with-temp-buffer
3713 (insert (org-trim (org-element-property :value el)))
3714 (let* ((label-fmt (regexp-quote
3715 (or (org-element-property :label-fmt el)
3716 org-coderef-label-format)))
3717 (ref-re
3718 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
3719 (replace-regexp-in-string "%s" ref label-fmt nil t))))
3720 ;; Element containing REF is found. Resolve it to either
3721 ;; a label or a line number, as needed.
3722 (when (re-search-backward ref-re nil t)
3723 (cond
3724 ((org-element-property :use-labels el) ref)
3725 ((eq (org-element-property :number-lines el) 'continued)
3726 (+ (org-export-get-loc el info) (line-number-at-pos)))
3727 (t (line-number-at-pos)))))))
3728 info 'first-match))
3730 (defun org-export-resolve-fuzzy-link (link info)
3731 "Return LINK destination.
3733 INFO is a plist holding contextual information.
3735 Return value can be an object, an element, or nil:
3737 - If LINK path matches a target object (i.e. <<path>>) or
3738 element (i.e. \"#+TARGET: path\"), return it.
3740 - If LINK path exactly matches the name affiliated keyword
3741 \(i.e. #+NAME: path) of an element, return that element.
3743 - If LINK path exactly matches any headline name, return that
3744 element. If more than one headline share that name, priority
3745 will be given to the one with the closest common ancestor, if
3746 any, or the first one in the parse tree otherwise.
3748 - Otherwise, return nil.
3750 Assume LINK type is \"fuzzy\". White spaces are not
3751 significant."
3752 (let* ((raw-path (org-element-property :path link))
3753 (match-title-p (eq (aref raw-path 0) ?*))
3754 ;; Split PATH at white spaces so matches are space
3755 ;; insensitive.
3756 (path (org-split-string
3757 (if match-title-p (substring raw-path 1) raw-path))))
3758 (cond
3759 ;; First try to find a matching "<<path>>" unless user specified
3760 ;; he was looking for a headline (path starts with a *
3761 ;; character).
3762 ((and (not match-title-p)
3763 (org-element-map (plist-get info :parse-tree) '(keyword target)
3764 (lambda (blob)
3765 (and (or (eq (org-element-type blob) 'target)
3766 (equal (org-element-property :key blob) "TARGET"))
3767 (equal (org-split-string (org-element-property :value blob))
3768 path)
3769 blob))
3770 info t)))
3771 ;; Then try to find an element with a matching "#+NAME: path"
3772 ;; affiliated keyword.
3773 ((and (not match-title-p)
3774 (org-element-map (plist-get info :parse-tree)
3775 org-element-all-elements
3776 (lambda (el)
3777 (let ((name (org-element-property :name el)))
3778 (when (and name (equal (org-split-string name) path)) el)))
3779 info 'first-match)))
3780 ;; Last case: link either points to a headline or to
3781 ;; nothingness. Try to find the source, with priority given to
3782 ;; headlines with the closest common ancestor. If such candidate
3783 ;; is found, return it, otherwise return nil.
3785 (let ((find-headline
3786 (function
3787 ;; Return first headline whose `:raw-value' property is
3788 ;; NAME in parse tree DATA, or nil. Statistics cookies
3789 ;; are ignored.
3790 (lambda (name data)
3791 (org-element-map data 'headline
3792 (lambda (headline)
3793 (when (equal (org-split-string
3794 (replace-regexp-in-string
3795 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
3796 (org-element-property :raw-value headline)))
3797 name)
3798 headline))
3799 info 'first-match)))))
3800 ;; Search among headlines sharing an ancestor with link, from
3801 ;; closest to farthest.
3802 (or (catch 'exit
3803 (mapc
3804 (lambda (parent)
3805 (when (eq (org-element-type parent) 'headline)
3806 (let ((foundp (funcall find-headline path parent)))
3807 (when foundp (throw 'exit foundp)))))
3808 (org-export-get-genealogy link)) nil)
3809 ;; No match with a common ancestor: try full parse-tree.
3810 (funcall find-headline path (plist-get info :parse-tree))))))))
3812 (defun org-export-resolve-id-link (link info)
3813 "Return headline referenced as LINK destination.
3815 INFO is a plist used as a communication channel.
3817 Return value can be the headline element matched in current parse
3818 tree, a file name or nil. Assume LINK type is either \"id\" or
3819 \"custom-id\"."
3820 (let ((id (org-element-property :path link)))
3821 ;; First check if id is within the current parse tree.
3822 (or (org-element-map (plist-get info :parse-tree) 'headline
3823 (lambda (headline)
3824 (when (or (string= (org-element-property :ID headline) id)
3825 (string= (org-element-property :CUSTOM_ID headline) id))
3826 headline))
3827 info 'first-match)
3828 ;; Otherwise, look for external files.
3829 (cdr (assoc id (plist-get info :id-alist))))))
3831 (defun org-export-resolve-radio-link (link info)
3832 "Return radio-target object referenced as LINK destination.
3834 INFO is a plist used as a communication channel.
3836 Return value can be a radio-target object or nil. Assume LINK
3837 has type \"radio\"."
3838 (let ((path (org-element-property :path link)))
3839 (org-element-map (plist-get info :parse-tree) 'radio-target
3840 (lambda (radio)
3841 (and (compare-strings
3842 (org-element-property :value radio) 0 nil path 0 nil t)
3843 radio))
3844 info 'first-match)))
3847 ;;;; For References
3849 ;; `org-export-get-ordinal' associates a sequence number to any object
3850 ;; or element.
3852 (defun org-export-get-ordinal (element info &optional types predicate)
3853 "Return ordinal number of an element or object.
3855 ELEMENT is the element or object considered. INFO is the plist
3856 used as a communication channel.
3858 Optional argument TYPES, when non-nil, is a list of element or
3859 object types, as symbols, that should also be counted in.
3860 Otherwise, only provided element's type is considered.
3862 Optional argument PREDICATE is a function returning a non-nil
3863 value if the current element or object should be counted in. It
3864 accepts two arguments: the element or object being considered and
3865 the plist used as a communication channel. This allows to count
3866 only a certain type of objects (i.e. inline images).
3868 Return value is a list of numbers if ELEMENT is a headline or an
3869 item. It is nil for keywords. It represents the footnote number
3870 for footnote definitions and footnote references. If ELEMENT is
3871 a target, return the same value as if ELEMENT was the closest
3872 table, item or headline containing the target. In any other
3873 case, return the sequence number of ELEMENT among elements or
3874 objects of the same type."
3875 ;; A target keyword, representing an invisible target, never has
3876 ;; a sequence number.
3877 (unless (eq (org-element-type element) 'keyword)
3878 ;; Ordinal of a target object refer to the ordinal of the closest
3879 ;; table, item, or headline containing the object.
3880 (when (eq (org-element-type element) 'target)
3881 (setq element
3882 (loop for parent in (org-export-get-genealogy element)
3883 when
3884 (memq
3885 (org-element-type parent)
3886 '(footnote-definition footnote-reference headline item
3887 table))
3888 return parent)))
3889 (case (org-element-type element)
3890 ;; Special case 1: A headline returns its number as a list.
3891 (headline (org-export-get-headline-number element info))
3892 ;; Special case 2: An item returns its number as a list.
3893 (item (let ((struct (org-element-property :structure element)))
3894 (org-list-get-item-number
3895 (org-element-property :begin element)
3896 struct
3897 (org-list-prevs-alist struct)
3898 (org-list-parents-alist struct))))
3899 ((footnote-definition footnote-reference)
3900 (org-export-get-footnote-number element info))
3901 (otherwise
3902 (let ((counter 0))
3903 ;; Increment counter until ELEMENT is found again.
3904 (org-element-map (plist-get info :parse-tree)
3905 (or types (org-element-type element))
3906 (lambda (el)
3907 (cond
3908 ((eq element el) (1+ counter))
3909 ((not predicate) (incf counter) nil)
3910 ((funcall predicate el info) (incf counter) nil)))
3911 info 'first-match))))))
3914 ;;;; For Src-Blocks
3916 ;; `org-export-get-loc' counts number of code lines accumulated in
3917 ;; src-block or example-block elements with a "+n" switch until
3918 ;; a given element, excluded. Note: "-n" switches reset that count.
3920 ;; `org-export-unravel-code' extracts source code (along with a code
3921 ;; references alist) from an `element-block' or `src-block' type
3922 ;; element.
3924 ;; `org-export-format-code' applies a formatting function to each line
3925 ;; of code, providing relative line number and code reference when
3926 ;; appropriate. Since it doesn't access the original element from
3927 ;; which the source code is coming, it expects from the code calling
3928 ;; it to know if lines should be numbered and if code references
3929 ;; should appear.
3931 ;; Eventually, `org-export-format-code-default' is a higher-level
3932 ;; function (it makes use of the two previous functions) which handles
3933 ;; line numbering and code references inclusion, and returns source
3934 ;; code in a format suitable for plain text or verbatim output.
3936 (defun org-export-get-loc (element info)
3937 "Return accumulated lines of code up to ELEMENT.
3939 INFO is the plist used as a communication channel.
3941 ELEMENT is excluded from count."
3942 (let ((loc 0))
3943 (org-element-map (plist-get info :parse-tree)
3944 `(src-block example-block ,(org-element-type element))
3945 (lambda (el)
3946 (cond
3947 ;; ELEMENT is reached: Quit the loop.
3948 ((eq el element))
3949 ;; Only count lines from src-block and example-block elements
3950 ;; with a "+n" or "-n" switch. A "-n" switch resets counter.
3951 ((not (memq (org-element-type el) '(src-block example-block))) nil)
3952 ((let ((linums (org-element-property :number-lines el)))
3953 (when linums
3954 ;; Accumulate locs or reset them.
3955 (let ((lines (org-count-lines
3956 (org-trim (org-element-property :value el)))))
3957 (setq loc (if (eq linums 'new) lines (+ loc lines))))))
3958 ;; Return nil to stay in the loop.
3959 nil)))
3960 info 'first-match)
3961 ;; Return value.
3962 loc))
3964 (defun org-export-unravel-code (element)
3965 "Clean source code and extract references out of it.
3967 ELEMENT has either a `src-block' an `example-block' type.
3969 Return a cons cell whose CAR is the source code, cleaned from any
3970 reference and protective comma and CDR is an alist between
3971 relative line number (integer) and name of code reference on that
3972 line (string)."
3973 (let* ((line 0) refs
3974 ;; Get code and clean it. Remove blank lines at its
3975 ;; beginning and end.
3976 (code (let ((c (replace-regexp-in-string
3977 "\\`\\([ \t]*\n\\)+" ""
3978 (replace-regexp-in-string
3979 "\\([ \t]*\n\\)*[ \t]*\\'" "\n"
3980 (org-element-property :value element)))))
3981 ;; If appropriate, remove global indentation.
3982 (if (or org-src-preserve-indentation
3983 (org-element-property :preserve-indent element))
3985 (org-remove-indentation c))))
3986 ;; Get format used for references.
3987 (label-fmt (regexp-quote
3988 (or (org-element-property :label-fmt element)
3989 org-coderef-label-format)))
3990 ;; Build a regexp matching a loc with a reference.
3991 (with-ref-re
3992 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)[ \t]*\\)$"
3993 (replace-regexp-in-string
3994 "%s" "\\([-a-zA-Z0-9_ ]+\\)" label-fmt nil t))))
3995 ;; Return value.
3996 (cons
3997 ;; Code with references removed.
3998 (org-element-normalize-string
3999 (mapconcat
4000 (lambda (loc)
4001 (incf line)
4002 (if (not (string-match with-ref-re loc)) loc
4003 ;; Ref line: remove ref, and signal its position in REFS.
4004 (push (cons line (match-string 3 loc)) refs)
4005 (replace-match "" nil nil loc 1)))
4006 (org-split-string code "\n") "\n"))
4007 ;; Reference alist.
4008 refs)))
4010 (defun org-export-format-code (code fun &optional num-lines ref-alist)
4011 "Format CODE by applying FUN line-wise and return it.
4013 CODE is a string representing the code to format. FUN is
4014 a function. It must accept three arguments: a line of
4015 code (string), the current line number (integer) or nil and the
4016 reference associated to the current line (string) or nil.
4018 Optional argument NUM-LINES can be an integer representing the
4019 number of code lines accumulated until the current code. Line
4020 numbers passed to FUN will take it into account. If it is nil,
4021 FUN's second argument will always be nil. This number can be
4022 obtained with `org-export-get-loc' function.
4024 Optional argument REF-ALIST can be an alist between relative line
4025 number (i.e. ignoring NUM-LINES) and the name of the code
4026 reference on it. If it is nil, FUN's third argument will always
4027 be nil. It can be obtained through the use of
4028 `org-export-unravel-code' function."
4029 (let ((--locs (org-split-string code "\n"))
4030 (--line 0))
4031 (org-element-normalize-string
4032 (mapconcat
4033 (lambda (--loc)
4034 (incf --line)
4035 (let ((--ref (cdr (assq --line ref-alist))))
4036 (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
4037 --locs "\n"))))
4039 (defun org-export-format-code-default (element info)
4040 "Return source code from ELEMENT, formatted in a standard way.
4042 ELEMENT is either a `src-block' or `example-block' element. INFO
4043 is a plist used as a communication channel.
4045 This function takes care of line numbering and code references
4046 inclusion. Line numbers, when applicable, appear at the
4047 beginning of the line, separated from the code by two white
4048 spaces. Code references, on the other hand, appear flushed to
4049 the right, separated by six white spaces from the widest line of
4050 code."
4051 ;; Extract code and references.
4052 (let* ((code-info (org-export-unravel-code element))
4053 (code (car code-info))
4054 (code-lines (org-split-string code "\n")))
4055 (if (null code-lines) ""
4056 (let* ((refs (and (org-element-property :retain-labels element)
4057 (cdr code-info)))
4058 ;; Handle line numbering.
4059 (num-start (case (org-element-property :number-lines element)
4060 (continued (org-export-get-loc element info))
4061 (new 0)))
4062 (num-fmt
4063 (and num-start
4064 (format "%%%ds "
4065 (length (number-to-string
4066 (+ (length code-lines) num-start))))))
4067 ;; Prepare references display, if required. Any reference
4068 ;; should start six columns after the widest line of code,
4069 ;; wrapped with parenthesis.
4070 (max-width
4071 (+ (apply 'max (mapcar 'length code-lines))
4072 (if (not num-start) 0 (length (format num-fmt num-start))))))
4073 (org-export-format-code
4074 code
4075 (lambda (loc line-num ref)
4076 (let ((number-str (and num-fmt (format num-fmt line-num))))
4077 (concat
4078 number-str
4080 (and ref
4081 (concat (make-string
4082 (- (+ 6 max-width)
4083 (+ (length loc) (length number-str))) ? )
4084 (format "(%s)" ref))))))
4085 num-start refs)))))
4088 ;;;; For Tables
4090 ;; `org-export-table-has-special-column-p' and and
4091 ;; `org-export-table-row-is-special-p' are predicates used to look for
4092 ;; meta-information about the table structure.
4094 ;; `org-table-has-header-p' tells when the rows before the first rule
4095 ;; should be considered as table's header.
4097 ;; `org-export-table-cell-width', `org-export-table-cell-alignment'
4098 ;; and `org-export-table-cell-borders' extract information from
4099 ;; a table-cell element.
4101 ;; `org-export-table-dimensions' gives the number on rows and columns
4102 ;; in the table, ignoring horizontal rules and special columns.
4103 ;; `org-export-table-cell-address', given a table-cell object, returns
4104 ;; the absolute address of a cell. On the other hand,
4105 ;; `org-export-get-table-cell-at' does the contrary.
4107 ;; `org-export-table-cell-starts-colgroup-p',
4108 ;; `org-export-table-cell-ends-colgroup-p',
4109 ;; `org-export-table-row-starts-rowgroup-p',
4110 ;; `org-export-table-row-ends-rowgroup-p',
4111 ;; `org-export-table-row-starts-header-p' and
4112 ;; `org-export-table-row-ends-header-p' indicate position of current
4113 ;; row or cell within the table.
4115 (defun org-export-table-has-special-column-p (table)
4116 "Non-nil when TABLE has a special column.
4117 All special columns will be ignored during export."
4118 ;; The table has a special column when every first cell of every row
4119 ;; has an empty value or contains a symbol among "/", "#", "!", "$",
4120 ;; "*" "_" and "^". Though, do not consider a first row containing
4121 ;; only empty cells as special.
4122 (let ((special-column-p 'empty))
4123 (catch 'exit
4124 (mapc
4125 (lambda (row)
4126 (when (eq (org-element-property :type row) 'standard)
4127 (let ((value (org-element-contents
4128 (car (org-element-contents row)))))
4129 (cond ((member value '(("/") ("#") ("!") ("$") ("*") ("_") ("^")))
4130 (setq special-column-p 'special))
4131 ((not value))
4132 (t (throw 'exit nil))))))
4133 (org-element-contents table))
4134 (eq special-column-p 'special))))
4136 (defun org-export-table-has-header-p (table info)
4137 "Non-nil when TABLE has an header.
4139 INFO is a plist used as a communication channel.
4141 A table has an header when it contains at least two row groups."
4142 (let ((rowgroup 1) row-flag)
4143 (org-element-map table 'table-row
4144 (lambda (row)
4145 (cond
4146 ((> rowgroup 1) t)
4147 ((and row-flag (eq (org-element-property :type row) 'rule))
4148 (incf rowgroup) (setq row-flag nil))
4149 ((and (not row-flag) (eq (org-element-property :type row) 'standard))
4150 (setq row-flag t) nil)))
4151 info)))
4153 (defun org-export-table-row-is-special-p (table-row info)
4154 "Non-nil if TABLE-ROW is considered special.
4156 INFO is a plist used as the communication channel.
4158 All special rows will be ignored during export."
4159 (when (eq (org-element-property :type table-row) 'standard)
4160 (let ((first-cell (org-element-contents
4161 (car (org-element-contents table-row)))))
4162 ;; A row is special either when...
4164 ;; ... it starts with a field only containing "/",
4165 (equal first-cell '("/"))
4166 ;; ... the table contains a special column and the row start
4167 ;; with a marking character among, "^", "_", "$" or "!",
4168 (and (org-export-table-has-special-column-p
4169 (org-export-get-parent table-row))
4170 (member first-cell '(("^") ("_") ("$") ("!"))))
4171 ;; ... it contains only alignment cookies and empty cells.
4172 (let ((special-row-p 'empty))
4173 (catch 'exit
4174 (mapc
4175 (lambda (cell)
4176 (let ((value (org-element-contents cell)))
4177 ;; Since VALUE is a secondary string, the following
4178 ;; checks avoid expanding it with `org-export-data'.
4179 (cond ((not value))
4180 ((and (not (cdr value))
4181 (stringp (car value))
4182 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'"
4183 (car value)))
4184 (setq special-row-p 'cookie))
4185 (t (throw 'exit nil)))))
4186 (org-element-contents table-row))
4187 (eq special-row-p 'cookie)))))))
4189 (defun org-export-table-row-group (table-row info)
4190 "Return TABLE-ROW's group.
4192 INFO is a plist used as the communication channel.
4194 Return value is the group number, as an integer, or nil special
4195 rows and table rules. Group 1 is also table's header."
4196 (unless (or (eq (org-element-property :type table-row) 'rule)
4197 (org-export-table-row-is-special-p table-row info))
4198 (let ((group 0) row-flag)
4199 (catch 'found
4200 (mapc
4201 (lambda (row)
4202 (cond
4203 ((and (eq (org-element-property :type row) 'standard)
4204 (not (org-export-table-row-is-special-p row info)))
4205 (unless row-flag (incf group) (setq row-flag t)))
4206 ((eq (org-element-property :type row) 'rule)
4207 (setq row-flag nil)))
4208 (when (eq table-row row) (throw 'found group)))
4209 (org-element-contents (org-export-get-parent table-row)))))))
4211 (defun org-export-table-cell-width (table-cell info)
4212 "Return TABLE-CELL contents width.
4214 INFO is a plist used as the communication channel.
4216 Return value is the width given by the last width cookie in the
4217 same column as TABLE-CELL, or nil."
4218 (let* ((row (org-export-get-parent table-cell))
4219 (column (let ((cells (org-element-contents row)))
4220 (- (length cells) (length (memq table-cell cells)))))
4221 (table (org-export-get-parent-table table-cell))
4222 cookie-width)
4223 (mapc
4224 (lambda (row)
4225 (cond
4226 ;; In a special row, try to find a width cookie at COLUMN.
4227 ((org-export-table-row-is-special-p row info)
4228 (let ((value (org-element-contents
4229 (elt (org-element-contents row) column))))
4230 ;; The following checks avoid expanding unnecessarily the
4231 ;; cell with `org-export-data'
4232 (when (and value
4233 (not (cdr value))
4234 (stringp (car value))
4235 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'" (car value))
4236 (match-string 1 (car value)))
4237 (setq cookie-width
4238 (string-to-number (match-string 1 (car value)))))))
4239 ;; Ignore table rules.
4240 ((eq (org-element-property :type row) 'rule))))
4241 (org-element-contents table))
4242 ;; Return value.
4243 cookie-width))
4245 (defun org-export-table-cell-alignment (table-cell info)
4246 "Return TABLE-CELL contents alignment.
4248 INFO is a plist used as the communication channel.
4250 Return alignment as specified by the last alignment cookie in the
4251 same column as TABLE-CELL. If no such cookie is found, a default
4252 alignment value will be deduced from fraction of numbers in the
4253 column (see `org-table-number-fraction' for more information).
4254 Possible values are `left', `right' and `center'."
4255 (let* ((row (org-export-get-parent table-cell))
4256 (column (let ((cells (org-element-contents row)))
4257 (- (length cells) (length (memq table-cell cells)))))
4258 (table (org-export-get-parent-table table-cell))
4259 (number-cells 0)
4260 (total-cells 0)
4261 cookie-align)
4262 (mapc
4263 (lambda (row)
4264 (cond
4265 ;; In a special row, try to find an alignment cookie at
4266 ;; COLUMN.
4267 ((org-export-table-row-is-special-p row info)
4268 (let ((value (org-element-contents
4269 (elt (org-element-contents row) column))))
4270 ;; Since VALUE is a secondary string, the following checks
4271 ;; avoid useless expansion through `org-export-data'.
4272 (when (and value
4273 (not (cdr value))
4274 (stringp (car value))
4275 (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'"
4276 (car value))
4277 (match-string 1 (car value)))
4278 (setq cookie-align (match-string 1 (car value))))))
4279 ;; Ignore table rules.
4280 ((eq (org-element-property :type row) 'rule))
4281 ;; In a standard row, check if cell's contents are expressing
4282 ;; some kind of number. Increase NUMBER-CELLS accordingly.
4283 ;; Though, don't bother if an alignment cookie has already
4284 ;; defined cell's alignment.
4285 ((not cookie-align)
4286 (let ((value (org-export-data
4287 (org-element-contents
4288 (elt (org-element-contents row) column))
4289 info)))
4290 (incf total-cells)
4291 (when (string-match org-table-number-regexp value)
4292 (incf number-cells))))))
4293 (org-element-contents table))
4294 ;; Return value. Alignment specified by cookies has precedence
4295 ;; over alignment deduced from cells contents.
4296 (cond ((equal cookie-align "l") 'left)
4297 ((equal cookie-align "r") 'right)
4298 ((equal cookie-align "c") 'center)
4299 ((>= (/ (float number-cells) total-cells) org-table-number-fraction)
4300 'right)
4301 (t 'left))))
4303 (defun org-export-table-cell-borders (table-cell info)
4304 "Return TABLE-CELL borders.
4306 INFO is a plist used as a communication channel.
4308 Return value is a list of symbols, or nil. Possible values are:
4309 `top', `bottom', `above', `below', `left' and `right'. Note:
4310 `top' (resp. `bottom') only happen for a cell in the first
4311 row (resp. last row) of the table, ignoring table rules, if any.
4313 Returned borders ignore special rows."
4314 (let* ((row (org-export-get-parent table-cell))
4315 (table (org-export-get-parent-table table-cell))
4316 borders)
4317 ;; Top/above border? TABLE-CELL has a border above when a rule
4318 ;; used to demarcate row groups can be found above. Hence,
4319 ;; finding a rule isn't sufficient to push `above' in BORDERS:
4320 ;; another regular row has to be found above that rule.
4321 (let (rule-flag)
4322 (catch 'exit
4323 (mapc (lambda (row)
4324 (cond ((eq (org-element-property :type row) 'rule)
4325 (setq rule-flag t))
4326 ((not (org-export-table-row-is-special-p row info))
4327 (if rule-flag (throw 'exit (push 'above borders))
4328 (throw 'exit nil)))))
4329 ;; Look at every row before the current one.
4330 (cdr (memq row (reverse (org-element-contents table)))))
4331 ;; No rule above, or rule found starts the table (ignoring any
4332 ;; special row): TABLE-CELL is at the top of the table.
4333 (when rule-flag (push 'above borders))
4334 (push 'top borders)))
4335 ;; Bottom/below border? TABLE-CELL has a border below when next
4336 ;; non-regular row below is a rule.
4337 (let (rule-flag)
4338 (catch 'exit
4339 (mapc (lambda (row)
4340 (cond ((eq (org-element-property :type row) 'rule)
4341 (setq rule-flag t))
4342 ((not (org-export-table-row-is-special-p row info))
4343 (if rule-flag (throw 'exit (push 'below borders))
4344 (throw 'exit nil)))))
4345 ;; Look at every row after the current one.
4346 (cdr (memq row (org-element-contents table))))
4347 ;; No rule below, or rule found ends the table (modulo some
4348 ;; special row): TABLE-CELL is at the bottom of the table.
4349 (when rule-flag (push 'below borders))
4350 (push 'bottom borders)))
4351 ;; Right/left borders? They can only be specified by column
4352 ;; groups. Column groups are defined in a row starting with "/".
4353 ;; Also a column groups row only contains "<", "<>", ">" or blank
4354 ;; cells.
4355 (catch 'exit
4356 (let ((column (let ((cells (org-element-contents row)))
4357 (- (length cells) (length (memq table-cell cells))))))
4358 (mapc
4359 (lambda (row)
4360 (unless (eq (org-element-property :type row) 'rule)
4361 (when (equal (org-element-contents
4362 (car (org-element-contents row)))
4363 '("/"))
4364 (let ((column-groups
4365 (mapcar
4366 (lambda (cell)
4367 (let ((value (org-element-contents cell)))
4368 (when (member value '(("<") ("<>") (">") nil))
4369 (car value))))
4370 (org-element-contents row))))
4371 ;; There's a left border when previous cell, if
4372 ;; any, ends a group, or current one starts one.
4373 (when (or (and (not (zerop column))
4374 (member (elt column-groups (1- column))
4375 '(">" "<>")))
4376 (member (elt column-groups column) '("<" "<>")))
4377 (push 'left borders))
4378 ;; There's a right border when next cell, if any,
4379 ;; starts a group, or current one ends one.
4380 (when (or (and (/= (1+ column) (length column-groups))
4381 (member (elt column-groups (1+ column))
4382 '("<" "<>")))
4383 (member (elt column-groups column) '(">" "<>")))
4384 (push 'right borders))
4385 (throw 'exit nil)))))
4386 ;; Table rows are read in reverse order so last column groups
4387 ;; row has precedence over any previous one.
4388 (reverse (org-element-contents table)))))
4389 ;; Return value.
4390 borders))
4392 (defun org-export-table-cell-starts-colgroup-p (table-cell info)
4393 "Non-nil when TABLE-CELL is at the beginning of a row group.
4394 INFO is a plist used as a communication channel."
4395 ;; A cell starts a column group either when it is at the beginning
4396 ;; of a row (or after the special column, if any) or when it has
4397 ;; a left border.
4398 (or (eq (org-element-map (org-export-get-parent table-cell) 'table-cell
4399 'identity info 'first-match)
4400 table-cell)
4401 (memq 'left (org-export-table-cell-borders table-cell info))))
4403 (defun org-export-table-cell-ends-colgroup-p (table-cell info)
4404 "Non-nil when TABLE-CELL is at the end of a row group.
4405 INFO is a plist used as a communication channel."
4406 ;; A cell ends a column group either when it is at the end of a row
4407 ;; or when it has a right border.
4408 (or (eq (car (last (org-element-contents
4409 (org-export-get-parent table-cell))))
4410 table-cell)
4411 (memq 'right (org-export-table-cell-borders table-cell info))))
4413 (defun org-export-table-row-starts-rowgroup-p (table-row info)
4414 "Non-nil when TABLE-ROW is at the beginning of a column group.
4415 INFO is a plist used as a communication channel."
4416 (unless (or (eq (org-element-property :type table-row) 'rule)
4417 (org-export-table-row-is-special-p table-row info))
4418 (let ((borders (org-export-table-cell-borders
4419 (car (org-element-contents table-row)) info)))
4420 (or (memq 'top borders) (memq 'above borders)))))
4422 (defun org-export-table-row-ends-rowgroup-p (table-row info)
4423 "Non-nil when TABLE-ROW is at the end of a column group.
4424 INFO is a plist used as a communication channel."
4425 (unless (or (eq (org-element-property :type table-row) 'rule)
4426 (org-export-table-row-is-special-p table-row info))
4427 (let ((borders (org-export-table-cell-borders
4428 (car (org-element-contents table-row)) info)))
4429 (or (memq 'bottom borders) (memq 'below borders)))))
4431 (defun org-export-table-row-starts-header-p (table-row info)
4432 "Non-nil when TABLE-ROW is the first table header's row.
4433 INFO is a plist used as a communication channel."
4434 (and (org-export-table-has-header-p
4435 (org-export-get-parent-table table-row) info)
4436 (org-export-table-row-starts-rowgroup-p table-row info)
4437 (= (org-export-table-row-group table-row info) 1)))
4439 (defun org-export-table-row-ends-header-p (table-row info)
4440 "Non-nil when TABLE-ROW is the last table header's row.
4441 INFO is a plist used as a communication channel."
4442 (and (org-export-table-has-header-p
4443 (org-export-get-parent-table table-row) info)
4444 (org-export-table-row-ends-rowgroup-p table-row info)
4445 (= (org-export-table-row-group table-row info) 1)))
4447 (defun org-export-table-dimensions (table info)
4448 "Return TABLE dimensions.
4450 INFO is a plist used as a communication channel.
4452 Return value is a CONS like (ROWS . COLUMNS) where
4453 ROWS (resp. COLUMNS) is the number of exportable
4454 rows (resp. columns)."
4455 (let (first-row (columns 0) (rows 0))
4456 ;; Set number of rows, and extract first one.
4457 (org-element-map table 'table-row
4458 (lambda (row)
4459 (when (eq (org-element-property :type row) 'standard)
4460 (incf rows)
4461 (unless first-row (setq first-row row)))) info)
4462 ;; Set number of columns.
4463 (org-element-map first-row 'table-cell (lambda (cell) (incf columns)) info)
4464 ;; Return value.
4465 (cons rows columns)))
4467 (defun org-export-table-cell-address (table-cell info)
4468 "Return address of a regular TABLE-CELL object.
4470 TABLE-CELL is the cell considered. INFO is a plist used as
4471 a communication channel.
4473 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4474 zero-based index. Only exportable cells are considered. The
4475 function returns nil for other cells."
4476 (let* ((table-row (org-export-get-parent table-cell))
4477 (table (org-export-get-parent-table table-cell)))
4478 ;; Ignore cells in special rows or in special column.
4479 (unless (or (org-export-table-row-is-special-p table-row info)
4480 (and (org-export-table-has-special-column-p table)
4481 (eq (car (org-element-contents table-row)) table-cell)))
4482 (cons
4483 ;; Row number.
4484 (let ((row-count 0))
4485 (org-element-map table 'table-row
4486 (lambda (row)
4487 (cond ((eq (org-element-property :type row) 'rule) nil)
4488 ((eq row table-row) row-count)
4489 (t (incf row-count) nil)))
4490 info 'first-match))
4491 ;; Column number.
4492 (let ((col-count 0))
4493 (org-element-map table-row 'table-cell
4494 (lambda (cell)
4495 (if (eq cell table-cell) col-count (incf col-count) nil))
4496 info 'first-match))))))
4498 (defun org-export-get-table-cell-at (address table info)
4499 "Return regular table-cell object at ADDRESS in TABLE.
4501 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4502 zero-based index. TABLE is a table type element. INFO is
4503 a plist used as a communication channel.
4505 If no table-cell, among exportable cells, is found at ADDRESS,
4506 return nil."
4507 (let ((column-pos (cdr address)) (column-count 0))
4508 (org-element-map
4509 ;; Row at (car address) or nil.
4510 (let ((row-pos (car address)) (row-count 0))
4511 (org-element-map table 'table-row
4512 (lambda (row)
4513 (cond ((eq (org-element-property :type row) 'rule) nil)
4514 ((= row-count row-pos) row)
4515 (t (incf row-count) nil)))
4516 info 'first-match))
4517 'table-cell
4518 (lambda (cell)
4519 (if (= column-count column-pos) cell
4520 (incf column-count) nil))
4521 info 'first-match)))
4524 ;;;; For Tables Of Contents
4526 ;; `org-export-collect-headlines' builds a list of all exportable
4527 ;; headline elements, maybe limited to a certain depth. One can then
4528 ;; easily parse it and transcode it.
4530 ;; Building lists of tables, figures or listings is quite similar.
4531 ;; Once the generic function `org-export-collect-elements' is defined,
4532 ;; `org-export-collect-tables', `org-export-collect-figures' and
4533 ;; `org-export-collect-listings' can be derived from it.
4535 (defun org-export-collect-headlines (info &optional n)
4536 "Collect headlines in order to build a table of contents.
4538 INFO is a plist used as a communication channel.
4540 When optional argument N is an integer, it specifies the depth of
4541 the table of contents. Otherwise, it is set to the value of the
4542 last headline level. See `org-export-headline-levels' for more
4543 information.
4545 Return a list of all exportable headlines as parsed elements.
4546 Footnote sections, if any, will be ignored."
4547 (unless (wholenump n) (setq n (plist-get info :headline-levels)))
4548 (org-element-map (plist-get info :parse-tree) 'headline
4549 (lambda (headline)
4550 (unless (org-element-property :footnote-section-p headline)
4551 ;; Strip contents from HEADLINE.
4552 (let ((relative-level (org-export-get-relative-level headline info)))
4553 (unless (> relative-level n) headline))))
4554 info))
4556 (defun org-export-collect-elements (type info &optional predicate)
4557 "Collect referenceable elements of a determined type.
4559 TYPE can be a symbol or a list of symbols specifying element
4560 types to search. Only elements with a caption are collected.
4562 INFO is a plist used as a communication channel.
4564 When non-nil, optional argument PREDICATE is a function accepting
4565 one argument, an element of type TYPE. It returns a non-nil
4566 value when that element should be collected.
4568 Return a list of all elements found, in order of appearance."
4569 (org-element-map (plist-get info :parse-tree) type
4570 (lambda (element)
4571 (and (org-element-property :caption element)
4572 (or (not predicate) (funcall predicate element))
4573 element))
4574 info))
4576 (defun org-export-collect-tables (info)
4577 "Build a list of tables.
4578 INFO is a plist used as a communication channel.
4580 Return a list of table elements with a caption."
4581 (org-export-collect-elements 'table info))
4583 (defun org-export-collect-figures (info predicate)
4584 "Build a list of figures.
4586 INFO is a plist used as a communication channel. PREDICATE is
4587 a function which accepts one argument: a paragraph element and
4588 whose return value is non-nil when that element should be
4589 collected.
4591 A figure is a paragraph type element, with a caption, verifying
4592 PREDICATE. The latter has to be provided since a \"figure\" is
4593 a vague concept that may depend on back-end.
4595 Return a list of elements recognized as figures."
4596 (org-export-collect-elements 'paragraph info predicate))
4598 (defun org-export-collect-listings (info)
4599 "Build a list of src blocks.
4601 INFO is a plist used as a communication channel.
4603 Return a list of src-block elements with a caption."
4604 (org-export-collect-elements 'src-block info))
4607 ;;;; Smart Quotes
4609 ;; The main function for the smart quotes sub-system is
4610 ;; `org-export-activate-smart-quotes', which replaces every quote in
4611 ;; a given string from the parse tree with its "smart" counterpart.
4613 ;; Dictionary for smart quotes is stored in
4614 ;; `org-export-smart-quotes-alist'.
4616 ;; Internally, regexps matching potential smart quotes (checks at
4617 ;; string boundaries are also necessary) are defined in
4618 ;; `org-export-smart-quotes-regexps'.
4620 (defconst org-export-smart-quotes-alist
4621 '(("de"
4622 (opening-double-quote :utf-8 "„" :html "&bdquo;" :latex "\"`"
4623 :texinfo "@quotedblbase{}")
4624 (closing-double-quote :utf-8 "“" :html "&ldquo;" :latex "\"'"
4625 :texinfo "@quotedblleft{}")
4626 (opening-single-quote :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}"
4627 :texinfo "@quotesinglbase{}")
4628 (closing-single-quote :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}"
4629 :texinfo "@quoteleft{}")
4630 (apostrophe :utf-8 "’" :html "&rsquo;"))
4631 ("en"
4632 (opening-double-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
4633 (closing-double-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
4634 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
4635 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
4636 (apostrophe :utf-8 "’" :html "&rsquo;"))
4637 ("es"
4638 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
4639 :texinfo "@guillemetleft{}")
4640 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
4641 :texinfo "@guillemetright{}")
4642 (opening-single-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
4643 (closing-single-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
4644 (apostrophe :utf-8 "’" :html "&rsquo;"))
4645 ("fr"
4646 (opening-double-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
4647 :texinfo "@guillemetleft{}@tie{}")
4648 (closing-double-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
4649 :texinfo "@tie{}@guillemetright{}")
4650 (opening-single-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
4651 :texinfo "@guillemetleft{}@tie{}")
4652 (closing-single-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
4653 :texinfo "@tie{}@guillemetright{}")
4654 (apostrophe :utf-8 "’" :html "&rsquo;")))
4655 "Smart quotes translations.
4657 Alist whose CAR is a language string and CDR is an alist with
4658 quote type as key and a plist associating various encodings to
4659 their translation as value.
4661 A quote type can be any symbol among `opening-double-quote',
4662 `closing-double-quote', `opening-single-quote',
4663 `closing-single-quote' and `apostrophe'.
4665 Valid encodings include `:utf-8', `:html', `:latex' and
4666 `:texinfo'.
4668 If no translation is found, the quote character is left as-is.")
4670 (defconst org-export-smart-quotes-regexps
4671 (list
4672 ;; Possible opening quote at beginning of string.
4673 "\\`\\([\"']\\)\\(\\w\\|\\s.\\|\\s_\\)"
4674 ;; Possible closing quote at beginning of string.
4675 "\\`\\([\"']\\)\\(\\s-\\|\\s)\\|\\s.\\)"
4676 ;; Possible apostrophe at beginning of string.
4677 "\\`\\('\\)\\S-"
4678 ;; Opening single and double quotes.
4679 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\(?:\\w\\|\\s.\\|\\s_\\)"
4680 ;; Closing single and double quotes.
4681 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\(?:\\s-\\|\\s)\\|\\s.\\)"
4682 ;; Apostrophe.
4683 "\\S-\\('\\)\\S-"
4684 ;; Possible opening quote at end of string.
4685 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\'"
4686 ;; Possible closing quote at end of string.
4687 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\'"
4688 ;; Possible apostrophe at end of string.
4689 "\\S-\\('\\)\\'")
4690 "List of regexps matching a quote or an apostrophe.
4691 In every regexp, quote or apostrophe matched is put in group 1.")
4693 (defun org-export-activate-smart-quotes (s encoding info &optional original)
4694 "Replace regular quotes with \"smart\" quotes in string S.
4696 ENCODING is a symbol among `:html', `:latex', `:texinfo' and
4697 `:utf-8'. INFO is a plist used as a communication channel.
4699 The function has to retrieve information about string
4700 surroundings in parse tree. It can only happen with an
4701 unmodified string. Thus, if S has already been through another
4702 process, a non-nil ORIGINAL optional argument will provide that
4703 original string.
4705 Return the new string."
4706 (if (equal s "") ""
4707 (let* ((prev (org-export-get-previous-element (or original s) info))
4708 ;; Try to be flexible when computing number of blanks
4709 ;; before object. The previous object may be a string
4710 ;; introduced by the back-end and not completely parsed.
4711 (pre-blank (and prev
4712 (or (org-element-property :post-blank prev)
4713 ;; A string with missing `:post-blank'
4714 ;; property.
4715 (and (stringp prev)
4716 (string-match " *\\'" prev)
4717 (length (match-string 0 prev)))
4718 ;; Fallback value.
4719 0)))
4720 (next (org-export-get-next-element (or original s) info))
4721 (get-smart-quote
4722 (lambda (q type)
4723 ;; Return smart quote associated to a give quote Q, as
4724 ;; a string. TYPE is a symbol among `open', `close' and
4725 ;; `apostrophe'.
4726 (let ((key (case type
4727 (apostrophe 'apostrophe)
4728 (open (if (equal "'" q) 'opening-single-quote
4729 'opening-double-quote))
4730 (otherwise (if (equal "'" q) 'closing-single-quote
4731 'closing-double-quote)))))
4732 (or (plist-get
4733 (cdr (assq key
4734 (cdr (assoc (plist-get info :language)
4735 org-export-smart-quotes-alist))))
4736 encoding)
4737 q)))))
4738 (if (or (equal "\"" s) (equal "'" s))
4739 ;; Only a quote: no regexp can match. We have to check both
4740 ;; sides and decide what to do.
4741 (cond ((and (not prev) (not next)) s)
4742 ((not prev) (funcall get-smart-quote s 'open))
4743 ((and (not next) (zerop pre-blank))
4744 (funcall get-smart-quote s 'close))
4745 ((not next) s)
4746 ((zerop pre-blank) (funcall get-smart-quote s 'apostrophe))
4747 (t (funcall get-smart-quote 'open)))
4748 ;; 1. Replace quote character at the beginning of S.
4749 (cond
4750 ;; Apostrophe?
4751 ((and prev (zerop pre-blank)
4752 (string-match (nth 2 org-export-smart-quotes-regexps) s))
4753 (setq s (replace-match
4754 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
4755 nil t s 1)))
4756 ;; Closing quote?
4757 ((and prev (zerop pre-blank)
4758 (string-match (nth 1 org-export-smart-quotes-regexps) s))
4759 (setq s (replace-match
4760 (funcall get-smart-quote (match-string 1 s) 'close)
4761 nil t s 1)))
4762 ;; Opening quote?
4763 ((and (or (not prev) (> pre-blank 0))
4764 (string-match (nth 0 org-export-smart-quotes-regexps) s))
4765 (setq s (replace-match
4766 (funcall get-smart-quote (match-string 1 s) 'open)
4767 nil t s 1))))
4768 ;; 2. Replace quotes in the middle of the string.
4769 (setq s (replace-regexp-in-string
4770 ;; Opening quotes.
4771 (nth 3 org-export-smart-quotes-regexps)
4772 (lambda (text)
4773 (funcall get-smart-quote (match-string 1 text) 'open))
4774 s nil t 1))
4775 (setq s (replace-regexp-in-string
4776 ;; Closing quotes.
4777 (nth 4 org-export-smart-quotes-regexps)
4778 (lambda (text)
4779 (funcall get-smart-quote (match-string 1 text) 'close))
4780 s nil t 1))
4781 (setq s (replace-regexp-in-string
4782 ;; Apostrophes.
4783 (nth 5 org-export-smart-quotes-regexps)
4784 (lambda (text)
4785 (funcall get-smart-quote (match-string 1 text) 'apostrophe))
4786 s nil t 1))
4787 ;; 3. Replace quote character at the end of S.
4788 (cond
4789 ;; Apostrophe?
4790 ((and next (string-match (nth 8 org-export-smart-quotes-regexps) s))
4791 (setq s (replace-match
4792 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
4793 nil t s 1)))
4794 ;; Closing quote?
4795 ((and (not next)
4796 (string-match (nth 7 org-export-smart-quotes-regexps) s))
4797 (setq s (replace-match
4798 (funcall get-smart-quote (match-string 1 s) 'close)
4799 nil t s 1)))
4800 ;; Opening quote?
4801 ((and next (string-match (nth 6 org-export-smart-quotes-regexps) s))
4802 (setq s (replace-match
4803 (funcall get-smart-quote (match-string 1 s) 'open)
4804 nil t s 1))))
4805 ;; Return string with smart quotes.
4806 s))))
4808 ;;;; Topology
4810 ;; Here are various functions to retrieve information about the
4811 ;; neighbourhood of a given element or object. Neighbours of interest
4812 ;; are direct parent (`org-export-get-parent'), parent headline
4813 ;; (`org-export-get-parent-headline'), first element containing an
4814 ;; object, (`org-export-get-parent-element'), parent table
4815 ;; (`org-export-get-parent-table'), previous element or object
4816 ;; (`org-export-get-previous-element') and next element or object
4817 ;; (`org-export-get-next-element').
4819 ;; `org-export-get-genealogy' returns the full genealogy of a given
4820 ;; element or object, from closest parent to full parse tree.
4822 (defun org-export-get-parent (blob)
4823 "Return BLOB parent or nil.
4824 BLOB is the element or object considered."
4825 (org-element-property :parent blob))
4827 (defun org-export-get-genealogy (blob)
4828 "Return full genealogy relative to a given element or object.
4830 BLOB is the element or object being considered.
4832 Ancestors are returned from closest to farthest, the last one
4833 being the full parse tree."
4834 (let (genealogy (parent blob))
4835 (while (setq parent (org-element-property :parent parent))
4836 (push parent genealogy))
4837 (nreverse genealogy)))
4839 (defun org-export-get-parent-headline (blob)
4840 "Return BLOB parent headline or nil.
4841 BLOB is the element or object being considered."
4842 (let ((parent blob))
4843 (while (and (setq parent (org-element-property :parent parent))
4844 (not (eq (org-element-type parent) 'headline))))
4845 parent))
4847 (defun org-export-get-parent-element (object)
4848 "Return first element containing OBJECT or nil.
4849 OBJECT is the object to consider."
4850 (let ((parent object))
4851 (while (and (setq parent (org-element-property :parent parent))
4852 (memq (org-element-type parent) org-element-all-objects)))
4853 parent))
4855 (defun org-export-get-parent-table (object)
4856 "Return OBJECT parent table or nil.
4857 OBJECT is either a `table-cell' or `table-element' type object."
4858 (let ((parent object))
4859 (while (and (setq parent (org-element-property :parent parent))
4860 (not (eq (org-element-type parent) 'table))))
4861 parent))
4863 (defun org-export-get-previous-element (blob info &optional n)
4864 "Return previous element or object.
4866 BLOB is an element or object. INFO is a plist used as
4867 a communication channel. Return previous exportable element or
4868 object, a string, or nil.
4870 When optional argument N is a positive integer, return a list
4871 containing up to N siblings before BLOB, from farthest to
4872 closest. With any other non-nil value, return a list containing
4873 all of them."
4874 (let ((siblings
4875 ;; An object can belong to the contents of its parent or
4876 ;; to a secondary string. We check the latter option
4877 ;; first.
4878 (let ((parent (org-export-get-parent blob)))
4879 (or (and (not (memq (org-element-type blob)
4880 org-element-all-elements))
4881 (let ((sec-value
4882 (org-element-property
4883 (cdr (assq (org-element-type parent)
4884 org-element-secondary-value-alist))
4885 parent)))
4886 (and (memq blob sec-value) sec-value)))
4887 (org-element-contents parent))))
4888 prev)
4889 (catch 'exit
4890 (mapc (lambda (obj)
4891 (cond ((memq obj (plist-get info :ignore-list)))
4892 ((null n) (throw 'exit obj))
4893 ((not (wholenump n)) (push obj prev))
4894 ((zerop n) (throw 'exit prev))
4895 (t (decf n) (push obj prev))))
4896 (cdr (memq blob (reverse siblings))))
4897 prev)))
4899 (defun org-export-get-next-element (blob info &optional n)
4900 "Return next element or object.
4902 BLOB is an element or object. INFO is a plist used as
4903 a communication channel. Return next exportable element or
4904 object, a string, or nil.
4906 When optional argument N is a positive integer, return a list
4907 containing up to N siblings after BLOB, from closest to farthest.
4908 With any other non-nil value, return a list containing all of
4909 them."
4910 (let ((siblings
4911 ;; An object can belong to the contents of its parent or to
4912 ;; a secondary string. We check the latter option first.
4913 (let ((parent (org-export-get-parent blob)))
4914 (or (and (not (memq (org-element-type blob)
4915 org-element-all-objects))
4916 (let ((sec-value
4917 (org-element-property
4918 (cdr (assq (org-element-type parent)
4919 org-element-secondary-value-alist))
4920 parent)))
4921 (cdr (memq blob sec-value))))
4922 (cdr (memq blob (org-element-contents parent))))))
4923 next)
4924 (catch 'exit
4925 (mapc (lambda (obj)
4926 (cond ((memq obj (plist-get info :ignore-list)))
4927 ((null n) (throw 'exit obj))
4928 ((not (wholenump n)) (push obj next))
4929 ((zerop n) (throw 'exit (nreverse next)))
4930 (t (decf n) (push obj next))))
4931 siblings)
4932 (nreverse next))))
4935 ;;;; Translation
4937 ;; `org-export-translate' translates a string according to language
4938 ;; specified by LANGUAGE keyword or `org-export-language-setup'
4939 ;; variable and a specified charset. `org-export-dictionary' contains
4940 ;; the dictionary used for the translation.
4942 (defconst org-export-dictionary
4943 '(("Author"
4944 ("ca" :default "Autor")
4945 ("cs" :default "Autor")
4946 ("da" :default "Ophavsmand")
4947 ("de" :default "Autor")
4948 ("eo" :html "A&#365;toro")
4949 ("es" :default "Autor")
4950 ("fi" :html "Tekij&auml;")
4951 ("fr" :default "Auteur")
4952 ("hu" :default "Szerz&otilde;")
4953 ("is" :html "H&ouml;fundur")
4954 ("it" :default "Autore")
4955 ("ja" :html "&#33879;&#32773;" :utf-8 "著者")
4956 ("nl" :default "Auteur")
4957 ("no" :default "Forfatter")
4958 ("nb" :default "Forfatter")
4959 ("nn" :default "Forfattar")
4960 ("pl" :default "Autor")
4961 ("ru" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
4962 ("sv" :html "F&ouml;rfattare")
4963 ("uk" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
4964 ("zh-CN" :html "&#20316;&#32773;" :utf-8 "作者")
4965 ("zh-TW" :html "&#20316;&#32773;" :utf-8 "作者"))
4966 ("Date"
4967 ("ca" :default "Data")
4968 ("cs" :default "Datum")
4969 ("da" :default "Dato")
4970 ("de" :default "Datum")
4971 ("eo" :default "Dato")
4972 ("es" :default "Fecha")
4973 ("fi" :html "P&auml;iv&auml;m&auml;&auml;r&auml;")
4974 ("hu" :html "D&aacute;tum")
4975 ("is" :default "Dagsetning")
4976 ("it" :default "Data")
4977 ("ja" :html "&#26085;&#20184;" :utf-8 "日付")
4978 ("nl" :default "Datum")
4979 ("no" :default "Dato")
4980 ("nb" :default "Dato")
4981 ("nn" :default "Dato")
4982 ("pl" :default "Data")
4983 ("ru" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
4984 ("sv" :default "Datum")
4985 ("uk" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
4986 ("zh-CN" :html "&#26085;&#26399;" :utf-8 "日期")
4987 ("zh-TW" :html "&#26085;&#26399;" :utf-8 "日期"))
4988 ("Equation"
4989 ("fr" :ascii "Equation" :default "Équation"))
4990 ("Figure")
4991 ("Footnotes"
4992 ("ca" :html "Peus de p&agrave;gina")
4993 ("cs" :default "Pozn\xe1mky pod carou")
4994 ("da" :default "Fodnoter")
4995 ("de" :html "Fu&szlig;noten")
4996 ("eo" :default "Piednotoj")
4997 ("es" :html "Pies de p&aacute;gina")
4998 ("fi" :default "Alaviitteet")
4999 ("fr" :default "Notes de bas de page")
5000 ("hu" :html "L&aacute;bjegyzet")
5001 ("is" :html "Aftanm&aacute;lsgreinar")
5002 ("it" :html "Note a pi&egrave; di pagina")
5003 ("ja" :html "&#33050;&#27880;" :utf-8 "脚注")
5004 ("nl" :default "Voetnoten")
5005 ("no" :default "Fotnoter")
5006 ("nb" :default "Fotnoter")
5007 ("nn" :default "Fotnotar")
5008 ("pl" :default "Przypis")
5009 ("ru" :html "&#1057;&#1085;&#1086;&#1089;&#1082;&#1080;" :utf-8 "Сноски")
5010 ("sv" :default "Fotnoter")
5011 ("uk" :html "&#1055;&#1088;&#1080;&#1084;&#1110;&#1090;&#1082;&#1080;"
5012 :utf-8 "Примітки")
5013 ("zh-CN" :html "&#33050;&#27880;" :utf-8 "脚注")
5014 ("zh-TW" :html "&#33139;&#35387;" :utf-8 "腳註"))
5015 ("List of Listings"
5016 ("fr" :default "Liste des programmes"))
5017 ("List of Tables"
5018 ("fr" :default "Liste des tableaux"))
5019 ("Listing %d:"
5020 ("fr"
5021 :ascii "Programme %d :" :default "Programme nº %d :"
5022 :latin1 "Programme %d :"))
5023 ("Listing %d: %s"
5024 ("fr"
5025 :ascii "Programme %d : %s" :default "Programme nº %d : %s"
5026 :latin1 "Programme %d : %s"))
5027 ("See section %s"
5028 ("fr" :default "cf. section %s"))
5029 ("Table %d:"
5030 ("fr"
5031 :ascii "Tableau %d :" :default "Tableau nº %d :" :latin1 "Tableau %d :"))
5032 ("Table %d: %s"
5033 ("fr"
5034 :ascii "Tableau %d : %s" :default "Tableau nº %d : %s"
5035 :latin1 "Tableau %d : %s"))
5036 ("Table of Contents"
5037 ("ca" :html "&Iacute;ndex")
5038 ("cs" :default "Obsah")
5039 ("da" :default "Indhold")
5040 ("de" :default "Inhaltsverzeichnis")
5041 ("eo" :default "Enhavo")
5042 ("es" :html "&Iacute;ndice")
5043 ("fi" :html "Sis&auml;llysluettelo")
5044 ("fr" :ascii "Sommaire" :default "Table des matières")
5045 ("hu" :html "Tartalomjegyz&eacute;k")
5046 ("is" :default "Efnisyfirlit")
5047 ("it" :default "Indice")
5048 ("ja" :html "&#30446;&#27425;" :utf-8 "目次")
5049 ("nl" :default "Inhoudsopgave")
5050 ("no" :default "Innhold")
5051 ("nb" :default "Innhold")
5052 ("nn" :default "Innhald")
5053 ("pl" :html "Spis tre&#x015b;ci")
5054 ("ru" :html "&#1057;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1077;"
5055 :utf-8 "Содержание")
5056 ("sv" :html "Inneh&aring;ll")
5057 ("uk" :html "&#1047;&#1084;&#1110;&#1089;&#1090;" :utf-8 "Зміст")
5058 ("zh-CN" :html "&#30446;&#24405;" :utf-8 "目录")
5059 ("zh-TW" :html "&#30446;&#37636;" :utf-8 "目錄"))
5060 ("Unknown reference"
5061 ("fr" :ascii "Destination inconnue" :default "Référence inconnue")))
5062 "Dictionary for export engine.
5064 Alist whose CAR is the string to translate and CDR is an alist
5065 whose CAR is the language string and CDR is a plist whose
5066 properties are possible charsets and values translated terms.
5068 It is used as a database for `org-export-translate'. Since this
5069 function returns the string as-is if no translation was found,
5070 the variable only needs to record values different from the
5071 entry.")
5073 (defun org-export-translate (s encoding info)
5074 "Translate string S according to language specification.
5076 ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1'
5077 and `:utf-8'. INFO is a plist used as a communication channel.
5079 Translation depends on `:language' property. Return the
5080 translated string. If no translation is found, try to fall back
5081 to `:default' encoding. If it fails, return S."
5082 (let* ((lang (plist-get info :language))
5083 (translations (cdr (assoc lang
5084 (cdr (assoc s org-export-dictionary))))))
5085 (or (plist-get translations encoding)
5086 (plist-get translations :default)
5087 s)))
5091 ;;; Asynchronous Export
5093 ;; `org-export-async-start' is the entry point for asynchronous
5094 ;; export. It recreates current buffer (including visibility,
5095 ;; narrowing and visited file) in an external Emacs process, and
5096 ;; evaluates a command there. It then applies a function on the
5097 ;; returned results in the current process.
5099 ;; Asynchronously generated results are never displayed directly.
5100 ;; Instead, they are stored in `org-export-stack-contents'. They can
5101 ;; then be retrieved by calling `org-export-stack'.
5103 ;; Export Stack is viewed through a dedicated major mode
5104 ;;`org-export-stack-mode' and tools: `org-export-stack-refresh',
5105 ;;`org-export-stack-delete', `org-export-stack-view' and
5106 ;;`org-export-stack-clear'.
5108 ;; For back-ends, `org-export-add-to-stack' add a new source to stack.
5109 ;; It should used whenever `org-export-async-start' is called.
5111 (defmacro org-export-async-start (fun &rest body)
5112 "Call function FUN on the results returned by BODY evaluation.
5114 BODY evaluation happens in an asynchronous process, from a buffer
5115 which is an exact copy of the current one.
5117 Use `org-export-add-to-stack' in FUN in order to register results
5118 in the stack. Examples for, respectively a temporary buffer and
5119 a file are:
5121 \(org-export-async-start
5122 \(lambda (output)
5123 \(with-current-buffer (get-buffer-create \"*Org BACKEND Export*\")
5124 \(erase-buffer)
5125 \(insert output)
5126 \(goto-char (point-min))
5127 \(org-export-add-to-stack (current-buffer) 'backend)))
5128 `(org-export-as 'backend ,subtreep ,visible-only ,body-only ',ext-plist))
5132 \(org-export-async-start
5133 \(lambda (f) (org-export-add-to-stack f 'backend))
5134 `(expand-file-name
5135 \(org-export-to-file
5136 'backend ,outfile ,subtreep ,visible-only ,body-only ',ext-plist)))"
5137 (declare (indent 1) (debug t))
5138 (org-with-gensyms (process temp-file copy-fun proc-buffer handler)
5139 ;; Write the full sexp evaluating BODY in a copy of the current
5140 ;; buffer to a temporary file, as it may be too long for program
5141 ;; args in `start-process'.
5142 `(with-temp-message "Initializing asynchronous export process"
5143 (let ((,copy-fun (org-export--generate-copy-script (current-buffer)))
5144 (,temp-file (make-temp-file "org-export-process")))
5145 (with-temp-file ,temp-file
5146 (insert
5147 (format
5148 "%S"
5149 `(with-temp-buffer
5150 ,(when org-export-async-debug '(setq debug-on-error t))
5151 ;; Ignore `kill-emacs-hook' and code evaluation
5152 ;; queries from Babel as we need a truly
5153 ;; non-interactive process.
5154 (setq kill-emacs-hook nil
5155 org-babel-confirm-evaluate-answer-no t)
5156 ;; Initialize export framework in external process.
5157 (require 'ox)
5158 ;; Re-create current buffer there.
5159 (funcall ,,copy-fun)
5160 (restore-buffer-modified-p nil)
5161 ;; Sexp to evaluate in the buffer.
5162 (print (progn ,,@body))))))
5163 ;; Start external process.
5164 (let* ((process-connection-type nil)
5165 (,proc-buffer (generate-new-buffer-name "*Org Export Process*"))
5166 (,process
5167 (start-process
5168 "org-export-process" ,proc-buffer
5169 (expand-file-name invocation-name invocation-directory)
5170 "-Q" "--batch"
5171 "-l" org-export-async-init-file
5172 "-l" ,temp-file)))
5173 ;; Register running process in stack.
5174 (org-export-add-to-stack (get-buffer ,proc-buffer) nil ,process)
5175 ;; Set-up sentinel in order to catch results.
5176 (set-process-sentinel
5177 ,process
5178 (let ((handler ',fun))
5179 `(lambda (p status)
5180 (let ((proc-buffer (process-buffer p)))
5181 (when (eq (process-status p) 'exit)
5182 (unwind-protect
5183 (if (zerop (process-exit-status p))
5184 (unwind-protect
5185 (let ((results
5186 (with-current-buffer proc-buffer
5187 (goto-char (point-max))
5188 (backward-sexp)
5189 (read (current-buffer)))))
5190 (funcall ,handler results))
5191 (unless org-export-async-debug
5192 (and (get-buffer proc-buffer)
5193 (kill-buffer proc-buffer))))
5194 (org-export-add-to-stack proc-buffer nil p)
5195 (ding)
5196 (message "Process '%s' exited abnormally" p))
5197 (unless org-export-async-debug
5198 (delete-file ,,temp-file)))))))))))))
5200 (defun org-export-add-to-stack (source backend &optional process)
5201 "Add a new result to export stack if not present already.
5203 SOURCE is a buffer or a file name containing export results.
5204 BACKEND is a symbol representing export back-end used to generate
5207 Entries already pointing to SOURCE and unavailable entries are
5208 removed beforehand. Return the new stack."
5209 (setq org-export-stack-contents
5210 (cons (list source backend (or process (current-time)))
5211 (org-export-stack-remove source))))
5213 (defun org-export-stack ()
5214 "Menu for asynchronous export results and running processes."
5215 (interactive)
5216 (let ((buffer (get-buffer-create "*Org Export Stack*")))
5217 (set-buffer buffer)
5218 (when (zerop (buffer-size)) (org-export-stack-mode))
5219 (org-export-stack-refresh)
5220 (pop-to-buffer buffer))
5221 (message "Type \"q\" to quit, \"?\" for help"))
5223 (defun org-export--stack-source-at-point ()
5224 "Return source from export results at point in stack."
5225 (let ((source (car (nth (1- (org-current-line)) org-export-stack-contents))))
5226 (if (not source) (error "Source unavailable, please refresh buffer")
5227 (let ((source-name (if (stringp source) source (buffer-name source))))
5228 (if (save-excursion
5229 (beginning-of-line)
5230 (looking-at (concat ".* +" (regexp-quote source-name) "$")))
5231 source
5232 ;; SOURCE is not consistent with current line. The stack
5233 ;; view is outdated.
5234 (error "Source unavailable; type `g' to update buffer"))))))
5236 (defun org-export-stack-clear ()
5237 "Remove all entries from export stack."
5238 (interactive)
5239 (setq org-export-stack-contents nil))
5241 (defun org-export-stack-refresh (&rest dummy)
5242 "Refresh the asynchronous export stack.
5243 DUMMY is ignored. Unavailable sources are removed from the list.
5244 Return the new stack."
5245 (let ((inhibit-read-only t))
5246 (org-preserve-lc
5247 (erase-buffer)
5248 (insert (concat
5249 (let ((counter 0))
5250 (mapconcat
5251 (lambda (entry)
5252 (let ((proc-p (processp (nth 2 entry))))
5253 (concat
5254 ;; Back-end.
5255 (format " %-12s " (or (nth 1 entry) ""))
5256 ;; Age.
5257 (let ((data (nth 2 entry)))
5258 (if proc-p (format " %6s " (process-status data))
5259 ;; Compute age of the results.
5260 (org-format-seconds
5261 "%4h:%.2m "
5262 (float-time (time-since data)))))
5263 ;; Source.
5264 (format " %s"
5265 (let ((source (car entry)))
5266 (if (stringp source) source
5267 (buffer-name source)))))))
5268 ;; Clear stack from exited processes, dead buffers or
5269 ;; non-existent files.
5270 (setq org-export-stack-contents
5271 (org-remove-if-not
5272 (lambda (el)
5273 (if (processp (nth 2 el))
5274 (buffer-live-p (process-buffer (nth 2 el)))
5275 (let ((source (car el)))
5276 (if (bufferp source) (buffer-live-p source)
5277 (file-exists-p source)))))
5278 org-export-stack-contents)) "\n")))))))
5280 (defun org-export-stack-remove (&optional source)
5281 "Remove export results at point from stack.
5282 If optional argument SOURCE is non-nil, remove it instead."
5283 (interactive)
5284 (let ((source (or source (org-export--stack-source-at-point))))
5285 (setq org-export-stack-contents
5286 (org-remove-if (lambda (el) (equal (car el) source))
5287 org-export-stack-contents))))
5289 (defun org-export-stack-view (&optional in-emacs)
5290 "View export results at point in stack.
5291 With an optional prefix argument IN-EMACS, force viewing files
5292 within Emacs."
5293 (interactive "P")
5294 (let ((source (org-export--stack-source-at-point)))
5295 (cond ((processp source)
5296 (org-switch-to-buffer-other-window (process-buffer source)))
5297 ((bufferp source) (org-switch-to-buffer-other-window source))
5298 (t (org-open-file source in-emacs)))))
5300 (defconst org-export-stack-mode-map
5301 (let ((km (make-sparse-keymap)))
5302 (define-key km " " 'next-line)
5303 (define-key km "n" 'next-line)
5304 (define-key km "\C-n" 'next-line)
5305 (define-key km [down] 'next-line)
5306 (define-key km "p" 'previous-line)
5307 (define-key km "\C-p" 'previous-line)
5308 (define-key km "\C-?" 'previous-line)
5309 (define-key km [up] 'previous-line)
5310 (define-key km "C" 'org-export-stack-clear)
5311 (define-key km "v" 'org-export-stack-view)
5312 (define-key km (kbd "RET") 'org-export-stack-view)
5313 (define-key km "d" 'org-export-stack-remove)
5315 "Keymap for Org Export Stack.")
5317 (define-derived-mode org-export-stack-mode special-mode "Org-Stack"
5318 "Mode for displaying asynchronous export stack.
5320 Type \\[org-export-stack] to visualize the asynchronous export
5321 stack.
5323 In an Org Export Stack buffer, use \\<org-export-stack-mode-map>\\[org-export-stack-view] to view export output
5324 on current line, \\[org-export-stack-remove] to remove it from the stack and \\[org-export-stack-clear] to clear
5325 stack completely.
5327 Removing entries in an Org Export Stack buffer doesn't affect
5328 files or buffers, only the display.
5330 \\{org-export-stack-mode-map}"
5331 (abbrev-mode 0)
5332 (auto-fill-mode 0)
5333 (setq buffer-read-only t
5334 buffer-undo-list t
5335 truncate-lines t
5336 header-line-format
5337 '(:eval
5338 (format " %-12s | %6s | %s" "Back-End" "Age" "Source")))
5339 (add-hook 'post-command-hook 'org-export-stack-refresh nil t)
5340 (set (make-local-variable 'revert-buffer-function)
5341 'org-export-stack-refresh))
5345 ;;; The Dispatcher
5347 ;; `org-export-dispatch' is the standard interactive way to start an
5348 ;; export process. It uses `org-export--dispatch-ui' as a subroutine
5349 ;; for its interface, which, in turn, delegates response to key
5350 ;; pressed to `org-export--dispatch-action'.
5352 ;;;###autoload
5353 (defun org-export-dispatch (&optional arg)
5354 "Export dispatcher for Org mode.
5356 It provides an access to common export related tasks in a buffer.
5357 Its interface comes in two flavours: standard and expert.
5359 While both share the same set of bindings, only the former
5360 displays the valid keys associations in a dedicated buffer.
5361 Scrolling (resp. line-wise motion) in this buffer is done with
5362 SPC and DEL (resp. C-n and C-p) keys.
5364 Set variable `org-export-dispatch-use-expert-ui' to switch to one
5365 flavour or the other.
5367 When ARG is \\[universal-argument], repeat the last export action, with the same set
5368 of options used back then, on the current buffer.
5370 When ARG is \\[universal-argument] \\[universal-argument], display the asynchronous export stack."
5371 (interactive "P")
5372 (let* ((input
5373 (cond ((equal arg '(16)) '(stack))
5374 ((and arg org-export-dispatch-last-action))
5375 (t (save-window-excursion
5376 (unwind-protect
5377 (progn
5378 ;; Remember where we are
5379 (move-marker org-export-dispatch-last-position
5380 (point)
5381 (org-base-buffer (current-buffer)))
5382 ;; Get and store an export command
5383 (setq org-export-dispatch-last-action
5384 (org-export--dispatch-ui
5385 (list org-export-initial-scope
5386 (and org-export-in-background 'async))
5388 org-export-dispatch-use-expert-ui)))
5389 (and (get-buffer "*Org Export Dispatcher*")
5390 (kill-buffer "*Org Export Dispatcher*")))))))
5391 (action (car input))
5392 (optns (cdr input)))
5393 (unless (memq 'subtree optns)
5394 (move-marker org-export-dispatch-last-position nil))
5395 (case action
5396 ;; First handle special hard-coded actions.
5397 (stack (org-export-stack))
5398 (publish-current-file
5399 (org-publish-current-file (memq 'force optns) (memq 'async optns)))
5400 (publish-current-project
5401 (org-publish-current-project (memq 'force optns) (memq 'async optns)))
5402 (publish-choose-project
5403 (org-publish (assoc (org-icompleting-read
5404 "Publish project: "
5405 org-publish-project-alist nil t)
5406 org-publish-project-alist)
5407 (memq 'force optns)
5408 (memq 'async optns)))
5409 (publish-all (org-publish-all (memq 'force optns) (memq 'async optns)))
5410 (otherwise
5411 (save-excursion
5412 (when arg
5413 ;; Repeating command, maybe move cursor
5414 ;; to restore subtree context
5415 (if (eq (marker-buffer org-export-dispatch-last-position)
5416 (org-base-buffer (current-buffer)))
5417 (goto-char org-export-dispatch-last-position)
5418 ;; We are in a differnet buffer, forget position
5419 (move-marker org-export-dispatch-last-position nil)))
5420 (funcall action
5421 ;; Return a symbol instead of a list to ease
5422 ;; asynchronous export macro use.
5423 (and (memq 'async optns) t)
5424 (and (memq 'subtree optns) t)
5425 (and (memq 'visible optns) t)
5426 (and (memq 'body optns) t)))))))
5428 (defun org-export--dispatch-ui (options first-key expertp)
5429 "Handle interface for `org-export-dispatch'.
5431 OPTIONS is a list containing current interactive options set for
5432 export. It can contain any of the following symbols:
5433 `body' toggles a body-only export
5434 `subtree' restricts export to current subtree
5435 `visible' restricts export to visible part of buffer.
5436 `force' force publishing files.
5437 `async' use asynchronous export process
5439 FIRST-KEY is the key pressed to select the first level menu. It
5440 is nil when this menu hasn't been selected yet.
5442 EXPERTP, when non-nil, triggers expert UI. In that case, no help
5443 buffer is provided, but indications about currently active
5444 options are given in the prompt. Moreover, \[?] allows to switch
5445 back to standard interface."
5446 (let* ((fontify-key
5447 (lambda (key &optional access-key)
5448 ;; Fontify KEY string. Optional argument ACCESS-KEY, when
5449 ;; non-nil is the required first-level key to activate
5450 ;; KEY. When its value is t, activate KEY independently
5451 ;; on the first key, if any. A nil value means KEY will
5452 ;; only be activated at first level.
5453 (if (or (eq access-key t) (eq access-key first-key))
5454 (org-propertize key 'face 'org-warning)
5455 key)))
5456 (fontify-value
5457 (lambda (value)
5458 ;; Fontify VALUE string.
5459 (org-propertize value 'face 'font-lock-variable-name-face)))
5460 ;; Prepare menu entries by extracting them from
5461 ;; `org-export-registered-backends', and sorting them by
5462 ;; access key and by ordinal, if any.
5463 (backends
5464 (sort
5465 (sort
5466 (delq nil
5467 (mapcar
5468 (lambda (b)
5469 (let ((name (car b)))
5470 (catch 'ignored
5471 ;; Ignore any back-end belonging to
5472 ;; `org-export-invisible-backends' or derived
5473 ;; from one of them.
5474 (dolist (ignored org-export-invisible-backends)
5475 (when (org-export-derived-backend-p name ignored)
5476 (throw 'ignored nil)))
5477 (org-export-backend-menu name))))
5478 org-export-registered-backends))
5479 (lambda (a b)
5480 (let ((key-a (nth 1 a))
5481 (key-b (nth 1 b)))
5482 (cond ((and (numberp key-a) (numberp key-b))
5483 (< key-a key-b))
5484 ((numberp key-b) t)))))
5485 (lambda (a b) (< (car a) (car b)))))
5486 ;; Compute a list of allowed keys based on the first key
5487 ;; pressed, if any. Some keys (?^B, ?^V, ?^S, ?^F, ?^A
5488 ;; and ?q) are always available.
5489 (allowed-keys
5490 (nconc (list 2 22 19 6 1)
5491 (if (not first-key) (org-uniquify (mapcar 'car backends))
5492 (let (sub-menu)
5493 (dolist (backend backends (sort (mapcar 'car sub-menu) '<))
5494 (when (eq (car backend) first-key)
5495 (setq sub-menu (append (nth 2 backend) sub-menu))))))
5496 (cond ((eq first-key ?P) (list ?f ?p ?x ?a))
5497 ((not first-key) (list ?P)))
5498 (list ?&)
5499 (when expertp (list ??))
5500 (list ?q)))
5501 ;; Build the help menu for standard UI.
5502 (help
5503 (unless expertp
5504 (concat
5505 ;; Options are hard-coded.
5506 (format "Options
5507 [%s] Body only: %s [%s] Visible only: %s
5508 [%s] Export scope: %s [%s] Force publishing: %s
5509 [%s] Async export: %s\n"
5510 (funcall fontify-key "C-b" t)
5511 (funcall fontify-value
5512 (if (memq 'body options) "On " "Off"))
5513 (funcall fontify-key "C-v" t)
5514 (funcall fontify-value
5515 (if (memq 'visible options) "On " "Off"))
5516 (funcall fontify-key "C-s" t)
5517 (funcall fontify-value
5518 (if (memq 'subtree options) "Subtree" "Buffer "))
5519 (funcall fontify-key "C-f" t)
5520 (funcall fontify-value
5521 (if (memq 'force options) "On " "Off"))
5522 (funcall fontify-key "C-a" t)
5523 (funcall fontify-value
5524 (if (memq 'async options) "On " "Off")))
5525 ;; Display registered back-end entries. When a key
5526 ;; appears for the second time, do not create another
5527 ;; entry, but append its sub-menu to existing menu.
5528 (let (last-key)
5529 (mapconcat
5530 (lambda (entry)
5531 (let ((top-key (car entry)))
5532 (concat
5533 (unless (eq top-key last-key)
5534 (setq last-key top-key)
5535 (format "\n[%s] %s\n"
5536 (funcall fontify-key (char-to-string top-key))
5537 (nth 1 entry)))
5538 (let ((sub-menu (nth 2 entry)))
5539 (unless (functionp sub-menu)
5540 ;; Split sub-menu into two columns.
5541 (let ((index -1))
5542 (concat
5543 (mapconcat
5544 (lambda (sub-entry)
5545 (incf index)
5546 (format
5547 (if (zerop (mod index 2)) " [%s] %-26s"
5548 "[%s] %s\n")
5549 (funcall fontify-key
5550 (char-to-string (car sub-entry))
5551 top-key)
5552 (nth 1 sub-entry)))
5553 sub-menu "")
5554 (when (zerop (mod index 2)) "\n"))))))))
5555 backends ""))
5556 ;; Publishing menu is hard-coded.
5557 (format "\n[%s] Publish
5558 [%s] Current file [%s] Current project
5559 [%s] Choose project [%s] All projects\n\n"
5560 (funcall fontify-key "P")
5561 (funcall fontify-key "f" ?P)
5562 (funcall fontify-key "p" ?P)
5563 (funcall fontify-key "x" ?P)
5564 (funcall fontify-key "a" ?P))
5565 (format "\[%s] Export stack\n" (funcall fontify-key "&" t))
5566 (format "\[%s] %s"
5567 (funcall fontify-key "q" t)
5568 (if first-key "Main menu" "Exit")))))
5569 ;; Build prompts for both standard and expert UI.
5570 (standard-prompt (unless expertp "Export command: "))
5571 (expert-prompt
5572 (when expertp
5573 (format
5574 "Export command (C-%s%s%s%s%s) [%s]: "
5575 (if (memq 'body options) (funcall fontify-key "b" t) "b")
5576 (if (memq 'visible options) (funcall fontify-key "v" t) "v")
5577 (if (memq 'subtree options) (funcall fontify-key "s" t) "s")
5578 (if (memq 'force options) (funcall fontify-key "f" t) "f")
5579 (if (memq 'async options) (funcall fontify-key "a" t) "a")
5580 (mapconcat (lambda (k)
5581 ;; Strip control characters.
5582 (unless (< k 27) (char-to-string k)))
5583 allowed-keys "")))))
5584 ;; With expert UI, just read key with a fancy prompt. In standard
5585 ;; UI, display an intrusive help buffer.
5586 (if expertp
5587 (org-export--dispatch-action
5588 expert-prompt allowed-keys backends options first-key expertp)
5589 ;; At first call, create frame layout in order to display menu.
5590 (unless (get-buffer "*Org Export Dispatcher*")
5591 (delete-other-windows)
5592 (org-switch-to-buffer-other-window
5593 (get-buffer-create "*Org Export Dispatcher*"))
5594 (setq cursor-type nil
5595 header-line-format "Use SPC, DEL, C-n or C-p to navigate.")
5596 ;; Make sure that invisible cursor will not highlight square
5597 ;; brackets.
5598 (set-syntax-table (copy-syntax-table))
5599 (modify-syntax-entry ?\[ "w"))
5600 ;; At this point, the buffer containing the menu exists and is
5601 ;; visible in the current window. So, refresh it.
5602 (with-current-buffer "*Org Export Dispatcher*"
5603 ;; Refresh help. Maintain display continuity by re-visiting
5604 ;; previous window position.
5605 (let ((pos (window-start)))
5606 (erase-buffer)
5607 (insert help)
5608 (set-window-start nil pos)))
5609 (org-fit-window-to-buffer)
5610 (org-export--dispatch-action
5611 standard-prompt allowed-keys backends options first-key expertp))))
5613 (defun org-export--dispatch-action
5614 (prompt allowed-keys backends options first-key expertp)
5615 "Read a character from command input and act accordingly.
5617 PROMPT is the displayed prompt, as a string. ALLOWED-KEYS is
5618 a list of characters available at a given step in the process.
5619 BACKENDS is a list of menu entries. OPTIONS, FIRST-KEY and
5620 EXPERTP are the same as defined in `org-export--dispatch-ui',
5621 which see.
5623 Toggle export options when required. Otherwise, return value is
5624 a list with action as CAR and a list of interactive export
5625 options as CDR."
5626 (let (key)
5627 ;; Scrolling: when in non-expert mode, act on motion keys (C-n,
5628 ;; C-p, SPC, DEL).
5629 (while (and (setq key (read-char-exclusive prompt))
5630 (not expertp)
5631 (memq key '(14 16 ?\s ?\d)))
5632 (case key
5633 (14 (if (not (pos-visible-in-window-p (point-max)))
5634 (ignore-errors (scroll-up-line))
5635 (message "End of buffer")
5636 (sit-for 1)))
5637 (16 (if (not (pos-visible-in-window-p (point-min)))
5638 (ignore-errors (scroll-down-line))
5639 (message "Beginning of buffer")
5640 (sit-for 1)))
5641 (?\s (if (not (pos-visible-in-window-p (point-max)))
5642 (scroll-up nil)
5643 (message "End of buffer")
5644 (sit-for 1)))
5645 (?\d (if (not (pos-visible-in-window-p (point-min)))
5646 (scroll-down nil)
5647 (message "Beginning of buffer")
5648 (sit-for 1)))))
5649 (cond
5650 ;; Ignore undefined associations.
5651 ((not (memq key allowed-keys))
5652 (ding)
5653 (unless expertp (message "Invalid key") (sit-for 1))
5654 (org-export--dispatch-ui options first-key expertp))
5655 ;; q key at first level aborts export. At second
5656 ;; level, cancel first key instead.
5657 ((eq key ?q) (if (not first-key) (error "Export aborted")
5658 (org-export--dispatch-ui options nil expertp)))
5659 ;; Help key: Switch back to standard interface if
5660 ;; expert UI was active.
5661 ((eq key ??) (org-export--dispatch-ui options first-key nil))
5662 ;; Switch to asynchronous export stack.
5663 ((eq key ?&) '(stack))
5664 ;; Toggle export options
5665 ;; C-b (2) C-v (22) C-s (19) C-f (6) C-a (1)
5666 ((memq key '(2 22 19 6 1))
5667 (org-export--dispatch-ui
5668 (let ((option (case key (2 'body) (22 'visible) (19 'subtree)
5669 (6 'force) (1 'async))))
5670 (if (memq option options) (remq option options)
5671 (cons option options)))
5672 first-key expertp))
5673 ;; Action selected: Send key and options back to
5674 ;; `org-export-dispatch'.
5675 ((or first-key (functionp (nth 2 (assq key backends))))
5676 (cons (cond
5677 ((not first-key) (nth 2 (assq key backends)))
5678 ;; Publishing actions are hard-coded. Send a special
5679 ;; signal to `org-export-dispatch'.
5680 ((eq first-key ?P)
5681 (case key
5682 (?f 'publish-current-file)
5683 (?p 'publish-current-project)
5684 (?x 'publish-choose-project)
5685 (?a 'publish-all)))
5686 ;; Return first action associated to FIRST-KEY + KEY
5687 ;; path. Indeed, derived backends can share the same
5688 ;; FIRST-KEY.
5689 (t (catch 'found
5690 (mapc (lambda (backend)
5691 (let ((match (assq key (nth 2 backend))))
5692 (when match (throw 'found (nth 2 match)))))
5693 (member (assq first-key backends) backends)))))
5694 options))
5695 ;; Otherwise, enter sub-menu.
5696 (t (org-export--dispatch-ui options key expertp)))))
5698 ;;; Miscellaneous
5700 (defun org-export--copy-to-kill-ring-p ()
5701 "Should we copy the export buffer to the kill ring?
5702 See also `org-export-copy-to-kill-ring'."
5703 (if (eq org-export-copy-to-kill-ring 'if-interactive)
5704 (not (or executing-kbd-macro noninteractive))
5705 (eq org-export-copy-to-kill-ring t)))
5707 (provide 'ox)
5709 ;; Local variables:
5710 ;; generated-autoload-file: "org-loaddefs.el"
5711 ;; End:
5713 ;;; ox.el ends here