org-export: Fix option item for drawers
[org-mode.git] / contrib / lisp / org-export.el
blob92171f8b9df073b45c1c58790bb0b6d27275f95a
1 ;;; org-export.el --- Generic Export Engine For Org
3 ;; Copyright (C) 2012 Free Software Foundation, Inc.
5 ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
6 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; This program 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 ;; This program 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 this program. 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 export options or
32 ;; contextual data, all in a single place. The exhaustive list of
33 ;; 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.
46 ;; The core function is `org-export-as'. It returns the transcoded
47 ;; buffer as a string.
49 ;; In order to derive an exporter out of this generic implementation,
50 ;; one can define a transcode function for each element or object.
51 ;; Such function should return a string for the corresponding element,
52 ;; without any trailing space, or nil. It must accept three
53 ;; arguments:
54 ;; 1. the element or object itself,
55 ;; 2. its contents, or nil when it isn't recursive,
56 ;; 3. the property list used as a communication channel.
58 ;; If no such function is found, that element or object type will
59 ;; simply be ignored, along with any separating blank line. The same
60 ;; will happen if the function returns the nil value. If that
61 ;; function returns the empty string, the type will be ignored, but
62 ;; the blank lines will be kept.
64 ;; Contents, when not nil, are stripped from any global indentation
65 ;; (although the relative one is preserved). They also always end
66 ;; with a single newline character.
68 ;; These functions must follow a strict naming convention:
69 ;; `org-BACKEND-TYPE' where, obviously, BACKEND is the name of the
70 ;; export back-end and TYPE the type of the element or object handled.
72 ;; Moreover, two additional functions can be defined. On the one
73 ;; hand, `org-BACKEND-template' returns the final transcoded string,
74 ;; and can be used to add a preamble and a postamble to document's
75 ;; body. It must accept two arguments: the transcoded string and the
76 ;; property list containing export options. On the other hand,
77 ;; `org-BACKEND-plain-text', when defined, is to be called on every
78 ;; text not recognized as an element or an object. It must accept two
79 ;; arguments: the text string and the information channel.
81 ;; Any back-end can define its own variables. Among them, those
82 ;; customizables should belong to the `org-export-BACKEND' group.
83 ;; Also, a special variable, `org-BACKEND-option-alist', allows to
84 ;; define buffer keywords and "#+options:" items specific to that
85 ;; back-end. See `org-export-option-alist' for supported defaults and
86 ;; syntax.
88 ;; Tools for common tasks across back-ends are implemented in the
89 ;; penultimate part of this file. A dispatcher for standard back-ends
90 ;; is provided in the last one.
92 ;;; Code:
93 (eval-when-compile (require 'cl))
94 (require 'org-element)
97 ;;; Internal Variables
99 ;; Among internal variables, the most important is
100 ;; `org-export-option-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-option-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 "EXPORT_EXCLUDE_TAGS" nil org-export-exclude-tags split)
113 (:filter-babel-call nil nil org-export-filter-babel-call-functions)
114 (:filter-center-block nil nil org-export-filter-center-block-functions)
115 (:filter-comment nil nil org-export-filter-comment-functions)
116 (:filter-comment-block nil nil org-export-filter-comment-block-functions)
117 (:filter-drawer nil nil org-export-filter-drawer-functions)
118 (:filter-dynamic-block nil nil org-export-filter-dynamic-block-functions)
119 (:filter-emphasis nil nil org-export-filter-emphasis-functions)
120 (:filter-entity nil nil org-export-filter-entity-functions)
121 (:filter-example-block nil nil org-export-filter-example-block-functions)
122 (:filter-export-block nil nil org-export-filter-export-block-functions)
123 (:filter-export-snippet nil nil org-export-filter-export-snippet-functions)
124 (:filter-final-output nil nil org-export-filter-final-output-functions)
125 (:filter-fixed-width nil nil org-export-filter-fixed-width-functions)
126 (:filter-footnote-definition nil nil org-export-filter-footnote-definition-functions)
127 (:filter-footnote-reference nil nil org-export-filter-footnote-reference-functions)
128 (:filter-headline nil nil org-export-filter-headline-functions)
129 (:filter-horizontal-rule nil nil org-export-filter-horizontal-rule-functions)
130 (:filter-inline-babel-call nil nil org-export-filter-inline-babel-call-functions)
131 (:filter-inline-src-block nil nil org-export-filter-inline-src-block-functions)
132 (:filter-inlinetask nil nil org-export-filter-inlinetask-functions)
133 (:filter-item nil nil org-export-filter-item-functions)
134 (:filter-keyword nil nil org-export-filter-keyword-functions)
135 (:filter-latex-environment nil nil org-export-filter-latex-environment-functions)
136 (:filter-latex-fragment nil nil org-export-filter-latex-fragment-functions)
137 (:filter-line-break nil nil org-export-filter-line-break-functions)
138 (:filter-link nil nil org-export-filter-link-functions)
139 (:filter-macro nil nil org-export-filter-macro-functions)
140 (:filter-paragraph nil nil org-export-filter-paragraph-functions)
141 (:filter-parse-tree nil nil org-export-filter-parse-tree-functions)
142 (:filter-plain-list nil nil org-export-filter-plain-list-functions)
143 (:filter-plain-text nil nil org-export-filter-plain-text-functions)
144 (:filter-property-drawer nil nil org-export-filter-property-drawer-functions)
145 (:filter-quote-block nil nil org-export-filter-quote-block-functions)
146 (:filter-quote-section nil nil org-export-filter-quote-section-functions)
147 (:filter-radio-target nil nil org-export-filter-radio-target-functions)
148 (:filter-section nil nil org-export-filter-section-functions)
149 (:filter-special-block nil nil org-export-filter-special-block-functions)
150 (:filter-src-block nil nil org-export-filter-src-block-functions)
151 (:filter-statistics-cookie nil nil org-export-filter-statistics-cookie-functions)
152 (:filter-subscript nil nil org-export-filter-subscript-functions)
153 (:filter-superscript nil nil org-export-filter-superscript-functions)
154 (:filter-table nil nil org-export-filter-table-functions)
155 (:filter-target nil nil org-export-filter-target-functions)
156 (:filter-time-stamp nil nil org-export-filter-time-stamp-functions)
157 (:filter-verbatim nil nil org-export-filter-verbatim-functions)
158 (:filter-verse-block nil nil org-export-filter-verse-block-functions)
159 (:headline-levels nil "H" org-export-headline-levels)
160 (:keywords "KEYWORDS" nil nil space)
161 (:language "LANGUAGE" nil org-export-default-language t)
162 (:preserve-breaks nil "\\n" org-export-preserve-breaks)
163 (:section-numbers nil "num" org-export-with-section-numbers)
164 (:select-tags "EXPORT_SELECT_TAGS" nil org-export-select-tags split)
165 (:time-stamp-file nil "timestamp" org-export-time-stamp-file)
166 (:title "TITLE" nil nil space)
167 (:with-archived-trees nil "arch" org-export-with-archived-trees)
168 (:with-author nil "author" org-export-with-author)
169 (:with-creator nil "creator" org-export-with-creator)
170 (:with-drawers nil "d" org-export-with-drawers)
171 (:with-email nil "email" org-export-with-email)
172 (:with-emphasize nil "*" org-export-with-emphasize)
173 (:with-entities nil "e" org-export-with-entities)
174 (:with-fixed-width nil ":" org-export-with-fixed-width)
175 (:with-footnotes nil "f" org-export-with-footnotes)
176 (:with-priority nil "pri" org-export-with-priority)
177 (:with-special-strings nil "-" org-export-with-special-strings)
178 (:with-sub-superscript nil "^" org-export-with-sub-superscripts)
179 (:with-toc nil "toc" org-export-with-toc)
180 (:with-tables nil "|" org-export-with-tables)
181 (:with-tags nil "tags" org-export-with-tags)
182 (:with-tasks nil "tasks" org-export-with-tasks)
183 (:with-timestamps nil "<" org-export-with-timestamps)
184 (:with-todo-keywords nil "todo" org-export-with-todo-keywords))
185 "Alist between export properties and ways to set them.
187 The car of the alist is the property name, and the cdr is a list
188 like \(KEYWORD OPTION DEFAULT BEHAVIOUR\) where:
190 KEYWORD is a string representing a buffer keyword, or nil.
191 OPTION is a string that could be found in an #+OPTIONS: line.
192 DEFAULT is the default value for the property.
193 BEHAVIOUR determine how Org should handle multiple keywords for
194 the same property. It is a symbol among:
195 nil Keep old value and discard the new one.
196 t Replace old value with the new one.
197 `space' Concatenate the values, separating them with a space.
198 `newline' Concatenate the values, separating them with
199 a newline.
200 `split' Split values at white spaces, and cons them to the
201 previous list.
203 KEYWORD and OPTION have precedence over DEFAULT.
205 All these properties should be back-end agnostic. For back-end
206 specific properties, define a similar variable named
207 `org-BACKEND-option-alist', replacing BACKEND with the name of
208 the appropriate back-end. You can also redefine properties
209 there, as they have precedence over these.")
211 (defconst org-export-special-keywords
212 '("SETUP_FILE" "OPTIONS" "MACRO")
213 "List of in-buffer keywords that require special treatment.
214 These keywords are not directly associated to a property. The
215 way they are handled must be hard-coded into
216 `org-export-get-inbuffer-options' function.")
220 ;;; User-configurable Variables
222 ;; Configuration for the masses.
224 ;; They should never be evaled directly, as their value is to be
225 ;; stored in a property list (cf. `org-export-option-alist').
227 (defgroup org-export nil
228 "Options for exporting Org mode files."
229 :tag "Org Export"
230 :group 'org)
232 (defgroup org-export-general nil
233 "General options for export engine."
234 :tag "Org Export General"
235 :group 'org-export)
237 (defcustom org-export-with-archived-trees 'headline
238 "Whether sub-trees with the ARCHIVE tag should be exported.
240 This can have three different values:
241 nil Do not export, pretend this tree is not present.
242 t Do export the entire tree.
243 `headline' Only export the headline, but skip the tree below it.
245 This option can also be set with the #+OPTIONS line,
246 e.g. \"arch:nil\"."
247 :group 'org-export-general
248 :type '(choice
249 (const :tag "Not at all" nil)
250 (const :tag "Headline only" 'headline)
251 (const :tag "Entirely" t)))
253 (defcustom org-export-with-author t
254 "Non-nil means insert author name into the exported file.
255 This option can also be set with the #+OPTIONS line,
256 e.g. \"author:nil\"."
257 :group 'org-export-general
258 :type 'boolean)
260 (defcustom org-export-with-creator 'comment
261 "Non-nil means the postamble should contain a creator sentence.
263 The sentence can be set in `org-export-creator-string' and
264 defaults to \"Generated by Org mode XX in Emacs XXX.\".
266 If the value is `comment' insert it as a comment."
267 :group 'org-export-general
268 :type '(choice
269 (const :tag "No creator sentence" nil)
270 (const :tag "Sentence as a comment" 'comment)
271 (const :tag "Insert the sentence" t)))
273 (defcustom org-export-creator-string
274 (format "Generated by Org mode %s in Emacs %s." org-version emacs-version)
275 "String to insert at the end of the generated document."
276 :group 'org-export-general
277 :type '(string :tag "Creator string"))
279 (defcustom org-export-with-drawers nil
280 "Non-nil means export with drawers like the property drawer.
281 When t, all drawers are exported. This may also be a list of
282 drawer names to export."
283 :group 'org-export-general
284 :type '(choice
285 (const :tag "All drawers" t)
286 (const :tag "None" nil)
287 (repeat :tag "Selected drawers"
288 (string :tag "Drawer name"))))
290 (defcustom org-export-with-email nil
291 "Non-nil means insert author email into the exported file.
292 This option can also be set with the #+OPTIONS line,
293 e.g. \"email:t\"."
294 :group 'org-export-general
295 :type 'boolean)
297 (defcustom org-export-with-emphasize t
298 "Non-nil means interpret *word*, /word/, and _word_ as emphasized text.
300 If the export target supports emphasizing text, the word will be
301 typeset in bold, italic, or underlined, respectively. Not all
302 export backends support this.
304 This option can also be set with the #+OPTIONS line, e.g. \"*:nil\"."
305 :group 'org-export-general
306 :type 'boolean)
308 (defcustom org-export-exclude-tags '("noexport")
309 "Tags that exclude a tree from export.
310 All trees carrying any of these tags will be excluded from
311 export. This is without condition, so even subtrees inside that
312 carry one of the `org-export-select-tags' will be removed."
313 :group 'org-export-general
314 :type '(repeat (string :tag "Tag")))
316 (defcustom org-export-with-fixed-width t
317 "Non-nil means lines starting with \":\" will be in fixed width font.
319 This can be used to have pre-formatted text, fragments of code
320 etc. For example:
321 : ;; Some Lisp examples
322 : (while (defc cnt)
323 : (ding))
324 will be looking just like this in also HTML. See also the QUOTE
325 keyword. Not all export backends support this.
327 This option can also be set with the #+OPTIONS line, e.g. \"::nil\"."
328 :group 'org-export-translation
329 :type 'boolean)
331 (defcustom org-export-with-footnotes t
332 "Non-nil means Org footnotes should be exported.
333 This option can also be set with the #+OPTIONS line,
334 e.g. \"f:nil\"."
335 :group 'org-export-general
336 :type 'boolean)
338 (defcustom org-export-headline-levels 3
339 "The last level which is still exported as a headline.
341 Inferior levels will produce itemize lists when exported. Note
342 that a numeric prefix argument to an exporter function overrides
343 this setting.
345 This option can also be set with the #+OPTIONS line, e.g. \"H:2\"."
346 :group 'org-export-general
347 :type 'integer)
349 (defcustom org-export-default-language "en"
350 "The default language for export and clocktable translations, as a string.
351 This may have an association in
352 `org-clock-clocktable-language-setup'."
353 :group 'org-export-general
354 :type '(string :tag "Language"))
356 (defcustom org-export-preserve-breaks nil
357 "Non-nil means preserve all line breaks when exporting.
359 Normally, in HTML output paragraphs will be reformatted.
361 This option can also be set with the #+OPTIONS line,
362 e.g. \"\\n:t\"."
363 :group 'org-export-general
364 :type 'boolean)
366 (defcustom org-export-with-entities t
367 "Non-nil means interpret entities when exporting.
369 For example, HTML export converts \\alpha to &alpha; and \\AA to
370 &Aring;.
372 For a list of supported names, see the constant `org-entities'
373 and the user option `org-entities-user'.
375 This option can also be set with the #+OPTIONS line,
376 e.g. \"e:nil\"."
377 :group 'org-export-general
378 :type 'boolean)
380 (defcustom org-export-with-priority nil
381 "Non-nil means include priority cookies in export.
382 When nil, remove priority cookies for export."
383 :group 'org-export-general
384 :type 'boolean)
386 (defcustom org-export-with-section-numbers t
387 "Non-nil means add section numbers to headlines when exporting.
389 This option can also be set with the #+OPTIONS line,
390 e.g. \"num:t\"."
391 :group 'org-export-general
392 :type 'boolean)
394 (defcustom org-export-select-tags '("export")
395 "Tags that select a tree for export.
396 If any such tag is found in a buffer, all trees that do not carry
397 one of these tags will be deleted before export. Inside trees
398 that are selected like this, you can still deselect a subtree by
399 tagging it with one of the `org-export-exclude-tags'."
400 :group 'org-export-general
401 :type '(repeat (string :tag "Tag")))
403 (defcustom org-export-with-special-strings t
404 "Non-nil means interpret \"\-\", \"--\" and \"---\" for export.
406 When this option is turned on, these strings will be exported as:
408 Org HTML LaTeX
409 -----+----------+--------
410 \\- &shy; \\-
411 -- &ndash; --
412 --- &mdash; ---
413 ... &hellip; \ldots
415 This option can also be set with the #+OPTIONS line,
416 e.g. \"-:nil\"."
417 :group 'org-export-general
418 :type 'boolean)
420 (defcustom org-export-with-sub-superscripts t
421 "Non-nil means interpret \"_\" and \"^\" for export.
423 When this option is turned on, you can use TeX-like syntax for
424 sub- and superscripts. Several characters after \"_\" or \"^\"
425 will be considered as a single item - so grouping with {} is
426 normally not needed. For example, the following things will be
427 parsed as single sub- or superscripts.
429 10^24 or 10^tau several digits will be considered 1 item.
430 10^-12 or 10^-tau a leading sign with digits or a word
431 x^2-y^3 will be read as x^2 - y^3, because items are
432 terminated by almost any nonword/nondigit char.
433 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
435 Still, ambiguity is possible - so when in doubt use {} to enclose
436 the sub/superscript. If you set this variable to the symbol
437 `{}', the braces are *required* in order to trigger
438 interpretations as sub/superscript. This can be helpful in
439 documents that need \"_\" frequently in plain text.
441 This option can also be set with the #+OPTIONS line,
442 e.g. \"^:nil\"."
443 :group 'org-export-general
444 :type '(choice
445 (const :tag "Interpret them" t)
446 (const :tag "Curly brackets only" {})
447 (const :tag "Do not interpret them" nil)))
449 (defcustom org-export-with-toc t
450 "Non-nil means create a table of contents in exported files.
452 The TOC contains headlines with levels up
453 to`org-export-headline-levels'. When an integer, include levels
454 up to N in the toc, this may then be different from
455 `org-export-headline-levels', but it will not be allowed to be
456 larger than the number of headline levels. When nil, no table of
457 contents is made.
459 This option can also be set with the #+OPTIONS line,
460 e.g. \"toc:nil\" or \"toc:3\"."
461 :group 'org-export-general
462 :type '(choice
463 (const :tag "No Table of Contents" nil)
464 (const :tag "Full Table of Contents" t)
465 (integer :tag "TOC to level")))
467 (defcustom org-export-with-tables t
468 "If non-nil, lines starting with \"|\" define a table.
469 For example:
471 | Name | Address | Birthday |
472 |-------------+----------+-----------|
473 | Arthur Dent | England | 29.2.2100 |
475 This option can also be set with the #+OPTIONS line, e.g. \"|:nil\"."
476 :group 'org-export-general
477 :type 'boolean)
479 (defcustom org-export-with-tags t
480 "If nil, do not export tags, just remove them from headlines.
482 If this is the symbol `not-in-toc', tags will be removed from
483 table of contents entries, but still be shown in the headlines of
484 the document.
486 This option can also be set with the #+OPTIONS line,
487 e.g. \"tags:nil\"."
488 :group 'org-export-general
489 :type '(choice
490 (const :tag "Off" nil)
491 (const :tag "Not in TOC" not-in-toc)
492 (const :tag "On" t)))
494 (defcustom org-export-with-tasks t
495 "Non-nil means include TODO items for export.
496 This may have the following values:
497 t include tasks independent of state.
498 todo include only tasks that are not yet done.
499 done include only tasks that are already done.
500 nil remove all tasks before export
501 list of keywords keep only tasks with these keywords"
502 :group 'org-export-general
503 :type '(choice
504 (const :tag "All tasks" t)
505 (const :tag "No tasks" nil)
506 (const :tag "Not-done tasks" todo)
507 (const :tag "Only done tasks" done)
508 (repeat :tag "Specific TODO keywords"
509 (string :tag "Keyword"))))
511 (defcustom org-export-time-stamp-file t
512 "Non-nil means insert a time stamp into the exported file.
513 The time stamp shows when the file was created.
515 This option can also be set with the #+OPTIONS line,
516 e.g. \"timestamp:nil\"."
517 :group 'org-export-general
518 :type 'boolean)
520 (defcustom org-export-with-timestamps t
521 "If nil, do not export time stamps and associated keywords."
522 :group 'org-export-general
523 :type 'boolean)
525 (defcustom org-export-with-todo-keywords t
526 "Non-nil means include TODO keywords in export.
527 When nil, remove all these keywords from the export.")
529 (defcustom org-export-allow-BIND 'confirm
530 "Non-nil means allow #+BIND to define local variable values for export.
531 This is a potential security risk, which is why the user must
532 confirm the use of these lines."
533 :group 'org-export-general
534 :type '(choice
535 (const :tag "Never" nil)
536 (const :tag "Always" t)
537 (const :tag "Ask a confirmation for each file" confirm)))
539 (defcustom org-export-snippet-translation-alist nil
540 "Alist between export snippets back-ends and exporter back-ends.
542 This variable allows to provide shortcuts for export snippets.
544 For example, with a value of '\(\(\"h\" . \"html\"\)\), the HTML
545 back-end will recognize the contents of \"@h{<b>}\" as HTML code
546 while every other back-end will ignore it."
547 :group 'org-export-general
548 :type '(repeat
549 (cons
550 (string :tag "Shortcut")
551 (string :tag "Back-end"))))
553 (defcustom org-export-coding-system nil
554 "Coding system for the exported file."
555 :group 'org-export-general
556 :type 'coding-system)
558 (defcustom org-export-copy-to-kill-ring t
559 "Non-nil means exported stuff will also be pushed onto the kill ring."
560 :group 'org-export-general
561 :type 'boolean)
563 (defcustom org-export-initial-scope 'buffer
564 "The initial scope when exporting with `org-export-dispatch'.
565 This variable can be either set to `buffer' or `subtree'."
566 :group 'org-export-general
567 :type '(choice
568 (const :tag "Export current buffer" 'buffer)
569 (const :tag "Export current subtree" 'subtree)))
571 (defcustom org-export-show-temporary-export-buffer t
572 "Non-nil means show buffer after exporting to temp buffer.
573 When Org exports to a file, the buffer visiting that file is ever
574 shown, but remains buried. However, when exporting to a temporary
575 buffer, that buffer is popped up in a second window. When this variable
576 is nil, the buffer remains buried also in these cases."
577 :group 'org-export-general
578 :type 'boolean)
580 (defcustom org-export-dispatch-use-expert-ui nil
581 "Non-nil means using a non-intrusive `org-export-dispatch'.
582 In that case, no help buffer is displayed. Though, an indicator
583 for current export scope is added to the prompt \(i.e. \"b\" when
584 output is restricted to body only, \"s\" when it is restricted to
585 the current subtree and \"v\" when only visible elements are
586 considered for export\). Also, \[?] allows to switch back to
587 standard mode."
588 :group 'org-export-general
589 :type 'boolean)
593 ;;; The Communication Channel
595 ;; During export process, every function has access to a number of
596 ;; properties. They are of three types:
598 ;; 1. Export options are collected once at the very beginning of the
599 ;; process, out of the original buffer and environment. The task
600 ;; is handled by `org-export-collect-options' function.
602 ;; All export options are defined through the
603 ;; `org-export-option-alist' variable.
605 ;; 2. Tree properties are extracted directly from the parsed tree, by
606 ;; `org-export-collect-tree-properties' and depend on export
607 ;; options (whole trees may be filtered out of the export process).
609 ;; 3. Local options are updated during parsing, and their value
610 ;; depends on the level of recursion. For now, only `:genealogy'
611 ;; belongs to that category.
613 ;; Here is the full list of properties available during transcode
614 ;; process, with their category (option, tree or local), their
615 ;; value type and the function updating them, when appropriate.
617 ;; + `author' :: Author's name.
618 ;; - category :: option
619 ;; - type :: string
621 ;; + `back-end' :: Current back-end used for transcoding.
622 ;; - category :: tree
623 ;; - type :: symbol
625 ;; + `creator' :: String to write as creation information.
626 ;; - category :: option
627 ;; - type :: string
629 ;; + `date' :: String to use as date.
630 ;; - category :: option
631 ;; - type :: string
633 ;; + `description' :: Description text for the current data.
634 ;; - category :: option
635 ;; - type :: string
637 ;; + `email' :: Author's email.
638 ;; - category :: option
639 ;; - type :: string
641 ;; + `exclude-tags' :: Tags for exclusion of subtrees from export
642 ;; process.
643 ;; - category :: option
644 ;; - type :: list of strings
646 ;; + `footnote-definition-alist' :: Alist between footnote labels and
647 ;; their definition, as parsed data. Only non-inlined footnotes
648 ;; are represented in this alist. Also, every definition isn't
649 ;; guaranteed to be referenced in the parse tree. The purpose of
650 ;; this property is to preserve definitions from oblivion
651 ;; (i.e. when the parse tree comes from a part of the original
652 ;; buffer), it isn't meant for direct use in a back-end. To
653 ;; retrieve a definition relative to a reference, use
654 ;; `org-export-get-footnote-definition' instead.
655 ;; - category :: option
656 ;; - type :: alist (STRING . LIST)
658 ;; + `genealogy' :: Flat list of current object or element's parents
659 ;; from closest to farthest.
660 ;; - category :: local
661 ;; - type :: list of elements and objects
663 ;; + `headline-levels' :: Maximum level being exported as an
664 ;; headline. Comparison is done with the relative level of
665 ;; headlines in the parse tree, not necessarily with their
666 ;; actual level.
667 ;; - category :: option
668 ;; - type :: integer
670 ;; + `headline-offset' :: Difference between relative and real level
671 ;; of headlines in the parse tree. For example, a value of -1
672 ;; means a level 2 headline should be considered as level
673 ;; 1 (cf. `org-export-get-relative-level').
674 ;; - category :: tree
675 ;; - type :: integer
677 ;; + `headline-numbering' :: Alist between headlines' beginning
678 ;; position and their numbering, as a list of numbers
679 ;; (cf. `org-export-get-headline-number').
680 ;; - category :: tree
681 ;; - type :: alist (INTEGER . LIST)
683 ;; + `included-files' :: List of files, with full path, included in
684 ;; the current buffer, through the "#+include:" keyword. It is
685 ;; mainly used to verify that no infinite recursive inclusion
686 ;; happens.
687 ;; - category :: local
688 ;; - type :: list of strings
690 ;; + `keywords' :: List of keywords attached to data.
691 ;; - category :: option
692 ;; - type :: string
694 ;; + `language' :: Default language used for translations.
695 ;; - category :: option
696 ;; - type :: string
698 ;; + `parse-tree' :: Whole parse tree, available at any time during
699 ;; transcoding.
700 ;; - category :: global
701 ;; - type :: list (as returned by `org-element-parse-buffer')
703 ;; + `preserve-breaks' :: Non-nil means transcoding should preserve
704 ;; all line breaks.
705 ;; - category :: option
706 ;; - type :: symbol (nil, t)
708 ;; + `section-numbers' :: Non-nil means transcoding should add
709 ;; section numbers to headlines.
710 ;; - category :: option
711 ;; - type :: symbol (nil, t)
713 ;; + `select-tags' :: List of tags enforcing inclusion of sub-trees in
714 ;; transcoding. When such a tag is present,
715 ;; subtrees without it are de facto excluded from
716 ;; the process. See `use-select-tags'.
717 ;; - category :: option
718 ;; - type :: list of strings
720 ;; + `target-list' :: List of targets encountered in the parse tree.
721 ;; This is used to partly resolve "fuzzy" links
722 ;; (cf. `org-export-resolve-fuzzy-link').
723 ;; - category :: tree
724 ;; - type :: list of strings
726 ;; + `time-stamp-file' :: Non-nil means transcoding should insert
727 ;; a time stamp in the output.
728 ;; - category :: option
729 ;; - type :: symbol (nil, t)
731 ;; + `use-select-tags' :: When non-nil, a select tags has been found
732 ;; in the parse tree. Thus, any headline without one will be
733 ;; filtered out. See `select-tags'.
734 ;; - category :: tree
735 ;; - type :: interger or nil
737 ;; + `with-archived-trees' :: Non-nil when archived subtrees should
738 ;; also be transcoded. If it is set to the `headline' symbol,
739 ;; only the archived headline's name is retained.
740 ;; - category :: option
741 ;; - type :: symbol (nil, t, `headline')
743 ;; + `with-author' :: Non-nil means author's name should be included
744 ;; in the output.
745 ;; - category :: option
746 ;; - type :: symbol (nil, t)
748 ;; + `with-creator' :: Non-nild means a creation sentence should be
749 ;; inserted at the end of the transcoded string. If the value
750 ;; is `comment', it should be commented.
751 ;; - category :: option
752 ;; - type :: symbol (`comment', nil, t)
754 ;; + `with-drawers' :: Non-nil means drawers should be exported. If
755 ;; its value is a list of names, only drawers with such names
756 ;; will be transcoded.
757 ;; - category :: option
758 ;; - type :: symbol (nil, t) or list of strings
760 ;; + `with-email' :: Non-nil means output should contain author's
761 ;; email.
762 ;; - category :: option
763 ;; - type :: symbol (nil, t)
765 ;; + `with-emphasize' :: Non-nil means emphasized text should be
766 ;; interpreted.
767 ;; - category :: option
768 ;; - type :: symbol (nil, t)
770 ;; + `with-fixed-width' :: Non-nil if transcoder should interpret
771 ;; strings starting with a colon as a fixed-with (verbatim)
772 ;; area.
773 ;; - category :: option
774 ;; - type :: symbol (nil, t)
776 ;; + `with-footnotes' :: Non-nil if transcoder should interpret
777 ;; footnotes.
778 ;; - category :: option
779 ;; - type :: symbol (nil, t)
781 ;; + `with-priority' :: Non-nil means transcoding should include
782 ;; priority cookies.
783 ;; - category :: option
784 ;; - type :: symbol (nil, t)
786 ;; + `with-special-strings' :: Non-nil means transcoding should
787 ;; interpret special strings in plain text.
788 ;; - category :: option
789 ;; - type :: symbol (nil, t)
791 ;; + `with-sub-superscript' :: Non-nil means transcoding should
792 ;; interpret subscript and superscript. With a value of "{}",
793 ;; only interpret those using curly brackets.
794 ;; - category :: option
795 ;; - type :: symbol (nil, {}, t)
797 ;; + `with-tables' :: Non-nil means transcoding should interpret
798 ;; tables.
799 ;; - category :: option
800 ;; - type :: symbol (nil, t)
802 ;; + `with-tags' :: Non-nil means transcoding should keep tags in
803 ;; headlines. A `not-in-toc' value will remove them
804 ;; from the table of contents, if any, nonetheless.
805 ;; - category :: option
806 ;; - type :: symbol (nil, t, `not-in-toc')
808 ;; + `with-tasks' :: Non-nil means transcoding should include
809 ;; headlines with a TODO keyword. A `todo' value
810 ;; will only include headlines with a todo type
811 ;; keyword while a `done' value will do the
812 ;; contrary. If a list of strings is provided, only
813 ;; tasks with keywords belonging to that list will
814 ;; be kept.
815 ;; - category :: option
816 ;; - type :: symbol (t, todo, done, nil) or list of strings
818 ;; + `with-timestamps' :: Non-nil means transcoding should include
819 ;; time stamps and associated keywords. Otherwise, completely
820 ;; remove them.
821 ;; - category :: option
822 ;; - type :: symbol: (t, nil)
824 ;; + `with-toc' :: Non-nil means that a table of contents has to be
825 ;; added to the output. An integer value limits its
826 ;; depth.
827 ;; - category :: option
828 ;; - type :: symbol (nil, t or integer)
830 ;; + `with-todo-keywords' :: Non-nil means transcoding should
831 ;; include TODO keywords.
832 ;; - category :: option
833 ;; - type :: symbol (nil, t)
835 ;;;; Export Options
837 ;; Export options come from five sources, in increasing precedence
838 ;; order:
840 ;; - Global variables,
841 ;; - External options provided at export time,
842 ;; - Options keyword symbols,
843 ;; - Buffer keywords,
844 ;; - Subtree properties.
846 ;; The central internal function with regards to export options is
847 ;; `org-export-collect-options'. It updates global variables with
848 ;; "#+BIND:" keywords, then retrieve and prioritize properties from
849 ;; the different sources.
851 ;; The internal functions doing the retrieval are:
852 ;; `org-export-parse-option-keyword' ,
853 ;; `org-export-get-subtree-options' ,
854 ;; `org-export-get-inbuffer-options' and
855 ;; `org-export-get-global-options'.
857 ;; Some properties do not rely on the previous sources but still
858 ;; depend on the original buffer are taken care of in
859 ;; `org-export-initial-options'.
861 ;; Also, `org-export-confirm-letbind' and `org-export-install-letbind'
862 ;; take care of the part relative to "#+BIND:" keywords.
864 (defun org-export-collect-options (backend subtreep ext-plist)
865 "Collect export options from the current buffer.
867 BACKEND is a symbol specifying the back-end to use.
869 When SUBTREEP is non-nil, assume the export is done against the
870 current sub-tree.
872 EXT-PLIST is a property list with external parameters overriding
873 org-mode's default settings, but still inferior to file-local
874 settings."
875 ;; First install #+BIND variables.
876 (org-export-install-letbind-maybe)
877 ;; Get and prioritize export options...
878 (let ((options (org-combine-plists
879 ;; ... from global variables...
880 (org-export-get-global-options backend)
881 ;; ... from buffer's name (default title)...
882 `(:title
883 ,(or (let ((file (buffer-file-name (buffer-base-buffer))))
884 (and file
885 (file-name-sans-extension
886 (file-name-nondirectory file))))
887 (buffer-name (buffer-base-buffer))))
888 ;; ... from an external property list...
889 ext-plist
890 ;; ... from in-buffer settings...
891 (org-export-get-inbuffer-options
892 (org-with-wide-buffer (buffer-string)) backend
893 (and buffer-file-name
894 (org-remove-double-quotes buffer-file-name)))
895 ;; ... and from subtree, when appropriate.
896 (and subtreep
897 (org-export-get-subtree-options)))))
898 ;; Add initial options.
899 (setq options (append (org-export-initial-options options) options))
900 ;; Return plist.
901 options))
903 (defun org-export-parse-option-keyword (options backend)
904 "Parse an OPTIONS line and return values as a plist.
905 BACKEND is a symbol specifying the back-end to use."
906 (let* ((all (append org-export-option-alist
907 (let ((var (intern
908 (format "org-%s-option-alist" backend))))
909 (and (boundp var) (eval var)))))
910 ;; Build an alist between #+OPTION: item and property-name.
911 (alist (delq nil
912 (mapcar (lambda (e)
913 (when (nth 2 e) (cons (regexp-quote (nth 2 e))
914 (car e))))
915 all)))
916 plist)
917 (mapc (lambda (e)
918 (when (string-match (concat "\\(\\`\\|[ \t]\\)"
919 (car e)
920 ":\\(([^)\n]+)\\|[^ \t\n\r;,.]*\\)")
921 options)
922 (setq plist (plist-put plist
923 (cdr e)
924 (car (read-from-string
925 (match-string 2 options)))))))
926 alist)
927 plist))
929 (defun org-export-get-subtree-options ()
930 "Get export options in subtree at point.
932 Assume point is at subtree's beginning.
934 Return options as a plist."
935 (let (prop plist)
936 (when (setq prop (progn (looking-at org-todo-line-regexp)
937 (or (save-match-data
938 (org-entry-get (point) "EXPORT_TITLE"))
939 (org-match-string-no-properties 3))))
940 (setq plist (plist-put plist :title prop)))
941 (when (setq prop (org-entry-get (point) "EXPORT_TEXT"))
942 (setq plist (plist-put plist :text prop)))
943 (when (setq prop (org-entry-get (point) "EXPORT_AUTHOR"))
944 (setq plist (plist-put plist :author prop)))
945 (when (setq prop (org-entry-get (point) "EXPORT_DATE"))
946 (setq plist (plist-put plist :date prop)))
947 (when (setq prop (org-entry-get (point) "EXPORT_OPTIONS"))
948 (setq plist (org-export-add-options-to-plist plist prop)))
949 plist))
951 (defun org-export-get-inbuffer-options (buffer-string backend files)
952 "Return in-buffer options as a plist.
953 BUFFER-STRING is the string of the buffer. BACKEND is a symbol
954 specifying which back-end should be used. FILES is a list of
955 setup files names read so far, used to avoid circular
956 dependencies."
957 (let ((case-fold-search t) plist)
958 ;; 1. Special keywords, as in `org-export-special-keywords'.
959 (let ((start 0)
960 (special-re (org-make-options-regexp org-export-special-keywords)))
961 (while (string-match special-re buffer-string start)
962 (setq start (match-end 0))
963 (let ((key (upcase (org-match-string-no-properties 1 buffer-string)))
964 ;; Special keywords do not have their value expanded.
965 (val (org-match-string-no-properties 2 buffer-string)))
966 (setq plist
967 (org-combine-plists
968 (cond
969 ((string= key "SETUP_FILE")
970 (let ((file (expand-file-name
971 (org-remove-double-quotes (org-trim val)))))
972 ;; Avoid circular dependencies.
973 (unless (member file files)
974 (org-export-get-inbuffer-options
975 (org-file-contents file 'noerror)
976 backend
977 (cons file files)))))
978 ((string= key "OPTIONS")
979 (org-export-parse-option-keyword val backend))
980 ((string= key "MACRO")
981 (string-match "^\\([-a-zA-Z0-9_]+\\)[ \t]+\\(.*?[ \t]*$\\)"
982 val)
983 (plist-put nil
984 (intern (concat ":macro-"
985 (downcase (match-string 1 val))))
986 (match-string 2 val))))
987 plist)))))
988 ;; 2. Standard options, as in `org-export-option-alist'.
989 (let* ((all (append org-export-option-alist
990 (let ((var (intern
991 (format "org-%s-option-alist" backend))))
992 (and (boundp var) (eval var)))))
993 ;; Build alist between keyword name and property name.
994 (alist (delq nil (mapcar (lambda (e)
995 (when (nth 1 e) (cons (nth 1 e) (car e))))
996 all)))
997 ;; Build regexp matching all keywords associated to export
998 ;; options. Note: the search is case insensitive.
999 (opt-re (org-make-options-regexp
1000 (delq nil (mapcar (lambda (e) (nth 1 e)) all))))
1001 (start 0))
1002 (while (string-match opt-re buffer-string start)
1003 (setq start (match-end 0))
1004 (let* ((key (upcase (org-match-string-no-properties 1 buffer-string)))
1005 ;; Expand value, applying restrictions for keywords.
1006 (val (org-match-string-no-properties 2 buffer-string))
1007 (prop (cdr (assoc key alist)))
1008 (behaviour (nth 4 (assq prop all))))
1009 (setq plist
1010 (plist-put
1011 plist prop
1012 ;; Handle value depending on specified BEHAVIOUR.
1013 (case behaviour
1014 (space (if (plist-get plist prop)
1015 (concat (plist-get plist prop) " " (org-trim val))
1016 (org-trim val)))
1017 (newline (org-trim
1018 (concat
1019 (plist-get plist prop) "\n" (org-trim val))))
1020 (split `(,@(plist-get plist prop) ,@(org-split-string val)))
1021 ('t val)
1022 (otherwise (plist-get plist prop)))))))
1023 ;; Parse keywords specified in `org-element-parsed-keywords'.
1024 (mapc
1025 (lambda (key)
1026 (let* ((prop (cdr (assoc (upcase key) alist)))
1027 (value (and prop (plist-get plist prop))))
1028 (when (stringp value)
1029 (setq plist
1030 (plist-put
1031 plist prop
1032 (org-element-parse-secondary-string
1033 value
1034 (cdr (assq 'keyword org-element-string-restrictions))))))))
1035 org-element-parsed-keywords))
1036 ;; Return final value.
1037 plist))
1039 (defun org-export-get-global-options (backend)
1040 "Return global export options as a plist.
1041 BACKEND is a symbol specifying which back-end should be used."
1042 (let ((all (append org-export-option-alist
1043 (let ((var (intern
1044 (format "org-%s-option-alist" backend))))
1045 (and (boundp var) (eval var)))))
1046 ;; Output value.
1047 plist)
1048 (mapc (lambda (cell)
1049 (setq plist
1050 (plist-put plist (car cell) (eval (nth 3 cell)))))
1051 all)
1052 ;; Return value.
1053 plist))
1055 (defun org-export-initial-options (options)
1056 "Return a plist with non-optional properties.
1057 OPTIONS is the export options plist computed so far."
1058 (list
1059 ;; `:macro-date', `:macro-time' and `:macro-property' could as well
1060 ;; be initialized as tree properties, since they don't depend on
1061 ;; initial environment. Though, it may be more logical to keep
1062 ;; them close to other ":macro-" properties.
1063 :macro-date "(eval (format-time-string \"$1\"))"
1064 :macro-time "(eval (format-time-string \"$1\"))"
1065 :macro-property "(eval (org-entry-get nil \"$1\" 'selective))"
1066 :macro-modification-time
1067 (and (buffer-file-name)
1068 (file-exists-p (buffer-file-name))
1069 (concat "(eval (format-time-string \"$1\" '"
1070 (prin1-to-string (nth 5 (file-attributes (buffer-file-name))))
1071 "))"))
1072 :macro-input-file (and (buffer-file-name)
1073 (file-name-nondirectory (buffer-file-name)))
1074 ;; Footnotes definitions must be collected in the original buffer,
1075 ;; as there's no insurance that they will still be in the parse
1076 ;; tree, due to some narrowing.
1077 :footnote-definition-alist
1078 (let (alist)
1079 (org-with-wide-buffer
1080 (goto-char (point-min))
1081 (while (re-search-forward org-footnote-definition-re nil t)
1082 (let ((def (org-footnote-at-definition-p)))
1083 (when def
1084 (org-skip-whitespace)
1085 (push (cons (car def)
1086 (save-restriction
1087 (narrow-to-region (point) (nth 2 def))
1088 ;; Like `org-element-parse-buffer', but
1089 ;; makes sure the definition doesn't start
1090 ;; with a section element.
1091 (nconc
1092 (list 'org-data nil)
1093 (org-element-parse-elements
1094 (point-min) (point-max) nil nil nil nil nil))))
1095 alist))))
1096 alist))))
1098 (defvar org-export-allow-BIND-local nil)
1099 (defun org-export-confirm-letbind ()
1100 "Can we use #+BIND values during export?
1101 By default this will ask for confirmation by the user, to divert
1102 possible security risks."
1103 (cond
1104 ((not org-export-allow-BIND) nil)
1105 ((eq org-export-allow-BIND t) t)
1106 ((local-variable-p 'org-export-allow-BIND-local) org-export-allow-BIND-local)
1107 (t (org-set-local 'org-export-allow-BIND-local
1108 (yes-or-no-p "Allow BIND values in this buffer? ")))))
1110 (defun org-export-install-letbind-maybe ()
1111 "Install the values from #+BIND lines as local variables.
1112 Variables must be installed before in-buffer options are
1113 retrieved."
1114 (let (letbind pair)
1115 (org-with-wide-buffer
1116 (goto-char (point-min))
1117 (while (re-search-forward (org-make-options-regexp '("BIND")) nil t)
1118 (when (org-export-confirm-letbind)
1119 (push (read (concat "(" (org-match-string-no-properties 2) ")"))
1120 letbind))))
1121 (while (setq pair (pop letbind))
1122 (org-set-local (car pair) (nth 1 pair)))))
1125 ;;;; Tree Properties
1127 ;; They are initialized at the beginning of the transcoding process by
1128 ;; `org-export-collect-tree-properties'.
1130 ;; Dedicated functions focus on computing the value of specific tree
1131 ;; properties during initialization. Thus,
1132 ;; `org-export-use-select-tag-p' determines if an headline makes use
1133 ;; of an export tag enforcing inclusion. `org-export-get-min-level'
1134 ;; gets the minimal exportable level, used as a basis to compute
1135 ;; relative level for headlines. `org-export-get-point-max' returns
1136 ;; the maximum exportable ending position in the parse tree.
1137 ;; Eventually `org-export-collect-headline-numbering' builds an alist
1138 ;; between headlines' beginning position and their numbering.
1140 (defun org-export-collect-tree-properties (data info backend)
1141 "Extract tree properties from parse tree.
1143 DATA is the parse tree from which information is retrieved. INFO
1144 is a list holding export options. BACKEND is the back-end called
1145 for transcoding, as a symbol.
1147 Following tree properties are set:
1148 `:back-end' Back-end used for transcoding.
1150 `:headline-offset' Offset between true level of headlines and
1151 local level. An offset of -1 means an headline
1152 of level 2 should be considered as a level
1153 1 headline in the context.
1155 `:headline-numbering' Alist of all headlines' beginning position
1156 as key an the associated numbering as value.
1158 `:parse-tree' Whole parse tree.
1160 `:target-list' List of all targets in the parse tree.
1162 `:use-select-tags' Non-nil when parsed tree use a special tag to
1163 enforce transcoding of the headline."
1164 ;; First, set `:use-select-tags' property, as it will be required
1165 ;; for further computations.
1166 (setq info
1167 (org-combine-plists
1168 info `(:use-select-tags ,(org-export-use-select-tags-p data info))))
1169 ;; Then get `:headline-offset' in order to be able to use
1170 ;; `org-export-get-relative-level'.
1171 (setq info
1172 (org-combine-plists
1173 info `(:headline-offset ,(- 1 (org-export-get-min-level data info)))))
1174 ;; Now, get the rest of the tree properties, now `:use-select-tags'
1175 ;; is set...
1176 (nconc
1177 `(:parse-tree
1178 ,data
1179 :target-list
1180 ,(org-element-map data 'target (lambda (target local) target) info)
1181 :headline-numbering ,(org-export-collect-headline-numbering data info)
1182 :back-end ,backend)
1183 info))
1185 (defun org-export-use-select-tags-p (data options)
1186 "Non-nil when data use a tag enforcing transcoding.
1187 DATA is parsed data as returned by `org-element-parse-buffer'.
1188 OPTIONS is a plist holding export options."
1189 (org-element-map
1190 data
1191 'headline
1192 (lambda (headline info)
1193 (let ((tags (org-element-get-property :with-tags headline)))
1194 (and tags (string-match
1195 (format ":%s:" (plist-get info :select-tags)) tags))))
1196 options
1197 'stop-at-first-match))
1199 (defun org-export-get-min-level (data options)
1200 "Return minimum exportable headline's level in DATA.
1201 DATA is parsed tree as returned by `org-element-parse-buffer'.
1202 OPTIONS is a plist holding export options."
1203 (catch 'exit
1204 (let ((min-level 10000))
1205 (mapc (lambda (blob)
1206 (when (and (eq (car blob) 'headline)
1207 (not (org-export-skip-p blob options)))
1208 (setq min-level
1209 (min (org-element-get-property :level blob) min-level)))
1210 (when (= min-level 1) (throw 'exit 1)))
1211 (org-element-get-contents data))
1212 ;; If no headline was found, for the sake of consistency, set
1213 ;; minimum level to 1 nonetheless.
1214 (if (= min-level 10000) 1 min-level))))
1216 (defun org-export-collect-headline-numbering (data options)
1217 "Return numbering of all exportable headlines in a parse tree.
1219 DATA is the parse tree. OPTIONS is the plist holding export
1220 options.
1222 Return an alist whose key is an headline and value is its
1223 associated numbering \(in the shape of a list of numbers\)."
1224 (let ((numbering (make-vector org-export-max-depth 0)))
1225 (org-element-map
1226 data
1227 'headline
1228 (lambda (headline info)
1229 (let ((relative-level
1230 (1- (org-export-get-relative-level headline info))))
1231 (cons
1232 headline
1233 (loop for n across numbering
1234 for idx from 0 to org-export-max-depth
1235 when (< idx relative-level) collect n
1236 when (= idx relative-level) collect (aset numbering idx (1+ n))
1237 when (> idx relative-level) do (aset numbering idx 0)))))
1238 options)))
1242 ;;; The Transcoder
1244 ;; This function reads Org data (obtained with, i.e.
1245 ;; `org-element-parse-buffer') and transcodes it into a specified
1246 ;; back-end output. It takes care of updating local properties,
1247 ;; filtering out elements or objects according to export options and
1248 ;; organizing the output blank lines and white space are preserved.
1250 ;; Though, this function is inapropriate for secondary strings, which
1251 ;; require a fresh copy of the plist passed as INFO argument. Thus,
1252 ;; `org-export-secondary-string' is provided for that specific task.
1254 ;; Internally, three functions handle the filtering of objects and
1255 ;; elements during the export. More precisely, `org-export-skip-p'
1256 ;; determines if the considered object or element should be ignored
1257 ;; altogether, `org-export-interpret-p' tells which elements or
1258 ;; objects should be seen as real Org syntax and `org-export-expand'
1259 ;; transforms the others back into their original shape.
1261 (defun org-export-data (data backend info)
1262 "Convert DATA to a string into BACKEND format.
1264 DATA is a nested list as returned by `org-element-parse-buffer'.
1266 BACKEND is a symbol among supported exporters.
1268 INFO is a plist holding export options and also used as
1269 a communication channel between elements when walking the nested
1270 list. See `org-export-update-info' function for more
1271 details.
1273 Return transcoded string."
1274 (mapconcat
1275 ;; BLOB can be an element, an object, a string, or nil.
1276 (lambda (blob)
1277 (cond
1278 ((not blob) nil)
1279 ;; BLOB is a string. Check if the optional transcoder for plain
1280 ;; text exists, and call it in that case. Otherwise, simply
1281 ;; return string. Also update INFO and call
1282 ;; `org-export-filter-plain-text-functions'.
1283 ((stringp blob)
1284 (let ((transcoder (intern (format "org-%s-plain-text" backend))))
1285 (org-export-filter-apply-functions
1286 (plist-get info :filter-plain-text)
1287 (if (fboundp transcoder) (funcall transcoder blob info) blob)
1288 backend)))
1289 ;; BLOB is an element or an object.
1291 (let* ((type (if (stringp blob) 'plain-text (car blob)))
1292 ;; 1. Determine the appropriate TRANSCODER.
1293 (transcoder
1294 (cond
1295 ;; 1.0 A full Org document is inserted.
1296 ((eq type 'org-data) 'identity)
1297 ;; 1.1. BLOB should be ignored.
1298 ((org-export-skip-p blob info) nil)
1299 ;; 1.2. BLOB shouldn't be transcoded. Interpret it
1300 ;; back into Org syntax.
1301 ((not (org-export-interpret-p blob info))
1302 'org-export-expand)
1303 ;; 1.3. Else apply naming convention.
1304 (t (let ((trans (intern
1305 (format "org-%s-%s" backend type))))
1306 (and (fboundp trans) trans)))))
1307 ;; 2. Compute CONTENTS of BLOB.
1308 (contents
1309 (cond
1310 ;; Case 0. No transcoder defined: ignore BLOB.
1311 ((not transcoder) nil)
1312 ;; Case 1. Transparently export an Org document.
1313 ((eq type 'org-data) (org-export-data blob backend info))
1314 ;; Case 2. For a recursive object.
1315 ((memq type org-element-recursive-objects)
1316 (org-export-data
1317 blob backend
1318 (org-combine-plists
1319 info
1320 `(:genealogy ,(cons blob (plist-get info :genealogy))))))
1321 ;; Case 3. For a recursive element.
1322 ((memq type org-element-greater-elements)
1323 ;; Ignore contents of an archived tree
1324 ;; when `:with-archived-trees' is `headline'.
1325 (unless (and
1326 (eq type 'headline)
1327 (eq (plist-get info :with-archived-trees) 'headline)
1328 (org-element-get-property :archivedp blob))
1329 (org-element-normalize-string
1330 (org-export-data
1331 blob backend
1332 (org-combine-plists
1333 info `(:genealogy
1334 ,(cons blob (plist-get info :genealogy))))))))
1335 ;; Case 4. For a paragraph.
1336 ((eq type 'paragraph)
1337 (let ((paragraph
1338 (org-element-normalize-contents
1339 blob
1340 ;; When normalizing contents of an item or
1341 ;; a footnote definition, ignore first line's
1342 ;; indentation: there is none and it might be
1343 ;; misleading.
1344 (and (not (org-export-get-previous-element blob info))
1345 (let ((parent (caar (plist-get info :genealogy))))
1346 (memq parent '(footnote-definition item)))))))
1347 (org-export-data
1348 paragraph backend
1349 (org-combine-plists
1350 info `(:genealogy
1351 ,(cons paragraph (plist-get info :genealogy)))))))))
1352 ;; 3. Transcode BLOB into RESULTS string.
1353 (results (cond
1354 ((not transcoder) nil)
1355 ((eq transcoder 'org-export-expand)
1356 (org-export-data
1357 `(org-data nil ,(funcall transcoder blob contents))
1358 backend info))
1359 (t (funcall transcoder blob contents info)))))
1360 ;; 4. Discard nil results. Otherwise, update INFO, append
1361 ;; the same white space between elements or objects as in
1362 ;; the original buffer, and call appropriate filters.
1363 (when results
1364 ;; No filter for a full document.
1365 (if (eq type 'org-data) results
1366 (org-export-filter-apply-functions
1367 (plist-get info (intern (format ":filter-%s" type)))
1368 (let ((post-blank (org-element-get-property :post-blank blob)))
1369 (if (memq type org-element-all-elements)
1370 (concat (org-element-normalize-string results)
1371 (make-string post-blank ?\n))
1372 (concat results (make-string post-blank ? ))))
1373 backend)))))))
1374 (org-element-get-contents data) ""))
1376 (defun org-export-secondary-string (secondary backend info)
1377 "Convert SECONDARY string into BACKEND format.
1379 SECONDARY is a nested list as returned by
1380 `org-element-parse-secondary-string'.
1382 BACKEND is a symbol among supported exporters. INFO is a plist
1383 used as a communication channel.
1385 Return transcoded string."
1386 ;; Make SECONDARY acceptable for `org-export-data'.
1387 (let ((s (if (listp secondary) secondary (list secondary))))
1388 (org-export-data `(org-data nil ,@s) backend (copy-sequence info))))
1390 (defun org-export-skip-p (blob info)
1391 "Non-nil when element or object BLOB should be skipped during export.
1392 INFO is the plist holding export options."
1393 ;; Check headline.
1394 (unless (stringp blob)
1395 (case (car blob)
1396 ('headline
1397 (let ((with-tasks (plist-get info :with-tasks))
1398 (todo (org-element-get-property :todo-keyword blob))
1399 (todo-type (org-element-get-property :todo-type blob))
1400 (archived (plist-get info :with-archived-trees))
1401 (tag-list (let ((tags (org-element-get-property :tags blob)))
1402 (and tags (org-split-string tags ":")))))
1404 ;; Ignore subtrees with an exclude tag.
1405 (loop for k in (plist-get info :exclude-tags)
1406 thereis (member k tag-list))
1407 ;; Ignore subtrees without a select tag, when such tag is found
1408 ;; in the buffer.
1409 (and (plist-get info :use-select-tags)
1410 (loop for k in (plist-get info :select-tags)
1411 never (member k tag-list)))
1412 ;; Ignore commented sub-trees.
1413 (org-element-get-property :commentedp blob)
1414 ;; Ignore archived subtrees if `:with-archived-trees' is nil.
1415 (and (not archived) (org-element-get-property :archivedp blob))
1416 ;; Ignore tasks, if specified by `:with-tasks' property.
1417 (and todo (not with-tasks))
1418 (and todo
1419 (memq with-tasks '(todo done))
1420 (not (eq todo-type with-tasks)))
1421 (and todo
1422 (consp with-tasks)
1423 (not (member todo with-tasks))))))
1424 ;; Check time-stamp.
1425 ('time-stamp (not (plist-get info :with-timestamps)))
1426 ;; Check drawer.
1427 ('drawer
1428 (or (not (plist-get info :with-drawers))
1429 (and (consp (plist-get info :with-drawers))
1430 (not (member (org-element-get-property :drawer-name blob)
1431 (plist-get info :with-drawers))))))
1432 ;; Check export snippet.
1433 ('export-snippet
1434 (let* ((raw-back-end (org-element-get-property :back-end blob))
1435 (true-back-end
1436 (or (cdr (assoc raw-back-end org-export-snippet-translation-alist))
1437 raw-back-end)))
1438 (not (string= (symbol-name (plist-get info :back-end))
1439 true-back-end)))))))
1441 (defun org-export-interpret-p (blob info)
1442 "Non-nil if element or object BLOB should be interpreted as Org syntax.
1443 Check is done according to export options INFO, stored as
1444 a plist."
1445 (case (car blob)
1446 ;; ... entities...
1447 (entity (plist-get info :with-entities))
1448 ;; ... emphasis...
1449 (emphasis (plist-get info :with-emphasize))
1450 ;; ... fixed-width areas.
1451 (fixed-width (plist-get info :with-fixed-width))
1452 ;; ... footnotes...
1453 ((footnote-definition footnote-reference)
1454 (plist-get info :with-footnotes))
1455 ;; ... sub/superscripts...
1456 ((subscript superscript)
1457 (let ((sub/super-p (plist-get info :with-sub-superscript)))
1458 (if (eq sub/super-p '{})
1459 (org-element-get-property :use-brackets-p blob)
1460 sub/super-p)))
1461 ;; ... tables...
1462 (table (plist-get info :with-tables))
1463 (otherwise t)))
1465 (defsubst org-export-expand (blob contents)
1466 "Expand a parsed element or object to its original state.
1467 BLOB is either an element or an object. CONTENTS is its
1468 contents, as a string or nil."
1469 (funcall
1470 (intern (format "org-element-%s-interpreter" (car blob))) blob contents))
1474 ;;; The Filter System
1476 ;; Filters allow end-users to tweak easily the transcoded output.
1477 ;; They are the functional counterpart of hooks, as every filter in
1478 ;; a set is applied to the return value of the previous one.
1480 ;; Every set is back-end agnostic. Although, a filter is always
1481 ;; called, in addition to the string it applies to, with the back-end
1482 ;; used as argument, so it's easy enough for the end-user to add
1483 ;; back-end specific filters in the set.
1485 ;; Filters sets are defined below. There are of four types:
1487 ;; - `org-export-filter-parse-tree-functions' applies directly on the
1488 ;; complete parsed tree. It's the only filters set that doesn't
1489 ;; apply to a string.
1490 ;; - `org-export-filter-final-output-functions' applies to the final
1491 ;; transcoded string.
1492 ;; - `org-export-filter-plain-text-functions' applies to any string
1493 ;; not recognized as Org syntax.
1494 ;; - `org-export-filter-TYPE-functions' applies on the string returned
1495 ;; after an element or object of type TYPE has been transcoded.
1497 ;; All filters sets are applied through
1498 ;; `org-export-filter-apply-functions' function. Filters in a set are
1499 ;; applied in reverse order, that is in the order of consing. It
1500 ;; allows developers to be reasonably sure that their filters will be
1501 ;; applied first.
1503 ;;;; Special Filters
1504 (defvar org-export-filter-parse-tree-functions nil
1505 "Filter, or list of filters, applied to the parsed tree.
1506 Each filter is called with two arguments: the parse tree, as
1507 returned by `org-element-parse-buffer', and the back-end as
1508 a symbol. It must return the modified parse tree to transcode.")
1510 (defvar org-export-filter-final-output-functions nil
1511 "Filter, or list of filters, applied to the transcoded string.
1512 Each filter is called with two arguments: the full transcoded
1513 string, and the back-end as a symbol. It must return a string
1514 that will be used as the final export output.")
1516 (defvar org-export-filter-plain-text-functions nil
1517 "Filter, or list of filters, applied to plain text.
1518 Each filter is called with two arguments: a string which contains
1519 no Org syntax, and the back-end as a symbol. It must return
1520 a string or nil.")
1523 ;;;; Elements Filters
1525 (defvar org-export-filter-center-block-functions nil
1526 "List of functions applied to a transcoded center block.
1527 Each filter is called with two arguments: the transcoded center
1528 block, as a string, and the back-end, as a symbol. It must
1529 return a string or nil.")
1531 (defvar org-export-filter-drawer-functions nil
1532 "List of functions applied to a transcoded drawer.
1533 Each filter is called with two arguments: the transcoded drawer,
1534 as a string, and the back-end, as a symbol. It must return
1535 a string or nil.")
1537 (defvar org-export-filter-dynamic-block-functions nil
1538 "List of functions applied to a transcoded dynamic-block.
1539 Each filter is called with two arguments: the transcoded
1540 dynamic-block, as a string, and the back-end, as a symbol. It
1541 must return a string or nil.")
1543 (defvar org-export-filter-headline-functions nil
1544 "List of functions applied to a transcoded headline.
1545 Each filter is called with two arguments: the transcoded
1546 headline, as a string, and the back-end, as a symbol. It must
1547 return a string or nil.")
1549 (defvar org-export-filter-inlinetask-functions nil
1550 "List of functions applied to a transcoded inlinetask.
1551 Each filter is called with two arguments: the transcoded
1552 inlinetask, as a string, and the back-end, as a symbol. It must
1553 return a string or nil.")
1555 (defvar org-export-filter-plain-list-functions nil
1556 "List of functions applied to a transcoded plain-list.
1557 Each filter is called with two arguments: the transcoded
1558 plain-list, as a string, and the back-end, as a symbol. It must
1559 return a string or nil.")
1561 (defvar org-export-filter-item-functions nil
1562 "List of functions applied to a transcoded item.
1563 Each filter is called with two arguments: the transcoded item, as
1564 a string, and the back-end, as a symbol. It must return a string
1565 or nil.")
1567 (defvar org-export-filter-comment-functions nil
1568 "List of functions applied to a transcoded comment.
1569 Each filter is called with two arguments: the transcoded comment,
1570 as a string, and the back-end, as a symbol. It must return
1571 a string or nil.")
1573 (defvar org-export-filter-comment-block-functions nil
1574 "List of functions applied to a transcoded comment-comment.
1575 Each filter is called with two arguments: the transcoded
1576 comment-block, as a string, and the back-end, as a symbol. It
1577 must return a string or nil.")
1579 (defvar org-export-filter-example-block-functions nil
1580 "List of functions applied to a transcoded example-block.
1581 Each filter is called with two arguments: the transcoded
1582 example-block, as a string, and the back-end, as a symbol. It
1583 must return a string or nil.")
1585 (defvar org-export-filter-export-block-functions nil
1586 "List of functions applied to a transcoded export-block.
1587 Each filter is called with two arguments: the transcoded
1588 export-block, as a string, and the back-end, as a symbol. It
1589 must return a string or nil.")
1591 (defvar org-export-filter-fixed-width-functions nil
1592 "List of functions applied to a transcoded fixed-width.
1593 Each filter is called with two arguments: the transcoded
1594 fixed-width, as a string, and the back-end, as a symbol. It must
1595 return a string or nil.")
1597 (defvar org-export-filter-footnote-definition-functions nil
1598 "List of functions applied to a transcoded footnote-definition.
1599 Each filter is called with two arguments: the transcoded
1600 footnote-definition, as a string, and the back-end, as a symbol.
1601 It must return a string or nil.")
1603 (defvar org-export-filter-horizontal-rule-functions nil
1604 "List of functions applied to a transcoded horizontal-rule.
1605 Each filter is called with two arguments: the transcoded
1606 horizontal-rule, as a string, and the back-end, as a symbol. It
1607 must return a string or nil.")
1609 (defvar org-export-filter-keyword-functions nil
1610 "List of functions applied to a transcoded keyword.
1611 Each filter is called with two arguments: the transcoded keyword,
1612 as a string, and the back-end, as a symbol. It must return
1613 a string or nil.")
1615 (defvar org-export-filter-latex-environment-functions nil
1616 "List of functions applied to a transcoded latex-environment.
1617 Each filter is called with two arguments: the transcoded
1618 latex-environment, as a string, and the back-end, as a symbol.
1619 It must return a string or nil.")
1621 (defvar org-export-filter-babel-call-functions nil
1622 "List of functions applied to a transcoded babel-call.
1623 Each filter is called with two arguments: the transcoded
1624 babel-call, as a string, and the back-end, as a symbol. It must
1625 return a string or nil.")
1627 (defvar org-export-filter-paragraph-functions nil
1628 "List of functions applied to a transcoded paragraph.
1629 Each filter is called with two arguments: the transcoded
1630 paragraph, as a string, and the back-end, as a symbol. It must
1631 return a string or nil.")
1633 (defvar org-export-filter-property-drawer-functions nil
1634 "List of functions applied to a transcoded property-drawer.
1635 Each filter is called with two arguments: the transcoded
1636 property-drawer, as a string, and the back-end, as a symbol. It
1637 must return a string or nil.")
1639 (defvar org-export-filter-quote-block-functions nil
1640 "List of functions applied to a transcoded quote block.
1641 Each filter is called with two arguments: the transcoded quote
1642 block, as a string, and the back-end, as a symbol. It must
1643 return a string or nil.")
1645 (defvar org-export-filter-quote-section-functions nil
1646 "List of functions applied to a transcoded quote-section.
1647 Each filter is called with two arguments: the transcoded
1648 quote-section, as a string, and the back-end, as a symbol. It
1649 must return a string or nil.")
1651 (defvar org-export-filter-section-functions nil
1652 "List of functions applied to a transcoded section.
1653 Each filter is called with two arguments: the transcoded section,
1654 as a string, and the back-end, as a symbol. It must return
1655 a string or nil.")
1657 (defvar org-export-filter-special-block-functions nil
1658 "List of functions applied to a transcoded special block.
1659 Each filter is called with two arguments: the transcoded special
1660 block, as a string, and the back-end, as a symbol. It must
1661 return a string or nil.")
1663 (defvar org-export-filter-src-block-functions nil
1664 "List of functions applied to a transcoded src-block.
1665 Each filter is called with two arguments: the transcoded
1666 src-block, as a string, and the back-end, as a symbol. It must
1667 return a string or nil.")
1669 (defvar org-export-filter-table-functions nil
1670 "List of functions applied to a transcoded table.
1671 Each filter is called with two arguments: the transcoded table,
1672 as a string, and the back-end, as a symbol. It must return
1673 a string or nil.")
1675 (defvar org-export-filter-verse-block-functions nil
1676 "List of functions applied to a transcoded verse block.
1677 Each filter is called with two arguments: the transcoded verse
1678 block, as a string, and the back-end, as a symbol. It must
1679 return a string or nil.")
1682 ;;;; Objects Filters
1684 (defvar org-export-filter-emphasis-functions nil
1685 "List of functions applied to a transcoded emphasis.
1686 Each filter is called with two arguments: the transcoded
1687 emphasis, as a string, and the back-end, as a symbol. It must
1688 return a string or nil.")
1690 (defvar org-export-filter-entity-functions nil
1691 "List of functions applied to a transcoded entity.
1692 Each filter is called with two arguments: the transcoded entity,
1693 as a string, and the back-end, as a symbol. It must return
1694 a string or nil.")
1696 (defvar org-export-filter-export-snippet-functions nil
1697 "List of functions applied to a transcoded export-snippet.
1698 Each filter is called with two arguments: the transcoded
1699 export-snippet, as a string, and the back-end, as a symbol. It
1700 must return a string or nil.")
1702 (defvar org-export-filter-footnote-reference-functions nil
1703 "List of functions applied to a transcoded footnote-reference.
1704 Each filter is called with two arguments: the transcoded
1705 footnote-reference, as a string, and the back-end, as a symbol.
1706 It must return a string or nil.")
1708 (defvar org-export-filter-inline-babel-call-functions nil
1709 "List of functions applied to a transcoded inline-babel-call.
1710 Each filter is called with two arguments: the transcoded
1711 inline-babel-call, as a string, and the back-end, as a symbol. It
1712 must return a string or nil.")
1714 (defvar org-export-filter-inline-src-block-functions nil
1715 "List of functions applied to a transcoded inline-src-block.
1716 Each filter is called with two arguments: the transcoded
1717 inline-src-block, as a string, and the back-end, as a symbol. It
1718 must return a string or nil.")
1720 (defvar org-export-filter-latex-fragment-functions nil
1721 "List of functions applied to a transcoded latex-fragment.
1722 Each filter is called with two arguments: the transcoded
1723 latex-fragment, as a string, and the back-end, as a symbol. It
1724 must return a string or nil.")
1726 (defvar org-export-filter-line-break-functions nil
1727 "List of functions applied to a transcoded line-break.
1728 Each filter is called with two arguments: the transcoded
1729 line-break, as a string, and the back-end, as a symbol. It must
1730 return a string or nil.")
1732 (defvar org-export-filter-link-functions nil
1733 "List of functions applied to a transcoded link.
1734 Each filter is called with two arguments: the transcoded link, as
1735 a string, and the back-end, as a symbol. It must return a string
1736 or nil.")
1738 (defvar org-export-filter-macro-functions nil
1739 "List of functions applied to a transcoded macro.
1740 Each filter is called with two arguments: the transcoded macro,
1741 as a string, and the back-end, as a symbol. It must return
1742 a string or nil.")
1744 (defvar org-export-filter-radio-target-functions nil
1745 "List of functions applied to a transcoded radio-target.
1746 Each filter is called with two arguments: the transcoded
1747 radio-target, as a string, and the back-end, as a symbol. It
1748 must return a string or nil.")
1750 (defvar org-export-filter-statistics-cookie-functions nil
1751 "List of functions applied to a transcoded statistics-cookie.
1752 Each filter is called with two arguments: the transcoded
1753 statistics-cookie, as a string, and the back-end, as a symbol.
1754 It must return a string or nil.")
1756 (defvar org-export-filter-subscript-functions nil
1757 "List of functions applied to a transcoded subscript.
1758 Each filter is called with two arguments: the transcoded
1759 subscript, as a string, and the back-end, as a symbol. It must
1760 return a string or nil.")
1762 (defvar org-export-filter-superscript-functions nil
1763 "List of functions applied to a transcoded superscript.
1764 Each filter is called with two arguments: the transcoded
1765 superscript, as a string, and the back-end, as a symbol. It must
1766 return a string or nil.")
1768 (defvar org-export-filter-target-functions nil
1769 "List of functions applied to a transcoded target.
1770 Each filter is called with two arguments: the transcoded target,
1771 as a string, and the back-end, as a symbol. It must return
1772 a string or nil.")
1774 (defvar org-export-filter-time-stamp-functions nil
1775 "List of functions applied to a transcoded time-stamp.
1776 Each filter is called with two arguments: the transcoded
1777 time-stamp, as a string, and the back-end, as a symbol. It must
1778 return a string or nil.")
1780 (defvar org-export-filter-verbatim-functions nil
1781 "List of functions applied to a transcoded verbatim.
1782 Each filter is called with two arguments: the transcoded
1783 verbatim, as a string, and the back-end, as a symbol. It must
1784 return a string or nil.")
1786 (defun org-export-filter-apply-functions (filters value backend)
1787 "Call every function in FILTERS with arguments VALUE and BACKEND.
1788 Functions are called in a LIFO fashion, to be sure that developer
1789 specified filters, if any, are called first."
1790 ;; Ensure FILTERS is a list.
1791 (loop for filter in filters
1792 if (not value) return nil else
1793 do (setq value (funcall filter value backend)))
1794 value)
1798 ;;; Core functions
1800 ;; This is the room for the main function, `org-export-as', along with
1801 ;; its derivatives, `org-export-to-buffer' and `org-export-to-file'.
1802 ;; They differ only by the way they output the resulting code.
1804 ;; `org-export-output-file-name' is an auxiliary function meant to be
1805 ;; used with `org-export-to-file'. With a given extension, it tries
1806 ;; to provide a canonical file name to write export output to.
1808 ;; Note that `org-export-as' doesn't really parse the current buffer,
1809 ;; but a copy of it (with the same buffer-local variables and
1810 ;; visibility), where Babel blocks are executed, if appropriate.
1811 ;; `org-export-with-current-buffer-copy' macro prepares that copy.
1813 (defun org-export-as (backend
1814 &optional subtreep visible-only body-only ext-plist)
1815 "Transcode current Org buffer into BACKEND code.
1817 If narrowing is active in the current buffer, only transcode its
1818 narrowed part.
1820 If a region is active, transcode that region.
1822 When optional argument SUBTREEP is non-nil, transcode the
1823 sub-tree at point, extracting information from the headline
1824 properties first.
1826 When optional argument VISIBLE-ONLY is non-nil, don't export
1827 contents of hidden elements.
1829 When optional argument BODY-ONLY is non-nil, only return body
1830 code, without preamble nor postamble.
1832 EXT-PLIST, when provided, is a property list with external
1833 parameters overriding Org default settings, but still inferior to
1834 file-local settings.
1836 Return code as a string."
1837 (save-excursion
1838 (save-restriction
1839 ;; Narrow buffer to an appropriate region for parsing.
1840 (when (org-region-active-p)
1841 (narrow-to-region (region-beginning) (region-end))
1842 (goto-char (point-min)))
1843 (when (and subtreep (not (org-at-heading-p)))
1844 ;; Ensure point is at sub-tree's beginning.
1845 (org-with-limited-levels (org-back-to-heading (not visible-only))))
1846 ;; Retrieve export options (INFO) and parsed tree (RAW-DATA).
1847 ;; Buffer isn't parsed directly. Instead, a temporary copy is
1848 ;; created, where all code blocks are evaluated. RAW-DATA is
1849 ;; the parsed tree of the buffer resulting from that process.
1850 ;; Eventually call `org-export-filter-parse-tree-functions'.
1851 (let* ((info (org-export-collect-options backend subtreep ext-plist))
1852 (raw-data (progn
1853 (when subtreep ; Only parse subtree contents.
1854 (let ((end (save-excursion (org-end-of-subtree t))))
1855 (narrow-to-region
1856 (progn (forward-line) (point)) end)))
1857 (org-export-filter-apply-functions
1858 (plist-get info :filter-parse-tree)
1859 (org-export-with-current-buffer-copy
1860 (org-export-blocks-preprocess)
1861 (org-element-parse-buffer nil visible-only))
1862 backend))))
1863 ;; Initialize the communication system and combine it to INFO.
1864 (setq info
1865 (org-combine-plists
1866 info (org-export-collect-tree-properties raw-data info backend)))
1867 ;; Now transcode RAW-DATA. Also call
1868 ;; `org-export-filter-final-output-functions'.
1869 (let* ((body (org-element-normalize-string
1870 (org-export-data raw-data backend info)))
1871 (template (intern (format "org-%s-template" backend)))
1872 (output (org-export-filter-apply-functions
1873 (plist-get info :filter-final-output)
1874 (if (or (not (fboundp template)) body-only) body
1875 (funcall template body info))
1876 backend)))
1877 ;; Maybe add final OUTPUT to kill ring before returning it.
1878 (when org-export-copy-to-kill-ring (org-kill-new output))
1879 output)))))
1881 (defun org-export-to-buffer (backend buffer &optional subtreep visible-only
1882 body-only ext-plist)
1883 "Call `org-export-as' with output to a specified buffer.
1885 BACKEND is the back-end used for transcoding, as a symbol.
1887 BUFFER is the output buffer. If it already exists, it will be
1888 erased first, otherwise, it will be created.
1890 Arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and EXT-PLIST are
1891 similar to those used in `org-export-as', which see.
1893 Return buffer."
1894 (let ((out (org-export-as backend subtreep visible-only body-only ext-plist))
1895 (buffer (get-buffer-create buffer)))
1896 (with-current-buffer buffer
1897 (erase-buffer)
1898 (insert out)
1899 (goto-char (point-min)))
1900 buffer))
1902 (defun org-export-to-file (backend file &optional subtreep visible-only
1903 body-only ext-plist)
1904 "Call `org-export-as' with output to a specified file.
1906 BACKEND is the back-end used for transcoding, as a symbol. FILE
1907 is the name of the output file, as a string.
1909 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
1910 EXT-PLIST are similar to those used in `org-export-as', which
1911 see.
1913 Return output file's name."
1914 ;; Checks for FILE permissions. `write-file' would do the same, but
1915 ;; we'd rather avoid needless transcoding of parse tree.
1916 (unless (file-writable-p file) (error "Output file not writable"))
1917 ;; Insert contents to a temporary buffer and write it to FILE.
1918 (let ((out (org-export-as
1919 backend subtreep visible-only body-only ext-plist)))
1920 (with-temp-buffer
1921 (insert out)
1922 (let ((coding-system-for-write org-export-coding-system))
1923 (write-file file))))
1924 ;; Return full path.
1925 file)
1927 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
1928 "Return output file's name according to buffer specifications.
1930 EXTENSION is a string representing the output file extension.
1932 With a non-nil optional argument SUBTREEP, try to determine
1933 output file's name by looking for \"EXPORT_FILE_NAME\" property
1934 of subtree at point.
1936 When optional argument PUB-DIR is set, use it as the publishing
1937 directory.
1939 Return file name as a string, or nil if it couldn't be
1940 determined."
1941 (let ((base-name
1942 (concat
1943 (file-name-as-directory (or pub-dir "."))
1944 ;; Output file name either comes from EXPORT_FILE_NAME
1945 ;; sub-tree property, assuming point is at beginning of said
1946 ;; sub-tree, or to the name of buffer's associated file.
1947 (file-name-sans-extension
1948 (or (and subtreep
1949 (org-entry-get
1950 (save-excursion
1951 (ignore-errors
1952 (org-back-to-heading (not visible-only)) (point)))
1953 "EXPORT_FILE_NAME" t))
1954 (file-name-nondirectory
1955 (or (buffer-file-name (buffer-base-buffer)))))))))
1956 ;; BASE-NAME will be nil when original buffer was temporary one.
1957 (when base-name (concat base-name extension))))
1959 (defmacro org-export-with-current-buffer-copy (&rest body)
1960 "Apply BODY in a copy of the current buffer.
1962 The copy preserves local variables and visibility of the original
1963 buffer.
1965 Point is at buffer's beginning when BODY is applied."
1966 (org-with-gensyms (original-buffer offset buffer-string overlays)
1967 `(let ((,original-buffer ,(current-buffer))
1968 (,offset ,(1- (point-min)))
1969 (,buffer-string ,(buffer-string))
1970 (,overlays (mapcar
1971 'copy-overlay (overlays-in (point-min) (point-max)))))
1972 (with-temp-buffer
1973 (let ((buffer-invisibility-spec nil))
1974 (org-clone-local-variables
1975 ,original-buffer "^\\(org-\\|orgtbl-\\|major-mode$\\)")
1976 (insert ,buffer-string)
1977 (mapc (lambda (ov)
1978 (move-overlay
1980 (- (overlay-start ov) ,offset)
1981 (- (overlay-end ov) ,offset)
1982 (current-buffer)))
1983 ,overlays)
1984 (goto-char (point-min))
1985 (progn ,@body))))))
1986 (def-edebug-spec org-export-with-current-buffer-copy (body))
1990 ;;; Tools For Back-Ends
1992 ;; A whole set of tools is available to help build new exporters. Any
1993 ;; function general enough to have its use across many back-ends
1994 ;; should be added here.
1996 ;; As of now, functions operating on footnotes, headlines, include
1997 ;; keywords, links, macros, references, src-blocks, tables and tables
1998 ;; of contents are implemented.
2000 ;;;; For Footnotes
2002 ;; `org-export-collect-footnote-definitions' is a tool to list
2003 ;; actually used footnotes definitions in the whole parse tree, or in
2004 ;; an headline, in order to add footnote listings throughout the
2005 ;; transcoded data.
2007 ;; `org-export-footnote-first-reference-p' is a predicate used by some
2008 ;; back-ends, when they need to attach the footnote definition only to
2009 ;; the first occurrence of the corresponding label.
2011 ;; `org-export-get-footnote-definition' and
2012 ;; `org-export-get-footnote-number' provide easier access to
2013 ;; additional information relative to a footnote reference.
2015 (defun org-export-collect-footnote-definitions (data info)
2016 "Return an alist between footnote numbers, labels and definitions.
2018 DATA is the parse tree from which definitions are collected.
2019 INFO is the plist used as a communication channel.
2021 Definitions are sorted by order of references. They either
2022 appear as Org data \(transcoded with `org-export-data'\) or as
2023 a secondary string for inlined footnotes \(transcoded with
2024 `org-export-secondary-string'\). Unreferenced definitions are
2025 ignored."
2026 (let (refs)
2027 ;; Collect seen references in REFS.
2028 (org-element-map
2029 data 'footnote-reference
2030 (lambda (footnote local)
2031 (when (org-export-footnote-first-reference-p footnote local)
2032 (list (org-export-get-footnote-number footnote local)
2033 (org-element-get-property :label footnote)
2034 (org-export-get-footnote-definition footnote local))))
2035 info)))
2037 (defun org-export-footnote-first-reference-p (footnote-reference info)
2038 "Non-nil when a footnote reference is the first one for its label.
2040 FOOTNOTE-REFERENCE is the footnote reference being considered.
2041 INFO is the plist used as a communication channel."
2042 (let ((label (org-element-get-property :label footnote-reference)))
2043 (or (not label)
2044 (equal
2045 footnote-reference
2046 (org-element-map
2047 (plist-get info :parse-tree) 'footnote-reference
2048 (lambda (footnote local)
2049 (when (string= (org-element-get-property :label footnote) label)
2050 footnote))
2051 info 'first-match)))))
2053 (defun org-export-get-footnote-definition (footnote-reference info)
2054 "Return definition of FOOTNOTE-REFERENCE as parsed data.
2055 INFO is the plist used as a communication channel."
2056 (let ((label (org-element-get-property :label footnote-reference)))
2057 (or (org-element-get-property :inline-definition footnote-reference)
2058 (cdr (assoc label (plist-get info :footnote-definition-alist))))))
2060 (defun org-export-get-footnote-number (footnote info)
2061 "Return number associated to a footnote.
2063 FOOTNOTE is either a footnote reference or a footnote definition.
2064 INFO is the plist used as a communication channel."
2065 (let ((label (org-element-get-property :label footnote)) seen-refs)
2066 (org-element-map
2067 (plist-get info :parse-tree) 'footnote-reference
2068 (lambda (fn local)
2069 (let ((fn-lbl (org-element-get-property :label fn)))
2070 (cond
2071 ((and (not fn-lbl) (equal fn footnote)) (1+ (length seen-refs)))
2072 ((and label (string= label fn-lbl)) (1+ (length seen-refs)))
2073 ;; Anonymous footnote: it's always a new one. Also, be sure
2074 ;; to return nil from the `cond' so `first-match' doesn't
2075 ;; get us out of the loop.
2076 ((not fn-lbl) (push 'inline seen-refs) nil)
2077 ;; Label not seen so far: add it so SEEN-REFS. Again,
2078 ;; return nil to stay in the loop.
2079 ((not (member fn-lbl seen-refs)) (push fn-lbl seen-refs) nil))))
2080 info 'first-match)))
2083 ;;;; For Headlines
2085 ;; `org-export-get-relative-level' is a shortcut to get headline
2086 ;; level, relatively to the lower headline level in the parsed tree.
2088 ;; `org-export-get-headline-number' returns the section number of an
2089 ;; headline, while `org-export-number-to-roman' allows to convert it
2090 ;; to roman numbers.
2092 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
2093 ;; `org-export-last-sibling-p' are three useful predicates when it
2094 ;; comes to fulfill the `:headline-levels' property.
2096 (defun org-export-get-relative-level (headline info)
2097 "Return HEADLINE relative level within current parsed tree.
2098 INFO is a plist holding contextual information."
2099 (+ (org-element-get-property :level headline)
2100 (or (plist-get info :headline-offset) 0)))
2102 (defun org-export-low-level-p (headline info)
2103 "Non-nil when HEADLINE is considered as low level.
2105 INFO is a plist used as a communication channel.
2107 A low level headlines has a relative level greater than
2108 `:headline-levels' property value.
2110 Return value is the difference between HEADLINE relative level
2111 and the last level being considered as high enough, or nil."
2112 (let ((limit (plist-get info :headline-levels)))
2113 (when (wholenump limit)
2114 (let ((level (org-export-get-relative-level headline info)))
2115 (and (> level limit) (- level limit))))))
2117 (defun org-export-get-headline-number (headline info)
2118 "Return HEADLINE numbering as a list of numbers.
2119 INFO is a plist holding contextual information."
2120 (cdr (assoc headline (plist-get info :headline-numbering))))
2122 (defun org-export-number-to-roman (n)
2123 "Convert integer N into a roman numeral."
2124 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
2125 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
2126 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
2127 ( 1 . "I")))
2128 (res ""))
2129 (if (<= n 0)
2130 (number-to-string n)
2131 (while roman
2132 (if (>= n (caar roman))
2133 (setq n (- n (caar roman))
2134 res (concat res (cdar roman)))
2135 (pop roman)))
2136 res)))
2138 (defun org-export-first-sibling-p (headline info)
2139 "Non-nil when HEADLINE is the first sibling in its sub-tree.
2140 INFO is the plist used as a communication channel."
2141 (not (eq (car (org-export-get-previous-element headline info)) 'headline)))
2143 (defun org-export-last-sibling-p (headline info)
2144 "Non-nil when HEADLINE is the last sibling in its sub-tree.
2145 INFO is the plist used as a communication channel."
2146 (equal
2147 (car (last (org-element-get-contents (car (plist-get info :genealogy)))))
2148 headline))
2151 ;;;; For Include Keywords
2153 ;; This section provides a tool to properly handle insertion of files
2154 ;; during export: `org-export-included-files'. It recursively
2155 ;; transcodes a file specfied by an include keyword.
2157 ;; It uses two helper functions: `org-export-get-file-contents'
2158 ;; returns contents of a file according to parameters specified in the
2159 ;; keyword while `org-export-parse-included-file' parses the file
2160 ;; specified by it.
2162 (defun org-export-included-file (keyword backend info)
2163 "Transcode file specified with include KEYWORD.
2165 KEYWORD is the include keyword element transcoded. BACKEND is
2166 the language back-end used for transcoding. INFO is the plist
2167 used as a communication channel.
2169 This function updates `:included-files' and `:headline-offset'
2170 properties.
2172 Return the transcoded string."
2173 (let ((data (org-export-parse-included-file keyword info))
2174 (file (let ((value (org-element-get-property :value keyword)))
2175 (and (string-match "^\"\\(\\S-+\\)\"" value)
2176 (match-string 1 value)))))
2177 (org-element-normalize-string
2178 (org-export-data
2179 data backend
2180 (org-combine-plists
2181 info
2182 ;; Store full path of already included files to avoid
2183 ;; recursive file inclusion.
2184 `(:included-files
2185 ,(cons (expand-file-name file) (plist-get info :included-files))
2186 ;; Ensure that a top-level headline in the included
2187 ;; file becomes a direct child of the current headline
2188 ;; in the buffer.
2189 :headline-offset
2190 ,(- (+ (org-element-get-property
2191 :level (org-export-get-parent-headline keyword info))
2192 (plist-get info :headline-offset))
2193 (1- (org-export-get-min-level data info)))))))))
2195 (defun org-export-get-file-contents (file &optional lines)
2196 "Get the contents of FILE and return them as a string.
2197 When optional argument LINES is a string specifying a range of
2198 lines, include only those lines."
2199 (with-temp-buffer
2200 (insert-file-contents file)
2201 (when lines
2202 (let* ((lines (split-string lines "-"))
2203 (lbeg (string-to-number (car lines)))
2204 (lend (string-to-number (cadr lines)))
2205 (beg (if (zerop lbeg) (point-min)
2206 (goto-char (point-min))
2207 (forward-line (1- lbeg))
2208 (point)))
2209 (end (if (zerop lend) (point-max)
2210 (goto-char (point-min))
2211 (forward-line (1- lend))
2212 (point))))
2213 (narrow-to-region beg end)))
2214 (buffer-string)))
2216 (defun org-export-parse-included-file (keyword info)
2217 "Parse file specified by include KEYWORD.
2219 KEYWORD is the include keyword element transcoded. BACKEND is
2220 the language back-end used for transcoding. INFO is the plist
2221 used as a communication channel.
2223 Return the parsed tree."
2224 (let* ((value (org-element-get-property :value keyword))
2225 (file (and (string-match "^\"\\(\\S-+\\)\"" value)
2226 (prog1 (match-string 1 value)
2227 (setq value (replace-match "" nil nil value)))))
2228 (lines (and (string-match
2229 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\"" value)
2230 (prog1 (match-string 1 value)
2231 (setq value (replace-match "" nil nil value)))))
2232 (env (cond ((string-match "\\<example\\>" value) "example")
2233 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
2234 (match-string 1 value)))))
2235 (cond
2236 ((or (not file)
2237 (not (file-exists-p file))
2238 (not (file-readable-p file)))
2239 (format "Cannot include file %s" file))
2240 ((and (not env)
2241 (member (expand-file-name file) (plist-get info :included-files)))
2242 (error "Recursive file inclusion: %S" file))
2243 (t (let ((raw (org-element-normalize-string
2244 (org-export-get-file-contents
2245 (expand-file-name file) lines))))
2246 ;; If environment isn't specified, Insert file in
2247 ;; a temporary buffer and parse it as Org syntax.
2248 ;; Otherwise, build the element representing the file.
2249 (cond
2250 ((not env)
2251 (with-temp-buffer
2252 (insert raw) (org-mode) (org-element-parse-buffer)))
2253 ((string= "example" env)
2254 `(org-data nil (example-block (:value ,raw :post-blank 0))))
2256 `(org-data
2258 (src-block (:value ,raw :language ,env :post-blank 0))))))))))
2261 ;;;; For Links
2263 ;; `org-export-solidify-link-text' turns a string into a safer version
2264 ;; for links, replacing most non-standard characters with hyphens.
2266 ;; `org-export-get-coderef-format' returns an appropriate format
2267 ;; string for coderefs.
2269 ;; `org-export-inline-image-p' returns a non-nil value when the link
2270 ;; provided should be considered as an inline image.
2272 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
2273 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
2274 ;; returns an appropriate unique identifier when found, or nil.
2276 ;; `org-export-resolve-id-link' returns the first headline with
2277 ;; specified id or custom-id in parse tree, or nil when none was
2278 ;; found.
2280 ;; `org-export-resolve-coderef' associates a reference to a line
2281 ;; number in the element it belongs, or returns the reference itself
2282 ;; when the element isn't numbered.
2284 (defun org-export-solidify-link-text (s)
2285 "Take link text S and make a safe target out of it."
2286 (save-match-data
2287 (mapconcat 'identity (org-split-string s "[^a-zA-Z0-9_\\.-]+") "-")))
2289 (defun org-export-get-coderef-format (path desc)
2290 "Return format string for code reference link.
2291 PATH is the link path. DESC is its description."
2292 (save-match-data
2293 (cond ((string-match (regexp-quote (concat "(" path ")")) desc)
2294 (replace-match "%s" t t desc))
2295 ((string= desc "") "%s")
2296 (t desc))))
2298 (defun org-export-inline-image-p (link &optional extensions)
2299 "Non-nil if LINK object points to an inline image.
2301 When non-nil, optional argument EXTENSIONS is a list of valid
2302 extensions for image files, as strings. Otherwise, a default
2303 list is provided \(cf `org-image-file-name-regexp'\)."
2304 (and (not (org-element-get-contents link))
2305 (string= (org-element-get-property :type link) "file")
2306 (org-file-image-p
2307 (expand-file-name (org-element-get-property :path link))
2308 extensions)))
2310 (defun org-export-resolve-fuzzy-link (link info)
2311 "Return LINK destination.
2313 INFO is a plist holding contextual information.
2315 Return value can be an object, an element, or nil:
2317 - If LINK path exactly matches any target, return the target
2318 object.
2320 - If LINK path exactly matches any headline name, return that
2321 element. If more than one headline share that name, priority
2322 will be given to the one with the closest common ancestor, if
2323 any, or the first one in the parse tree otherwise.
2325 - Otherwise, return nil.
2327 Assume LINK type is \"fuzzy\"."
2328 (let ((path (org-element-get-property :path link)))
2329 ;; Link points to a target: return it.
2330 (or (loop for target in (plist-get info :target-list)
2331 when (string= (org-element-get-property :raw-value target) path)
2332 return target)
2333 ;; Link either points to an headline or nothing. Try to find
2334 ;; the source, with priority given to headlines with the closest
2335 ;; common ancestor. If such candidate is found, return its
2336 ;; beginning position as an unique identifier, otherwise return
2337 ;; nil.
2338 (let ((find-headline
2339 (function
2340 ;; Return first headline whose `:raw-value' property
2341 ;; is NAME in parse tree DATA, or nil.
2342 (lambda (name data)
2343 (org-element-map
2344 data 'headline
2345 (lambda (headline local)
2346 (when (string=
2347 (org-element-get-property :raw-value headline)
2348 name)
2349 headline))
2350 info 'first-match)))))
2351 ;; Search among headlines sharing an ancestor with link,
2352 ;; from closest to farthest.
2353 (or (catch 'exit
2354 (mapc
2355 (lambda (parent)
2356 (when (eq (car parent) 'headline)
2357 (let ((foundp (funcall find-headline path parent)))
2358 (when foundp (throw 'exit foundp)))))
2359 (plist-get info :genealogy)) nil)
2360 ;; No match with a common ancestor: try the full parse-tree.
2361 (funcall find-headline path (plist-get info :parse-tree)))))))
2363 (defun org-export-resolve-id-link (link info)
2364 "Return headline referenced as LINK destination.
2366 INFO is a plist used as a communication channel.
2368 Return value can be an headline element or nil. Assume LINK type
2369 is either \"id\" or \"custom-id\"."
2370 (let ((id (org-element-get-property :path link)))
2371 (org-element-map
2372 (plist-get info :parse-tree) 'headline
2373 (lambda (headline local)
2374 (when (or (string= (org-element-get-property :id headline) id)
2375 (string= (org-element-get-property :custom-id headline) id))
2376 headline))
2377 info 'first-match)))
2379 (defun org-export-resolve-coderef (ref info)
2380 "Resolve a code reference REF.
2382 INFO is a plist used as a communication channel.
2384 Return associated line number in source code, or REF itself,
2385 depending on src-block or example element's switches."
2386 (org-element-map
2387 (plist-get info :parse-tree) '(src-block example)
2388 (lambda (el local)
2389 (let ((switches (or (org-element-get-property :switches el) "")))
2390 (with-temp-buffer
2391 (insert (org-trim (org-element-get-property :value el)))
2392 ;; Build reference regexp.
2393 (let* ((label
2394 (or (and (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
2395 (match-string 1 switches))
2396 org-coderef-label-format))
2397 (ref-re
2398 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
2399 (replace-regexp-in-string "%s" ref label nil t))))
2400 ;; Element containing REF is found. Only associate REF to
2401 ;; a line number if element has "+n" or "-n" and "-k" or
2402 ;; "-r" as switches. When it has "+n", count accumulated
2403 ;; locs before, too.
2404 (when (re-search-backward ref-re nil t)
2405 (cond
2406 ((not (string-match "-[kr]\\>" switches)) ref)
2407 ((string-match "-n\\>" switches) (line-number-at-pos))
2408 ((string-match "\\+n\\>" switches)
2409 (+ (org-export-get-loc el local) (line-number-at-pos)))
2410 (t ref)))))))
2411 info 'first-match))
2414 ;;;; For Macros
2416 ;; `org-export-expand-macro' simply takes care of expanding macros.
2418 (defun org-export-expand-macro (macro info)
2419 "Expand MACRO and return it as a string.
2420 INFO is a plist holding export options."
2421 (let* ((key (org-element-get-property :key macro))
2422 (args (org-element-get-property :args macro))
2423 (value (plist-get info (intern (format ":macro-%s" key)))))
2424 ;; Replace arguments in VALUE.
2425 (let ((s 0) n)
2426 (while (string-match "\\$\\([0-9]+\\)" value s)
2427 (setq s (1+ (match-beginning 0))
2428 n (string-to-number (match-string 1 value)))
2429 (and (>= (length args) n)
2430 (setq value (replace-match (nth (1- n) args) t t value)))))
2431 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
2432 (when (string-match "\\`(eval\\>" value)
2433 (setq value (eval (read value))))
2434 ;; Return expanded string.
2435 (format "%s" value)))
2438 ;;;; For References
2440 ;; `org-export-get-ordinal' associates a sequence number to any object
2441 ;; or element.
2443 (defun org-export-get-ordinal
2444 (element info &optional types within-section predicate)
2445 "Return ordinal number of an element or object.
2447 ELEMENT is the element or object considered. INFO is the plist
2448 used as a communication channel.
2450 Optional argument TYPES, when non-nil, is a list of element or
2451 object types, as symbols, that should also be counted in.
2452 Otherwise, only provided element's type is considered.
2454 When optional argument WITHIN-SECTION is non-nil, narrow counting
2455 to the section containing ELEMENT.
2457 Optional argument PREDICATE is a function returning a non-nil
2458 value if the current element or object should be counted in. It
2459 accepts one argument: the element or object being considered.
2460 This argument allows to count only a certain type of objects,
2461 like inline images, which are a subset of links \(in that case,
2462 `org-export-inline-image-p' might be an useful predicate\)."
2463 (let ((counter 0)
2464 ;; Determine if search should apply to current section, in
2465 ;; which case it should be retrieved first, or to full parse
2466 ;; tree. As a special case, an element or object without
2467 ;; a parent headline will also trigger a full search,
2468 ;; notwithstanding WITHIN-SECTION value.
2469 (data
2470 (if (not within-section) (plist-get info :parse-tree)
2471 (or (org-export-get-parent-headline element info)
2472 (plist-get info :parse-tree)))))
2473 ;; Increment counter until ELEMENT is found again.
2474 (org-element-map
2475 data (or types (car element))
2476 (lambda (el local)
2477 (cond
2478 ((equal element el) (1+ counter))
2479 ((not predicate) (incf counter) nil)
2480 ((funcall predicate el) (incf counter) nil)))
2481 info 'first-match)))
2484 ;;;; For Src-Blocks
2486 ;; `org-export-get-loc' counts number of code lines accumulated in
2487 ;; src-block or example-block elements with a "+n" switch until
2488 ;; a given element, excluded. Note: "-n" switches reset that count.
2490 ;; `org-export-handle-code' takes care of line numbering and reference
2491 ;; cleaning in source code, when appropriate.
2493 (defun org-export-get-loc (element info)
2494 "Return accumulated lines of code up to ELEMENT.
2496 INFO is the plist used as a communication channel.
2498 ELEMENT is excluded from count."
2499 (let ((loc 0))
2500 (org-element-map
2501 (plist-get info :parse-tree) `(src-block example-block ,(car element))
2502 (lambda (el local)
2503 (cond
2504 ;; ELEMENT is reached: Quit the loop.
2505 ((equal el element) t)
2506 ;; Only count lines from src-block and example-block elements
2507 ;; with a "+n" or "-n" switch. A "-n" switch resets counter.
2508 ((not (memq (car el) '(src-block example-block))) nil)
2509 ((let ((switches (org-element-get-property :switches el)))
2510 (when (and switches (string-match "\\([-+]\\)n\\>" switches))
2511 ;; Accumulate locs or reset them.
2512 (let ((accumulatep (string= (match-string 1 switches) "-"))
2513 (lines (org-count-lines
2514 (org-trim (org-element-get-property :value el)))))
2515 (setq loc (if accumulatep lines (+ loc lines))))))
2516 ;; Return nil to stay in the loop.
2517 nil)))
2518 info 'first-match)
2519 ;; Return value.
2520 loc))
2522 (defun org-export-handle-code (element info &optional num-fmt ref-fmt delayed)
2523 "Handle line numbers and code references in ELEMENT.
2525 ELEMENT has either a `src-block' an `example-block' type. INFO
2526 is a plist used as a communication channel.
2528 If optional argument NUM-FMT is a string, it will be used as
2529 a format string for numbers at beginning of each line.
2531 If optional argument REF-FMT is a string, it will be used as
2532 a format string for each line of code containing a reference.
2534 When optional argument DELAYED is non-nil, `org-loc' and
2535 `org-coderef' properties, set to an adequate value, are applied
2536 to, respectively, numbered lines and lines with a reference. No
2537 line numbering is done and all references are stripped from the
2538 resulting string. Both NUM-FMT and REF-FMT arguments are ignored
2539 in that situation.
2541 Return new code as a string."
2542 (let* ((switches (or (org-element-get-property :switches element) ""))
2543 (code (org-element-get-property :value element))
2544 (numberp (string-match "[-+]n\\>" switches))
2545 (accumulatep (string-match "\\+n\\>" switches))
2546 ;; Initialize loc counter when any kind of numbering is
2547 ;; active.
2548 (total-LOC (cond
2549 (accumulatep (org-export-get-loc element info))
2550 (numberp 0)))
2551 ;; Get code and clean it. Remove blank lines at its
2552 ;; beginning and end. Also remove protective commas.
2553 (preserve-indent-p (or org-src-preserve-indentation
2554 (string-match "-i\\>" switches)))
2555 (replace-labels (when (string-match "-r\\>" switches)
2556 (if (string-match "-k\\>" switches) 'keep t)))
2557 (code (let ((c (replace-regexp-in-string
2558 "\\`\\([ \t]*\n\\)+" ""
2559 (replace-regexp-in-string
2560 "\\(:?[ \t]*\n\\)*[ \t]*\\'" "\n" code))))
2561 ;; If appropriate, remove global indentation.
2562 (unless preserve-indent-p (setq c (org-remove-indentation c)))
2563 ;; Free up the protected lines. Note: Org blocks
2564 ;; have commas at the beginning or every line.
2565 (if (string=
2566 (or (org-element-get-property :language element) "")
2567 "org")
2568 (replace-regexp-in-string "^," "" c)
2569 (replace-regexp-in-string
2570 "^\\(,\\)\\(:?\\*\\|[ \t]*#\\+\\)" "" c nil nil 1))))
2571 ;; Split code to process it line by line.
2572 (code-lines (org-split-string code "\n"))
2573 ;; If numbering is active, ensure line numbers will be
2574 ;; correctly padded before applying the format string.
2575 (num-fmt
2576 (when (and (not delayed) numberp)
2577 (format (if (stringp num-fmt) num-fmt "%s: ")
2578 (format "%%%ds"
2579 (length (number-to-string
2580 (+ (length code-lines) total-LOC)))))))
2581 ;; Get format used for references.
2582 (label-fmt (or (and (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
2583 (match-string 1 switches))
2584 org-coderef-label-format))
2585 ;; Build a regexp matching a loc with a reference.
2586 (with-ref-re (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
2587 (replace-regexp-in-string
2588 "%s" "\\([-a-zA-Z0-9_ ]+\\)" label-fmt nil t))))
2589 (org-element-normalize-string
2590 (mapconcat
2591 (lambda (loc)
2592 ;; Maybe add line number to current line of code (LOC).
2593 (when numberp
2594 (incf total-LOC)
2595 (setq loc (if delayed (org-add-props loc nil 'org-loc total-LOC)
2596 (concat (format num-fmt total-LOC) loc))))
2597 ;; Take action if at a ref line.
2598 (when (string-match with-ref-re loc)
2599 (let ((ref (match-string 3 loc)))
2600 (setq loc
2601 ;; Option "-r" without "-k" removes labels.
2602 ;; A non-nil DELAYED removes labels unconditionally.
2603 (if (or delayed
2604 (and replace-labels (not (eq replace-labels 'keep))))
2605 (replace-match "" nil nil loc 1)
2606 (replace-match (format "(%s)" ref) nil nil loc 2)))
2607 ;; Store REF in `org-coderef' property if DELAYED asks to.
2608 (cond (delayed (setq loc (org-add-props loc nil 'org-coderef ref)))
2609 ;; If REF-FMT is defined, apply it to current LOC.
2610 ((stringp ref-fmt) (setq loc (format ref-fmt loc))))))
2611 ;; Return updated LOC for concatenation.
2612 loc)
2613 code-lines "\n"))))
2616 ;;;; For Tables
2618 ;; `org-export-table-format-info' extracts formatting information
2619 ;; (alignment, column groups and presence of a special column) from
2620 ;; a raw table and returns it as a property list.
2622 ;; `org-export-clean-table' cleans the raw table from any Org
2623 ;; table-specific syntax.
2625 (defun org-export-table-format-info (table)
2626 "Extract info from TABLE.
2627 Return a plist whose properties and values are:
2628 `:alignment' vector of strings among \"r\", \"l\" and \"c\",
2629 `:column-groups' vector of symbols among `start', `end', `start-end',
2630 `:row-groups' list of integers representing row groups.
2631 `:special-column-p' non-nil if table has a special column.
2632 `:width' vector of integers representing desired width of
2633 current column, or nil."
2634 (with-temp-buffer
2635 (insert table)
2636 (goto-char 1)
2637 (org-table-align)
2638 (let ((align (vconcat (mapcar (lambda (c) (if c "r" "l"))
2639 org-table-last-alignment)))
2640 (width (make-vector (length org-table-last-alignment) nil))
2641 (colgroups (make-vector (length org-table-last-alignment) nil))
2642 (row-group 0)
2643 (rowgroups)
2644 (special-column-p 'empty))
2645 (mapc (lambda (row)
2646 (if (string-match "^[ \t]*|[-+]+|[ \t]*$" row)
2647 (incf row-group)
2648 ;; Determine if a special column is present by looking
2649 ;; for special markers in the first column. More
2650 ;; accurately, the first column is considered special
2651 ;; if it only contains special markers and, maybe,
2652 ;; empty cells.
2653 (setq special-column-p
2654 (cond
2655 ((not special-column-p) nil)
2656 ((string-match "^[ \t]*| *\\\\?\\([/#!$*_^]\\) *|" row)
2657 'special)
2658 ((string-match "^[ \t]*| +|" row) special-column-p))))
2659 (cond
2660 ;; Read forced alignment and width information, if any,
2661 ;; and determine final alignment for the table.
2662 ((org-table-cookie-line-p row)
2663 (let ((col 0))
2664 (mapc (lambda (field)
2665 (when (string-match
2666 "<\\([lrc]\\)?\\([0-9]+\\)?>" field)
2667 (let ((align-data (match-string 1 field)))
2668 (when align-data (aset align col align-data)))
2669 (let ((w-data (match-string 2 field)))
2670 (when w-data
2671 (aset width col (string-to-number w-data)))))
2672 (incf col))
2673 (org-split-string row "[ \t]*|[ \t]*"))))
2674 ;; Read column groups information.
2675 ((org-table-colgroup-line-p row)
2676 (let ((col 0))
2677 (mapc (lambda (field)
2678 (aset colgroups col
2679 (cond ((string= "<" field) 'start)
2680 ((string= ">" field) 'end)
2681 ((string= "<>" field) 'start-end)))
2682 (incf col))
2683 (org-split-string row "[ \t]*|[ \t]*"))))
2684 ;; Contents line.
2685 (t (push row-group rowgroups))))
2686 (org-split-string table "\n"))
2687 ;; Return plist.
2688 (list :alignment align
2689 :column-groups colgroups
2690 :row-groups (reverse rowgroups)
2691 :special-column-p (eq special-column-p 'special)
2692 :width width))))
2694 (defun org-export-clean-table (table specialp)
2695 "Clean string TABLE from its formatting elements.
2696 Remove any row containing column groups or formatting cookies and
2697 rows starting with a special marker. If SPECIALP is non-nil,
2698 assume the table contains a special formatting column and remove
2699 it also."
2700 (let ((rows (org-split-string table "\n")))
2701 (mapconcat 'identity
2702 (delq nil
2703 (mapcar
2704 (lambda (row)
2705 (cond
2706 ((org-table-colgroup-line-p row) nil)
2707 ((org-table-cookie-line-p row) nil)
2708 ;; Ignore rows starting with a special marker.
2709 ((string-match "^[ \t]*| *[!_^/] *|" row) nil)
2710 ;; Remove special column.
2711 ((and specialp
2712 (or (string-match "^\\([ \t]*\\)|-+\\+" row)
2713 (string-match "^\\([ \t]*\\)|[^|]*|" row)))
2714 (replace-match "\\1|" t nil row))
2715 (t row)))
2716 rows))
2717 "\n")))
2720 ;;;; For Tables Of Contents
2722 ;; `org-export-collect-headlines' builds a list of all exportable
2723 ;; headline elements, maybe limited to a certain depth. One can then
2724 ;; easily parse it and transcode it.
2726 ;; Building lists of tables, figures or listings is quite similar.
2727 ;; Once the generic function `org-export-collect-elements' is defined,
2728 ;; `org-export-collect-tables', `org-export-collect-figures' and
2729 ;; `org-export-collect-listings' can be derived from it.
2731 (defun org-export-collect-headlines (info &optional n)
2732 "Collect headlines in order to build a table of contents.
2734 INFO is a plist used as a communication channel.
2736 When non-nil, optional argument N must be an integer. It
2737 specifies the depth of the table of contents.
2739 Return a list of all exportable headlines as parsed elements."
2740 (org-element-map
2741 (plist-get info :parse-tree)
2742 'headline
2743 (lambda (headline local)
2744 ;; Strip contents from HEADLINE.
2745 (let ((relative-level (org-export-get-relative-level headline local)))
2746 (unless (and n (> relative-level n)) headline)))
2747 info))
2749 (defun org-export-collect-elements (type info &optional predicate)
2750 "Collect referenceable elements of a determined type.
2752 TYPE can be a symbol or a list of symbols specifying element
2753 types to search. Only elements with a caption or a name are
2754 collected.
2756 INFO is a plist used as a communication channel.
2758 When non-nil, optional argument PREDICATE is a function accepting
2759 one argument, an element of type TYPE. It returns a non-nil
2760 value when that element should be collected.
2762 Return a list of all elements found, in order of appearance."
2763 (org-element-map
2764 (plist-get info :parse-tree) type
2765 (lambda (element local)
2766 (and (or (org-element-get-property :caption element)
2767 (org-element-get-property :name element))
2768 (or (not predicate) (funcall predicate element))
2769 element)) info))
2771 (defun org-export-collect-tables (info)
2772 "Build a list of tables.
2774 INFO is a plist used as a communication channel.
2776 Return a list of table elements with a caption or a name
2777 affiliated keyword."
2778 (org-export-collect-elements 'table info))
2780 (defun org-export-collect-figures (info predicate)
2781 "Build a list of figures.
2783 INFO is a plist used as a communication channel. PREDICATE is
2784 a function which accepts one argument: a paragraph element and
2785 whose return value is non-nil when that element should be
2786 collected.
2788 A figure is a paragraph type element, with a caption or a name,
2789 verifying PREDICATE. The latter has to be provided since
2790 a \"figure\" is a vague concept that may depend on back-end.
2792 Return a list of elements recognized as figures."
2793 (org-export-collect-elements 'paragraph info predicate))
2795 (defun org-export-collect-listings (info)
2796 "Build a list of src blocks.
2798 INFO is a plist used as a communication channel.
2800 Return a list of src-block elements with a caption or a name
2801 affiliated keyword."
2802 (org-export-collect-elements 'src-block info))
2805 ;;;; Topology
2807 (defun org-export-get-parent-headline (blob info)
2808 "Return BLOB's closest parent headline or nil.
2809 INFO is a plist used as a communication channel."
2810 (catch 'exit
2811 (mapc
2812 (lambda (el) (when (eq (car el) 'headline) (throw 'exit el)))
2813 (plist-get info :genealogy))
2814 nil))
2816 (defun org-export-get-previous-element (blob info)
2817 "Return previous element or object.
2819 BLOB is an element or object. INFO is a plist used as
2820 a communication channel.
2822 Return previous element or object, a string, or nil."
2823 (let ((parent (car (plist-get info :genealogy))))
2824 (cadr (member blob (reverse (org-element-get-contents parent))))))
2828 ;;; The Dispatcher
2830 ;; `org-export-dispatch' is the standard interactive way to start an
2831 ;; export process. It uses `org-export-dispatch-ui' as a subroutine
2832 ;; for its interface. Most commons back-ends should have an entry in
2833 ;; it.
2835 (defun org-export-dispatch ()
2836 "Export dispatcher for Org mode.
2838 It provides an access to common export related tasks in a buffer.
2839 Its interface comes in two flavours: standard and expert. While
2840 both share the same set of bindings, only the former displays the
2841 valid keys associations. Set `org-export-dispatch-use-expert-ui'
2842 to switch to one or the other.
2844 Return an error if key pressed has no associated command."
2845 (interactive)
2846 (let* ((input (org-export-dispatch-ui
2847 (if (listp org-export-initial-scope) org-export-initial-scope
2848 (list org-export-initial-scope))
2849 org-export-dispatch-use-expert-ui))
2850 (raw-key (car input))
2851 (scope (cdr input)))
2852 ;; Translate "C-a", "C-b"... into "a", "b"... Then take action
2853 ;; depending on user's key pressed.
2854 (case (if (< raw-key 27) (+ raw-key 96) raw-key)
2855 ;; Export with `e-latex' back-end.
2857 (let ((outbuf
2858 (org-export-to-buffer
2859 'e-latex "*Org E-LaTeX Export*"
2860 (memq 'subtree scope) (memq 'visible scope) (memq 'body scope))))
2861 (with-current-buffer outbuf (latex-mode))
2862 (when org-export-show-temporary-export-buffer
2863 (switch-to-buffer-other-window outbuf))))
2864 (?l (org-e-latex-export-to-latex
2865 (memq 'subtree scope) (memq 'visible scope) (memq 'body scope)))
2866 (?p (org-e-latex-export-to-pdf
2867 (memq 'subtree scope) (memq 'visible scope) (memq 'body scope)))
2868 (?d (org-open-file
2869 (org-e-latex-export-to-pdf
2870 (memq 'subtree scope) (memq 'visible scope) (memq 'body scope))))
2871 ;; Undefined command.
2872 (t (error "No command associated with key %s"
2873 (char-to-string raw-key))))))
2875 (defun org-export-dispatch-ui (scope expertp)
2876 "Handle interface for `org-export-dispatch'.
2878 SCOPE is a list containing current interactive options set for
2879 export. It can contain any of the following symbols:
2880 `body' toggles a body-only export
2881 `subtree' restricts export to current subtree
2882 `visible' restricts export to visible part of buffer.
2884 EXPERTP, when non-nil, triggers expert UI. In that case, no help
2885 buffer is provided, but indications about currently active
2886 options are given in the prompt. Moreover, \[?] allows to switch
2887 back to standard interface.
2889 Return value is a list with key pressed as car and a list of
2890 final interactive export options as cdr."
2891 (let ((help (format "------------------- General Options -------------------
2892 \[1] Body only: %s
2893 \[2] Export scope: %s
2894 \[3] Visible only: %s
2896 -------------------- LaTeX Export ---------------------
2897 \[l] to LaTeX file [L] to temporary buffer
2898 \[p] to PDF file [d] ... and open it"
2899 (if (memq 'body scope) "On" "Off")
2900 (if (memq 'subtree scope) "Subtree" "Buffer")
2901 (if (memq 'visible scope) "On" "Off")))
2902 (standard-prompt "Export command: ")
2903 (expert-prompt (format "Export command (%s%s%s): "
2904 (if (memq 'body scope) "b" "-")
2905 (if (memq 'subtree scope) "s" "-")
2906 (if (memq 'visible scope) "v" "-")))
2907 (handle-keypress
2908 (function
2909 ;; Read a character from command input, toggling interactive
2910 ;; options when applicable. PROMPT is the displayed prompt,
2911 ;; as a string.
2912 (lambda (prompt)
2913 (let ((key (read-char-exclusive prompt)))
2914 (cond
2915 ;; Ignore non-standard characters (i.e. "M-a").
2916 ((not (characterp key)) (org-export-dispatch-ui scope expertp))
2917 ;; Switch back to standard interface.
2918 ((and (eq key ??) expertp) (org-export-dispatch-ui scope nil))
2919 ((eq key ?1)
2920 (org-export-dispatch-ui
2921 (if (memq 'body scope) (remq 'body scope) (cons 'body scope))
2922 expertp))
2923 ((eq key ?2)
2924 (org-export-dispatch-ui
2925 (if (memq 'subtree scope) (remq 'subtree scope)
2926 (cons 'subtree scope))
2927 expertp))
2928 ((eq key ?3)
2929 (org-export-dispatch-ui
2930 (if (memq 'visible scope) (remq 'visible scope)
2931 (cons 'visible scope))
2932 expertp))
2933 (t (cons key scope))))))))
2934 ;; With expert UI, just read key with a fancy prompt. In standard
2935 ;; UI, display an intrusive help buffer.
2936 (if expertp (funcall handle-keypress expert-prompt)
2937 (save-window-excursion
2938 (delete-other-windows)
2939 (with-output-to-temp-buffer "*Org Export/Publishing Help*" (princ help))
2940 (org-fit-window-to-buffer
2941 (get-buffer-window "*Org Export/Publishing Help*"))
2942 (funcall handle-keypress standard-prompt)))))
2945 (provide 'org-export)
2946 ;;; org-export.el ends here