contrib/lisp/org-export: Improve footnote API
[org-mode.git] / contrib / lisp / org-export.el
blob509b6c28d939dad9eab53cdaa516e3ecd98e9332
1 ;;; org-export.el --- Generic Export Engine For Org
3 ;; Copyright (C) 2011 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 last
89 ;; part of this file.
91 ;;; Code:
92 (eval-when-compile (require 'cl))
93 (require 'org-element)
96 ;;; Internal Variables
98 ;; Among internal variables, the most important is
99 ;; `org-export-option-alist'. This variable define the global export
100 ;; options, shared between every exporter, and how they are acquired.
102 (defconst org-export-max-depth 19
103 "Maximum nesting depth for headlines, counting from 0.")
105 (defconst org-export-option-alist
106 '((:author "AUTHOR" nil user-full-name t)
107 (:creator "CREATOR" nil org-export-creator-string)
108 (:date "DATE" nil nil t)
109 (:description "DESCRIPTION" nil nil newline)
110 (:email "EMAIL" nil user-mail-address t)
111 (:exclude-tags "EXPORT_EXCLUDE_TAGS" nil org-export-exclude-tags split)
112 (:headline-levels nil "H" org-export-headline-levels)
113 (:keywords "KEYWORDS" nil nil space)
114 (:language "LANGUAGE" nil org-export-default-language t)
115 (:preserve-breaks nil "\\n" org-export-preserve-breaks)
116 (:section-numbers nil "num" org-export-with-section-numbers)
117 (:select-tags "EXPORT_SELECT_TAGS" nil org-export-select-tags split)
118 (:time-stamp-file nil "timestamp" org-export-time-stamp-file)
119 (:title "TITLE" nil nil space)
120 (:with-archived-trees nil "arch" org-export-with-archived-trees)
121 (:with-author nil "author" org-export-with-author)
122 (:with-creator nil "creator" org-export-with-creator)
123 (:with-drawers nil "drawer" org-export-with-drawers)
124 (:with-email nil "email" org-export-with-email)
125 (:with-emphasize nil "*" org-export-with-emphasize)
126 (:with-entities nil "e" org-export-with-entities)
127 (:with-fixed-width nil ":" org-export-with-fixed-width)
128 (:with-footnotes nil "f" org-export-with-footnotes)
129 (:with-priority nil "pri" org-export-with-priority)
130 (:with-special-strings nil "-" org-export-with-special-strings)
131 (:with-sub-superscript nil "^" org-export-with-sub-superscripts)
132 (:with-toc nil "toc" org-export-with-toc)
133 (:with-tables nil "|" org-export-with-tables)
134 (:with-tags nil "tags" org-export-with-tags)
135 (:with-tasks nil "tasks" org-export-with-tasks)
136 (:with-timestamps nil "<" org-export-with-timestamps)
137 (:with-todo-keywords nil "todo" org-export-with-todo-keywords))
138 "Alist between export properties and ways to set them.
140 The car of the alist is the property name, and the cdr is a list
141 like \(KEYWORD OPTION DEFAULT BEHAVIOUR\) where:
143 KEYWORD is a string representing a buffer keyword, or nil.
144 OPTION is a string that could be found in an #+OPTIONS: line.
145 DEFAULT is the default value for the property.
146 BEHAVIOUR determine how Org should handle multiple keywords for
147 the same property. It is a symbol among:
148 nil Keep old value and discard the new one.
149 t Replace old value with the new one.
150 `space' Concatenate the values, separating them with a space.
151 `newline' Concatenate the values, separating them with
152 a newline.
153 `split' Split values at white spaces, and cons them to the
154 previous list.
156 KEYWORD and OPTION have precedence over DEFAULT.
158 All these properties should be back-end agnostic. For back-end
159 specific properties, define a similar variable named
160 `org-BACKEND-option-alist', replacing BACKEND with the name of
161 the appropriate back-end. You can also redefine properties
162 there, as they have precedence over these.")
164 (defconst org-export-special-keywords
165 '("SETUP_FILE" "OPTIONS" "MACRO")
166 "List of in-buffer keywords that require special treatment.
167 These keywords are not directly associated to a property. The
168 way they are handled must be hard-coded into
169 `org-export-get-inbuffer-options' function.")
173 ;;; User-configurable Variables
175 ;; Configuration for the masses.
177 ;; They should never be evaled directly, as their value is to be
178 ;; stored in a property list (cf. `org-export-option-alist').
180 (defgroup org-export nil
181 "Options for exporting Org mode files."
182 :tag "Org Export"
183 :group 'org)
185 (defgroup org-export-general nil
186 "General options for export engine."
187 :tag "Org Export General"
188 :group 'org-export)
190 (defcustom org-export-with-archived-trees 'headline
191 "Whether sub-trees with the ARCHIVE tag should be exported.
193 This can have three different values:
194 nil Do not export, pretend this tree is not present.
195 t Do export the entire tree.
196 `headline' Only export the headline, but skip the tree below it.
198 This option can also be set with the #+OPTIONS line,
199 e.g. \"arch:nil\"."
200 :group 'org-export-general
201 :type '(choice
202 (const :tag "Not at all" nil)
203 (const :tag "Headline only" 'headline)
204 (const :tag "Entirely" t)))
206 (defcustom org-export-with-author t
207 "Non-nil means insert author name into the exported file.
208 This option can also be set with the #+OPTIONS line,
209 e.g. \"author:nil\"."
210 :group 'org-export-general
211 :type 'boolean)
213 (defcustom org-export-with-creator 'comment
214 "Non-nil means the postamble should contain a creator sentence.
216 The sentence can be set in `org-export-creator-string' and
217 defaults to \"Generated by Org mode XX in Emacs XXX.\".
219 If the value is `comment' insert it as a comment."
220 :group 'org-export-general
221 :type '(choice
222 (const :tag "No creator sentence" nil)
223 (const :tag "Sentence as a comment" 'comment)
224 (const :tag "Insert the sentence" t)))
226 (defcustom org-export-creator-string
227 (format "Generated by Org mode %s in Emacs %s." org-version emacs-version)
228 "String to insert at the end of the generated document."
229 :group 'org-export-general
230 :type '(string :tag "Creator string"))
232 (defcustom org-export-with-drawers nil
233 "Non-nil means export with drawers like the property drawer.
234 When t, all drawers are exported. This may also be a list of
235 drawer names to export."
236 :group 'org-export-general
237 :type '(choice
238 (const :tag "All drawers" t)
239 (const :tag "None" nil)
240 (repeat :tag "Selected drawers"
241 (string :tag "Drawer name"))))
243 (defcustom org-export-with-email nil
244 "Non-nil means insert author email into the exported file.
245 This option can also be set with the #+OPTIONS line,
246 e.g. \"email:t\"."
247 :group 'org-export-general
248 :type 'boolean)
250 (defcustom org-export-with-emphasize t
251 "Non-nil means interpret *word*, /word/, and _word_ as emphasized text.
253 If the export target supports emphasizing text, the word will be
254 typeset in bold, italic, or underlined, respectively. Not all
255 export backends support this.
257 This option can also be set with the #+OPTIONS line, e.g. \"*:nil\"."
258 :group 'org-export-general
259 :type 'boolean)
261 (defcustom org-export-exclude-tags '("noexport")
262 "Tags that exclude a tree from export.
263 All trees carrying any of these tags will be excluded from
264 export. This is without condition, so even subtrees inside that
265 carry one of the `org-export-select-tags' will be removed."
266 :group 'org-export-general
267 :type '(repeat (string :tag "Tag")))
269 (defcustom org-export-with-fixed-width t
270 "Non-nil means lines starting with \":\" will be in fixed width font.
272 This can be used to have pre-formatted text, fragments of code
273 etc. For example:
274 : ;; Some Lisp examples
275 : (while (defc cnt)
276 : (ding))
277 will be looking just like this in also HTML. See also the QUOTE
278 keyword. Not all export backends support this.
280 This option can also be set with the #+OPTIONS line, e.g. \"::nil\"."
281 :group 'org-export-translation
282 :type 'boolean)
284 (defcustom org-export-with-footnotes t
285 "Non-nil means Org footnotes should be exported.
286 This option can also be set with the #+OPTIONS line,
287 e.g. \"f:nil\"."
288 :group 'org-export-general
289 :type 'boolean)
291 (defcustom org-export-headline-levels 3
292 "The last level which is still exported as a headline.
294 Inferior levels will produce itemize lists when exported. Note
295 that a numeric prefix argument to an exporter function overrides
296 this setting.
298 This option can also be set with the #+OPTIONS line, e.g. \"H:2\"."
299 :group 'org-export-general
300 :type 'integer)
302 (defcustom org-export-default-language "en"
303 "The default language for export and clocktable translations, as a string.
304 This may have an association in
305 `org-clock-clocktable-language-setup'."
306 :group 'org-export-general
307 :type '(string :tag "Language"))
309 (defcustom org-export-preserve-breaks nil
310 "Non-nil means preserve all line breaks when exporting.
312 Normally, in HTML output paragraphs will be reformatted.
314 This option can also be set with the #+OPTIONS line,
315 e.g. \"\\n:t\"."
316 :group 'org-export-general
317 :type 'boolean)
319 (defcustom org-export-with-entities t
320 "Non-nil means interpret entities when exporting.
322 For example, HTML export converts \\alpha to &alpha; and \\AA to
323 &Aring;.
325 For a list of supported names, see the constant `org-entities'
326 and the user option `org-entities-user'.
328 This option can also be set with the #+OPTIONS line,
329 e.g. \"e:nil\"."
330 :group 'org-export-general
331 :type 'boolean)
333 (defcustom org-export-with-priority nil
334 "Non-nil means include priority cookies in export.
335 When nil, remove priority cookies for export."
336 :group 'org-export-general
337 :type 'boolean)
339 (defcustom org-export-with-section-numbers t
340 "Non-nil means add section numbers to headlines when exporting.
342 This option can also be set with the #+OPTIONS line,
343 e.g. \"num:t\"."
344 :group 'org-export-general
345 :type 'boolean)
347 (defcustom org-export-select-tags '("export")
348 "Tags that select a tree for export.
349 If any such tag is found in a buffer, all trees that do not carry
350 one of these tags will be deleted before export. Inside trees
351 that are selected like this, you can still deselect a subtree by
352 tagging it with one of the `org-export-exclude-tags'."
353 :group 'org-export-general
354 :type '(repeat (string :tag "Tag")))
356 (defcustom org-export-with-special-strings t
357 "Non-nil means interpret \"\-\", \"--\" and \"---\" for export.
359 When this option is turned on, these strings will be exported as:
361 Org HTML LaTeX
362 -----+----------+--------
363 \\- &shy; \\-
364 -- &ndash; --
365 --- &mdash; ---
366 ... &hellip; \ldots
368 This option can also be set with the #+OPTIONS line,
369 e.g. \"-:nil\"."
370 :group 'org-export-general
371 :type 'boolean)
373 (defcustom org-export-with-sub-superscripts t
374 "Non-nil means interpret \"_\" and \"^\" for export.
376 When this option is turned on, you can use TeX-like syntax for
377 sub- and superscripts. Several characters after \"_\" or \"^\"
378 will be considered as a single item - so grouping with {} is
379 normally not needed. For example, the following things will be
380 parsed as single sub- or superscripts.
382 10^24 or 10^tau several digits will be considered 1 item.
383 10^-12 or 10^-tau a leading sign with digits or a word
384 x^2-y^3 will be read as x^2 - y^3, because items are
385 terminated by almost any nonword/nondigit char.
386 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
388 Still, ambiguity is possible - so when in doubt use {} to enclose
389 the sub/superscript. If you set this variable to the symbol
390 `{}', the braces are *required* in order to trigger
391 interpretations as sub/superscript. This can be helpful in
392 documents that need \"_\" frequently in plain text.
394 This option can also be set with the #+OPTIONS line,
395 e.g. \"^:nil\"."
396 :group 'org-export-general
397 :type '(choice
398 (const :tag "Interpret them" t)
399 (const :tag "Curly brackets only" {})
400 (const :tag "Do not interpret them" nil)))
402 (defcustom org-export-with-toc t
403 "Non-nil means create a table of contents in exported files.
405 The TOC contains headlines with levels up
406 to`org-export-headline-levels'. When an integer, include levels
407 up to N in the toc, this may then be different from
408 `org-export-headline-levels', but it will not be allowed to be
409 larger than the number of headline levels. When nil, no table of
410 contents is made.
412 This option can also be set with the #+OPTIONS line,
413 e.g. \"toc:nil\" or \"toc:3\"."
414 :group 'org-export-general
415 :type '(choice
416 (const :tag "No Table of Contents" nil)
417 (const :tag "Full Table of Contents" t)
418 (integer :tag "TOC to level")))
420 (defcustom org-export-with-tables t
421 "If non-nil, lines starting with \"|\" define a table.
422 For example:
424 | Name | Address | Birthday |
425 |-------------+----------+-----------|
426 | Arthur Dent | England | 29.2.2100 |
428 This option can also be set with the #+OPTIONS line, e.g. \"|:nil\"."
429 :group 'org-export-general
430 :type 'boolean)
432 (defcustom org-export-with-tags t
433 "If nil, do not export tags, just remove them from headlines.
435 If this is the symbol `not-in-toc', tags will be removed from
436 table of contents entries, but still be shown in the headlines of
437 the document.
439 This option can also be set with the #+OPTIONS line,
440 e.g. \"tags:nil\"."
441 :group 'org-export-general
442 :type '(choice
443 (const :tag "Off" nil)
444 (const :tag "Not in TOC" not-in-toc)
445 (const :tag "On" t)))
447 (defcustom org-export-with-tasks t
448 "Non-nil means include TODO items for export.
449 This may have the following values:
450 t include tasks independent of state.
451 todo include only tasks that are not yet done.
452 done include only tasks that are already done.
453 nil remove all tasks before export
454 list of keywords keep only tasks with these keywords"
455 :group 'org-export-general
456 :type '(choice
457 (const :tag "All tasks" t)
458 (const :tag "No tasks" nil)
459 (const :tag "Not-done tasks" todo)
460 (const :tag "Only done tasks" done)
461 (repeat :tag "Specific TODO keywords"
462 (string :tag "Keyword"))))
464 (defcustom org-export-time-stamp-file t
465 "Non-nil means insert a time stamp into the exported file.
466 The time stamp shows when the file was created.
468 This option can also be set with the #+OPTIONS line,
469 e.g. \"timestamp:nil\"."
470 :group 'org-export-general
471 :type 'boolean)
473 (defcustom org-export-with-timestamps t
474 "If nil, do not export time stamps and associated keywords."
475 :group 'org-export-general
476 :type 'boolean)
478 (defcustom org-export-with-todo-keywords t
479 "Non-nil means include TODO keywords in export.
480 When nil, remove all these keywords from the export.")
482 (defcustom org-export-allow-BIND 'confirm
483 "Non-nil means allow #+BIND to define local variable values for export.
484 This is a potential security risk, which is why the user must
485 confirm the use of these lines."
486 :group 'org-export-general
487 :type '(choice
488 (const :tag "Never" nil)
489 (const :tag "Always" t)
490 (const :tag "Ask a confirmation for each file" confirm)))
492 (defcustom org-export-snippet-translation-alist nil
493 "Alist between export snippets back-ends and exporter back-ends.
495 This variable allows to provide shortcuts for export snippets.
497 For example, with a value of '\(\(\"h\" . \"html\"\)\), the HTML
498 back-end will recognize the contents of \"@h{<b>}\" as HTML code
499 while every other back-end will ignore it."
500 :group 'org-export-general
501 :type '(repeat
502 (cons
503 (string :tag "Shortcut")
504 (string :tag "Back-end"))))
508 ;;; The Communication Channel
510 ;; During export process, every function has access to a number of
511 ;; properties. They are of three types:
513 ;; 1. Export options are collected once at the very beginning of the
514 ;; process, out of the original buffer and environment. The task
515 ;; is handled by `org-export-collect-options' function.
517 ;; All export options are defined through the
518 ;; `org-export-option-alist' variable.
520 ;; 2. Persistent properties are stored in
521 ;; `org-export-persistent-properties' and available at every level
522 ;; of recursion. Their value is extracted directly from the parsed
523 ;; tree, and depends on export options (whole trees may be filtered
524 ;; out of the export process).
526 ;; Properties belonging to that type are defined in the
527 ;; `org-export-persistent-properties-list' variable.
529 ;; 3. Every other property is considered local, and available at
530 ;; a precise level of recursion and below.
532 ;; Managing properties during transcode process is mainly done with
533 ;; `org-export-update-info'. Even though they come from different
534 ;; sources, the function transparently concatenates them in a single
535 ;; property list passed as an argument to each transcode function.
536 ;; Thus, during export, all necessary information is available through
537 ;; that single property list, and the element or object itself.
538 ;; Though, modifying a property will still require some special care,
539 ;; and should be done with `org-export-set-property' instead of plain
540 ;; `plist-put'.
542 ;; Here is the full list of properties available during transcode
543 ;; process, with their category (option, persistent or local), their
544 ;; value type and the function updating them, when appropriate.
546 ;; + `author' :: Author's name.
547 ;; - category :: option
548 ;; - type :: string
550 ;; + `back-end' :: Current back-end used for transcoding.
551 ;; - category :: persistent
552 ;; - type :: symbol
554 ;; + `code-refs' :: Association list between reference name and real
555 ;; labels in source code. It is used to properly
556 ;; resolve links inside source blocks.
557 ;; - category :: persistent
558 ;; - type :: alist (INT-OR-STRING . STRING)
559 ;; - update :: `org-export-handle-code'
561 ;; + `creator' :: String to write as creation information.
562 ;; - category :: option
563 ;; - type :: string
565 ;; + `date' :: String to use as date.
566 ;; - category :: option
567 ;; - type :: string
569 ;; + `description' :: Description text for the current data.
570 ;; - category :: option
571 ;; - type :: string
573 ;; + `email' :: Author's email.
574 ;; - category :: option
575 ;; - type :: string
577 ;; + `exclude-tags' :: Tags for exclusion of subtrees from export
578 ;; process.
579 ;; - category :: option
580 ;; - type :: list of strings
582 ;; + `footnote-definition-alist' :: Alist between footnote labels and
583 ;; their definition, as parsed data. Only non-inlined footnotes
584 ;; are represented in this alist. Also, every definition isn't
585 ;; guaranteed to be referenced in the parse tree. The purpose of
586 ;; this property is to preserve definitions from oblivion
587 ;; (i.e. when the parse tree comes from a part of the original
588 ;; buffer), it isn't meant for direct use in a back-end. To
589 ;; retrieve a definition relative to a reference, use
590 ;; `org-export-get-footnote-definition' instead.
591 ;; - category :: option
592 ;; - type :: alist (STRING . LIST)
594 ;; + `footnote-seen-labels' :: List of already transcoded footnote
595 ;; labels. It is used to know when a reference appears for the
596 ;; first time. (cf. `org-export-footnote-first-reference-p').
597 ;; - category :: persistent
598 ;; - type :: list of strings
599 ;; - update :: `org-export-update-info'
601 ;; + `genealogy' :: List of current element's parents types.
602 ;; - category :: local
603 ;; - type :: list of symbols
604 ;; - update :: `org-export-update-info'
606 ;; + `headline-alist' :: Alist between headlines raw name and their
607 ;; boundaries. It is used to resolve "fuzzy" links
608 ;; (cf. `org-export-resolve-fuzzy-link').
609 ;; - category :: persistent
610 ;; - type :: alist (STRING INTEGER INTEGER)
612 ;; + `headline-levels' :: Maximum level being exported as an
613 ;; headline. Comparison is done with the relative level of
614 ;; headlines in the parse tree, not necessarily with their
615 ;; actual level.
616 ;; - category :: option
617 ;; - type :: integer
619 ;; + `headline-offset' :: Difference between relative and real level
620 ;; of headlines in the parse tree. For example, a value of -1
621 ;; means a level 2 headline should be considered as level
622 ;; 1 (cf. `org-export-get-relative-level').
623 ;; - category :: persistent
624 ;; - type :: integer
626 ;; + `headline-numbering' :: Alist between headlines' beginning
627 ;; position and their numbering, as a list of numbers
628 ;; (cf. `org-export-get-headline-number').
629 ;; - category :: persistent
630 ;; - type :: alist (INTEGER . LIST)
632 ;; + `included-files' :: List of files, with full path, included in
633 ;; the current buffer, through the "#+include:" keyword. It is
634 ;; mainly used to verify that no infinite recursive inclusion
635 ;; happens.
636 ;; - category :: local
637 ;; - type :: list of strings
639 ;; + `inherited-properties' :: Properties of the headline ancestors
640 ;; of the current element or object. Those from the closest
641 ;; headline have precedence over the others.
642 ;; - category :: local
643 ;; - type :: plist
645 ;; + `keywords' :: List of keywords attached to data.
646 ;; - category :: option
647 ;; - type :: string
649 ;; + `language' :: Default language used for translations.
650 ;; - category :: option
651 ;; - type :: string
653 ;; + `parent-properties' :: Properties of the parent element.
654 ;; - category :: local
655 ;; - type :: plist
656 ;; - update :: `org-export-update-info'
658 ;; + `parse-tree' :: Whole parse tree, available at any time during
659 ;; transcoding.
660 ;; - category :: global
661 ;; - type :: list (as returned by `org-element-parse-buffer')
663 ;; + `point-max' :: Last ending position in the parse tree.
664 ;; - category :: global
665 ;; - type :: integer
667 ;; + `preserve-breaks' :: Non-nil means transcoding should preserve
668 ;; all line breaks.
669 ;; - category :: option
670 ;; - type :: symbol (nil, t)
672 ;; + `previous-element' :: Previous element's type at the same
673 ;; level.
674 ;; - category :: local
675 ;; - type :: symbol
676 ;; - update :: `org-export-update-info'
678 ;; + `previous-object' :: Previous object type (or `plain-text') at
679 ;; the same level.
680 ;; - category :: local
681 ;; - type :: symbol
682 ;; - update :: `org-export-update-info'
684 ;; + `section-numbers' :: Non-nil means transcoding should add
685 ;; section numbers to headlines.
686 ;; - category :: option
687 ;; - type :: symbol (nil, t)
689 ;; + `select-tags' :: List of tags enforcing inclusion of sub-trees in
690 ;; transcoding. When such a tag is present,
691 ;; subtrees without it are de facto excluded from
692 ;; the process. See `use-select-tags'.
693 ;; - category :: option
694 ;; - type :: list of strings
696 ;; + `target-list' :: List of targets raw names encoutered in the
697 ;; parse tree. This is used to partly resolve
698 ;; "fuzzy" links
699 ;; (cf. `org-export-resolve-fuzzy-link').
700 ;; - category :: persistent
701 ;; - type :: list of strings
703 ;; + `time-stamp-file' :: Non-nil means transcoding should insert
704 ;; a time stamp in the output.
705 ;; - category :: option
706 ;; - type :: symbol (nil, t)
708 ;; + `total-loc' :: Contains total lines of code accumulated by source
709 ;; blocks with the "+n" option so far.
710 ;; - category :: persistent
711 ;; - type :: integer
712 ;; - update :: `org-export-handle-code'
714 ;; + `use-select-tags' :: When non-nil, a select tags has been found
715 ;; in the parse tree. Thus, any headline without one will be
716 ;; filtered out. See `select-tags'.
717 ;; - category :: persistent
718 ;; - type :: interger or nil
720 ;; + `with-archived-trees' :: Non-nil when archived subtrees should
721 ;; also be transcoded. If it is set to the `headline' symbol,
722 ;; only the archived headline's name is retained.
723 ;; - category :: option
724 ;; - type :: symbol (nil, t, `headline')
726 ;; + `with-author' :: Non-nil means author's name should be included
727 ;; in the output.
728 ;; - category :: option
729 ;; - type :: symbol (nil, t)
731 ;; + `with-creator' :: Non-nild means a creation sentence should be
732 ;; inserted at the end of the transcoded string. If the value
733 ;; is `comment', it should be commented.
734 ;; - category :: option
735 ;; - type :: symbol (`comment', nil, t)
737 ;; + `with-drawers' :: Non-nil means drawers should be exported. If
738 ;; its value is a list of names, only drawers with such names
739 ;; will be transcoded.
740 ;; - category :: option
741 ;; - type :: symbol (nil, t) or list of strings
743 ;; + `with-email' :: Non-nil means output should contain author's
744 ;; email.
745 ;; - category :: option
746 ;; - type :: symbol (nil, t)
748 ;; + `with-emphasize' :: Non-nil means emphasized text should be
749 ;; interpreted.
750 ;; - category :: option
751 ;; - type :: symbol (nil, t)
753 ;; + `with-fixed-width' :: Non-nil if transcoder should interpret
754 ;; strings starting with a colon as a fixed-with (verbatim)
755 ;; area.
756 ;; - category :: option
757 ;; - type :: symbol (nil, t)
759 ;; + `with-footnotes' :: Non-nil if transcoder should interpret
760 ;; footnotes.
761 ;; - category :: option
762 ;; - type :: symbol (nil, t)
764 ;; + `with-priority' :: Non-nil means transcoding should include
765 ;; priority cookies.
766 ;; - category :: option
767 ;; - type :: symbol (nil, t)
769 ;; + `with-special-strings' :: Non-nil means transcoding should
770 ;; interpret special strings in plain text.
771 ;; - category :: option
772 ;; - type :: symbol (nil, t)
774 ;; + `with-sub-superscript' :: Non-nil means transcoding should
775 ;; interpret subscript and superscript. With a value of "{}",
776 ;; only interpret those using curly brackets.
777 ;; - category :: option
778 ;; - type :: symbol (nil, {}, t)
780 ;; + `with-tables' :: Non-nil means transcoding should interpret
781 ;; tables.
782 ;; - category :: option
783 ;; - type :: symbol (nil, t)
785 ;; + `with-tags' :: Non-nil means transcoding should keep tags in
786 ;; headlines. A `not-in-toc' value will remove them
787 ;; from the table of contents, if any, nonetheless.
788 ;; - category :: option
789 ;; - type :: symbol (nil, t, `not-in-toc')
791 ;; + `with-tasks' :: Non-nil means transcoding should include
792 ;; headlines with a TODO keyword. A `todo' value
793 ;; will only include headlines with a todo type
794 ;; keyword while a `done' value will do the
795 ;; contrary. If a list of strings is provided, only
796 ;; tasks with keywords belonging to that list will
797 ;; be kept.
798 ;; - category :: option
799 ;; - type :: symbol (t, todo, done, nil) or list of strings
801 ;; + `with-timestamps' :: Non-nil means transcoding should include
802 ;; time stamps and associated keywords. Otherwise, completely
803 ;; remove them.
804 ;; - category :: option
805 ;; - type :: symbol: (t, nil)
807 ;; + `with-toc' :: Non-nil means that a table of contents has to be
808 ;; added to the output. An integer value limits its
809 ;; depth.
810 ;; - category :: option
811 ;; - type :: symbol (nil, t or integer)
813 ;; + `with-todo-keywords' :: Non-nil means transcoding should
814 ;; include TODO keywords.
815 ;; - category :: option
816 ;; - type :: symbol (nil, t)
818 ;;;; Export Options
820 ;; Export options come from five sources, in increasing precedence
821 ;; order:
823 ;; - Global variables,
824 ;; - External options provided at export time,
825 ;; - Options keyword symbols,
826 ;; - Buffer keywords,
827 ;; - Subtree properties.
829 ;; The central internal function with regards to export options is
830 ;; `org-export-collect-options'. It updates global variables with
831 ;; "#+BIND:" keywords, then retrieve and prioritize properties from
832 ;; the different sources.
834 ;; The internal functions doing the retrieval are:
835 ;; `org-export-parse-option-keyword' ,
836 ;; `org-export-get-subtree-options' ,
837 ;; `org-export-get-inbuffer-options' and
838 ;; `org-export-get-global-options'.
840 ;; Some properties do not rely on the previous sources but still
841 ;; depend on the original buffer are taken care of in
842 ;; `org-export-initial-options'.
844 ;; Also, `org-export-confirm-letbind' and `org-export-install-letbind'
845 ;; take care of the part relative to "#+BIND:" keywords.
847 (defun org-export-collect-options (backend subtreep ext-plist)
848 "Collect export options from the current buffer.
850 BACKEND is a symbol specifying the back-end to use.
852 When SUBTREEP is non-nil, assume the export is done against the
853 current sub-tree.
855 EXT-PLIST is a property list with external parameters overriding
856 org-mode's default settings, but still inferior to file-local
857 settings."
858 ;; First install #+BIND variables.
859 (org-export-install-letbind-maybe)
860 ;; Get and prioritize export options...
861 (let ((options (org-combine-plists
862 ;; ... from global variables...
863 (org-export-get-global-options backend)
864 ;; ... from an external property list...
865 ext-plist
866 ;; ... from in-buffer settings...
867 (org-export-get-inbuffer-options
868 (org-with-wide-buffer (buffer-string)) backend
869 (and buffer-file-name
870 (org-remove-double-quotes buffer-file-name)))
871 ;; ... and from subtree, when appropriate.
872 (and subtreep
873 (org-export-get-subtree-options)))))
874 ;; Add initial options.
875 (setq options (append (org-export-initial-options options)
876 options))
877 ;; Set a default title if none has been specified so far.
878 (unless (plist-get options :title)
879 (setq options (plist-put options :title
880 (or (and buffer-file-name
881 (file-name-sans-extension
882 (file-name-nondirectory
883 buffer-file-name)))
884 (buffer-name)))))
885 ;; Return plist.
886 options))
888 (defun org-export-parse-option-keyword (options backend)
889 "Parse an OPTIONS line and return values as a plist.
890 BACKEND is a symbol specifying the back-end to use."
891 (let* ((all (append org-export-option-alist
892 (let ((var (intern
893 (format "org-%s-option-alist" backend))))
894 (and (boundp var) (eval var)))))
895 ;; Build an alist between #+OPTION: item and property-name.
896 (alist (delq nil
897 (mapcar (lambda (e)
898 (when (nth 2 e) (cons (regexp-quote (nth 2 e))
899 (car e))))
900 all)))
901 plist)
902 (mapc (lambda (e)
903 (when (string-match (concat "\\(\\`\\|[ \t]\\)"
904 (car e)
905 ":\\(([^)\n]+)\\|[^ \t\n\r;,.]*\\)")
906 options)
907 (setq plist (plist-put plist
908 (cdr e)
909 (car (read-from-string
910 (match-string 2 options)))))))
911 alist)
912 plist))
914 (defun org-export-get-subtree-options ()
915 "Get export options in subtree at point.
916 Return the options as a plist."
917 (org-with-wide-buffer
918 (when (ignore-errors (org-back-to-heading t))
919 (let (prop plist)
920 (when (setq prop (progn (looking-at org-todo-line-regexp)
921 (or (org-entry-get (point) "EXPORT_TITLE")
922 (org-match-string-no-properties 3))))
923 (setq plist (plist-put plist :title prop)))
924 (when (setq prop (org-entry-get (point) "EXPORT_TEXT"))
925 (setq plist (plist-put plist :text prop)))
926 (when (setq prop (org-entry-get (point) "EXPORT_AUTHOR"))
927 (setq plist (plist-put plist :author prop)))
928 (when (setq prop (org-entry-get (point) "EXPORT_DATE"))
929 (setq plist (plist-put plist :date prop)))
930 (when (setq prop (org-entry-get (point) "EXPORT_OPTIONS"))
931 (setq plist (org-export-add-options-to-plist plist prop)))
932 plist))))
934 (defun org-export-get-inbuffer-options (buffer-string backend files)
935 "Return in-buffer options as a plist.
936 BUFFER-STRING is the string of the buffer. BACKEND is a symbol
937 specifying which back-end should be used."
938 (let ((case-fold-search t) plist)
939 ;; 1. Special keywords, as in `org-export-special-keywords'.
940 (let ((start 0)
941 (special-re (org-make-options-regexp org-export-special-keywords)))
942 (while (string-match special-re buffer-string start)
943 (setq start (match-end 0))
944 (let ((key (upcase (org-match-string-no-properties 1 buffer-string)))
945 ;; Special keywords do not have their value expanded.
946 (val (org-match-string-no-properties 2 buffer-string)))
947 (setq plist
948 (org-combine-plists
949 (cond
950 ((string= key "SETUP_FILE")
951 (let ((file (expand-file-name
952 (org-remove-double-quotes (org-trim val)))))
953 ;; Avoid circular dependencies.
954 (unless (member file files)
955 (org-export-get-inbuffer-options
956 (org-file-contents file 'noerror)
957 backend
958 (cons file files)))))
959 ((string= key "OPTIONS")
960 (org-export-parse-option-keyword val backend))
961 ((string= key "MACRO")
962 (string-match "^\\([-a-zA-Z0-9_]+\\)[ \t]+\\(.*?[ \t]*$\\)"
963 val)
964 (plist-put nil
965 (intern (concat ":macro-"
966 (downcase (match-string 1 val))))
967 (match-string 2 val))))
968 plist)))))
969 ;; 2. Standard options, as in `org-export-option-alist'.
970 (let* ((all (append org-export-option-alist
971 (let ((var (intern
972 (format "org-%s-option-alist" backend))))
973 (and (boundp var) (eval var)))))
974 ;; Build alist between keyword name and property name.
975 (alist (delq nil (mapcar (lambda (e)
976 (when (nth 1 e) (cons (nth 1 e) (car e))))
977 all)))
978 ;; Build regexp matching all keywords associated to export
979 ;; options. Note: the search is case insensitive.
980 (opt-re (org-make-options-regexp
981 (delq nil (mapcar (lambda (e) (nth 1 e)) all))))
982 (start 0))
983 (while (string-match opt-re buffer-string start)
984 (setq start (match-end 0))
985 (let* ((key (upcase (org-match-string-no-properties 1 buffer-string)))
986 ;; Expand value, applying restrictions for keywords.
987 (val (org-match-string-no-properties 2 buffer-string))
988 (prop (cdr (assoc key alist)))
989 (behaviour (nth 4 (assq prop all))))
990 (setq plist
991 (plist-put
992 plist prop
993 ;; Handle value depending on specified BEHAVIOUR.
994 (case behaviour
995 (space (if (plist-get plist prop)
996 (concat (plist-get plist prop) " " (org-trim val))
997 (org-trim val)))
998 (newline (org-trim
999 (concat
1000 (plist-get plist prop) "\n" (org-trim val))))
1001 (split `(,@(plist-get plist prop) ,@(org-split-string val)))
1002 ('t val)
1003 (otherwise (plist-get plist prop)))))))
1004 ;; Parse keywords specified in `org-element-parsed-keywords'.
1005 (mapc
1006 (lambda (key)
1007 (let* ((prop (cdr (assoc (upcase key) alist)))
1008 (value (and prop (plist-get plist prop))))
1009 (when (stringp value)
1010 (setq plist
1011 (plist-put
1012 plist prop
1013 (org-element-parse-secondary-string
1014 value
1015 (cdr (assq 'keyword org-element-string-restrictions))))))))
1016 org-element-parsed-keywords))
1017 ;; Return final value.
1018 plist))
1020 (defun org-export-get-global-options (backend)
1021 "Return global export options as a plist.
1022 BACKEND is a symbol specifying which back-end should be used."
1023 (let ((all (append org-export-option-alist
1024 (let ((var (intern
1025 (format "org-%s-option-alist" backend))))
1026 (and (boundp var) (eval var)))))
1027 ;; Output value.
1028 plist)
1029 (mapc (lambda (cell)
1030 (setq plist
1031 (plist-put plist (car cell) (eval (nth 3 cell)))))
1032 all)
1033 ;; Return value.
1034 plist))
1036 (defun org-export-initial-options (options)
1037 "Return a plist with non-optional properties.
1038 OPTIONS is the export options plist computed so far."
1039 (list
1040 ;; `:macro-date', `:macro-time' and `:macro-property' could as well
1041 ;; be initialized as persistent properties, since they don't depend
1042 ;; on initial environment. Though, it may be more logical to keep
1043 ;; them close to other ":macro-" properties.
1044 :macro-date "(eval (format-time-string \"$1\"))"
1045 :macro-time "(eval (format-time-string \"$1\"))"
1046 :macro-property "(eval (org-entry-get nil \"$1\" 'selective))"
1047 :macro-modification-time
1048 (and (buffer-file-name)
1049 (file-exists-p (buffer-file-name))
1050 (concat "(eval (format-time-string \"$1\" '"
1051 (prin1-to-string (nth 5 (file-attributes (buffer-file-name))))
1052 "))"))
1053 :macro-input-file (and (buffer-file-name)
1054 (file-name-nondirectory (buffer-file-name)))
1055 ;; Footnotes definitions must be collected in the original buffer,
1056 ;; as there's no insurance that they will still be in the parse
1057 ;; tree, due to some narrowing.
1058 :footnote-definition-alist
1059 (let (alist)
1060 (org-with-wide-buffer
1061 (goto-char (point-min))
1062 (while (re-search-forward org-footnote-definition-re nil t)
1063 (let ((def (org-footnote-at-definition-p)))
1064 (when def
1065 (org-skip-whitespace)
1066 (push (cons (car def)
1067 (save-restriction
1068 (narrow-to-region (point) (nth 2 def))
1069 (org-element-parse-buffer)))
1070 alist))))
1071 alist))))
1073 (defvar org-export-allow-BIND-local nil)
1074 (defun org-export-confirm-letbind ()
1075 "Can we use #+BIND values during export?
1076 By default this will ask for confirmation by the user, to divert
1077 possible security risks."
1078 (cond
1079 ((not org-export-allow-BIND) nil)
1080 ((eq org-export-allow-BIND t) t)
1081 ((local-variable-p 'org-export-allow-BIND-local) org-export-allow-BIND-local)
1082 (t (org-set-local 'org-export-allow-BIND-local
1083 (yes-or-no-p "Allow BIND values in this buffer? ")))))
1085 (defun org-export-install-letbind-maybe ()
1086 "Install the values from #+BIND lines as local variables.
1087 Variables must be installed before in-buffer options are
1088 retrieved."
1089 (let (letbind pair)
1090 (org-with-wide-buffer
1091 (goto-char (point-min))
1092 (while (re-search-forward (org-make-options-regexp '("BIND")) nil t)
1093 (when (org-export-confirm-letbind)
1094 (push (read (concat "(" (org-match-string-no-properties 2) ")"))
1095 letbind))))
1096 (while (setq pair (pop letbind))
1097 (org-set-local (car pair) (nth 1 pair)))))
1100 ;;;; Persistent Properties
1102 ;; Persistent properties are declared in
1103 ;; `org-export-persistent-properties-list' variable. Most of them are
1104 ;; initialized at the beginning of the transcoding process by
1105 ;; `org-export-initialize-persistent-properties'. The others are
1106 ;; updated during that process.
1108 ;; Dedicated functions focus on computing the value of specific
1109 ;; persistent properties during initialization. Thus,
1110 ;; `org-export-use-select-tag-p' determines if an headline makes use
1111 ;; of an export tag enforcing inclusion. `org-export-get-min-level'
1112 ;; gets the minimal exportable level, used as a basis to compute
1113 ;; relative level for headlines. `org-export-get-point-max' returns
1114 ;; the maximum exportable ending position in the parse tree.
1115 ;; Eventually `org-export-collect-headline-numbering' builds an alist
1116 ;; between headlines' beginning position and their numbering.
1118 (defconst org-export-persistent-properties-list
1119 '(:back-end :code-refs :headline-alist :headline-numbering :headline-offset
1120 :parse-tree :point-max :footnote-seen-labels :target-list
1121 :total-loc :use-select-tags)
1122 "List of persistent properties.")
1124 (defconst org-export-persistent-properties nil
1125 "Used internally to store properties and values during transcoding.
1127 Only properties that should survive recursion are saved here.
1129 This variable is reset before each transcoding.")
1131 (defun org-export-initialize-persistent-properties (data options backend)
1132 "Initialize `org-export-persistent-properties'.
1134 DATA is the parse tree from which information is retrieved.
1135 OPTIONS is a list holding export options. BACKEND is the
1136 back-end called for transcoding, as a symbol.
1138 Following initial persistent properties are set:
1139 `:back-end' Back-end used for transcoding.
1141 `:headline-alist' Alist of all headlines' name as key and a list
1142 holding beginning and ending positions as
1143 value.
1145 `:headline-offset' Offset between true level of headlines and
1146 local level. An offset of -1 means an headline
1147 of level 2 should be considered as a level
1148 1 headline in the context.
1150 `:headline-numbering' Alist of all headlines' beginning position
1151 as key an the associated numbering as value.
1153 `:parse-tree' Whole parse tree.
1155 `:point-max' Last position in the parse tree
1157 `:target-list' List of all targets' raw name in the parse tree.
1159 `:use-select-tags' Non-nil when parsed tree use a special tag to
1160 enforce transcoding of the headline."
1161 ;; First delete any residual persistent property.
1162 (setq org-export-persistent-properties nil)
1163 ;; Immediately after, set `:use-select-tags' property, as it will be
1164 ;; required for further computations.
1165 (setq options
1166 (org-export-set-property
1167 options
1168 :use-select-tags
1169 (org-export-use-select-tags-p data options)))
1170 ;; Get the rest of the initial persistent properties, now
1171 ;; `:use-select-tags' is set...
1172 ;; 1. `:parse-tree' ...
1173 (setq options (org-export-set-property options :parse-tree data))
1174 ;; 2. `:headline-offset' ...
1175 (setq options
1176 (org-export-set-property
1177 options :headline-offset
1178 (- 1 (org-export-get-min-level data options))))
1179 ;; 3. `:point-max' ...
1180 (setq options (org-export-set-property
1181 options :point-max
1182 (org-export-get-point-max data options)))
1183 ;; 4. `:target-list'...
1184 (setq options (org-export-set-property
1185 options :target-list
1186 (org-element-map
1187 data 'target
1188 (lambda (target info)
1189 (org-element-get-property :raw-value target)))))
1190 ;; 5. `:headline-alist'
1191 (setq options (org-export-set-property
1192 options :headline-alist
1193 (org-element-map
1194 data 'headline
1195 (lambda (headline info)
1196 (list (org-element-get-property :raw-value headline)
1197 (org-element-get-property :begin headline)
1198 (org-element-get-property :end headline))))))
1199 ;; 6. `:headline-numbering'
1200 (setq options (org-export-set-property
1201 options :headline-numbering
1202 (org-export-collect-headline-numbering data options)))
1203 ;; 7. `:back-end'
1204 (setq options (org-export-set-property options :back-end backend)))
1206 (defun org-export-use-select-tags-p (data options)
1207 "Non-nil when data use a tag enforcing transcoding.
1208 DATA is parsed data as returned by `org-element-parse-buffer'.
1209 OPTIONS is a plist holding export options."
1210 (org-element-map
1211 data
1212 'headline
1213 (lambda (headline info)
1214 (let ((tags (org-element-get-property :with-tags headline)))
1215 (and tags (string-match
1216 (format ":%s:" (plist-get info :select-tags)) tags))))
1217 options
1218 'stop-at-first-match))
1220 (defun org-export-get-min-level (data options)
1221 "Return minimum exportable headline's level in DATA.
1222 DATA is parsed tree as returned by `org-element-parse-buffer'.
1223 OPTIONS is a plist holding export options."
1224 (catch 'exit
1225 (let ((min-level 10000))
1226 (mapc (lambda (blob)
1227 (when (and (eq (car blob) 'headline)
1228 (not (org-export-skip-p blob options)))
1229 (setq min-level
1230 (min (org-element-get-property :level blob) min-level)))
1231 (when (= min-level 1) (throw 'exit 1)))
1232 (org-element-get-contents data))
1233 ;; If no headline was found, for the sake of consistency, set
1234 ;; minimum level to 1 nonetheless.
1235 (if (= min-level 10000) 1 min-level))))
1237 (defun org-export-get-point-max (data options)
1238 "Return last exportable ending position in DATA.
1239 DATA is parsed tree as returned by `org-element-parse-buffer'.
1240 OPTIONS is a plist holding export options."
1241 (let ((pos-max 1))
1242 (mapc (lambda (blob)
1243 (unless (and (eq (car blob) 'headline)
1244 (org-export-skip-p blob options))
1245 (setq pos-max (org-element-get-property :end blob))))
1246 (org-element-get-contents data))
1247 pos-max))
1249 (defun org-export-collect-headline-numbering (data options)
1250 "Return numbering of all exportable headlines in a parse tree.
1252 DATA is the parse tree. OPTIONS is the plist holding export
1253 options.
1255 Return an alist whose key is headline's beginning position and
1256 value is its associated numbering (in the shape of a list of
1257 numbers)."
1258 (let ((numbering (make-vector org-export-max-depth 0)))
1259 (org-element-map
1260 data
1261 'headline
1262 (lambda (headline info)
1263 (let ((relative-level (1- (org-export-get-relative-level blob info))))
1264 (cons
1265 (org-element-get-property :begin headline)
1266 (loop for n across numbering
1267 for idx from 0 to org-export-max-depth
1268 when (< idx relative-level) collect n
1269 when (= idx relative-level) collect (aset numbering idx (1+ n))
1270 when (> idx relative-level) do (aset numbering idx 0)))))
1271 options)))
1274 ;;;; Properties Management
1276 ;; This is mostly done with the help of two functions. On the one
1277 ;; hand `org-export-update-info' is used to keep up-to-date local
1278 ;; information while walking the nested list representing the parsed
1279 ;; document. On the other end, `org-export-set-property' handles
1280 ;; properties modifications according to their type (persistent or
1281 ;; local).
1283 ;; As exceptions, `:code-refs' and `:total-loc' properties are updated
1284 ;; with `org-export-handle-code' function.
1286 (defun org-export-update-info (blob info recursep)
1287 "Update export options depending on context.
1289 BLOB is the element or object being parsed. INFO is the plist
1290 holding the export options.
1292 When RECURSEP is non-nil, assume the following element or object
1293 will be inside the current one.
1295 The following properties are updated:
1296 `footnote-seen-labels' List of already parsed footnote
1297 labels (string list)
1298 `genealogy' List of current element's parents
1299 (symbol list).
1300 `inherited-properties' List of inherited properties from
1301 parent headlines (plist).
1302 `parent-properties' List of last element's properties
1303 (plist).
1304 `previous-element' Previous element's type (symbol).
1305 `previous-object' Previous object's type (symbol).
1307 Return the property list."
1308 (let* ((type (and (not (stringp blob)) (car blob))))
1309 (cond
1310 ;; Case 1: We're moving into a recursive blob.
1311 (recursep
1312 (org-combine-plists
1313 info
1314 `(:genealogy ,(cons type (plist-get info :genealogy))
1315 :previous-element nil
1316 :previous-object nil
1317 :parent-properties
1318 ,(if (memq type org-element-all-elements)
1319 (nth 1 blob)
1320 (plist-get info :parent-properties))
1321 :inherited-properties
1322 ,(if (eq type 'headline)
1323 (org-combine-plists
1324 (plist-get info :inherited-properties) (nth 1 blob))
1325 (plist-get info :inherited-properties)))
1326 ;; Add persistent properties.
1327 org-export-persistent-properties))
1328 ;; Case 2: No recursion.
1330 ;; At a footnote reference: mark its label as seen, if not
1331 ;; already the case.
1332 (when (eq type 'footnote-reference)
1333 (let ((label (org-element-get-property :label blob))
1334 (seen-labels (plist-get org-export-persistent-properties
1335 :footnote-seen-labels)))
1336 ;; Store anonymous footnotes (nil label) without checking if
1337 ;; another anonymous footnote was seen before.
1338 (unless (and label (member label seen-labels))
1339 (setq info (org-export-set-property
1340 info :footnote-seen-labels (push label seen-labels))))))
1341 ;; Set `:previous-element' or `:previous-object' according to
1342 ;; BLOB.
1343 (setq info (cond ((not type)
1344 (org-export-set-property
1345 info :previous-object 'plain-text))
1346 ((memq type org-element-all-elements)
1347 (org-export-set-property info :previous-element type))
1348 (t (org-export-set-property info :previous-object type))))
1349 ;; Return updated value.
1350 info))))
1352 (defun org-export-set-property (info prop value)
1353 "Set property PROP to VALUE in plist INFO.
1354 Return the new plist."
1355 (when (memq prop org-export-persistent-properties-list)
1356 (setq org-export-persistent-properties
1357 (plist-put org-export-persistent-properties prop value)))
1358 (plist-put info prop value))
1362 ;;; The Transcoder
1364 ;; This function reads Org data (obtained with, i.e.
1365 ;; `org-element-parse-buffer') and transcodes it into a specified
1366 ;; back-end output. It takes care of updating local properties,
1367 ;; filtering out elements or objects according to export options and
1368 ;; organizing the output blank lines and white space are preserved.
1370 ;; Though, this function is inapropriate for secondary strings, which
1371 ;; require a fresh copy of the plist passed as INFO argument. Thus,
1372 ;; `org-export-secondary-string' is provided for that specific task.
1374 ;; Internally, three functions handle the filtering of objects and
1375 ;; elements during the export. More precisely, `org-export-skip-p'
1376 ;; determines if the considered object or element should be ignored
1377 ;; altogether, `org-export-interpret-p' tells which elements or
1378 ;; objects should be seen as real Org syntax and `org-export-expand'
1379 ;; transforms the others back into their original shape.
1381 (defun org-export-data (data backend info)
1382 "Convert DATA to a string into BACKEND format.
1384 DATA is a nested list as returned by `org-element-parse-buffer'.
1386 BACKEND is a symbol among supported exporters.
1388 INFO is a plist holding export options and also used as
1389 a communication channel between elements when walking the nested
1390 list. See `org-export-update-info' function for more
1391 details.
1393 Return transcoded string."
1394 (mapconcat
1395 ;; BLOB can be an element, an object, a string, or nil.
1396 (lambda (blob)
1397 (cond
1398 ((not blob) nil) ((equal blob "") nil)
1399 ;; BLOB is a string. Check if the optional transcoder for plain
1400 ;; text exists, and call it in that case. Otherwise, simply
1401 ;; return string. Also update INFO and call
1402 ;; `org-export-filter-plain-text-functions'.
1403 ((stringp blob)
1404 (setq info (org-export-update-info blob info nil))
1405 (let ((transcoder (intern (format "org-%s-plain-text" backend))))
1406 (org-export-filter-apply-functions
1407 org-export-filter-plain-text-functions
1408 (if (fboundp transcoder) (funcall transcoder blob info) blob)
1409 backend)))
1410 ;; BLOB is an element or an object.
1412 (let* ((type (if (stringp blob) 'plain-text (car blob)))
1413 ;; 1. Determine the appropriate TRANSCODER.
1414 (transcoder
1415 (cond
1416 ;; 1.0 A full Org document is inserted.
1417 ((eq type 'org-data) 'identity)
1418 ;; 1.1. BLOB should be ignored.
1419 ((org-export-skip-p blob info) nil)
1420 ;; 1.2. BLOB shouldn't be transcoded. Interpret it
1421 ;; back into Org syntax.
1422 ((not (org-export-interpret-p blob info))
1423 'org-export-expand)
1424 ;; 1.3. Else apply naming convention.
1425 (t (let ((trans (intern
1426 (format "org-%s-%s" backend type))))
1427 (and (fboundp trans) trans)))))
1428 ;; 2. Compute CONTENTS of BLOB.
1429 (contents
1430 (cond
1431 ;; Case 0. No transcoder defined: ignore BLOB.
1432 ((not transcoder) nil)
1433 ;; Case 1. Transparently export an Org document.
1434 ((eq type 'org-data)
1435 (org-export-data blob backend info))
1436 ;; Case 2. For a recursive object.
1437 ((memq type org-element-recursive-objects)
1438 (org-export-data
1439 blob backend (org-export-update-info blob info t)))
1440 ;; Case 3. For a recursive element.
1441 ((memq type org-element-greater-elements)
1442 ;; Ignore contents of an archived tree
1443 ;; when `:with-archived-trees' is `headline'.
1444 (unless (and
1445 (eq type 'headline)
1446 (eq (plist-get info :with-archived-trees) 'headline)
1447 (org-element-get-property :archivedp blob))
1448 (org-element-normalize-string
1449 (org-export-data
1450 blob backend (org-export-update-info blob info t)))))
1451 ;; Case 4. For a paragraph.
1452 ((eq type 'paragraph)
1453 (let ((paragraph
1454 (org-element-normalize-contents
1455 blob
1456 ;; When normalizing contents of an item or
1457 ;; a footnote definition, ignore first line's
1458 ;; indentation: there is none and it might be
1459 ;; misleading.
1460 (and (not (plist-get info :previous-element))
1461 (let ((parent (car (plist-get info :genealogy))))
1462 (memq parent '(footnote-definition item)))))))
1463 (org-export-data
1464 paragraph
1465 backend
1466 (org-export-update-info blob info t))))))
1467 ;; 3. Transcode BLOB into RESULTS string.
1468 (results (cond
1469 ((not transcoder) nil)
1470 ((eq transcoder 'org-export-expand)
1471 (org-export-data
1472 `(org-data nil ,(funcall transcoder blob contents))
1473 backend info))
1474 (t (funcall transcoder blob contents info)))))
1475 ;; 4. Discard nil results. Otherwise, update INFO, append
1476 ;; the same white space between elements or objects as in
1477 ;; the original buffer, and call appropriate filters.
1478 (when results
1479 (setq info (org-export-update-info blob info nil))
1480 ;; No filter for a full document.
1481 (if (eq type 'org-data)
1482 results
1483 (org-export-filter-apply-functions
1484 (eval (intern (format "org-export-filter-%s-functions" type)))
1485 (if (memq type org-element-all-elements)
1486 (concat
1487 (org-element-normalize-string results)
1488 (make-string (org-element-get-property :post-blank blob) 10))
1489 (concat
1490 results
1491 (make-string
1492 (org-element-get-property :post-blank blob) 32)))
1493 backend)))))))
1494 (org-element-get-contents data) ""))
1496 (defun org-export-secondary-string (secondary backend info)
1497 "Convert SECONDARY string into BACKEND format.
1499 SECONDARY is a nested list as returned by
1500 `org-element-parse-secondary-string'.
1502 BACKEND is a symbol among supported exporters.
1504 INFO is a plist holding export options and also used as
1505 a communication channel between elements when walking the nested
1506 list. See `org-export-update-info' function for more
1507 details.
1509 Return transcoded string."
1510 ;; Make SECONDARY acceptable for `org-export-data'.
1511 (let ((s (if (listp secondary) secondary (list secondary))))
1512 (org-export-data `(org-data nil ,@s) backend (copy-sequence info))))
1514 (defun org-export-skip-p (blob info)
1515 "Non-nil when element or object BLOB should be skipped during export.
1516 INFO is the plist holding export options."
1517 ;; Check headline.
1518 (unless (stringp blob)
1519 (case (car blob)
1520 ('headline
1521 (let ((with-tasks (plist-get info :with-tasks))
1522 (todo (org-element-get-property :todo-keyword blob))
1523 (todo-type (org-element-get-property :todo-type blob))
1524 (archived (plist-get info :with-archived-trees))
1525 (tag-list (let ((tags (org-element-get-property :tags blob)))
1526 (and tags (org-split-string tags ":")))))
1528 ;; Ignore subtrees with an exclude tag.
1529 (loop for k in (plist-get info :exclude-tags)
1530 thereis (member k tag-list))
1531 ;; Ignore subtrees without a select tag, when such tag is found
1532 ;; in the buffer.
1533 (and (plist-get info :use-select-tags)
1534 (loop for k in (plist-get info :select-tags)
1535 never (member k tag-list)))
1536 ;; Ignore commented sub-trees.
1537 (org-element-get-property :commentedp blob)
1538 ;; Ignore archived subtrees if `:with-archived-trees' is nil.
1539 (and (not archived) (org-element-get-property :archivedp blob))
1540 ;; Ignore tasks, if specified by `:with-tasks' property.
1541 (and todo (not with-tasks))
1542 (and todo
1543 (memq with-tasks '(todo done))
1544 (not (eq todo-type with-tasks)))
1545 (and todo
1546 (consp with-tasks)
1547 (not (member todo with-tasks))))))
1548 ;; Check time-stamp.
1549 ('time-stamp (not (plist-get info :with-timestamps)))
1550 ;; Check drawer.
1551 ('drawer
1552 (or (not (plist-get info :with-drawers))
1553 (and (consp (plist-get info :with-drawers))
1554 (not (member (org-element-get-property :drawer-name blob)
1555 (plist-get info :with-drawers))))))
1556 ;; Check export snippet.
1557 ('export-snippet
1558 (let* ((raw-back-end (org-element-get-property :back-end blob))
1559 (true-back-end
1560 (or (cdr (assoc raw-back-end org-export-snippet-translation-alist))
1561 raw-back-end)))
1562 (not (string= (symbol-name (plist-get info :back-end))
1563 true-back-end)))))))
1565 (defun org-export-interpret-p (blob info)
1566 "Non-nil if element or object BLOB should be interpreted as Org syntax.
1567 Check is done according to export options INFO, stored as
1568 a plist."
1569 (case (car blob)
1570 ;; ... entities...
1571 (entity (plist-get info :with-entities))
1572 ;; ... emphasis...
1573 (emphasis (plist-get info :with-emphasize))
1574 ;; ... fixed-width areas.
1575 (fixed-width (plist-get info :with-fixed-width))
1576 ;; ... footnotes...
1577 ((footnote-definition footnote-reference)
1578 (plist-get info :with-footnotes))
1579 ;; ... sub/superscripts...
1580 ((subscript superscript)
1581 (let ((sub/super-p (plist-get info :with-sub-superscript)))
1582 (if (eq sub/super-p '{})
1583 (org-element-get-property :use-brackets-p blob)
1584 sub/super-p)))
1585 ;; ... tables...
1586 (table (plist-get info :with-tables))
1587 (otherwise t)))
1589 (defsubst org-export-expand (blob contents)
1590 "Expand a parsed element or object to its original state.
1591 BLOB is either an element or an object. CONTENTS is its
1592 contents, as a string or nil."
1593 (funcall
1594 (intern (format "org-element-%s-interpreter" (car blob))) blob contents))
1598 ;;; The Filter System
1600 ;; Filters allow end-users to tweak easily the transcoded output.
1601 ;; They are the functional counterpart of hooks, as every filter in
1602 ;; a set is applied to the return value of the previous one.
1604 ;; Every set is back-end agnostic. Although, a filter is always
1605 ;; called, in addition to the string it applies to, with the back-end
1606 ;; used as argument, so it's easy enough for the end-user to add
1607 ;; back-end specific filters in the set.
1609 ;; Filters sets are defined below. There are of four types:
1611 ;; - `org-export-filter-parse-tree-functions' applies directly on the
1612 ;; complete parsed tree. It's the only filters set that doesn't
1613 ;; apply to a string.
1614 ;; - `org-export-filter-final-output-functions' applies to the final
1615 ;; transcoded string.
1616 ;; - `org-export-filter-plain-text-functions' applies to any string
1617 ;; not recognized as Org syntax.
1618 ;; - `org-export-filter-TYPE-functions' applies on the string returned
1619 ;; after an element or object of type TYPE has been transcoded.
1621 ;; All filters sets are applied through
1622 ;; `org-export-filter-apply-functions' function. Filters in a set are
1623 ;; applied in reverse order, that is in the order of consing. It
1624 ;; allows developers to be reasonably sure that their filters will be
1625 ;; applied first.
1627 ;;;; Special Filters
1628 (defvar org-export-filter-parse-tree-functions nil
1629 "Filter, or list of filters, applied to the parsed tree.
1630 Each filter is called with two arguments: the parse tree, as
1631 returned by `org-element-parse-buffer', and the back-end as
1632 a symbol. It must return the modified parse tree to transcode.")
1634 (defvar org-export-filter-final-output-functions nil
1635 "Filter, or list of filters, applied to the transcoded string.
1636 Each filter is called with two arguments: the full transcoded
1637 string, and the back-end as a symbol. It must return a string
1638 that will be used as the final export output.")
1640 (defvar org-export-filter-plain-text-functions nil
1641 "Filter, or list of filters, applied to plain text.
1642 Each filter is called with two arguments: a string which contains
1643 no Org syntax, and the back-end as a symbol. It must return
1644 a string or nil.")
1647 ;;;; Elements Filters
1649 (defvar org-export-filter-center-block-functions nil
1650 "Filter, or list of filters, applied to a transcoded center block.
1651 Each filter is called with two arguments: the transcoded center
1652 block, as a string, and the back-end, as a symbol. It must
1653 return a string or nil.")
1655 (defvar org-export-filter-drawer-functions nil
1656 "Filter, or list of filters, applied to a transcoded drawer.
1657 Each filter is called with two arguments: the transcoded drawer,
1658 as a string, and the back-end, as a symbol. It must return
1659 a string or nil.")
1661 (defvar org-export-filter-dynamic-block-functions nil
1662 "Filter, or list of filters, applied to a transcoded dynamic-block.
1663 Each filter is called with two arguments: the transcoded
1664 dynamic-block, as a string, and the back-end, as a symbol. It
1665 must return a string or nil.")
1667 (defvar org-export-filter-headline-functions nil
1668 "Filter, or list of filters, applied to a transcoded headline.
1669 Each filter is called with two arguments: the transcoded
1670 headline, as a string, and the back-end, as a symbol. It must
1671 return a string or nil.")
1673 (defvar org-export-filter-inlinetask-functions nil
1674 "Filter, or list of filters, applied to a transcoded inlinetask.
1675 Each filter is called with two arguments: the transcoded
1676 inlinetask, as a string, and the back-end, as a symbol. It must
1677 return a string or nil.")
1679 (defvar org-export-filter-plain-list-functions nil
1680 "Filter, or list of filters, applied to a transcoded plain-list.
1681 Each filter is called with two arguments: the transcoded
1682 plain-list, as a string, and the back-end, as a symbol. It must
1683 return a string or nil.")
1685 (defvar org-export-filter-item-functions nil
1686 "Filter, or list of filters, applied to a transcoded item.
1687 Each filter is called with two arguments: the transcoded item, as
1688 a string, and the back-end, as a symbol. It must return a string
1689 or nil.")
1691 (defvar org-export-filter-comment-functions nil
1692 "Filter, or list of filters, applied to a transcoded comment.
1693 Each filter is called with two arguments: the transcoded comment,
1694 as a string, and the back-end, as a symbol. It must return
1695 a string or nil.")
1697 (defvar org-export-filter-comment-block-functions nil
1698 "Filter, or list of filters, applied to a transcoded comment-comment.
1699 Each filter is called with two arguments: the transcoded
1700 comment-block, as a string, and the back-end, as a symbol. It
1701 must return a string or nil.")
1703 (defvar org-export-filter-example-block-functions nil
1704 "Filter, or list of filters, applied to a transcoded example-block.
1705 Each filter is called with two arguments: the transcoded
1706 example-block, as a string, and the back-end, as a symbol. It
1707 must return a string or nil.")
1709 (defvar org-export-filter-export-block-functions nil
1710 "Filter, or list of filters, applied to a transcoded export-block.
1711 Each filter is called with two arguments: the transcoded
1712 export-block, as a string, and the back-end, as a symbol. It
1713 must return a string or nil.")
1715 (defvar org-export-filter-fixed-width-functions nil
1716 "Filter, or list of filters, applied to a transcoded fixed-width.
1717 Each filter is called with two arguments: the transcoded
1718 fixed-width, as a string, and the back-end, as a symbol. It must
1719 return a string or nil.")
1721 (defvar org-export-filter-footnote-definition-functions nil
1722 "Filter, or list of filters, applied to a transcoded footnote-definition.
1723 Each filter is called with two arguments: the transcoded
1724 footnote-definition, as a string, and the back-end, as a symbol.
1725 It must return a string or nil.")
1727 (defvar org-export-filter-horizontal-rule-functions nil
1728 "Filter, or list of filters, applied to a transcoded horizontal-rule.
1729 Each filter is called with two arguments: the transcoded
1730 horizontal-rule, as a string, and the back-end, as a symbol. It
1731 must return a string or nil.")
1733 (defvar org-export-filter-keyword-functions nil
1734 "Filter, or list of filters, applied to a transcoded keyword.
1735 Each filter is called with two arguments: the transcoded keyword,
1736 as a string, and the back-end, as a symbol. It must return
1737 a string or nil.")
1739 (defvar org-export-filter-latex-environment-functions nil
1740 "Filter, or list of filters, applied to a transcoded latex-environment.
1741 Each filter is called with two arguments: the transcoded
1742 latex-environment, as a string, and the back-end, as a symbol.
1743 It must return a string or nil.")
1745 (defvar org-export-filter-babel-call-functions nil
1746 "Filter, or list of filters, applied to a transcoded babel-call.
1747 Each filter is called with two arguments: the transcoded
1748 babel-call, as a string, and the back-end, as a symbol. It must
1749 return a string or nil.")
1751 (defvar org-export-filter-paragraph-functions nil
1752 "Filter, or list of filters, applied to a transcoded paragraph.
1753 Each filter is called with two arguments: the transcoded
1754 paragraph, as a string, and the back-end, as a symbol. It must
1755 return a string or nil.")
1757 (defvar org-export-filter-property-drawer-functions nil
1758 "Filter, or list of filters, applied to a transcoded property-drawer.
1759 Each filter is called with two arguments: the transcoded
1760 property-drawer, as a string, and the back-end, as a symbol. It
1761 must return a string or nil.")
1763 (defvar org-export-filter-quote-block-functions nil
1764 "Filter, or list of filters, applied to a transcoded quote block.
1765 Each filter is called with two arguments: the transcoded quote
1766 block, as a string, and the back-end, as a symbol. It must
1767 return a string or nil.")
1769 (defvar org-export-filter-quote-section-functions nil
1770 "Filter, or list of filters, applied to a transcoded quote-section.
1771 Each filter is called with two arguments: the transcoded
1772 quote-section, as a string, and the back-end, as a symbol. It
1773 must return a string or nil.")
1775 (defvar org-export-filter-special-block-functions nil
1776 "Filter, or list of filters, applied to a transcoded special block.
1777 Each filter is called with two arguments: the transcoded special
1778 block, as a string, and the back-end, as a symbol. It must
1779 return a string or nil.")
1781 (defvar org-export-filter-src-block-functions nil
1782 "Filter, or list of filters, applied to a transcoded src-block.
1783 Each filter is called with two arguments: the transcoded
1784 src-block, as a string, and the back-end, as a symbol. It must
1785 return a string or nil.")
1787 (defvar org-export-filter-table-functions nil
1788 "Filter, or list of filters, applied to a transcoded table.
1789 Each filter is called with two arguments: the transcoded table,
1790 as a string, and the back-end, as a symbol. It must return
1791 a string or nil.")
1793 (defvar org-export-filter-verse-block-functions nil
1794 "Filter, or list of filters, applied to a transcoded verse block.
1795 Each filter is called with two arguments: the transcoded verse
1796 block, as a string, and the back-end, as a symbol. It must
1797 return a string or nil.")
1800 ;;;; Objects Filters
1802 (defvar org-export-filter-emphasis-functions nil
1803 "Filter, or list of filters, applied to a transcoded emphasis.
1804 Each filter is called with two arguments: the transcoded
1805 emphasis, as a string, and the back-end, as a symbol. It must
1806 return a string or nil.")
1808 (defvar org-export-filter-entity-functions nil
1809 "Filter, or list of filters, applied to a transcoded entity.
1810 Each filter is called with two arguments: the transcoded entity,
1811 as a string, and the back-end, as a symbol. It must return
1812 a string or nil.")
1814 (defvar org-export-filter-export-snippet-functions nil
1815 "Filter, or list of filters, applied to a transcoded export-snippet.
1816 Each filter is called with two arguments: the transcoded
1817 export-snippet, as a string, and the back-end, as a symbol. It
1818 must return a string or nil.")
1820 (defvar org-export-filter-footnote-reference-functions nil
1821 "Filter, or list of filters, applied to a transcoded footnote-reference.
1822 Each filter is called with two arguments: the transcoded
1823 footnote-reference, as a string, and the back-end, as a symbol.
1824 It must return a string or nil.")
1826 (defvar org-export-filter-inline-babel-call-functions nil
1827 "Filter, or list of filters, applied to a transcoded inline-babel-call.
1828 Each filter is called with two arguments: the transcoded
1829 inline-babel-call, as a string, and the back-end, as a symbol. It
1830 must return a string or nil.")
1832 (defvar org-export-filter-inline-src-block-functions nil
1833 "Filter, or list of filters, applied to a transcoded inline-src-block.
1834 Each filter is called with two arguments: the transcoded
1835 inline-src-block, as a string, and the back-end, as a symbol. It
1836 must return a string or nil.")
1838 (defvar org-export-filter-latex-fragment-functions nil
1839 "Filter, or list of filters, applied to a transcoded latex-fragment.
1840 Each filter is called with two arguments: the transcoded
1841 latex-fragment, as a string, and the back-end, as a symbol. It
1842 must return a string or nil.")
1844 (defvar org-export-filter-line-break-functions nil
1845 "Filter, or list of filters, applied to a transcoded line-break.
1846 Each filter is called with two arguments: the transcoded
1847 line-break, as a string, and the back-end, as a symbol. It must
1848 return a string or nil.")
1850 (defvar org-export-filter-link-functions nil
1851 "Filter, or list of filters, applied to a transcoded link.
1852 Each filter is called with two arguments: the transcoded link, as
1853 a string, and the back-end, as a symbol. It must return a string
1854 or nil.")
1856 (defvar org-export-filter-macro-functions nil
1857 "Filter, or list of filters, applied to a transcoded macro.
1858 Each filter is called with two arguments: the transcoded macro,
1859 as a string, and the back-end, as a symbol. It must return
1860 a string or nil.")
1862 (defvar org-export-filter-radio-target-functions nil
1863 "Filter, or list of filters, applied to a transcoded radio-target.
1864 Each filter is called with two arguments: the transcoded
1865 radio-target, as a string, and the back-end, as a symbol. It
1866 must return a string or nil.")
1868 (defvar org-export-filter-statistics-cookie-functions nil
1869 "Filter, or list of filters, applied to a transcoded statistics-cookie.
1870 Each filter is called with two arguments: the transcoded
1871 statistics-cookie, as a string, and the back-end, as a symbol.
1872 It must return a string or nil.")
1874 (defvar org-export-filter-subscript-functions nil
1875 "Filter, or list of filters, applied to a transcoded subscript.
1876 Each filter is called with two arguments: the transcoded
1877 subscript, as a string, and the back-end, as a symbol. It must
1878 return a string or nil.")
1880 (defvar org-export-filter-superscript-functions nil
1881 "Filter, or list of filters, applied to a transcoded superscript.
1882 Each filter is called with two arguments: the transcoded
1883 superscript, as a string, and the back-end, as a symbol. It must
1884 return a string or nil.")
1886 (defvar org-export-filter-target-functions nil
1887 "Filter, or list of filters, applied to a transcoded target.
1888 Each filter is called with two arguments: the transcoded target,
1889 as a string, and the back-end, as a symbol. It must return
1890 a string or nil.")
1892 (defvar org-export-filter-time-stamp-functions nil
1893 "Filter, or list of filters, applied to a transcoded time-stamp.
1894 Each filter is called with two arguments: the transcoded
1895 time-stamp, as a string, and the back-end, as a symbol. It must
1896 return a string or nil.")
1898 (defvar org-export-filter-verbatim-functions nil
1899 "Filter, or list of filters, applied to a transcoded verbatim.
1900 Each filter is called with two arguments: the transcoded
1901 verbatim, as a string, and the back-end, as a symbol. It must
1902 return a string or nil.")
1904 (defun org-export-filter-apply-functions (filters value backend)
1905 "Call every function in FILTERS with arguments VALUE and BACKEND.
1906 Functions are called in reverse order, to be reasonably sure that
1907 developer-specified filters, if any, are called first."
1908 ;; Ensure FILTERS is a list.
1909 (let ((filters (if (listp filters) (reverse filters) (list filters))))
1910 (loop for filter in filters
1911 if (not value) return nil else
1912 do (setq value (funcall filter value backend))))
1913 value)
1917 ;;; Core functions
1919 ;; This is the room for the main function, `org-export-as', along with
1920 ;; its derivatives, `org-export-to-buffer' and `org-export-to-file'.
1921 ;; They differ only by the way they output the resulting code.
1923 ;; Note that `org-export-as' doesn't really parse the current buffer,
1924 ;; but a copy of it (with the same buffer-local variables and
1925 ;; visibility), where Babel blocks are executed, if appropriate.
1926 ;; `org-export-with-current-buffer-copy' macro prepares that copy.
1928 (defun org-export-as (backend
1929 &optional subtreep visible-only body-only ext-plist)
1930 "Transcode current Org buffer into BACKEND code.
1932 If narrowing is active in the current buffer, only transcode its
1933 narrowed part.
1935 If a region is active, transcode that region.
1937 When optional argument SUBTREEP is non-nil, transcode the
1938 sub-tree at point, extracting information from the headline
1939 properties first.
1941 When optional argument VISIBLE-ONLY is non-nil, don't export
1942 contents of hidden elements.
1944 When optional argument BODY-ONLY is non-nil, only return body
1945 code, without preamble nor postamble.
1947 EXT-PLIST, when provided, is a property list with external
1948 parameters overriding Org default settings, but still inferior to
1949 file-local settings.
1951 Return code as a string."
1952 (save-excursion
1953 (save-restriction
1954 ;; Narrow buffer to an appropriate region for parsing.
1955 (when (org-region-active-p)
1956 (narrow-to-region (region-beginning) (region-end)))
1957 (goto-char (point-min))
1958 (when subtreep
1959 (unless (org-at-heading-p)
1960 (org-with-limited-levels (outline-next-heading)))
1961 (let ((end (save-excursion (org-end-of-subtree t)))
1962 (begin (progn (forward-line)
1963 (org-skip-whitespace)
1964 (point-at-bol))))
1965 (narrow-to-region begin end)))
1966 ;; Retrieve export options (INFO) and parsed tree (RAW-DATA).
1967 ;; Buffer isn't parsed directly. Instead, a temporary copy is
1968 ;; created, where all code blocks are evaluated. RAW-DATA is
1969 ;; the parsed tree of the buffer resulting from that process.
1970 ;; Eventually call `org-export-filter-parse-tree-functions'..
1971 (let ((info (org-export-collect-options backend subtreep ext-plist))
1972 (raw-data (org-export-filter-apply-functions
1973 org-export-filter-parse-tree-functions
1974 (org-export-with-current-buffer-copy
1975 (org-export-blocks-preprocess)
1976 (org-element-parse-buffer nil visible-only))
1977 backend)))
1978 ;; Initialize the communication system and combine it to INFO.
1979 (setq info
1980 (org-combine-plists
1981 info
1982 (org-export-initialize-persistent-properties
1983 raw-data info backend)))
1984 ;; Now transcode RAW-DATA. Also call
1985 ;; `org-export-filter-final-output-functions'.
1986 (let ((body (org-element-normalize-string
1987 (org-export-data raw-data backend info)))
1988 (template (intern (format "org-%s-template" backend))))
1989 (if (and (not body-only) (fboundp template))
1990 (org-trim
1991 (org-export-filter-apply-functions
1992 org-export-filter-final-output-functions
1993 (funcall template body info)
1994 backend))
1995 (org-export-filter-apply-functions
1996 org-export-filter-final-output-functions body backend)))))))
1998 (defun org-export-to-buffer (backend buffer &optional subtreep visible-only
1999 body-only ext-plist)
2000 "Call `org-export-as' with output to a specified buffer.
2002 BACKEND is the back-end used for transcoding, as a symbol.
2004 BUFFER is the output buffer. If it already exists, it will be
2005 erased first, otherwise, it will be created.
2007 Arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and EXT-PLIST are
2008 similar to those used in `org-export-as', which see.
2010 Return buffer."
2011 (let ((out (org-export-as backend subtreep visible-only body-only ext-plist))
2012 (buffer (get-buffer-create buffer)))
2013 (with-current-buffer buffer
2014 (erase-buffer)
2015 (insert out)
2016 (goto-char (point-min)))
2017 buffer))
2019 (defun org-export-to-file (backend filename &optional post-process subtreep
2020 visible-only body-only ext-plist)
2021 "Call `org-export-as' with output to a specified file.
2023 BACKEND is the back-end used for transcoding, as a symbol.
2025 FILENAME is the output file name. If it already exists, it will
2026 be erased first, unless it isn't writable, in which case an error
2027 will be returned. Otherwise, the file will be created.
2029 Optional argument POST-PROCESS, when non-nil, is a function
2030 applied to the output file. It expects one argument: the file
2031 name, as a string. It can be used to call shell commands on that
2032 file, display a specific buffer, etc.
2034 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
2035 EXT-PLIST are similar to those used in `org-export-as', which
2036 see.
2038 Return file name."
2039 ;; Checks for file and directory permissions.
2040 (cond
2041 ((not (file-exists-p filename))
2042 (let ((dir (or (file-name-directory filename) default-directory)))
2043 (unless (file-writable-p dir) (error "Output directory not writable"))))
2044 ((not (file-writable-p filename)) (error "Output file not writable")))
2045 ;; All checks passed: insert contents to a temporary buffer and
2046 ;; write it to the specified file.
2047 (let ((out (org-export-as backend subtreep visible-only body-only ext-plist)))
2048 (with-temp-buffer
2049 (insert out)
2050 (write-file filename)))
2051 (when post-process (funcall post-process filename))
2052 ;; Return value.
2053 filename)
2055 (defmacro org-export-with-current-buffer-copy (&rest body)
2056 "Apply BODY in a copy of the current buffer.
2058 The copy preserves local variables and visibility of the original
2059 buffer.
2061 Point is at buffer's beginning when BODY is applied."
2062 (org-with-gensyms (original-buffer offset buffer-string overlays)
2063 `(let ((,original-buffer ,(current-buffer))
2064 (,offset ,(1- (point-min)))
2065 (,buffer-string ,(buffer-string))
2066 (,overlays (mapcar
2067 'copy-overlay (overlays-in (point-min) (point-max)))))
2068 (with-temp-buffer
2069 (let ((buffer-invisibility-spec nil))
2070 (org-clone-local-variables
2071 ,original-buffer "^\\(org-\\|orgtbl-\\|major-mode$\\)")
2072 (insert ,buffer-string)
2073 (mapc (lambda (ov)
2074 (move-overlay
2076 (- (overlay-start ov) ,offset)
2077 (- (overlay-end ov) ,offset)
2078 (current-buffer)))
2079 ,overlays)
2080 (goto-char (point-min))
2081 (progn ,@body))))))
2082 (def-edebug-spec org-export-with-current-buffer-copy (body))
2086 ;;; Tools For Back-Ends
2088 ;; A whole set of tools is available to help build new exporters. Any
2089 ;; function general enough to have its use across many back-ends
2090 ;; should be added here.
2092 ;; As of now, functions operating on footnotes, headlines, include
2093 ;; keywords, links, macros, references, src-blocks, tables and tables
2094 ;; of contents are implemented.
2096 ;;;; For Footnotes
2098 ;; `org-export-collect-footnote-definitions' is a tool to list
2099 ;; actually used footnotes definitions in the whole parse tree, or in
2100 ;; an headline, in order to add footnote listings throughout the
2101 ;; transcoded data.
2103 ;; `org-export-footnote-first-reference-p' is a predicate used by some
2104 ;; back-ends, when they need to attach the footnote definition only to
2105 ;; the first occurrence of the corresponding label.
2107 ;; `org-export-get-footnote-definition' and
2108 ;; `org-export-get-footnote-number' provide easier access to
2109 ;; additional information relative to a footnote reference.
2111 (defun org-export-collect-footnote-definitions (data info)
2112 "Return an alist between footnote label and its definition.
2114 DATA is the parse tree from which definitions are collected.
2115 INFO is the plist used as a communication channel.
2117 As anonymous footnotes have no label, the key used is that case
2118 is their beginning position.
2120 Definitions are sorted by order of references. They either
2121 appear as Org data \(transcoded with `org-export-data'\) or as
2122 a secondary string for inlined footnotes \(transcoded with
2123 `org-export-secondary-string'\). Unreferenced definitions are
2124 ignored."
2125 (org-element-map
2126 data 'footnote-reference
2127 (lambda (footnote local)
2128 (cond
2129 ;; Definition already collected.
2130 ((not (org-export-footnote-first-reference-p footnote local)) nil)
2131 ;; Reference has a label: Use it as a key, and get the
2132 ;; corresponding definition.
2133 ((org-element-get-property :label footnote)
2134 (cons (org-element-get-property :label footnote)
2135 (org-export-get-footnote-definition footnote local)))
2136 ;; No label: This is an anonymous footnote. Use beginning
2137 ;; position as the key and inline definition (a secondary
2138 ;; string) as its value.
2139 (t (cons (org-element-get-property :begin footnote)
2140 (org-element-get-property :inline-definition footnote)))))
2141 info))
2143 (defun org-export-footnote-first-reference-p (footnote-reference info)
2144 "Non-nil when a footnote reference is the first one for its label.
2146 FOOTNOTE-REFERENCE is the footnote reference being considered.
2147 INFO is the plist used as a communication channel."
2148 (let ((label (org-element-get-property :label footnote-reference)))
2149 (not (and label (member label (plist-get info :footnote-seen-labels))))))
2151 (defun org-export-get-footnote-definition (footnote-reference info)
2152 "Return definition of FOOTNOTE-REFERENCE as parsed data.
2153 INFO is the plist used as a communication channel."
2154 (let ((label (org-element-get-property :label footnote-reference)))
2155 (or (org-element-get-property :inline-definition footnote-reference)
2156 (cdr (assoc label (plist-get info :footnote-definition-alist))))))
2158 (defun org-export-get-footnote-number (footnote-reference info)
2159 "Return footnote number associated to FOOTNOTE-REFERENCE.
2160 INFO is the plist used as a communication channel."
2161 (let* ((all-seen (plist-get info :footnote-seen-labels))
2162 (label (org-element-get-property :label footnote-reference))
2163 ;; Anonymous footnotes are always new footnotes.
2164 (seenp (and label (member label all-seen))))
2165 (if seenp (length seenp) (1+ (length all-seen)))))
2168 ;;;; For Headlines
2170 ;; `org-export-get-relative-level' is a shortcut to get headline
2171 ;; level, relatively to the lower headline level in the parsed tree.
2173 ;; `org-export-get-headline-number' returns the section number of an
2174 ;; headline, while `org-export-number-to-roman' allows to convert it
2175 ;; to roman numbers.
2177 ;; `org-export-first-sibling-p' and `org-export-last-sibling-p' are
2178 ;; two useful predicates when it comes to fulfill the
2179 ;; `:headline-levels' property.
2181 (defun org-export-get-relative-level (headline info)
2182 "Return HEADLINE relative level within current parsed tree.
2183 INFO is a plist holding contextual information."
2184 (+ (org-element-get-property :level headline)
2185 (or (plist-get info :headline-offset) 0)))
2187 (defun org-export-get-headline-number (headline info)
2188 "Return HEADLINE numbering as a list of numbers.
2189 INFO is a plist holding contextual information."
2190 (cdr (assq (org-element-get-property :begin headline)
2191 (plist-get info :headline-numbering))))
2193 (defun org-export-number-to-roman (n)
2194 "Convert integer N into a roman numeral."
2195 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
2196 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
2197 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
2198 ( 1 . "I")))
2199 (res ""))
2200 (if (<= n 0)
2201 (number-to-string n)
2202 (while roman
2203 (if (>= n (caar roman))
2204 (setq n (- n (caar roman))
2205 res (concat res (cdar roman)))
2206 (pop roman)))
2207 res)))
2209 (defun org-export-first-sibling-p (headline info)
2210 "Non-nil when HEADLINE is the first sibling in its sub-tree.
2211 INFO is the plist used as a communication channel."
2212 (not (eq (plist-get info :previous-element) 'headline)))
2214 (defun org-export-last-sibling-p (headline info)
2215 "Non-nil when HEADLINE is the last sibling in its sub-tree.
2216 INFO is the plist used as a communication channel."
2217 (= (org-element-get-property :end headline)
2218 (or (plist-get (plist-get info :parent-properties) :end)
2219 (plist-get info :point-max))))
2222 ;;;; For Include Keywords
2224 ;; This section provides a tool to properly handle insertion of files
2225 ;; during export: `org-export-included-files'. It recursively
2226 ;; transcodes a file specfied by an include keyword.
2228 ;; It uses two helper functions: `org-export-get-file-contents'
2229 ;; returns contents of a file according to parameters specified in the
2230 ;; keyword while `org-export-parse-included-file' parses the file
2231 ;; specified by it.
2233 (defun org-export-included-file (keyword backend info)
2234 "Transcode file specified with include KEYWORD.
2236 KEYWORD is the include keyword element transcoded. BACKEND is
2237 the language back-end used for transcoding. INFO is the plist
2238 used as a communication channel.
2240 This function updates `:included-files' and `:headline-offset'
2241 properties.
2243 Return the transcoded string."
2244 (let ((data (org-export-parse-included-file keyword info))
2245 (file (let ((value (org-element-get-property :value keyword)))
2246 (and (string-match "^\"\\(\\S-+\\)\"" value)
2247 (match-string 1 value)))))
2248 (org-element-normalize-string
2249 (org-export-data
2250 data backend
2251 (org-combine-plists
2252 info
2253 ;; Store full path of already included files to avoid
2254 ;; recursive file inclusion.
2255 `(:included-files
2256 ,(cons (expand-file-name file) (plist-get info :included-files))
2257 ;; Ensure that a top-level headline in the included
2258 ;; file becomes a direct child of the current headline
2259 ;; in the buffer.
2260 :headline-offset
2261 ,(- (+ (plist-get (plist-get info :inherited-properties) :level)
2262 (plist-get info :headline-offset))
2263 (1- (org-export-get-min-level data info)))))))))
2265 (defun org-export-get-file-contents (file &optional lines)
2266 "Get the contents of FILE and return them as a string.
2267 When optional argument LINES is a string specifying a range of
2268 lines, include only those lines."
2269 (with-temp-buffer
2270 (insert-file-contents file)
2271 (when lines
2272 (let* ((lines (split-string lines "-"))
2273 (lbeg (string-to-number (car lines)))
2274 (lend (string-to-number (cadr lines)))
2275 (beg (if (zerop lbeg) (point-min)
2276 (goto-char (point-min))
2277 (forward-line (1- lbeg))
2278 (point)))
2279 (end (if (zerop lend) (point-max)
2280 (goto-char (point-min))
2281 (forward-line (1- lend))
2282 (point))))
2283 (narrow-to-region beg end)))
2284 (buffer-string)))
2286 (defun org-export-parse-included-file (keyword info)
2287 "Parse file specified by include KEYWORD.
2289 KEYWORD is the include keyword element transcoded. BACKEND is the
2290 language back-end used for transcoding. INFO is the plist used as
2291 a communication channel.
2293 Return the parsed tree."
2294 (let* ((value (org-element-get-property :value keyword))
2295 (file (and (string-match "^\"\\(\\S-+\\)\"" value)
2296 (prog1 (match-string 1 value)
2297 (setq value (replace-match "" nil nil value)))))
2298 (lines (and (string-match
2299 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\"" value)
2300 (prog1 (match-string 1 value)
2301 (setq value (replace-match "" nil nil value)))))
2302 (env (cond ((string-match "\\<example\\>" value) "example")
2303 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
2304 (match-string 1 value)))))
2305 (cond
2306 ((or (not file)
2307 (not (file-exists-p file))
2308 (not (file-readable-p file)))
2309 (format "Cannot include file %s" file))
2310 ((and (not env)
2311 (member (expand-file-name file) (plist-get info :included-files)))
2312 (error "Recursive file inclusion: %S" file))
2313 (t (let ((raw (org-element-normalize-string
2314 (org-export-get-file-contents
2315 (expand-file-name file) lines))))
2316 ;; If environment isn't specified, Insert file in
2317 ;; a temporary buffer and parse it as Org syntax.
2318 ;; Otherwise, build the element representing the file.
2319 (cond
2320 ((not env)
2321 (with-temp-buffer
2322 (insert raw) (org-mode) (org-element-parse-buffer)))
2323 ((string= "example" env)
2324 `(org-data nil (example-block (:value ,raw :post-blank 0))))
2326 `(org-data
2328 (src-block (:value ,raw :language ,env :post-blank 0))))))))))
2331 ;;;; For Links
2333 ;; `org-export-solidify-link-text' turns a string into a safer version
2334 ;; for links, replacing most non-standard characters with hyphens.
2336 ;; `org-export-get-coderef-format' returns an appropriate format
2337 ;; string for coderefs.
2339 ;; `org-export-inline-image-p' returns a non-nil value when the link
2340 ;; provided should be considered as an inline image.
2342 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
2343 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
2344 ;; returns an appropriate unique identifier when found, or nil.
2346 (defun org-export-solidify-link-text (s)
2347 "Take link text and make a safe target out of it."
2348 (save-match-data
2349 (mapconcat 'identity (org-split-string s "[^a-zA-Z0-9_\\.-]+") "-")))
2351 (defun org-export-get-coderef-format (path desc)
2352 "Return format string for code reference link.
2353 PATH is the link path. DESC is its description."
2354 (save-match-data
2355 (cond ((string-match (regexp-quote (concat "(" path ")")) desc)
2356 (replace-match "%s" t t desc))
2357 ((string= desc "") "%s")
2358 (t desc))))
2360 (defun org-export-inline-image-p (link &optional extensions)
2361 "Non-nil if LINK object points to an inline image.
2363 When non-nil, optional argument EXTENSIONS is a list of valid
2364 extensions for image files, as strings. Otherwise, a default
2365 list is provided \(cf. `org-image-file-name-regexp'\)."
2366 (and (not (org-element-get-contents link))
2367 (string= (org-element-get-property :type link) "file")
2368 (org-file-image-p
2369 (expand-file-name (org-element-get-property :path link))
2370 extensions)))
2372 (defun org-export-resolve-fuzzy-link (link info)
2373 "Return an unique identifier for LINK destination.
2375 INFO is a plist holding contextual information.
2377 Return value can be a string, an buffer position, or nil:
2379 - If LINK path exactly matches any target, return its name as the
2380 identifier.
2382 - If LINK path exactly matches any headline name, return
2383 headline's beginning position as the identifier. If more than
2384 one headline share that name, priority will be given to the one
2385 with the closest common ancestor, if any, or the first one in
2386 the parse tree otherwise.
2388 - Otherwise, return nil.
2390 Assume LINK type is \"fuzzy\"."
2391 (let ((path (org-element-get-property :path link)))
2392 (if (member path (plist-get info :target-list))
2393 ;; Link points to a target: return its name as a string.
2394 path
2395 ;; Link either points to an headline or nothing. Try to find
2396 ;; the source, with priority given to headlines with the closest
2397 ;; common ancestor. If such candidate is found, return its
2398 ;; beginning position as an unique identifier, otherwise return
2399 ;; nil.
2400 (let* ((head-alist (plist-get info :headline-alist))
2401 (link-begin (org-element-get-property :begin link))
2402 (link-end (org-element-get-property :end link))
2403 ;; Store candidates as a list of cons cells holding their
2404 ;; beginning and ending position.
2405 (cands (loop for head in head-alist
2406 when (string= (car head) path)
2407 collect (cons (nth 1 head) (nth 2 head)))))
2408 (cond
2409 ;; No candidate: return nil.
2410 ((not cands) nil)
2411 ;; If one or more candidates share common ancestors with
2412 ;; LINK, return beginning position of the first one matching
2413 ;; the closer ancestor shared.
2414 ((let ((ancestors (loop for head in head-alist
2415 when (and (> link-begin (nth 1 head))
2416 (<= link-end (nth 2 head)))
2417 collect (cons (nth 1 head) (nth 2 head)))))
2418 (loop named main for ancestor in (nreverse ancestors) do
2419 (loop for candidate in cands
2420 when (and (>= (car candidate) (car ancestor))
2421 (<= (cdr candidate) (cdr ancestor)))
2422 do (return-from main (car candidate))))))
2423 ;; No candidate have a common ancestor with link: First match
2424 ;; will do. Return its beginning position.
2425 (t (caar cands)))))))
2428 ;;;; For Macros
2430 ;; `org-export-expand-macro' simply takes care of expanding macros.
2432 (defun org-export-expand-macro (macro info)
2433 "Expand MACRO and return it as a string.
2434 INFO is a plist holding export options."
2435 (let* ((key (org-element-get-property :key macro))
2436 (args (org-element-get-property :args macro))
2437 (value (plist-get info (intern (format ":macro-%s" key)))))
2438 ;; Replace arguments in VALUE.
2439 (let ((s 0) n)
2440 (while (string-match "\\$\\([0-9]+\\)" value s)
2441 (setq s (1+ (match-beginning 0))
2442 n (string-to-number (match-string 1 value)))
2443 (and (>= (length args) n)
2444 (setq value (replace-match (nth (1- n) args) t t value)))))
2445 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
2446 (when (string-match "\\`(eval\\>" value)
2447 (setq value (eval (read value))))
2448 ;; Return expanded string.
2449 (format "%s" value)))
2452 ;;;; For References
2454 ;; `org-export-get-ordinal' associates a sequence number to any object
2455 ;; or element.
2457 (defun org-export-get-ordinal (element info &optional within-section predicate)
2458 "Return ordinal number of an element or object.
2460 ELEMENT is the element or object considered. INFO is the plist
2461 used as a communication channel.
2463 When optional argument WITHIN-SECTION is non-nil, narrow counting
2464 to the section containing ELEMENT.
2466 Optional argument PREDICATE is a function returning a non-nil
2467 value if the current element or object should be counted in. It
2468 accepts one argument: the element or object being considered.
2469 This argument allows to count only a certain type of objects,
2470 like inline images, which are a subset of links \(in that case,
2471 `org-export-inline-image-p' might be an useful predicate\)."
2472 (let ((counter 0)
2473 (type (car element))
2474 ;; Determine if search should apply to current section, in
2475 ;; which case it should be retrieved first, or to full parse
2476 ;; tree. As a special case, an element or object without
2477 ;; a parent headline will also trigger a full search,
2478 ;; notwithstanding WITHIN-SECTION value.
2479 (data
2480 (let ((parse-tree (plist-get info :parse-tree)))
2481 (if within-section
2482 (let ((parent (plist-get (plist-get info :inherited-properties)
2483 :begin)))
2484 (if (not parent) parse-tree
2485 (org-element-map
2486 parse-tree 'headline
2487 (lambda (el local)
2488 (when (= (org-element-get-property :begin el) parent) el))
2489 info 'first-match)))
2490 parse-tree))))
2491 ;; Increment counter until ELEMENT is found again.
2492 (org-element-map
2493 data type
2494 (lambda (el local)
2495 (cond
2496 ((and (functionp predicate) (funcall predicate el)))
2497 ((equal element el) (1+ counter))
2498 (t (incf counter) nil)))
2499 info 'first-match)))
2502 ;;;; For Src-Blocks
2504 ;; `org-export-handle-code' takes care of line numbering and reference
2505 ;; cleaning in source code, when appropriate. It also updates global
2506 ;; LOC count (`:total-loc' property) and code references alist
2507 ;; (`:code-refs' property).
2509 (defun org-export-handle-code (code switches info
2510 &optional language num-fmt ref-fmt)
2511 "Handle line numbers and code references in CODE.
2513 CODE is the string to process. SWITCHES is the option string
2514 determining which changes will be applied to CODE. INFO is the
2515 plist used as a communication channel during export.
2517 Optional argument LANGUAGE, when non-nil, is a string specifying
2518 code's language.
2520 If optional argument NUM-FMT is a string, it will be used as
2521 a format string for numbers at beginning of each line.
2523 If optional argument REF-FMT is a string, it will be used as
2524 a format string for each line of code containing a reference.
2526 Update the following INFO properties by side-effect: `:total-loc'
2527 and `:code-refs'.
2529 Return new code as a string."
2530 (let* ((switches (or switches ""))
2531 (numberp (string-match "[-+]n\\>" switches))
2532 (continuep (string-match "\\+n\\>" switches))
2533 (total-LOC (if (and numberp (not continuep))
2535 (or (plist-get info :total-loc) 0)))
2536 (preserve-indent-p (or org-src-preserve-indentation
2537 (string-match "-i\\>" switches)))
2538 (replace-labels (when (string-match "-r\\>" switches)
2539 (if (string-match "-k\\>" switches) 'keep t)))
2540 ;; Get code and clean it. Remove blank lines at its
2541 ;; beginning and end. Also remove protective commas.
2542 (code (let ((c (replace-regexp-in-string
2543 "\\`\\([ \t]*\n\\)+" ""
2544 (replace-regexp-in-string
2545 "\\(:?[ \t]*\n\\)*[ \t]*\\'" "\n" code))))
2546 ;; If appropriate, remove global indentation.
2547 (unless preserve-indent-p (setq c (org-remove-indentation c)))
2548 ;; Free up the protected lines. Note: Org blocks
2549 ;; have commas at the beginning or every line.
2550 (if (string= language "org")
2551 (replace-regexp-in-string "^," "" c)
2552 (replace-regexp-in-string
2553 "^\\(,\\)\\(:?\\*\\|[ \t]*#\\+\\)" "" c nil nil 1))))
2554 ;; Split code to process it line by line.
2555 (code-lines (org-split-string code "\n"))
2556 ;; Ensure line numbers will be correctly padded before
2557 ;; applying the format string.
2558 (num-fmt (format (if (stringp num-fmt) num-fmt "%s: ")
2559 (format "%%%ds"
2560 (length (number-to-string
2561 (+ (length code-lines)
2562 total-LOC))))))
2563 ;; Get format used for references.
2564 (label-fmt (or (and (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
2565 (match-string 1 switches))
2566 org-coderef-label-format))
2567 ;; Build a regexp matching a loc with a reference.
2568 (with-ref-re (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
2569 (replace-regexp-in-string
2570 "%s" "\\([-a-zA-Z0-9_ ]+\\)" label-fmt nil t)))
2571 coderefs)
2572 (org-element-normalize-string
2573 (mapconcat (lambda (loc)
2574 ;; Maybe add line number to current line of code
2575 ;; (LOC).
2576 (when numberp
2577 (setq loc (concat (format num-fmt (incf total-LOC)) loc)))
2578 ;; Take action if at a ref line.
2579 (when (string-match with-ref-re loc)
2580 (let ((ref (match-string 3 loc)))
2581 (setq loc
2582 (cond
2583 ;; Option "-k": don't remove labels. Use
2584 ;; numbers for references when lines are
2585 ;; numbered, use labels otherwise.
2586 ((eq replace-labels 'keep)
2587 (let ((full-ref (format "(%s)" ref)))
2588 (push (cons ref (if numberp total-LOC full-ref))
2589 coderefs)
2590 (replace-match full-ref nil nil loc 2))
2591 (replace-match (format "(%s)" ref) nil nil loc 2))
2592 ;; Option "-r" without "-k": remove labels.
2593 ;; Use numbers for references when lines are
2594 ;; numbered, use labels otherwise.
2595 (replace-labels
2596 (push (cons ref (if numberp total-LOC ref))
2597 coderefs)
2598 (replace-match "" nil nil loc 1))
2599 ;; Else: don't remove labels and don't use
2600 ;; numbers for references.
2602 (let ((full-ref (format "(%s)" ref)))
2603 (push (cons ref full-ref) coderefs)
2604 (replace-match full-ref nil nil loc 2)))))))
2605 ;; If REF-FMT is defined, apply it to current LOC.
2606 (when (stringp ref-fmt) (setq loc (format ref-fmt loc)))
2607 ;; Update by side-effect communication channel.
2608 ;; Return updated LOC.
2609 (setq info (org-export-set-property
2610 (org-export-set-property
2611 info :code-refs coderefs)
2612 :total-loc total-LOC))
2613 loc)
2614 code-lines "\n"))))
2617 ;;;; For Tables
2619 ;; `org-export-table-format-info' extracts formatting information
2620 ;; (alignment, column groups and presence of a special column) from
2621 ;; a raw table and returns it as a property list.
2623 ;; `org-export-clean-table' cleans the raw table from any Org
2624 ;; table-specific syntax.
2626 (defun org-export-table-format-info (table)
2627 "Extract info from TABLE.
2628 Return a plist whose properties and values are:
2629 `:alignment' vector of strings among \"r\", \"l\" and \"c\",
2630 `:column-groups' vector of symbols among `start', `end', `start-end',
2631 `:row-groups' list of integers representing row groups.
2632 `:special-column-p' non-nil if table has a special column.
2633 `:width' vector of integers representing desired width of
2634 current column, or nil."
2635 (with-temp-buffer
2636 (insert table)
2637 (goto-char 1)
2638 (org-table-align)
2639 (let ((align (vconcat (mapcar (lambda (c) (if c "r" "l"))
2640 org-table-last-alignment)))
2641 (width (make-vector (length org-table-last-alignment) nil))
2642 (colgroups (make-vector (length org-table-last-alignment) nil))
2643 (row-group 0)
2644 (rowgroups)
2645 (special-column-p 'empty))
2646 (mapc (lambda (row)
2647 (if (string-match "^[ \t]*|[-+]+|[ \t]*$" row)
2648 (incf row-group)
2649 (push row-group rowgroups)
2650 ;; Determine if a special column is present by looking
2651 ;; for special markers in the first column. More
2652 ;; accurately, the first column is considered special
2653 ;; if it only contains special markers and, maybe,
2654 ;; empty cells.
2655 (setq special-column-p
2656 (cond
2657 ((not special-column-p) nil)
2658 ((string-match "^[ \t]*| *\\\\?\\([\#!$*_^]\\) *|"
2659 row) 'special)
2660 ((string-match "^[ \t]*| +|" row) special-column-p))))
2661 (cond
2662 ;; Read forced alignment and width information, if any,
2663 ;; and determine final alignment for the table.
2664 ((org-table-cookie-line-p row)
2665 (let ((col 0))
2666 (mapc (lambda (field)
2667 (when (string-match "<\\([lrc]\\)\\([0-9]+\\)?>" field)
2668 (aset align col (match-string 1 field))
2669 (aset width col (let ((w (match-string 2 field)))
2670 (and w (string-to-number w)))))
2671 (incf col))
2672 (org-split-string row "[ \t]*|[ \t]*"))))
2673 ;; Read column groups information.
2674 ((org-table-colgroup-line-p row)
2675 (let ((col 0))
2676 (mapc (lambda (field)
2677 (aset colgroups col
2678 (cond ((string= "<" field) 'start)
2679 ((string= ">" field) 'end)
2680 ((string= "<>" field) 'start-end)))
2681 (incf col))
2682 (org-split-string row "[ \t]*|[ \t]*"))))))
2683 (org-split-string table "\n"))
2684 ;; Return plist.
2685 (list :alignment align
2686 :column-groups colgroups
2687 :row-groups (reverse rowgroups)
2688 :special-column-p (eq special-column-p 'special)
2689 :width width))))
2691 (defun org-export-clean-table (table specialp)
2692 "Clean string TABLE from its formatting elements.
2693 Remove any row containing column groups or formatting cookies and
2694 rows starting with a special marker. If SPECIALP is non-nil,
2695 assume the table contains a special formatting column and remove
2696 it also."
2697 (let ((rows (org-split-string table "\n")))
2698 (mapconcat 'identity
2699 (delq nil
2700 (mapcar
2701 (lambda (row)
2702 (cond
2703 ((org-table-colgroup-line-p row) nil)
2704 ((org-table-cookie-line-p row) nil)
2705 ;; Ignore rows starting with a special marker.
2706 ((string-match "^[ \t]*| *[!_^/] *|" row) nil)
2707 ;; Remove special column.
2708 ((and specialp
2709 (or (string-match "^\\([ \t]*\\)|-+\\+" row)
2710 (string-match "^\\([ \t]*\\)|[^|]*|" row)))
2711 (replace-match "\\1|" t nil row))
2712 (t row)))
2713 rows))
2714 "\n")))
2717 ;;;; For Tables Of Contents
2719 ;; `org-export-collect-headlines' builds a list of all exportable
2720 ;; headline elements, maybe limited to a certain depth. One can then
2721 ;; easily parse it and transcode it.
2723 ;; Building lists of tables, figures or listings is quite similar.
2724 ;; Once the generic function `org-export-collect-elements' is defined,
2725 ;; `org-export-collect-tables', `org-export-collect-figures' and
2726 ;; `org-export-collect-listings' can be derived from it.
2728 (defun org-export-collect-headlines (info &optional n)
2729 "Collect headlines in order to build a table of contents.
2731 When non-nil, optional argument N must be an integer. It
2732 specifies the depth of the table of contents.
2734 Return a list of all exportable headlines as parsed elements."
2735 (org-element-map
2736 (plist-get info :parse-tree)
2737 'headline
2738 (lambda (headline local)
2739 ;; Strip contents from HEADLINE.
2740 (let ((relative-level (org-export-get-relative-level headline local)))
2741 (unless (and n (> relative-level n)) headline)))
2742 info))
2744 (defun org-export-collect-elements (type backend info)
2745 "Collect named elements of type TYPE.
2747 Only elements with a caption or a name are collected.
2749 BACKEND is the back-end used to transcode their caption or name.
2750 INFO is a plist holding export options.
2752 Return an alist where key is entry's name and value an unique
2753 identifier that might be used for internal links."
2754 (org-element-map
2755 (plist-get info :parse-tree)
2756 type
2757 (lambda (element info)
2758 (let ((entry
2759 (cond
2760 ((org-element-get-property :caption element)
2761 (org-export-secondary-string
2762 (org-element-get-property :caption element) backend info))
2763 ((org-element-get-property :name element)
2764 (org-export-secondary-string
2765 (org-element-get-property :name element) backend info)))))
2766 ;; Skip elements with neither a caption nor a name.
2767 (when entry (cons entry (org-element-get-property :begin element)))))
2768 info))
2770 (defun org-export-collect-tables (backend info)
2771 "Build a list of tables.
2773 BACKEND is the back-end used to transcode table's name. INFO is
2774 a plist holding export options.
2776 Return an alist where key is the caption of the table and value
2777 an unique identifier that might be used for internal links."
2778 (org-export-collect-elements 'table backend info))
2780 (defun org-export-collect-figures (backend info)
2781 "Build a list of figures.
2783 A figure is a paragraph type element with a caption or a name.
2785 BACKEND is the back-end used to transcode headline's name. INFO
2786 is a plist holding export options.
2788 Return an alist where key is the caption of the figure and value
2789 an unique indentifier that might be used for internal links."
2790 (org-export-collect-elements 'paragraph backend info))
2792 (defun org-export-collect-listings (backend info)
2793 "Build a list of src blocks.
2795 BACKEND is the back-end used to transcode src block's name. INFO
2796 is a plist holding export options.
2798 Return an alist where key is the caption of the src block and
2799 value an unique indentifier that might be used for internal
2800 links."
2801 (org-export-collect-elements 'src-block backend info))
2804 (provide 'org-export)
2805 ;;; org-export.el ends here