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