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