org-export: Fix docstrings
[org-mode/org-mode-NeilSmithlineMods.git] / contrib / lisp / org-export.el
blobf319fd502589ba86a52ed4140e5626dd5bc8355c
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. Tree properties are extracted directly from the parsed tree, by
560 ;; `org-export-collect-tree-properties' and depend on export
561 ;; options (whole trees may be filtered out of the export process).
563 ;; 3. Local options are updated during parsing, and their value
564 ;; depends on the level of recursion. For now, only `:genealogy'
565 ;; belongs to that category.
567 ;; Here is the full list of properties available during transcode
568 ;; process, with their category (option, tree or local), their
569 ;; value type and the function updating them, when appropriate.
571 ;; + `author' :: Author's name.
572 ;; - category :: option
573 ;; - type :: string
575 ;; + `back-end' :: Current back-end used for transcoding.
576 ;; - category :: tree
577 ;; - type :: symbol
579 ;; + `creator' :: String to write as creation information.
580 ;; - category :: option
581 ;; - type :: string
583 ;; + `date' :: String to use as date.
584 ;; - category :: option
585 ;; - type :: string
587 ;; + `description' :: Description text for the current data.
588 ;; - category :: option
589 ;; - type :: string
591 ;; + `email' :: Author's email.
592 ;; - category :: option
593 ;; - type :: string
595 ;; + `exclude-tags' :: Tags for exclusion of subtrees from export
596 ;; process.
597 ;; - category :: option
598 ;; - type :: list of strings
600 ;; + `footnote-definition-alist' :: Alist between footnote labels and
601 ;; their definition, as parsed data. Only non-inlined footnotes
602 ;; are represented in this alist. Also, every definition isn't
603 ;; guaranteed to be referenced in the parse tree. The purpose of
604 ;; this property is to preserve definitions from oblivion
605 ;; (i.e. when the parse tree comes from a part of the original
606 ;; buffer), it isn't meant for direct use in a back-end. To
607 ;; retrieve a definition relative to a reference, use
608 ;; `org-export-get-footnote-definition' instead.
609 ;; - category :: option
610 ;; - type :: alist (STRING . LIST)
612 ;; + `genealogy' :: Flat list of current object or element's parents
613 ;; from closest to farthest.
614 ;; - category :: local
615 ;; - type :: list of elements and objects
617 ;; + `headline-levels' :: Maximum level being exported as an
618 ;; headline. Comparison is done with the relative level of
619 ;; headlines in the parse tree, not necessarily with their
620 ;; actual level.
621 ;; - category :: option
622 ;; - type :: integer
624 ;; + `headline-offset' :: Difference between relative and real level
625 ;; of headlines in the parse tree. For example, a value of -1
626 ;; means a level 2 headline should be considered as level
627 ;; 1 (cf. `org-export-get-relative-level').
628 ;; - category :: tree
629 ;; - type :: integer
631 ;; + `headline-numbering' :: Alist between headlines' beginning
632 ;; position and their numbering, as a list of numbers
633 ;; (cf. `org-export-get-headline-number').
634 ;; - category :: tree
635 ;; - type :: alist (INTEGER . LIST)
637 ;; + `included-files' :: List of files, with full path, included in
638 ;; the current buffer, through the "#+include:" keyword. It is
639 ;; mainly used to verify that no infinite recursive inclusion
640 ;; happens.
641 ;; - category :: local
642 ;; - type :: list of strings
644 ;; + `keywords' :: List of keywords attached to data.
645 ;; - category :: option
646 ;; - type :: string
648 ;; + `language' :: Default language used for translations.
649 ;; - category :: option
650 ;; - type :: string
652 ;; + `parse-tree' :: Whole parse tree, available at any time during
653 ;; transcoding.
654 ;; - category :: global
655 ;; - type :: list (as returned by `org-element-parse-buffer')
657 ;; + `preserve-breaks' :: Non-nil means transcoding should preserve
658 ;; all line breaks.
659 ;; - category :: option
660 ;; - type :: symbol (nil, t)
662 ;; + `section-numbers' :: Non-nil means transcoding should add
663 ;; section numbers to headlines.
664 ;; - category :: option
665 ;; - type :: symbol (nil, t)
667 ;; + `select-tags' :: List of tags enforcing inclusion of sub-trees in
668 ;; transcoding. When such a tag is present,
669 ;; subtrees without it are de facto excluded from
670 ;; the process. See `use-select-tags'.
671 ;; - category :: option
672 ;; - type :: list of strings
674 ;; + `target-list' :: List of targets encountered in the parse tree.
675 ;; This is used to partly resolve "fuzzy" links
676 ;; (cf. `org-export-resolve-fuzzy-link').
677 ;; - category :: tree
678 ;; - type :: list of strings
680 ;; + `time-stamp-file' :: Non-nil means transcoding should insert
681 ;; a time stamp in the output.
682 ;; - category :: option
683 ;; - type :: symbol (nil, t)
685 ;; + `use-select-tags' :: When non-nil, a select tags has been found
686 ;; in the parse tree. Thus, any headline without one will be
687 ;; filtered out. See `select-tags'.
688 ;; - category :: tree
689 ;; - type :: interger or nil
691 ;; + `with-archived-trees' :: Non-nil when archived subtrees should
692 ;; also be transcoded. If it is set to the `headline' symbol,
693 ;; only the archived headline's name is retained.
694 ;; - category :: option
695 ;; - type :: symbol (nil, t, `headline')
697 ;; + `with-author' :: Non-nil means author's name should be included
698 ;; in the output.
699 ;; - category :: option
700 ;; - type :: symbol (nil, t)
702 ;; + `with-creator' :: Non-nild means a creation sentence should be
703 ;; inserted at the end of the transcoded string. If the value
704 ;; is `comment', it should be commented.
705 ;; - category :: option
706 ;; - type :: symbol (`comment', nil, t)
708 ;; + `with-drawers' :: Non-nil means drawers should be exported. If
709 ;; its value is a list of names, only drawers with such names
710 ;; will be transcoded.
711 ;; - category :: option
712 ;; - type :: symbol (nil, t) or list of strings
714 ;; + `with-email' :: Non-nil means output should contain author's
715 ;; email.
716 ;; - category :: option
717 ;; - type :: symbol (nil, t)
719 ;; + `with-emphasize' :: Non-nil means emphasized text should be
720 ;; interpreted.
721 ;; - category :: option
722 ;; - type :: symbol (nil, t)
724 ;; + `with-fixed-width' :: Non-nil if transcoder should interpret
725 ;; strings starting with a colon as a fixed-with (verbatim)
726 ;; area.
727 ;; - category :: option
728 ;; - type :: symbol (nil, t)
730 ;; + `with-footnotes' :: Non-nil if transcoder should interpret
731 ;; footnotes.
732 ;; - category :: option
733 ;; - type :: symbol (nil, t)
735 ;; + `with-priority' :: Non-nil means transcoding should include
736 ;; priority cookies.
737 ;; - category :: option
738 ;; - type :: symbol (nil, t)
740 ;; + `with-special-strings' :: Non-nil means transcoding should
741 ;; interpret special strings in plain text.
742 ;; - category :: option
743 ;; - type :: symbol (nil, t)
745 ;; + `with-sub-superscript' :: Non-nil means transcoding should
746 ;; interpret subscript and superscript. With a value of "{}",
747 ;; only interpret those using curly brackets.
748 ;; - category :: option
749 ;; - type :: symbol (nil, {}, t)
751 ;; + `with-tables' :: Non-nil means transcoding should interpret
752 ;; tables.
753 ;; - category :: option
754 ;; - type :: symbol (nil, t)
756 ;; + `with-tags' :: Non-nil means transcoding should keep tags in
757 ;; headlines. A `not-in-toc' value will remove them
758 ;; from the table of contents, if any, nonetheless.
759 ;; - category :: option
760 ;; - type :: symbol (nil, t, `not-in-toc')
762 ;; + `with-tasks' :: Non-nil means transcoding should include
763 ;; headlines with a TODO keyword. A `todo' value
764 ;; will only include headlines with a todo type
765 ;; keyword while a `done' value will do the
766 ;; contrary. If a list of strings is provided, only
767 ;; tasks with keywords belonging to that list will
768 ;; be kept.
769 ;; - category :: option
770 ;; - type :: symbol (t, todo, done, nil) or list of strings
772 ;; + `with-timestamps' :: Non-nil means transcoding should include
773 ;; time stamps and associated keywords. Otherwise, completely
774 ;; remove them.
775 ;; - category :: option
776 ;; - type :: symbol: (t, nil)
778 ;; + `with-toc' :: Non-nil means that a table of contents has to be
779 ;; added to the output. An integer value limits its
780 ;; depth.
781 ;; - category :: option
782 ;; - type :: symbol (nil, t or integer)
784 ;; + `with-todo-keywords' :: Non-nil means transcoding should
785 ;; include TODO keywords.
786 ;; - category :: option
787 ;; - type :: symbol (nil, t)
789 ;;;; Export Options
791 ;; Export options come from five sources, in increasing precedence
792 ;; order:
794 ;; - Global variables,
795 ;; - External options provided at export time,
796 ;; - Options keyword symbols,
797 ;; - Buffer keywords,
798 ;; - Subtree properties.
800 ;; The central internal function with regards to export options is
801 ;; `org-export-collect-options'. It updates global variables with
802 ;; "#+BIND:" keywords, then retrieve and prioritize properties from
803 ;; the different sources.
805 ;; The internal functions doing the retrieval are:
806 ;; `org-export-parse-option-keyword' ,
807 ;; `org-export-get-subtree-options' ,
808 ;; `org-export-get-inbuffer-options' and
809 ;; `org-export-get-global-options'.
811 ;; Some properties do not rely on the previous sources but still
812 ;; depend on the original buffer are taken care of in
813 ;; `org-export-initial-options'.
815 ;; Also, `org-export-confirm-letbind' and `org-export-install-letbind'
816 ;; take care of the part relative to "#+BIND:" keywords.
818 (defun org-export-collect-options (backend subtreep ext-plist)
819 "Collect export options from the current buffer.
821 BACKEND is a symbol specifying the back-end to use.
823 When SUBTREEP is non-nil, assume the export is done against the
824 current sub-tree.
826 EXT-PLIST is a property list with external parameters overriding
827 org-mode's default settings, but still inferior to file-local
828 settings."
829 ;; First install #+BIND variables.
830 (org-export-install-letbind-maybe)
831 ;; Get and prioritize export options...
832 (let ((options (org-combine-plists
833 ;; ... from global variables...
834 (org-export-get-global-options backend)
835 ;; ... from buffer's name (default title)...
836 `(:title
837 ,(or (let ((file (buffer-file-name (buffer-base-buffer))))
838 (and file
839 (file-name-sans-extension
840 (file-name-nondirectory file))))
841 (buffer-name (buffer-base-buffer))))
842 ;; ... from an external property list...
843 ext-plist
844 ;; ... from in-buffer settings...
845 (org-export-get-inbuffer-options
846 (org-with-wide-buffer (buffer-string)) backend
847 (and buffer-file-name
848 (org-remove-double-quotes buffer-file-name)))
849 ;; ... and from subtree, when appropriate.
850 (and subtreep
851 (org-export-get-subtree-options)))))
852 ;; Add initial options.
853 (setq options (append (org-export-initial-options options) options))
854 ;; Return plist.
855 options))
857 (defun org-export-parse-option-keyword (options backend)
858 "Parse an OPTIONS line and return values as a plist.
859 BACKEND is a symbol specifying the back-end to use."
860 (let* ((all (append org-export-option-alist
861 (let ((var (intern
862 (format "org-%s-option-alist" backend))))
863 (and (boundp var) (eval var)))))
864 ;; Build an alist between #+OPTION: item and property-name.
865 (alist (delq nil
866 (mapcar (lambda (e)
867 (when (nth 2 e) (cons (regexp-quote (nth 2 e))
868 (car e))))
869 all)))
870 plist)
871 (mapc (lambda (e)
872 (when (string-match (concat "\\(\\`\\|[ \t]\\)"
873 (car e)
874 ":\\(([^)\n]+)\\|[^ \t\n\r;,.]*\\)")
875 options)
876 (setq plist (plist-put plist
877 (cdr e)
878 (car (read-from-string
879 (match-string 2 options)))))))
880 alist)
881 plist))
883 (defun org-export-get-subtree-options ()
884 "Get export options in subtree at point.
886 Assume point is at subtree's beginning.
888 Return options as a plist."
889 (let (prop plist)
890 (when (setq prop (progn (looking-at org-todo-line-regexp)
891 (or (save-match-data
892 (org-entry-get (point) "EXPORT_TITLE"))
893 (org-match-string-no-properties 3))))
894 (setq plist (plist-put plist :title prop)))
895 (when (setq prop (org-entry-get (point) "EXPORT_TEXT"))
896 (setq plist (plist-put plist :text prop)))
897 (when (setq prop (org-entry-get (point) "EXPORT_AUTHOR"))
898 (setq plist (plist-put plist :author prop)))
899 (when (setq prop (org-entry-get (point) "EXPORT_DATE"))
900 (setq plist (plist-put plist :date prop)))
901 (when (setq prop (org-entry-get (point) "EXPORT_OPTIONS"))
902 (setq plist (org-export-add-options-to-plist plist prop)))
903 plist))
905 (defun org-export-get-inbuffer-options (buffer-string backend files)
906 "Return in-buffer options as a plist.
907 BUFFER-STRING is the string of the buffer. BACKEND is a symbol
908 specifying which back-end should be used. FILES is a list of
909 setup files names read so far, used to avoid circular
910 dependencies."
911 (let ((case-fold-search t) plist)
912 ;; 1. Special keywords, as in `org-export-special-keywords'.
913 (let ((start 0)
914 (special-re (org-make-options-regexp org-export-special-keywords)))
915 (while (string-match special-re buffer-string start)
916 (setq start (match-end 0))
917 (let ((key (upcase (org-match-string-no-properties 1 buffer-string)))
918 ;; Special keywords do not have their value expanded.
919 (val (org-match-string-no-properties 2 buffer-string)))
920 (setq plist
921 (org-combine-plists
922 (cond
923 ((string= key "SETUP_FILE")
924 (let ((file (expand-file-name
925 (org-remove-double-quotes (org-trim val)))))
926 ;; Avoid circular dependencies.
927 (unless (member file files)
928 (org-export-get-inbuffer-options
929 (org-file-contents file 'noerror)
930 backend
931 (cons file files)))))
932 ((string= key "OPTIONS")
933 (org-export-parse-option-keyword val backend))
934 ((string= key "MACRO")
935 (string-match "^\\([-a-zA-Z0-9_]+\\)[ \t]+\\(.*?[ \t]*$\\)"
936 val)
937 (plist-put nil
938 (intern (concat ":macro-"
939 (downcase (match-string 1 val))))
940 (match-string 2 val))))
941 plist)))))
942 ;; 2. Standard options, as in `org-export-option-alist'.
943 (let* ((all (append org-export-option-alist
944 (let ((var (intern
945 (format "org-%s-option-alist" backend))))
946 (and (boundp var) (eval var)))))
947 ;; Build alist between keyword name and property name.
948 (alist (delq nil (mapcar (lambda (e)
949 (when (nth 1 e) (cons (nth 1 e) (car e))))
950 all)))
951 ;; Build regexp matching all keywords associated to export
952 ;; options. Note: the search is case insensitive.
953 (opt-re (org-make-options-regexp
954 (delq nil (mapcar (lambda (e) (nth 1 e)) all))))
955 (start 0))
956 (while (string-match opt-re buffer-string start)
957 (setq start (match-end 0))
958 (let* ((key (upcase (org-match-string-no-properties 1 buffer-string)))
959 ;; Expand value, applying restrictions for keywords.
960 (val (org-match-string-no-properties 2 buffer-string))
961 (prop (cdr (assoc key alist)))
962 (behaviour (nth 4 (assq prop all))))
963 (setq plist
964 (plist-put
965 plist prop
966 ;; Handle value depending on specified BEHAVIOUR.
967 (case behaviour
968 (space (if (plist-get plist prop)
969 (concat (plist-get plist prop) " " (org-trim val))
970 (org-trim val)))
971 (newline (org-trim
972 (concat
973 (plist-get plist prop) "\n" (org-trim val))))
974 (split `(,@(plist-get plist prop) ,@(org-split-string val)))
975 ('t val)
976 (otherwise (plist-get plist prop)))))))
977 ;; Parse keywords specified in `org-element-parsed-keywords'.
978 (mapc
979 (lambda (key)
980 (let* ((prop (cdr (assoc (upcase key) alist)))
981 (value (and prop (plist-get plist prop))))
982 (when (stringp value)
983 (setq plist
984 (plist-put
985 plist prop
986 (org-element-parse-secondary-string
987 value
988 (cdr (assq 'keyword org-element-string-restrictions))))))))
989 org-element-parsed-keywords))
990 ;; Return final value.
991 plist))
993 (defun org-export-get-global-options (backend)
994 "Return global export options as a plist.
995 BACKEND is a symbol specifying which back-end should be used."
996 (let ((all (append org-export-option-alist
997 (let ((var (intern
998 (format "org-%s-option-alist" backend))))
999 (and (boundp var) (eval var)))))
1000 ;; Output value.
1001 plist)
1002 (mapc (lambda (cell)
1003 (setq plist
1004 (plist-put plist (car cell) (eval (nth 3 cell)))))
1005 all)
1006 ;; Return value.
1007 plist))
1009 (defun org-export-initial-options (options)
1010 "Return a plist with non-optional properties.
1011 OPTIONS is the export options plist computed so far."
1012 (list
1013 ;; `:macro-date', `:macro-time' and `:macro-property' could as well
1014 ;; be initialized as tree properties, since they don't depend on
1015 ;; initial environment. Though, it may be more logical to keep
1016 ;; them close to other ":macro-" properties.
1017 :macro-date "(eval (format-time-string \"$1\"))"
1018 :macro-time "(eval (format-time-string \"$1\"))"
1019 :macro-property "(eval (org-entry-get nil \"$1\" 'selective))"
1020 :macro-modification-time
1021 (and (buffer-file-name)
1022 (file-exists-p (buffer-file-name))
1023 (concat "(eval (format-time-string \"$1\" '"
1024 (prin1-to-string (nth 5 (file-attributes (buffer-file-name))))
1025 "))"))
1026 :macro-input-file (and (buffer-file-name)
1027 (file-name-nondirectory (buffer-file-name)))
1028 ;; Footnotes definitions must be collected in the original buffer,
1029 ;; as there's no insurance that they will still be in the parse
1030 ;; tree, due to some narrowing.
1031 :footnote-definition-alist
1032 (let (alist)
1033 (org-with-wide-buffer
1034 (goto-char (point-min))
1035 (while (re-search-forward org-footnote-definition-re nil t)
1036 (let ((def (org-footnote-at-definition-p)))
1037 (when def
1038 (org-skip-whitespace)
1039 (push (cons (car def)
1040 (save-restriction
1041 (narrow-to-region (point) (nth 2 def))
1042 ;; Like `org-element-parse-buffer', but
1043 ;; makes sure the definition doesn't start
1044 ;; with a section element.
1045 (nconc
1046 (list 'org-data nil)
1047 (org-element-parse-elements
1048 (point-min) (point-max) nil nil nil nil nil))))
1049 alist))))
1050 alist))))
1052 (defvar org-export-allow-BIND-local nil)
1053 (defun org-export-confirm-letbind ()
1054 "Can we use #+BIND values during export?
1055 By default this will ask for confirmation by the user, to divert
1056 possible security risks."
1057 (cond
1058 ((not org-export-allow-BIND) nil)
1059 ((eq org-export-allow-BIND t) t)
1060 ((local-variable-p 'org-export-allow-BIND-local) org-export-allow-BIND-local)
1061 (t (org-set-local 'org-export-allow-BIND-local
1062 (yes-or-no-p "Allow BIND values in this buffer? ")))))
1064 (defun org-export-install-letbind-maybe ()
1065 "Install the values from #+BIND lines as local variables.
1066 Variables must be installed before in-buffer options are
1067 retrieved."
1068 (let (letbind pair)
1069 (org-with-wide-buffer
1070 (goto-char (point-min))
1071 (while (re-search-forward (org-make-options-regexp '("BIND")) nil t)
1072 (when (org-export-confirm-letbind)
1073 (push (read (concat "(" (org-match-string-no-properties 2) ")"))
1074 letbind))))
1075 (while (setq pair (pop letbind))
1076 (org-set-local (car pair) (nth 1 pair)))))
1079 ;;;; Tree Properties
1081 ;; They are initialized at the beginning of the transcoding process by
1082 ;; `org-export-collect-tree-properties'.
1084 ;; Dedicated functions focus on computing the value of specific tree
1085 ;; properties during initialization. Thus,
1086 ;; `org-export-use-select-tag-p' determines if an headline makes use
1087 ;; of an export tag enforcing inclusion. `org-export-get-min-level'
1088 ;; gets the minimal exportable level, used as a basis to compute
1089 ;; relative level for headlines. `org-export-get-point-max' returns
1090 ;; the maximum exportable ending position in the parse tree.
1091 ;; Eventually `org-export-collect-headline-numbering' builds an alist
1092 ;; between headlines' beginning position and their numbering.
1094 (defun org-export-collect-tree-properties (data info backend)
1095 "Extract tree properties from parse tree.
1097 DATA is the parse tree from which information is retrieved. INFO
1098 is a list holding export options. BACKEND is the back-end called
1099 for transcoding, as a symbol.
1101 Following tree properties are set:
1102 `:back-end' Back-end used for transcoding.
1104 `:headline-offset' Offset between true level of headlines and
1105 local level. An offset of -1 means an headline
1106 of level 2 should be considered as a level
1107 1 headline in the context.
1109 `:headline-numbering' Alist of all headlines' beginning position
1110 as key an the associated numbering as value.
1112 `:parse-tree' Whole parse tree.
1114 `:target-list' List of all targets in the parse tree.
1116 `:use-select-tags' Non-nil when parsed tree use a special tag to
1117 enforce transcoding of the headline."
1118 ;; First, set `:use-select-tags' property, as it will be required
1119 ;; for further computations.
1120 (setq info
1121 (org-combine-plists
1122 info `(:use-select-tags ,(org-export-use-select-tags-p data info))))
1123 ;; Then get `:headline-offset' in order to be able to use
1124 ;; `org-export-get-relative-level'.
1125 (setq info
1126 (org-combine-plists
1127 info `(:headline-offset ,(- 1 (org-export-get-min-level data info)))))
1128 ;; Now, get the rest of the tree properties, now `:use-select-tags'
1129 ;; is set...
1130 (nconc
1131 `(:parse-tree
1132 ,data
1133 :target-list
1134 ,(org-element-map data 'target (lambda (target local) target) info)
1135 :headline-numbering ,(org-export-collect-headline-numbering data info)
1136 :back-end ,backend)
1137 info))
1139 (defun org-export-use-select-tags-p (data options)
1140 "Non-nil when data use a tag enforcing transcoding.
1141 DATA is parsed data as returned by `org-element-parse-buffer'.
1142 OPTIONS is a plist holding export options."
1143 (org-element-map
1144 data
1145 'headline
1146 (lambda (headline info)
1147 (let ((tags (org-element-get-property :with-tags headline)))
1148 (and tags (string-match
1149 (format ":%s:" (plist-get info :select-tags)) tags))))
1150 options
1151 'stop-at-first-match))
1153 (defun org-export-get-min-level (data options)
1154 "Return minimum exportable headline's level in DATA.
1155 DATA is parsed tree as returned by `org-element-parse-buffer'.
1156 OPTIONS is a plist holding export options."
1157 (catch 'exit
1158 (let ((min-level 10000))
1159 (mapc (lambda (blob)
1160 (when (and (eq (car blob) 'headline)
1161 (not (org-export-skip-p blob options)))
1162 (setq min-level
1163 (min (org-element-get-property :level blob) min-level)))
1164 (when (= min-level 1) (throw 'exit 1)))
1165 (org-element-get-contents data))
1166 ;; If no headline was found, for the sake of consistency, set
1167 ;; minimum level to 1 nonetheless.
1168 (if (= min-level 10000) 1 min-level))))
1170 (defun org-export-collect-headline-numbering (data options)
1171 "Return numbering of all exportable headlines in a parse tree.
1173 DATA is the parse tree. OPTIONS is the plist holding export
1174 options.
1176 Return an alist whose key is an headline and value is its
1177 associated numbering \(in the shape of a list of numbers\)."
1178 (let ((numbering (make-vector org-export-max-depth 0)))
1179 (org-element-map
1180 data
1181 'headline
1182 (lambda (headline info)
1183 (let ((relative-level
1184 (1- (org-export-get-relative-level headline info))))
1185 (cons
1186 headline
1187 (loop for n across numbering
1188 for idx from 0 to org-export-max-depth
1189 when (< idx relative-level) collect n
1190 when (= idx relative-level) collect (aset numbering idx (1+ n))
1191 when (> idx relative-level) do (aset numbering idx 0)))))
1192 options)))
1196 ;;; The Transcoder
1198 ;; This function reads Org data (obtained with, i.e.
1199 ;; `org-element-parse-buffer') and transcodes it into a specified
1200 ;; back-end output. It takes care of updating local properties,
1201 ;; filtering out elements or objects according to export options and
1202 ;; organizing the output blank lines and white space are preserved.
1204 ;; Though, this function is inapropriate for secondary strings, which
1205 ;; require a fresh copy of the plist passed as INFO argument. Thus,
1206 ;; `org-export-secondary-string' is provided for that specific task.
1208 ;; Internally, three functions handle the filtering of objects and
1209 ;; elements during the export. More precisely, `org-export-skip-p'
1210 ;; determines if the considered object or element should be ignored
1211 ;; altogether, `org-export-interpret-p' tells which elements or
1212 ;; objects should be seen as real Org syntax and `org-export-expand'
1213 ;; transforms the others back into their original shape.
1215 (defun org-export-data (data backend info)
1216 "Convert DATA to a string into BACKEND format.
1218 DATA is a nested list as returned by `org-element-parse-buffer'.
1220 BACKEND is a symbol among supported exporters.
1222 INFO is a plist holding export options and also used as
1223 a communication channel between elements when walking the nested
1224 list. See `org-export-update-info' function for more
1225 details.
1227 Return transcoded string."
1228 (mapconcat
1229 ;; BLOB can be an element, an object, a string, or nil.
1230 (lambda (blob)
1231 (cond
1232 ((not blob) nil)
1233 ;; BLOB is a string. Check if the optional transcoder for plain
1234 ;; text exists, and call it in that case. Otherwise, simply
1235 ;; return string. Also update INFO and call
1236 ;; `org-export-filter-plain-text-functions'.
1237 ((stringp blob)
1238 (let ((transcoder (intern (format "org-%s-plain-text" backend))))
1239 (org-export-filter-apply-functions
1240 org-export-filter-plain-text-functions
1241 (if (fboundp transcoder) (funcall transcoder blob info) blob)
1242 backend)))
1243 ;; BLOB is an element or an object.
1245 (let* ((type (if (stringp blob) 'plain-text (car blob)))
1246 ;; 1. Determine the appropriate TRANSCODER.
1247 (transcoder
1248 (cond
1249 ;; 1.0 A full Org document is inserted.
1250 ((eq type 'org-data) 'identity)
1251 ;; 1.1. BLOB should be ignored.
1252 ((org-export-skip-p blob info) nil)
1253 ;; 1.2. BLOB shouldn't be transcoded. Interpret it
1254 ;; back into Org syntax.
1255 ((not (org-export-interpret-p blob info))
1256 'org-export-expand)
1257 ;; 1.3. Else apply naming convention.
1258 (t (let ((trans (intern
1259 (format "org-%s-%s" backend type))))
1260 (and (fboundp trans) trans)))))
1261 ;; 2. Compute CONTENTS of BLOB.
1262 (contents
1263 (cond
1264 ;; Case 0. No transcoder defined: ignore BLOB.
1265 ((not transcoder) nil)
1266 ;; Case 1. Transparently export an Org document.
1267 ((eq type 'org-data) (org-export-data blob backend info))
1268 ;; Case 2. For a recursive object.
1269 ((memq type org-element-recursive-objects)
1270 (org-export-data
1271 blob backend
1272 (org-combine-plists
1273 info
1274 `(:genealogy ,(cons blob (plist-get info :genealogy))))))
1275 ;; Case 3. For a recursive element.
1276 ((memq type org-element-greater-elements)
1277 ;; Ignore contents of an archived tree
1278 ;; when `:with-archived-trees' is `headline'.
1279 (unless (and
1280 (eq type 'headline)
1281 (eq (plist-get info :with-archived-trees) 'headline)
1282 (org-element-get-property :archivedp blob))
1283 (org-element-normalize-string
1284 (org-export-data
1285 blob backend
1286 (org-combine-plists
1287 info `(:genealogy
1288 ,(cons blob (plist-get info :genealogy))))))))
1289 ;; Case 4. For a paragraph.
1290 ((eq type 'paragraph)
1291 (let ((paragraph
1292 (org-element-normalize-contents
1293 blob
1294 ;; When normalizing contents of an item or
1295 ;; a footnote definition, ignore first line's
1296 ;; indentation: there is none and it might be
1297 ;; misleading.
1298 (and (not (org-export-get-previous-element blob info))
1299 (let ((parent (caar (plist-get info :genealogy))))
1300 (memq parent '(footnote-definition item)))))))
1301 (org-export-data
1302 paragraph backend
1303 (org-combine-plists
1304 info `(:genealogy
1305 ,(cons paragraph (plist-get info :genealogy)))))))))
1306 ;; 3. Transcode BLOB into RESULTS string.
1307 (results (cond
1308 ((not transcoder) nil)
1309 ((eq transcoder 'org-export-expand)
1310 (org-export-data
1311 `(org-data nil ,(funcall transcoder blob contents))
1312 backend info))
1313 (t (funcall transcoder blob contents info)))))
1314 ;; 4. Discard nil results. Otherwise, update INFO, append
1315 ;; the same white space between elements or objects as in
1316 ;; the original buffer, and call appropriate filters.
1317 (when results
1318 ;; No filter for a full document.
1319 (if (eq type 'org-data) results
1320 (org-export-filter-apply-functions
1321 (eval (intern (format "org-export-filter-%s-functions" type)))
1322 (let ((post-blank (org-element-get-property :post-blank blob)))
1323 (if (memq type org-element-all-elements)
1324 (concat (org-element-normalize-string results)
1325 (make-string post-blank ?\n))
1326 (concat results (make-string post-blank ? ))))
1327 backend)))))))
1328 (org-element-get-contents data) ""))
1330 (defun org-export-secondary-string (secondary backend info)
1331 "Convert SECONDARY string into BACKEND format.
1333 SECONDARY is a nested list as returned by
1334 `org-element-parse-secondary-string'.
1336 BACKEND is a symbol among supported exporters. INFO is a plist
1337 used as a communication channel.
1339 Return transcoded string."
1340 ;; Make SECONDARY acceptable for `org-export-data'.
1341 (let ((s (if (listp secondary) secondary (list secondary))))
1342 (org-export-data `(org-data nil ,@s) backend (copy-sequence info))))
1344 (defun org-export-skip-p (blob info)
1345 "Non-nil when element or object BLOB should be skipped during export.
1346 INFO is the plist holding export options."
1347 ;; Check headline.
1348 (unless (stringp blob)
1349 (case (car blob)
1350 ('headline
1351 (let ((with-tasks (plist-get info :with-tasks))
1352 (todo (org-element-get-property :todo-keyword blob))
1353 (todo-type (org-element-get-property :todo-type blob))
1354 (archived (plist-get info :with-archived-trees))
1355 (tag-list (let ((tags (org-element-get-property :tags blob)))
1356 (and tags (org-split-string tags ":")))))
1358 ;; Ignore subtrees with an exclude tag.
1359 (loop for k in (plist-get info :exclude-tags)
1360 thereis (member k tag-list))
1361 ;; Ignore subtrees without a select tag, when such tag is found
1362 ;; in the buffer.
1363 (and (plist-get info :use-select-tags)
1364 (loop for k in (plist-get info :select-tags)
1365 never (member k tag-list)))
1366 ;; Ignore commented sub-trees.
1367 (org-element-get-property :commentedp blob)
1368 ;; Ignore archived subtrees if `:with-archived-trees' is nil.
1369 (and (not archived) (org-element-get-property :archivedp blob))
1370 ;; Ignore tasks, if specified by `:with-tasks' property.
1371 (and todo (not with-tasks))
1372 (and todo
1373 (memq with-tasks '(todo done))
1374 (not (eq todo-type with-tasks)))
1375 (and todo
1376 (consp with-tasks)
1377 (not (member todo with-tasks))))))
1378 ;; Check time-stamp.
1379 ('time-stamp (not (plist-get info :with-timestamps)))
1380 ;; Check drawer.
1381 ('drawer
1382 (or (not (plist-get info :with-drawers))
1383 (and (consp (plist-get info :with-drawers))
1384 (not (member (org-element-get-property :drawer-name blob)
1385 (plist-get info :with-drawers))))))
1386 ;; Check export snippet.
1387 ('export-snippet
1388 (let* ((raw-back-end (org-element-get-property :back-end blob))
1389 (true-back-end
1390 (or (cdr (assoc raw-back-end org-export-snippet-translation-alist))
1391 raw-back-end)))
1392 (not (string= (symbol-name (plist-get info :back-end))
1393 true-back-end)))))))
1395 (defun org-export-interpret-p (blob info)
1396 "Non-nil if element or object BLOB should be interpreted as Org syntax.
1397 Check is done according to export options INFO, stored as
1398 a plist."
1399 (case (car blob)
1400 ;; ... entities...
1401 (entity (plist-get info :with-entities))
1402 ;; ... emphasis...
1403 (emphasis (plist-get info :with-emphasize))
1404 ;; ... fixed-width areas.
1405 (fixed-width (plist-get info :with-fixed-width))
1406 ;; ... footnotes...
1407 ((footnote-definition footnote-reference)
1408 (plist-get info :with-footnotes))
1409 ;; ... sub/superscripts...
1410 ((subscript superscript)
1411 (let ((sub/super-p (plist-get info :with-sub-superscript)))
1412 (if (eq sub/super-p '{})
1413 (org-element-get-property :use-brackets-p blob)
1414 sub/super-p)))
1415 ;; ... tables...
1416 (table (plist-get info :with-tables))
1417 (otherwise t)))
1419 (defsubst org-export-expand (blob contents)
1420 "Expand a parsed element or object to its original state.
1421 BLOB is either an element or an object. CONTENTS is its
1422 contents, as a string or nil."
1423 (funcall
1424 (intern (format "org-element-%s-interpreter" (car blob))) blob contents))
1428 ;;; The Filter System
1430 ;; Filters allow end-users to tweak easily the transcoded output.
1431 ;; They are the functional counterpart of hooks, as every filter in
1432 ;; a set is applied to the return value of the previous one.
1434 ;; Every set is back-end agnostic. Although, a filter is always
1435 ;; called, in addition to the string it applies to, with the back-end
1436 ;; used as argument, so it's easy enough for the end-user to add
1437 ;; back-end specific filters in the set.
1439 ;; Filters sets are defined below. There are of four types:
1441 ;; - `org-export-filter-parse-tree-functions' applies directly on the
1442 ;; complete parsed tree. It's the only filters set that doesn't
1443 ;; apply to a string.
1444 ;; - `org-export-filter-final-output-functions' applies to the final
1445 ;; transcoded string.
1446 ;; - `org-export-filter-plain-text-functions' applies to any string
1447 ;; not recognized as Org syntax.
1448 ;; - `org-export-filter-TYPE-functions' applies on the string returned
1449 ;; after an element or object of type TYPE has been transcoded.
1451 ;; All filters sets are applied through
1452 ;; `org-export-filter-apply-functions' function. Filters in a set are
1453 ;; applied in reverse order, that is in the order of consing. It
1454 ;; allows developers to be reasonably sure that their filters will be
1455 ;; applied first.
1457 ;;;; Special Filters
1458 (defvar org-export-filter-parse-tree-functions nil
1459 "Filter, or list of filters, applied to the parsed tree.
1460 Each filter is called with two arguments: the parse tree, as
1461 returned by `org-element-parse-buffer', and the back-end as
1462 a symbol. It must return the modified parse tree to transcode.")
1464 (defvar org-export-filter-final-output-functions nil
1465 "Filter, or list of filters, applied to the transcoded string.
1466 Each filter is called with two arguments: the full transcoded
1467 string, and the back-end as a symbol. It must return a string
1468 that will be used as the final export output.")
1470 (defvar org-export-filter-plain-text-functions nil
1471 "Filter, or list of filters, applied to plain text.
1472 Each filter is called with two arguments: a string which contains
1473 no Org syntax, and the back-end as a symbol. It must return
1474 a string or nil.")
1477 ;;;; Elements Filters
1479 (defvar org-export-filter-center-block-functions nil
1480 "Filter, or list of filters, applied to a transcoded center block.
1481 Each filter is called with two arguments: the transcoded center
1482 block, as a string, and the back-end, as a symbol. It must
1483 return a string or nil.")
1485 (defvar org-export-filter-drawer-functions nil
1486 "Filter, or list of filters, applied to a transcoded drawer.
1487 Each filter is called with two arguments: the transcoded drawer,
1488 as a string, and the back-end, as a symbol. It must return
1489 a string or nil.")
1491 (defvar org-export-filter-dynamic-block-functions nil
1492 "Filter, or list of filters, applied to a transcoded dynamic-block.
1493 Each filter is called with two arguments: the transcoded
1494 dynamic-block, as a string, and the back-end, as a symbol. It
1495 must return a string or nil.")
1497 (defvar org-export-filter-headline-functions nil
1498 "Filter, or list of filters, applied to a transcoded headline.
1499 Each filter is called with two arguments: the transcoded
1500 headline, as a string, and the back-end, as a symbol. It must
1501 return a string or nil.")
1503 (defvar org-export-filter-inlinetask-functions nil
1504 "Filter, or list of filters, applied to a transcoded inlinetask.
1505 Each filter is called with two arguments: the transcoded
1506 inlinetask, as a string, and the back-end, as a symbol. It must
1507 return a string or nil.")
1509 (defvar org-export-filter-plain-list-functions nil
1510 "Filter, or list of filters, applied to a transcoded plain-list.
1511 Each filter is called with two arguments: the transcoded
1512 plain-list, as a string, and the back-end, as a symbol. It must
1513 return a string or nil.")
1515 (defvar org-export-filter-item-functions nil
1516 "Filter, or list of filters, applied to a transcoded item.
1517 Each filter is called with two arguments: the transcoded item, as
1518 a string, and the back-end, as a symbol. It must return a string
1519 or nil.")
1521 (defvar org-export-filter-comment-functions nil
1522 "Filter, or list of filters, applied to a transcoded comment.
1523 Each filter is called with two arguments: the transcoded comment,
1524 as a string, and the back-end, as a symbol. It must return
1525 a string or nil.")
1527 (defvar org-export-filter-comment-block-functions nil
1528 "Filter, or list of filters, applied to a transcoded comment-comment.
1529 Each filter is called with two arguments: the transcoded
1530 comment-block, as a string, and the back-end, as a symbol. It
1531 must return a string or nil.")
1533 (defvar org-export-filter-example-block-functions nil
1534 "Filter, or list of filters, applied to a transcoded example-block.
1535 Each filter is called with two arguments: the transcoded
1536 example-block, as a string, and the back-end, as a symbol. It
1537 must return a string or nil.")
1539 (defvar org-export-filter-export-block-functions nil
1540 "Filter, or list of filters, applied to a transcoded export-block.
1541 Each filter is called with two arguments: the transcoded
1542 export-block, as a string, and the back-end, as a symbol. It
1543 must return a string or nil.")
1545 (defvar org-export-filter-fixed-width-functions nil
1546 "Filter, or list of filters, applied to a transcoded fixed-width.
1547 Each filter is called with two arguments: the transcoded
1548 fixed-width, as a string, and the back-end, as a symbol. It must
1549 return a string or nil.")
1551 (defvar org-export-filter-footnote-definition-functions nil
1552 "Filter, or list of filters, applied to a transcoded footnote-definition.
1553 Each filter is called with two arguments: the transcoded
1554 footnote-definition, as a string, and the back-end, as a symbol.
1555 It must return a string or nil.")
1557 (defvar org-export-filter-horizontal-rule-functions nil
1558 "Filter, or list of filters, applied to a transcoded horizontal-rule.
1559 Each filter is called with two arguments: the transcoded
1560 horizontal-rule, as a string, and the back-end, as a symbol. It
1561 must return a string or nil.")
1563 (defvar org-export-filter-keyword-functions nil
1564 "Filter, or list of filters, applied to a transcoded keyword.
1565 Each filter is called with two arguments: the transcoded keyword,
1566 as a string, and the back-end, as a symbol. It must return
1567 a string or nil.")
1569 (defvar org-export-filter-latex-environment-functions nil
1570 "Filter, or list of filters, applied to a transcoded latex-environment.
1571 Each filter is called with two arguments: the transcoded
1572 latex-environment, as a string, and the back-end, as a symbol.
1573 It must return a string or nil.")
1575 (defvar org-export-filter-babel-call-functions nil
1576 "Filter, or list of filters, applied to a transcoded babel-call.
1577 Each filter is called with two arguments: the transcoded
1578 babel-call, as a string, and the back-end, as a symbol. It must
1579 return a string or nil.")
1581 (defvar org-export-filter-paragraph-functions nil
1582 "Filter, or list of filters, applied to a transcoded paragraph.
1583 Each filter is called with two arguments: the transcoded
1584 paragraph, as a string, and the back-end, as a symbol. It must
1585 return a string or nil.")
1587 (defvar org-export-filter-property-drawer-functions nil
1588 "Filter, or list of filters, applied to a transcoded property-drawer.
1589 Each filter is called with two arguments: the transcoded
1590 property-drawer, as a string, and the back-end, as a symbol. It
1591 must return a string or nil.")
1593 (defvar org-export-filter-quote-block-functions nil
1594 "Filter, or list of filters, applied to a transcoded quote block.
1595 Each filter is called with two arguments: the transcoded quote
1596 block, as a string, and the back-end, as a symbol. It must
1597 return a string or nil.")
1599 (defvar org-export-filter-quote-section-functions nil
1600 "Filter, or list of filters, applied to a transcoded quote-section.
1601 Each filter is called with two arguments: the transcoded
1602 quote-section, as a string, and the back-end, as a symbol. It
1603 must return a string or nil.")
1605 (defvar org-export-filter-section-functions nil
1606 "Filter, or list of filters, applied to a transcoded section.
1607 Each filter is called with two arguments: the transcoded section,
1608 as a string, and the back-end, as a symbol. It must return
1609 a string or nil.")
1611 (defvar org-export-filter-special-block-functions nil
1612 "Filter, or list of filters, applied to a transcoded special block.
1613 Each filter is called with two arguments: the transcoded special
1614 block, as a string, and the back-end, as a symbol. It must
1615 return a string or nil.")
1617 (defvar org-export-filter-src-block-functions nil
1618 "Filter, or list of filters, applied to a transcoded src-block.
1619 Each filter is called with two arguments: the transcoded
1620 src-block, as a string, and the back-end, as a symbol. It must
1621 return a string or nil.")
1623 (defvar org-export-filter-table-functions nil
1624 "Filter, or list of filters, applied to a transcoded table.
1625 Each filter is called with two arguments: the transcoded table,
1626 as a string, and the back-end, as a symbol. It must return
1627 a string or nil.")
1629 (defvar org-export-filter-verse-block-functions nil
1630 "Filter, or list of filters, applied to a transcoded verse block.
1631 Each filter is called with two arguments: the transcoded verse
1632 block, as a string, and the back-end, as a symbol. It must
1633 return a string or nil.")
1636 ;;;; Objects Filters
1638 (defvar org-export-filter-emphasis-functions nil
1639 "Filter, or list of filters, applied to a transcoded emphasis.
1640 Each filter is called with two arguments: the transcoded
1641 emphasis, as a string, and the back-end, as a symbol. It must
1642 return a string or nil.")
1644 (defvar org-export-filter-entity-functions nil
1645 "Filter, or list of filters, applied to a transcoded entity.
1646 Each filter is called with two arguments: the transcoded entity,
1647 as a string, and the back-end, as a symbol. It must return
1648 a string or nil.")
1650 (defvar org-export-filter-export-snippet-functions nil
1651 "Filter, or list of filters, applied to a transcoded export-snippet.
1652 Each filter is called with two arguments: the transcoded
1653 export-snippet, as a string, and the back-end, as a symbol. It
1654 must return a string or nil.")
1656 (defvar org-export-filter-footnote-reference-functions nil
1657 "Filter, or list of filters, applied to a transcoded footnote-reference.
1658 Each filter is called with two arguments: the transcoded
1659 footnote-reference, as a string, and the back-end, as a symbol.
1660 It must return a string or nil.")
1662 (defvar org-export-filter-inline-babel-call-functions nil
1663 "Filter, or list of filters, applied to a transcoded inline-babel-call.
1664 Each filter is called with two arguments: the transcoded
1665 inline-babel-call, as a string, and the back-end, as a symbol. It
1666 must return a string or nil.")
1668 (defvar org-export-filter-inline-src-block-functions nil
1669 "Filter, or list of filters, applied to a transcoded inline-src-block.
1670 Each filter is called with two arguments: the transcoded
1671 inline-src-block, as a string, and the back-end, as a symbol. It
1672 must return a string or nil.")
1674 (defvar org-export-filter-latex-fragment-functions nil
1675 "Filter, or list of filters, applied to a transcoded latex-fragment.
1676 Each filter is called with two arguments: the transcoded
1677 latex-fragment, as a string, and the back-end, as a symbol. It
1678 must return a string or nil.")
1680 (defvar org-export-filter-line-break-functions nil
1681 "Filter, or list of filters, applied to a transcoded line-break.
1682 Each filter is called with two arguments: the transcoded
1683 line-break, as a string, and the back-end, as a symbol. It must
1684 return a string or nil.")
1686 (defvar org-export-filter-link-functions nil
1687 "Filter, or list of filters, applied to a transcoded link.
1688 Each filter is called with two arguments: the transcoded link, as
1689 a string, and the back-end, as a symbol. It must return a string
1690 or nil.")
1692 (defvar org-export-filter-macro-functions nil
1693 "Filter, or list of filters, applied to a transcoded macro.
1694 Each filter is called with two arguments: the transcoded macro,
1695 as a string, and the back-end, as a symbol. It must return
1696 a string or nil.")
1698 (defvar org-export-filter-radio-target-functions nil
1699 "Filter, or list of filters, applied to a transcoded radio-target.
1700 Each filter is called with two arguments: the transcoded
1701 radio-target, as a string, and the back-end, as a symbol. It
1702 must return a string or nil.")
1704 (defvar org-export-filter-statistics-cookie-functions nil
1705 "Filter, or list of filters, applied to a transcoded statistics-cookie.
1706 Each filter is called with two arguments: the transcoded
1707 statistics-cookie, as a string, and the back-end, as a symbol.
1708 It must return a string or nil.")
1710 (defvar org-export-filter-subscript-functions nil
1711 "Filter, or list of filters, applied to a transcoded subscript.
1712 Each filter is called with two arguments: the transcoded
1713 subscript, as a string, and the back-end, as a symbol. It must
1714 return a string or nil.")
1716 (defvar org-export-filter-superscript-functions nil
1717 "Filter, or list of filters, applied to a transcoded superscript.
1718 Each filter is called with two arguments: the transcoded
1719 superscript, as a string, and the back-end, as a symbol. It must
1720 return a string or nil.")
1722 (defvar org-export-filter-target-functions nil
1723 "Filter, or list of filters, applied to a transcoded target.
1724 Each filter is called with two arguments: the transcoded target,
1725 as a string, and the back-end, as a symbol. It must return
1726 a string or nil.")
1728 (defvar org-export-filter-time-stamp-functions nil
1729 "Filter, or list of filters, applied to a transcoded time-stamp.
1730 Each filter is called with two arguments: the transcoded
1731 time-stamp, as a string, and the back-end, as a symbol. It must
1732 return a string or nil.")
1734 (defvar org-export-filter-verbatim-functions nil
1735 "Filter, or list of filters, applied to a transcoded verbatim.
1736 Each filter is called with two arguments: the transcoded
1737 verbatim, as a string, and the back-end, as a symbol. It must
1738 return a string or nil.")
1740 (defun org-export-filter-apply-functions (filters value backend)
1741 "Call every function in FILTERS with arguments VALUE and BACKEND.
1742 Functions are called in reverse order, to be reasonably sure that
1743 developer-specified filters, if any, are called first."
1744 ;; Ensure FILTERS is a list.
1745 (let ((filters (if (listp filters) (reverse filters) (list filters))))
1746 (loop for filter in filters
1747 if (not value) return nil else
1748 do (setq value (funcall filter value backend))))
1749 value)
1753 ;;; Core functions
1755 ;; This is the room for the main function, `org-export-as', along with
1756 ;; its derivatives, `org-export-to-buffer' and `org-export-to-file'.
1757 ;; They differ only by the way they output the resulting code.
1759 ;; `org-export-output-file-name' is an auxiliary function meant to be
1760 ;; used with `org-export-to-file'. With a given extension, it tries
1761 ;; to provide a canonical file name to write export output to.
1763 ;; Note that `org-export-as' doesn't really parse the current buffer,
1764 ;; but a copy of it (with the same buffer-local variables and
1765 ;; visibility), where Babel blocks are executed, if appropriate.
1766 ;; `org-export-with-current-buffer-copy' macro prepares that copy.
1768 (defun org-export-as (backend
1769 &optional subtreep visible-only body-only ext-plist)
1770 "Transcode current Org buffer into BACKEND code.
1772 If narrowing is active in the current buffer, only transcode its
1773 narrowed part.
1775 If a region is active, transcode that region.
1777 When optional argument SUBTREEP is non-nil, transcode the
1778 sub-tree at point, extracting information from the headline
1779 properties first.
1781 When optional argument VISIBLE-ONLY is non-nil, don't export
1782 contents of hidden elements.
1784 When optional argument BODY-ONLY is non-nil, only return body
1785 code, without preamble nor postamble.
1787 EXT-PLIST, when provided, is a property list with external
1788 parameters overriding Org default settings, but still inferior to
1789 file-local settings.
1791 Return code as a string."
1792 (save-excursion
1793 (save-restriction
1794 ;; Narrow buffer to an appropriate region for parsing.
1795 (when (org-region-active-p)
1796 (narrow-to-region (region-beginning) (region-end))
1797 (goto-char (point-min)))
1798 (when (and subtreep (not (org-at-heading-p)))
1799 ;; Ensure point is at sub-tree's beginning.
1800 (org-with-limited-levels (org-back-to-heading (not visible-only))))
1801 ;; Retrieve export options (INFO) and parsed tree (RAW-DATA).
1802 ;; Buffer isn't parsed directly. Instead, a temporary copy is
1803 ;; created, where all code blocks are evaluated. RAW-DATA is
1804 ;; the parsed tree of the buffer resulting from that process.
1805 ;; Eventually call `org-export-filter-parse-tree-functions'.
1806 (let ((info (org-export-collect-options backend subtreep ext-plist))
1807 (raw-data (progn
1808 (when subtreep ; Only parse subtree contents.
1809 (let ((end (save-excursion (org-end-of-subtree t))))
1810 (narrow-to-region
1811 (progn (forward-line) (point)) end)))
1812 (org-export-filter-apply-functions
1813 org-export-filter-parse-tree-functions
1814 (org-export-with-current-buffer-copy
1815 (org-export-blocks-preprocess)
1816 (org-element-parse-buffer nil visible-only))
1817 backend))))
1818 ;; Initialize the communication system and combine it to INFO.
1819 (setq info
1820 (org-combine-plists
1821 info (org-export-collect-tree-properties raw-data info backend)))
1822 ;; Now transcode RAW-DATA. Also call
1823 ;; `org-export-filter-final-output-functions'.
1824 (let* ((body (org-element-normalize-string
1825 (org-export-data raw-data backend info)))
1826 (template (intern (format "org-%s-template" backend)))
1827 (output (org-export-filter-apply-functions
1828 org-export-filter-final-output-functions
1829 (if (or (not (fboundp template)) body-only) body
1830 (funcall template body info))
1831 backend)))
1832 ;; Maybe add final OUTPUT to kill ring before returning it.
1833 (when org-export-copy-to-kill-ring (org-kill-new output))
1834 output)))))
1836 (defun org-export-to-buffer (backend buffer &optional subtreep visible-only
1837 body-only ext-plist)
1838 "Call `org-export-as' with output to a specified buffer.
1840 BACKEND is the back-end used for transcoding, as a symbol.
1842 BUFFER is the output buffer. If it already exists, it will be
1843 erased first, otherwise, it will be created.
1845 Arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and EXT-PLIST are
1846 similar to those used in `org-export-as', which see.
1848 Return buffer."
1849 (let ((out (org-export-as backend subtreep visible-only body-only ext-plist))
1850 (buffer (get-buffer-create buffer)))
1851 (with-current-buffer buffer
1852 (erase-buffer)
1853 (insert out)
1854 (goto-char (point-min)))
1855 buffer))
1857 (defun org-export-to-file (backend file &optional subtreep visible-only
1858 body-only ext-plist)
1859 "Call `org-export-as' with output to a specified file.
1861 BACKEND is the back-end used for transcoding, as a symbol. FILE
1862 is the name of the output file, as a string.
1864 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
1865 EXT-PLIST are similar to those used in `org-export-as', which
1866 see.
1868 Return output file's name."
1869 ;; Checks for FILE permissions. `write-file' would do the same, but
1870 ;; we'd rather avoid needless transcoding of parse tree.
1871 (unless (file-writable-p file) (error "Output file not writable"))
1872 ;; Insert contents to a temporary buffer and write it to FILE.
1873 (let ((out (org-export-as
1874 backend subtreep visible-only body-only ext-plist)))
1875 (with-temp-buffer
1876 (insert out)
1877 (let ((coding-system-for-write org-export-coding-system))
1878 (write-file file))))
1879 ;; Return full path.
1880 file)
1882 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
1883 "Return output file's name according to buffer specifications.
1885 EXTENSION is a string representing the output file extension.
1887 With a non-nil optional argument SUBTREEP, try to determine
1888 output file's name by looking for \"EXPORT_FILE_NAME\" property
1889 of subtree at point.
1891 When optional argument PUB-DIR is set, use it as the publishing
1892 directory.
1894 Return file name as a string, or nil if it couldn't be
1895 determined."
1896 (let ((base-name
1897 (concat
1898 (file-name-as-directory (or pub-dir "."))
1899 ;; Output file name either comes from EXPORT_FILE_NAME
1900 ;; sub-tree property, assuming point is at beginning of said
1901 ;; sub-tree, or to the name of buffer's associated file.
1902 (file-name-sans-extension
1903 (or (and subtreep
1904 (org-entry-get
1905 (save-excursion
1906 (ignore-errors
1907 (org-back-to-heading (not visible-only)) (point)))
1908 "EXPORT_FILE_NAME" t))
1909 (file-name-nondirectory
1910 (or (buffer-file-name (buffer-base-buffer)))))))))
1911 ;; BASE-NAME will be nil when original buffer was temporary one.
1912 (when base-name (concat base-name extension))))
1914 (defmacro org-export-with-current-buffer-copy (&rest body)
1915 "Apply BODY in a copy of the current buffer.
1917 The copy preserves local variables and visibility of the original
1918 buffer.
1920 Point is at buffer's beginning when BODY is applied."
1921 (org-with-gensyms (original-buffer offset buffer-string overlays)
1922 `(let ((,original-buffer ,(current-buffer))
1923 (,offset ,(1- (point-min)))
1924 (,buffer-string ,(buffer-string))
1925 (,overlays (mapcar
1926 'copy-overlay (overlays-in (point-min) (point-max)))))
1927 (with-temp-buffer
1928 (let ((buffer-invisibility-spec nil))
1929 (org-clone-local-variables
1930 ,original-buffer "^\\(org-\\|orgtbl-\\|major-mode$\\)")
1931 (insert ,buffer-string)
1932 (mapc (lambda (ov)
1933 (move-overlay
1935 (- (overlay-start ov) ,offset)
1936 (- (overlay-end ov) ,offset)
1937 (current-buffer)))
1938 ,overlays)
1939 (goto-char (point-min))
1940 (progn ,@body))))))
1941 (def-edebug-spec org-export-with-current-buffer-copy (body))
1945 ;;; Tools For Back-Ends
1947 ;; A whole set of tools is available to help build new exporters. Any
1948 ;; function general enough to have its use across many back-ends
1949 ;; should be added here.
1951 ;; As of now, functions operating on footnotes, headlines, include
1952 ;; keywords, links, macros, references, src-blocks, tables and tables
1953 ;; of contents are implemented.
1955 ;;;; For Footnotes
1957 ;; `org-export-collect-footnote-definitions' is a tool to list
1958 ;; actually used footnotes definitions in the whole parse tree, or in
1959 ;; an headline, in order to add footnote listings throughout the
1960 ;; transcoded data.
1962 ;; `org-export-footnote-first-reference-p' is a predicate used by some
1963 ;; back-ends, when they need to attach the footnote definition only to
1964 ;; the first occurrence of the corresponding label.
1966 ;; `org-export-get-footnote-definition' and
1967 ;; `org-export-get-footnote-number' provide easier access to
1968 ;; additional information relative to a footnote reference.
1970 (defun org-export-collect-footnote-definitions (data info)
1971 "Return an alist between footnote numbers, labels and definitions.
1973 DATA is the parse tree from which definitions are collected.
1974 INFO is the plist used as a communication channel.
1976 Definitions are sorted by order of references. They either
1977 appear as Org data \(transcoded with `org-export-data'\) or as
1978 a secondary string for inlined footnotes \(transcoded with
1979 `org-export-secondary-string'\). Unreferenced definitions are
1980 ignored."
1981 (let (refs)
1982 ;; Collect seen references in REFS.
1983 (org-element-map
1984 data 'footnote-reference
1985 (lambda (footnote local)
1986 (when (org-export-footnote-first-reference-p footnote local)
1987 (list (org-export-get-footnote-number footnote local)
1988 (org-element-get-property :label footnote)
1989 (org-export-get-footnote-definition footnote local))))
1990 info)))
1992 (defun org-export-footnote-first-reference-p (footnote-reference info)
1993 "Non-nil when a footnote reference is the first one for its label.
1995 FOOTNOTE-REFERENCE is the footnote reference being considered.
1996 INFO is the plist used as a communication channel."
1997 (let ((label (org-element-get-property :label footnote-reference)))
1998 (or (not label)
1999 (equal
2000 footnote-reference
2001 (org-element-map
2002 (plist-get info :parse-tree) 'footnote-reference
2003 (lambda (footnote local)
2004 (when (string= (org-element-get-property :label footnote) label)
2005 footnote))
2006 info 'first-match)))))
2008 (defun org-export-get-footnote-definition (footnote-reference info)
2009 "Return definition of FOOTNOTE-REFERENCE as parsed data.
2010 INFO is the plist used as a communication channel."
2011 (let ((label (org-element-get-property :label footnote-reference)))
2012 (or (org-element-get-property :inline-definition footnote-reference)
2013 (cdr (assoc label (plist-get info :footnote-definition-alist))))))
2015 (defun org-export-get-footnote-number (footnote info)
2016 "Return number associated to a footnote.
2018 FOOTNOTE is either a footnote reference or a footnote definition.
2019 INFO is the plist used as a communication channel."
2020 (let ((label (org-element-get-property :label footnote)) seen-refs)
2021 (org-element-map
2022 (plist-get info :parse-tree) 'footnote-reference
2023 (lambda (fn local)
2024 (let ((fn-lbl (org-element-get-property :label fn)))
2025 (cond
2026 ((and (not fn-lbl) (equal fn footnote)) (1+ (length seen-refs)))
2027 ((and label (string= label fn-lbl)) (1+ (length seen-refs)))
2028 ;; Anonymous footnote: it's always a new one. Also, be sure
2029 ;; to return nil from the `cond' so `first-match' doesn't
2030 ;; get us out of the loop.
2031 ((not fn-lbl) (push 'inline seen-refs) nil)
2032 ;; Label not seen so far: add it so SEEN-REFS. Again,
2033 ;; return nil to stay in the loop.
2034 ((not (member fn-lbl seen-refs)) (push fn-lbl seen-refs) nil))))
2035 info 'first-match)))
2038 ;;;; For Headlines
2040 ;; `org-export-get-relative-level' is a shortcut to get headline
2041 ;; level, relatively to the lower headline level in the parsed tree.
2043 ;; `org-export-get-headline-number' returns the section number of an
2044 ;; headline, while `org-export-number-to-roman' allows to convert it
2045 ;; to roman numbers.
2047 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
2048 ;; `org-export-last-sibling-p' are three useful predicates when it
2049 ;; comes to fulfill the `:headline-levels' property.
2051 (defun org-export-get-relative-level (headline info)
2052 "Return HEADLINE relative level within current parsed tree.
2053 INFO is a plist holding contextual information."
2054 (+ (org-element-get-property :level headline)
2055 (or (plist-get info :headline-offset) 0)))
2057 (defun org-export-low-level-p (headline info)
2058 "Non-nil when HEADLINE is considered as low level.
2060 INFO is a plist used as a communication channel.
2062 A low level headlines has a relative level greater than
2063 `:headline-levels' property value.
2065 Return value is the difference between HEADLINE relative level
2066 and the last level being considered as high enough, or nil."
2067 (let ((limit (plist-get info :headline-levels)))
2068 (when (wholenump limit)
2069 (let ((level (org-export-get-relative-level headline info)))
2070 (and (> level limit) (- level limit))))))
2072 (defun org-export-get-headline-number (headline info)
2073 "Return HEADLINE numbering as a list of numbers.
2074 INFO is a plist holding contextual information."
2075 (cdr (assoc headline (plist-get info :headline-numbering))))
2077 (defun org-export-number-to-roman (n)
2078 "Convert integer N into a roman numeral."
2079 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
2080 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
2081 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
2082 ( 1 . "I")))
2083 (res ""))
2084 (if (<= n 0)
2085 (number-to-string n)
2086 (while roman
2087 (if (>= n (caar roman))
2088 (setq n (- n (caar roman))
2089 res (concat res (cdar roman)))
2090 (pop roman)))
2091 res)))
2093 (defun org-export-first-sibling-p (headline info)
2094 "Non-nil when HEADLINE is the first sibling in its sub-tree.
2095 INFO is the plist used as a communication channel."
2096 (not (eq (car (org-export-get-previous-element headline info)) 'headline)))
2098 (defun org-export-last-sibling-p (headline info)
2099 "Non-nil when HEADLINE is the last sibling in its sub-tree.
2100 INFO is the plist used as a communication channel."
2101 (equal
2102 (car (last (org-element-get-contents (car (plist-get info :genealogy)))))
2103 headline))
2106 ;;;; For Include Keywords
2108 ;; This section provides a tool to properly handle insertion of files
2109 ;; during export: `org-export-included-files'. It recursively
2110 ;; transcodes a file specfied by an include keyword.
2112 ;; It uses two helper functions: `org-export-get-file-contents'
2113 ;; returns contents of a file according to parameters specified in the
2114 ;; keyword while `org-export-parse-included-file' parses the file
2115 ;; specified by it.
2117 (defun org-export-included-file (keyword backend info)
2118 "Transcode file specified with include KEYWORD.
2120 KEYWORD is the include keyword element transcoded. BACKEND is
2121 the language back-end used for transcoding. INFO is the plist
2122 used as a communication channel.
2124 This function updates `:included-files' and `:headline-offset'
2125 properties.
2127 Return the transcoded string."
2128 (let ((data (org-export-parse-included-file keyword info))
2129 (file (let ((value (org-element-get-property :value keyword)))
2130 (and (string-match "^\"\\(\\S-+\\)\"" value)
2131 (match-string 1 value)))))
2132 (org-element-normalize-string
2133 (org-export-data
2134 data backend
2135 (org-combine-plists
2136 info
2137 ;; Store full path of already included files to avoid
2138 ;; recursive file inclusion.
2139 `(:included-files
2140 ,(cons (expand-file-name file) (plist-get info :included-files))
2141 ;; Ensure that a top-level headline in the included
2142 ;; file becomes a direct child of the current headline
2143 ;; in the buffer.
2144 :headline-offset
2145 ,(- (+ (org-element-get-property
2146 :level (org-export-get-parent-headline keyword info))
2147 (plist-get info :headline-offset))
2148 (1- (org-export-get-min-level data info)))))))))
2150 (defun org-export-get-file-contents (file &optional lines)
2151 "Get the contents of FILE and return them as a string.
2152 When optional argument LINES is a string specifying a range of
2153 lines, include only those lines."
2154 (with-temp-buffer
2155 (insert-file-contents file)
2156 (when lines
2157 (let* ((lines (split-string lines "-"))
2158 (lbeg (string-to-number (car lines)))
2159 (lend (string-to-number (cadr lines)))
2160 (beg (if (zerop lbeg) (point-min)
2161 (goto-char (point-min))
2162 (forward-line (1- lbeg))
2163 (point)))
2164 (end (if (zerop lend) (point-max)
2165 (goto-char (point-min))
2166 (forward-line (1- lend))
2167 (point))))
2168 (narrow-to-region beg end)))
2169 (buffer-string)))
2171 (defun org-export-parse-included-file (keyword info)
2172 "Parse file specified by include KEYWORD.
2174 KEYWORD is the include keyword element transcoded. BACKEND is
2175 the language back-end used for transcoding. INFO is the plist
2176 used as a communication channel.
2178 Return the parsed tree."
2179 (let* ((value (org-element-get-property :value keyword))
2180 (file (and (string-match "^\"\\(\\S-+\\)\"" value)
2181 (prog1 (match-string 1 value)
2182 (setq value (replace-match "" nil nil value)))))
2183 (lines (and (string-match
2184 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\"" value)
2185 (prog1 (match-string 1 value)
2186 (setq value (replace-match "" nil nil value)))))
2187 (env (cond ((string-match "\\<example\\>" value) "example")
2188 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
2189 (match-string 1 value)))))
2190 (cond
2191 ((or (not file)
2192 (not (file-exists-p file))
2193 (not (file-readable-p file)))
2194 (format "Cannot include file %s" file))
2195 ((and (not env)
2196 (member (expand-file-name file) (plist-get info :included-files)))
2197 (error "Recursive file inclusion: %S" file))
2198 (t (let ((raw (org-element-normalize-string
2199 (org-export-get-file-contents
2200 (expand-file-name file) lines))))
2201 ;; If environment isn't specified, Insert file in
2202 ;; a temporary buffer and parse it as Org syntax.
2203 ;; Otherwise, build the element representing the file.
2204 (cond
2205 ((not env)
2206 (with-temp-buffer
2207 (insert raw) (org-mode) (org-element-parse-buffer)))
2208 ((string= "example" env)
2209 `(org-data nil (example-block (:value ,raw :post-blank 0))))
2211 `(org-data
2213 (src-block (:value ,raw :language ,env :post-blank 0))))))))))
2216 ;;;; For Links
2218 ;; `org-export-solidify-link-text' turns a string into a safer version
2219 ;; for links, replacing most non-standard characters with hyphens.
2221 ;; `org-export-get-coderef-format' returns an appropriate format
2222 ;; string for coderefs.
2224 ;; `org-export-inline-image-p' returns a non-nil value when the link
2225 ;; provided should be considered as an inline image.
2227 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
2228 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
2229 ;; returns an appropriate unique identifier when found, or nil.
2231 ;; `org-export-resolve-id-link' returns the first headline with
2232 ;; specified id or custom-id in parse tree, or nil when none was
2233 ;; found.
2235 ;; `org-export-resolve-coderef' associates a reference to a line
2236 ;; number in the element it belongs, or returns the reference itself
2237 ;; when the element isn't numbered.
2239 (defun org-export-solidify-link-text (s)
2240 "Take link text S and make a safe target out of it."
2241 (save-match-data
2242 (mapconcat 'identity (org-split-string s "[^a-zA-Z0-9_\\.-]+") "-")))
2244 (defun org-export-get-coderef-format (path desc)
2245 "Return format string for code reference link.
2246 PATH is the link path. DESC is its description."
2247 (save-match-data
2248 (cond ((string-match (regexp-quote (concat "(" path ")")) desc)
2249 (replace-match "%s" t t desc))
2250 ((string= desc "") "%s")
2251 (t desc))))
2253 (defun org-export-inline-image-p (link &optional extensions)
2254 "Non-nil if LINK object points to an inline image.
2256 When non-nil, optional argument EXTENSIONS is a list of valid
2257 extensions for image files, as strings. Otherwise, a default
2258 list is provided \(cf `org-image-file-name-regexp'\)."
2259 (and (not (org-element-get-contents link))
2260 (string= (org-element-get-property :type link) "file")
2261 (org-file-image-p
2262 (expand-file-name (org-element-get-property :path link))
2263 extensions)))
2265 (defun org-export-resolve-fuzzy-link (link info)
2266 "Return LINK destination.
2268 INFO is a plist holding contextual information.
2270 Return value can be an object, an element, or nil:
2272 - If LINK path exactly matches any target, return the target
2273 object.
2275 - If LINK path exactly matches any headline name, return that
2276 element. If more than one headline share that name, priority
2277 will be given to the one with the closest common ancestor, if
2278 any, or the first one in the parse tree otherwise.
2280 - Otherwise, return nil.
2282 Assume LINK type is \"fuzzy\"."
2283 (let ((path (org-element-get-property :path link)))
2284 ;; Link points to a target: return it.
2285 (or (loop for target in (plist-get info :target-list)
2286 when (string= (org-element-get-property :raw-value target) path)
2287 return target)
2288 ;; Link either points to an headline or nothing. Try to find
2289 ;; the source, with priority given to headlines with the closest
2290 ;; common ancestor. If such candidate is found, return its
2291 ;; beginning position as an unique identifier, otherwise return
2292 ;; nil.
2293 (let ((find-headline
2294 (function
2295 ;; Return first headline whose `:raw-value' property
2296 ;; is NAME in parse tree DATA, or nil.
2297 (lambda (name data)
2298 (org-element-map
2299 data 'headline
2300 (lambda (headline local)
2301 (when (string=
2302 (org-element-get-property :raw-value headline)
2303 name)
2304 headline))
2305 info 'first-match)))))
2306 ;; Search among headlines sharing an ancestor with link,
2307 ;; from closest to farthest.
2308 (or (catch 'exit
2309 (mapc
2310 (lambda (parent)
2311 (when (eq (car parent) 'headline)
2312 (let ((foundp (funcall find-headline path parent)))
2313 (when foundp (throw 'exit foundp)))))
2314 (plist-get info :genealogy)) nil)
2315 ;; No match with a common ancestor: try the full parse-tree.
2316 (funcall find-headline path (plist-get info :parse-tree)))))))
2318 (defun org-export-resolve-id-link (link info)
2319 "Return headline referenced as LINK destination.
2321 INFO is a plist used as a communication channel.
2323 Return value can be an headline element or nil. Assume LINK type
2324 is either \"id\" or \"custom-id\"."
2325 (let ((id (org-element-get-property :path link)))
2326 (org-element-map
2327 (plist-get info :parse-tree) 'headline
2328 (lambda (headline local)
2329 (when (or (string= (org-element-get-property :id headline) id)
2330 (string= (org-element-get-property :custom-id headline) id))
2331 headline))
2332 info 'first-match)))
2334 (defun org-export-resolve-coderef (ref info)
2335 "Resolve a code reference REF.
2337 INFO is a plist used as a communication channel.
2339 Return associated line number in source code, or REF itself,
2340 depending on src-block or example element's switches."
2341 (org-element-map
2342 (plist-get info :parse-tree) '(src-block example)
2343 (lambda (el local)
2344 (let ((switches (or (org-element-get-property :switches el) "")))
2345 (with-temp-buffer
2346 (insert (org-trim (org-element-get-property :value el)))
2347 ;; Build reference regexp.
2348 (let* ((label
2349 (or (and (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
2350 (match-string 1 switches))
2351 org-coderef-label-format))
2352 (ref-re
2353 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
2354 (replace-regexp-in-string "%s" ref label nil t))))
2355 ;; Element containing REF is found. Only associate REF to
2356 ;; a line number if element has "+n" or "-n" and "-k" or
2357 ;; "-r" as switches. When it has "+n", count accumulated
2358 ;; locs before, too.
2359 (when (re-search-backward ref-re nil t)
2360 (cond
2361 ((not (string-match "-[kr]\\>" switches)) ref)
2362 ((string-match "-n\\>" switches) (line-number-at-pos))
2363 ((string-match "\\+n\\>" switches)
2364 (+ (org-export-get-loc el local) (line-number-at-pos)))
2365 (t ref)))))))
2366 info 'first-match))
2369 ;;;; For Macros
2371 ;; `org-export-expand-macro' simply takes care of expanding macros.
2373 (defun org-export-expand-macro (macro info)
2374 "Expand MACRO and return it as a string.
2375 INFO is a plist holding export options."
2376 (let* ((key (org-element-get-property :key macro))
2377 (args (org-element-get-property :args macro))
2378 (value (plist-get info (intern (format ":macro-%s" key)))))
2379 ;; Replace arguments in VALUE.
2380 (let ((s 0) n)
2381 (while (string-match "\\$\\([0-9]+\\)" value s)
2382 (setq s (1+ (match-beginning 0))
2383 n (string-to-number (match-string 1 value)))
2384 (and (>= (length args) n)
2385 (setq value (replace-match (nth (1- n) args) t t value)))))
2386 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
2387 (when (string-match "\\`(eval\\>" value)
2388 (setq value (eval (read value))))
2389 ;; Return expanded string.
2390 (format "%s" value)))
2393 ;;;; For References
2395 ;; `org-export-get-ordinal' associates a sequence number to any object
2396 ;; or element.
2398 (defun org-export-get-ordinal (element info &optional within-section predicate)
2399 "Return ordinal number of an element or object.
2401 ELEMENT is the element or object considered. INFO is the plist
2402 used as a communication channel.
2404 When optional argument WITHIN-SECTION is non-nil, narrow counting
2405 to the section containing ELEMENT.
2407 Optional argument PREDICATE is a function returning a non-nil
2408 value if the current element or object should be counted in. It
2409 accepts one argument: the element or object being considered.
2410 This argument allows to count only a certain type of objects,
2411 like inline images, which are a subset of links \(in that case,
2412 `org-export-inline-image-p' might be an useful predicate\)."
2413 (let ((counter 0)
2414 (type (car element))
2415 ;; Determine if search should apply to current section, in
2416 ;; which case it should be retrieved first, or to full parse
2417 ;; tree. As a special case, an element or object without
2418 ;; a parent headline will also trigger a full search,
2419 ;; notwithstanding WITHIN-SECTION value.
2420 (data
2421 (if (not within-section) (plist-get info :parse-tree)
2422 (or (org-export-get-parent-headline element info)
2423 (plist-get info :parse-tree)))))
2424 ;; Increment counter until ELEMENT is found again.
2425 (org-element-map
2426 data type
2427 (lambda (el local)
2428 (cond
2429 ((and (functionp predicate) (funcall predicate el)))
2430 ((equal element el) (1+ counter))
2431 (t (incf counter) nil)))
2432 info 'first-match)))
2435 ;;;; For Src-Blocks
2437 ;; `org-export-get-loc' counts number of code lines accumulated in
2438 ;; src-block or example-block elements with a "+n" switch until
2439 ;; a given element, excluded. Note: "-n" switches reset that count.
2441 ;; `org-export-handle-code' takes care of line numbering and reference
2442 ;; cleaning in source code, when appropriate.
2444 (defun org-export-get-loc (element info)
2445 "Return accumulated lines of code up to ELEMENT.
2447 INFO is the plist used as a communication channel.
2449 ELEMENT is excluded from count."
2450 (let ((loc 0))
2451 (org-element-map
2452 (plist-get info :parse-tree) `(src-block example-block ,(car element))
2453 (lambda (el local)
2454 (cond
2455 ;; ELEMENT is reached: Quit the loop.
2456 ((equal el element) t)
2457 ;; Only count lines from src-block and example-block elements
2458 ;; with a "+n" or "-n" switch. A "-n" switch resets counter.
2459 ((not (memq (car el) '(src-block example-block))) nil)
2460 ((let ((switches (org-element-get-property :switches el)))
2461 (when (and switches (string-match "\\([-+]\\)n\\>" switches))
2462 ;; Accumulate locs or reset them.
2463 (let ((accumulatep (string= (match-string 1 switches) "-"))
2464 (lines (org-count-lines
2465 (org-trim (org-element-get-property :value el)))))
2466 (setq loc (if accumulatep lines (+ loc lines))))))
2467 ;; Return nil to stay in the loop.
2468 nil)))
2469 info 'first-match)
2470 ;; Return value.
2471 loc))
2473 (defun org-export-handle-code (element info &optional num-fmt ref-fmt delayed)
2474 "Handle line numbers and code references in ELEMENT.
2476 ELEMENT has either a `src-block' an `example-block' type. INFO
2477 is a plist used as a communication channel.
2479 If optional argument NUM-FMT is a string, it will be used as
2480 a format string for numbers at beginning of each line.
2482 If optional argument REF-FMT is a string, it will be used as
2483 a format string for each line of code containing a reference.
2485 When optional argument DELAYED is non-nil, `org-loc' and
2486 `org-coderef' properties, set to an adequate value, are applied
2487 to, respectively, numbered lines and lines with a reference. No
2488 line numbering is done and all references are stripped from the
2489 resulting string. Both NUM-FMT and REF-FMT arguments are ignored
2490 in that situation.
2492 Return new code as a string."
2493 (let* ((switches (or (org-element-get-property :switches element) ""))
2494 (code (org-element-get-property :value element))
2495 (numberp (string-match "[-+]n\\>" switches))
2496 (accumulatep (string-match "\\+n\\>" switches))
2497 ;; Initialize loc counter when any kind of numbering is
2498 ;; active.
2499 (total-LOC (cond
2500 (accumulatep (org-export-get-loc element info))
2501 (numberp 0)))
2502 ;; Get code and clean it. Remove blank lines at its
2503 ;; beginning and end. Also remove protective commas.
2504 (preserve-indent-p (or org-src-preserve-indentation
2505 (string-match "-i\\>" switches)))
2506 (replace-labels (when (string-match "-r\\>" switches)
2507 (if (string-match "-k\\>" switches) 'keep t)))
2508 (code (let ((c (replace-regexp-in-string
2509 "\\`\\([ \t]*\n\\)+" ""
2510 (replace-regexp-in-string
2511 "\\(:?[ \t]*\n\\)*[ \t]*\\'" "\n" code))))
2512 ;; If appropriate, remove global indentation.
2513 (unless preserve-indent-p (setq c (org-remove-indentation c)))
2514 ;; Free up the protected lines. Note: Org blocks
2515 ;; have commas at the beginning or every line.
2516 (if (string=
2517 (or (org-element-get-property :language element) "")
2518 "org")
2519 (replace-regexp-in-string "^," "" c)
2520 (replace-regexp-in-string
2521 "^\\(,\\)\\(:?\\*\\|[ \t]*#\\+\\)" "" c nil nil 1))))
2522 ;; Split code to process it line by line.
2523 (code-lines (org-split-string code "\n"))
2524 ;; If numbering is active, ensure line numbers will be
2525 ;; correctly padded before applying the format string.
2526 (num-fmt
2527 (when (and (not delayed) numberp)
2528 (format (if (stringp num-fmt) num-fmt "%s: ")
2529 (format "%%%ds"
2530 (length (number-to-string
2531 (+ (length code-lines) total-LOC)))))))
2532 ;; Get format used for references.
2533 (label-fmt (or (and (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
2534 (match-string 1 switches))
2535 org-coderef-label-format))
2536 ;; Build a regexp matching a loc with a reference.
2537 (with-ref-re (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
2538 (replace-regexp-in-string
2539 "%s" "\\([-a-zA-Z0-9_ ]+\\)" label-fmt nil t))))
2540 (org-element-normalize-string
2541 (mapconcat
2542 (lambda (loc)
2543 ;; Maybe add line number to current line of code (LOC).
2544 (when numberp
2545 (incf total-LOC)
2546 (setq loc (if delayed (org-add-props loc nil 'org-loc total-LOC)
2547 (concat (format num-fmt total-LOC) loc))))
2548 ;; Take action if at a ref line.
2549 (when (string-match with-ref-re loc)
2550 (let ((ref (match-string 3 loc)))
2551 (setq loc
2552 ;; Option "-r" without "-k" removes labels.
2553 ;; A non-nil DELAYED removes labels unconditionally.
2554 (if (or delayed
2555 (and replace-labels (not (eq replace-labels 'keep))))
2556 (replace-match "" nil nil loc 1)
2557 (replace-match (format "(%s)" ref) nil nil loc 2)))
2558 ;; Store REF in `org-coderef' property if DELAYED asks to.
2559 (cond (delayed (setq loc (org-add-props loc nil 'org-coderef ref)))
2560 ;; If REF-FMT is defined, apply it to current LOC.
2561 ((stringp ref-fmt) (setq loc (format ref-fmt loc))))))
2562 ;; Return updated LOC for concatenation.
2563 loc)
2564 code-lines "\n"))))
2567 ;;;; For Tables
2569 ;; `org-export-table-format-info' extracts formatting information
2570 ;; (alignment, column groups and presence of a special column) from
2571 ;; a raw table and returns it as a property list.
2573 ;; `org-export-clean-table' cleans the raw table from any Org
2574 ;; table-specific syntax.
2576 (defun org-export-table-format-info (table)
2577 "Extract info from TABLE.
2578 Return a plist whose properties and values are:
2579 `:alignment' vector of strings among \"r\", \"l\" and \"c\",
2580 `:column-groups' vector of symbols among `start', `end', `start-end',
2581 `:row-groups' list of integers representing row groups.
2582 `:special-column-p' non-nil if table has a special column.
2583 `:width' vector of integers representing desired width of
2584 current column, or nil."
2585 (with-temp-buffer
2586 (insert table)
2587 (goto-char 1)
2588 (org-table-align)
2589 (let ((align (vconcat (mapcar (lambda (c) (if c "r" "l"))
2590 org-table-last-alignment)))
2591 (width (make-vector (length org-table-last-alignment) nil))
2592 (colgroups (make-vector (length org-table-last-alignment) nil))
2593 (row-group 0)
2594 (rowgroups)
2595 (special-column-p 'empty))
2596 (mapc (lambda (row)
2597 (if (string-match "^[ \t]*|[-+]+|[ \t]*$" row)
2598 (incf row-group)
2599 ;; Determine if a special column is present by looking
2600 ;; for special markers in the first column. More
2601 ;; accurately, the first column is considered special
2602 ;; if it only contains special markers and, maybe,
2603 ;; empty cells.
2604 (setq special-column-p
2605 (cond
2606 ((not special-column-p) nil)
2607 ((string-match "^[ \t]*| *\\\\?\\([/#!$*_^]\\) *|" row)
2608 'special)
2609 ((string-match "^[ \t]*| +|" row) special-column-p))))
2610 (cond
2611 ;; Read forced alignment and width information, if any,
2612 ;; and determine final alignment for the table.
2613 ((org-table-cookie-line-p row)
2614 (let ((col 0))
2615 (mapc (lambda (field)
2616 (when (string-match
2617 "<\\([lrc]\\)?\\([0-9]+\\)?>" field)
2618 (let ((align-data (match-string 1 field)))
2619 (when align-data (aset align col align-data)))
2620 (let ((w-data (match-string 2 field)))
2621 (when w-data
2622 (aset width col (string-to-number w-data)))))
2623 (incf col))
2624 (org-split-string row "[ \t]*|[ \t]*"))))
2625 ;; Read column groups information.
2626 ((org-table-colgroup-line-p row)
2627 (let ((col 0))
2628 (mapc (lambda (field)
2629 (aset colgroups col
2630 (cond ((string= "<" field) 'start)
2631 ((string= ">" field) 'end)
2632 ((string= "<>" field) 'start-end)))
2633 (incf col))
2634 (org-split-string row "[ \t]*|[ \t]*"))))
2635 ;; Contents line.
2636 (t (push row-group rowgroups))))
2637 (org-split-string table "\n"))
2638 ;; Return plist.
2639 (list :alignment align
2640 :column-groups colgroups
2641 :row-groups (reverse rowgroups)
2642 :special-column-p (eq special-column-p 'special)
2643 :width width))))
2645 (defun org-export-clean-table (table specialp)
2646 "Clean string TABLE from its formatting elements.
2647 Remove any row containing column groups or formatting cookies and
2648 rows starting with a special marker. If SPECIALP is non-nil,
2649 assume the table contains a special formatting column and remove
2650 it also."
2651 (let ((rows (org-split-string table "\n")))
2652 (mapconcat 'identity
2653 (delq nil
2654 (mapcar
2655 (lambda (row)
2656 (cond
2657 ((org-table-colgroup-line-p row) nil)
2658 ((org-table-cookie-line-p row) nil)
2659 ;; Ignore rows starting with a special marker.
2660 ((string-match "^[ \t]*| *[!_^/] *|" row) nil)
2661 ;; Remove special column.
2662 ((and specialp
2663 (or (string-match "^\\([ \t]*\\)|-+\\+" row)
2664 (string-match "^\\([ \t]*\\)|[^|]*|" row)))
2665 (replace-match "\\1|" t nil row))
2666 (t row)))
2667 rows))
2668 "\n")))
2671 ;;;; For Tables Of Contents
2673 ;; `org-export-collect-headlines' builds a list of all exportable
2674 ;; headline elements, maybe limited to a certain depth. One can then
2675 ;; easily parse it and transcode it.
2677 ;; Building lists of tables, figures or listings is quite similar.
2678 ;; Once the generic function `org-export-collect-elements' is defined,
2679 ;; `org-export-collect-tables', `org-export-collect-figures' and
2680 ;; `org-export-collect-listings' can be derived from it.
2682 (defun org-export-collect-headlines (info &optional n)
2683 "Collect headlines in order to build a table of contents.
2685 INFO is a plist used as a communication channel.
2687 When non-nil, optional argument N must be an integer. It
2688 specifies the depth of the table of contents.
2690 Return a list of all exportable headlines as parsed elements."
2691 (org-element-map
2692 (plist-get info :parse-tree)
2693 'headline
2694 (lambda (headline local)
2695 ;; Strip contents from HEADLINE.
2696 (let ((relative-level (org-export-get-relative-level headline local)))
2697 (unless (and n (> relative-level n)) headline)))
2698 info))
2700 (defun org-export-collect-elements (type backend info)
2701 "Collect named elements of type TYPE.
2703 Only elements with a caption or a name are collected.
2705 BACKEND is the back-end used to transcode their caption or name.
2706 INFO is a plist holding export options.
2708 Return an alist where key is entry's name and value an unique
2709 identifier that might be used for internal links."
2710 (org-element-map
2711 (plist-get info :parse-tree)
2712 type
2713 (lambda (element info)
2714 (let ((entry
2715 (cond
2716 ((org-element-get-property :caption element)
2717 (org-export-secondary-string
2718 (org-element-get-property :caption element) backend info))
2719 ((org-element-get-property :name element)
2720 (org-export-secondary-string
2721 (org-element-get-property :name element) backend info)))))
2722 ;; Skip elements with neither a caption nor a name.
2723 (when entry (cons entry (org-element-get-property :begin element)))))
2724 info))
2726 (defun org-export-collect-tables (backend info)
2727 "Build a list of tables.
2729 BACKEND is the back-end used to transcode table's name. INFO is
2730 a plist holding export options.
2732 Return an alist where key is the caption of the table and value
2733 an unique identifier that might be used for internal links."
2734 (org-export-collect-elements 'table backend info))
2736 (defun org-export-collect-figures (backend info)
2737 "Build a list of figures.
2739 A figure is a paragraph type element with a caption or a name.
2741 BACKEND is the back-end used to transcode headline's name. INFO
2742 is a plist holding export options.
2744 Return an alist where key is the caption of the figure and value
2745 an unique indentifier that might be used for internal links."
2746 (org-export-collect-elements 'paragraph backend info))
2748 (defun org-export-collect-listings (backend info)
2749 "Build a list of src blocks.
2751 BACKEND is the back-end used to transcode src block's name. INFO
2752 is a plist holding export options.
2754 Return an alist where key is the caption of the src block and
2755 value an unique indentifier that might be used for internal
2756 links."
2757 (org-export-collect-elements 'src-block backend info))
2760 ;;;; Topology
2762 (defun org-export-get-parent-headline (blob info)
2763 "Return BLOB's closest parent headline or nil.
2764 INFO is a plist used as a communication channel."
2765 (catch 'exit
2766 (mapc
2767 (lambda (el) (when (eq (car el) 'headline) (throw 'exit el)))
2768 (plist-get info :genealogy))
2769 nil))
2771 (defun org-export-get-previous-element (blob info)
2772 "Return previous element or object.
2774 BLOB is an element or object. INFO is a plist used as
2775 a communication channel.
2777 Return previous element or object, a string, or nil."
2778 (let ((parent (car (plist-get info :genealogy))))
2779 (cadr (member blob (reverse (org-element-get-contents parent))))))
2783 ;;; The Dispatcher
2785 ;; `org-export-dispatch' is the standard interactive way to start an
2786 ;; export process. It uses `org-export-dispatch-ui' as a subroutine
2787 ;; for its interface. Most commons back-ends should have an entry in
2788 ;; it.
2790 (defun org-export-dispatch ()
2791 "Export dispatcher for Org mode.
2793 It provides an access to common export related tasks in a buffer.
2794 Its interface comes in two flavours: standard and expert. While
2795 both share the same set of bindings, only the former displays the
2796 valid keys associations. Set `org-export-dispatch-use-expert-ui'
2797 to switch to one or the other.
2799 Return an error if key pressed has no associated command."
2800 (interactive)
2801 (let* ((input (org-export-dispatch-ui
2802 (if (listp org-export-initial-scope) org-export-initial-scope
2803 (list org-export-initial-scope))
2804 org-export-dispatch-use-expert-ui))
2805 (raw-key (car input))
2806 (scope (cdr input)))
2807 ;; Translate "C-a", "C-b"... into "a", "b"... Then take action
2808 ;; depending on user's key pressed.
2809 (case (if (< raw-key 27) (+ raw-key 96) raw-key)
2810 ;; Export with `e-latex' back-end.
2812 (let ((outbuf
2813 (org-export-to-buffer
2814 'e-latex "*Org E-LaTeX Export*"
2815 (memq 'subtree scope) (memq 'visible scope) (memq 'body scope))))
2816 (with-current-buffer outbuf (latex-mode))
2817 (when org-export-show-temporary-export-buffer
2818 (switch-to-buffer-other-window outbuf))))
2819 (?l (org-e-latex-export-to-latex
2820 (memq 'subtree scope) (memq 'visible scope) (memq 'body scope)))
2821 (?p (org-e-latex-export-to-pdf
2822 (memq 'subtree scope) (memq 'visible scope) (memq 'body scope)))
2823 (?d (org-open-file
2824 (org-e-latex-export-to-pdf
2825 (memq 'subtree scope) (memq 'visible scope) (memq 'body scope))))
2826 ;; Undefined command.
2827 (t (error "No command associated with key %s"
2828 (char-to-string raw-key))))))
2830 (defun org-export-dispatch-ui (scope expertp)
2831 "Handle interface for `org-export-dispatch'.
2833 SCOPE is a list containing current interactive options set for
2834 export. It can contain any of the following symbols:
2835 `body' toggles a body-only export
2836 `subtree' restricts export to current subtree
2837 `visible' restricts export to visible part of buffer.
2839 EXPERTP, when non-nil, triggers expert UI. In that case, no help
2840 buffer is provided, but indications about currently active
2841 options are given in the prompt. Moreover, \[?] allows to switch
2842 back to standard interface.
2844 Return value is a list with key pressed as car and a list of
2845 final interactive export options as cdr."
2846 (let ((help (format "------------------- General Options -------------------
2847 \[1] Body only: %s
2848 \[2] Export scope: %s
2849 \[3] Visible only: %s
2851 -------------------- LaTeX Export ---------------------
2852 \[l] to LaTeX file [L] to temporary buffer
2853 \[p] to PDF file [d] ... and open it"
2854 (if (memq 'body scope) "On" "Off")
2855 (if (memq 'subtree scope) "Subtree" "Buffer")
2856 (if (memq 'visible scope) "On" "Off")))
2857 (standard-prompt "Export command: ")
2858 (expert-prompt (format "Export command (%s%s%s): "
2859 (if (memq 'body scope) "b" "-")
2860 (if (memq 'subtree scope) "s" "-")
2861 (if (memq 'visible scope) "v" "-")))
2862 (handle-keypress
2863 (function
2864 ;; Read a character from command input, toggling interactive
2865 ;; options when applicable. PROMPT is the displayed prompt,
2866 ;; as a string.
2867 (lambda (prompt)
2868 (let ((key (read-char-exclusive prompt)))
2869 (cond
2870 ;; Ignore non-standard characters (i.e. "M-a").
2871 ((not (characterp key)) (org-export-dispatch-ui scope expertp))
2872 ;; Switch back to standard interface.
2873 ((and (eq key ??) expertp) (org-export-dispatch-ui scope nil))
2874 ((eq key ?1)
2875 (org-export-dispatch-ui
2876 (if (memq 'body scope) (remq 'body scope) (cons 'body scope))
2877 expertp))
2878 ((eq key ?2)
2879 (org-export-dispatch-ui
2880 (if (memq 'subtree scope) (remq 'subtree scope)
2881 (cons 'subtree scope))
2882 expertp))
2883 ((eq key ?3)
2884 (org-export-dispatch-ui
2885 (if (memq 'visible scope) (remq 'visible scope)
2886 (cons 'visible scope))
2887 expertp))
2888 (t (cons key scope))))))))
2889 ;; With expert UI, just read key with a fancy prompt. In standard
2890 ;; UI, display an intrusive help buffer.
2891 (if expertp (funcall handle-keypress expert-prompt)
2892 (save-window-excursion
2893 (delete-other-windows)
2894 (with-output-to-temp-buffer "*Org Export/Publishing Help*" (princ help))
2895 (org-fit-window-to-buffer
2896 (get-buffer-window "*Org Export/Publishing Help*"))
2897 (funcall handle-keypress standard-prompt)))))
2900 (provide 'org-export)
2901 ;;; org-export.el ends here