org-export: Remove :previous-element :previous-object properties
[org-mode/org-mode-NeilSmithlineMods.git] / contrib / lisp / org-export.el
blob95773df26a5d1ec6206712772c883f69e97ff468
1 ;;; org-export.el --- Generic Export Engine For Org
3 ;; Copyright (C) 2012 Free Software Foundation, Inc.
5 ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
6 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; This program is free software; you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation, either version 3 of the License, or
11 ;; (at your option) any later version.
13 ;; This program is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 ;; GNU General Public License for more details.
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
21 ;;; Commentary:
23 ;; This library implements a generic export engine for Org, built on
24 ;; its syntactical parser: Org Elements.
26 ;; Besides that parser, the generic exporter is made of three distinct
27 ;; parts:
29 ;; - The communication channel consists in a property list, which is
30 ;; created and updated during the process. Its use is to offer
31 ;; every piece of information, would it be export options or
32 ;; contextual data, all in a single place. The exhaustive list of
33 ;; properties is given in "The Communication Channel" section of
34 ;; this file.
36 ;; - The transcoder walks the parse tree, ignores or treat as plain
37 ;; text elements and objects according to export options, and
38 ;; eventually calls back-end specific functions to do the real
39 ;; transcoding, concatenating their return value along the way.
41 ;; - The filter system is activated at the very beginning and the very
42 ;; end of the export process, and each time an element or an object
43 ;; has been converted. It is the entry point to fine-tune standard
44 ;; output from back-end transcoders.
46 ;; The core function is `org-export-as'. It returns the transcoded
47 ;; buffer as a string.
49 ;; In order to derive an exporter out of this generic implementation,
50 ;; one can define a transcode function for each element or object.
51 ;; Such function should return a string for the corresponding element,
52 ;; without any trailing space, or nil. It must accept three
53 ;; arguments:
54 ;; 1. the element or object itself,
55 ;; 2. its contents, or nil when it isn't recursive,
56 ;; 3. the property list used as a communication channel.
58 ;; If no such function is found, that element or object type will
59 ;; simply be ignored, along with any separating blank line. The same
60 ;; will happen if the function returns the nil value. If that
61 ;; function returns the empty string, the type will be ignored, but
62 ;; the blank lines will be kept.
64 ;; Contents, when not nil, are stripped from any global indentation
65 ;; (although the relative one is preserved). They also always end
66 ;; with a single newline character.
68 ;; These functions must follow a strict naming convention:
69 ;; `org-BACKEND-TYPE' where, obviously, BACKEND is the name of the
70 ;; export back-end and TYPE the type of the element or object handled.
72 ;; Moreover, two additional functions can be defined. On the one
73 ;; hand, `org-BACKEND-template' returns the final transcoded string,
74 ;; and can be used to add a preamble and a postamble to document's
75 ;; body. It must accept two arguments: the transcoded string and the
76 ;; property list containing export options. On the other hand,
77 ;; `org-BACKEND-plain-text', when defined, is to be called on every
78 ;; text not recognized as an element or an object. It must accept two
79 ;; arguments: the text string and the information channel.
81 ;; Any back-end can define its own variables. Among them, those
82 ;; customizables should belong to the `org-export-BACKEND' group.
83 ;; Also, a special variable, `org-BACKEND-option-alist', allows to
84 ;; define buffer keywords and "#+options:" items specific to that
85 ;; back-end. See `org-export-option-alist' for supported defaults and
86 ;; syntax.
88 ;; Tools for common tasks across back-ends are implemented in the
89 ;; penultimate part of this file. A dispatcher for standard back-ends
90 ;; is provided in the last one.
92 ;;; Code:
93 (eval-when-compile (require 'cl))
94 (require 'org-element)
97 ;;; Internal Variables
99 ;; Among internal variables, the most important is
100 ;; `org-export-option-alist'. This variable define the global export
101 ;; options, shared between every exporter, and how they are acquired.
103 (defconst org-export-max-depth 19
104 "Maximum nesting depth for headlines, counting from 0.")
106 (defconst org-export-option-alist
107 '((:author "AUTHOR" nil user-full-name t)
108 (:creator "CREATOR" nil org-export-creator-string)
109 (:date "DATE" nil nil t)
110 (:description "DESCRIPTION" nil nil newline)
111 (:email "EMAIL" nil user-mail-address t)
112 (:exclude-tags "EXPORT_EXCLUDE_TAGS" nil org-export-exclude-tags split)
113 (:headline-levels nil "H" org-export-headline-levels)
114 (:keywords "KEYWORDS" nil nil space)
115 (:language "LANGUAGE" nil org-export-default-language t)
116 (:preserve-breaks nil "\\n" org-export-preserve-breaks)
117 (:section-numbers nil "num" org-export-with-section-numbers)
118 (:select-tags "EXPORT_SELECT_TAGS" nil org-export-select-tags split)
119 (:time-stamp-file nil "timestamp" org-export-time-stamp-file)
120 (:title "TITLE" nil nil space)
121 (:with-archived-trees nil "arch" org-export-with-archived-trees)
122 (:with-author nil "author" org-export-with-author)
123 (:with-creator nil "creator" org-export-with-creator)
124 (:with-drawers nil "drawer" org-export-with-drawers)
125 (:with-email nil "email" org-export-with-email)
126 (:with-emphasize nil "*" org-export-with-emphasize)
127 (:with-entities nil "e" org-export-with-entities)
128 (:with-fixed-width nil ":" org-export-with-fixed-width)
129 (:with-footnotes nil "f" org-export-with-footnotes)
130 (:with-priority nil "pri" org-export-with-priority)
131 (:with-special-strings nil "-" org-export-with-special-strings)
132 (:with-sub-superscript nil "^" org-export-with-sub-superscripts)
133 (:with-toc nil "toc" org-export-with-toc)
134 (:with-tables nil "|" org-export-with-tables)
135 (:with-tags nil "tags" org-export-with-tags)
136 (:with-tasks nil "tasks" org-export-with-tasks)
137 (:with-timestamps nil "<" org-export-with-timestamps)
138 (:with-todo-keywords nil "todo" org-export-with-todo-keywords))
139 "Alist between export properties and ways to set them.
141 The car of the alist is the property name, and the cdr is a list
142 like \(KEYWORD OPTION DEFAULT BEHAVIOUR\) where:
144 KEYWORD is a string representing a buffer keyword, or nil.
145 OPTION is a string that could be found in an #+OPTIONS: line.
146 DEFAULT is the default value for the property.
147 BEHAVIOUR determine how Org should handle multiple keywords for
148 the same property. It is a symbol among:
149 nil Keep old value and discard the new one.
150 t Replace old value with the new one.
151 `space' Concatenate the values, separating them with a space.
152 `newline' Concatenate the values, separating them with
153 a newline.
154 `split' Split values at white spaces, and cons them to the
155 previous list.
157 KEYWORD and OPTION have precedence over DEFAULT.
159 All these properties should be back-end agnostic. For back-end
160 specific properties, define a similar variable named
161 `org-BACKEND-option-alist', replacing BACKEND with the name of
162 the appropriate back-end. You can also redefine properties
163 there, as they have precedence over these.")
165 (defconst org-export-special-keywords
166 '("SETUP_FILE" "OPTIONS" "MACRO")
167 "List of in-buffer keywords that require special treatment.
168 These keywords are not directly associated to a property. The
169 way they are handled must be hard-coded into
170 `org-export-get-inbuffer-options' function.")
174 ;;; User-configurable Variables
176 ;; Configuration for the masses.
178 ;; They should never be evaled directly, as their value is to be
179 ;; stored in a property list (cf. `org-export-option-alist').
181 (defgroup org-export nil
182 "Options for exporting Org mode files."
183 :tag "Org Export"
184 :group 'org)
186 (defgroup org-export-general nil
187 "General options for export engine."
188 :tag "Org Export General"
189 :group 'org-export)
191 (defcustom org-export-with-archived-trees 'headline
192 "Whether sub-trees with the ARCHIVE tag should be exported.
194 This can have three different values:
195 nil Do not export, pretend this tree is not present.
196 t Do export the entire tree.
197 `headline' Only export the headline, but skip the tree below it.
199 This option can also be set with the #+OPTIONS line,
200 e.g. \"arch:nil\"."
201 :group 'org-export-general
202 :type '(choice
203 (const :tag "Not at all" nil)
204 (const :tag "Headline only" 'headline)
205 (const :tag "Entirely" t)))
207 (defcustom org-export-with-author t
208 "Non-nil means insert author name into the exported file.
209 This option can also be set with the #+OPTIONS line,
210 e.g. \"author:nil\"."
211 :group 'org-export-general
212 :type 'boolean)
214 (defcustom org-export-with-creator 'comment
215 "Non-nil means the postamble should contain a creator sentence.
217 The sentence can be set in `org-export-creator-string' and
218 defaults to \"Generated by Org mode XX in Emacs XXX.\".
220 If the value is `comment' insert it as a comment."
221 :group 'org-export-general
222 :type '(choice
223 (const :tag "No creator sentence" nil)
224 (const :tag "Sentence as a comment" 'comment)
225 (const :tag "Insert the sentence" t)))
227 (defcustom org-export-creator-string
228 (format "Generated by Org mode %s in Emacs %s." org-version emacs-version)
229 "String to insert at the end of the generated document."
230 :group 'org-export-general
231 :type '(string :tag "Creator string"))
233 (defcustom org-export-with-drawers nil
234 "Non-nil means export with drawers like the property drawer.
235 When t, all drawers are exported. This may also be a list of
236 drawer names to export."
237 :group 'org-export-general
238 :type '(choice
239 (const :tag "All drawers" t)
240 (const :tag "None" nil)
241 (repeat :tag "Selected drawers"
242 (string :tag "Drawer name"))))
244 (defcustom org-export-with-email nil
245 "Non-nil means insert author email into the exported file.
246 This option can also be set with the #+OPTIONS line,
247 e.g. \"email:t\"."
248 :group 'org-export-general
249 :type 'boolean)
251 (defcustom org-export-with-emphasize t
252 "Non-nil means interpret *word*, /word/, and _word_ as emphasized text.
254 If the export target supports emphasizing text, the word will be
255 typeset in bold, italic, or underlined, respectively. Not all
256 export backends support this.
258 This option can also be set with the #+OPTIONS line, e.g. \"*:nil\"."
259 :group 'org-export-general
260 :type 'boolean)
262 (defcustom org-export-exclude-tags '("noexport")
263 "Tags that exclude a tree from export.
264 All trees carrying any of these tags will be excluded from
265 export. This is without condition, so even subtrees inside that
266 carry one of the `org-export-select-tags' will be removed."
267 :group 'org-export-general
268 :type '(repeat (string :tag "Tag")))
270 (defcustom org-export-with-fixed-width t
271 "Non-nil means lines starting with \":\" will be in fixed width font.
273 This can be used to have pre-formatted text, fragments of code
274 etc. For example:
275 : ;; Some Lisp examples
276 : (while (defc cnt)
277 : (ding))
278 will be looking just like this in also HTML. See also the QUOTE
279 keyword. Not all export backends support this.
281 This option can also be set with the #+OPTIONS line, e.g. \"::nil\"."
282 :group 'org-export-translation
283 :type 'boolean)
285 (defcustom org-export-with-footnotes t
286 "Non-nil means Org footnotes should be exported.
287 This option can also be set with the #+OPTIONS line,
288 e.g. \"f:nil\"."
289 :group 'org-export-general
290 :type 'boolean)
292 (defcustom org-export-headline-levels 3
293 "The last level which is still exported as a headline.
295 Inferior levels will produce itemize lists when exported. Note
296 that a numeric prefix argument to an exporter function overrides
297 this setting.
299 This option can also be set with the #+OPTIONS line, e.g. \"H:2\"."
300 :group 'org-export-general
301 :type 'integer)
303 (defcustom org-export-default-language "en"
304 "The default language for export and clocktable translations, as a string.
305 This may have an association in
306 `org-clock-clocktable-language-setup'."
307 :group 'org-export-general
308 :type '(string :tag "Language"))
310 (defcustom org-export-preserve-breaks nil
311 "Non-nil means preserve all line breaks when exporting.
313 Normally, in HTML output paragraphs will be reformatted.
315 This option can also be set with the #+OPTIONS line,
316 e.g. \"\\n:t\"."
317 :group 'org-export-general
318 :type 'boolean)
320 (defcustom org-export-with-entities t
321 "Non-nil means interpret entities when exporting.
323 For example, HTML export converts \\alpha to &alpha; and \\AA to
324 &Aring;.
326 For a list of supported names, see the constant `org-entities'
327 and the user option `org-entities-user'.
329 This option can also be set with the #+OPTIONS line,
330 e.g. \"e:nil\"."
331 :group 'org-export-general
332 :type 'boolean)
334 (defcustom org-export-with-priority nil
335 "Non-nil means include priority cookies in export.
336 When nil, remove priority cookies for export."
337 :group 'org-export-general
338 :type 'boolean)
340 (defcustom org-export-with-section-numbers t
341 "Non-nil means add section numbers to headlines when exporting.
343 This option can also be set with the #+OPTIONS line,
344 e.g. \"num:t\"."
345 :group 'org-export-general
346 :type 'boolean)
348 (defcustom org-export-select-tags '("export")
349 "Tags that select a tree for export.
350 If any such tag is found in a buffer, all trees that do not carry
351 one of these tags will be deleted before export. Inside trees
352 that are selected like this, you can still deselect a subtree by
353 tagging it with one of the `org-export-exclude-tags'."
354 :group 'org-export-general
355 :type '(repeat (string :tag "Tag")))
357 (defcustom org-export-with-special-strings t
358 "Non-nil means interpret \"\-\", \"--\" and \"---\" for export.
360 When this option is turned on, these strings will be exported as:
362 Org HTML LaTeX
363 -----+----------+--------
364 \\- &shy; \\-
365 -- &ndash; --
366 --- &mdash; ---
367 ... &hellip; \ldots
369 This option can also be set with the #+OPTIONS line,
370 e.g. \"-:nil\"."
371 :group 'org-export-general
372 :type 'boolean)
374 (defcustom org-export-with-sub-superscripts t
375 "Non-nil means interpret \"_\" and \"^\" for export.
377 When this option is turned on, you can use TeX-like syntax for
378 sub- and superscripts. Several characters after \"_\" or \"^\"
379 will be considered as a single item - so grouping with {} is
380 normally not needed. For example, the following things will be
381 parsed as single sub- or superscripts.
383 10^24 or 10^tau several digits will be considered 1 item.
384 10^-12 or 10^-tau a leading sign with digits or a word
385 x^2-y^3 will be read as x^2 - y^3, because items are
386 terminated by almost any nonword/nondigit char.
387 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
389 Still, ambiguity is possible - so when in doubt use {} to enclose
390 the sub/superscript. If you set this variable to the symbol
391 `{}', the braces are *required* in order to trigger
392 interpretations as sub/superscript. This can be helpful in
393 documents that need \"_\" frequently in plain text.
395 This option can also be set with the #+OPTIONS line,
396 e.g. \"^:nil\"."
397 :group 'org-export-general
398 :type '(choice
399 (const :tag "Interpret them" t)
400 (const :tag "Curly brackets only" {})
401 (const :tag "Do not interpret them" nil)))
403 (defcustom org-export-with-toc t
404 "Non-nil means create a table of contents in exported files.
406 The TOC contains headlines with levels up
407 to`org-export-headline-levels'. When an integer, include levels
408 up to N in the toc, this may then be different from
409 `org-export-headline-levels', but it will not be allowed to be
410 larger than the number of headline levels. When nil, no table of
411 contents is made.
413 This option can also be set with the #+OPTIONS line,
414 e.g. \"toc:nil\" or \"toc:3\"."
415 :group 'org-export-general
416 :type '(choice
417 (const :tag "No Table of Contents" nil)
418 (const :tag "Full Table of Contents" t)
419 (integer :tag "TOC to level")))
421 (defcustom org-export-with-tables t
422 "If non-nil, lines starting with \"|\" define a table.
423 For example:
425 | Name | Address | Birthday |
426 |-------------+----------+-----------|
427 | Arthur Dent | England | 29.2.2100 |
429 This option can also be set with the #+OPTIONS line, e.g. \"|:nil\"."
430 :group 'org-export-general
431 :type 'boolean)
433 (defcustom org-export-with-tags t
434 "If nil, do not export tags, just remove them from headlines.
436 If this is the symbol `not-in-toc', tags will be removed from
437 table of contents entries, but still be shown in the headlines of
438 the document.
440 This option can also be set with the #+OPTIONS line,
441 e.g. \"tags:nil\"."
442 :group 'org-export-general
443 :type '(choice
444 (const :tag "Off" nil)
445 (const :tag "Not in TOC" not-in-toc)
446 (const :tag "On" t)))
448 (defcustom org-export-with-tasks t
449 "Non-nil means include TODO items for export.
450 This may have the following values:
451 t include tasks independent of state.
452 todo include only tasks that are not yet done.
453 done include only tasks that are already done.
454 nil remove all tasks before export
455 list of keywords keep only tasks with these keywords"
456 :group 'org-export-general
457 :type '(choice
458 (const :tag "All tasks" t)
459 (const :tag "No tasks" nil)
460 (const :tag "Not-done tasks" todo)
461 (const :tag "Only done tasks" done)
462 (repeat :tag "Specific TODO keywords"
463 (string :tag "Keyword"))))
465 (defcustom org-export-time-stamp-file t
466 "Non-nil means insert a time stamp into the exported file.
467 The time stamp shows when the file was created.
469 This option can also be set with the #+OPTIONS line,
470 e.g. \"timestamp:nil\"."
471 :group 'org-export-general
472 :type 'boolean)
474 (defcustom org-export-with-timestamps t
475 "If nil, do not export time stamps and associated keywords."
476 :group 'org-export-general
477 :type 'boolean)
479 (defcustom org-export-with-todo-keywords t
480 "Non-nil means include TODO keywords in export.
481 When nil, remove all these keywords from the export.")
483 (defcustom org-export-allow-BIND 'confirm
484 "Non-nil means allow #+BIND to define local variable values for export.
485 This is a potential security risk, which is why the user must
486 confirm the use of these lines."
487 :group 'org-export-general
488 :type '(choice
489 (const :tag "Never" nil)
490 (const :tag "Always" t)
491 (const :tag "Ask a confirmation for each file" confirm)))
493 (defcustom org-export-snippet-translation-alist nil
494 "Alist between export snippets back-ends and exporter back-ends.
496 This variable allows to provide shortcuts for export snippets.
498 For example, with a value of '\(\(\"h\" . \"html\"\)\), the HTML
499 back-end will recognize the contents of \"@h{<b>}\" as HTML code
500 while every other back-end will ignore it."
501 :group 'org-export-general
502 :type '(repeat
503 (cons
504 (string :tag "Shortcut")
505 (string :tag "Back-end"))))
507 (defcustom org-export-coding-system nil
508 "Coding system for the exported file."
509 :group 'org-export-general
510 :type 'coding-system)
512 (defcustom org-export-copy-to-kill-ring t
513 "Non-nil means exported stuff will also be pushed onto the kill ring."
514 :group 'org-export-general
515 :type 'boolean)
517 (defcustom org-export-initial-scope 'buffer
518 "The initial scope when exporting with `org-export-dispatch'.
519 This variable can be either set to `buffer' or `subtree'."
520 :group 'org-export-general
521 :type '(choice
522 (const :tag "Export current buffer" 'buffer)
523 (const :tag "Export current subtree" 'subtree)))
525 (defcustom org-export-show-temporary-export-buffer t
526 "Non-nil means show buffer after exporting to temp buffer.
527 When Org exports to a file, the buffer visiting that file is ever
528 shown, but remains buried. However, when exporting to a temporary
529 buffer, that buffer is popped up in a second window. When this variable
530 is nil, the buffer remains buried also in these cases."
531 :group 'org-export-general
532 :type 'boolean)
534 (defcustom org-export-dispatch-use-expert-ui nil
535 "Non-nil means using a non-intrusive `org-export-dispatch'.
536 In that case, no help buffer is displayed. Though, an indicator
537 for current export scope is added to the prompt \(i.e. \"b\" when
538 output is restricted to body only, \"s\" when it is restricted to
539 the current subtree and \"v\" when only visible elements are
540 considered for export\). Also, \[?] allows to switch back to
541 standard mode."
542 :group 'org-export-general
543 :type 'boolean)
547 ;;; The Communication Channel
549 ;; During export process, every function has access to a number of
550 ;; properties. They are of three types:
552 ;; 1. Export options are collected once at the very beginning of the
553 ;; process, out of the original buffer and environment. The task
554 ;; is handled by `org-export-collect-options' function.
556 ;; All export options are defined through the
557 ;; `org-export-option-alist' variable.
559 ;; 2. Persistent properties are stored in
560 ;; `org-export-persistent-properties' and available at every level
561 ;; of recursion. Their value is extracted directly from the parsed
562 ;; tree, and depends on export options (whole trees may be filtered
563 ;; out of the export process).
565 ;; Properties belonging to that type are defined in the
566 ;; `org-export-persistent-properties-list' variable.
568 ;; 3. Every other property is considered local, and available at
569 ;; a precise level of recursion and below.
571 ;; Managing properties during transcode process is mainly done with
572 ;; `org-export-update-info'. Even though they come from different
573 ;; sources, the function transparently concatenates them in a single
574 ;; property list passed as an argument to each transcode function.
575 ;; Thus, during export, all necessary information is available through
576 ;; that single property list, and the element or object itself.
577 ;; Though, modifying a property will still require some special care,
578 ;; and should be done with `org-export-set-property' instead of plain
579 ;; `plist-put'.
581 ;; Here is the full list of properties available during transcode
582 ;; process, with their category (option, persistent or local), their
583 ;; value type and the function updating them, when appropriate.
585 ;; + `author' :: Author's name.
586 ;; - category :: option
587 ;; - type :: string
589 ;; + `back-end' :: Current back-end used for transcoding.
590 ;; - category :: persistent
591 ;; - type :: symbol
593 ;; + `code-refs' :: Association list between reference name and real
594 ;; labels in source code. It is used to properly
595 ;; resolve links inside source blocks.
596 ;; - category :: persistent
597 ;; - type :: alist (INT-OR-STRING . STRING)
598 ;; - update :: `org-export-handle-code'
600 ;; + `creator' :: String to write as creation information.
601 ;; - category :: option
602 ;; - type :: string
604 ;; + `date' :: String to use as date.
605 ;; - category :: option
606 ;; - type :: string
608 ;; + `description' :: Description text for the current data.
609 ;; - category :: option
610 ;; - type :: string
612 ;; + `email' :: Author's email.
613 ;; - category :: option
614 ;; - type :: string
616 ;; + `exclude-tags' :: Tags for exclusion of subtrees from export
617 ;; process.
618 ;; - category :: option
619 ;; - type :: list of strings
621 ;; + `footnote-definition-alist' :: Alist between footnote labels and
622 ;; their definition, as parsed data. Only non-inlined footnotes
623 ;; are represented in this alist. Also, every definition isn't
624 ;; guaranteed to be referenced in the parse tree. The purpose of
625 ;; this property is to preserve definitions from oblivion
626 ;; (i.e. when the parse tree comes from a part of the original
627 ;; buffer), it isn't meant for direct use in a back-end. To
628 ;; retrieve a definition relative to a reference, use
629 ;; `org-export-get-footnote-definition' instead.
630 ;; - category :: option
631 ;; - type :: alist (STRING . LIST)
633 ;; + `genealogy' :: Flat list of current object or element's parents
634 ;; from closest to farthest.
635 ;; - category :: local
636 ;; - type :: list of elements and objects
637 ;; - update :: `org-export-update-info'
639 ;; + `headline-alist' :: Alist between headlines raw name and their
640 ;; boundaries. It is used to resolve "fuzzy" links
641 ;; (cf. `org-export-resolve-fuzzy-link').
642 ;; - category :: persistent
643 ;; - type :: alist (STRING INTEGER INTEGER)
645 ;; + `headline-levels' :: Maximum level being exported as an
646 ;; headline. Comparison is done with the relative level of
647 ;; headlines in the parse tree, not necessarily with their
648 ;; actual level.
649 ;; - category :: option
650 ;; - type :: integer
652 ;; + `headline-offset' :: Difference between relative and real level
653 ;; of headlines in the parse tree. For example, a value of -1
654 ;; means a level 2 headline should be considered as level
655 ;; 1 (cf. `org-export-get-relative-level').
656 ;; - category :: persistent
657 ;; - type :: integer
659 ;; + `headline-numbering' :: Alist between headlines' beginning
660 ;; position and their numbering, as a list of numbers
661 ;; (cf. `org-export-get-headline-number').
662 ;; - category :: persistent
663 ;; - type :: alist (INTEGER . LIST)
665 ;; + `included-files' :: List of files, with full path, included in
666 ;; the current buffer, through the "#+include:" keyword. It is
667 ;; mainly used to verify that no infinite recursive inclusion
668 ;; happens.
669 ;; - category :: local
670 ;; - type :: list of strings
672 ;; + `keywords' :: List of keywords attached to data.
673 ;; - category :: option
674 ;; - type :: string
676 ;; + `language' :: Default language used for translations.
677 ;; - category :: option
678 ;; - type :: string
680 ;; + `parse-tree' :: Whole parse tree, available at any time during
681 ;; transcoding.
682 ;; - category :: global
683 ;; - type :: list (as returned by `org-element-parse-buffer')
685 ;; + `point-max' :: Last ending position in the parse tree.
686 ;; - category :: global
687 ;; - type :: integer
689 ;; + `preserve-breaks' :: Non-nil means transcoding should preserve
690 ;; all line breaks.
691 ;; - category :: option
692 ;; - type :: symbol (nil, t)
694 ;; + `section-numbers' :: Non-nil means transcoding should add
695 ;; section numbers to headlines.
696 ;; - category :: option
697 ;; - type :: symbol (nil, t)
699 ;; + `select-tags' :: List of tags enforcing inclusion of sub-trees in
700 ;; transcoding. When such a tag is present,
701 ;; subtrees without it are de facto excluded from
702 ;; the process. See `use-select-tags'.
703 ;; - category :: option
704 ;; - type :: list of strings
706 ;; + `target-list' :: List of targets raw names encoutered in the
707 ;; parse tree. This is used to partly resolve
708 ;; "fuzzy" links
709 ;; (cf. `org-export-resolve-fuzzy-link').
710 ;; - category :: persistent
711 ;; - type :: list of strings
713 ;; + `time-stamp-file' :: Non-nil means transcoding should insert
714 ;; a time stamp in the output.
715 ;; - category :: option
716 ;; - type :: symbol (nil, t)
718 ;; + `total-loc' :: Contains total lines of code accumulated by source
719 ;; blocks with the "+n" option so far.
720 ;; - category :: persistent
721 ;; - type :: integer
722 ;; - update :: `org-export-handle-code'
724 ;; + `use-select-tags' :: When non-nil, a select tags has been found
725 ;; in the parse tree. Thus, any headline without one will be
726 ;; filtered out. See `select-tags'.
727 ;; - category :: persistent
728 ;; - type :: interger or nil
730 ;; + `with-archived-trees' :: Non-nil when archived subtrees should
731 ;; also be transcoded. If it is set to the `headline' symbol,
732 ;; only the archived headline's name is retained.
733 ;; - category :: option
734 ;; - type :: symbol (nil, t, `headline')
736 ;; + `with-author' :: Non-nil means author's name should be included
737 ;; in the output.
738 ;; - category :: option
739 ;; - type :: symbol (nil, t)
741 ;; + `with-creator' :: Non-nild means a creation sentence should be
742 ;; inserted at the end of the transcoded string. If the value
743 ;; is `comment', it should be commented.
744 ;; - category :: option
745 ;; - type :: symbol (`comment', nil, t)
747 ;; + `with-drawers' :: Non-nil means drawers should be exported. If
748 ;; its value is a list of names, only drawers with such names
749 ;; will be transcoded.
750 ;; - category :: option
751 ;; - type :: symbol (nil, t) or list of strings
753 ;; + `with-email' :: Non-nil means output should contain author's
754 ;; email.
755 ;; - category :: option
756 ;; - type :: symbol (nil, t)
758 ;; + `with-emphasize' :: Non-nil means emphasized text should be
759 ;; interpreted.
760 ;; - category :: option
761 ;; - type :: symbol (nil, t)
763 ;; + `with-fixed-width' :: Non-nil if transcoder should interpret
764 ;; strings starting with a colon as a fixed-with (verbatim)
765 ;; area.
766 ;; - category :: option
767 ;; - type :: symbol (nil, t)
769 ;; + `with-footnotes' :: Non-nil if transcoder should interpret
770 ;; footnotes.
771 ;; - category :: option
772 ;; - type :: symbol (nil, t)
774 ;; + `with-priority' :: Non-nil means transcoding should include
775 ;; priority cookies.
776 ;; - category :: option
777 ;; - type :: symbol (nil, t)
779 ;; + `with-special-strings' :: Non-nil means transcoding should
780 ;; interpret special strings in plain text.
781 ;; - category :: option
782 ;; - type :: symbol (nil, t)
784 ;; + `with-sub-superscript' :: Non-nil means transcoding should
785 ;; interpret subscript and superscript. With a value of "{}",
786 ;; only interpret those using curly brackets.
787 ;; - category :: option
788 ;; - type :: symbol (nil, {}, t)
790 ;; + `with-tables' :: Non-nil means transcoding should interpret
791 ;; tables.
792 ;; - category :: option
793 ;; - type :: symbol (nil, t)
795 ;; + `with-tags' :: Non-nil means transcoding should keep tags in
796 ;; headlines. A `not-in-toc' value will remove them
797 ;; from the table of contents, if any, nonetheless.
798 ;; - category :: option
799 ;; - type :: symbol (nil, t, `not-in-toc')
801 ;; + `with-tasks' :: Non-nil means transcoding should include
802 ;; headlines with a TODO keyword. A `todo' value
803 ;; will only include headlines with a todo type
804 ;; keyword while a `done' value will do the
805 ;; contrary. If a list of strings is provided, only
806 ;; tasks with keywords belonging to that list will
807 ;; be kept.
808 ;; - category :: option
809 ;; - type :: symbol (t, todo, done, nil) or list of strings
811 ;; + `with-timestamps' :: Non-nil means transcoding should include
812 ;; time stamps and associated keywords. Otherwise, completely
813 ;; remove them.
814 ;; - category :: option
815 ;; - type :: symbol: (t, nil)
817 ;; + `with-toc' :: Non-nil means that a table of contents has to be
818 ;; added to the output. An integer value limits its
819 ;; depth.
820 ;; - category :: option
821 ;; - type :: symbol (nil, t or integer)
823 ;; + `with-todo-keywords' :: Non-nil means transcoding should
824 ;; include TODO keywords.
825 ;; - category :: option
826 ;; - type :: symbol (nil, t)
828 ;;;; Export Options
830 ;; Export options come from five sources, in increasing precedence
831 ;; order:
833 ;; - Global variables,
834 ;; - External options provided at export time,
835 ;; - Options keyword symbols,
836 ;; - Buffer keywords,
837 ;; - Subtree properties.
839 ;; The central internal function with regards to export options is
840 ;; `org-export-collect-options'. It updates global variables with
841 ;; "#+BIND:" keywords, then retrieve and prioritize properties from
842 ;; the different sources.
844 ;; The internal functions doing the retrieval are:
845 ;; `org-export-parse-option-keyword' ,
846 ;; `org-export-get-subtree-options' ,
847 ;; `org-export-get-inbuffer-options' and
848 ;; `org-export-get-global-options'.
850 ;; Some properties do not rely on the previous sources but still
851 ;; depend on the original buffer are taken care of in
852 ;; `org-export-initial-options'.
854 ;; Also, `org-export-confirm-letbind' and `org-export-install-letbind'
855 ;; take care of the part relative to "#+BIND:" keywords.
857 (defun org-export-collect-options (backend subtreep ext-plist)
858 "Collect export options from the current buffer.
860 BACKEND is a symbol specifying the back-end to use.
862 When SUBTREEP is non-nil, assume the export is done against the
863 current sub-tree.
865 EXT-PLIST is a property list with external parameters overriding
866 org-mode's default settings, but still inferior to file-local
867 settings."
868 ;; First install #+BIND variables.
869 (org-export-install-letbind-maybe)
870 ;; Get and prioritize export options...
871 (let ((options (org-combine-plists
872 ;; ... from global variables...
873 (org-export-get-global-options backend)
874 ;; ... from an external property list...
875 ext-plist
876 ;; ... from in-buffer settings...
877 (org-export-get-inbuffer-options
878 (org-with-wide-buffer (buffer-string)) backend
879 (and buffer-file-name
880 (org-remove-double-quotes buffer-file-name)))
881 ;; ... and from subtree, when appropriate.
882 (and subtreep
883 (org-export-get-subtree-options)))))
884 ;; Add initial options.
885 (setq options (append (org-export-initial-options options)
886 options))
887 ;; Set a default title if none has been specified so far.
888 (unless (plist-get options :title)
889 (setq options (plist-put options :title
890 (or (and buffer-file-name
891 (file-name-sans-extension
892 (file-name-nondirectory
893 buffer-file-name)))
894 (buffer-name)))))
895 ;; Return plist.
896 options))
898 (defun org-export-parse-option-keyword (options backend)
899 "Parse an OPTIONS line and return values as a plist.
900 BACKEND is a symbol specifying the back-end to use."
901 (let* ((all (append org-export-option-alist
902 (let ((var (intern
903 (format "org-%s-option-alist" backend))))
904 (and (boundp var) (eval var)))))
905 ;; Build an alist between #+OPTION: item and property-name.
906 (alist (delq nil
907 (mapcar (lambda (e)
908 (when (nth 2 e) (cons (regexp-quote (nth 2 e))
909 (car e))))
910 all)))
911 plist)
912 (mapc (lambda (e)
913 (when (string-match (concat "\\(\\`\\|[ \t]\\)"
914 (car e)
915 ":\\(([^)\n]+)\\|[^ \t\n\r;,.]*\\)")
916 options)
917 (setq plist (plist-put plist
918 (cdr e)
919 (car (read-from-string
920 (match-string 2 options)))))))
921 alist)
922 plist))
924 (defun org-export-get-subtree-options ()
925 "Get export options in subtree at point.
927 Assume point is at subtree's beginning.
929 Return options as a plist."
930 (let (prop plist)
931 (when (setq prop (progn (looking-at org-todo-line-regexp)
932 (or (save-match-data
933 (org-entry-get (point) "EXPORT_TITLE"))
934 (org-match-string-no-properties 3))))
935 (setq plist (plist-put plist :title prop)))
936 (when (setq prop (org-entry-get (point) "EXPORT_TEXT"))
937 (setq plist (plist-put plist :text prop)))
938 (when (setq prop (org-entry-get (point) "EXPORT_AUTHOR"))
939 (setq plist (plist-put plist :author prop)))
940 (when (setq prop (org-entry-get (point) "EXPORT_DATE"))
941 (setq plist (plist-put plist :date prop)))
942 (when (setq prop (org-entry-get (point) "EXPORT_OPTIONS"))
943 (setq plist (org-export-add-options-to-plist plist prop)))
944 plist))
946 (defun org-export-get-inbuffer-options (buffer-string backend files)
947 "Return in-buffer options as a plist.
948 BUFFER-STRING is the string of the buffer. BACKEND is a symbol
949 specifying which back-end should be used."
950 (let ((case-fold-search t) plist)
951 ;; 1. Special keywords, as in `org-export-special-keywords'.
952 (let ((start 0)
953 (special-re (org-make-options-regexp org-export-special-keywords)))
954 (while (string-match special-re buffer-string start)
955 (setq start (match-end 0))
956 (let ((key (upcase (org-match-string-no-properties 1 buffer-string)))
957 ;; Special keywords do not have their value expanded.
958 (val (org-match-string-no-properties 2 buffer-string)))
959 (setq plist
960 (org-combine-plists
961 (cond
962 ((string= key "SETUP_FILE")
963 (let ((file (expand-file-name
964 (org-remove-double-quotes (org-trim val)))))
965 ;; Avoid circular dependencies.
966 (unless (member file files)
967 (org-export-get-inbuffer-options
968 (org-file-contents file 'noerror)
969 backend
970 (cons file files)))))
971 ((string= key "OPTIONS")
972 (org-export-parse-option-keyword val backend))
973 ((string= key "MACRO")
974 (string-match "^\\([-a-zA-Z0-9_]+\\)[ \t]+\\(.*?[ \t]*$\\)"
975 val)
976 (plist-put nil
977 (intern (concat ":macro-"
978 (downcase (match-string 1 val))))
979 (match-string 2 val))))
980 plist)))))
981 ;; 2. Standard options, as in `org-export-option-alist'.
982 (let* ((all (append org-export-option-alist
983 (let ((var (intern
984 (format "org-%s-option-alist" backend))))
985 (and (boundp var) (eval var)))))
986 ;; Build alist between keyword name and property name.
987 (alist (delq nil (mapcar (lambda (e)
988 (when (nth 1 e) (cons (nth 1 e) (car e))))
989 all)))
990 ;; Build regexp matching all keywords associated to export
991 ;; options. Note: the search is case insensitive.
992 (opt-re (org-make-options-regexp
993 (delq nil (mapcar (lambda (e) (nth 1 e)) all))))
994 (start 0))
995 (while (string-match opt-re buffer-string start)
996 (setq start (match-end 0))
997 (let* ((key (upcase (org-match-string-no-properties 1 buffer-string)))
998 ;; Expand value, applying restrictions for keywords.
999 (val (org-match-string-no-properties 2 buffer-string))
1000 (prop (cdr (assoc key alist)))
1001 (behaviour (nth 4 (assq prop all))))
1002 (setq plist
1003 (plist-put
1004 plist prop
1005 ;; Handle value depending on specified BEHAVIOUR.
1006 (case behaviour
1007 (space (if (plist-get plist prop)
1008 (concat (plist-get plist prop) " " (org-trim val))
1009 (org-trim val)))
1010 (newline (org-trim
1011 (concat
1012 (plist-get plist prop) "\n" (org-trim val))))
1013 (split `(,@(plist-get plist prop) ,@(org-split-string val)))
1014 ('t val)
1015 (otherwise (plist-get plist prop)))))))
1016 ;; Parse keywords specified in `org-element-parsed-keywords'.
1017 (mapc
1018 (lambda (key)
1019 (let* ((prop (cdr (assoc (upcase key) alist)))
1020 (value (and prop (plist-get plist prop))))
1021 (when (stringp value)
1022 (setq plist
1023 (plist-put
1024 plist prop
1025 (org-element-parse-secondary-string
1026 value
1027 (cdr (assq 'keyword org-element-string-restrictions))))))))
1028 org-element-parsed-keywords))
1029 ;; Return final value.
1030 plist))
1032 (defun org-export-get-global-options (backend)
1033 "Return global export options as a plist.
1034 BACKEND is a symbol specifying which back-end should be used."
1035 (let ((all (append org-export-option-alist
1036 (let ((var (intern
1037 (format "org-%s-option-alist" backend))))
1038 (and (boundp var) (eval var)))))
1039 ;; Output value.
1040 plist)
1041 (mapc (lambda (cell)
1042 (setq plist
1043 (plist-put plist (car cell) (eval (nth 3 cell)))))
1044 all)
1045 ;; Return value.
1046 plist))
1048 (defun org-export-initial-options (options)
1049 "Return a plist with non-optional properties.
1050 OPTIONS is the export options plist computed so far."
1051 (list
1052 ;; `:macro-date', `:macro-time' and `:macro-property' could as well
1053 ;; be initialized as persistent properties, since they don't depend
1054 ;; on initial environment. Though, it may be more logical to keep
1055 ;; them close to other ":macro-" properties.
1056 :macro-date "(eval (format-time-string \"$1\"))"
1057 :macro-time "(eval (format-time-string \"$1\"))"
1058 :macro-property "(eval (org-entry-get nil \"$1\" 'selective))"
1059 :macro-modification-time
1060 (and (buffer-file-name)
1061 (file-exists-p (buffer-file-name))
1062 (concat "(eval (format-time-string \"$1\" '"
1063 (prin1-to-string (nth 5 (file-attributes (buffer-file-name))))
1064 "))"))
1065 :macro-input-file (and (buffer-file-name)
1066 (file-name-nondirectory (buffer-file-name)))
1067 ;; Footnotes definitions must be collected in the original buffer,
1068 ;; as there's no insurance that they will still be in the parse
1069 ;; tree, due to some narrowing.
1070 :footnote-definition-alist
1071 (let (alist)
1072 (org-with-wide-buffer
1073 (goto-char (point-min))
1074 (while (re-search-forward org-footnote-definition-re nil t)
1075 (let ((def (org-footnote-at-definition-p)))
1076 (when def
1077 (org-skip-whitespace)
1078 (push (cons (car def)
1079 (save-restriction
1080 (narrow-to-region (point) (nth 2 def))
1081 (org-element-parse-buffer)))
1082 alist))))
1083 alist))))
1085 (defvar org-export-allow-BIND-local nil)
1086 (defun org-export-confirm-letbind ()
1087 "Can we use #+BIND values during export?
1088 By default this will ask for confirmation by the user, to divert
1089 possible security risks."
1090 (cond
1091 ((not org-export-allow-BIND) nil)
1092 ((eq org-export-allow-BIND t) t)
1093 ((local-variable-p 'org-export-allow-BIND-local) org-export-allow-BIND-local)
1094 (t (org-set-local 'org-export-allow-BIND-local
1095 (yes-or-no-p "Allow BIND values in this buffer? ")))))
1097 (defun org-export-install-letbind-maybe ()
1098 "Install the values from #+BIND lines as local variables.
1099 Variables must be installed before in-buffer options are
1100 retrieved."
1101 (let (letbind pair)
1102 (org-with-wide-buffer
1103 (goto-char (point-min))
1104 (while (re-search-forward (org-make-options-regexp '("BIND")) nil t)
1105 (when (org-export-confirm-letbind)
1106 (push (read (concat "(" (org-match-string-no-properties 2) ")"))
1107 letbind))))
1108 (while (setq pair (pop letbind))
1109 (org-set-local (car pair) (nth 1 pair)))))
1112 ;;;; Persistent Properties
1114 ;; Persistent properties are declared in
1115 ;; `org-export-persistent-properties-list' variable. Most of them are
1116 ;; initialized at the beginning of the transcoding process by
1117 ;; `org-export-initialize-persistent-properties'. The others are
1118 ;; updated during that process.
1120 ;; Dedicated functions focus on computing the value of specific
1121 ;; persistent properties during initialization. Thus,
1122 ;; `org-export-use-select-tag-p' determines if an headline makes use
1123 ;; of an export tag enforcing inclusion. `org-export-get-min-level'
1124 ;; gets the minimal exportable level, used as a basis to compute
1125 ;; relative level for headlines. `org-export-get-point-max' returns
1126 ;; the maximum exportable ending position in the parse tree.
1127 ;; Eventually `org-export-collect-headline-numbering' builds an alist
1128 ;; between headlines' beginning position and their numbering.
1130 (defconst org-export-persistent-properties-list
1131 '(:back-end :code-refs :headline-alist :headline-numbering :headline-offset
1132 :parse-tree :point-max :target-list :total-loc :use-select-tags)
1133 "List of persistent properties.")
1135 (defconst org-export-persistent-properties nil
1136 "Used internally to store properties and values during transcoding.
1138 Only properties that should survive recursion are saved here.
1140 This variable is reset before each transcoding.")
1142 (defun org-export-initialize-persistent-properties (data options backend)
1143 "Initialize `org-export-persistent-properties'.
1145 DATA is the parse tree from which information is retrieved.
1146 OPTIONS is a list holding export options. BACKEND is the
1147 back-end called for transcoding, as a symbol.
1149 Following initial persistent properties are set:
1150 `:back-end' Back-end used for transcoding.
1152 `:headline-alist' Alist of all headlines' name as key and a list
1153 holding beginning and ending positions as
1154 value.
1156 `:headline-offset' Offset between true level of headlines and
1157 local level. An offset of -1 means an headline
1158 of level 2 should be considered as a level
1159 1 headline in the context.
1161 `:headline-numbering' Alist of all headlines' beginning position
1162 as key an the associated numbering as value.
1164 `:parse-tree' Whole parse tree.
1166 `:point-max' Last position in the parse tree
1168 `:target-list' List of all targets' raw name in the parse tree.
1170 `:use-select-tags' Non-nil when parsed tree use a special tag to
1171 enforce transcoding of the headline."
1172 ;; First delete any residual persistent property.
1173 (setq org-export-persistent-properties nil)
1174 ;; Immediately after, set `:use-select-tags' property, as it will be
1175 ;; required for further computations.
1176 (setq options
1177 (org-export-set-property
1178 options
1179 :use-select-tags
1180 (org-export-use-select-tags-p data options)))
1181 ;; Get the rest of the initial persistent properties, now
1182 ;; `:use-select-tags' is set...
1183 ;; 1. `:parse-tree' ...
1184 (setq options (org-export-set-property options :parse-tree data))
1185 ;; 2. `:headline-offset' ...
1186 (setq options
1187 (org-export-set-property
1188 options :headline-offset
1189 (- 1 (org-export-get-min-level data options))))
1190 ;; 3. `:point-max' ...
1191 (setq options (org-export-set-property
1192 options :point-max
1193 (org-export-get-point-max data options)))
1194 ;; 4. `:target-list'...
1195 (setq options (org-export-set-property
1196 options :target-list
1197 (org-element-map
1198 data 'target
1199 (lambda (target info)
1200 (org-element-get-property :raw-value target)))))
1201 ;; 5. `:headline-alist'
1202 (setq options (org-export-set-property
1203 options :headline-alist
1204 (org-element-map
1205 data 'headline
1206 (lambda (headline info)
1207 (list (org-element-get-property :raw-value headline)
1208 (org-element-get-property :begin headline)
1209 (org-element-get-property :end headline))))))
1210 ;; 6. `:headline-numbering'
1211 (setq options (org-export-set-property
1212 options :headline-numbering
1213 (org-export-collect-headline-numbering data options)))
1214 ;; 7. `:back-end'
1215 (setq options (org-export-set-property options :back-end backend)))
1217 (defun org-export-use-select-tags-p (data options)
1218 "Non-nil when data use a tag enforcing transcoding.
1219 DATA is parsed data as returned by `org-element-parse-buffer'.
1220 OPTIONS is a plist holding export options."
1221 (org-element-map
1222 data
1223 'headline
1224 (lambda (headline info)
1225 (let ((tags (org-element-get-property :with-tags headline)))
1226 (and tags (string-match
1227 (format ":%s:" (plist-get info :select-tags)) tags))))
1228 options
1229 'stop-at-first-match))
1231 (defun org-export-get-min-level (data options)
1232 "Return minimum exportable headline's level in DATA.
1233 DATA is parsed tree as returned by `org-element-parse-buffer'.
1234 OPTIONS is a plist holding export options."
1235 (catch 'exit
1236 (let ((min-level 10000))
1237 (mapc (lambda (blob)
1238 (when (and (eq (car blob) 'headline)
1239 (not (org-export-skip-p blob options)))
1240 (setq min-level
1241 (min (org-element-get-property :level blob) min-level)))
1242 (when (= min-level 1) (throw 'exit 1)))
1243 (org-element-get-contents data))
1244 ;; If no headline was found, for the sake of consistency, set
1245 ;; minimum level to 1 nonetheless.
1246 (if (= min-level 10000) 1 min-level))))
1248 (defun org-export-get-point-max (data options)
1249 "Return last exportable ending position in DATA.
1250 DATA is parsed tree as returned by `org-element-parse-buffer'.
1251 OPTIONS is a plist holding export options."
1252 (let ((pos-max 1))
1253 (mapc (lambda (blob)
1254 (unless (and (eq (car blob) 'headline)
1255 (org-export-skip-p blob options))
1256 (setq pos-max (org-element-get-property :end blob))))
1257 (org-element-get-contents data))
1258 pos-max))
1260 (defun org-export-collect-headline-numbering (data options)
1261 "Return numbering of all exportable headlines in a parse tree.
1263 DATA is the parse tree. OPTIONS is the plist holding export
1264 options.
1266 Return an alist whose key is headline's beginning position and
1267 value is its associated numbering (in the shape of a list of
1268 numbers)."
1269 (let ((numbering (make-vector org-export-max-depth 0)))
1270 (org-element-map
1271 data
1272 'headline
1273 (lambda (headline info)
1274 (let ((relative-level
1275 (1- (org-export-get-relative-level headline info))))
1276 (cons
1277 (org-element-get-property :begin headline)
1278 (loop for n across numbering
1279 for idx from 0 to org-export-max-depth
1280 when (< idx relative-level) collect n
1281 when (= idx relative-level) collect (aset numbering idx (1+ n))
1282 when (> idx relative-level) do (aset numbering idx 0)))))
1283 options)))
1286 ;;;; Properties Management
1288 ;; This is mostly done with the help of two functions. On the one
1289 ;; hand `org-export-update-info' is used to keep up-to-date local
1290 ;; information while walking the nested list representing the parsed
1291 ;; document. On the other end, `org-export-set-property' handles
1292 ;; properties modifications according to their type (persistent or
1293 ;; local).
1295 ;; As exceptions, `:code-refs' and `:total-loc' properties are updated
1296 ;; with `org-export-handle-code' function.
1298 (defun org-export-update-info (blob info recursep)
1299 "Update export options depending on context.
1301 BLOB is the element or object being parsed. INFO is the plist
1302 holding the export options.
1304 When RECURSEP is non-nil, assume the following element or object
1305 will be inside the current one.
1307 The following properties are updated:
1308 `genealogy' List of current element's parents
1309 (list of elements and objects).
1310 `previous-element' Previous element's type (symbol).
1311 `previous-object' Previous object's type (symbol).
1313 Return the property list."
1314 (let* ((type (and (not (stringp blob)) (car blob))))
1315 (cond
1316 ;; Case 1: We're moving into a recursive blob.
1317 (recursep
1318 (org-combine-plists
1319 info
1320 `(:genealogy ,(cons blob (plist-get info :genealogy)))
1321 org-export-persistent-properties)))))
1323 (defun org-export-set-property (info prop value)
1324 "Set property PROP to VALUE in plist INFO.
1325 Return the new plist."
1326 (when (memq prop org-export-persistent-properties-list)
1327 (setq org-export-persistent-properties
1328 (plist-put org-export-persistent-properties prop value)))
1329 (plist-put info prop value))
1333 ;;; The Transcoder
1335 ;; This function reads Org data (obtained with, i.e.
1336 ;; `org-element-parse-buffer') and transcodes it into a specified
1337 ;; back-end output. It takes care of updating local properties,
1338 ;; filtering out elements or objects according to export options and
1339 ;; organizing the output blank lines and white space are preserved.
1341 ;; Though, this function is inapropriate for secondary strings, which
1342 ;; require a fresh copy of the plist passed as INFO argument. Thus,
1343 ;; `org-export-secondary-string' is provided for that specific task.
1345 ;; Internally, three functions handle the filtering of objects and
1346 ;; elements during the export. More precisely, `org-export-skip-p'
1347 ;; determines if the considered object or element should be ignored
1348 ;; altogether, `org-export-interpret-p' tells which elements or
1349 ;; objects should be seen as real Org syntax and `org-export-expand'
1350 ;; transforms the others back into their original shape.
1352 (defun org-export-data (data backend info)
1353 "Convert DATA to a string into BACKEND format.
1355 DATA is a nested list as returned by `org-element-parse-buffer'.
1357 BACKEND is a symbol among supported exporters.
1359 INFO is a plist holding export options and also used as
1360 a communication channel between elements when walking the nested
1361 list. See `org-export-update-info' function for more
1362 details.
1364 Return transcoded string."
1365 (mapconcat
1366 ;; BLOB can be an element, an object, a string, or nil.
1367 (lambda (blob)
1368 (cond
1369 ((not blob) nil) ((equal blob "") nil)
1370 ;; BLOB is a string. Check if the optional transcoder for plain
1371 ;; text exists, and call it in that case. Otherwise, simply
1372 ;; return string. Also update INFO and call
1373 ;; `org-export-filter-plain-text-functions'.
1374 ((stringp blob)
1375 (setq info (org-export-update-info blob info nil))
1376 (let ((transcoder (intern (format "org-%s-plain-text" backend))))
1377 (org-export-filter-apply-functions
1378 org-export-filter-plain-text-functions
1379 (if (fboundp transcoder) (funcall transcoder blob info) blob)
1380 backend)))
1381 ;; BLOB is an element or an object.
1383 (let* ((type (if (stringp blob) 'plain-text (car blob)))
1384 ;; 1. Determine the appropriate TRANSCODER.
1385 (transcoder
1386 (cond
1387 ;; 1.0 A full Org document is inserted.
1388 ((eq type 'org-data) 'identity)
1389 ;; 1.1. BLOB should be ignored.
1390 ((org-export-skip-p blob info) nil)
1391 ;; 1.2. BLOB shouldn't be transcoded. Interpret it
1392 ;; back into Org syntax.
1393 ((not (org-export-interpret-p blob info))
1394 'org-export-expand)
1395 ;; 1.3. Else apply naming convention.
1396 (t (let ((trans (intern
1397 (format "org-%s-%s" backend type))))
1398 (and (fboundp trans) trans)))))
1399 ;; 2. Compute CONTENTS of BLOB.
1400 (contents
1401 (cond
1402 ;; Case 0. No transcoder defined: ignore BLOB.
1403 ((not transcoder) nil)
1404 ;; Case 1. Transparently export an Org document.
1405 ((eq type 'org-data)
1406 (org-export-data blob backend info))
1407 ;; Case 2. For a recursive object.
1408 ((memq type org-element-recursive-objects)
1409 (org-export-data
1410 blob backend (org-export-update-info blob info t)))
1411 ;; Case 3. For a recursive element.
1412 ((memq type org-element-greater-elements)
1413 ;; Ignore contents of an archived tree
1414 ;; when `:with-archived-trees' is `headline'.
1415 (unless (and
1416 (eq type 'headline)
1417 (eq (plist-get info :with-archived-trees) 'headline)
1418 (org-element-get-property :archivedp blob))
1419 (org-element-normalize-string
1420 (org-export-data
1421 blob backend (org-export-update-info blob info t)))))
1422 ;; Case 4. For a paragraph.
1423 ((eq type 'paragraph)
1424 (let ((paragraph
1425 (org-element-normalize-contents
1426 blob
1427 ;; When normalizing contents of an item or
1428 ;; a footnote definition, ignore first line's
1429 ;; indentation: there is none and it might be
1430 ;; misleading.
1431 (and (not (plist-get info :previous-element))
1432 (let ((parent (caar (plist-get info :genealogy))))
1433 (memq parent '(footnote-definition item)))))))
1434 (org-export-data
1435 paragraph
1436 backend
1437 (org-export-update-info blob info t))))))
1438 ;; 3. Transcode BLOB into RESULTS string.
1439 (results (cond
1440 ((not transcoder) nil)
1441 ((eq transcoder 'org-export-expand)
1442 (org-export-data
1443 `(org-data nil ,(funcall transcoder blob contents))
1444 backend info))
1445 (t (funcall transcoder blob contents info)))))
1446 ;; 4. Discard nil results. Otherwise, update INFO, append
1447 ;; the same white space between elements or objects as in
1448 ;; the original buffer, and call appropriate filters.
1449 (when results
1450 (setq info (org-export-update-info blob info nil))
1451 ;; No filter for a full document.
1452 (if (eq type 'org-data)
1453 results
1454 (org-export-filter-apply-functions
1455 (eval (intern (format "org-export-filter-%s-functions" type)))
1456 (if (memq type org-element-all-elements)
1457 (concat
1458 (org-element-normalize-string results)
1459 (make-string (org-element-get-property :post-blank blob) 10))
1460 (concat
1461 results
1462 (make-string
1463 (org-element-get-property :post-blank blob) 32)))
1464 backend)))))))
1465 (org-element-get-contents data) ""))
1467 (defun org-export-secondary-string (secondary backend info)
1468 "Convert SECONDARY string into BACKEND format.
1470 SECONDARY is a nested list as returned by
1471 `org-element-parse-secondary-string'.
1473 BACKEND is a symbol among supported exporters.
1475 INFO is a plist holding export options and also used as
1476 a communication channel between elements when walking the nested
1477 list. See `org-export-update-info' function for more
1478 details.
1480 Return transcoded string."
1481 ;; Make SECONDARY acceptable for `org-export-data'.
1482 (let ((s (if (listp secondary) secondary (list secondary))))
1483 (org-export-data `(org-data nil ,@s) backend (copy-sequence info))))
1485 (defun org-export-skip-p (blob info)
1486 "Non-nil when element or object BLOB should be skipped during export.
1487 INFO is the plist holding export options."
1488 ;; Check headline.
1489 (unless (stringp blob)
1490 (case (car blob)
1491 ('headline
1492 (let ((with-tasks (plist-get info :with-tasks))
1493 (todo (org-element-get-property :todo-keyword blob))
1494 (todo-type (org-element-get-property :todo-type blob))
1495 (archived (plist-get info :with-archived-trees))
1496 (tag-list (let ((tags (org-element-get-property :tags blob)))
1497 (and tags (org-split-string tags ":")))))
1499 ;; Ignore subtrees with an exclude tag.
1500 (loop for k in (plist-get info :exclude-tags)
1501 thereis (member k tag-list))
1502 ;; Ignore subtrees without a select tag, when such tag is found
1503 ;; in the buffer.
1504 (and (plist-get info :use-select-tags)
1505 (loop for k in (plist-get info :select-tags)
1506 never (member k tag-list)))
1507 ;; Ignore commented sub-trees.
1508 (org-element-get-property :commentedp blob)
1509 ;; Ignore archived subtrees if `:with-archived-trees' is nil.
1510 (and (not archived) (org-element-get-property :archivedp blob))
1511 ;; Ignore tasks, if specified by `:with-tasks' property.
1512 (and todo (not with-tasks))
1513 (and todo
1514 (memq with-tasks '(todo done))
1515 (not (eq todo-type with-tasks)))
1516 (and todo
1517 (consp with-tasks)
1518 (not (member todo with-tasks))))))
1519 ;; Check time-stamp.
1520 ('time-stamp (not (plist-get info :with-timestamps)))
1521 ;; Check drawer.
1522 ('drawer
1523 (or (not (plist-get info :with-drawers))
1524 (and (consp (plist-get info :with-drawers))
1525 (not (member (org-element-get-property :drawer-name blob)
1526 (plist-get info :with-drawers))))))
1527 ;; Check export snippet.
1528 ('export-snippet
1529 (let* ((raw-back-end (org-element-get-property :back-end blob))
1530 (true-back-end
1531 (or (cdr (assoc raw-back-end org-export-snippet-translation-alist))
1532 raw-back-end)))
1533 (not (string= (symbol-name (plist-get info :back-end))
1534 true-back-end)))))))
1536 (defun org-export-interpret-p (blob info)
1537 "Non-nil if element or object BLOB should be interpreted as Org syntax.
1538 Check is done according to export options INFO, stored as
1539 a plist."
1540 (case (car blob)
1541 ;; ... entities...
1542 (entity (plist-get info :with-entities))
1543 ;; ... emphasis...
1544 (emphasis (plist-get info :with-emphasize))
1545 ;; ... fixed-width areas.
1546 (fixed-width (plist-get info :with-fixed-width))
1547 ;; ... footnotes...
1548 ((footnote-definition footnote-reference)
1549 (plist-get info :with-footnotes))
1550 ;; ... sub/superscripts...
1551 ((subscript superscript)
1552 (let ((sub/super-p (plist-get info :with-sub-superscript)))
1553 (if (eq sub/super-p '{})
1554 (org-element-get-property :use-brackets-p blob)
1555 sub/super-p)))
1556 ;; ... tables...
1557 (table (plist-get info :with-tables))
1558 (otherwise t)))
1560 (defsubst org-export-expand (blob contents)
1561 "Expand a parsed element or object to its original state.
1562 BLOB is either an element or an object. CONTENTS is its
1563 contents, as a string or nil."
1564 (funcall
1565 (intern (format "org-element-%s-interpreter" (car blob))) blob contents))
1569 ;;; The Filter System
1571 ;; Filters allow end-users to tweak easily the transcoded output.
1572 ;; They are the functional counterpart of hooks, as every filter in
1573 ;; a set is applied to the return value of the previous one.
1575 ;; Every set is back-end agnostic. Although, a filter is always
1576 ;; called, in addition to the string it applies to, with the back-end
1577 ;; used as argument, so it's easy enough for the end-user to add
1578 ;; back-end specific filters in the set.
1580 ;; Filters sets are defined below. There are of four types:
1582 ;; - `org-export-filter-parse-tree-functions' applies directly on the
1583 ;; complete parsed tree. It's the only filters set that doesn't
1584 ;; apply to a string.
1585 ;; - `org-export-filter-final-output-functions' applies to the final
1586 ;; transcoded string.
1587 ;; - `org-export-filter-plain-text-functions' applies to any string
1588 ;; not recognized as Org syntax.
1589 ;; - `org-export-filter-TYPE-functions' applies on the string returned
1590 ;; after an element or object of type TYPE has been transcoded.
1592 ;; All filters sets are applied through
1593 ;; `org-export-filter-apply-functions' function. Filters in a set are
1594 ;; applied in reverse order, that is in the order of consing. It
1595 ;; allows developers to be reasonably sure that their filters will be
1596 ;; applied first.
1598 ;;;; Special Filters
1599 (defvar org-export-filter-parse-tree-functions nil
1600 "Filter, or list of filters, applied to the parsed tree.
1601 Each filter is called with two arguments: the parse tree, as
1602 returned by `org-element-parse-buffer', and the back-end as
1603 a symbol. It must return the modified parse tree to transcode.")
1605 (defvar org-export-filter-final-output-functions nil
1606 "Filter, or list of filters, applied to the transcoded string.
1607 Each filter is called with two arguments: the full transcoded
1608 string, and the back-end as a symbol. It must return a string
1609 that will be used as the final export output.")
1611 (defvar org-export-filter-plain-text-functions nil
1612 "Filter, or list of filters, applied to plain text.
1613 Each filter is called with two arguments: a string which contains
1614 no Org syntax, and the back-end as a symbol. It must return
1615 a string or nil.")
1618 ;;;; Elements Filters
1620 (defvar org-export-filter-center-block-functions nil
1621 "Filter, or list of filters, applied to a transcoded center block.
1622 Each filter is called with two arguments: the transcoded center
1623 block, as a string, and the back-end, as a symbol. It must
1624 return a string or nil.")
1626 (defvar org-export-filter-drawer-functions nil
1627 "Filter, or list of filters, applied to a transcoded drawer.
1628 Each filter is called with two arguments: the transcoded drawer,
1629 as a string, and the back-end, as a symbol. It must return
1630 a string or nil.")
1632 (defvar org-export-filter-dynamic-block-functions nil
1633 "Filter, or list of filters, applied to a transcoded dynamic-block.
1634 Each filter is called with two arguments: the transcoded
1635 dynamic-block, as a string, and the back-end, as a symbol. It
1636 must return a string or nil.")
1638 (defvar org-export-filter-headline-functions nil
1639 "Filter, or list of filters, applied to a transcoded headline.
1640 Each filter is called with two arguments: the transcoded
1641 headline, as a string, and the back-end, as a symbol. It must
1642 return a string or nil.")
1644 (defvar org-export-filter-inlinetask-functions nil
1645 "Filter, or list of filters, applied to a transcoded inlinetask.
1646 Each filter is called with two arguments: the transcoded
1647 inlinetask, as a string, and the back-end, as a symbol. It must
1648 return a string or nil.")
1650 (defvar org-export-filter-plain-list-functions nil
1651 "Filter, or list of filters, applied to a transcoded plain-list.
1652 Each filter is called with two arguments: the transcoded
1653 plain-list, as a string, and the back-end, as a symbol. It must
1654 return a string or nil.")
1656 (defvar org-export-filter-item-functions nil
1657 "Filter, or list of filters, applied to a transcoded item.
1658 Each filter is called with two arguments: the transcoded item, as
1659 a string, and the back-end, as a symbol. It must return a string
1660 or nil.")
1662 (defvar org-export-filter-comment-functions nil
1663 "Filter, or list of filters, applied to a transcoded comment.
1664 Each filter is called with two arguments: the transcoded comment,
1665 as a string, and the back-end, as a symbol. It must return
1666 a string or nil.")
1668 (defvar org-export-filter-comment-block-functions nil
1669 "Filter, or list of filters, applied to a transcoded comment-comment.
1670 Each filter is called with two arguments: the transcoded
1671 comment-block, as a string, and the back-end, as a symbol. It
1672 must return a string or nil.")
1674 (defvar org-export-filter-example-block-functions nil
1675 "Filter, or list of filters, applied to a transcoded example-block.
1676 Each filter is called with two arguments: the transcoded
1677 example-block, as a string, and the back-end, as a symbol. It
1678 must return a string or nil.")
1680 (defvar org-export-filter-export-block-functions nil
1681 "Filter, or list of filters, applied to a transcoded export-block.
1682 Each filter is called with two arguments: the transcoded
1683 export-block, as a string, and the back-end, as a symbol. It
1684 must return a string or nil.")
1686 (defvar org-export-filter-fixed-width-functions nil
1687 "Filter, or list of filters, applied to a transcoded fixed-width.
1688 Each filter is called with two arguments: the transcoded
1689 fixed-width, as a string, and the back-end, as a symbol. It must
1690 return a string or nil.")
1692 (defvar org-export-filter-footnote-definition-functions nil
1693 "Filter, or list of filters, applied to a transcoded footnote-definition.
1694 Each filter is called with two arguments: the transcoded
1695 footnote-definition, as a string, and the back-end, as a symbol.
1696 It must return a string or nil.")
1698 (defvar org-export-filter-horizontal-rule-functions nil
1699 "Filter, or list of filters, applied to a transcoded horizontal-rule.
1700 Each filter is called with two arguments: the transcoded
1701 horizontal-rule, as a string, and the back-end, as a symbol. It
1702 must return a string or nil.")
1704 (defvar org-export-filter-keyword-functions nil
1705 "Filter, or list of filters, applied to a transcoded keyword.
1706 Each filter is called with two arguments: the transcoded keyword,
1707 as a string, and the back-end, as a symbol. It must return
1708 a string or nil.")
1710 (defvar org-export-filter-latex-environment-functions nil
1711 "Filter, or list of filters, applied to a transcoded latex-environment.
1712 Each filter is called with two arguments: the transcoded
1713 latex-environment, as a string, and the back-end, as a symbol.
1714 It must return a string or nil.")
1716 (defvar org-export-filter-babel-call-functions nil
1717 "Filter, or list of filters, applied to a transcoded babel-call.
1718 Each filter is called with two arguments: the transcoded
1719 babel-call, as a string, and the back-end, as a symbol. It must
1720 return a string or nil.")
1722 (defvar org-export-filter-paragraph-functions nil
1723 "Filter, or list of filters, applied to a transcoded paragraph.
1724 Each filter is called with two arguments: the transcoded
1725 paragraph, as a string, and the back-end, as a symbol. It must
1726 return a string or nil.")
1728 (defvar org-export-filter-property-drawer-functions nil
1729 "Filter, or list of filters, applied to a transcoded property-drawer.
1730 Each filter is called with two arguments: the transcoded
1731 property-drawer, as a string, and the back-end, as a symbol. It
1732 must return a string or nil.")
1734 (defvar org-export-filter-quote-block-functions nil
1735 "Filter, or list of filters, applied to a transcoded quote block.
1736 Each filter is called with two arguments: the transcoded quote
1737 block, as a string, and the back-end, as a symbol. It must
1738 return a string or nil.")
1740 (defvar org-export-filter-quote-section-functions nil
1741 "Filter, or list of filters, applied to a transcoded quote-section.
1742 Each filter is called with two arguments: the transcoded
1743 quote-section, as a string, and the back-end, as a symbol. It
1744 must return a string or nil.")
1746 (defvar org-export-filter-section-functions nil
1747 "Filter, or list of filters, applied to a transcoded section.
1748 Each filter is called with two arguments: the transcoded section,
1749 as a string, and the back-end, as a symbol. It must return
1750 a string or nil.")
1752 (defvar org-export-filter-special-block-functions nil
1753 "Filter, or list of filters, applied to a transcoded special block.
1754 Each filter is called with two arguments: the transcoded special
1755 block, as a string, and the back-end, as a symbol. It must
1756 return a string or nil.")
1758 (defvar org-export-filter-src-block-functions nil
1759 "Filter, or list of filters, applied to a transcoded src-block.
1760 Each filter is called with two arguments: the transcoded
1761 src-block, as a string, and the back-end, as a symbol. It must
1762 return a string or nil.")
1764 (defvar org-export-filter-table-functions nil
1765 "Filter, or list of filters, applied to a transcoded table.
1766 Each filter is called with two arguments: the transcoded table,
1767 as a string, and the back-end, as a symbol. It must return
1768 a string or nil.")
1770 (defvar org-export-filter-verse-block-functions nil
1771 "Filter, or list of filters, applied to a transcoded verse block.
1772 Each filter is called with two arguments: the transcoded verse
1773 block, as a string, and the back-end, as a symbol. It must
1774 return a string or nil.")
1777 ;;;; Objects Filters
1779 (defvar org-export-filter-emphasis-functions nil
1780 "Filter, or list of filters, applied to a transcoded emphasis.
1781 Each filter is called with two arguments: the transcoded
1782 emphasis, as a string, and the back-end, as a symbol. It must
1783 return a string or nil.")
1785 (defvar org-export-filter-entity-functions nil
1786 "Filter, or list of filters, applied to a transcoded entity.
1787 Each filter is called with two arguments: the transcoded entity,
1788 as a string, and the back-end, as a symbol. It must return
1789 a string or nil.")
1791 (defvar org-export-filter-export-snippet-functions nil
1792 "Filter, or list of filters, applied to a transcoded export-snippet.
1793 Each filter is called with two arguments: the transcoded
1794 export-snippet, as a string, and the back-end, as a symbol. It
1795 must return a string or nil.")
1797 (defvar org-export-filter-footnote-reference-functions nil
1798 "Filter, or list of filters, applied to a transcoded footnote-reference.
1799 Each filter is called with two arguments: the transcoded
1800 footnote-reference, as a string, and the back-end, as a symbol.
1801 It must return a string or nil.")
1803 (defvar org-export-filter-inline-babel-call-functions nil
1804 "Filter, or list of filters, applied to a transcoded inline-babel-call.
1805 Each filter is called with two arguments: the transcoded
1806 inline-babel-call, as a string, and the back-end, as a symbol. It
1807 must return a string or nil.")
1809 (defvar org-export-filter-inline-src-block-functions nil
1810 "Filter, or list of filters, applied to a transcoded inline-src-block.
1811 Each filter is called with two arguments: the transcoded
1812 inline-src-block, as a string, and the back-end, as a symbol. It
1813 must return a string or nil.")
1815 (defvar org-export-filter-latex-fragment-functions nil
1816 "Filter, or list of filters, applied to a transcoded latex-fragment.
1817 Each filter is called with two arguments: the transcoded
1818 latex-fragment, as a string, and the back-end, as a symbol. It
1819 must return a string or nil.")
1821 (defvar org-export-filter-line-break-functions nil
1822 "Filter, or list of filters, applied to a transcoded line-break.
1823 Each filter is called with two arguments: the transcoded
1824 line-break, as a string, and the back-end, as a symbol. It must
1825 return a string or nil.")
1827 (defvar org-export-filter-link-functions nil
1828 "Filter, or list of filters, applied to a transcoded link.
1829 Each filter is called with two arguments: the transcoded link, as
1830 a string, and the back-end, as a symbol. It must return a string
1831 or nil.")
1833 (defvar org-export-filter-macro-functions nil
1834 "Filter, or list of filters, applied to a transcoded macro.
1835 Each filter is called with two arguments: the transcoded macro,
1836 as a string, and the back-end, as a symbol. It must return
1837 a string or nil.")
1839 (defvar org-export-filter-radio-target-functions nil
1840 "Filter, or list of filters, applied to a transcoded radio-target.
1841 Each filter is called with two arguments: the transcoded
1842 radio-target, as a string, and the back-end, as a symbol. It
1843 must return a string or nil.")
1845 (defvar org-export-filter-statistics-cookie-functions nil
1846 "Filter, or list of filters, applied to a transcoded statistics-cookie.
1847 Each filter is called with two arguments: the transcoded
1848 statistics-cookie, as a string, and the back-end, as a symbol.
1849 It must return a string or nil.")
1851 (defvar org-export-filter-subscript-functions nil
1852 "Filter, or list of filters, applied to a transcoded subscript.
1853 Each filter is called with two arguments: the transcoded
1854 subscript, as a string, and the back-end, as a symbol. It must
1855 return a string or nil.")
1857 (defvar org-export-filter-superscript-functions nil
1858 "Filter, or list of filters, applied to a transcoded superscript.
1859 Each filter is called with two arguments: the transcoded
1860 superscript, as a string, and the back-end, as a symbol. It must
1861 return a string or nil.")
1863 (defvar org-export-filter-target-functions nil
1864 "Filter, or list of filters, applied to a transcoded target.
1865 Each filter is called with two arguments: the transcoded target,
1866 as a string, and the back-end, as a symbol. It must return
1867 a string or nil.")
1869 (defvar org-export-filter-time-stamp-functions nil
1870 "Filter, or list of filters, applied to a transcoded time-stamp.
1871 Each filter is called with two arguments: the transcoded
1872 time-stamp, as a string, and the back-end, as a symbol. It must
1873 return a string or nil.")
1875 (defvar org-export-filter-verbatim-functions nil
1876 "Filter, or list of filters, applied to a transcoded verbatim.
1877 Each filter is called with two arguments: the transcoded
1878 verbatim, as a string, and the back-end, as a symbol. It must
1879 return a string or nil.")
1881 (defun org-export-filter-apply-functions (filters value backend)
1882 "Call every function in FILTERS with arguments VALUE and BACKEND.
1883 Functions are called in reverse order, to be reasonably sure that
1884 developer-specified filters, if any, are called first."
1885 ;; Ensure FILTERS is a list.
1886 (let ((filters (if (listp filters) (reverse filters) (list filters))))
1887 (loop for filter in filters
1888 if (not value) return nil else
1889 do (setq value (funcall filter value backend))))
1890 value)
1894 ;;; Core functions
1896 ;; This is the room for the main function, `org-export-as', along with
1897 ;; its derivatives, `org-export-to-buffer' and `org-export-to-file'.
1898 ;; They differ only by the way they output the resulting code.
1900 ;; Note that `org-export-as' doesn't really parse the current buffer,
1901 ;; but a copy of it (with the same buffer-local variables and
1902 ;; visibility), where Babel blocks are executed, if appropriate.
1903 ;; `org-export-with-current-buffer-copy' macro prepares that copy.
1905 (defun org-export-as (backend
1906 &optional subtreep visible-only body-only ext-plist)
1907 "Transcode current Org buffer into BACKEND code.
1909 If narrowing is active in the current buffer, only transcode its
1910 narrowed part.
1912 If a region is active, transcode that region.
1914 When optional argument SUBTREEP is non-nil, transcode the
1915 sub-tree at point, extracting information from the headline
1916 properties first.
1918 When optional argument VISIBLE-ONLY is non-nil, don't export
1919 contents of hidden elements.
1921 When optional argument BODY-ONLY is non-nil, only return body
1922 code, without preamble nor postamble.
1924 EXT-PLIST, when provided, is a property list with external
1925 parameters overriding Org default settings, but still inferior to
1926 file-local settings.
1928 Return code as a string."
1929 (save-excursion
1930 (save-restriction
1931 ;; Narrow buffer to an appropriate region for parsing.
1932 (when (org-region-active-p)
1933 (narrow-to-region (region-beginning) (region-end))
1934 (goto-char (point-min)))
1935 (when (and subtreep (not (org-at-heading-p)))
1936 ;; Ensure point is at sub-tree's beginning.
1937 (org-with-limited-levels (org-back-to-heading (not visible-only))))
1938 ;; Retrieve export options (INFO) and parsed tree (RAW-DATA).
1939 ;; Buffer isn't parsed directly. Instead, a temporary copy is
1940 ;; created, where all code blocks are evaluated. RAW-DATA is
1941 ;; the parsed tree of the buffer resulting from that process.
1942 ;; Eventually call `org-export-filter-parse-tree-functions'.
1943 (let ((info (org-export-collect-options backend subtreep ext-plist))
1944 (raw-data (progn
1945 (when subtreep ; Only parse subtree contents.
1946 (let ((end (save-excursion (org-end-of-subtree t))))
1947 (narrow-to-region
1948 (progn (forward-line) (point)) end)))
1949 (org-export-filter-apply-functions
1950 org-export-filter-parse-tree-functions
1951 (org-export-with-current-buffer-copy
1952 (org-export-blocks-preprocess)
1953 (org-element-parse-buffer nil visible-only))
1954 backend))))
1955 ;; Initialize the communication system and combine it to INFO.
1956 (setq info
1957 (org-combine-plists
1958 info
1959 (org-export-initialize-persistent-properties
1960 raw-data info backend)))
1961 ;; Now transcode RAW-DATA. Also call
1962 ;; `org-export-filter-final-output-functions'.
1963 (let* ((body (org-element-normalize-string
1964 (org-export-data raw-data backend info)))
1965 (template (intern (format "org-%s-template" backend)))
1966 (output (org-export-filter-apply-functions
1967 org-export-filter-final-output-functions
1968 (if (or (not (fboundp template)) body-only) body
1969 (funcall template body info))
1970 backend)))
1971 ;; Maybe add final OUTPUT to kill ring before returning it.
1972 (when org-export-copy-to-kill-ring (org-kill-new output))
1973 output)))))
1975 (defun org-export-to-buffer (backend buffer &optional subtreep visible-only
1976 body-only ext-plist)
1977 "Call `org-export-as' with output to a specified buffer.
1979 BACKEND is the back-end used for transcoding, as a symbol.
1981 BUFFER is the output buffer. If it already exists, it will be
1982 erased first, otherwise, it will be created.
1984 Arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and EXT-PLIST are
1985 similar to those used in `org-export-as', which see.
1987 Return buffer."
1988 (let ((out (org-export-as backend subtreep visible-only body-only ext-plist))
1989 (buffer (get-buffer-create buffer)))
1990 (with-current-buffer buffer
1991 (erase-buffer)
1992 (insert out)
1993 (goto-char (point-min)))
1994 buffer))
1996 (defun org-export-to-file (backend &optional post-process subtreep visible-only
1997 body-only ext-plist pub-dir)
1998 "Call `org-export-as' with output to a specified file.
2000 BACKEND is the back-end used for transcoding, as a symbol.
2002 Optional argument POST-PROCESS, when non-nil, is a function
2003 applied to the output file. It expects one argument: the file
2004 name, as a string. It can be used to call shell commands on that
2005 file, display a specific buffer, etc.
2007 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
2008 EXT-PLIST are similar to those used in `org-export-as', which
2009 see.
2011 When optional argument PUB-DIR is set, use it as the publishing
2012 directory.
2014 Return output file's name."
2015 ;; First get output directory and output file name.
2016 (let ((out-file
2017 (concat (file-name-as-directory (or pub-dir "."))
2018 ;; Output file name either comes from
2019 ;; EXPORT_FILE_NAME sub-tree property, assuming input
2020 ;; is narrowed to said sub-tree, or to the name of
2021 ;; buffer's associated file.
2022 (file-name-sans-extension
2023 (or (and subtreep
2024 (org-entry-get
2025 (save-excursion
2026 (ignore-errors
2027 (org-back-to-heading (not visible-only))
2028 (point)))
2029 "EXPORT_FILE_NAME" t))
2030 (file-name-nondirectory
2031 (or (buffer-file-name (buffer-base-buffer))
2032 (error "Output file's name undefined")))))
2033 ".tex")))
2034 ;; Checks for file and directory permissions.
2035 (cond
2036 ((not (file-exists-p out-file))
2037 (unless (file-writable-p (or pub-dir "."))
2038 (error "Output directory not writable")))
2039 ((not (file-writable-p out-file)) (error "Output file not writable")))
2040 ;; All checks passed: insert contents to a temporary buffer and
2041 ;; write it to the specified file.
2042 (let ((out (org-export-as
2043 backend subtreep visible-only body-only ext-plist)))
2044 (with-temp-buffer
2045 (insert out)
2046 (let ((coding-system-for-write org-export-coding-system))
2047 (write-file out-file))))
2048 (when post-process (funcall post-process out-file))
2049 ;; Return full path.
2050 out-file))
2052 (defmacro org-export-with-current-buffer-copy (&rest body)
2053 "Apply BODY in a copy of the current buffer.
2055 The copy preserves local variables and visibility of the original
2056 buffer.
2058 Point is at buffer's beginning when BODY is applied."
2059 (org-with-gensyms (original-buffer offset buffer-string overlays)
2060 `(let ((,original-buffer ,(current-buffer))
2061 (,offset ,(1- (point-min)))
2062 (,buffer-string ,(buffer-string))
2063 (,overlays (mapcar
2064 'copy-overlay (overlays-in (point-min) (point-max)))))
2065 (with-temp-buffer
2066 (let ((buffer-invisibility-spec nil))
2067 (org-clone-local-variables
2068 ,original-buffer "^\\(org-\\|orgtbl-\\|major-mode$\\)")
2069 (insert ,buffer-string)
2070 (mapc (lambda (ov)
2071 (move-overlay
2073 (- (overlay-start ov) ,offset)
2074 (- (overlay-end ov) ,offset)
2075 (current-buffer)))
2076 ,overlays)
2077 (goto-char (point-min))
2078 (progn ,@body))))))
2079 (def-edebug-spec org-export-with-current-buffer-copy (body))
2083 ;;; Tools For Back-Ends
2085 ;; A whole set of tools is available to help build new exporters. Any
2086 ;; function general enough to have its use across many back-ends
2087 ;; should be added here.
2089 ;; As of now, functions operating on footnotes, headlines, include
2090 ;; keywords, links, macros, references, src-blocks, tables and tables
2091 ;; of contents are implemented.
2093 ;;;; For Footnotes
2095 ;; `org-export-collect-footnote-definitions' is a tool to list
2096 ;; actually used footnotes definitions in the whole parse tree, or in
2097 ;; an headline, in order to add footnote listings throughout the
2098 ;; transcoded data.
2100 ;; `org-export-footnote-first-reference-p' is a predicate used by some
2101 ;; back-ends, when they need to attach the footnote definition only to
2102 ;; the first occurrence of the corresponding label.
2104 ;; `org-export-get-footnote-definition' and
2105 ;; `org-export-get-footnote-number' provide easier access to
2106 ;; additional information relative to a footnote reference.
2108 (defun org-export-collect-footnote-definitions (data info)
2109 "Return an alist between footnote numbers, labels and definitions.
2111 DATA is the parse tree from which definitions are collected.
2112 INFO is the plist used as a communication channel.
2114 Definitions are sorted by order of references. They either
2115 appear as Org data \(transcoded with `org-export-data'\) or as
2116 a secondary string for inlined footnotes \(transcoded with
2117 `org-export-secondary-string'\). Unreferenced definitions are
2118 ignored."
2119 (let (refs)
2120 ;; Collect seen references in REFS.
2121 (org-element-map
2122 data 'footnote-reference
2123 (lambda (footnote local)
2124 (when (org-export-footnote-first-reference-p footnote local)
2125 (list (org-export-get-footnote-number footnote local)
2126 (org-element-get-property :label footnote)
2127 (org-export-get-footnote-definition footnote local))))
2128 info)))
2130 (defun org-export-footnote-first-reference-p (footnote-reference info)
2131 "Non-nil when a footnote reference is the first one for its label.
2133 FOOTNOTE-REFERENCE is the footnote reference being considered.
2134 INFO is the plist used as a communication channel."
2135 (let ((label (org-element-get-property :label footnote-reference)))
2136 (or (not label)
2137 (equal
2138 footnote-reference
2139 (org-element-map
2140 (plist-get info :parse-tree) 'footnote-reference
2141 (lambda (footnote local)
2142 (when (string= (org-element-get-property :label footnote) label)
2143 footnote))
2144 info 'first-match)))))
2146 (defun org-export-get-footnote-definition (footnote-reference info)
2147 "Return definition of FOOTNOTE-REFERENCE as parsed data.
2148 INFO is the plist used as a communication channel."
2149 (let ((label (org-element-get-property :label footnote-reference)))
2150 (or (org-element-get-property :inline-definition footnote-reference)
2151 (cdr (assoc label (plist-get info :footnote-definition-alist))))))
2153 (defun org-export-get-footnote-number (footnote info)
2154 "Return number associated to a footnote.
2156 FOOTNOTE is either a footnote reference or a footnote definition.
2157 INFO is the plist used as a communication channel."
2158 (let ((label (org-element-get-property :label footnote)) seen-refs)
2159 (org-element-map
2160 (plist-get info :parse-tree) 'footnote-reference
2161 (lambda (fn local)
2162 (let ((fn-lbl (org-element-get-property :label fn)))
2163 (cond
2164 ((and (not fn-lbl) (equal fn footnote)) (1+ (length seen-refs)))
2165 ((and label (string= label fn-lbl)) (1+ (length seen-refs)))
2166 ;; Anonymous footnote: it's always a new one. Also, be sure
2167 ;; to return nil from the `cond' so `first-match' doesn't
2168 ;; get us out of the loop.
2169 ((not fn-lbl) (push 'inline seen-refs) nil)
2170 ;; Label not seen so far: add it so SEEN-REFS. Again,
2171 ;; return nil to stay in the loop.
2172 ((not (member fn-lbl seen-refs)) (push fn-lbl seen-refs) nil))))
2173 info 'first-match)))
2176 ;;;; For Headlines
2178 ;; `org-export-get-relative-level' is a shortcut to get headline
2179 ;; level, relatively to the lower headline level in the parsed tree.
2181 ;; `org-export-get-headline-number' returns the section number of an
2182 ;; headline, while `org-export-number-to-roman' allows to convert it
2183 ;; to roman numbers.
2185 ;; `org-export-first-sibling-p' and `org-export-last-sibling-p' are
2186 ;; two useful predicates when it comes to fulfill the
2187 ;; `:headline-levels' property.
2189 (defun org-export-get-relative-level (headline info)
2190 "Return HEADLINE relative level within current parsed tree.
2191 INFO is a plist holding contextual information."
2192 (+ (org-element-get-property :level headline)
2193 (or (plist-get info :headline-offset) 0)))
2195 (defun org-export-get-headline-number (headline info)
2196 "Return HEADLINE numbering as a list of numbers.
2197 INFO is a plist holding contextual information."
2198 (cdr (assq (org-element-get-property :begin headline)
2199 (plist-get info :headline-numbering))))
2201 (defun org-export-number-to-roman (n)
2202 "Convert integer N into a roman numeral."
2203 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
2204 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
2205 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
2206 ( 1 . "I")))
2207 (res ""))
2208 (if (<= n 0)
2209 (number-to-string n)
2210 (while roman
2211 (if (>= n (caar roman))
2212 (setq n (- n (caar roman))
2213 res (concat res (cdar roman)))
2214 (pop roman)))
2215 res)))
2217 (defun org-export-first-sibling-p (headline info)
2218 "Non-nil when HEADLINE is the first sibling in its sub-tree.
2219 INFO is the plist used as a communication channel."
2220 (not (eq (plist-get info :previous-element) 'headline)))
2222 (defun org-export-last-sibling-p (headline info)
2223 "Non-nil when HEADLINE is the last sibling in its sub-tree.
2224 INFO is the plist used as a communication channel."
2225 (= (org-element-get-property :end headline)
2226 (or (org-element-get-property
2227 :end (org-export-get-parent-headline headline info))
2228 (plist-get info :point-max))))
2231 ;;;; For Include Keywords
2233 ;; This section provides a tool to properly handle insertion of files
2234 ;; during export: `org-export-included-files'. It recursively
2235 ;; transcodes a file specfied by an include keyword.
2237 ;; It uses two helper functions: `org-export-get-file-contents'
2238 ;; returns contents of a file according to parameters specified in the
2239 ;; keyword while `org-export-parse-included-file' parses the file
2240 ;; specified by it.
2242 (defun org-export-included-file (keyword backend info)
2243 "Transcode file specified with include KEYWORD.
2245 KEYWORD is the include keyword element transcoded. BACKEND is
2246 the language back-end used for transcoding. INFO is the plist
2247 used as a communication channel.
2249 This function updates `:included-files' and `:headline-offset'
2250 properties.
2252 Return the transcoded string."
2253 (let ((data (org-export-parse-included-file keyword info))
2254 (file (let ((value (org-element-get-property :value keyword)))
2255 (and (string-match "^\"\\(\\S-+\\)\"" value)
2256 (match-string 1 value)))))
2257 (org-element-normalize-string
2258 (org-export-data
2259 data backend
2260 (org-combine-plists
2261 info
2262 ;; Store full path of already included files to avoid
2263 ;; recursive file inclusion.
2264 `(:included-files
2265 ,(cons (expand-file-name file) (plist-get info :included-files))
2266 ;; Ensure that a top-level headline in the included
2267 ;; file becomes a direct child of the current headline
2268 ;; in the buffer.
2269 :headline-offset
2270 ,(- (+ (org-element-get-property
2271 :level (org-export-get-parent-headline keyword info))
2272 (plist-get info :headline-offset))
2273 (1- (org-export-get-min-level data info)))))))))
2275 (defun org-export-get-file-contents (file &optional lines)
2276 "Get the contents of FILE and return them as a string.
2277 When optional argument LINES is a string specifying a range of
2278 lines, include only those lines."
2279 (with-temp-buffer
2280 (insert-file-contents file)
2281 (when lines
2282 (let* ((lines (split-string lines "-"))
2283 (lbeg (string-to-number (car lines)))
2284 (lend (string-to-number (cadr lines)))
2285 (beg (if (zerop lbeg) (point-min)
2286 (goto-char (point-min))
2287 (forward-line (1- lbeg))
2288 (point)))
2289 (end (if (zerop lend) (point-max)
2290 (goto-char (point-min))
2291 (forward-line (1- lend))
2292 (point))))
2293 (narrow-to-region beg end)))
2294 (buffer-string)))
2296 (defun org-export-parse-included-file (keyword info)
2297 "Parse file specified by include KEYWORD.
2299 KEYWORD is the include keyword element transcoded. BACKEND is the
2300 language back-end used for transcoding. INFO is the plist used as
2301 a communication channel.
2303 Return the parsed tree."
2304 (let* ((value (org-element-get-property :value keyword))
2305 (file (and (string-match "^\"\\(\\S-+\\)\"" value)
2306 (prog1 (match-string 1 value)
2307 (setq value (replace-match "" nil nil value)))))
2308 (lines (and (string-match
2309 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\"" value)
2310 (prog1 (match-string 1 value)
2311 (setq value (replace-match "" nil nil value)))))
2312 (env (cond ((string-match "\\<example\\>" value) "example")
2313 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
2314 (match-string 1 value)))))
2315 (cond
2316 ((or (not file)
2317 (not (file-exists-p file))
2318 (not (file-readable-p file)))
2319 (format "Cannot include file %s" file))
2320 ((and (not env)
2321 (member (expand-file-name file) (plist-get info :included-files)))
2322 (error "Recursive file inclusion: %S" file))
2323 (t (let ((raw (org-element-normalize-string
2324 (org-export-get-file-contents
2325 (expand-file-name file) lines))))
2326 ;; If environment isn't specified, Insert file in
2327 ;; a temporary buffer and parse it as Org syntax.
2328 ;; Otherwise, build the element representing the file.
2329 (cond
2330 ((not env)
2331 (with-temp-buffer
2332 (insert raw) (org-mode) (org-element-parse-buffer)))
2333 ((string= "example" env)
2334 `(org-data nil (example-block (:value ,raw :post-blank 0))))
2336 `(org-data
2338 (src-block (:value ,raw :language ,env :post-blank 0))))))))))
2341 ;;;; For Links
2343 ;; `org-export-solidify-link-text' turns a string into a safer version
2344 ;; for links, replacing most non-standard characters with hyphens.
2346 ;; `org-export-get-coderef-format' returns an appropriate format
2347 ;; string for coderefs.
2349 ;; `org-export-inline-image-p' returns a non-nil value when the link
2350 ;; provided should be considered as an inline image.
2352 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
2353 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
2354 ;; returns an appropriate unique identifier when found, or nil.
2356 (defun org-export-solidify-link-text (s)
2357 "Take link text and make a safe target out of it."
2358 (save-match-data
2359 (mapconcat 'identity (org-split-string s "[^a-zA-Z0-9_\\.-]+") "-")))
2361 (defun org-export-get-coderef-format (path desc)
2362 "Return format string for code reference link.
2363 PATH is the link path. DESC is its description."
2364 (save-match-data
2365 (cond ((string-match (regexp-quote (concat "(" path ")")) desc)
2366 (replace-match "%s" t t desc))
2367 ((string= desc "") "%s")
2368 (t desc))))
2370 (defun org-export-inline-image-p (link &optional extensions)
2371 "Non-nil if LINK object points to an inline image.
2373 When non-nil, optional argument EXTENSIONS is a list of valid
2374 extensions for image files, as strings. Otherwise, a default
2375 list is provided \(cf. `org-image-file-name-regexp'\)."
2376 (and (not (org-element-get-contents link))
2377 (string= (org-element-get-property :type link) "file")
2378 (org-file-image-p
2379 (expand-file-name (org-element-get-property :path link))
2380 extensions)))
2382 (defun org-export-resolve-fuzzy-link (link info)
2383 "Return an unique identifier for LINK destination.
2385 INFO is a plist holding contextual information.
2387 Return value can be a string, an buffer position, or nil:
2389 - If LINK path exactly matches any target, return its name as the
2390 identifier.
2392 - If LINK path exactly matches any headline name, return
2393 headline's beginning position as the identifier. If more than
2394 one headline share that name, priority will be given to the one
2395 with the closest common ancestor, if any, or the first one in
2396 the parse tree otherwise.
2398 - Otherwise, return nil.
2400 Assume LINK type is \"fuzzy\"."
2401 (let ((path (org-element-get-property :path link)))
2402 (if (member path (plist-get info :target-list))
2403 ;; Link points to a target: return its name as a string.
2404 path
2405 ;; Link either points to an headline or nothing. Try to find
2406 ;; the source, with priority given to headlines with the closest
2407 ;; common ancestor. If such candidate is found, return its
2408 ;; beginning position as an unique identifier, otherwise return
2409 ;; nil.
2410 (let* ((head-alist (plist-get info :headline-alist))
2411 (link-begin (org-element-get-property :begin link))
2412 (link-end (org-element-get-property :end link))
2413 ;; Store candidates as a list of cons cells holding their
2414 ;; beginning and ending position.
2415 (cands (loop for head in head-alist
2416 when (string= (car head) path)
2417 collect (cons (nth 1 head) (nth 2 head)))))
2418 (cond
2419 ;; No candidate: return nil.
2420 ((not cands) nil)
2421 ;; If one or more candidates share common ancestors with
2422 ;; LINK, return beginning position of the first one matching
2423 ;; the closer ancestor shared.
2424 ((let ((ancestors (loop for head in head-alist
2425 when (and (> link-begin (nth 1 head))
2426 (<= link-end (nth 2 head)))
2427 collect (cons (nth 1 head) (nth 2 head)))))
2428 (loop named main for ancestor in (nreverse ancestors) do
2429 (loop for candidate in cands
2430 when (and (>= (car candidate) (car ancestor))
2431 (<= (cdr candidate) (cdr ancestor)))
2432 do (return-from main (car candidate))))))
2433 ;; No candidate have a common ancestor with link: First match
2434 ;; will do. Return its beginning position.
2435 (t (caar cands)))))))
2438 ;;;; For Macros
2440 ;; `org-export-expand-macro' simply takes care of expanding macros.
2442 (defun org-export-expand-macro (macro info)
2443 "Expand MACRO and return it as a string.
2444 INFO is a plist holding export options."
2445 (let* ((key (org-element-get-property :key macro))
2446 (args (org-element-get-property :args macro))
2447 (value (plist-get info (intern (format ":macro-%s" key)))))
2448 ;; Replace arguments in VALUE.
2449 (let ((s 0) n)
2450 (while (string-match "\\$\\([0-9]+\\)" value s)
2451 (setq s (1+ (match-beginning 0))
2452 n (string-to-number (match-string 1 value)))
2453 (and (>= (length args) n)
2454 (setq value (replace-match (nth (1- n) args) t t value)))))
2455 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
2456 (when (string-match "\\`(eval\\>" value)
2457 (setq value (eval (read value))))
2458 ;; Return expanded string.
2459 (format "%s" value)))
2462 ;;;; For References
2464 ;; `org-export-get-ordinal' associates a sequence number to any object
2465 ;; or element.
2467 (defun org-export-get-ordinal (element info &optional within-section predicate)
2468 "Return ordinal number of an element or object.
2470 ELEMENT is the element or object considered. INFO is the plist
2471 used as a communication channel.
2473 When optional argument WITHIN-SECTION is non-nil, narrow counting
2474 to the section containing ELEMENT.
2476 Optional argument PREDICATE is a function returning a non-nil
2477 value if the current element or object should be counted in. It
2478 accepts one argument: the element or object being considered.
2479 This argument allows to count only a certain type of objects,
2480 like inline images, which are a subset of links \(in that case,
2481 `org-export-inline-image-p' might be an useful predicate\)."
2482 (let ((counter 0)
2483 (type (car element))
2484 ;; Determine if search should apply to current section, in
2485 ;; which case it should be retrieved first, or to full parse
2486 ;; tree. As a special case, an element or object without
2487 ;; a parent headline will also trigger a full search,
2488 ;; notwithstanding WITHIN-SECTION value.
2489 (data
2490 (if (not within-section) (plist-get info :parse-tree)
2491 (or (org-export-get-parent-headline element info)
2492 (plist-get info :parse-tree)))))
2493 ;; Increment counter until ELEMENT is found again.
2494 (org-element-map
2495 data type
2496 (lambda (el local)
2497 (cond
2498 ((and (functionp predicate) (funcall predicate el)))
2499 ((equal element el) (1+ counter))
2500 (t (incf counter) nil)))
2501 info 'first-match)))
2504 ;;;; For Src-Blocks
2506 ;; `org-export-handle-code' takes care of line numbering and reference
2507 ;; cleaning in source code, when appropriate. It also updates global
2508 ;; LOC count (`:total-loc' property) and code references alist
2509 ;; (`:code-refs' property).
2511 (defun org-export-handle-code (code switches info
2512 &optional language num-fmt ref-fmt)
2513 "Handle line numbers and code references in CODE.
2515 CODE is the string to process. SWITCHES is the option string
2516 determining which changes will be applied to CODE. INFO is the
2517 plist used as a communication channel during export.
2519 Optional argument LANGUAGE, when non-nil, is a string specifying
2520 code's language.
2522 If optional argument NUM-FMT is a string, it will be used as
2523 a format string for numbers at beginning of each line.
2525 If optional argument REF-FMT is a string, it will be used as
2526 a format string for each line of code containing a reference.
2528 Update the following INFO properties by side-effect: `:total-loc'
2529 and `:code-refs'.
2531 Return new code as a string."
2532 (let* ((switches (or switches ""))
2533 (numberp (string-match "[-+]n\\>" switches))
2534 (continuep (string-match "\\+n\\>" switches))
2535 (total-LOC (if (and numberp (not continuep))
2537 (or (plist-get info :total-loc) 0)))
2538 (preserve-indent-p (or org-src-preserve-indentation
2539 (string-match "-i\\>" switches)))
2540 (replace-labels (when (string-match "-r\\>" switches)
2541 (if (string-match "-k\\>" switches) 'keep t)))
2542 ;; Get code and clean it. Remove blank lines at its
2543 ;; beginning and end. Also remove protective commas.
2544 (code (let ((c (replace-regexp-in-string
2545 "\\`\\([ \t]*\n\\)+" ""
2546 (replace-regexp-in-string
2547 "\\(:?[ \t]*\n\\)*[ \t]*\\'" "\n" code))))
2548 ;; If appropriate, remove global indentation.
2549 (unless preserve-indent-p (setq c (org-remove-indentation c)))
2550 ;; Free up the protected lines. Note: Org blocks
2551 ;; have commas at the beginning or every line.
2552 (if (string= language "org")
2553 (replace-regexp-in-string "^," "" c)
2554 (replace-regexp-in-string
2555 "^\\(,\\)\\(:?\\*\\|[ \t]*#\\+\\)" "" c nil nil 1))))
2556 ;; Split code to process it line by line.
2557 (code-lines (org-split-string code "\n"))
2558 ;; Ensure line numbers will be correctly padded before
2559 ;; applying the format string.
2560 (num-fmt (format (if (stringp num-fmt) num-fmt "%s: ")
2561 (format "%%%ds"
2562 (length (number-to-string
2563 (+ (length code-lines)
2564 total-LOC))))))
2565 ;; Get format used for references.
2566 (label-fmt (or (and (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
2567 (match-string 1 switches))
2568 org-coderef-label-format))
2569 ;; Build a regexp matching a loc with a reference.
2570 (with-ref-re (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
2571 (replace-regexp-in-string
2572 "%s" "\\([-a-zA-Z0-9_ ]+\\)" label-fmt nil t)))
2573 coderefs)
2574 (org-element-normalize-string
2575 (mapconcat (lambda (loc)
2576 ;; Maybe add line number to current line of code
2577 ;; (LOC).
2578 (when numberp
2579 (setq loc (concat (format num-fmt (incf total-LOC)) loc)))
2580 ;; Take action if at a ref line.
2581 (when (string-match with-ref-re loc)
2582 (let ((ref (match-string 3 loc)))
2583 (setq loc
2584 (cond
2585 ;; Option "-k": don't remove labels. Use
2586 ;; numbers for references when lines are
2587 ;; numbered, use labels otherwise.
2588 ((eq replace-labels 'keep)
2589 (let ((full-ref (format "(%s)" ref)))
2590 (push (cons ref (if numberp total-LOC full-ref))
2591 coderefs)
2592 (replace-match full-ref nil nil loc 2))
2593 (replace-match (format "(%s)" ref) nil nil loc 2))
2594 ;; Option "-r" without "-k": remove labels.
2595 ;; Use numbers for references when lines are
2596 ;; numbered, use labels otherwise.
2597 (replace-labels
2598 (push (cons ref (if numberp total-LOC ref))
2599 coderefs)
2600 (replace-match "" nil nil loc 1))
2601 ;; Else: don't remove labels and don't use
2602 ;; numbers for references.
2604 (let ((full-ref (format "(%s)" ref)))
2605 (push (cons ref full-ref) coderefs)
2606 (replace-match full-ref nil nil loc 2)))))))
2607 ;; If REF-FMT is defined, apply it to current LOC.
2608 (when (stringp ref-fmt) (setq loc (format ref-fmt loc)))
2609 ;; Update by side-effect communication channel.
2610 ;; Return updated LOC.
2611 (setq info (org-export-set-property
2612 (org-export-set-property
2613 info :code-refs coderefs)
2614 :total-loc total-LOC))
2615 loc)
2616 code-lines "\n"))))
2619 ;;;; For Tables
2621 ;; `org-export-table-format-info' extracts formatting information
2622 ;; (alignment, column groups and presence of a special column) from
2623 ;; a raw table and returns it as a property list.
2625 ;; `org-export-clean-table' cleans the raw table from any Org
2626 ;; table-specific syntax.
2628 (defun org-export-table-format-info (table)
2629 "Extract info from TABLE.
2630 Return a plist whose properties and values are:
2631 `:alignment' vector of strings among \"r\", \"l\" and \"c\",
2632 `:column-groups' vector of symbols among `start', `end', `start-end',
2633 `:row-groups' list of integers representing row groups.
2634 `:special-column-p' non-nil if table has a special column.
2635 `:width' vector of integers representing desired width of
2636 current column, or nil."
2637 (with-temp-buffer
2638 (insert table)
2639 (goto-char 1)
2640 (org-table-align)
2641 (let ((align (vconcat (mapcar (lambda (c) (if c "r" "l"))
2642 org-table-last-alignment)))
2643 (width (make-vector (length org-table-last-alignment) nil))
2644 (colgroups (make-vector (length org-table-last-alignment) nil))
2645 (row-group 0)
2646 (rowgroups)
2647 (special-column-p 'empty))
2648 (mapc (lambda (row)
2649 (if (string-match "^[ \t]*|[-+]+|[ \t]*$" row)
2650 (incf row-group)
2651 ;; Determine if a special column is present by looking
2652 ;; for special markers in the first column. More
2653 ;; accurately, the first column is considered special
2654 ;; if it only contains special markers and, maybe,
2655 ;; empty cells.
2656 (setq special-column-p
2657 (cond
2658 ((not special-column-p) nil)
2659 ((string-match "^[ \t]*| *\\\\?\\([/#!$*_^]\\) *|" row)
2660 'special)
2661 ((string-match "^[ \t]*| +|" row) special-column-p))))
2662 (cond
2663 ;; Read forced alignment and width information, if any,
2664 ;; and determine final alignment for the table.
2665 ((org-table-cookie-line-p row)
2666 (let ((col 0))
2667 (mapc (lambda (field)
2668 (when (string-match
2669 "<\\([lrc]\\)?\\([0-9]+\\)?>" field)
2670 (let ((align-data (match-string 1 field)))
2671 (when align-data (aset align col align-data)))
2672 (let ((w-data (match-string 2 field)))
2673 (when w-data
2674 (aset width col (string-to-number w-data)))))
2675 (incf col))
2676 (org-split-string row "[ \t]*|[ \t]*"))))
2677 ;; Read column groups information.
2678 ((org-table-colgroup-line-p row)
2679 (let ((col 0))
2680 (mapc (lambda (field)
2681 (aset colgroups col
2682 (cond ((string= "<" field) 'start)
2683 ((string= ">" field) 'end)
2684 ((string= "<>" field) 'start-end)))
2685 (incf col))
2686 (org-split-string row "[ \t]*|[ \t]*"))))
2687 ;; Contents line.
2688 (t (push row-group rowgroups))))
2689 (org-split-string table "\n"))
2690 ;; Return plist.
2691 (list :alignment align
2692 :column-groups colgroups
2693 :row-groups (reverse rowgroups)
2694 :special-column-p (eq special-column-p 'special)
2695 :width width))))
2697 (defun org-export-clean-table (table specialp)
2698 "Clean string TABLE from its formatting elements.
2699 Remove any row containing column groups or formatting cookies and
2700 rows starting with a special marker. If SPECIALP is non-nil,
2701 assume the table contains a special formatting column and remove
2702 it also."
2703 (let ((rows (org-split-string table "\n")))
2704 (mapconcat 'identity
2705 (delq nil
2706 (mapcar
2707 (lambda (row)
2708 (cond
2709 ((org-table-colgroup-line-p row) nil)
2710 ((org-table-cookie-line-p row) nil)
2711 ;; Ignore rows starting with a special marker.
2712 ((string-match "^[ \t]*| *[!_^/] *|" row) nil)
2713 ;; Remove special column.
2714 ((and specialp
2715 (or (string-match "^\\([ \t]*\\)|-+\\+" row)
2716 (string-match "^\\([ \t]*\\)|[^|]*|" row)))
2717 (replace-match "\\1|" t nil row))
2718 (t row)))
2719 rows))
2720 "\n")))
2723 ;;;; For Tables Of Contents
2725 ;; `org-export-collect-headlines' builds a list of all exportable
2726 ;; headline elements, maybe limited to a certain depth. One can then
2727 ;; easily parse it and transcode it.
2729 ;; Building lists of tables, figures or listings is quite similar.
2730 ;; Once the generic function `org-export-collect-elements' is defined,
2731 ;; `org-export-collect-tables', `org-export-collect-figures' and
2732 ;; `org-export-collect-listings' can be derived from it.
2734 (defun org-export-collect-headlines (info &optional n)
2735 "Collect headlines in order to build a table of contents.
2737 When non-nil, optional argument N must be an integer. It
2738 specifies the depth of the table of contents.
2740 Return a list of all exportable headlines as parsed elements."
2741 (org-element-map
2742 (plist-get info :parse-tree)
2743 'headline
2744 (lambda (headline local)
2745 ;; Strip contents from HEADLINE.
2746 (let ((relative-level (org-export-get-relative-level headline local)))
2747 (unless (and n (> relative-level n)) headline)))
2748 info))
2750 (defun org-export-collect-elements (type backend info)
2751 "Collect named elements of type TYPE.
2753 Only elements with a caption or a name are collected.
2755 BACKEND is the back-end used to transcode their caption or name.
2756 INFO is a plist holding export options.
2758 Return an alist where key is entry's name and value an unique
2759 identifier that might be used for internal links."
2760 (org-element-map
2761 (plist-get info :parse-tree)
2762 type
2763 (lambda (element info)
2764 (let ((entry
2765 (cond
2766 ((org-element-get-property :caption element)
2767 (org-export-secondary-string
2768 (org-element-get-property :caption element) backend info))
2769 ((org-element-get-property :name element)
2770 (org-export-secondary-string
2771 (org-element-get-property :name element) backend info)))))
2772 ;; Skip elements with neither a caption nor a name.
2773 (when entry (cons entry (org-element-get-property :begin element)))))
2774 info))
2776 (defun org-export-collect-tables (backend info)
2777 "Build a list of tables.
2779 BACKEND is the back-end used to transcode table's name. INFO is
2780 a plist holding export options.
2782 Return an alist where key is the caption of the table and value
2783 an unique identifier that might be used for internal links."
2784 (org-export-collect-elements 'table backend info))
2786 (defun org-export-collect-figures (backend info)
2787 "Build a list of figures.
2789 A figure is a paragraph type element with a caption or a name.
2791 BACKEND is the back-end used to transcode headline's name. INFO
2792 is a plist holding export options.
2794 Return an alist where key is the caption of the figure and value
2795 an unique indentifier that might be used for internal links."
2796 (org-export-collect-elements 'paragraph backend info))
2798 (defun org-export-collect-listings (backend info)
2799 "Build a list of src blocks.
2801 BACKEND is the back-end used to transcode src block's name. INFO
2802 is a plist holding export options.
2804 Return an alist where key is the caption of the src block and
2805 value an unique indentifier that might be used for internal
2806 links."
2807 (org-export-collect-elements 'src-block backend info))
2810 ;;;; Misc. Tools
2812 (defun org-export-get-parent-headline (blob info)
2813 "Return BLOB's closest parent headline or nil."
2814 (catch 'exit
2815 (mapc
2816 (lambda (el) (when (eq (car el) 'headline) (throw 'exit el)))
2817 (plist-get info :genealogy))
2818 nil))
2822 ;;; The Dispatcher
2824 ;; `org-export-dispatch' is the standard interactive way to start an
2825 ;; export process. It uses `org-export-dispatch-ui' as a subroutine
2826 ;; for its interface. Most commons back-ends should have an entry in
2827 ;; it.
2829 (defun org-export-dispatch ()
2830 "Export dispatcher for Org mode.
2832 It provides an access to common export related tasks in a buffer.
2833 Its interface comes in two flavours: standard and expert. While
2834 both share the same set of bindings, only the former displays the
2835 valid keys associations. Set `org-export-dispatch-use-expert-ui'
2836 to switch to one or the other.
2838 Return an error if key pressed has no associated command."
2839 (interactive)
2840 (let* ((input (org-export-dispatch-ui
2841 (if (listp org-export-initial-scope) org-export-initial-scope
2842 (list org-export-initial-scope))
2843 org-export-dispatch-use-expert-ui))
2844 (raw-key (car input))
2845 (scope (cdr input)))
2846 ;; Translate "C-a", "C-b"... into "a", "b"... Then take action
2847 ;; depending on user's key pressed.
2848 (case (if (< raw-key 27) (+ raw-key 96) raw-key)
2849 ;; Export with `e-latex' back-end.
2850 (?L (let ((outbuf (org-export-to-buffer
2851 'e-latex "*Org E-latex Export*"
2852 (memq 'subtree scope)
2853 (memq 'visible scope)
2854 (memq 'body scope))))
2855 (with-current-buffer outbuf (latex-mode))
2856 (when org-export-show-temporary-export-buffer
2857 (switch-to-buffer-other-window outbuf))))
2858 ((?l ?p ?d)
2859 (org-export-to-file
2860 'e-latex
2861 (cond ((eq raw-key ?p) #'org-e-latex-compile)
2862 ((eq raw-key ?d)
2863 (lambda (file) (org-open-file (org-e-latex-compile file)))))
2864 (memq 'subtree scope)
2865 (memq 'visible scope)
2866 (memq 'body scope)))
2867 ;; Undefined command.
2868 (t (error "No command associated with key %s"
2869 (char-to-string raw-key))))))
2871 (defun org-export-dispatch-ui (scope expertp)
2872 "Handle interface for `org-export-dispatch'.
2874 SCOPE is a list containing current interactive options set for
2875 export. It can contain any of the following symbols:
2876 `body' toggles a body-only export
2877 `subtree' restricts export to current subtree
2878 `visible' restricts export to visible part of buffer.
2880 EXPERTP, when non-nil, triggers expert UI. In that case, no help
2881 buffer is provided, but indications about currently active
2882 options are given in the prompt. Moreover, \[?] allows to switch
2883 back to standard interface.
2885 Return value is a list with key pressed as car and a list of
2886 final interactive export options as cdr."
2887 (let ((help (format "------------------- General Options -------------------
2888 \[1] Body only: %s
2889 \[2] Export scope: %s
2890 \[3] Visible only: %s
2892 -------------------- LaTeX Export ---------------------
2893 \[l] to LaTeX file [L] to temporary buffer
2894 \[p] to PDF file [d] ... and open it"
2895 (if (memq 'body scope) "On" "Off")
2896 (if (memq 'subtree scope) "Subtree" "Buffer")
2897 (if (memq 'visible scope) "On" "Off")))
2898 (standard-prompt "Export command: ")
2899 (expert-prompt (format "Export command (%s%s%s): "
2900 (if (memq 'body scope) "b" "-")
2901 (if (memq 'subtree scope) "s" "-")
2902 (if (memq 'visible scope) "v" "-")))
2903 (handle-keypress
2904 (function
2905 ;; Read a character from command input, toggling interactive
2906 ;; options when applicable. PROMPT is the displayed prompt,
2907 ;; as a string.
2908 (lambda (prompt)
2909 (let ((key (read-char-exclusive prompt)))
2910 (cond
2911 ;; Ignore non-standard characters (i.e. "M-a").
2912 ((not (characterp key)) (org-export-dispatch-ui scope expertp))
2913 ;; Switch back to standard interface.
2914 ((and (eq key ??) expertp) (org-export-dispatch-ui scope nil))
2915 ((eq key ?1)
2916 (org-export-dispatch-ui
2917 (if (memq 'body scope) (remq 'body scope) (cons 'body scope))
2918 expertp))
2919 ((eq key ?2)
2920 (org-export-dispatch-ui
2921 (if (memq 'subtree scope) (remq 'subtree scope)
2922 (cons 'subtree scope))
2923 expertp))
2924 ((eq key ?3)
2925 (org-export-dispatch-ui
2926 (if (memq 'visible scope) (remq 'visible scope)
2927 (cons 'visible scope))
2928 expertp))
2929 (t (cons key scope))))))))
2930 ;; With expert UI, just read key with a fancy prompt. In standard
2931 ;; UI, display an intrusive help buffer.
2932 (if expertp (funcall handle-keypress expert-prompt)
2933 (save-window-excursion
2934 (delete-other-windows)
2935 (with-output-to-temp-buffer "*Org Export/Publishing Help*" (princ help))
2936 (org-fit-window-to-buffer
2937 (get-buffer-window "*Org Export/Publishing Help*"))
2938 (funcall handle-keypress standard-prompt)))))
2941 (provide 'org-export)
2942 ;;; org-export.el ends here