ox.el (org-export-as): Allow user functions in `org-export-before-parsing-hook' to...
[org-mode/org-tableheadings.git] / lisp / ox.el
blobf9fa036119948ee75d0a5ea9ac61247c9f93a9b7
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 (save-excursion
2885 (run-hook-with-args 'org-export-before-parsing-hook backend))
2886 ;; Update communication channel with environment. Also
2887 ;; install user's and developer's filters.
2888 (setq info
2889 (org-export-install-filters
2890 (org-combine-plists
2891 info (org-export-get-environment backend subtreep ext-plist))))
2892 ;; Expand export-specific set of macros: {{{author}}},
2893 ;; {{{date}}}, {{{email}}} and {{{title}}}. It must be done
2894 ;; once regular macros have been expanded, since document
2895 ;; keywords may contain one of them.
2896 (org-macro-replace-all
2897 (list (cons "author"
2898 (org-element-interpret-data (plist-get info :author)))
2899 (cons "date"
2900 (org-element-interpret-data (plist-get info :date)))
2901 ;; EMAIL is not a parsed keyword: store it as-is.
2902 (cons "email" (or (plist-get info :email) ""))
2903 (cons "title"
2904 (org-element-interpret-data (plist-get info :title)))))
2905 ;; Call options filters and update export options. We do not
2906 ;; use `org-export-filter-apply-functions' here since the
2907 ;; arity of such filters is different.
2908 (dolist (filter (plist-get info :filter-options))
2909 (let ((result (funcall filter info backend)))
2910 (when result (setq info result))))
2911 ;; Parse buffer and call parse-tree filter on it.
2912 (setq tree
2913 (org-export-filter-apply-functions
2914 (plist-get info :filter-parse-tree)
2915 (org-element-parse-buffer nil visible-only) info))
2916 ;; Now tree is complete, compute its properties and add them
2917 ;; to communication channel.
2918 (setq info
2919 (org-combine-plists
2920 info (org-export-collect-tree-properties tree info)))
2921 ;; Eventually transcode TREE. Wrap the resulting string into
2922 ;; a template.
2923 (let* ((body (org-element-normalize-string
2924 (or (org-export-data tree info) "")))
2925 (inner-template (cdr (assq 'inner-template
2926 (plist-get info :translate-alist))))
2927 (full-body (if (not (functionp inner-template)) body
2928 (funcall inner-template body info)))
2929 (template (cdr (assq 'template
2930 (plist-get info :translate-alist)))))
2931 ;; Remove all text properties since they cannot be
2932 ;; retrieved from an external process. Finally call
2933 ;; final-output filter and return result.
2934 (org-no-properties
2935 (org-export-filter-apply-functions
2936 (plist-get info :filter-final-output)
2937 (if (or (not (functionp template)) body-only) full-body
2938 (funcall template full-body info))
2939 info))))))))
2941 ;;;###autoload
2942 (defun org-export-to-buffer
2943 (backend buffer &optional subtreep visible-only body-only ext-plist)
2944 "Call `org-export-as' with output to a specified buffer.
2946 BACKEND is the back-end used for transcoding, as a symbol.
2948 BUFFER is the output buffer. If it already exists, it will be
2949 erased first, otherwise, it will be created.
2951 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
2952 EXT-PLIST are similar to those used in `org-export-as', which
2953 see.
2955 Depending on `org-export-copy-to-kill-ring', add buffer contents
2956 to kill ring. Return buffer."
2957 (let ((out (org-export-as backend subtreep visible-only body-only ext-plist))
2958 (buffer (get-buffer-create buffer)))
2959 (with-current-buffer buffer
2960 (erase-buffer)
2961 (insert out)
2962 (goto-char (point-min)))
2963 ;; Maybe add buffer contents to kill ring.
2964 (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p out))
2965 (org-kill-new out))
2966 ;; Return buffer.
2967 buffer))
2969 ;;;###autoload
2970 (defun org-export-to-file
2971 (backend file &optional subtreep visible-only body-only ext-plist)
2972 "Call `org-export-as' with output to a specified file.
2974 BACKEND is the back-end used for transcoding, as a symbol. FILE
2975 is the name of the output file, as a string.
2977 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
2978 EXT-PLIST are similar to those used in `org-export-as', which
2979 see.
2981 Depending on `org-export-copy-to-kill-ring', add file contents
2982 to kill ring. Return output file's name."
2983 ;; Checks for FILE permissions. `write-file' would do the same, but
2984 ;; we'd rather avoid needless transcoding of parse tree.
2985 (unless (file-writable-p file) (error "Output file not writable"))
2986 ;; Insert contents to a temporary buffer and write it to FILE.
2987 (let ((out (org-export-as backend subtreep visible-only body-only ext-plist)))
2988 (with-temp-buffer
2989 (insert out)
2990 (let ((coding-system-for-write org-export-coding-system))
2991 (write-file file)))
2992 ;; Maybe add file contents to kill ring.
2993 (when (and (org-export--copy-to-kill-ring-p) (org-string-nw-p out))
2994 (org-kill-new out)))
2995 ;; Return full path.
2996 file)
2998 ;;;###autoload
2999 (defun org-export-string-as (string backend &optional body-only ext-plist)
3000 "Transcode STRING into BACKEND code.
3002 When optional argument BODY-ONLY is non-nil, only return body
3003 code, without preamble nor postamble.
3005 Optional argument EXT-PLIST, when provided, is a property list
3006 with external parameters overriding Org default settings, but
3007 still inferior to file-local settings.
3009 Return code as a string."
3010 (with-temp-buffer
3011 (insert string)
3012 (org-mode)
3013 (org-export-as backend nil nil body-only ext-plist)))
3015 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
3016 "Return output file's name according to buffer specifications.
3018 EXTENSION is a string representing the output file extension,
3019 with the leading dot.
3021 With a non-nil optional argument SUBTREEP, try to determine
3022 output file's name by looking for \"EXPORT_FILE_NAME\" property
3023 of subtree at point.
3025 When optional argument PUB-DIR is set, use it as the publishing
3026 directory.
3028 When optional argument VISIBLE-ONLY is non-nil, don't export
3029 contents of hidden elements.
3031 Return file name as a string."
3032 (let* ((visited-file (buffer-file-name (buffer-base-buffer)))
3033 (base-name
3034 ;; File name may come from EXPORT_FILE_NAME subtree
3035 ;; property, assuming point is at beginning of said
3036 ;; sub-tree.
3037 (file-name-sans-extension
3038 (or (and subtreep
3039 (org-entry-get
3040 (save-excursion
3041 (ignore-errors (org-back-to-heading) (point)))
3042 "EXPORT_FILE_NAME" t))
3043 ;; File name may be extracted from buffer's associated
3044 ;; file, if any.
3045 (and visited-file (file-name-nondirectory visited-file))
3046 ;; Can't determine file name on our own: Ask user.
3047 (let ((read-file-name-function
3048 (and org-completion-use-ido 'ido-read-file-name)))
3049 (read-file-name
3050 "Output file: " pub-dir nil nil nil
3051 (lambda (name)
3052 (string= (file-name-extension name t) extension)))))))
3053 (output-file
3054 ;; Build file name. Enforce EXTENSION over whatever user
3055 ;; may have come up with. PUB-DIR, if defined, always has
3056 ;; precedence over any provided path.
3057 (cond
3058 (pub-dir
3059 (concat (file-name-as-directory pub-dir)
3060 (file-name-nondirectory base-name)
3061 extension))
3062 ((file-name-absolute-p base-name) (concat base-name extension))
3063 (t (concat (file-name-as-directory ".") base-name extension)))))
3064 ;; If writing to OUTPUT-FILE would overwrite original file, append
3065 ;; EXTENSION another time to final name.
3066 (if (and visited-file (org-file-equal-p visited-file output-file))
3067 (concat output-file extension)
3068 output-file)))
3070 (defun org-export-expand-include-keyword (&optional included dir)
3071 "Expand every include keyword in buffer.
3072 Optional argument INCLUDED is a list of included file names along
3073 with their line restriction, when appropriate. It is used to
3074 avoid infinite recursion. Optional argument DIR is the current
3075 working directory. It is used to properly resolve relative
3076 paths."
3077 (let ((case-fold-search t))
3078 (goto-char (point-min))
3079 (while (re-search-forward "^[ \t]*#\\+INCLUDE: +\\(.*\\)[ \t]*$" nil t)
3080 (when (eq (org-element-type (save-match-data (org-element-at-point)))
3081 'keyword)
3082 (beginning-of-line)
3083 ;; Extract arguments from keyword's value.
3084 (let* ((value (match-string 1))
3085 (ind (org-get-indentation))
3086 (file (and (string-match "^\"\\(\\S-+\\)\"" value)
3087 (prog1 (expand-file-name (match-string 1 value) dir)
3088 (setq value (replace-match "" nil nil value)))))
3089 (lines
3090 (and (string-match
3091 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\"" value)
3092 (prog1 (match-string 1 value)
3093 (setq value (replace-match "" nil nil value)))))
3094 (env (cond ((string-match "\\<example\\>" value) 'example)
3095 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
3096 (match-string 1 value))))
3097 ;; Minimal level of included file defaults to the child
3098 ;; level of the current headline, if any, or one. It
3099 ;; only applies is the file is meant to be included as
3100 ;; an Org one.
3101 (minlevel
3102 (and (not env)
3103 (if (string-match ":minlevel +\\([0-9]+\\)" value)
3104 (prog1 (string-to-number (match-string 1 value))
3105 (setq value (replace-match "" nil nil value)))
3106 (let ((cur (org-current-level)))
3107 (if cur (1+ (org-reduced-level cur)) 1))))))
3108 ;; Remove keyword.
3109 (delete-region (point) (progn (forward-line) (point)))
3110 (cond
3111 ((not file) (error "Invalid syntax in INCLUDE keyword"))
3112 ((not (file-readable-p file)) (error "Cannot include file %s" file))
3113 ;; Check if files has already been parsed. Look after
3114 ;; inclusion lines too, as different parts of the same file
3115 ;; can be included too.
3116 ((member (list file lines) included)
3117 (error "Recursive file inclusion: %s" file))
3119 (cond
3120 ((eq env 'example)
3121 (insert
3122 (let ((ind-str (make-string ind ? ))
3123 (contents
3124 (org-escape-code-in-string
3125 (org-export--prepare-file-contents file lines))))
3126 (format "%s#+BEGIN_EXAMPLE\n%s%s#+END_EXAMPLE\n"
3127 ind-str contents ind-str))))
3128 ((stringp env)
3129 (insert
3130 (let ((ind-str (make-string ind ? ))
3131 (contents
3132 (org-escape-code-in-string
3133 (org-export--prepare-file-contents file lines))))
3134 (format "%s#+BEGIN_SRC %s\n%s%s#+END_SRC\n"
3135 ind-str env contents ind-str))))
3137 (insert
3138 (with-temp-buffer
3139 (org-mode)
3140 (insert
3141 (org-export--prepare-file-contents file lines ind minlevel))
3142 (org-export-expand-include-keyword
3143 (cons (list file lines) included)
3144 (file-name-directory file))
3145 (buffer-string))))))))))))
3147 (defun org-export--prepare-file-contents (file &optional lines ind minlevel)
3148 "Prepare the contents of FILE for inclusion and return them as a string.
3150 When optional argument LINES is a string specifying a range of
3151 lines, include only those lines.
3153 Optional argument IND, when non-nil, is an integer specifying the
3154 global indentation of returned contents. Since its purpose is to
3155 allow an included file to stay in the same environment it was
3156 created \(i.e. a list item), it doesn't apply past the first
3157 headline encountered.
3159 Optional argument MINLEVEL, when non-nil, is an integer
3160 specifying the level that any top-level headline in the included
3161 file should have."
3162 (with-temp-buffer
3163 (insert-file-contents file)
3164 (when lines
3165 (let* ((lines (split-string lines "-"))
3166 (lbeg (string-to-number (car lines)))
3167 (lend (string-to-number (cadr lines)))
3168 (beg (if (zerop lbeg) (point-min)
3169 (goto-char (point-min))
3170 (forward-line (1- lbeg))
3171 (point)))
3172 (end (if (zerop lend) (point-max)
3173 (goto-char (point-min))
3174 (forward-line (1- lend))
3175 (point))))
3176 (narrow-to-region beg end)))
3177 ;; Remove blank lines at beginning and end of contents. The logic
3178 ;; behind that removal is that blank lines around include keyword
3179 ;; override blank lines in included file.
3180 (goto-char (point-min))
3181 (org-skip-whitespace)
3182 (beginning-of-line)
3183 (delete-region (point-min) (point))
3184 (goto-char (point-max))
3185 (skip-chars-backward " \r\t\n")
3186 (forward-line)
3187 (delete-region (point) (point-max))
3188 ;; If IND is set, preserve indentation of include keyword until
3189 ;; the first headline encountered.
3190 (when ind
3191 (unless (eq major-mode 'org-mode) (org-mode))
3192 (goto-char (point-min))
3193 (let ((ind-str (make-string ind ? )))
3194 (while (not (or (eobp) (looking-at org-outline-regexp-bol)))
3195 ;; Do not move footnote definitions out of column 0.
3196 (unless (and (looking-at org-footnote-definition-re)
3197 (eq (org-element-type (org-element-at-point))
3198 'footnote-definition))
3199 (insert ind-str))
3200 (forward-line))))
3201 ;; When MINLEVEL is specified, compute minimal level for headlines
3202 ;; in the file (CUR-MIN), and remove stars to each headline so
3203 ;; that headlines with minimal level have a level of MINLEVEL.
3204 (when minlevel
3205 (unless (eq major-mode 'org-mode) (org-mode))
3206 (org-with-limited-levels
3207 (let ((levels (org-map-entries
3208 (lambda () (org-reduced-level (org-current-level))))))
3209 (when levels
3210 (let ((offset (- minlevel (apply 'min levels))))
3211 (unless (zerop offset)
3212 (when org-odd-levels-only (setq offset (* offset 2)))
3213 ;; Only change stars, don't bother moving whole
3214 ;; sections.
3215 (org-map-entries
3216 (lambda () (if (< offset 0) (delete-char (abs offset))
3217 (insert (make-string offset ?*)))))))))))
3218 (org-element-normalize-string (buffer-string))))
3220 (defun org-export-execute-babel-code ()
3221 "Execute every Babel code in the visible part of current buffer."
3222 ;; Get a pristine copy of current buffer so Babel references can be
3223 ;; properly resolved.
3224 (let ((reference (org-export-copy-buffer)))
3225 (unwind-protect (let ((org-current-export-file reference))
3226 (org-babel-exp-process-buffer))
3227 (kill-buffer reference))))
3231 ;;; Tools For Back-Ends
3233 ;; A whole set of tools is available to help build new exporters. Any
3234 ;; function general enough to have its use across many back-ends
3235 ;; should be added here.
3237 ;;;; For Affiliated Keywords
3239 ;; `org-export-read-attribute' reads a property from a given element
3240 ;; as a plist. It can be used to normalize affiliated keywords'
3241 ;; syntax.
3243 ;; Since captions can span over multiple lines and accept dual values,
3244 ;; their internal representation is a bit tricky. Therefore,
3245 ;; `org-export-get-caption' transparently returns a given element's
3246 ;; caption as a secondary string.
3248 (defun org-export-read-attribute (attribute element &optional property)
3249 "Turn ATTRIBUTE property from ELEMENT into a plist.
3251 When optional argument PROPERTY is non-nil, return the value of
3252 that property within attributes.
3254 This function assumes attributes are defined as \":keyword
3255 value\" pairs. It is appropriate for `:attr_html' like
3256 properties. All values will become strings except the empty
3257 string and \"nil\", which will become nil."
3258 (let ((attributes
3259 (let ((value (org-element-property attribute element)))
3260 (when value
3261 (let ((s (mapconcat 'identity value " ")) result)
3262 (while (string-match
3263 "\\(?:^\\|[ \t]+\\)\\(:[-a-zA-Z0-9_]+\\)\\([ \t]+\\|$\\)"
3265 (let ((value (substring s 0 (match-beginning 0))))
3266 (push (and (not (member value '("nil" ""))) value) result))
3267 (push (intern (match-string 1 s)) result)
3268 (setq s (substring s (match-end 0))))
3269 ;; Ignore any string before the first property with `cdr'.
3270 (cdr (nreverse (cons (and (org-string-nw-p s)
3271 (not (equal s "nil"))
3273 result))))))))
3274 (if property (plist-get attributes property) attributes)))
3276 (defun org-export-get-caption (element &optional shortp)
3277 "Return caption from ELEMENT as a secondary string.
3279 When optional argument SHORTP is non-nil, return short caption,
3280 as a secondary string, instead.
3282 Caption lines are separated by a white space."
3283 (let ((full-caption (org-element-property :caption element)) caption)
3284 (dolist (line full-caption (cdr caption))
3285 (let ((cap (funcall (if shortp 'cdr 'car) line)))
3286 (when cap
3287 (setq caption (nconc (list " ") (copy-sequence cap) caption)))))))
3290 ;;;; For Derived Back-ends
3292 ;; `org-export-with-backend' is a function allowing to locally use
3293 ;; another back-end to transcode some object or element. In a derived
3294 ;; back-end, it may be used as a fall-back function once all specific
3295 ;; cases have been treated.
3297 (defun org-export-with-backend (back-end data &optional contents info)
3298 "Call a transcoder from BACK-END on DATA.
3299 CONTENTS, when non-nil, is the transcoded contents of DATA
3300 element, as a string. INFO, when non-nil, is the communication
3301 channel used for export, as a plist.."
3302 (org-export-barf-if-invalid-backend back-end)
3303 (let ((type (org-element-type data)))
3304 (if (memq type '(nil org-data)) (error "No foreign transcoder available")
3305 (let ((transcoder
3306 (cdr (assq type (org-export-backend-translate-table back-end)))))
3307 (if (functionp transcoder) (funcall transcoder data contents info)
3308 (error "No foreign transcoder available"))))))
3311 ;;;; For Export Snippets
3313 ;; Every export snippet is transmitted to the back-end. Though, the
3314 ;; latter will only retain one type of export-snippet, ignoring
3315 ;; others, based on the former's target back-end. The function
3316 ;; `org-export-snippet-backend' returns that back-end for a given
3317 ;; export-snippet.
3319 (defun org-export-snippet-backend (export-snippet)
3320 "Return EXPORT-SNIPPET targeted back-end as a symbol.
3321 Translation, with `org-export-snippet-translation-alist', is
3322 applied."
3323 (let ((back-end (org-element-property :back-end export-snippet)))
3324 (intern
3325 (or (cdr (assoc back-end org-export-snippet-translation-alist))
3326 back-end))))
3329 ;;;; For Footnotes
3331 ;; `org-export-collect-footnote-definitions' is a tool to list
3332 ;; actually used footnotes definitions in the whole parse tree, or in
3333 ;; a headline, in order to add footnote listings throughout the
3334 ;; transcoded data.
3336 ;; `org-export-footnote-first-reference-p' is a predicate used by some
3337 ;; back-ends, when they need to attach the footnote definition only to
3338 ;; the first occurrence of the corresponding label.
3340 ;; `org-export-get-footnote-definition' and
3341 ;; `org-export-get-footnote-number' provide easier access to
3342 ;; additional information relative to a footnote reference.
3344 (defun org-export-collect-footnote-definitions (data info)
3345 "Return an alist between footnote numbers, labels and definitions.
3347 DATA is the parse tree from which definitions are collected.
3348 INFO is the plist used as a communication channel.
3350 Definitions are sorted by order of references. They either
3351 appear as Org data or as a secondary string for inlined
3352 footnotes. Unreferenced definitions are ignored."
3353 (let* (num-alist
3354 collect-fn ; for byte-compiler.
3355 (collect-fn
3356 (function
3357 (lambda (data)
3358 ;; Collect footnote number, label and definition in DATA.
3359 (org-element-map data 'footnote-reference
3360 (lambda (fn)
3361 (when (org-export-footnote-first-reference-p fn info)
3362 (let ((def (org-export-get-footnote-definition fn info)))
3363 (push
3364 (list (org-export-get-footnote-number fn info)
3365 (org-element-property :label fn)
3366 def)
3367 num-alist)
3368 ;; Also search in definition for nested footnotes.
3369 (when (eq (org-element-property :type fn) 'standard)
3370 (funcall collect-fn def)))))
3371 ;; Don't enter footnote definitions since it will happen
3372 ;; when their first reference is found.
3373 info nil 'footnote-definition)))))
3374 (funcall collect-fn (plist-get info :parse-tree))
3375 (reverse num-alist)))
3377 (defun org-export-footnote-first-reference-p (footnote-reference info)
3378 "Non-nil when a footnote reference is the first one for its label.
3380 FOOTNOTE-REFERENCE is the footnote reference being considered.
3381 INFO is the plist used as a communication channel."
3382 (let ((label (org-element-property :label footnote-reference)))
3383 ;; Anonymous footnotes are always a first reference.
3384 (if (not label) t
3385 ;; Otherwise, return the first footnote with the same LABEL and
3386 ;; test if it is equal to FOOTNOTE-REFERENCE.
3387 (let* (search-refs ; for byte-compiler.
3388 (search-refs
3389 (function
3390 (lambda (data)
3391 (org-element-map data 'footnote-reference
3392 (lambda (fn)
3393 (cond
3394 ((string= (org-element-property :label fn) label)
3395 (throw 'exit fn))
3396 ;; If FN isn't inlined, be sure to traverse its
3397 ;; definition before resuming search. See
3398 ;; comments in `org-export-get-footnote-number'
3399 ;; for more information.
3400 ((eq (org-element-property :type fn) 'standard)
3401 (funcall search-refs
3402 (org-export-get-footnote-definition fn info)))))
3403 ;; Don't enter footnote definitions since it will
3404 ;; happen when their first reference is found.
3405 info 'first-match 'footnote-definition)))))
3406 (eq (catch 'exit (funcall search-refs (plist-get info :parse-tree)))
3407 footnote-reference)))))
3409 (defun org-export-get-footnote-definition (footnote-reference info)
3410 "Return definition of FOOTNOTE-REFERENCE as parsed data.
3411 INFO is the plist used as a communication channel. If no such
3412 definition can be found, return the \"DEFINITION NOT FOUND\"
3413 string."
3414 (let ((label (org-element-property :label footnote-reference)))
3415 (or (org-element-property :inline-definition footnote-reference)
3416 (cdr (assoc label (plist-get info :footnote-definition-alist)))
3417 "DEFINITION NOT FOUND.")))
3419 (defun org-export-get-footnote-number (footnote info)
3420 "Return number associated to a footnote.
3422 FOOTNOTE is either a footnote reference or a footnote definition.
3423 INFO is the plist used as a communication channel."
3424 (let* ((label (org-element-property :label footnote))
3425 seen-refs
3426 search-ref ; For byte-compiler.
3427 (search-ref
3428 (function
3429 (lambda (data)
3430 ;; Search footnote references through DATA, filling
3431 ;; SEEN-REFS along the way.
3432 (org-element-map data 'footnote-reference
3433 (lambda (fn)
3434 (let ((fn-lbl (org-element-property :label fn)))
3435 (cond
3436 ;; Anonymous footnote match: return number.
3437 ((and (not fn-lbl) (eq fn footnote))
3438 (throw 'exit (1+ (length seen-refs))))
3439 ;; Labels match: return number.
3440 ((and label (string= label fn-lbl))
3441 (throw 'exit (1+ (length seen-refs))))
3442 ;; Anonymous footnote: it's always a new one.
3443 ;; Also, be sure to return nil from the `cond' so
3444 ;; `first-match' doesn't get us out of the loop.
3445 ((not fn-lbl) (push 'inline seen-refs) nil)
3446 ;; Label not seen so far: add it so SEEN-REFS.
3448 ;; Also search for subsequent references in
3449 ;; footnote definition so numbering follows
3450 ;; reading logic. Note that we don't have to care
3451 ;; about inline definitions, since
3452 ;; `org-element-map' already traverses them at the
3453 ;; right time.
3455 ;; Once again, return nil to stay in the loop.
3456 ((not (member fn-lbl seen-refs))
3457 (push fn-lbl seen-refs)
3458 (funcall search-ref
3459 (org-export-get-footnote-definition fn info))
3460 nil))))
3461 ;; Don't enter footnote definitions since it will
3462 ;; happen when their first reference is found.
3463 info 'first-match 'footnote-definition)))))
3464 (catch 'exit (funcall search-ref (plist-get info :parse-tree)))))
3467 ;;;; For Headlines
3469 ;; `org-export-get-relative-level' is a shortcut to get headline
3470 ;; level, relatively to the lower headline level in the parsed tree.
3472 ;; `org-export-get-headline-number' returns the section number of an
3473 ;; headline, while `org-export-number-to-roman' allows to convert it
3474 ;; to roman numbers.
3476 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
3477 ;; `org-export-last-sibling-p' are three useful predicates when it
3478 ;; comes to fulfill the `:headline-levels' property.
3480 ;; `org-export-get-tags', `org-export-get-category' and
3481 ;; `org-export-get-node-property' extract useful information from an
3482 ;; headline or a parent headline. They all handle inheritance.
3484 ;; `org-export-get-alt-title' tries to retrieve an alternative title,
3485 ;; as a secondary string, suitable for table of contents. It falls
3486 ;; back onto default title.
3488 (defun org-export-get-relative-level (headline info)
3489 "Return HEADLINE relative level within current parsed tree.
3490 INFO is a plist holding contextual information."
3491 (+ (org-element-property :level headline)
3492 (or (plist-get info :headline-offset) 0)))
3494 (defun org-export-low-level-p (headline info)
3495 "Non-nil when HEADLINE is considered as low level.
3497 INFO is a plist used as a communication channel.
3499 A low level headlines has a relative level greater than
3500 `:headline-levels' property value.
3502 Return value is the difference between HEADLINE relative level
3503 and the last level being considered as high enough, or nil."
3504 (let ((limit (plist-get info :headline-levels)))
3505 (when (wholenump limit)
3506 (let ((level (org-export-get-relative-level headline info)))
3507 (and (> level limit) (- level limit))))))
3509 (defun org-export-get-headline-number (headline info)
3510 "Return HEADLINE numbering as a list of numbers.
3511 INFO is a plist holding contextual information."
3512 (cdr (assoc headline (plist-get info :headline-numbering))))
3514 (defun org-export-numbered-headline-p (headline info)
3515 "Return a non-nil value if HEADLINE element should be numbered.
3516 INFO is a plist used as a communication channel."
3517 (let ((sec-num (plist-get info :section-numbers))
3518 (level (org-export-get-relative-level headline info)))
3519 (if (wholenump sec-num) (<= level sec-num) sec-num)))
3521 (defun org-export-number-to-roman (n)
3522 "Convert integer N into a roman numeral."
3523 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
3524 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
3525 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
3526 ( 1 . "I")))
3527 (res ""))
3528 (if (<= n 0)
3529 (number-to-string n)
3530 (while roman
3531 (if (>= n (caar roman))
3532 (setq n (- n (caar roman))
3533 res (concat res (cdar roman)))
3534 (pop roman)))
3535 res)))
3537 (defun org-export-get-tags (element info &optional tags inherited)
3538 "Return list of tags associated to ELEMENT.
3540 ELEMENT has either an `headline' or an `inlinetask' type. INFO
3541 is a plist used as a communication channel.
3543 Select tags (see `org-export-select-tags') and exclude tags (see
3544 `org-export-exclude-tags') are removed from the list.
3546 When non-nil, optional argument TAGS should be a list of strings.
3547 Any tag belonging to this list will also be removed.
3549 When optional argument INHERITED is non-nil, tags can also be
3550 inherited from parent headlines and FILETAGS keywords."
3551 (org-remove-if
3552 (lambda (tag) (or (member tag (plist-get info :select-tags))
3553 (member tag (plist-get info :exclude-tags))
3554 (member tag tags)))
3555 (if (not inherited) (org-element-property :tags element)
3556 ;; Build complete list of inherited tags.
3557 (let ((current-tag-list (org-element-property :tags element)))
3558 (mapc
3559 (lambda (parent)
3560 (mapc
3561 (lambda (tag)
3562 (when (and (memq (org-element-type parent) '(headline inlinetask))
3563 (not (member tag current-tag-list)))
3564 (push tag current-tag-list)))
3565 (org-element-property :tags parent)))
3566 (org-export-get-genealogy element))
3567 ;; Add FILETAGS keywords and return results.
3568 (org-uniquify (append (plist-get info :filetags) current-tag-list))))))
3570 (defun org-export-get-node-property (property blob &optional inherited)
3571 "Return node PROPERTY value for BLOB.
3573 PROPERTY is an upcase symbol (i.e. `:COOKIE_DATA'). BLOB is an
3574 element or object.
3576 If optional argument INHERITED is non-nil, the value can be
3577 inherited from a parent headline.
3579 Return value is a string or nil."
3580 (let ((headline (if (eq (org-element-type blob) 'headline) blob
3581 (org-export-get-parent-headline blob))))
3582 (if (not inherited) (org-element-property property blob)
3583 (let ((parent headline) value)
3584 (catch 'found
3585 (while parent
3586 (when (plist-member (nth 1 parent) property)
3587 (throw 'found (org-element-property property parent)))
3588 (setq parent (org-element-property :parent parent))))))))
3590 (defun org-export-get-category (blob info)
3591 "Return category for element or object BLOB.
3593 INFO is a plist used as a communication channel.
3595 CATEGORY is automatically inherited from a parent headline, from
3596 #+CATEGORY: keyword or created out of original file name. If all
3597 fail, the fall-back value is \"???\"."
3598 (or (let ((headline (if (eq (org-element-type blob) 'headline) blob
3599 (org-export-get-parent-headline blob))))
3600 ;; Almost like `org-export-node-property', but we cannot trust
3601 ;; `plist-member' as every headline has a `:CATEGORY'
3602 ;; property, would it be nil or equal to "???" (which has the
3603 ;; same meaning).
3604 (let ((parent headline) value)
3605 (catch 'found
3606 (while parent
3607 (let ((category (org-element-property :CATEGORY parent)))
3608 (and category (not (equal "???" category))
3609 (throw 'found category)))
3610 (setq parent (org-element-property :parent parent))))))
3611 (org-element-map (plist-get info :parse-tree) 'keyword
3612 (lambda (kwd)
3613 (when (equal (org-element-property :key kwd) "CATEGORY")
3614 (org-element-property :value kwd)))
3615 info 'first-match)
3616 (let ((file (plist-get info :input-file)))
3617 (and file (file-name-sans-extension (file-name-nondirectory file))))
3618 "???"))
3620 (defun org-export-get-alt-title (headline info)
3621 "Return alternative title for HEADLINE, as a secondary string.
3622 INFO is a plist used as a communication channel. If no optional
3623 title is defined, fall-back to the regular title."
3624 (or (org-element-property :alt-title headline)
3625 (org-element-property :title headline)))
3627 (defun org-export-first-sibling-p (headline info)
3628 "Non-nil when HEADLINE is the first sibling in its sub-tree.
3629 INFO is a plist used as a communication channel."
3630 (not (eq (org-element-type (org-export-get-previous-element headline info))
3631 'headline)))
3633 (defun org-export-last-sibling-p (headline info)
3634 "Non-nil when HEADLINE is the last sibling in its sub-tree.
3635 INFO is a plist used as a communication channel."
3636 (not (org-export-get-next-element headline info)))
3639 ;;;; For Links
3641 ;; `org-export-solidify-link-text' turns a string into a safer version
3642 ;; for links, replacing most non-standard characters with hyphens.
3644 ;; `org-export-get-coderef-format' returns an appropriate format
3645 ;; string for coderefs.
3647 ;; `org-export-inline-image-p' returns a non-nil value when the link
3648 ;; provided should be considered as an inline image.
3650 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
3651 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
3652 ;; returns an appropriate unique identifier when found, or nil.
3654 ;; `org-export-resolve-id-link' returns the first headline with
3655 ;; specified id or custom-id in parse tree, the path to the external
3656 ;; file with the id or nil when neither was found.
3658 ;; `org-export-resolve-coderef' associates a reference to a line
3659 ;; number in the element it belongs, or returns the reference itself
3660 ;; when the element isn't numbered.
3662 (defun org-export-solidify-link-text (s)
3663 "Take link text S and make a safe target out of it."
3664 (save-match-data
3665 (mapconcat 'identity (org-split-string s "[^a-zA-Z0-9_.-:]+") "-")))
3667 (defun org-export-get-coderef-format (path desc)
3668 "Return format string for code reference link.
3669 PATH is the link path. DESC is its description."
3670 (save-match-data
3671 (cond ((not desc) "%s")
3672 ((string-match (regexp-quote (concat "(" path ")")) desc)
3673 (replace-match "%s" t t desc))
3674 (t desc))))
3676 (defun org-export-inline-image-p (link &optional rules)
3677 "Non-nil if LINK object points to an inline image.
3679 Optional argument is a set of RULES defining inline images. It
3680 is an alist where associations have the following shape:
3682 \(TYPE . REGEXP)
3684 Applying a rule means apply REGEXP against LINK's path when its
3685 type is TYPE. The function will return a non-nil value if any of
3686 the provided rules is non-nil. The default rule is
3687 `org-export-default-inline-image-rule'.
3689 This only applies to links without a description."
3690 (and (not (org-element-contents link))
3691 (let ((case-fold-search t)
3692 (rules (or rules org-export-default-inline-image-rule)))
3693 (catch 'exit
3694 (mapc
3695 (lambda (rule)
3696 (and (string= (org-element-property :type link) (car rule))
3697 (string-match (cdr rule)
3698 (org-element-property :path link))
3699 (throw 'exit t)))
3700 rules)
3701 ;; Return nil if no rule matched.
3702 nil))))
3704 (defun org-export-resolve-coderef (ref info)
3705 "Resolve a code reference REF.
3707 INFO is a plist used as a communication channel.
3709 Return associated line number in source code, or REF itself,
3710 depending on src-block or example element's switches."
3711 (org-element-map (plist-get info :parse-tree) '(example-block src-block)
3712 (lambda (el)
3713 (with-temp-buffer
3714 (insert (org-trim (org-element-property :value el)))
3715 (let* ((label-fmt (regexp-quote
3716 (or (org-element-property :label-fmt el)
3717 org-coderef-label-format)))
3718 (ref-re
3719 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
3720 (replace-regexp-in-string "%s" ref label-fmt nil t))))
3721 ;; Element containing REF is found. Resolve it to either
3722 ;; a label or a line number, as needed.
3723 (when (re-search-backward ref-re nil t)
3724 (cond
3725 ((org-element-property :use-labels el) ref)
3726 ((eq (org-element-property :number-lines el) 'continued)
3727 (+ (org-export-get-loc el info) (line-number-at-pos)))
3728 (t (line-number-at-pos)))))))
3729 info 'first-match))
3731 (defun org-export-resolve-fuzzy-link (link info)
3732 "Return LINK destination.
3734 INFO is a plist holding contextual information.
3736 Return value can be an object, an element, or nil:
3738 - If LINK path matches a target object (i.e. <<path>>) or
3739 element (i.e. \"#+TARGET: path\"), return it.
3741 - If LINK path exactly matches the name affiliated keyword
3742 \(i.e. #+NAME: path) of an element, return that element.
3744 - If LINK path exactly matches any headline name, return that
3745 element. If more than one headline share that name, priority
3746 will be given to the one with the closest common ancestor, if
3747 any, or the first one in the parse tree otherwise.
3749 - Otherwise, return nil.
3751 Assume LINK type is \"fuzzy\". White spaces are not
3752 significant."
3753 (let* ((raw-path (org-element-property :path link))
3754 (match-title-p (eq (aref raw-path 0) ?*))
3755 ;; Split PATH at white spaces so matches are space
3756 ;; insensitive.
3757 (path (org-split-string
3758 (if match-title-p (substring raw-path 1) raw-path))))
3759 (cond
3760 ;; First try to find a matching "<<path>>" unless user specified
3761 ;; he was looking for a headline (path starts with a *
3762 ;; character).
3763 ((and (not match-title-p)
3764 (org-element-map (plist-get info :parse-tree) '(keyword target)
3765 (lambda (blob)
3766 (and (or (eq (org-element-type blob) 'target)
3767 (equal (org-element-property :key blob) "TARGET"))
3768 (equal (org-split-string (org-element-property :value blob))
3769 path)
3770 blob))
3771 info t)))
3772 ;; Then try to find an element with a matching "#+NAME: path"
3773 ;; affiliated keyword.
3774 ((and (not match-title-p)
3775 (org-element-map (plist-get info :parse-tree)
3776 org-element-all-elements
3777 (lambda (el)
3778 (let ((name (org-element-property :name el)))
3779 (when (and name (equal (org-split-string name) path)) el)))
3780 info 'first-match)))
3781 ;; Last case: link either points to a headline or to
3782 ;; nothingness. Try to find the source, with priority given to
3783 ;; headlines with the closest common ancestor. If such candidate
3784 ;; is found, return it, otherwise return nil.
3786 (let ((find-headline
3787 (function
3788 ;; Return first headline whose `:raw-value' property is
3789 ;; NAME in parse tree DATA, or nil. Statistics cookies
3790 ;; are ignored.
3791 (lambda (name data)
3792 (org-element-map data 'headline
3793 (lambda (headline)
3794 (when (equal (org-split-string
3795 (replace-regexp-in-string
3796 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
3797 (org-element-property :raw-value headline)))
3798 name)
3799 headline))
3800 info 'first-match)))))
3801 ;; Search among headlines sharing an ancestor with link, from
3802 ;; closest to farthest.
3803 (or (catch 'exit
3804 (mapc
3805 (lambda (parent)
3806 (when (eq (org-element-type parent) 'headline)
3807 (let ((foundp (funcall find-headline path parent)))
3808 (when foundp (throw 'exit foundp)))))
3809 (org-export-get-genealogy link)) nil)
3810 ;; No match with a common ancestor: try full parse-tree.
3811 (funcall find-headline path (plist-get info :parse-tree))))))))
3813 (defun org-export-resolve-id-link (link info)
3814 "Return headline referenced as LINK destination.
3816 INFO is a plist used as a communication channel.
3818 Return value can be the headline element matched in current parse
3819 tree, a file name or nil. Assume LINK type is either \"id\" or
3820 \"custom-id\"."
3821 (let ((id (org-element-property :path link)))
3822 ;; First check if id is within the current parse tree.
3823 (or (org-element-map (plist-get info :parse-tree) 'headline
3824 (lambda (headline)
3825 (when (or (string= (org-element-property :ID headline) id)
3826 (string= (org-element-property :CUSTOM_ID headline) id))
3827 headline))
3828 info 'first-match)
3829 ;; Otherwise, look for external files.
3830 (cdr (assoc id (plist-get info :id-alist))))))
3832 (defun org-export-resolve-radio-link (link info)
3833 "Return radio-target object referenced as LINK destination.
3835 INFO is a plist used as a communication channel.
3837 Return value can be a radio-target object or nil. Assume LINK
3838 has type \"radio\"."
3839 (let ((path (org-element-property :path link)))
3840 (org-element-map (plist-get info :parse-tree) 'radio-target
3841 (lambda (radio)
3842 (and (compare-strings
3843 (org-element-property :value radio) 0 nil path 0 nil t)
3844 radio))
3845 info 'first-match)))
3848 ;;;; For References
3850 ;; `org-export-get-ordinal' associates a sequence number to any object
3851 ;; or element.
3853 (defun org-export-get-ordinal (element info &optional types predicate)
3854 "Return ordinal number of an element or object.
3856 ELEMENT is the element or object considered. INFO is the plist
3857 used as a communication channel.
3859 Optional argument TYPES, when non-nil, is a list of element or
3860 object types, as symbols, that should also be counted in.
3861 Otherwise, only provided element's type is considered.
3863 Optional argument PREDICATE is a function returning a non-nil
3864 value if the current element or object should be counted in. It
3865 accepts two arguments: the element or object being considered and
3866 the plist used as a communication channel. This allows to count
3867 only a certain type of objects (i.e. inline images).
3869 Return value is a list of numbers if ELEMENT is a headline or an
3870 item. It is nil for keywords. It represents the footnote number
3871 for footnote definitions and footnote references. If ELEMENT is
3872 a target, return the same value as if ELEMENT was the closest
3873 table, item or headline containing the target. In any other
3874 case, return the sequence number of ELEMENT among elements or
3875 objects of the same type."
3876 ;; A target keyword, representing an invisible target, never has
3877 ;; a sequence number.
3878 (unless (eq (org-element-type element) 'keyword)
3879 ;; Ordinal of a target object refer to the ordinal of the closest
3880 ;; table, item, or headline containing the object.
3881 (when (eq (org-element-type element) 'target)
3882 (setq element
3883 (loop for parent in (org-export-get-genealogy element)
3884 when
3885 (memq
3886 (org-element-type parent)
3887 '(footnote-definition footnote-reference headline item
3888 table))
3889 return parent)))
3890 (case (org-element-type element)
3891 ;; Special case 1: A headline returns its number as a list.
3892 (headline (org-export-get-headline-number element info))
3893 ;; Special case 2: An item returns its number as a list.
3894 (item (let ((struct (org-element-property :structure element)))
3895 (org-list-get-item-number
3896 (org-element-property :begin element)
3897 struct
3898 (org-list-prevs-alist struct)
3899 (org-list-parents-alist struct))))
3900 ((footnote-definition footnote-reference)
3901 (org-export-get-footnote-number element info))
3902 (otherwise
3903 (let ((counter 0))
3904 ;; Increment counter until ELEMENT is found again.
3905 (org-element-map (plist-get info :parse-tree)
3906 (or types (org-element-type element))
3907 (lambda (el)
3908 (cond
3909 ((eq element el) (1+ counter))
3910 ((not predicate) (incf counter) nil)
3911 ((funcall predicate el info) (incf counter) nil)))
3912 info 'first-match))))))
3915 ;;;; For Src-Blocks
3917 ;; `org-export-get-loc' counts number of code lines accumulated in
3918 ;; src-block or example-block elements with a "+n" switch until
3919 ;; a given element, excluded. Note: "-n" switches reset that count.
3921 ;; `org-export-unravel-code' extracts source code (along with a code
3922 ;; references alist) from an `element-block' or `src-block' type
3923 ;; element.
3925 ;; `org-export-format-code' applies a formatting function to each line
3926 ;; of code, providing relative line number and code reference when
3927 ;; appropriate. Since it doesn't access the original element from
3928 ;; which the source code is coming, it expects from the code calling
3929 ;; it to know if lines should be numbered and if code references
3930 ;; should appear.
3932 ;; Eventually, `org-export-format-code-default' is a higher-level
3933 ;; function (it makes use of the two previous functions) which handles
3934 ;; line numbering and code references inclusion, and returns source
3935 ;; code in a format suitable for plain text or verbatim output.
3937 (defun org-export-get-loc (element info)
3938 "Return accumulated lines of code up to ELEMENT.
3940 INFO is the plist used as a communication channel.
3942 ELEMENT is excluded from count."
3943 (let ((loc 0))
3944 (org-element-map (plist-get info :parse-tree)
3945 `(src-block example-block ,(org-element-type element))
3946 (lambda (el)
3947 (cond
3948 ;; ELEMENT is reached: Quit the loop.
3949 ((eq el element))
3950 ;; Only count lines from src-block and example-block elements
3951 ;; with a "+n" or "-n" switch. A "-n" switch resets counter.
3952 ((not (memq (org-element-type el) '(src-block example-block))) nil)
3953 ((let ((linums (org-element-property :number-lines el)))
3954 (when linums
3955 ;; Accumulate locs or reset them.
3956 (let ((lines (org-count-lines
3957 (org-trim (org-element-property :value el)))))
3958 (setq loc (if (eq linums 'new) lines (+ loc lines))))))
3959 ;; Return nil to stay in the loop.
3960 nil)))
3961 info 'first-match)
3962 ;; Return value.
3963 loc))
3965 (defun org-export-unravel-code (element)
3966 "Clean source code and extract references out of it.
3968 ELEMENT has either a `src-block' an `example-block' type.
3970 Return a cons cell whose CAR is the source code, cleaned from any
3971 reference and protective comma and CDR is an alist between
3972 relative line number (integer) and name of code reference on that
3973 line (string)."
3974 (let* ((line 0) refs
3975 ;; Get code and clean it. Remove blank lines at its
3976 ;; beginning and end.
3977 (code (let ((c (replace-regexp-in-string
3978 "\\`\\([ \t]*\n\\)+" ""
3979 (replace-regexp-in-string
3980 "\\([ \t]*\n\\)*[ \t]*\\'" "\n"
3981 (org-element-property :value element)))))
3982 ;; If appropriate, remove global indentation.
3983 (if (or org-src-preserve-indentation
3984 (org-element-property :preserve-indent element))
3986 (org-remove-indentation c))))
3987 ;; Get format used for references.
3988 (label-fmt (regexp-quote
3989 (or (org-element-property :label-fmt element)
3990 org-coderef-label-format)))
3991 ;; Build a regexp matching a loc with a reference.
3992 (with-ref-re
3993 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)[ \t]*\\)$"
3994 (replace-regexp-in-string
3995 "%s" "\\([-a-zA-Z0-9_ ]+\\)" label-fmt nil t))))
3996 ;; Return value.
3997 (cons
3998 ;; Code with references removed.
3999 (org-element-normalize-string
4000 (mapconcat
4001 (lambda (loc)
4002 (incf line)
4003 (if (not (string-match with-ref-re loc)) loc
4004 ;; Ref line: remove ref, and signal its position in REFS.
4005 (push (cons line (match-string 3 loc)) refs)
4006 (replace-match "" nil nil loc 1)))
4007 (org-split-string code "\n") "\n"))
4008 ;; Reference alist.
4009 refs)))
4011 (defun org-export-format-code (code fun &optional num-lines ref-alist)
4012 "Format CODE by applying FUN line-wise and return it.
4014 CODE is a string representing the code to format. FUN is
4015 a function. It must accept three arguments: a line of
4016 code (string), the current line number (integer) or nil and the
4017 reference associated to the current line (string) or nil.
4019 Optional argument NUM-LINES can be an integer representing the
4020 number of code lines accumulated until the current code. Line
4021 numbers passed to FUN will take it into account. If it is nil,
4022 FUN's second argument will always be nil. This number can be
4023 obtained with `org-export-get-loc' function.
4025 Optional argument REF-ALIST can be an alist between relative line
4026 number (i.e. ignoring NUM-LINES) and the name of the code
4027 reference on it. If it is nil, FUN's third argument will always
4028 be nil. It can be obtained through the use of
4029 `org-export-unravel-code' function."
4030 (let ((--locs (org-split-string code "\n"))
4031 (--line 0))
4032 (org-element-normalize-string
4033 (mapconcat
4034 (lambda (--loc)
4035 (incf --line)
4036 (let ((--ref (cdr (assq --line ref-alist))))
4037 (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
4038 --locs "\n"))))
4040 (defun org-export-format-code-default (element info)
4041 "Return source code from ELEMENT, formatted in a standard way.
4043 ELEMENT is either a `src-block' or `example-block' element. INFO
4044 is a plist used as a communication channel.
4046 This function takes care of line numbering and code references
4047 inclusion. Line numbers, when applicable, appear at the
4048 beginning of the line, separated from the code by two white
4049 spaces. Code references, on the other hand, appear flushed to
4050 the right, separated by six white spaces from the widest line of
4051 code."
4052 ;; Extract code and references.
4053 (let* ((code-info (org-export-unravel-code element))
4054 (code (car code-info))
4055 (code-lines (org-split-string code "\n")))
4056 (if (null code-lines) ""
4057 (let* ((refs (and (org-element-property :retain-labels element)
4058 (cdr code-info)))
4059 ;; Handle line numbering.
4060 (num-start (case (org-element-property :number-lines element)
4061 (continued (org-export-get-loc element info))
4062 (new 0)))
4063 (num-fmt
4064 (and num-start
4065 (format "%%%ds "
4066 (length (number-to-string
4067 (+ (length code-lines) num-start))))))
4068 ;; Prepare references display, if required. Any reference
4069 ;; should start six columns after the widest line of code,
4070 ;; wrapped with parenthesis.
4071 (max-width
4072 (+ (apply 'max (mapcar 'length code-lines))
4073 (if (not num-start) 0 (length (format num-fmt num-start))))))
4074 (org-export-format-code
4075 code
4076 (lambda (loc line-num ref)
4077 (let ((number-str (and num-fmt (format num-fmt line-num))))
4078 (concat
4079 number-str
4081 (and ref
4082 (concat (make-string
4083 (- (+ 6 max-width)
4084 (+ (length loc) (length number-str))) ? )
4085 (format "(%s)" ref))))))
4086 num-start refs)))))
4089 ;;;; For Tables
4091 ;; `org-export-table-has-special-column-p' and and
4092 ;; `org-export-table-row-is-special-p' are predicates used to look for
4093 ;; meta-information about the table structure.
4095 ;; `org-table-has-header-p' tells when the rows before the first rule
4096 ;; should be considered as table's header.
4098 ;; `org-export-table-cell-width', `org-export-table-cell-alignment'
4099 ;; and `org-export-table-cell-borders' extract information from
4100 ;; a table-cell element.
4102 ;; `org-export-table-dimensions' gives the number on rows and columns
4103 ;; in the table, ignoring horizontal rules and special columns.
4104 ;; `org-export-table-cell-address', given a table-cell object, returns
4105 ;; the absolute address of a cell. On the other hand,
4106 ;; `org-export-get-table-cell-at' does the contrary.
4108 ;; `org-export-table-cell-starts-colgroup-p',
4109 ;; `org-export-table-cell-ends-colgroup-p',
4110 ;; `org-export-table-row-starts-rowgroup-p',
4111 ;; `org-export-table-row-ends-rowgroup-p',
4112 ;; `org-export-table-row-starts-header-p' and
4113 ;; `org-export-table-row-ends-header-p' indicate position of current
4114 ;; row or cell within the table.
4116 (defun org-export-table-has-special-column-p (table)
4117 "Non-nil when TABLE has a special column.
4118 All special columns will be ignored during export."
4119 ;; The table has a special column when every first cell of every row
4120 ;; has an empty value or contains a symbol among "/", "#", "!", "$",
4121 ;; "*" "_" and "^". Though, do not consider a first row containing
4122 ;; only empty cells as special.
4123 (let ((special-column-p 'empty))
4124 (catch 'exit
4125 (mapc
4126 (lambda (row)
4127 (when (eq (org-element-property :type row) 'standard)
4128 (let ((value (org-element-contents
4129 (car (org-element-contents row)))))
4130 (cond ((member value '(("/") ("#") ("!") ("$") ("*") ("_") ("^")))
4131 (setq special-column-p 'special))
4132 ((not value))
4133 (t (throw 'exit nil))))))
4134 (org-element-contents table))
4135 (eq special-column-p 'special))))
4137 (defun org-export-table-has-header-p (table info)
4138 "Non-nil when TABLE has an header.
4140 INFO is a plist used as a communication channel.
4142 A table has an header when it contains at least two row groups."
4143 (let ((rowgroup 1) row-flag)
4144 (org-element-map table 'table-row
4145 (lambda (row)
4146 (cond
4147 ((> rowgroup 1) t)
4148 ((and row-flag (eq (org-element-property :type row) 'rule))
4149 (incf rowgroup) (setq row-flag nil))
4150 ((and (not row-flag) (eq (org-element-property :type row) 'standard))
4151 (setq row-flag t) nil)))
4152 info)))
4154 (defun org-export-table-row-is-special-p (table-row info)
4155 "Non-nil if TABLE-ROW is considered special.
4157 INFO is a plist used as the communication channel.
4159 All special rows will be ignored during export."
4160 (when (eq (org-element-property :type table-row) 'standard)
4161 (let ((first-cell (org-element-contents
4162 (car (org-element-contents table-row)))))
4163 ;; A row is special either when...
4165 ;; ... it starts with a field only containing "/",
4166 (equal first-cell '("/"))
4167 ;; ... the table contains a special column and the row start
4168 ;; with a marking character among, "^", "_", "$" or "!",
4169 (and (org-export-table-has-special-column-p
4170 (org-export-get-parent table-row))
4171 (member first-cell '(("^") ("_") ("$") ("!"))))
4172 ;; ... it contains only alignment cookies and empty cells.
4173 (let ((special-row-p 'empty))
4174 (catch 'exit
4175 (mapc
4176 (lambda (cell)
4177 (let ((value (org-element-contents cell)))
4178 ;; Since VALUE is a secondary string, the following
4179 ;; checks avoid expanding it with `org-export-data'.
4180 (cond ((not value))
4181 ((and (not (cdr value))
4182 (stringp (car value))
4183 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'"
4184 (car value)))
4185 (setq special-row-p 'cookie))
4186 (t (throw 'exit nil)))))
4187 (org-element-contents table-row))
4188 (eq special-row-p 'cookie)))))))
4190 (defun org-export-table-row-group (table-row info)
4191 "Return TABLE-ROW's group.
4193 INFO is a plist used as the communication channel.
4195 Return value is the group number, as an integer, or nil special
4196 rows and table rules. Group 1 is also table's header."
4197 (unless (or (eq (org-element-property :type table-row) 'rule)
4198 (org-export-table-row-is-special-p table-row info))
4199 (let ((group 0) row-flag)
4200 (catch 'found
4201 (mapc
4202 (lambda (row)
4203 (cond
4204 ((and (eq (org-element-property :type row) 'standard)
4205 (not (org-export-table-row-is-special-p row info)))
4206 (unless row-flag (incf group) (setq row-flag t)))
4207 ((eq (org-element-property :type row) 'rule)
4208 (setq row-flag nil)))
4209 (when (eq table-row row) (throw 'found group)))
4210 (org-element-contents (org-export-get-parent table-row)))))))
4212 (defun org-export-table-cell-width (table-cell info)
4213 "Return TABLE-CELL contents width.
4215 INFO is a plist used as the communication channel.
4217 Return value is the width given by the last width cookie in the
4218 same column as TABLE-CELL, or nil."
4219 (let* ((row (org-export-get-parent table-cell))
4220 (column (let ((cells (org-element-contents row)))
4221 (- (length cells) (length (memq table-cell cells)))))
4222 (table (org-export-get-parent-table table-cell))
4223 cookie-width)
4224 (mapc
4225 (lambda (row)
4226 (cond
4227 ;; In a special row, try to find a width cookie at COLUMN.
4228 ((org-export-table-row-is-special-p row info)
4229 (let ((value (org-element-contents
4230 (elt (org-element-contents row) column))))
4231 ;; The following checks avoid expanding unnecessarily the
4232 ;; cell with `org-export-data'
4233 (when (and value
4234 (not (cdr value))
4235 (stringp (car value))
4236 (string-match "\\`<[lrc]?\\([0-9]+\\)?>\\'" (car value))
4237 (match-string 1 (car value)))
4238 (setq cookie-width
4239 (string-to-number (match-string 1 (car value)))))))
4240 ;; Ignore table rules.
4241 ((eq (org-element-property :type row) 'rule))))
4242 (org-element-contents table))
4243 ;; Return value.
4244 cookie-width))
4246 (defun org-export-table-cell-alignment (table-cell info)
4247 "Return TABLE-CELL contents alignment.
4249 INFO is a plist used as the communication channel.
4251 Return alignment as specified by the last alignment cookie in the
4252 same column as TABLE-CELL. If no such cookie is found, a default
4253 alignment value will be deduced from fraction of numbers in the
4254 column (see `org-table-number-fraction' for more information).
4255 Possible values are `left', `right' and `center'."
4256 (let* ((row (org-export-get-parent table-cell))
4257 (column (let ((cells (org-element-contents row)))
4258 (- (length cells) (length (memq table-cell cells)))))
4259 (table (org-export-get-parent-table table-cell))
4260 (number-cells 0)
4261 (total-cells 0)
4262 cookie-align)
4263 (mapc
4264 (lambda (row)
4265 (cond
4266 ;; In a special row, try to find an alignment cookie at
4267 ;; COLUMN.
4268 ((org-export-table-row-is-special-p row info)
4269 (let ((value (org-element-contents
4270 (elt (org-element-contents row) column))))
4271 ;; Since VALUE is a secondary string, the following checks
4272 ;; avoid useless expansion through `org-export-data'.
4273 (when (and value
4274 (not (cdr value))
4275 (stringp (car value))
4276 (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'"
4277 (car value))
4278 (match-string 1 (car value)))
4279 (setq cookie-align (match-string 1 (car value))))))
4280 ;; Ignore table rules.
4281 ((eq (org-element-property :type row) 'rule))
4282 ;; In a standard row, check if cell's contents are expressing
4283 ;; some kind of number. Increase NUMBER-CELLS accordingly.
4284 ;; Though, don't bother if an alignment cookie has already
4285 ;; defined cell's alignment.
4286 ((not cookie-align)
4287 (let ((value (org-export-data
4288 (org-element-contents
4289 (elt (org-element-contents row) column))
4290 info)))
4291 (incf total-cells)
4292 (when (string-match org-table-number-regexp value)
4293 (incf number-cells))))))
4294 (org-element-contents table))
4295 ;; Return value. Alignment specified by cookies has precedence
4296 ;; over alignment deduced from cells contents.
4297 (cond ((equal cookie-align "l") 'left)
4298 ((equal cookie-align "r") 'right)
4299 ((equal cookie-align "c") 'center)
4300 ((>= (/ (float number-cells) total-cells) org-table-number-fraction)
4301 'right)
4302 (t 'left))))
4304 (defun org-export-table-cell-borders (table-cell info)
4305 "Return TABLE-CELL borders.
4307 INFO is a plist used as a communication channel.
4309 Return value is a list of symbols, or nil. Possible values are:
4310 `top', `bottom', `above', `below', `left' and `right'. Note:
4311 `top' (resp. `bottom') only happen for a cell in the first
4312 row (resp. last row) of the table, ignoring table rules, if any.
4314 Returned borders ignore special rows."
4315 (let* ((row (org-export-get-parent table-cell))
4316 (table (org-export-get-parent-table table-cell))
4317 borders)
4318 ;; Top/above border? TABLE-CELL has a border above when a rule
4319 ;; used to demarcate row groups can be found above. Hence,
4320 ;; finding a rule isn't sufficient to push `above' in BORDERS:
4321 ;; another regular row has to be found above that rule.
4322 (let (rule-flag)
4323 (catch 'exit
4324 (mapc (lambda (row)
4325 (cond ((eq (org-element-property :type row) 'rule)
4326 (setq rule-flag t))
4327 ((not (org-export-table-row-is-special-p row info))
4328 (if rule-flag (throw 'exit (push 'above borders))
4329 (throw 'exit nil)))))
4330 ;; Look at every row before the current one.
4331 (cdr (memq row (reverse (org-element-contents table)))))
4332 ;; No rule above, or rule found starts the table (ignoring any
4333 ;; special row): TABLE-CELL is at the top of the table.
4334 (when rule-flag (push 'above borders))
4335 (push 'top borders)))
4336 ;; Bottom/below border? TABLE-CELL has a border below when next
4337 ;; non-regular row below is a rule.
4338 (let (rule-flag)
4339 (catch 'exit
4340 (mapc (lambda (row)
4341 (cond ((eq (org-element-property :type row) 'rule)
4342 (setq rule-flag t))
4343 ((not (org-export-table-row-is-special-p row info))
4344 (if rule-flag (throw 'exit (push 'below borders))
4345 (throw 'exit nil)))))
4346 ;; Look at every row after the current one.
4347 (cdr (memq row (org-element-contents table))))
4348 ;; No rule below, or rule found ends the table (modulo some
4349 ;; special row): TABLE-CELL is at the bottom of the table.
4350 (when rule-flag (push 'below borders))
4351 (push 'bottom borders)))
4352 ;; Right/left borders? They can only be specified by column
4353 ;; groups. Column groups are defined in a row starting with "/".
4354 ;; Also a column groups row only contains "<", "<>", ">" or blank
4355 ;; cells.
4356 (catch 'exit
4357 (let ((column (let ((cells (org-element-contents row)))
4358 (- (length cells) (length (memq table-cell cells))))))
4359 (mapc
4360 (lambda (row)
4361 (unless (eq (org-element-property :type row) 'rule)
4362 (when (equal (org-element-contents
4363 (car (org-element-contents row)))
4364 '("/"))
4365 (let ((column-groups
4366 (mapcar
4367 (lambda (cell)
4368 (let ((value (org-element-contents cell)))
4369 (when (member value '(("<") ("<>") (">") nil))
4370 (car value))))
4371 (org-element-contents row))))
4372 ;; There's a left border when previous cell, if
4373 ;; any, ends a group, or current one starts one.
4374 (when (or (and (not (zerop column))
4375 (member (elt column-groups (1- column))
4376 '(">" "<>")))
4377 (member (elt column-groups column) '("<" "<>")))
4378 (push 'left borders))
4379 ;; There's a right border when next cell, if any,
4380 ;; starts a group, or current one ends one.
4381 (when (or (and (/= (1+ column) (length column-groups))
4382 (member (elt column-groups (1+ column))
4383 '("<" "<>")))
4384 (member (elt column-groups column) '(">" "<>")))
4385 (push 'right borders))
4386 (throw 'exit nil)))))
4387 ;; Table rows are read in reverse order so last column groups
4388 ;; row has precedence over any previous one.
4389 (reverse (org-element-contents table)))))
4390 ;; Return value.
4391 borders))
4393 (defun org-export-table-cell-starts-colgroup-p (table-cell info)
4394 "Non-nil when TABLE-CELL is at the beginning of a row group.
4395 INFO is a plist used as a communication channel."
4396 ;; A cell starts a column group either when it is at the beginning
4397 ;; of a row (or after the special column, if any) or when it has
4398 ;; a left border.
4399 (or (eq (org-element-map (org-export-get-parent table-cell) 'table-cell
4400 'identity info 'first-match)
4401 table-cell)
4402 (memq 'left (org-export-table-cell-borders table-cell info))))
4404 (defun org-export-table-cell-ends-colgroup-p (table-cell info)
4405 "Non-nil when TABLE-CELL is at the end of a row group.
4406 INFO is a plist used as a communication channel."
4407 ;; A cell ends a column group either when it is at the end of a row
4408 ;; or when it has a right border.
4409 (or (eq (car (last (org-element-contents
4410 (org-export-get-parent table-cell))))
4411 table-cell)
4412 (memq 'right (org-export-table-cell-borders table-cell info))))
4414 (defun org-export-table-row-starts-rowgroup-p (table-row info)
4415 "Non-nil when TABLE-ROW is at the beginning of a column group.
4416 INFO is a plist used as a communication channel."
4417 (unless (or (eq (org-element-property :type table-row) 'rule)
4418 (org-export-table-row-is-special-p table-row info))
4419 (let ((borders (org-export-table-cell-borders
4420 (car (org-element-contents table-row)) info)))
4421 (or (memq 'top borders) (memq 'above borders)))))
4423 (defun org-export-table-row-ends-rowgroup-p (table-row info)
4424 "Non-nil when TABLE-ROW is at the end of a column group.
4425 INFO is a plist used as a communication channel."
4426 (unless (or (eq (org-element-property :type table-row) 'rule)
4427 (org-export-table-row-is-special-p table-row info))
4428 (let ((borders (org-export-table-cell-borders
4429 (car (org-element-contents table-row)) info)))
4430 (or (memq 'bottom borders) (memq 'below borders)))))
4432 (defun org-export-table-row-starts-header-p (table-row info)
4433 "Non-nil when TABLE-ROW is the first table header's row.
4434 INFO is a plist used as a communication channel."
4435 (and (org-export-table-has-header-p
4436 (org-export-get-parent-table table-row) info)
4437 (org-export-table-row-starts-rowgroup-p table-row info)
4438 (= (org-export-table-row-group table-row info) 1)))
4440 (defun org-export-table-row-ends-header-p (table-row info)
4441 "Non-nil when TABLE-ROW is the last table header's row.
4442 INFO is a plist used as a communication channel."
4443 (and (org-export-table-has-header-p
4444 (org-export-get-parent-table table-row) info)
4445 (org-export-table-row-ends-rowgroup-p table-row info)
4446 (= (org-export-table-row-group table-row info) 1)))
4448 (defun org-export-table-dimensions (table info)
4449 "Return TABLE dimensions.
4451 INFO is a plist used as a communication channel.
4453 Return value is a CONS like (ROWS . COLUMNS) where
4454 ROWS (resp. COLUMNS) is the number of exportable
4455 rows (resp. columns)."
4456 (let (first-row (columns 0) (rows 0))
4457 ;; Set number of rows, and extract first one.
4458 (org-element-map table 'table-row
4459 (lambda (row)
4460 (when (eq (org-element-property :type row) 'standard)
4461 (incf rows)
4462 (unless first-row (setq first-row row)))) info)
4463 ;; Set number of columns.
4464 (org-element-map first-row 'table-cell (lambda (cell) (incf columns)) info)
4465 ;; Return value.
4466 (cons rows columns)))
4468 (defun org-export-table-cell-address (table-cell info)
4469 "Return address of a regular TABLE-CELL object.
4471 TABLE-CELL is the cell considered. INFO is a plist used as
4472 a communication channel.
4474 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4475 zero-based index. Only exportable cells are considered. The
4476 function returns nil for other cells."
4477 (let* ((table-row (org-export-get-parent table-cell))
4478 (table (org-export-get-parent-table table-cell)))
4479 ;; Ignore cells in special rows or in special column.
4480 (unless (or (org-export-table-row-is-special-p table-row info)
4481 (and (org-export-table-has-special-column-p table)
4482 (eq (car (org-element-contents table-row)) table-cell)))
4483 (cons
4484 ;; Row number.
4485 (let ((row-count 0))
4486 (org-element-map table 'table-row
4487 (lambda (row)
4488 (cond ((eq (org-element-property :type row) 'rule) nil)
4489 ((eq row table-row) row-count)
4490 (t (incf row-count) nil)))
4491 info 'first-match))
4492 ;; Column number.
4493 (let ((col-count 0))
4494 (org-element-map table-row 'table-cell
4495 (lambda (cell)
4496 (if (eq cell table-cell) col-count (incf col-count) nil))
4497 info 'first-match))))))
4499 (defun org-export-get-table-cell-at (address table info)
4500 "Return regular table-cell object at ADDRESS in TABLE.
4502 Address is a CONS cell (ROW . COLUMN), where ROW and COLUMN are
4503 zero-based index. TABLE is a table type element. INFO is
4504 a plist used as a communication channel.
4506 If no table-cell, among exportable cells, is found at ADDRESS,
4507 return nil."
4508 (let ((column-pos (cdr address)) (column-count 0))
4509 (org-element-map
4510 ;; Row at (car address) or nil.
4511 (let ((row-pos (car address)) (row-count 0))
4512 (org-element-map table 'table-row
4513 (lambda (row)
4514 (cond ((eq (org-element-property :type row) 'rule) nil)
4515 ((= row-count row-pos) row)
4516 (t (incf row-count) nil)))
4517 info 'first-match))
4518 'table-cell
4519 (lambda (cell)
4520 (if (= column-count column-pos) cell
4521 (incf column-count) nil))
4522 info 'first-match)))
4525 ;;;; For Tables Of Contents
4527 ;; `org-export-collect-headlines' builds a list of all exportable
4528 ;; headline elements, maybe limited to a certain depth. One can then
4529 ;; easily parse it and transcode it.
4531 ;; Building lists of tables, figures or listings is quite similar.
4532 ;; Once the generic function `org-export-collect-elements' is defined,
4533 ;; `org-export-collect-tables', `org-export-collect-figures' and
4534 ;; `org-export-collect-listings' can be derived from it.
4536 (defun org-export-collect-headlines (info &optional n)
4537 "Collect headlines in order to build a table of contents.
4539 INFO is a plist used as a communication channel.
4541 When optional argument N is an integer, it specifies the depth of
4542 the table of contents. Otherwise, it is set to the value of the
4543 last headline level. See `org-export-headline-levels' for more
4544 information.
4546 Return a list of all exportable headlines as parsed elements.
4547 Footnote sections, if any, will be ignored."
4548 (unless (wholenump n) (setq n (plist-get info :headline-levels)))
4549 (org-element-map (plist-get info :parse-tree) 'headline
4550 (lambda (headline)
4551 (unless (org-element-property :footnote-section-p headline)
4552 ;; Strip contents from HEADLINE.
4553 (let ((relative-level (org-export-get-relative-level headline info)))
4554 (unless (> relative-level n) headline))))
4555 info))
4557 (defun org-export-collect-elements (type info &optional predicate)
4558 "Collect referenceable elements of a determined type.
4560 TYPE can be a symbol or a list of symbols specifying element
4561 types to search. Only elements with a caption are collected.
4563 INFO is a plist used as a communication channel.
4565 When non-nil, optional argument PREDICATE is a function accepting
4566 one argument, an element of type TYPE. It returns a non-nil
4567 value when that element should be collected.
4569 Return a list of all elements found, in order of appearance."
4570 (org-element-map (plist-get info :parse-tree) type
4571 (lambda (element)
4572 (and (org-element-property :caption element)
4573 (or (not predicate) (funcall predicate element))
4574 element))
4575 info))
4577 (defun org-export-collect-tables (info)
4578 "Build a list of tables.
4579 INFO is a plist used as a communication channel.
4581 Return a list of table elements with a caption."
4582 (org-export-collect-elements 'table info))
4584 (defun org-export-collect-figures (info predicate)
4585 "Build a list of figures.
4587 INFO is a plist used as a communication channel. PREDICATE is
4588 a function which accepts one argument: a paragraph element and
4589 whose return value is non-nil when that element should be
4590 collected.
4592 A figure is a paragraph type element, with a caption, verifying
4593 PREDICATE. The latter has to be provided since a \"figure\" is
4594 a vague concept that may depend on back-end.
4596 Return a list of elements recognized as figures."
4597 (org-export-collect-elements 'paragraph info predicate))
4599 (defun org-export-collect-listings (info)
4600 "Build a list of src blocks.
4602 INFO is a plist used as a communication channel.
4604 Return a list of src-block elements with a caption."
4605 (org-export-collect-elements 'src-block info))
4608 ;;;; Smart Quotes
4610 ;; The main function for the smart quotes sub-system is
4611 ;; `org-export-activate-smart-quotes', which replaces every quote in
4612 ;; a given string from the parse tree with its "smart" counterpart.
4614 ;; Dictionary for smart quotes is stored in
4615 ;; `org-export-smart-quotes-alist'.
4617 ;; Internally, regexps matching potential smart quotes (checks at
4618 ;; string boundaries are also necessary) are defined in
4619 ;; `org-export-smart-quotes-regexps'.
4621 (defconst org-export-smart-quotes-alist
4622 '(("de"
4623 (opening-double-quote :utf-8 "„" :html "&bdquo;" :latex "\"`"
4624 :texinfo "@quotedblbase{}")
4625 (closing-double-quote :utf-8 "“" :html "&ldquo;" :latex "\"'"
4626 :texinfo "@quotedblleft{}")
4627 (opening-single-quote :utf-8 "‚" :html "&sbquo;" :latex "\\glq{}"
4628 :texinfo "@quotesinglbase{}")
4629 (closing-single-quote :utf-8 "‘" :html "&lsquo;" :latex "\\grq{}"
4630 :texinfo "@quoteleft{}")
4631 (apostrophe :utf-8 "’" :html "&rsquo;"))
4632 ("en"
4633 (opening-double-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
4634 (closing-double-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
4635 (opening-single-quote :utf-8 "‘" :html "&lsquo;" :latex "`" :texinfo "`")
4636 (closing-single-quote :utf-8 "’" :html "&rsquo;" :latex "'" :texinfo "'")
4637 (apostrophe :utf-8 "’" :html "&rsquo;"))
4638 ("es"
4639 (opening-double-quote :utf-8 "«" :html "&laquo;" :latex "\\guillemotleft{}"
4640 :texinfo "@guillemetleft{}")
4641 (closing-double-quote :utf-8 "»" :html "&raquo;" :latex "\\guillemotright{}"
4642 :texinfo "@guillemetright{}")
4643 (opening-single-quote :utf-8 "“" :html "&ldquo;" :latex "``" :texinfo "``")
4644 (closing-single-quote :utf-8 "”" :html "&rdquo;" :latex "''" :texinfo "''")
4645 (apostrophe :utf-8 "’" :html "&rsquo;"))
4646 ("fr"
4647 (opening-double-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
4648 :texinfo "@guillemetleft{}@tie{}")
4649 (closing-double-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
4650 :texinfo "@tie{}@guillemetright{}")
4651 (opening-single-quote :utf-8 "« " :html "&laquo;&nbsp;" :latex "\\og "
4652 :texinfo "@guillemetleft{}@tie{}")
4653 (closing-single-quote :utf-8 " »" :html "&nbsp;&raquo;" :latex "\\fg{}"
4654 :texinfo "@tie{}@guillemetright{}")
4655 (apostrophe :utf-8 "’" :html "&rsquo;")))
4656 "Smart quotes translations.
4658 Alist whose CAR is a language string and CDR is an alist with
4659 quote type as key and a plist associating various encodings to
4660 their translation as value.
4662 A quote type can be any symbol among `opening-double-quote',
4663 `closing-double-quote', `opening-single-quote',
4664 `closing-single-quote' and `apostrophe'.
4666 Valid encodings include `:utf-8', `:html', `:latex' and
4667 `:texinfo'.
4669 If no translation is found, the quote character is left as-is.")
4671 (defconst org-export-smart-quotes-regexps
4672 (list
4673 ;; Possible opening quote at beginning of string.
4674 "\\`\\([\"']\\)\\(\\w\\|\\s.\\|\\s_\\)"
4675 ;; Possible closing quote at beginning of string.
4676 "\\`\\([\"']\\)\\(\\s-\\|\\s)\\|\\s.\\)"
4677 ;; Possible apostrophe at beginning of string.
4678 "\\`\\('\\)\\S-"
4679 ;; Opening single and double quotes.
4680 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\(?:\\w\\|\\s.\\|\\s_\\)"
4681 ;; Closing single and double quotes.
4682 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\(?:\\s-\\|\\s)\\|\\s.\\)"
4683 ;; Apostrophe.
4684 "\\S-\\('\\)\\S-"
4685 ;; Possible opening quote at end of string.
4686 "\\(?:\\s-\\|\\s(\\)\\([\"']\\)\\'"
4687 ;; Possible closing quote at end of string.
4688 "\\(?:\\w\\|\\s.\\|\\s_\\)\\([\"']\\)\\'"
4689 ;; Possible apostrophe at end of string.
4690 "\\S-\\('\\)\\'")
4691 "List of regexps matching a quote or an apostrophe.
4692 In every regexp, quote or apostrophe matched is put in group 1.")
4694 (defun org-export-activate-smart-quotes (s encoding info &optional original)
4695 "Replace regular quotes with \"smart\" quotes in string S.
4697 ENCODING is a symbol among `:html', `:latex', `:texinfo' and
4698 `:utf-8'. INFO is a plist used as a communication channel.
4700 The function has to retrieve information about string
4701 surroundings in parse tree. It can only happen with an
4702 unmodified string. Thus, if S has already been through another
4703 process, a non-nil ORIGINAL optional argument will provide that
4704 original string.
4706 Return the new string."
4707 (if (equal s "") ""
4708 (let* ((prev (org-export-get-previous-element (or original s) info))
4709 ;; Try to be flexible when computing number of blanks
4710 ;; before object. The previous object may be a string
4711 ;; introduced by the back-end and not completely parsed.
4712 (pre-blank (and prev
4713 (or (org-element-property :post-blank prev)
4714 ;; A string with missing `:post-blank'
4715 ;; property.
4716 (and (stringp prev)
4717 (string-match " *\\'" prev)
4718 (length (match-string 0 prev)))
4719 ;; Fallback value.
4720 0)))
4721 (next (org-export-get-next-element (or original s) info))
4722 (get-smart-quote
4723 (lambda (q type)
4724 ;; Return smart quote associated to a give quote Q, as
4725 ;; a string. TYPE is a symbol among `open', `close' and
4726 ;; `apostrophe'.
4727 (let ((key (case type
4728 (apostrophe 'apostrophe)
4729 (open (if (equal "'" q) 'opening-single-quote
4730 'opening-double-quote))
4731 (otherwise (if (equal "'" q) 'closing-single-quote
4732 'closing-double-quote)))))
4733 (or (plist-get
4734 (cdr (assq key
4735 (cdr (assoc (plist-get info :language)
4736 org-export-smart-quotes-alist))))
4737 encoding)
4738 q)))))
4739 (if (or (equal "\"" s) (equal "'" s))
4740 ;; Only a quote: no regexp can match. We have to check both
4741 ;; sides and decide what to do.
4742 (cond ((and (not prev) (not next)) s)
4743 ((not prev) (funcall get-smart-quote s 'open))
4744 ((and (not next) (zerop pre-blank))
4745 (funcall get-smart-quote s 'close))
4746 ((not next) s)
4747 ((zerop pre-blank) (funcall get-smart-quote s 'apostrophe))
4748 (t (funcall get-smart-quote 'open)))
4749 ;; 1. Replace quote character at the beginning of S.
4750 (cond
4751 ;; Apostrophe?
4752 ((and prev (zerop pre-blank)
4753 (string-match (nth 2 org-export-smart-quotes-regexps) s))
4754 (setq s (replace-match
4755 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
4756 nil t s 1)))
4757 ;; Closing quote?
4758 ((and prev (zerop pre-blank)
4759 (string-match (nth 1 org-export-smart-quotes-regexps) s))
4760 (setq s (replace-match
4761 (funcall get-smart-quote (match-string 1 s) 'close)
4762 nil t s 1)))
4763 ;; Opening quote?
4764 ((and (or (not prev) (> pre-blank 0))
4765 (string-match (nth 0 org-export-smart-quotes-regexps) s))
4766 (setq s (replace-match
4767 (funcall get-smart-quote (match-string 1 s) 'open)
4768 nil t s 1))))
4769 ;; 2. Replace quotes in the middle of the string.
4770 (setq s (replace-regexp-in-string
4771 ;; Opening quotes.
4772 (nth 3 org-export-smart-quotes-regexps)
4773 (lambda (text)
4774 (funcall get-smart-quote (match-string 1 text) 'open))
4775 s nil t 1))
4776 (setq s (replace-regexp-in-string
4777 ;; Closing quotes.
4778 (nth 4 org-export-smart-quotes-regexps)
4779 (lambda (text)
4780 (funcall get-smart-quote (match-string 1 text) 'close))
4781 s nil t 1))
4782 (setq s (replace-regexp-in-string
4783 ;; Apostrophes.
4784 (nth 5 org-export-smart-quotes-regexps)
4785 (lambda (text)
4786 (funcall get-smart-quote (match-string 1 text) 'apostrophe))
4787 s nil t 1))
4788 ;; 3. Replace quote character at the end of S.
4789 (cond
4790 ;; Apostrophe?
4791 ((and next (string-match (nth 8 org-export-smart-quotes-regexps) s))
4792 (setq s (replace-match
4793 (funcall get-smart-quote (match-string 1 s) 'apostrophe)
4794 nil t s 1)))
4795 ;; Closing quote?
4796 ((and (not next)
4797 (string-match (nth 7 org-export-smart-quotes-regexps) s))
4798 (setq s (replace-match
4799 (funcall get-smart-quote (match-string 1 s) 'close)
4800 nil t s 1)))
4801 ;; Opening quote?
4802 ((and next (string-match (nth 6 org-export-smart-quotes-regexps) s))
4803 (setq s (replace-match
4804 (funcall get-smart-quote (match-string 1 s) 'open)
4805 nil t s 1))))
4806 ;; Return string with smart quotes.
4807 s))))
4809 ;;;; Topology
4811 ;; Here are various functions to retrieve information about the
4812 ;; neighbourhood of a given element or object. Neighbours of interest
4813 ;; are direct parent (`org-export-get-parent'), parent headline
4814 ;; (`org-export-get-parent-headline'), first element containing an
4815 ;; object, (`org-export-get-parent-element'), parent table
4816 ;; (`org-export-get-parent-table'), previous element or object
4817 ;; (`org-export-get-previous-element') and next element or object
4818 ;; (`org-export-get-next-element').
4820 ;; `org-export-get-genealogy' returns the full genealogy of a given
4821 ;; element or object, from closest parent to full parse tree.
4823 (defun org-export-get-parent (blob)
4824 "Return BLOB parent or nil.
4825 BLOB is the element or object considered."
4826 (org-element-property :parent blob))
4828 (defun org-export-get-genealogy (blob)
4829 "Return full genealogy relative to a given element or object.
4831 BLOB is the element or object being considered.
4833 Ancestors are returned from closest to farthest, the last one
4834 being the full parse tree."
4835 (let (genealogy (parent blob))
4836 (while (setq parent (org-element-property :parent parent))
4837 (push parent genealogy))
4838 (nreverse genealogy)))
4840 (defun org-export-get-parent-headline (blob)
4841 "Return BLOB parent headline or nil.
4842 BLOB is the element or object being considered."
4843 (let ((parent blob))
4844 (while (and (setq parent (org-element-property :parent parent))
4845 (not (eq (org-element-type parent) 'headline))))
4846 parent))
4848 (defun org-export-get-parent-element (object)
4849 "Return first element containing OBJECT or nil.
4850 OBJECT is the object to consider."
4851 (let ((parent object))
4852 (while (and (setq parent (org-element-property :parent parent))
4853 (memq (org-element-type parent) org-element-all-objects)))
4854 parent))
4856 (defun org-export-get-parent-table (object)
4857 "Return OBJECT parent table or nil.
4858 OBJECT is either a `table-cell' or `table-element' type object."
4859 (let ((parent object))
4860 (while (and (setq parent (org-element-property :parent parent))
4861 (not (eq (org-element-type parent) 'table))))
4862 parent))
4864 (defun org-export-get-previous-element (blob info &optional n)
4865 "Return previous element or object.
4867 BLOB is an element or object. INFO is a plist used as
4868 a communication channel. Return previous exportable element or
4869 object, a string, or nil.
4871 When optional argument N is a positive integer, return a list
4872 containing up to N siblings before BLOB, from farthest to
4873 closest. With any other non-nil value, return a list containing
4874 all of them."
4875 (let ((siblings
4876 ;; An object can belong to the contents of its parent or
4877 ;; to a secondary string. We check the latter option
4878 ;; first.
4879 (let ((parent (org-export-get-parent blob)))
4880 (or (and (not (memq (org-element-type blob)
4881 org-element-all-elements))
4882 (let ((sec-value
4883 (org-element-property
4884 (cdr (assq (org-element-type parent)
4885 org-element-secondary-value-alist))
4886 parent)))
4887 (and (memq blob sec-value) sec-value)))
4888 (org-element-contents parent))))
4889 prev)
4890 (catch 'exit
4891 (mapc (lambda (obj)
4892 (cond ((memq obj (plist-get info :ignore-list)))
4893 ((null n) (throw 'exit obj))
4894 ((not (wholenump n)) (push obj prev))
4895 ((zerop n) (throw 'exit prev))
4896 (t (decf n) (push obj prev))))
4897 (cdr (memq blob (reverse siblings))))
4898 prev)))
4900 (defun org-export-get-next-element (blob info &optional n)
4901 "Return next element or object.
4903 BLOB is an element or object. INFO is a plist used as
4904 a communication channel. Return next exportable element or
4905 object, a string, or nil.
4907 When optional argument N is a positive integer, return a list
4908 containing up to N siblings after BLOB, from closest to farthest.
4909 With any other non-nil value, return a list containing all of
4910 them."
4911 (let ((siblings
4912 ;; An object can belong to the contents of its parent or to
4913 ;; a secondary string. We check the latter option first.
4914 (let ((parent (org-export-get-parent blob)))
4915 (or (and (not (memq (org-element-type blob)
4916 org-element-all-objects))
4917 (let ((sec-value
4918 (org-element-property
4919 (cdr (assq (org-element-type parent)
4920 org-element-secondary-value-alist))
4921 parent)))
4922 (cdr (memq blob sec-value))))
4923 (cdr (memq blob (org-element-contents parent))))))
4924 next)
4925 (catch 'exit
4926 (mapc (lambda (obj)
4927 (cond ((memq obj (plist-get info :ignore-list)))
4928 ((null n) (throw 'exit obj))
4929 ((not (wholenump n)) (push obj next))
4930 ((zerop n) (throw 'exit (nreverse next)))
4931 (t (decf n) (push obj next))))
4932 siblings)
4933 (nreverse next))))
4936 ;;;; Translation
4938 ;; `org-export-translate' translates a string according to language
4939 ;; specified by LANGUAGE keyword or `org-export-language-setup'
4940 ;; variable and a specified charset. `org-export-dictionary' contains
4941 ;; the dictionary used for the translation.
4943 (defconst org-export-dictionary
4944 '(("Author"
4945 ("ca" :default "Autor")
4946 ("cs" :default "Autor")
4947 ("da" :default "Ophavsmand")
4948 ("de" :default "Autor")
4949 ("eo" :html "A&#365;toro")
4950 ("es" :default "Autor")
4951 ("fi" :html "Tekij&auml;")
4952 ("fr" :default "Auteur")
4953 ("hu" :default "Szerz&otilde;")
4954 ("is" :html "H&ouml;fundur")
4955 ("it" :default "Autore")
4956 ("ja" :html "&#33879;&#32773;" :utf-8 "著者")
4957 ("nl" :default "Auteur")
4958 ("no" :default "Forfatter")
4959 ("nb" :default "Forfatter")
4960 ("nn" :default "Forfattar")
4961 ("pl" :default "Autor")
4962 ("ru" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
4963 ("sv" :html "F&ouml;rfattare")
4964 ("uk" :html "&#1040;&#1074;&#1090;&#1086;&#1088;" :utf-8 "Автор")
4965 ("zh-CN" :html "&#20316;&#32773;" :utf-8 "作者")
4966 ("zh-TW" :html "&#20316;&#32773;" :utf-8 "作者"))
4967 ("Date"
4968 ("ca" :default "Data")
4969 ("cs" :default "Datum")
4970 ("da" :default "Dato")
4971 ("de" :default "Datum")
4972 ("eo" :default "Dato")
4973 ("es" :default "Fecha")
4974 ("fi" :html "P&auml;iv&auml;m&auml;&auml;r&auml;")
4975 ("hu" :html "D&aacute;tum")
4976 ("is" :default "Dagsetning")
4977 ("it" :default "Data")
4978 ("ja" :html "&#26085;&#20184;" :utf-8 "日付")
4979 ("nl" :default "Datum")
4980 ("no" :default "Dato")
4981 ("nb" :default "Dato")
4982 ("nn" :default "Dato")
4983 ("pl" :default "Data")
4984 ("ru" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
4985 ("sv" :default "Datum")
4986 ("uk" :html "&#1044;&#1072;&#1090;&#1072;" :utf-8 "Дата")
4987 ("zh-CN" :html "&#26085;&#26399;" :utf-8 "日期")
4988 ("zh-TW" :html "&#26085;&#26399;" :utf-8 "日期"))
4989 ("Equation"
4990 ("fr" :ascii "Equation" :default "Équation"))
4991 ("Figure")
4992 ("Footnotes"
4993 ("ca" :html "Peus de p&agrave;gina")
4994 ("cs" :default "Pozn\xe1mky pod carou")
4995 ("da" :default "Fodnoter")
4996 ("de" :html "Fu&szlig;noten")
4997 ("eo" :default "Piednotoj")
4998 ("es" :html "Pies de p&aacute;gina")
4999 ("fi" :default "Alaviitteet")
5000 ("fr" :default "Notes de bas de page")
5001 ("hu" :html "L&aacute;bjegyzet")
5002 ("is" :html "Aftanm&aacute;lsgreinar")
5003 ("it" :html "Note a pi&egrave; di pagina")
5004 ("ja" :html "&#33050;&#27880;" :utf-8 "脚注")
5005 ("nl" :default "Voetnoten")
5006 ("no" :default "Fotnoter")
5007 ("nb" :default "Fotnoter")
5008 ("nn" :default "Fotnotar")
5009 ("pl" :default "Przypis")
5010 ("ru" :html "&#1057;&#1085;&#1086;&#1089;&#1082;&#1080;" :utf-8 "Сноски")
5011 ("sv" :default "Fotnoter")
5012 ("uk" :html "&#1055;&#1088;&#1080;&#1084;&#1110;&#1090;&#1082;&#1080;"
5013 :utf-8 "Примітки")
5014 ("zh-CN" :html "&#33050;&#27880;" :utf-8 "脚注")
5015 ("zh-TW" :html "&#33139;&#35387;" :utf-8 "腳註"))
5016 ("List of Listings"
5017 ("fr" :default "Liste des programmes"))
5018 ("List of Tables"
5019 ("fr" :default "Liste des tableaux"))
5020 ("Listing %d:"
5021 ("fr"
5022 :ascii "Programme %d :" :default "Programme nº %d :"
5023 :latin1 "Programme %d :"))
5024 ("Listing %d: %s"
5025 ("fr"
5026 :ascii "Programme %d : %s" :default "Programme nº %d : %s"
5027 :latin1 "Programme %d : %s"))
5028 ("See section %s"
5029 ("fr" :default "cf. section %s"))
5030 ("Table %d:"
5031 ("fr"
5032 :ascii "Tableau %d :" :default "Tableau nº %d :" :latin1 "Tableau %d :"))
5033 ("Table %d: %s"
5034 ("fr"
5035 :ascii "Tableau %d : %s" :default "Tableau nº %d : %s"
5036 :latin1 "Tableau %d : %s"))
5037 ("Table of Contents"
5038 ("ca" :html "&Iacute;ndex")
5039 ("cs" :default "Obsah")
5040 ("da" :default "Indhold")
5041 ("de" :default "Inhaltsverzeichnis")
5042 ("eo" :default "Enhavo")
5043 ("es" :html "&Iacute;ndice")
5044 ("fi" :html "Sis&auml;llysluettelo")
5045 ("fr" :ascii "Sommaire" :default "Table des matières")
5046 ("hu" :html "Tartalomjegyz&eacute;k")
5047 ("is" :default "Efnisyfirlit")
5048 ("it" :default "Indice")
5049 ("ja" :html "&#30446;&#27425;" :utf-8 "目次")
5050 ("nl" :default "Inhoudsopgave")
5051 ("no" :default "Innhold")
5052 ("nb" :default "Innhold")
5053 ("nn" :default "Innhald")
5054 ("pl" :html "Spis tre&#x015b;ci")
5055 ("ru" :html "&#1057;&#1086;&#1076;&#1077;&#1088;&#1078;&#1072;&#1085;&#1080;&#1077;"
5056 :utf-8 "Содержание")
5057 ("sv" :html "Inneh&aring;ll")
5058 ("uk" :html "&#1047;&#1084;&#1110;&#1089;&#1090;" :utf-8 "Зміст")
5059 ("zh-CN" :html "&#30446;&#24405;" :utf-8 "目录")
5060 ("zh-TW" :html "&#30446;&#37636;" :utf-8 "目錄"))
5061 ("Unknown reference"
5062 ("fr" :ascii "Destination inconnue" :default "Référence inconnue")))
5063 "Dictionary for export engine.
5065 Alist whose CAR is the string to translate and CDR is an alist
5066 whose CAR is the language string and CDR is a plist whose
5067 properties are possible charsets and values translated terms.
5069 It is used as a database for `org-export-translate'. Since this
5070 function returns the string as-is if no translation was found,
5071 the variable only needs to record values different from the
5072 entry.")
5074 (defun org-export-translate (s encoding info)
5075 "Translate string S according to language specification.
5077 ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1'
5078 and `:utf-8'. INFO is a plist used as a communication channel.
5080 Translation depends on `:language' property. Return the
5081 translated string. If no translation is found, try to fall back
5082 to `:default' encoding. If it fails, return S."
5083 (let* ((lang (plist-get info :language))
5084 (translations (cdr (assoc lang
5085 (cdr (assoc s org-export-dictionary))))))
5086 (or (plist-get translations encoding)
5087 (plist-get translations :default)
5088 s)))
5092 ;;; Asynchronous Export
5094 ;; `org-export-async-start' is the entry point for asynchronous
5095 ;; export. It recreates current buffer (including visibility,
5096 ;; narrowing and visited file) in an external Emacs process, and
5097 ;; evaluates a command there. It then applies a function on the
5098 ;; returned results in the current process.
5100 ;; Asynchronously generated results are never displayed directly.
5101 ;; Instead, they are stored in `org-export-stack-contents'. They can
5102 ;; then be retrieved by calling `org-export-stack'.
5104 ;; Export Stack is viewed through a dedicated major mode
5105 ;;`org-export-stack-mode' and tools: `org-export-stack-refresh',
5106 ;;`org-export-stack-delete', `org-export-stack-view' and
5107 ;;`org-export-stack-clear'.
5109 ;; For back-ends, `org-export-add-to-stack' add a new source to stack.
5110 ;; It should used whenever `org-export-async-start' is called.
5112 (defmacro org-export-async-start (fun &rest body)
5113 "Call function FUN on the results returned by BODY evaluation.
5115 BODY evaluation happens in an asynchronous process, from a buffer
5116 which is an exact copy of the current one.
5118 Use `org-export-add-to-stack' in FUN in order to register results
5119 in the stack. Examples for, respectively a temporary buffer and
5120 a file are:
5122 \(org-export-async-start
5123 \(lambda (output)
5124 \(with-current-buffer (get-buffer-create \"*Org BACKEND Export*\")
5125 \(erase-buffer)
5126 \(insert output)
5127 \(goto-char (point-min))
5128 \(org-export-add-to-stack (current-buffer) 'backend)))
5129 `(org-export-as 'backend ,subtreep ,visible-only ,body-only ',ext-plist))
5133 \(org-export-async-start
5134 \(lambda (f) (org-export-add-to-stack f 'backend))
5135 `(expand-file-name
5136 \(org-export-to-file
5137 'backend ,outfile ,subtreep ,visible-only ,body-only ',ext-plist)))"
5138 (declare (indent 1) (debug t))
5139 (org-with-gensyms (process temp-file copy-fun proc-buffer handler)
5140 ;; Write the full sexp evaluating BODY in a copy of the current
5141 ;; buffer to a temporary file, as it may be too long for program
5142 ;; args in `start-process'.
5143 `(with-temp-message "Initializing asynchronous export process"
5144 (let ((,copy-fun (org-export--generate-copy-script (current-buffer)))
5145 (,temp-file (make-temp-file "org-export-process")))
5146 (with-temp-file ,temp-file
5147 (insert
5148 (format
5149 "%S"
5150 `(with-temp-buffer
5151 ,(when org-export-async-debug '(setq debug-on-error t))
5152 ;; Ignore `kill-emacs-hook' and code evaluation
5153 ;; queries from Babel as we need a truly
5154 ;; non-interactive process.
5155 (setq kill-emacs-hook nil
5156 org-babel-confirm-evaluate-answer-no t)
5157 ;; Initialize export framework in external process.
5158 (require 'ox)
5159 ;; Re-create current buffer there.
5160 (funcall ,,copy-fun)
5161 (restore-buffer-modified-p nil)
5162 ;; Sexp to evaluate in the buffer.
5163 (print (progn ,,@body))))))
5164 ;; Start external process.
5165 (let* ((process-connection-type nil)
5166 (,proc-buffer (generate-new-buffer-name "*Org Export Process*"))
5167 (,process
5168 (start-process
5169 "org-export-process" ,proc-buffer
5170 (expand-file-name invocation-name invocation-directory)
5171 "-Q" "--batch"
5172 "-l" org-export-async-init-file
5173 "-l" ,temp-file)))
5174 ;; Register running process in stack.
5175 (org-export-add-to-stack (get-buffer ,proc-buffer) nil ,process)
5176 ;; Set-up sentinel in order to catch results.
5177 (set-process-sentinel
5178 ,process
5179 (let ((handler ',fun))
5180 `(lambda (p status)
5181 (let ((proc-buffer (process-buffer p)))
5182 (when (eq (process-status p) 'exit)
5183 (unwind-protect
5184 (if (zerop (process-exit-status p))
5185 (unwind-protect
5186 (let ((results
5187 (with-current-buffer proc-buffer
5188 (goto-char (point-max))
5189 (backward-sexp)
5190 (read (current-buffer)))))
5191 (funcall ,handler results))
5192 (unless org-export-async-debug
5193 (and (get-buffer proc-buffer)
5194 (kill-buffer proc-buffer))))
5195 (org-export-add-to-stack proc-buffer nil p)
5196 (ding)
5197 (message "Process '%s' exited abnormally" p))
5198 (unless org-export-async-debug
5199 (delete-file ,,temp-file)))))))))))))
5201 (defun org-export-add-to-stack (source backend &optional process)
5202 "Add a new result to export stack if not present already.
5204 SOURCE is a buffer or a file name containing export results.
5205 BACKEND is a symbol representing export back-end used to generate
5208 Entries already pointing to SOURCE and unavailable entries are
5209 removed beforehand. Return the new stack."
5210 (setq org-export-stack-contents
5211 (cons (list source backend (or process (current-time)))
5212 (org-export-stack-remove source))))
5214 (defun org-export-stack ()
5215 "Menu for asynchronous export results and running processes."
5216 (interactive)
5217 (let ((buffer (get-buffer-create "*Org Export Stack*")))
5218 (set-buffer buffer)
5219 (when (zerop (buffer-size)) (org-export-stack-mode))
5220 (org-export-stack-refresh)
5221 (pop-to-buffer buffer))
5222 (message "Type \"q\" to quit, \"?\" for help"))
5224 (defun org-export--stack-source-at-point ()
5225 "Return source from export results at point in stack."
5226 (let ((source (car (nth (1- (org-current-line)) org-export-stack-contents))))
5227 (if (not source) (error "Source unavailable, please refresh buffer")
5228 (let ((source-name (if (stringp source) source (buffer-name source))))
5229 (if (save-excursion
5230 (beginning-of-line)
5231 (looking-at (concat ".* +" (regexp-quote source-name) "$")))
5232 source
5233 ;; SOURCE is not consistent with current line. The stack
5234 ;; view is outdated.
5235 (error "Source unavailable; type `g' to update buffer"))))))
5237 (defun org-export-stack-clear ()
5238 "Remove all entries from export stack."
5239 (interactive)
5240 (setq org-export-stack-contents nil))
5242 (defun org-export-stack-refresh (&rest dummy)
5243 "Refresh the asynchronous export stack.
5244 DUMMY is ignored. Unavailable sources are removed from the list.
5245 Return the new stack."
5246 (let ((inhibit-read-only t))
5247 (org-preserve-lc
5248 (erase-buffer)
5249 (insert (concat
5250 (let ((counter 0))
5251 (mapconcat
5252 (lambda (entry)
5253 (let ((proc-p (processp (nth 2 entry))))
5254 (concat
5255 ;; Back-end.
5256 (format " %-12s " (or (nth 1 entry) ""))
5257 ;; Age.
5258 (let ((data (nth 2 entry)))
5259 (if proc-p (format " %6s " (process-status data))
5260 ;; Compute age of the results.
5261 (org-format-seconds
5262 "%4h:%.2m "
5263 (float-time (time-since data)))))
5264 ;; Source.
5265 (format " %s"
5266 (let ((source (car entry)))
5267 (if (stringp source) source
5268 (buffer-name source)))))))
5269 ;; Clear stack from exited processes, dead buffers or
5270 ;; non-existent files.
5271 (setq org-export-stack-contents
5272 (org-remove-if-not
5273 (lambda (el)
5274 (if (processp (nth 2 el))
5275 (buffer-live-p (process-buffer (nth 2 el)))
5276 (let ((source (car el)))
5277 (if (bufferp source) (buffer-live-p source)
5278 (file-exists-p source)))))
5279 org-export-stack-contents)) "\n")))))))
5281 (defun org-export-stack-remove (&optional source)
5282 "Remove export results at point from stack.
5283 If optional argument SOURCE is non-nil, remove it instead."
5284 (interactive)
5285 (let ((source (or source (org-export--stack-source-at-point))))
5286 (setq org-export-stack-contents
5287 (org-remove-if (lambda (el) (equal (car el) source))
5288 org-export-stack-contents))))
5290 (defun org-export-stack-view (&optional in-emacs)
5291 "View export results at point in stack.
5292 With an optional prefix argument IN-EMACS, force viewing files
5293 within Emacs."
5294 (interactive "P")
5295 (let ((source (org-export--stack-source-at-point)))
5296 (cond ((processp source)
5297 (org-switch-to-buffer-other-window (process-buffer source)))
5298 ((bufferp source) (org-switch-to-buffer-other-window source))
5299 (t (org-open-file source in-emacs)))))
5301 (defconst org-export-stack-mode-map
5302 (let ((km (make-sparse-keymap)))
5303 (define-key km " " 'next-line)
5304 (define-key km "n" 'next-line)
5305 (define-key km "\C-n" 'next-line)
5306 (define-key km [down] 'next-line)
5307 (define-key km "p" 'previous-line)
5308 (define-key km "\C-p" 'previous-line)
5309 (define-key km "\C-?" 'previous-line)
5310 (define-key km [up] 'previous-line)
5311 (define-key km "C" 'org-export-stack-clear)
5312 (define-key km "v" 'org-export-stack-view)
5313 (define-key km (kbd "RET") 'org-export-stack-view)
5314 (define-key km "d" 'org-export-stack-remove)
5316 "Keymap for Org Export Stack.")
5318 (define-derived-mode org-export-stack-mode special-mode "Org-Stack"
5319 "Mode for displaying asynchronous export stack.
5321 Type \\[org-export-stack] to visualize the asynchronous export
5322 stack.
5324 In an Org Export Stack buffer, use \\<org-export-stack-mode-map>\\[org-export-stack-view] to view export output
5325 on current line, \\[org-export-stack-remove] to remove it from the stack and \\[org-export-stack-clear] to clear
5326 stack completely.
5328 Removing entries in an Org Export Stack buffer doesn't affect
5329 files or buffers, only the display.
5331 \\{org-export-stack-mode-map}"
5332 (abbrev-mode 0)
5333 (auto-fill-mode 0)
5334 (setq buffer-read-only t
5335 buffer-undo-list t
5336 truncate-lines t
5337 header-line-format
5338 '(:eval
5339 (format " %-12s | %6s | %s" "Back-End" "Age" "Source")))
5340 (add-hook 'post-command-hook 'org-export-stack-refresh nil t)
5341 (set (make-local-variable 'revert-buffer-function)
5342 'org-export-stack-refresh))
5346 ;;; The Dispatcher
5348 ;; `org-export-dispatch' is the standard interactive way to start an
5349 ;; export process. It uses `org-export--dispatch-ui' as a subroutine
5350 ;; for its interface, which, in turn, delegates response to key
5351 ;; pressed to `org-export--dispatch-action'.
5353 ;;;###autoload
5354 (defun org-export-dispatch (&optional arg)
5355 "Export dispatcher for Org mode.
5357 It provides an access to common export related tasks in a buffer.
5358 Its interface comes in two flavours: standard and expert.
5360 While both share the same set of bindings, only the former
5361 displays the valid keys associations in a dedicated buffer.
5362 Scrolling (resp. line-wise motion) in this buffer is done with
5363 SPC and DEL (resp. C-n and C-p) keys.
5365 Set variable `org-export-dispatch-use-expert-ui' to switch to one
5366 flavour or the other.
5368 When ARG is \\[universal-argument], repeat the last export action, with the same set
5369 of options used back then, on the current buffer.
5371 When ARG is \\[universal-argument] \\[universal-argument], display the asynchronous export stack."
5372 (interactive "P")
5373 (let* ((input
5374 (cond ((equal arg '(16)) '(stack))
5375 ((and arg org-export-dispatch-last-action))
5376 (t (save-window-excursion
5377 (unwind-protect
5378 (progn
5379 ;; Remember where we are
5380 (move-marker org-export-dispatch-last-position
5381 (point)
5382 (org-base-buffer (current-buffer)))
5383 ;; Get and store an export command
5384 (setq org-export-dispatch-last-action
5385 (org-export--dispatch-ui
5386 (list org-export-initial-scope
5387 (and org-export-in-background 'async))
5389 org-export-dispatch-use-expert-ui)))
5390 (and (get-buffer "*Org Export Dispatcher*")
5391 (kill-buffer "*Org Export Dispatcher*")))))))
5392 (action (car input))
5393 (optns (cdr input)))
5394 (unless (memq 'subtree optns)
5395 (move-marker org-export-dispatch-last-position nil))
5396 (case action
5397 ;; First handle special hard-coded actions.
5398 (stack (org-export-stack))
5399 (publish-current-file
5400 (org-publish-current-file (memq 'force optns) (memq 'async optns)))
5401 (publish-current-project
5402 (org-publish-current-project (memq 'force optns) (memq 'async optns)))
5403 (publish-choose-project
5404 (org-publish (assoc (org-icompleting-read
5405 "Publish project: "
5406 org-publish-project-alist nil t)
5407 org-publish-project-alist)
5408 (memq 'force optns)
5409 (memq 'async optns)))
5410 (publish-all (org-publish-all (memq 'force optns) (memq 'async optns)))
5411 (otherwise
5412 (save-excursion
5413 (when arg
5414 ;; Repeating command, maybe move cursor
5415 ;; to restore subtree context
5416 (if (eq (marker-buffer org-export-dispatch-last-position)
5417 (org-base-buffer (current-buffer)))
5418 (goto-char org-export-dispatch-last-position)
5419 ;; We are in a differnet buffer, forget position
5420 (move-marker org-export-dispatch-last-position nil)))
5421 (funcall action
5422 ;; Return a symbol instead of a list to ease
5423 ;; asynchronous export macro use.
5424 (and (memq 'async optns) t)
5425 (and (memq 'subtree optns) t)
5426 (and (memq 'visible optns) t)
5427 (and (memq 'body optns) t)))))))
5429 (defun org-export--dispatch-ui (options first-key expertp)
5430 "Handle interface for `org-export-dispatch'.
5432 OPTIONS is a list containing current interactive options set for
5433 export. It can contain any of the following symbols:
5434 `body' toggles a body-only export
5435 `subtree' restricts export to current subtree
5436 `visible' restricts export to visible part of buffer.
5437 `force' force publishing files.
5438 `async' use asynchronous export process
5440 FIRST-KEY is the key pressed to select the first level menu. It
5441 is nil when this menu hasn't been selected yet.
5443 EXPERTP, when non-nil, triggers expert UI. In that case, no help
5444 buffer is provided, but indications about currently active
5445 options are given in the prompt. Moreover, \[?] allows to switch
5446 back to standard interface."
5447 (let* ((fontify-key
5448 (lambda (key &optional access-key)
5449 ;; Fontify KEY string. Optional argument ACCESS-KEY, when
5450 ;; non-nil is the required first-level key to activate
5451 ;; KEY. When its value is t, activate KEY independently
5452 ;; on the first key, if any. A nil value means KEY will
5453 ;; only be activated at first level.
5454 (if (or (eq access-key t) (eq access-key first-key))
5455 (org-propertize key 'face 'org-warning)
5456 key)))
5457 (fontify-value
5458 (lambda (value)
5459 ;; Fontify VALUE string.
5460 (org-propertize value 'face 'font-lock-variable-name-face)))
5461 ;; Prepare menu entries by extracting them from
5462 ;; `org-export-registered-backends', and sorting them by
5463 ;; access key and by ordinal, if any.
5464 (backends
5465 (sort
5466 (sort
5467 (delq nil
5468 (mapcar
5469 (lambda (b)
5470 (let ((name (car b)))
5471 (catch 'ignored
5472 ;; Ignore any back-end belonging to
5473 ;; `org-export-invisible-backends' or derived
5474 ;; from one of them.
5475 (dolist (ignored org-export-invisible-backends)
5476 (when (org-export-derived-backend-p name ignored)
5477 (throw 'ignored nil)))
5478 (org-export-backend-menu name))))
5479 org-export-registered-backends))
5480 (lambda (a b)
5481 (let ((key-a (nth 1 a))
5482 (key-b (nth 1 b)))
5483 (cond ((and (numberp key-a) (numberp key-b))
5484 (< key-a key-b))
5485 ((numberp key-b) t)))))
5486 (lambda (a b) (< (car a) (car b)))))
5487 ;; Compute a list of allowed keys based on the first key
5488 ;; pressed, if any. Some keys (?^B, ?^V, ?^S, ?^F, ?^A
5489 ;; and ?q) are always available.
5490 (allowed-keys
5491 (nconc (list 2 22 19 6 1)
5492 (if (not first-key) (org-uniquify (mapcar 'car backends))
5493 (let (sub-menu)
5494 (dolist (backend backends (sort (mapcar 'car sub-menu) '<))
5495 (when (eq (car backend) first-key)
5496 (setq sub-menu (append (nth 2 backend) sub-menu))))))
5497 (cond ((eq first-key ?P) (list ?f ?p ?x ?a))
5498 ((not first-key) (list ?P)))
5499 (list ?&)
5500 (when expertp (list ??))
5501 (list ?q)))
5502 ;; Build the help menu for standard UI.
5503 (help
5504 (unless expertp
5505 (concat
5506 ;; Options are hard-coded.
5507 (format "Options
5508 [%s] Body only: %s [%s] Visible only: %s
5509 [%s] Export scope: %s [%s] Force publishing: %s
5510 [%s] Async export: %s\n"
5511 (funcall fontify-key "C-b" t)
5512 (funcall fontify-value
5513 (if (memq 'body options) "On " "Off"))
5514 (funcall fontify-key "C-v" t)
5515 (funcall fontify-value
5516 (if (memq 'visible options) "On " "Off"))
5517 (funcall fontify-key "C-s" t)
5518 (funcall fontify-value
5519 (if (memq 'subtree options) "Subtree" "Buffer "))
5520 (funcall fontify-key "C-f" t)
5521 (funcall fontify-value
5522 (if (memq 'force options) "On " "Off"))
5523 (funcall fontify-key "C-a" t)
5524 (funcall fontify-value
5525 (if (memq 'async options) "On " "Off")))
5526 ;; Display registered back-end entries. When a key
5527 ;; appears for the second time, do not create another
5528 ;; entry, but append its sub-menu to existing menu.
5529 (let (last-key)
5530 (mapconcat
5531 (lambda (entry)
5532 (let ((top-key (car entry)))
5533 (concat
5534 (unless (eq top-key last-key)
5535 (setq last-key top-key)
5536 (format "\n[%s] %s\n"
5537 (funcall fontify-key (char-to-string top-key))
5538 (nth 1 entry)))
5539 (let ((sub-menu (nth 2 entry)))
5540 (unless (functionp sub-menu)
5541 ;; Split sub-menu into two columns.
5542 (let ((index -1))
5543 (concat
5544 (mapconcat
5545 (lambda (sub-entry)
5546 (incf index)
5547 (format
5548 (if (zerop (mod index 2)) " [%s] %-26s"
5549 "[%s] %s\n")
5550 (funcall fontify-key
5551 (char-to-string (car sub-entry))
5552 top-key)
5553 (nth 1 sub-entry)))
5554 sub-menu "")
5555 (when (zerop (mod index 2)) "\n"))))))))
5556 backends ""))
5557 ;; Publishing menu is hard-coded.
5558 (format "\n[%s] Publish
5559 [%s] Current file [%s] Current project
5560 [%s] Choose project [%s] All projects\n\n"
5561 (funcall fontify-key "P")
5562 (funcall fontify-key "f" ?P)
5563 (funcall fontify-key "p" ?P)
5564 (funcall fontify-key "x" ?P)
5565 (funcall fontify-key "a" ?P))
5566 (format "\[%s] Export stack\n" (funcall fontify-key "&" t))
5567 (format "\[%s] %s"
5568 (funcall fontify-key "q" t)
5569 (if first-key "Main menu" "Exit")))))
5570 ;; Build prompts for both standard and expert UI.
5571 (standard-prompt (unless expertp "Export command: "))
5572 (expert-prompt
5573 (when expertp
5574 (format
5575 "Export command (C-%s%s%s%s%s) [%s]: "
5576 (if (memq 'body options) (funcall fontify-key "b" t) "b")
5577 (if (memq 'visible options) (funcall fontify-key "v" t) "v")
5578 (if (memq 'subtree options) (funcall fontify-key "s" t) "s")
5579 (if (memq 'force options) (funcall fontify-key "f" t) "f")
5580 (if (memq 'async options) (funcall fontify-key "a" t) "a")
5581 (mapconcat (lambda (k)
5582 ;; Strip control characters.
5583 (unless (< k 27) (char-to-string k)))
5584 allowed-keys "")))))
5585 ;; With expert UI, just read key with a fancy prompt. In standard
5586 ;; UI, display an intrusive help buffer.
5587 (if expertp
5588 (org-export--dispatch-action
5589 expert-prompt allowed-keys backends options first-key expertp)
5590 ;; At first call, create frame layout in order to display menu.
5591 (unless (get-buffer "*Org Export Dispatcher*")
5592 (delete-other-windows)
5593 (org-switch-to-buffer-other-window
5594 (get-buffer-create "*Org Export Dispatcher*"))
5595 (setq cursor-type nil
5596 header-line-format "Use SPC, DEL, C-n or C-p to navigate.")
5597 ;; Make sure that invisible cursor will not highlight square
5598 ;; brackets.
5599 (set-syntax-table (copy-syntax-table))
5600 (modify-syntax-entry ?\[ "w"))
5601 ;; At this point, the buffer containing the menu exists and is
5602 ;; visible in the current window. So, refresh it.
5603 (with-current-buffer "*Org Export Dispatcher*"
5604 ;; Refresh help. Maintain display continuity by re-visiting
5605 ;; previous window position.
5606 (let ((pos (window-start)))
5607 (erase-buffer)
5608 (insert help)
5609 (set-window-start nil pos)))
5610 (org-fit-window-to-buffer)
5611 (org-export--dispatch-action
5612 standard-prompt allowed-keys backends options first-key expertp))))
5614 (defun org-export--dispatch-action
5615 (prompt allowed-keys backends options first-key expertp)
5616 "Read a character from command input and act accordingly.
5618 PROMPT is the displayed prompt, as a string. ALLOWED-KEYS is
5619 a list of characters available at a given step in the process.
5620 BACKENDS is a list of menu entries. OPTIONS, FIRST-KEY and
5621 EXPERTP are the same as defined in `org-export--dispatch-ui',
5622 which see.
5624 Toggle export options when required. Otherwise, return value is
5625 a list with action as CAR and a list of interactive export
5626 options as CDR."
5627 (let (key)
5628 ;; Scrolling: when in non-expert mode, act on motion keys (C-n,
5629 ;; C-p, SPC, DEL).
5630 (while (and (setq key (read-char-exclusive prompt))
5631 (not expertp)
5632 (memq key '(14 16 ?\s ?\d)))
5633 (case key
5634 (14 (if (not (pos-visible-in-window-p (point-max)))
5635 (ignore-errors (scroll-up-line))
5636 (message "End of buffer")
5637 (sit-for 1)))
5638 (16 (if (not (pos-visible-in-window-p (point-min)))
5639 (ignore-errors (scroll-down-line))
5640 (message "Beginning of buffer")
5641 (sit-for 1)))
5642 (?\s (if (not (pos-visible-in-window-p (point-max)))
5643 (scroll-up nil)
5644 (message "End of buffer")
5645 (sit-for 1)))
5646 (?\d (if (not (pos-visible-in-window-p (point-min)))
5647 (scroll-down nil)
5648 (message "Beginning of buffer")
5649 (sit-for 1)))))
5650 (cond
5651 ;; Ignore undefined associations.
5652 ((not (memq key allowed-keys))
5653 (ding)
5654 (unless expertp (message "Invalid key") (sit-for 1))
5655 (org-export--dispatch-ui options first-key expertp))
5656 ;; q key at first level aborts export. At second
5657 ;; level, cancel first key instead.
5658 ((eq key ?q) (if (not first-key) (error "Export aborted")
5659 (org-export--dispatch-ui options nil expertp)))
5660 ;; Help key: Switch back to standard interface if
5661 ;; expert UI was active.
5662 ((eq key ??) (org-export--dispatch-ui options first-key nil))
5663 ;; Switch to asynchronous export stack.
5664 ((eq key ?&) '(stack))
5665 ;; Toggle export options
5666 ;; C-b (2) C-v (22) C-s (19) C-f (6) C-a (1)
5667 ((memq key '(2 22 19 6 1))
5668 (org-export--dispatch-ui
5669 (let ((option (case key (2 'body) (22 'visible) (19 'subtree)
5670 (6 'force) (1 'async))))
5671 (if (memq option options) (remq option options)
5672 (cons option options)))
5673 first-key expertp))
5674 ;; Action selected: Send key and options back to
5675 ;; `org-export-dispatch'.
5676 ((or first-key (functionp (nth 2 (assq key backends))))
5677 (cons (cond
5678 ((not first-key) (nth 2 (assq key backends)))
5679 ;; Publishing actions are hard-coded. Send a special
5680 ;; signal to `org-export-dispatch'.
5681 ((eq first-key ?P)
5682 (case key
5683 (?f 'publish-current-file)
5684 (?p 'publish-current-project)
5685 (?x 'publish-choose-project)
5686 (?a 'publish-all)))
5687 ;; Return first action associated to FIRST-KEY + KEY
5688 ;; path. Indeed, derived backends can share the same
5689 ;; FIRST-KEY.
5690 (t (catch 'found
5691 (mapc (lambda (backend)
5692 (let ((match (assq key (nth 2 backend))))
5693 (when match (throw 'found (nth 2 match)))))
5694 (member (assq first-key backends) backends)))))
5695 options))
5696 ;; Otherwise, enter sub-menu.
5697 (t (org-export--dispatch-ui options key expertp)))))
5699 ;;; Miscellaneous
5701 (defun org-export--copy-to-kill-ring-p ()
5702 "Should we copy the export buffer to the kill ring?
5703 See also `org-export-copy-to-kill-ring'."
5704 (if (eq org-export-copy-to-kill-ring 'if-interactive)
5705 (not (or executing-kbd-macro noninteractive))
5706 (eq org-export-copy-to-kill-ring t)))
5708 (provide 'ox)
5710 ;; Local variables:
5711 ;; generated-autoload-file: "org-loaddefs.el"
5712 ;; End:
5714 ;;; ox.el ends here