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