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