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