org-export: Fix error when exporting a buffer with a code block
[org-mode/org-mode-NeilSmithlineMods.git] / contrib / lisp / org-export.el
bloba062a3e98ee2e84b8d653c9c9ce9507e87511bc9
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 When set to an integer n, numbering will only happen for
398 headlines whose relative level is higher or equal to n.
400 This option can also be set with the #+OPTIONS line,
401 e.g. \"num:t\"."
402 :group 'org-export-general
403 :type 'boolean)
405 (defcustom org-export-select-tags '("export")
406 "Tags that select a tree for export.
407 If any such tag is found in a buffer, all trees that do not carry
408 one of these tags will be deleted before export. Inside trees
409 that are selected like this, you can still deselect a subtree by
410 tagging it with one of the `org-export-exclude-tags'."
411 :group 'org-export-general
412 :type '(repeat (string :tag "Tag")))
414 (defcustom org-export-with-special-strings t
415 "Non-nil means interpret \"\-\", \"--\" and \"---\" for export.
417 When this option is turned on, these strings will be exported as:
419 Org HTML LaTeX
420 -----+----------+--------
421 \\- &shy; \\-
422 -- &ndash; --
423 --- &mdash; ---
424 ... &hellip; \ldots
426 This option can also be set with the #+OPTIONS line,
427 e.g. \"-:nil\"."
428 :group 'org-export-general
429 :type 'boolean)
431 (defcustom org-export-with-sub-superscripts t
432 "Non-nil means interpret \"_\" and \"^\" for export.
434 When this option is turned on, you can use TeX-like syntax for
435 sub- and superscripts. Several characters after \"_\" or \"^\"
436 will be considered as a single item - so grouping with {} is
437 normally not needed. For example, the following things will be
438 parsed as single sub- or superscripts.
440 10^24 or 10^tau several digits will be considered 1 item.
441 10^-12 or 10^-tau a leading sign with digits or a word
442 x^2-y^3 will be read as x^2 - y^3, because items are
443 terminated by almost any nonword/nondigit char.
444 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
446 Still, ambiguity is possible - so when in doubt use {} to enclose
447 the sub/superscript. If you set this variable to the symbol
448 `{}', the braces are *required* in order to trigger
449 interpretations as sub/superscript. This can be helpful in
450 documents that need \"_\" frequently in plain text.
452 This option can also be set with the #+OPTIONS line,
453 e.g. \"^:nil\"."
454 :group 'org-export-general
455 :type '(choice
456 (const :tag "Interpret them" t)
457 (const :tag "Curly brackets only" {})
458 (const :tag "Do not interpret them" nil)))
460 (defcustom org-export-with-toc t
461 "Non-nil means create a table of contents in exported files.
463 The TOC contains headlines with levels up
464 to`org-export-headline-levels'. When an integer, include levels
465 up to N in the toc, this may then be different from
466 `org-export-headline-levels', but it will not be allowed to be
467 larger than the number of headline levels. When nil, no table of
468 contents is made.
470 This option can also be set with the #+OPTIONS line,
471 e.g. \"toc:nil\" or \"toc:3\"."
472 :group 'org-export-general
473 :type '(choice
474 (const :tag "No Table of Contents" nil)
475 (const :tag "Full Table of Contents" t)
476 (integer :tag "TOC to level")))
478 (defcustom org-export-with-tables t
479 "If non-nil, lines starting with \"|\" define a table.
480 For example:
482 | Name | Address | Birthday |
483 |-------------+----------+-----------|
484 | Arthur Dent | England | 29.2.2100 |
486 This option can also be set with the #+OPTIONS line, e.g. \"|:nil\"."
487 :group 'org-export-general
488 :type 'boolean)
490 (defcustom org-export-with-tags t
491 "If nil, do not export tags, just remove them from headlines.
493 If this is the symbol `not-in-toc', tags will be removed from
494 table of contents entries, but still be shown in the headlines of
495 the document.
497 This option can also be set with the #+OPTIONS line,
498 e.g. \"tags:nil\"."
499 :group 'org-export-general
500 :type '(choice
501 (const :tag "Off" nil)
502 (const :tag "Not in TOC" not-in-toc)
503 (const :tag "On" t)))
505 (defcustom org-export-with-tasks t
506 "Non-nil means include TODO items for export.
507 This may have the following values:
508 t include tasks independent of state.
509 todo include only tasks that are not yet done.
510 done include only tasks that are already done.
511 nil remove all tasks before export
512 list of keywords keep only tasks with these keywords"
513 :group 'org-export-general
514 :type '(choice
515 (const :tag "All tasks" t)
516 (const :tag "No tasks" nil)
517 (const :tag "Not-done tasks" todo)
518 (const :tag "Only done tasks" done)
519 (repeat :tag "Specific TODO keywords"
520 (string :tag "Keyword"))))
522 (defcustom org-export-time-stamp-file t
523 "Non-nil means insert a time stamp into the exported file.
524 The time stamp shows when the file was created.
526 This option can also be set with the #+OPTIONS line,
527 e.g. \"timestamp:nil\"."
528 :group 'org-export-general
529 :type 'boolean)
531 (defcustom org-export-with-timestamps t
532 "If nil, do not export time stamps and associated keywords."
533 :group 'org-export-general
534 :type 'boolean)
536 (defcustom org-export-with-todo-keywords t
537 "Non-nil means include TODO keywords in export.
538 When nil, remove all these keywords from the export.")
540 (defcustom org-export-allow-BIND 'confirm
541 "Non-nil means allow #+BIND to define local variable values for export.
542 This is a potential security risk, which is why the user must
543 confirm the use of these lines."
544 :group 'org-export-general
545 :type '(choice
546 (const :tag "Never" nil)
547 (const :tag "Always" t)
548 (const :tag "Ask a confirmation for each file" confirm)))
550 (defcustom org-export-snippet-translation-alist nil
551 "Alist between export snippets back-ends and exporter back-ends.
553 This variable allows to provide shortcuts for export snippets.
555 For example, with a value of '\(\(\"h\" . \"html\"\)\), the HTML
556 back-end will recognize the contents of \"@h{<b>}\" as HTML code
557 while every other back-end will ignore it."
558 :group 'org-export-general
559 :type '(repeat
560 (cons
561 (string :tag "Shortcut")
562 (string :tag "Back-end"))))
564 (defcustom org-export-coding-system nil
565 "Coding system for the exported file."
566 :group 'org-export-general
567 :type 'coding-system)
569 (defcustom org-export-copy-to-kill-ring t
570 "Non-nil means exported stuff will also be pushed onto the kill ring."
571 :group 'org-export-general
572 :type 'boolean)
574 (defcustom org-export-initial-scope 'buffer
575 "The initial scope when exporting with `org-export-dispatch'.
576 This variable can be either set to `buffer' or `subtree'."
577 :group 'org-export-general
578 :type '(choice
579 (const :tag "Export current buffer" 'buffer)
580 (const :tag "Export current subtree" 'subtree)))
582 (defcustom org-export-show-temporary-export-buffer t
583 "Non-nil means show buffer after exporting to temp buffer.
584 When Org exports to a file, the buffer visiting that file is ever
585 shown, but remains buried. However, when exporting to a temporary
586 buffer, that buffer is popped up in a second window. When this variable
587 is nil, the buffer remains buried also in these cases."
588 :group 'org-export-general
589 :type 'boolean)
591 (defcustom org-export-dispatch-use-expert-ui nil
592 "Non-nil means using a non-intrusive `org-export-dispatch'.
593 In that case, no help buffer is displayed. Though, an indicator
594 for current export scope is added to the prompt \(i.e. \"b\" when
595 output is restricted to body only, \"s\" when it is restricted to
596 the current subtree and \"v\" when only visible elements are
597 considered for export\). Also, \[?] allows to switch back to
598 standard mode."
599 :group 'org-export-general
600 :type 'boolean)
604 ;;; The Communication Channel
606 ;; During export process, every function has access to a number of
607 ;; properties. They are of three types:
609 ;; 1. Export options are collected once at the very beginning of the
610 ;; process, out of the original buffer and environment. The task
611 ;; is handled by `org-export-collect-options' function.
613 ;; All export options are defined through the
614 ;; `org-export-option-alist' variable.
616 ;; 2. Tree properties are extracted directly from the parsed tree, by
617 ;; `org-export-collect-tree-properties' and depend on export
618 ;; options (whole trees may be filtered out of the export process).
620 ;; 3. Local options are updated during parsing, and their value
621 ;; depends on the level of recursion. For now, only `:genealogy'
622 ;; belongs to that category.
624 ;; Here is the full list of properties available during transcode
625 ;; process, with their category (option, tree or local), their
626 ;; value type and the function updating them, when appropriate.
628 ;; + `author' :: Author's name.
629 ;; - category :: option
630 ;; - type :: string
632 ;; + `back-end' :: Current back-end used for transcoding.
633 ;; - category :: tree
634 ;; - type :: symbol
636 ;; + `creator' :: String to write as creation information.
637 ;; - category :: option
638 ;; - type :: string
640 ;; + `date' :: String to use as date.
641 ;; - category :: option
642 ;; - type :: string
644 ;; + `description' :: Description text for the current data.
645 ;; - category :: option
646 ;; - type :: string
648 ;; + `email' :: Author's email.
649 ;; - category :: option
650 ;; - type :: string
652 ;; + `exclude-tags' :: Tags for exclusion of subtrees from export
653 ;; process.
654 ;; - category :: option
655 ;; - type :: list of strings
657 ;; + `footnote-definition-alist' :: Alist between footnote labels and
658 ;; their definition, as parsed data. Only non-inlined footnotes
659 ;; are represented in this alist. Also, every definition isn't
660 ;; guaranteed to be referenced in the parse tree. The purpose of
661 ;; this property is to preserve definitions from oblivion
662 ;; (i.e. when the parse tree comes from a part of the original
663 ;; buffer), it isn't meant for direct use in a back-end. To
664 ;; retrieve a definition relative to a reference, use
665 ;; `org-export-get-footnote-definition' instead.
666 ;; - category :: option
667 ;; - type :: alist (STRING . LIST)
669 ;; + `genealogy' :: Flat list of current object or element's parents
670 ;; from closest to farthest.
671 ;; - category :: local
672 ;; - type :: list of elements and objects
674 ;; + `headline-levels' :: Maximum level being exported as an
675 ;; headline. Comparison is done with the relative level of
676 ;; headlines in the parse tree, not necessarily with their
677 ;; actual level.
678 ;; - category :: option
679 ;; - type :: integer
681 ;; + `headline-offset' :: Difference between relative and real level
682 ;; of headlines in the parse tree. For example, a value of -1
683 ;; means a level 2 headline should be considered as level
684 ;; 1 (cf. `org-export-get-relative-level').
685 ;; - category :: tree
686 ;; - type :: integer
688 ;; + `headline-numbering' :: Alist between headlines' beginning
689 ;; position and their numbering, as a list of numbers
690 ;; (cf. `org-export-get-headline-number').
691 ;; - category :: tree
692 ;; - type :: alist (INTEGER . LIST)
694 ;; + `included-files' :: List of files, with full path, included in
695 ;; the current buffer, through the "#+include:" keyword. It is
696 ;; mainly used to verify that no infinite recursive inclusion
697 ;; happens.
698 ;; - category :: local
699 ;; - type :: list of strings
701 ;; + `keywords' :: List of keywords attached to data.
702 ;; - category :: option
703 ;; - type :: string
705 ;; + `language' :: Default language used for translations.
706 ;; - category :: option
707 ;; - type :: string
709 ;; + `parse-tree' :: Whole parse tree, available at any time during
710 ;; transcoding.
711 ;; - category :: global
712 ;; - type :: list (as returned by `org-element-parse-buffer')
714 ;; + `preserve-breaks' :: Non-nil means transcoding should preserve
715 ;; all line breaks.
716 ;; - category :: option
717 ;; - type :: symbol (nil, t)
719 ;; + `section-numbers' :: Non-nil means transcoding should add
720 ;; section numbers to headlines.
721 ;; - category :: option
722 ;; - type :: symbol (nil, t)
724 ;; + `select-tags' :: List of tags enforcing inclusion of sub-trees in
725 ;; transcoding. When such a tag is present,
726 ;; subtrees without it are de facto excluded from
727 ;; the process. See `use-select-tags'.
728 ;; - category :: option
729 ;; - type :: list of strings
731 ;; + `target-list' :: List of targets encountered in the parse tree.
732 ;; This is used to partly resolve "fuzzy" links
733 ;; (cf. `org-export-resolve-fuzzy-link').
734 ;; - category :: tree
735 ;; - type :: list of strings
737 ;; + `time-stamp-file' :: Non-nil means transcoding should insert
738 ;; a time stamp in the output.
739 ;; - category :: option
740 ;; - type :: symbol (nil, t)
742 ;; + `use-select-tags' :: When non-nil, a select tags has been found
743 ;; in the parse tree. Thus, any headline without one will be
744 ;; filtered out. See `select-tags'.
745 ;; - category :: tree
746 ;; - type :: interger or nil
748 ;; + `with-archived-trees' :: Non-nil when archived subtrees should
749 ;; also be transcoded. If it is set to the `headline' symbol,
750 ;; only the archived headline's name is retained.
751 ;; - category :: option
752 ;; - type :: symbol (nil, t, `headline')
754 ;; + `with-author' :: Non-nil means author's name should be included
755 ;; in the output.
756 ;; - category :: option
757 ;; - type :: symbol (nil, t)
759 ;; + `with-creator' :: Non-nild means a creation sentence should be
760 ;; inserted at the end of the transcoded string. If the value
761 ;; is `comment', it should be commented.
762 ;; - category :: option
763 ;; - type :: symbol (`comment', nil, t)
765 ;; + `with-drawers' :: Non-nil means drawers should be exported. If
766 ;; its value is a list of names, only drawers with such names
767 ;; will be transcoded.
768 ;; - category :: option
769 ;; - type :: symbol (nil, t) or list of strings
771 ;; + `with-email' :: Non-nil means output should contain author's
772 ;; email.
773 ;; - category :: option
774 ;; - type :: symbol (nil, t)
776 ;; + `with-emphasize' :: Non-nil means emphasized text should be
777 ;; interpreted.
778 ;; - category :: option
779 ;; - type :: symbol (nil, t)
781 ;; + `with-fixed-width' :: Non-nil if transcoder should interpret
782 ;; strings starting with a colon as a fixed-with (verbatim)
783 ;; area.
784 ;; - category :: option
785 ;; - type :: symbol (nil, t)
787 ;; + `with-footnotes' :: Non-nil if transcoder should interpret
788 ;; footnotes.
789 ;; - category :: option
790 ;; - type :: symbol (nil, t)
792 ;; + `with-priority' :: Non-nil means transcoding should include
793 ;; priority cookies.
794 ;; - category :: option
795 ;; - type :: symbol (nil, t)
797 ;; + `with-special-strings' :: Non-nil means transcoding should
798 ;; interpret special strings in plain text.
799 ;; - category :: option
800 ;; - type :: symbol (nil, t)
802 ;; + `with-sub-superscript' :: Non-nil means transcoding should
803 ;; interpret subscript and superscript. With a value of "{}",
804 ;; only interpret those using curly brackets.
805 ;; - category :: option
806 ;; - type :: symbol (nil, {}, t)
808 ;; + `with-tables' :: Non-nil means transcoding should interpret
809 ;; tables.
810 ;; - category :: option
811 ;; - type :: symbol (nil, t)
813 ;; + `with-tags' :: Non-nil means transcoding should keep tags in
814 ;; headlines. A `not-in-toc' value will remove them
815 ;; from the table of contents, if any, nonetheless.
816 ;; - category :: option
817 ;; - type :: symbol (nil, t, `not-in-toc')
819 ;; + `with-tasks' :: Non-nil means transcoding should include
820 ;; headlines with a TODO keyword. A `todo' value
821 ;; will only include headlines with a todo type
822 ;; keyword while a `done' value will do the
823 ;; contrary. If a list of strings is provided, only
824 ;; tasks with keywords belonging to that list will
825 ;; be kept.
826 ;; - category :: option
827 ;; - type :: symbol (t, todo, done, nil) or list of strings
829 ;; + `with-timestamps' :: Non-nil means transcoding should include
830 ;; time stamps and associated keywords. Otherwise, completely
831 ;; remove them.
832 ;; - category :: option
833 ;; - type :: symbol: (t, nil)
835 ;; + `with-toc' :: Non-nil means that a table of contents has to be
836 ;; added to the output. An integer value limits its
837 ;; depth.
838 ;; - category :: option
839 ;; - type :: symbol (nil, t or integer)
841 ;; + `with-todo-keywords' :: Non-nil means transcoding should
842 ;; include TODO keywords.
843 ;; - category :: option
844 ;; - type :: symbol (nil, t)
846 ;;;; Export Options
848 ;; Export options come from five sources, in increasing precedence
849 ;; order:
851 ;; - Global variables,
852 ;; - External options provided at export time,
853 ;; - Options keyword symbols,
854 ;; - Buffer keywords,
855 ;; - Subtree properties.
857 ;; The central internal function with regards to export options is
858 ;; `org-export-collect-options'. It updates global variables with
859 ;; "#+BIND:" keywords, then retrieve and prioritize properties from
860 ;; the different sources.
862 ;; The internal functions doing the retrieval are:
863 ;; `org-export-parse-option-keyword' ,
864 ;; `org-export-get-subtree-options' ,
865 ;; `org-export-get-inbuffer-options' and
866 ;; `org-export-get-global-options'.
868 ;; Some properties do not rely on the previous sources but still
869 ;; depend on the original buffer are taken care of in
870 ;; `org-export-initial-options'.
872 ;; Also, `org-export-confirm-letbind' and `org-export-install-letbind'
873 ;; take care of the part relative to "#+BIND:" keywords.
875 (defun org-export-collect-options (backend subtreep ext-plist)
876 "Collect export options from the current buffer.
878 BACKEND is a symbol specifying the back-end to use.
880 When SUBTREEP is non-nil, assume the export is done against the
881 current sub-tree.
883 EXT-PLIST is a property list with external parameters overriding
884 org-mode's default settings, but still inferior to file-local
885 settings."
886 ;; First install #+BIND variables.
887 (org-export-install-letbind-maybe)
888 ;; Get and prioritize export options...
889 (let ((options (org-combine-plists
890 ;; ... from global variables...
891 (org-export-get-global-options backend)
892 ;; ... from buffer's name (default title)...
893 `(:title
894 ,(or (let ((file (buffer-file-name (buffer-base-buffer))))
895 (and file
896 (file-name-sans-extension
897 (file-name-nondirectory file))))
898 (buffer-name (buffer-base-buffer))))
899 ;; ... from an external property list...
900 ext-plist
901 ;; ... from in-buffer settings...
902 (org-export-get-inbuffer-options
903 (org-with-wide-buffer (buffer-string)) backend
904 (and buffer-file-name
905 (org-remove-double-quotes buffer-file-name)))
906 ;; ... and from subtree, when appropriate.
907 (and subtreep
908 (org-export-get-subtree-options)))))
909 ;; Add initial options.
910 (setq options (append (org-export-initial-options options) options))
911 ;; Return plist.
912 options))
914 (defun org-export-parse-option-keyword (options backend)
915 "Parse an OPTIONS line and return values as a plist.
916 BACKEND is a symbol specifying the back-end to use."
917 (let* ((all (append org-export-option-alist
918 (let ((var (intern
919 (format "org-%s-option-alist" backend))))
920 (and (boundp var) (eval var)))))
921 ;; Build an alist between #+OPTION: item and property-name.
922 (alist (delq nil
923 (mapcar (lambda (e)
924 (when (nth 2 e) (cons (regexp-quote (nth 2 e))
925 (car e))))
926 all)))
927 plist)
928 (mapc (lambda (e)
929 (when (string-match (concat "\\(\\`\\|[ \t]\\)"
930 (car e)
931 ":\\(([^)\n]+)\\|[^ \t\n\r;,.]*\\)")
932 options)
933 (setq plist (plist-put plist
934 (cdr e)
935 (car (read-from-string
936 (match-string 2 options)))))))
937 alist)
938 plist))
940 (defun org-export-get-subtree-options ()
941 "Get export options in subtree at point.
943 Assume point is at subtree's beginning.
945 Return options as a plist."
946 (let (prop plist)
947 (when (setq prop (progn (looking-at org-todo-line-regexp)
948 (or (save-match-data
949 (org-entry-get (point) "EXPORT_TITLE"))
950 (org-match-string-no-properties 3))))
951 (setq plist
952 (plist-put
953 plist :title
954 (org-element-parse-secondary-string
955 prop
956 (cdr (assq 'keyword org-element-string-restrictions))))))
957 (when (setq prop (org-entry-get (point) "EXPORT_TEXT"))
958 (setq plist (plist-put plist :text prop)))
959 (when (setq prop (org-entry-get (point) "EXPORT_AUTHOR"))
960 (setq plist (plist-put plist :author prop)))
961 (when (setq prop (org-entry-get (point) "EXPORT_DATE"))
962 (setq plist (plist-put plist :date prop)))
963 (when (setq prop (org-entry-get (point) "EXPORT_OPTIONS"))
964 (setq plist (org-export-add-options-to-plist plist prop)))
965 plist))
967 (defun org-export-get-inbuffer-options (buffer-string backend files)
968 "Return in-buffer options as a plist.
969 BUFFER-STRING is the string of the buffer. BACKEND is a symbol
970 specifying which back-end should be used. FILES is a list of
971 setup files names read so far, used to avoid circular
972 dependencies."
973 (let ((case-fold-search t) plist)
974 ;; 1. Special keywords, as in `org-export-special-keywords'.
975 (let ((start 0)
976 (special-re (org-make-options-regexp org-export-special-keywords)))
977 (while (string-match special-re buffer-string start)
978 (setq start (match-end 0))
979 (let ((key (upcase (org-match-string-no-properties 1 buffer-string)))
980 ;; Special keywords do not have their value expanded.
981 (val (org-match-string-no-properties 2 buffer-string)))
982 (setq plist
983 (org-combine-plists
984 (cond
985 ((string= key "SETUP_FILE")
986 (let ((file (expand-file-name
987 (org-remove-double-quotes (org-trim val)))))
988 ;; Avoid circular dependencies.
989 (unless (member file files)
990 (org-export-get-inbuffer-options
991 (org-file-contents file 'noerror)
992 backend
993 (cons file files)))))
994 ((string= key "OPTIONS")
995 (org-export-parse-option-keyword val backend))
996 ((string= key "MACRO")
997 (when (string-match
998 "^\\([-a-zA-Z0-9_]+\\)\\(?:[ \t]+\\(.*?\\)[ \t]*$\\)?"
999 val)
1000 (let ((key (intern
1001 (concat ":macro-"
1002 (downcase (match-string 1 val)))))
1003 (value (match-string 2 val)))
1004 (cond
1005 ((not value) "")
1006 ((string-match "\\`(eval\\>" value) (list key value))
1008 (list
1010 ;; If user explicitly asks for a newline, be
1011 ;; sure to preserve it from further filling
1012 ;; with `hard-newline'.
1013 (replace-regexp-in-string
1014 "\\\\n" hard-newline value))))))))
1015 plist)))))
1016 ;; 2. Standard options, as in `org-export-option-alist'.
1017 (let* ((all (append org-export-option-alist
1018 (let ((var (intern
1019 (format "org-%s-option-alist" backend))))
1020 (and (boundp var) (eval var)))))
1021 ;; Build alist between keyword name and property name.
1022 (alist (delq nil (mapcar (lambda (e)
1023 (when (nth 1 e) (cons (nth 1 e) (car e))))
1024 all)))
1025 ;; Build regexp matching all keywords associated to export
1026 ;; options. Note: the search is case insensitive.
1027 (opt-re (org-make-options-regexp
1028 (delq nil (mapcar (lambda (e) (nth 1 e)) all))))
1029 (start 0))
1030 (while (string-match opt-re buffer-string start)
1031 (setq start (match-end 0))
1032 (let* ((key (upcase (org-match-string-no-properties 1 buffer-string)))
1033 ;; Expand value, applying restrictions for keywords.
1034 (val (org-match-string-no-properties 2 buffer-string))
1035 (prop (cdr (assoc key alist)))
1036 (behaviour (nth 4 (assq prop all))))
1037 (setq plist
1038 (plist-put
1039 plist prop
1040 ;; Handle value depending on specified BEHAVIOUR.
1041 (case behaviour
1042 (space (if (plist-get plist prop)
1043 (concat (plist-get plist prop) " " (org-trim val))
1044 (org-trim val)))
1045 (newline (org-trim
1046 (concat
1047 (plist-get plist prop) "\n" (org-trim val))))
1048 (split `(,@(plist-get plist prop) ,@(org-split-string val)))
1049 ('t val)
1050 (otherwise (plist-get plist prop)))))))
1051 ;; Parse keywords specified in `org-element-parsed-keywords'.
1052 (mapc
1053 (lambda (key)
1054 (let* ((prop (cdr (assoc (upcase key) alist)))
1055 (value (and prop (plist-get plist prop))))
1056 (when (stringp value)
1057 (setq plist
1058 (plist-put
1059 plist prop
1060 (org-element-parse-secondary-string
1061 value
1062 (cdr (assq 'keyword org-element-string-restrictions))))))))
1063 org-element-parsed-keywords))
1064 ;; Return final value.
1065 plist))
1067 (defun org-export-get-global-options (backend)
1068 "Return global export options as a plist.
1069 BACKEND is a symbol specifying which back-end should be used."
1070 (let ((all (append org-export-option-alist
1071 (let ((var (intern
1072 (format "org-%s-option-alist" backend))))
1073 (and (boundp var) (eval var)))))
1074 ;; Output value.
1075 plist)
1076 (mapc (lambda (cell)
1077 (setq plist
1078 (plist-put plist (car cell) (eval (nth 3 cell)))))
1079 all)
1080 ;; Return value.
1081 plist))
1083 (defun org-export-initial-options (options)
1084 "Return a plist with non-optional properties.
1085 OPTIONS is the export options plist computed so far."
1086 (list
1087 ;; `:macro-date', `:macro-time' and `:macro-property' could as well
1088 ;; be initialized as tree properties, since they don't depend on
1089 ;; initial environment. Though, it may be more logical to keep
1090 ;; them close to other ":macro-" properties.
1091 :macro-date "(eval (format-time-string \"$1\"))"
1092 :macro-time "(eval (format-time-string \"$1\"))"
1093 :macro-property "(eval (org-entry-get nil \"$1\" 'selective))"
1094 :macro-modification-time
1095 (and (buffer-file-name)
1096 (file-exists-p (buffer-file-name))
1097 (concat "(eval (format-time-string \"$1\" '"
1098 (prin1-to-string (nth 5 (file-attributes (buffer-file-name))))
1099 "))"))
1100 :macro-input-file (and (buffer-file-name)
1101 (file-name-nondirectory (buffer-file-name)))
1102 ;; Footnotes definitions must be collected in the original buffer,
1103 ;; as there's no insurance that they will still be in the parse
1104 ;; tree, due to some narrowing.
1105 :footnote-definition-alist
1106 (let (alist)
1107 (org-with-wide-buffer
1108 (goto-char (point-min))
1109 (while (re-search-forward org-footnote-definition-re nil t)
1110 (let ((def (org-footnote-at-definition-p)))
1111 (when def
1112 (org-skip-whitespace)
1113 (push (cons (car def)
1114 (save-restriction
1115 (narrow-to-region (point) (nth 2 def))
1116 ;; Like `org-element-parse-buffer', but
1117 ;; makes sure the definition doesn't start
1118 ;; with a section element.
1119 (nconc
1120 (list 'org-data nil)
1121 (org-element-parse-elements
1122 (point-min) (point-max) nil nil nil nil nil))))
1123 alist))))
1124 alist))))
1126 (defvar org-export-allow-BIND-local nil)
1127 (defun org-export-confirm-letbind ()
1128 "Can we use #+BIND values during export?
1129 By default this will ask for confirmation by the user, to divert
1130 possible security risks."
1131 (cond
1132 ((not org-export-allow-BIND) nil)
1133 ((eq org-export-allow-BIND t) t)
1134 ((local-variable-p 'org-export-allow-BIND-local) org-export-allow-BIND-local)
1135 (t (org-set-local 'org-export-allow-BIND-local
1136 (yes-or-no-p "Allow BIND values in this buffer? ")))))
1138 (defun org-export-install-letbind-maybe ()
1139 "Install the values from #+BIND lines as local variables.
1140 Variables must be installed before in-buffer options are
1141 retrieved."
1142 (let (letbind pair)
1143 (org-with-wide-buffer
1144 (goto-char (point-min))
1145 (while (re-search-forward (org-make-options-regexp '("BIND")) nil t)
1146 (when (org-export-confirm-letbind)
1147 (push (read (concat "(" (org-match-string-no-properties 2) ")"))
1148 letbind))))
1149 (while (setq pair (pop letbind))
1150 (org-set-local (car pair) (nth 1 pair)))))
1153 ;;;; Tree Properties
1155 ;; They are initialized at the beginning of the transcoding process by
1156 ;; `org-export-collect-tree-properties'.
1158 ;; Dedicated functions focus on computing the value of specific tree
1159 ;; properties during initialization. Thus,
1160 ;; `org-export-use-select-tag-p' determines if an headline makes use
1161 ;; of an export tag enforcing inclusion. `org-export-get-min-level'
1162 ;; gets the minimal exportable level, used as a basis to compute
1163 ;; relative level for headlines. `org-export-get-point-max' returns
1164 ;; the maximum exportable ending position in the parse tree.
1165 ;; Eventually `org-export-collect-headline-numbering' builds an alist
1166 ;; between headlines' beginning position and their numbering.
1168 (defun org-export-collect-tree-properties (data info backend)
1169 "Extract tree properties from parse tree.
1171 DATA is the parse tree from which information is retrieved. INFO
1172 is a list holding export options. BACKEND is the back-end called
1173 for transcoding, as a symbol.
1175 Following tree properties are set:
1176 `:back-end' Back-end used for transcoding.
1178 `:headline-offset' Offset between true level of headlines and
1179 local level. An offset of -1 means an headline
1180 of level 2 should be considered as a level
1181 1 headline in the context.
1183 `:headline-numbering' Alist of all headlines' beginning position
1184 as key an the associated numbering as value.
1186 `:parse-tree' Whole parse tree.
1188 `:target-list' List of all targets in the parse tree.
1190 `:use-select-tags' Non-nil when parsed tree use a special tag to
1191 enforce transcoding of the headline."
1192 ;; First, set `:use-select-tags' property, as it will be required
1193 ;; for further computations.
1194 (setq info
1195 (org-combine-plists
1196 info `(:use-select-tags ,(org-export-use-select-tags-p data info))))
1197 ;; Then get `:headline-offset' in order to be able to use
1198 ;; `org-export-get-relative-level'.
1199 (setq info
1200 (org-combine-plists
1201 info `(:headline-offset ,(- 1 (org-export-get-min-level data info)))))
1202 ;; Now, get the rest of the tree properties, now `:use-select-tags'
1203 ;; is set...
1204 (nconc
1205 `(:parse-tree
1206 ,data
1207 :target-list
1208 ,(org-element-map data 'target (lambda (target local) target) info)
1209 :headline-numbering ,(org-export-collect-headline-numbering data info)
1210 :back-end ,backend)
1211 info))
1213 (defun org-export-use-select-tags-p (data options)
1214 "Non-nil when data use a tag enforcing transcoding.
1215 DATA is parsed data as returned by `org-element-parse-buffer'.
1216 OPTIONS is a plist holding export options."
1217 (org-element-map
1218 data
1219 'headline
1220 (lambda (headline info)
1221 (let ((tags (org-element-get-property :with-tags headline)))
1222 (and tags (string-match
1223 (format ":%s:" (plist-get info :select-tags)) tags))))
1224 options
1225 'stop-at-first-match))
1227 (defun org-export-get-min-level (data options)
1228 "Return minimum exportable headline's level in DATA.
1229 DATA is parsed tree as returned by `org-element-parse-buffer'.
1230 OPTIONS is a plist holding export options."
1231 (catch 'exit
1232 (let ((min-level 10000))
1233 (mapc (lambda (blob)
1234 (when (and (eq (car blob) 'headline)
1235 (not (org-export-skip-p blob options)))
1236 (setq min-level
1237 (min (org-element-get-property :level blob) min-level)))
1238 (when (= min-level 1) (throw 'exit 1)))
1239 (org-element-get-contents data))
1240 ;; If no headline was found, for the sake of consistency, set
1241 ;; minimum level to 1 nonetheless.
1242 (if (= min-level 10000) 1 min-level))))
1244 (defun org-export-collect-headline-numbering (data options)
1245 "Return numbering of all exportable headlines in a parse tree.
1247 DATA is the parse tree. OPTIONS is the plist holding export
1248 options.
1250 Return an alist whose key is an headline and value is its
1251 associated numbering \(in the shape of a list of numbers\)."
1252 (let ((numbering (make-vector org-export-max-depth 0)))
1253 (org-element-map
1254 data
1255 'headline
1256 (lambda (headline info)
1257 (let ((relative-level
1258 (1- (org-export-get-relative-level headline info))))
1259 (cons
1260 headline
1261 (loop for n across numbering
1262 for idx from 0 to org-export-max-depth
1263 when (< idx relative-level) collect n
1264 when (= idx relative-level) collect (aset numbering idx (1+ n))
1265 when (> idx relative-level) do (aset numbering idx 0)))))
1266 options)))
1270 ;;; The Transcoder
1272 ;; This function reads Org data (obtained with, i.e.
1273 ;; `org-element-parse-buffer') and transcodes it into a specified
1274 ;; back-end output. It takes care of updating local properties,
1275 ;; filtering out elements or objects according to export options and
1276 ;; organizing the output blank lines and white space are preserved.
1278 ;; Though, this function is inapropriate for secondary strings, which
1279 ;; require a fresh copy of the plist passed as INFO argument. Thus,
1280 ;; `org-export-secondary-string' is provided for that specific task.
1282 ;; Internally, three functions handle the filtering of objects and
1283 ;; elements during the export. More precisely, `org-export-skip-p'
1284 ;; determines if the considered object or element should be ignored
1285 ;; altogether, `org-export-interpret-p' tells which elements or
1286 ;; objects should be seen as real Org syntax and `org-export-expand'
1287 ;; transforms the others back into their original shape.
1289 (defun org-export-data (data backend info)
1290 "Convert DATA to a string into BACKEND format.
1292 DATA is a nested list as returned by `org-element-parse-buffer'.
1294 BACKEND is a symbol among supported exporters.
1296 INFO is a plist holding export options and also used as
1297 a communication channel between elements when walking the nested
1298 list. See `org-export-update-info' function for more
1299 details.
1301 Return transcoded string."
1302 (mapconcat
1303 ;; BLOB can be an element, an object, a string, or nil.
1304 (lambda (blob)
1305 (cond
1306 ((not blob) nil)
1307 ;; BLOB is a string. Check if the optional transcoder for plain
1308 ;; text exists, and call it in that case. Otherwise, simply
1309 ;; return string. Also update INFO and call
1310 ;; `org-export-filter-plain-text-functions'.
1311 ((stringp blob)
1312 (let ((transcoder (intern (format "org-%s-plain-text" backend))))
1313 (org-export-filter-apply-functions
1314 (plist-get info :filter-plain-text)
1315 (if (fboundp transcoder) (funcall transcoder blob info) blob)
1316 backend)))
1317 ;; BLOB is an element or an object.
1319 (let* ((type (if (stringp blob) 'plain-text (car blob)))
1320 ;; 1. Determine the appropriate TRANSCODER.
1321 (transcoder
1322 (cond
1323 ;; 1.0 A full Org document is inserted.
1324 ((eq type 'org-data) 'identity)
1325 ;; 1.1. BLOB should be ignored.
1326 ((org-export-skip-p blob info) nil)
1327 ;; 1.2. BLOB shouldn't be transcoded. Interpret it
1328 ;; back into Org syntax.
1329 ((not (org-export-interpret-p blob info))
1330 'org-export-expand)
1331 ;; 1.3. Else apply naming convention.
1332 (t (let ((trans (intern
1333 (format "org-%s-%s" backend type))))
1334 (and (fboundp trans) trans)))))
1335 ;; 2. Compute CONTENTS of BLOB.
1336 (contents
1337 (cond
1338 ;; Case 0. No transcoder defined: ignore BLOB.
1339 ((not transcoder) nil)
1340 ;; Case 1. Transparently export an Org document.
1341 ((eq type 'org-data) (org-export-data blob backend info))
1342 ;; Case 2. For a recursive object.
1343 ((memq type org-element-recursive-objects)
1344 (org-export-data
1345 blob backend
1346 (org-combine-plists
1347 info
1348 `(:genealogy ,(cons blob (plist-get info :genealogy))))))
1349 ;; Case 3. For a recursive element.
1350 ((memq type org-element-greater-elements)
1351 ;; Ignore contents of an archived tree
1352 ;; when `:with-archived-trees' is `headline'.
1353 (unless (and
1354 (eq type 'headline)
1355 (eq (plist-get info :with-archived-trees) 'headline)
1356 (org-element-get-property :archivedp blob))
1357 (org-element-normalize-string
1358 (org-export-data
1359 blob backend
1360 (org-combine-plists
1361 info `(:genealogy
1362 ,(cons blob (plist-get info :genealogy))))))))
1363 ;; Case 4. For a paragraph.
1364 ((eq type 'paragraph)
1365 (let ((paragraph
1366 (org-element-normalize-contents
1367 blob
1368 ;; When normalizing contents of an item or
1369 ;; a footnote definition, ignore first line's
1370 ;; indentation: there is none and it might be
1371 ;; misleading.
1372 (and (not (org-export-get-previous-element blob info))
1373 (let ((parent (caar (plist-get info :genealogy))))
1374 (memq parent '(footnote-definition item)))))))
1375 (org-export-data
1376 paragraph backend
1377 (org-combine-plists
1378 info `(:genealogy
1379 ,(cons paragraph (plist-get info :genealogy)))))))))
1380 ;; 3. Transcode BLOB into RESULTS string.
1381 (results (cond
1382 ((not transcoder) nil)
1383 ((eq transcoder 'org-export-expand)
1384 (org-export-data
1385 `(org-data nil ,(funcall transcoder blob contents))
1386 backend info))
1387 (t (funcall transcoder blob contents info)))))
1388 ;; 4. Discard nil results. Otherwise, update INFO, append
1389 ;; the same white space between elements or objects as in
1390 ;; the original buffer, and call appropriate filters.
1391 (when results
1392 ;; No filter for a full document.
1393 (if (eq type 'org-data) results
1394 (org-export-filter-apply-functions
1395 (plist-get info (intern (format ":filter-%s" type)))
1396 (let ((post-blank (org-element-get-property :post-blank blob)))
1397 (if (memq type org-element-all-elements)
1398 (concat (org-element-normalize-string results)
1399 (make-string post-blank ?\n))
1400 (concat results (make-string post-blank ? ))))
1401 backend)))))))
1402 (org-element-get-contents data) ""))
1404 (defun org-export-secondary-string (secondary backend info)
1405 "Convert SECONDARY string into BACKEND format.
1407 SECONDARY is a nested list as returned by
1408 `org-element-parse-secondary-string'.
1410 BACKEND is a symbol among supported exporters. INFO is a plist
1411 used as a communication channel.
1413 Return transcoded string."
1414 ;; Make SECONDARY acceptable for `org-export-data'.
1415 (let ((s (if (listp secondary) secondary (list secondary))))
1416 (org-export-data `(org-data nil ,@s) backend (copy-sequence info))))
1418 (defun org-export-skip-p (blob info)
1419 "Non-nil when element or object BLOB should be skipped during export.
1420 INFO is the plist holding export options."
1421 ;; Check headline.
1422 (unless (stringp blob)
1423 (case (car blob)
1424 ('headline
1425 (let ((with-tasks (plist-get info :with-tasks))
1426 (todo (org-element-get-property :todo-keyword blob))
1427 (todo-type (org-element-get-property :todo-type blob))
1428 (archived (plist-get info :with-archived-trees))
1429 (tag-list (let ((tags (org-element-get-property :tags blob)))
1430 (and tags (org-split-string tags ":")))))
1432 ;; Ignore subtrees with an exclude tag.
1433 (loop for k in (plist-get info :exclude-tags)
1434 thereis (member k tag-list))
1435 ;; Ignore subtrees without a select tag, when such tag is found
1436 ;; in the buffer.
1437 (and (plist-get info :use-select-tags)
1438 (loop for k in (plist-get info :select-tags)
1439 never (member k tag-list)))
1440 ;; Ignore commented sub-trees.
1441 (org-element-get-property :commentedp blob)
1442 ;; Ignore archived subtrees if `:with-archived-trees' is nil.
1443 (and (not archived) (org-element-get-property :archivedp blob))
1444 ;; Ignore tasks, if specified by `:with-tasks' property.
1445 (and todo (not with-tasks))
1446 (and todo
1447 (memq with-tasks '(todo done))
1448 (not (eq todo-type with-tasks)))
1449 (and todo
1450 (consp with-tasks)
1451 (not (member todo with-tasks))))))
1452 ;; Check time-stamp.
1453 ('time-stamp (not (plist-get info :with-timestamps)))
1454 ;; Check drawer.
1455 ('drawer
1456 (or (not (plist-get info :with-drawers))
1457 (and (consp (plist-get info :with-drawers))
1458 (not (member (org-element-get-property :drawer-name blob)
1459 (plist-get info :with-drawers))))))
1460 ;; Check export snippet.
1461 ('export-snippet
1462 (let* ((raw-back-end (org-element-get-property :back-end blob))
1463 (true-back-end
1464 (or (cdr (assoc raw-back-end org-export-snippet-translation-alist))
1465 raw-back-end)))
1466 (not (string= (symbol-name (plist-get info :back-end))
1467 true-back-end)))))))
1469 (defun org-export-interpret-p (blob info)
1470 "Non-nil if element or object BLOB should be interpreted as Org syntax.
1471 Check is done according to export options INFO, stored as
1472 a plist."
1473 (case (car blob)
1474 ;; ... entities...
1475 (entity (plist-get info :with-entities))
1476 ;; ... emphasis...
1477 (emphasis (plist-get info :with-emphasize))
1478 ;; ... fixed-width areas.
1479 (fixed-width (plist-get info :with-fixed-width))
1480 ;; ... footnotes...
1481 ((footnote-definition footnote-reference)
1482 (plist-get info :with-footnotes))
1483 ;; ... sub/superscripts...
1484 ((subscript superscript)
1485 (let ((sub/super-p (plist-get info :with-sub-superscript)))
1486 (if (eq sub/super-p '{})
1487 (org-element-get-property :use-brackets-p blob)
1488 sub/super-p)))
1489 ;; ... tables...
1490 (table (plist-get info :with-tables))
1491 (otherwise t)))
1493 (defsubst org-export-expand (blob contents)
1494 "Expand a parsed element or object to its original state.
1495 BLOB is either an element or an object. CONTENTS is its
1496 contents, as a string or nil."
1497 (funcall
1498 (intern (format "org-element-%s-interpreter" (car blob))) blob contents))
1502 ;;; The Filter System
1504 ;; Filters allow end-users to tweak easily the transcoded output.
1505 ;; They are the functional counterpart of hooks, as every filter in
1506 ;; a set is applied to the return value of the previous one.
1508 ;; Every set is back-end agnostic. Although, a filter is always
1509 ;; called, in addition to the string it applies to, with the back-end
1510 ;; used as argument, so it's easy enough for the end-user to add
1511 ;; back-end specific filters in the set.
1513 ;; Filters sets are defined below. There are of four types:
1515 ;; - `org-export-filter-parse-tree-functions' applies directly on the
1516 ;; complete parsed tree. It's the only filters set that doesn't
1517 ;; apply to a string.
1518 ;; - `org-export-filter-final-output-functions' applies to the final
1519 ;; transcoded string.
1520 ;; - `org-export-filter-plain-text-functions' applies to any string
1521 ;; not recognized as Org syntax.
1522 ;; - `org-export-filter-TYPE-functions' applies on the string returned
1523 ;; after an element or object of type TYPE has been transcoded.
1525 ;; All filters sets are applied through
1526 ;; `org-export-filter-apply-functions' function. Filters in a set are
1527 ;; applied in reverse order, that is in the order of consing. It
1528 ;; allows developers to be reasonably sure that their filters will be
1529 ;; applied first.
1531 ;;;; Special Filters
1532 (defvar org-export-filter-parse-tree-functions nil
1533 "Filter, or list of filters, applied to the parsed tree.
1534 Each filter is called with two arguments: the parse tree, as
1535 returned by `org-element-parse-buffer', and the back-end as
1536 a symbol. It must return the modified parse tree to transcode.")
1538 (defvar org-export-filter-final-output-functions nil
1539 "Filter, or list of filters, applied to the transcoded string.
1540 Each filter is called with two arguments: the full transcoded
1541 string, and the back-end as a symbol. It must return a string
1542 that will be used as the final export output.")
1544 (defvar org-export-filter-plain-text-functions nil
1545 "Filter, or list of filters, applied to plain text.
1546 Each filter is called with two arguments: a string which contains
1547 no Org syntax, and the back-end as a symbol. It must return
1548 a string or nil.")
1551 ;;;; Elements Filters
1553 (defvar org-export-filter-center-block-functions nil
1554 "List of functions applied to a transcoded center block.
1555 Each filter is called with two arguments: the transcoded center
1556 block, as a string, and the back-end, as a symbol. It must
1557 return a string or nil.")
1559 (defvar org-export-filter-drawer-functions nil
1560 "List of functions applied to a transcoded drawer.
1561 Each filter is called with two arguments: the transcoded drawer,
1562 as a string, and the back-end, as a symbol. It must return
1563 a string or nil.")
1565 (defvar org-export-filter-dynamic-block-functions nil
1566 "List of functions applied to a transcoded dynamic-block.
1567 Each filter is called with two arguments: the transcoded
1568 dynamic-block, as a string, and the back-end, as a symbol. It
1569 must return a string or nil.")
1571 (defvar org-export-filter-headline-functions nil
1572 "List of functions applied to a transcoded headline.
1573 Each filter is called with two arguments: the transcoded
1574 headline, as a string, and the back-end, as a symbol. It must
1575 return a string or nil.")
1577 (defvar org-export-filter-inlinetask-functions nil
1578 "List of functions applied to a transcoded inlinetask.
1579 Each filter is called with two arguments: the transcoded
1580 inlinetask, as a string, and the back-end, as a symbol. It must
1581 return a string or nil.")
1583 (defvar org-export-filter-plain-list-functions nil
1584 "List of functions applied to a transcoded plain-list.
1585 Each filter is called with two arguments: the transcoded
1586 plain-list, as a string, and the back-end, as a symbol. It must
1587 return a string or nil.")
1589 (defvar org-export-filter-item-functions nil
1590 "List of functions applied to a transcoded item.
1591 Each filter is called with two arguments: the transcoded item, as
1592 a string, and the back-end, as a symbol. It must return a string
1593 or nil.")
1595 (defvar org-export-filter-comment-functions nil
1596 "List of functions applied to a transcoded comment.
1597 Each filter is called with two arguments: the transcoded comment,
1598 as a string, and the back-end, as a symbol. It must return
1599 a string or nil.")
1601 (defvar org-export-filter-comment-block-functions nil
1602 "List of functions applied to a transcoded comment-comment.
1603 Each filter is called with two arguments: the transcoded
1604 comment-block, as a string, and the back-end, as a symbol. It
1605 must return a string or nil.")
1607 (defvar org-export-filter-example-block-functions nil
1608 "List of functions applied to a transcoded example-block.
1609 Each filter is called with two arguments: the transcoded
1610 example-block, as a string, and the back-end, as a symbol. It
1611 must return a string or nil.")
1613 (defvar org-export-filter-export-block-functions nil
1614 "List of functions applied to a transcoded export-block.
1615 Each filter is called with two arguments: the transcoded
1616 export-block, as a string, and the back-end, as a symbol. It
1617 must return a string or nil.")
1619 (defvar org-export-filter-fixed-width-functions nil
1620 "List of functions applied to a transcoded fixed-width.
1621 Each filter is called with two arguments: the transcoded
1622 fixed-width, as a string, and the back-end, as a symbol. It must
1623 return a string or nil.")
1625 (defvar org-export-filter-footnote-definition-functions nil
1626 "List of functions applied to a transcoded footnote-definition.
1627 Each filter is called with two arguments: the transcoded
1628 footnote-definition, as a string, and the back-end, as a symbol.
1629 It must return a string or nil.")
1631 (defvar org-export-filter-horizontal-rule-functions nil
1632 "List of functions applied to a transcoded horizontal-rule.
1633 Each filter is called with two arguments: the transcoded
1634 horizontal-rule, as a string, and the back-end, as a symbol. It
1635 must return a string or nil.")
1637 (defvar org-export-filter-keyword-functions nil
1638 "List of functions applied to a transcoded keyword.
1639 Each filter is called with two arguments: the transcoded keyword,
1640 as a string, and the back-end, as a symbol. It must return
1641 a string or nil.")
1643 (defvar org-export-filter-latex-environment-functions nil
1644 "List of functions applied to a transcoded latex-environment.
1645 Each filter is called with two arguments: the transcoded
1646 latex-environment, as a string, and the back-end, as a symbol.
1647 It must return a string or nil.")
1649 (defvar org-export-filter-babel-call-functions nil
1650 "List of functions applied to a transcoded babel-call.
1651 Each filter is called with two arguments: the transcoded
1652 babel-call, as a string, and the back-end, as a symbol. It must
1653 return a string or nil.")
1655 (defvar org-export-filter-paragraph-functions nil
1656 "List of functions applied to a transcoded paragraph.
1657 Each filter is called with two arguments: the transcoded
1658 paragraph, as a string, and the back-end, as a symbol. It must
1659 return a string or nil.")
1661 (defvar org-export-filter-property-drawer-functions nil
1662 "List of functions applied to a transcoded property-drawer.
1663 Each filter is called with two arguments: the transcoded
1664 property-drawer, as a string, and the back-end, as a symbol. It
1665 must return a string or nil.")
1667 (defvar org-export-filter-quote-block-functions nil
1668 "List of functions applied to a transcoded quote block.
1669 Each filter is called with two arguments: the transcoded quote
1670 block, as a string, and the back-end, as a symbol. It must
1671 return a string or nil.")
1673 (defvar org-export-filter-quote-section-functions nil
1674 "List of functions applied to a transcoded quote-section.
1675 Each filter is called with two arguments: the transcoded
1676 quote-section, as a string, and the back-end, as a symbol. It
1677 must return a string or nil.")
1679 (defvar org-export-filter-section-functions nil
1680 "List of functions applied to a transcoded section.
1681 Each filter is called with two arguments: the transcoded section,
1682 as a string, and the back-end, as a symbol. It must return
1683 a string or nil.")
1685 (defvar org-export-filter-special-block-functions nil
1686 "List of functions applied to a transcoded special block.
1687 Each filter is called with two arguments: the transcoded special
1688 block, as a string, and the back-end, as a symbol. It must
1689 return a string or nil.")
1691 (defvar org-export-filter-src-block-functions nil
1692 "List of functions applied to a transcoded src-block.
1693 Each filter is called with two arguments: the transcoded
1694 src-block, as a string, and the back-end, as a symbol. It must
1695 return a string or nil.")
1697 (defvar org-export-filter-table-functions nil
1698 "List of functions applied to a transcoded table.
1699 Each filter is called with two arguments: the transcoded table,
1700 as a string, and the back-end, as a symbol. It must return
1701 a string or nil.")
1703 (defvar org-export-filter-verse-block-functions nil
1704 "List of functions applied to a transcoded verse block.
1705 Each filter is called with two arguments: the transcoded verse
1706 block, as a string, and the back-end, as a symbol. It must
1707 return a string or nil.")
1710 ;;;; Objects Filters
1712 (defvar org-export-filter-emphasis-functions nil
1713 "List of functions applied to a transcoded emphasis.
1714 Each filter is called with two arguments: the transcoded
1715 emphasis, as a string, and the back-end, as a symbol. It must
1716 return a string or nil.")
1718 (defvar org-export-filter-entity-functions nil
1719 "List of functions applied to a transcoded entity.
1720 Each filter is called with two arguments: the transcoded entity,
1721 as a string, and the back-end, as a symbol. It must return
1722 a string or nil.")
1724 (defvar org-export-filter-export-snippet-functions nil
1725 "List of functions applied to a transcoded export-snippet.
1726 Each filter is called with two arguments: the transcoded
1727 export-snippet, as a string, and the back-end, as a symbol. It
1728 must return a string or nil.")
1730 (defvar org-export-filter-footnote-reference-functions nil
1731 "List of functions applied to a transcoded footnote-reference.
1732 Each filter is called with two arguments: the transcoded
1733 footnote-reference, as a string, and the back-end, as a symbol.
1734 It must return a string or nil.")
1736 (defvar org-export-filter-inline-babel-call-functions nil
1737 "List of functions applied to a transcoded inline-babel-call.
1738 Each filter is called with two arguments: the transcoded
1739 inline-babel-call, as a string, and the back-end, as a symbol. It
1740 must return a string or nil.")
1742 (defvar org-export-filter-inline-src-block-functions nil
1743 "List of functions applied to a transcoded inline-src-block.
1744 Each filter is called with two arguments: the transcoded
1745 inline-src-block, as a string, and the back-end, as a symbol. It
1746 must return a string or nil.")
1748 (defvar org-export-filter-latex-fragment-functions nil
1749 "List of functions applied to a transcoded latex-fragment.
1750 Each filter is called with two arguments: the transcoded
1751 latex-fragment, as a string, and the back-end, as a symbol. It
1752 must return a string or nil.")
1754 (defvar org-export-filter-line-break-functions nil
1755 "List of functions applied to a transcoded line-break.
1756 Each filter is called with two arguments: the transcoded
1757 line-break, as a string, and the back-end, as a symbol. It must
1758 return a string or nil.")
1760 (defvar org-export-filter-link-functions nil
1761 "List of functions applied to a transcoded link.
1762 Each filter is called with two arguments: the transcoded link, as
1763 a string, and the back-end, as a symbol. It must return a string
1764 or nil.")
1766 (defvar org-export-filter-macro-functions nil
1767 "List of functions applied to a transcoded macro.
1768 Each filter is called with two arguments: the transcoded macro,
1769 as a string, and the back-end, as a symbol. It must return
1770 a string or nil.")
1772 (defvar org-export-filter-radio-target-functions nil
1773 "List of functions applied to a transcoded radio-target.
1774 Each filter is called with two arguments: the transcoded
1775 radio-target, as a string, and the back-end, as a symbol. It
1776 must return a string or nil.")
1778 (defvar org-export-filter-statistics-cookie-functions nil
1779 "List of functions applied to a transcoded statistics-cookie.
1780 Each filter is called with two arguments: the transcoded
1781 statistics-cookie, as a string, and the back-end, as a symbol.
1782 It must return a string or nil.")
1784 (defvar org-export-filter-subscript-functions nil
1785 "List of functions applied to a transcoded subscript.
1786 Each filter is called with two arguments: the transcoded
1787 subscript, as a string, and the back-end, as a symbol. It must
1788 return a string or nil.")
1790 (defvar org-export-filter-superscript-functions nil
1791 "List of functions applied to a transcoded superscript.
1792 Each filter is called with two arguments: the transcoded
1793 superscript, as a string, and the back-end, as a symbol. It must
1794 return a string or nil.")
1796 (defvar org-export-filter-target-functions nil
1797 "List of functions applied to a transcoded target.
1798 Each filter is called with two arguments: the transcoded target,
1799 as a string, and the back-end, as a symbol. It must return
1800 a string or nil.")
1802 (defvar org-export-filter-time-stamp-functions nil
1803 "List of functions applied to a transcoded time-stamp.
1804 Each filter is called with two arguments: the transcoded
1805 time-stamp, as a string, and the back-end, as a symbol. It must
1806 return a string or nil.")
1808 (defvar org-export-filter-verbatim-functions nil
1809 "List of functions applied to a transcoded verbatim.
1810 Each filter is called with two arguments: the transcoded
1811 verbatim, as a string, and the back-end, as a symbol. It must
1812 return a string or nil.")
1814 (defun org-export-filter-apply-functions (filters value backend)
1815 "Call every function in FILTERS with arguments VALUE and BACKEND.
1816 Functions are called in a LIFO fashion, to be sure that developer
1817 specified filters, if any, are called first."
1818 ;; Ensure FILTERS is a list.
1819 (loop for filter in filters
1820 if (not value) return nil else
1821 do (setq value (funcall filter value backend)))
1822 value)
1826 ;;; Core functions
1828 ;; This is the room for the main function, `org-export-as', along with
1829 ;; its derivatives, `org-export-to-buffer' and `org-export-to-file'.
1830 ;; They differ only by the way they output the resulting code.
1832 ;; `org-export-output-file-name' is an auxiliary function meant to be
1833 ;; used with `org-export-to-file'. With a given extension, it tries
1834 ;; to provide a canonical file name to write export output to.
1836 ;; Note that `org-export-as' doesn't really parse the current buffer,
1837 ;; but a copy of it (with the same buffer-local variables and
1838 ;; visibility), where Babel blocks are executed, if appropriate.
1839 ;; `org-export-with-current-buffer-copy' macro prepares that copy.
1841 (defun org-export-as (backend
1842 &optional subtreep visible-only body-only ext-plist)
1843 "Transcode current Org buffer into BACKEND code.
1845 If narrowing is active in the current buffer, only transcode its
1846 narrowed part.
1848 If a region is active, transcode that region.
1850 When optional argument SUBTREEP is non-nil, transcode the
1851 sub-tree at point, extracting information from the headline
1852 properties first.
1854 When optional argument VISIBLE-ONLY is non-nil, don't export
1855 contents of hidden elements.
1857 When optional argument BODY-ONLY is non-nil, only return body
1858 code, without preamble nor postamble.
1860 EXT-PLIST, when provided, is a property list with external
1861 parameters overriding Org default settings, but still inferior to
1862 file-local settings.
1864 Return code as a string."
1865 (save-excursion
1866 (save-restriction
1867 ;; Narrow buffer to an appropriate region for parsing.
1868 (when (org-region-active-p)
1869 (narrow-to-region (region-beginning) (region-end))
1870 (goto-char (point-min)))
1871 (when (and subtreep (not (org-at-heading-p)))
1872 ;; Ensure point is at sub-tree's beginning.
1873 (org-with-limited-levels (org-back-to-heading (not visible-only))))
1874 ;; Retrieve export options (INFO) and parsed tree (RAW-DATA).
1875 ;; Buffer isn't parsed directly. Instead, a temporary copy is
1876 ;; created, where all code blocks are evaluated. RAW-DATA is
1877 ;; the parsed tree of the buffer resulting from that process.
1878 ;; Eventually call `org-export-filter-parse-tree-functions'.
1879 (let* ((info (org-export-collect-options backend subtreep ext-plist))
1880 (raw-data (progn
1881 (when subtreep ; Only parse subtree contents.
1882 (let ((end (save-excursion (org-end-of-subtree t))))
1883 (narrow-to-region
1884 (progn (forward-line) (point)) end)))
1885 (org-export-filter-apply-functions
1886 (plist-get info :filter-parse-tree)
1887 (org-export-with-current-buffer-copy
1888 (let ((org-current-export-file (current-buffer)))
1889 (org-export-blocks-preprocess))
1890 (org-element-parse-buffer nil visible-only))
1891 backend))))
1892 ;; Initialize the communication system and combine it to INFO.
1893 (setq info
1894 (org-combine-plists
1895 info (org-export-collect-tree-properties raw-data info backend)))
1896 ;; Now transcode RAW-DATA. Also call
1897 ;; `org-export-filter-final-output-functions'.
1898 (let* ((body (org-element-normalize-string
1899 (org-export-data raw-data backend info)))
1900 (template (intern (format "org-%s-template" backend)))
1901 (output (org-export-filter-apply-functions
1902 (plist-get info :filter-final-output)
1903 (if (or (not (fboundp template)) body-only) body
1904 (funcall template body info))
1905 backend)))
1906 ;; Maybe add final OUTPUT to kill ring before returning it.
1907 (when org-export-copy-to-kill-ring (org-kill-new output))
1908 output)))))
1910 (defun org-export-to-buffer (backend buffer &optional subtreep visible-only
1911 body-only ext-plist)
1912 "Call `org-export-as' with output to a specified buffer.
1914 BACKEND is the back-end used for transcoding, as a symbol.
1916 BUFFER is the output buffer. If it already exists, it will be
1917 erased first, otherwise, it will be created.
1919 Arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and EXT-PLIST are
1920 similar to those used in `org-export-as', which see.
1922 Return buffer."
1923 (let ((out (org-export-as backend subtreep visible-only body-only ext-plist))
1924 (buffer (get-buffer-create buffer)))
1925 (with-current-buffer buffer
1926 (erase-buffer)
1927 (insert out)
1928 (goto-char (point-min)))
1929 buffer))
1931 (defun org-export-to-file (backend file &optional subtreep visible-only
1932 body-only ext-plist)
1933 "Call `org-export-as' with output to a specified file.
1935 BACKEND is the back-end used for transcoding, as a symbol. FILE
1936 is the name of the output file, as a string.
1938 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY and
1939 EXT-PLIST are similar to those used in `org-export-as', which
1940 see.
1942 Return output file's name."
1943 ;; Checks for FILE permissions. `write-file' would do the same, but
1944 ;; we'd rather avoid needless transcoding of parse tree.
1945 (unless (file-writable-p file) (error "Output file not writable"))
1946 ;; Insert contents to a temporary buffer and write it to FILE.
1947 (let ((out (org-export-as
1948 backend subtreep visible-only body-only ext-plist)))
1949 (with-temp-buffer
1950 (insert out)
1951 (let ((coding-system-for-write org-export-coding-system))
1952 (write-file file))))
1953 ;; Return full path.
1954 file)
1956 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
1957 "Return output file's name according to buffer specifications.
1959 EXTENSION is a string representing the output file extension,
1960 with the leading dot.
1962 With a non-nil optional argument SUBTREEP, try to determine
1963 output file's name by looking for \"EXPORT_FILE_NAME\" property
1964 of subtree at point.
1966 When optional argument PUB-DIR is set, use it as the publishing
1967 directory.
1969 Return file name as a string, or nil if it couldn't be
1970 determined."
1971 (let ((base-name
1972 ;; File name may come from EXPORT_FILE_NAME subtree property,
1973 ;; assuming point is at beginning of said sub-tree.
1974 (file-name-sans-extension
1975 (or (and subtreep
1976 (org-entry-get
1977 (save-excursion
1978 (ignore-errors
1979 (org-back-to-heading (not visible-only)) (point)))
1980 "EXPORT_FILE_NAME" t))
1981 ;; File name may be extracted from buffer's associated
1982 ;; file, if any.
1983 (buffer-file-name (buffer-base-buffer))
1984 ;; Can't determine file name on our own: Ask user.
1985 (let ((read-file-name-function
1986 (and org-completion-use-ido 'ido-read-file-name)))
1987 (read-file-name
1988 "Output file: " pub-dir nil nil nil
1989 (lambda (name)
1990 (string= (file-name-extension name t) extension))))))))
1991 ;; Build file name. Enforce EXTENSION over whatever user may have
1992 ;; come up with. PUB-DIR, if defined, always has precedence over
1993 ;; any provided path.
1994 (cond
1995 (pub-dir
1996 (concat (file-name-as-directory pub-dir)
1997 (file-name-nondirectory base-name)
1998 extension))
1999 ((string= (file-name-nondirectory base-name) base-name)
2000 (concat (file-name-as-directory ".") base-name extension))
2001 (t (concat base-name extension)))))
2003 (defmacro org-export-with-current-buffer-copy (&rest body)
2004 "Apply BODY in a copy of the current buffer.
2006 The copy preserves local variables and visibility of the original
2007 buffer.
2009 Point is at buffer's beginning when BODY is applied."
2010 (org-with-gensyms (original-buffer offset buffer-string overlays)
2011 `(let ((,original-buffer ,(current-buffer))
2012 (,offset ,(1- (point-min)))
2013 (,buffer-string ,(buffer-string))
2014 (,overlays (mapcar
2015 'copy-overlay (overlays-in (point-min) (point-max)))))
2016 (with-temp-buffer
2017 (let ((buffer-invisibility-spec nil))
2018 (org-clone-local-variables
2019 ,original-buffer
2020 "^\\(org-\\|orgtbl-\\|major-mode$\\|outline-\\(regexp\\|level\\)$\\)")
2021 (insert ,buffer-string)
2022 (mapc (lambda (ov)
2023 (move-overlay
2025 (- (overlay-start ov) ,offset)
2026 (- (overlay-end ov) ,offset)
2027 (current-buffer)))
2028 ,overlays)
2029 (goto-char (point-min))
2030 (progn ,@body))))))
2031 (def-edebug-spec org-export-with-current-buffer-copy (body))
2035 ;;; Tools For Back-Ends
2037 ;; A whole set of tools is available to help build new exporters. Any
2038 ;; function general enough to have its use across many back-ends
2039 ;; should be added here.
2041 ;; As of now, functions operating on footnotes, headlines, include
2042 ;; keywords, links, macros, references, src-blocks, tables and tables
2043 ;; of contents are implemented.
2045 ;;;; For Footnotes
2047 ;; `org-export-collect-footnote-definitions' is a tool to list
2048 ;; actually used footnotes definitions in the whole parse tree, or in
2049 ;; an headline, in order to add footnote listings throughout the
2050 ;; transcoded data.
2052 ;; `org-export-footnote-first-reference-p' is a predicate used by some
2053 ;; back-ends, when they need to attach the footnote definition only to
2054 ;; the first occurrence of the corresponding label.
2056 ;; `org-export-get-footnote-definition' and
2057 ;; `org-export-get-footnote-number' provide easier access to
2058 ;; additional information relative to a footnote reference.
2060 (defun org-export-collect-footnote-definitions (data info)
2061 "Return an alist between footnote numbers, labels and definitions.
2063 DATA is the parse tree from which definitions are collected.
2064 INFO is the plist used as a communication channel.
2066 Definitions are sorted by order of references. They either
2067 appear as Org data \(transcoded with `org-export-data'\) or as
2068 a secondary string for inlined footnotes \(transcoded with
2069 `org-export-secondary-string'\). Unreferenced definitions are
2070 ignored."
2071 (let (refs)
2072 ;; Collect seen references in REFS.
2073 (org-element-map
2074 data 'footnote-reference
2075 (lambda (footnote local)
2076 (when (org-export-footnote-first-reference-p footnote local)
2077 (list (org-export-get-footnote-number footnote local)
2078 (org-element-get-property :label footnote)
2079 (org-export-get-footnote-definition footnote local))))
2080 info)))
2082 (defun org-export-footnote-first-reference-p (footnote-reference info)
2083 "Non-nil when a footnote reference is the first one for its label.
2085 FOOTNOTE-REFERENCE is the footnote reference being considered.
2086 INFO is the plist used as a communication channel."
2087 (let ((label (org-element-get-property :label footnote-reference)))
2088 (or (not label)
2089 (equal
2090 footnote-reference
2091 (org-element-map
2092 (plist-get info :parse-tree) 'footnote-reference
2093 (lambda (footnote local)
2094 (when (string= (org-element-get-property :label footnote) label)
2095 footnote))
2096 info 'first-match)))))
2098 (defun org-export-get-footnote-definition (footnote-reference info)
2099 "Return definition of FOOTNOTE-REFERENCE as parsed data.
2100 INFO is the plist used as a communication channel."
2101 (let ((label (org-element-get-property :label footnote-reference)))
2102 (or (org-element-get-property :inline-definition footnote-reference)
2103 (cdr (assoc label (plist-get info :footnote-definition-alist))))))
2105 (defun org-export-get-footnote-number (footnote info)
2106 "Return number associated to a footnote.
2108 FOOTNOTE is either a footnote reference or a footnote definition.
2109 INFO is the plist used as a communication channel."
2110 (let ((label (org-element-get-property :label footnote)) seen-refs)
2111 (org-element-map
2112 (plist-get info :parse-tree) 'footnote-reference
2113 (lambda (fn local)
2114 (let ((fn-lbl (org-element-get-property :label fn)))
2115 (cond
2116 ((and (not fn-lbl) (equal fn footnote)) (1+ (length seen-refs)))
2117 ((and label (string= label fn-lbl)) (1+ (length seen-refs)))
2118 ;; Anonymous footnote: it's always a new one. Also, be sure
2119 ;; to return nil from the `cond' so `first-match' doesn't
2120 ;; get us out of the loop.
2121 ((not fn-lbl) (push 'inline seen-refs) nil)
2122 ;; Label not seen so far: add it so SEEN-REFS. Again,
2123 ;; return nil to stay in the loop.
2124 ((not (member fn-lbl seen-refs)) (push fn-lbl seen-refs) nil))))
2125 info 'first-match)))
2128 ;;;; For Headlines
2130 ;; `org-export-get-relative-level' is a shortcut to get headline
2131 ;; level, relatively to the lower headline level in the parsed tree.
2133 ;; `org-export-get-headline-number' returns the section number of an
2134 ;; headline, while `org-export-number-to-roman' allows to convert it
2135 ;; to roman numbers.
2137 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
2138 ;; `org-export-last-sibling-p' are three useful predicates when it
2139 ;; comes to fulfill the `:headline-levels' property.
2141 (defun org-export-get-relative-level (headline info)
2142 "Return HEADLINE relative level within current parsed tree.
2143 INFO is a plist holding contextual information."
2144 (+ (org-element-get-property :level headline)
2145 (or (plist-get info :headline-offset) 0)))
2147 (defun org-export-low-level-p (headline info)
2148 "Non-nil when HEADLINE is considered as low level.
2150 INFO is a plist used as a communication channel.
2152 A low level headlines has a relative level greater than
2153 `:headline-levels' property value.
2155 Return value is the difference between HEADLINE relative level
2156 and the last level being considered as high enough, or nil."
2157 (let ((limit (plist-get info :headline-levels)))
2158 (when (wholenump limit)
2159 (let ((level (org-export-get-relative-level headline info)))
2160 (and (> level limit) (- level limit))))))
2162 (defun org-export-get-headline-number (headline info)
2163 "Return HEADLINE numbering as a list of numbers.
2164 INFO is a plist holding contextual information."
2165 (cdr (assoc headline (plist-get info :headline-numbering))))
2167 (defun org-export-number-to-roman (n)
2168 "Convert integer N into a roman numeral."
2169 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
2170 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
2171 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
2172 ( 1 . "I")))
2173 (res ""))
2174 (if (<= n 0)
2175 (number-to-string n)
2176 (while roman
2177 (if (>= n (caar roman))
2178 (setq n (- n (caar roman))
2179 res (concat res (cdar roman)))
2180 (pop roman)))
2181 res)))
2183 (defun org-export-first-sibling-p (headline info)
2184 "Non-nil when HEADLINE is the first sibling in its sub-tree.
2185 INFO is the plist used as a communication channel."
2186 (not (eq (car (org-export-get-previous-element headline info)) 'headline)))
2188 (defun org-export-last-sibling-p (headline info)
2189 "Non-nil when HEADLINE is the last sibling in its sub-tree.
2190 INFO is the plist used as a communication channel."
2191 (equal
2192 (car (last (org-element-get-contents (car (plist-get info :genealogy)))))
2193 headline))
2196 ;;;; For Include Keywords
2198 ;; This section provides a tool to properly handle insertion of files
2199 ;; during export: `org-export-included-files'. It recursively
2200 ;; transcodes a file specfied by an include keyword.
2202 ;; It uses two helper functions: `org-export-get-file-contents'
2203 ;; returns contents of a file according to parameters specified in the
2204 ;; keyword while `org-export-parse-included-file' parses the file
2205 ;; specified by it.
2207 (defun org-export-included-file (keyword backend info)
2208 "Transcode file specified with include KEYWORD.
2210 KEYWORD is the include keyword element transcoded. BACKEND is
2211 the language back-end used for transcoding. INFO is the plist
2212 used as a communication channel.
2214 This function updates `:included-files' and `:headline-offset'
2215 properties.
2217 Return the transcoded string."
2218 (let ((data (org-export-parse-included-file keyword info))
2219 (file (let ((value (org-element-get-property :value keyword)))
2220 (and (string-match "^\"\\(\\S-+\\)\"" value)
2221 (match-string 1 value)))))
2222 (org-element-normalize-string
2223 (org-export-data
2224 data backend
2225 (org-combine-plists
2226 info
2227 ;; Store full path of already included files to avoid
2228 ;; recursive file inclusion.
2229 `(:included-files
2230 ,(cons (expand-file-name file) (plist-get info :included-files))
2231 ;; Ensure that a top-level headline in the included
2232 ;; file becomes a direct child of the current headline
2233 ;; in the buffer.
2234 :headline-offset
2235 ,(- (+ (org-element-get-property
2236 :level (org-export-get-parent-headline keyword info))
2237 (plist-get info :headline-offset))
2238 (1- (org-export-get-min-level data info)))))))))
2240 (defun org-export-get-file-contents (file &optional lines)
2241 "Get the contents of FILE and return them as a string.
2242 When optional argument LINES is a string specifying a range of
2243 lines, include only those lines."
2244 (with-temp-buffer
2245 (insert-file-contents file)
2246 (when lines
2247 (let* ((lines (split-string lines "-"))
2248 (lbeg (string-to-number (car lines)))
2249 (lend (string-to-number (cadr lines)))
2250 (beg (if (zerop lbeg) (point-min)
2251 (goto-char (point-min))
2252 (forward-line (1- lbeg))
2253 (point)))
2254 (end (if (zerop lend) (point-max)
2255 (goto-char (point-min))
2256 (forward-line (1- lend))
2257 (point))))
2258 (narrow-to-region beg end)))
2259 (buffer-string)))
2261 (defun org-export-parse-included-file (keyword info)
2262 "Parse file specified by include KEYWORD.
2264 KEYWORD is the include keyword element transcoded. BACKEND is
2265 the language back-end used for transcoding. INFO is the plist
2266 used as a communication channel.
2268 Return the parsed tree."
2269 (let* ((value (org-element-get-property :value keyword))
2270 (file (and (string-match "^\"\\(\\S-+\\)\"" value)
2271 (prog1 (match-string 1 value)
2272 (setq value (replace-match "" nil nil value)))))
2273 (lines (and (string-match
2274 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\"" value)
2275 (prog1 (match-string 1 value)
2276 (setq value (replace-match "" nil nil value)))))
2277 (env (cond ((string-match "\\<example\\>" value) "example")
2278 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
2279 (match-string 1 value)))))
2280 (cond
2281 ((or (not file)
2282 (not (file-exists-p file))
2283 (not (file-readable-p file)))
2284 (format "Cannot include file %s" file))
2285 ((and (not env)
2286 (member (expand-file-name file) (plist-get info :included-files)))
2287 (error "Recursive file inclusion: %S" file))
2288 (t (let ((raw (org-element-normalize-string
2289 (org-export-get-file-contents
2290 (expand-file-name file) lines))))
2291 ;; If environment isn't specified, Insert file in
2292 ;; a temporary buffer and parse it as Org syntax.
2293 ;; Otherwise, build the element representing the file.
2294 (cond
2295 ((not env)
2296 (with-temp-buffer
2297 (insert raw) (org-mode) (org-element-parse-buffer)))
2298 ((string= "example" env)
2299 `(org-data nil (example-block (:value ,raw :post-blank 0))))
2301 `(org-data
2303 (src-block (:value ,raw :language ,env :post-blank 0))))))))))
2306 ;;;; For Links
2308 ;; `org-export-solidify-link-text' turns a string into a safer version
2309 ;; for links, replacing most non-standard characters with hyphens.
2311 ;; `org-export-get-coderef-format' returns an appropriate format
2312 ;; string for coderefs.
2314 ;; `org-export-inline-image-p' returns a non-nil value when the link
2315 ;; provided should be considered as an inline image.
2317 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
2318 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
2319 ;; returns an appropriate unique identifier when found, or nil.
2321 ;; `org-export-resolve-id-link' returns the first headline with
2322 ;; specified id or custom-id in parse tree, or nil when none was
2323 ;; found.
2325 ;; `org-export-resolve-coderef' associates a reference to a line
2326 ;; number in the element it belongs, or returns the reference itself
2327 ;; when the element isn't numbered.
2329 (defun org-export-solidify-link-text (s)
2330 "Take link text S and make a safe target out of it."
2331 (save-match-data
2332 (mapconcat 'identity (org-split-string s "[^a-zA-Z0-9_\\.-]+") "-")))
2334 (defun org-export-get-coderef-format (path desc)
2335 "Return format string for code reference link.
2336 PATH is the link path. DESC is its description."
2337 (save-match-data
2338 (cond ((string-match (regexp-quote (concat "(" path ")")) desc)
2339 (replace-match "%s" t t desc))
2340 ((string= desc "") "%s")
2341 (t desc))))
2343 (defun org-export-inline-image-p (link &optional extensions)
2344 "Non-nil if LINK object points to an inline image.
2346 When non-nil, optional argument EXTENSIONS is a list of valid
2347 extensions for image files, as strings. Otherwise, a default
2348 list is provided \(cf `org-image-file-name-regexp'\)."
2349 (and (not (org-element-get-contents link))
2350 (string= (org-element-get-property :type link) "file")
2351 (org-file-image-p
2352 (expand-file-name (org-element-get-property :path link))
2353 extensions)))
2355 (defun org-export-resolve-fuzzy-link (link info)
2356 "Return LINK destination.
2358 INFO is a plist holding contextual information.
2360 Return value can be an object, an element, or nil:
2362 - If LINK path exactly matches any target, return the target
2363 object.
2365 - If LINK path exactly matches any headline name, return that
2366 element. If more than one headline share that name, priority
2367 will be given to the one with the closest common ancestor, if
2368 any, or the first one in the parse tree otherwise.
2370 - Otherwise, return nil.
2372 Assume LINK type is \"fuzzy\"."
2373 (let ((path (org-element-get-property :path link)))
2374 ;; Link points to a target: return it.
2375 (or (loop for target in (plist-get info :target-list)
2376 when (string= (org-element-get-property :raw-value target) path)
2377 return target)
2378 ;; Link either points to an headline or nothing. Try to find
2379 ;; the source, with priority given to headlines with the closest
2380 ;; common ancestor. If such candidate is found, return its
2381 ;; beginning position as an unique identifier, otherwise return
2382 ;; nil.
2383 (let ((find-headline
2384 (function
2385 ;; Return first headline whose `:raw-value' property
2386 ;; is NAME in parse tree DATA, or nil.
2387 (lambda (name data)
2388 (org-element-map
2389 data 'headline
2390 (lambda (headline local)
2391 (when (string=
2392 (org-element-get-property :raw-value headline)
2393 name)
2394 headline))
2395 info 'first-match)))))
2396 ;; Search among headlines sharing an ancestor with link,
2397 ;; from closest to farthest.
2398 (or (catch 'exit
2399 (mapc
2400 (lambda (parent)
2401 (when (eq (car parent) 'headline)
2402 (let ((foundp (funcall find-headline path parent)))
2403 (when foundp (throw 'exit foundp)))))
2404 (plist-get info :genealogy)) nil)
2405 ;; No match with a common ancestor: try the full parse-tree.
2406 (funcall find-headline path (plist-get info :parse-tree)))))))
2408 (defun org-export-resolve-id-link (link info)
2409 "Return headline referenced as LINK destination.
2411 INFO is a plist used as a communication channel.
2413 Return value can be an headline element or nil. Assume LINK type
2414 is either \"id\" or \"custom-id\"."
2415 (let ((id (org-element-get-property :path link)))
2416 (org-element-map
2417 (plist-get info :parse-tree) 'headline
2418 (lambda (headline local)
2419 (when (or (string= (org-element-get-property :id headline) id)
2420 (string= (org-element-get-property :custom-id headline) id))
2421 headline))
2422 info 'first-match)))
2424 (defun org-export-resolve-coderef (ref info)
2425 "Resolve a code reference REF.
2427 INFO is a plist used as a communication channel.
2429 Return associated line number in source code, or REF itself,
2430 depending on src-block or example element's switches."
2431 (org-element-map
2432 (plist-get info :parse-tree) '(src-block example)
2433 (lambda (el local)
2434 (let ((switches (or (org-element-get-property :switches el) "")))
2435 (with-temp-buffer
2436 (insert (org-trim (org-element-get-property :value el)))
2437 ;; Build reference regexp.
2438 (let* ((label
2439 (or (and (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
2440 (match-string 1 switches))
2441 org-coderef-label-format))
2442 (ref-re
2443 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
2444 (replace-regexp-in-string "%s" ref label nil t))))
2445 ;; Element containing REF is found. Only associate REF to
2446 ;; a line number if element has "+n" or "-n" and "-k" or
2447 ;; "-r" as switches. When it has "+n", count accumulated
2448 ;; locs before, too.
2449 (when (re-search-backward ref-re nil t)
2450 (cond
2451 ((not (string-match "-[kr]\\>" switches)) ref)
2452 ((string-match "-n\\>" switches) (line-number-at-pos))
2453 ((string-match "\\+n\\>" switches)
2454 (+ (org-export-get-loc el local) (line-number-at-pos)))
2455 (t ref)))))))
2456 info 'first-match))
2459 ;;;; For Macros
2461 ;; `org-export-expand-macro' simply takes care of expanding macros.
2463 (defun org-export-expand-macro (macro info)
2464 "Expand MACRO and return it as a string.
2465 INFO is a plist holding export options."
2466 (let* ((key (org-element-get-property :key macro))
2467 (args (org-element-get-property :args macro))
2468 (value (plist-get info (intern (format ":macro-%s" key)))))
2469 ;; Replace arguments in VALUE.
2470 (let ((s 0) n)
2471 (while (string-match "\\$\\([0-9]+\\)" value s)
2472 (setq s (1+ (match-beginning 0))
2473 n (string-to-number (match-string 1 value)))
2474 (and (>= (length args) n)
2475 (setq value (replace-match (nth (1- n) args) t t value)))))
2476 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
2477 (when (string-match "\\`(eval\\>" value)
2478 (setq value (eval (read value))))
2479 ;; Return expanded string.
2480 (format "%s" value)))
2483 ;;;; For References
2485 ;; `org-export-get-ordinal' associates a sequence number to any object
2486 ;; or element.
2488 (defun org-export-get-ordinal
2489 (element info &optional types within-section predicate)
2490 "Return ordinal number of an element or object.
2492 ELEMENT is the element or object considered. INFO is the plist
2493 used as a communication channel.
2495 Optional argument TYPES, when non-nil, is a list of element or
2496 object types, as symbols, that should also be counted in.
2497 Otherwise, only provided element's type is considered.
2499 When optional argument WITHIN-SECTION is non-nil, narrow counting
2500 to the section containing ELEMENT.
2502 Optional argument PREDICATE is a function returning a non-nil
2503 value if the current element or object should be counted in. It
2504 accepts one argument: the element or object being considered.
2505 This argument allows to count only a certain type of objects,
2506 like inline images, which are a subset of links \(in that case,
2507 `org-export-inline-image-p' might be an useful predicate\)."
2508 (let ((counter 0)
2509 ;; Determine if search should apply to current section, in
2510 ;; which case it should be retrieved first, or to full parse
2511 ;; tree. As a special case, an element or object without
2512 ;; a parent headline will also trigger a full search,
2513 ;; notwithstanding WITHIN-SECTION value.
2514 (data
2515 (if (not within-section) (plist-get info :parse-tree)
2516 (or (org-export-get-parent-headline element info)
2517 (plist-get info :parse-tree)))))
2518 ;; Increment counter until ELEMENT is found again.
2519 (org-element-map
2520 data (or types (car element))
2521 (lambda (el local)
2522 (cond
2523 ((equal element el) (1+ counter))
2524 ((not predicate) (incf counter) nil)
2525 ((funcall predicate el) (incf counter) nil)))
2526 info 'first-match)))
2529 ;;;; For Src-Blocks
2531 ;; `org-export-get-loc' counts number of code lines accumulated in
2532 ;; src-block or example-block elements with a "+n" switch until
2533 ;; a given element, excluded. Note: "-n" switches reset that count.
2535 ;; `org-export-handle-code' takes care of line numbering and reference
2536 ;; cleaning in source code, when appropriate.
2538 (defun org-export-get-loc (element info)
2539 "Return accumulated lines of code up to ELEMENT.
2541 INFO is the plist used as a communication channel.
2543 ELEMENT is excluded from count."
2544 (let ((loc 0))
2545 (org-element-map
2546 (plist-get info :parse-tree) `(src-block example-block ,(car element))
2547 (lambda (el local)
2548 (cond
2549 ;; ELEMENT is reached: Quit the loop.
2550 ((equal el element) t)
2551 ;; Only count lines from src-block and example-block elements
2552 ;; with a "+n" or "-n" switch. A "-n" switch resets counter.
2553 ((not (memq (car el) '(src-block example-block))) nil)
2554 ((let ((switches (org-element-get-property :switches el)))
2555 (when (and switches (string-match "\\([-+]\\)n\\>" switches))
2556 ;; Accumulate locs or reset them.
2557 (let ((accumulatep (string= (match-string 1 switches) "-"))
2558 (lines (org-count-lines
2559 (org-trim (org-element-get-property :value el)))))
2560 (setq loc (if accumulatep lines (+ loc lines))))))
2561 ;; Return nil to stay in the loop.
2562 nil)))
2563 info 'first-match)
2564 ;; Return value.
2565 loc))
2567 (defun org-export-handle-code (element info &optional num-fmt ref-fmt delayed)
2568 "Handle line numbers and code references in ELEMENT.
2570 ELEMENT has either a `src-block' an `example-block' type. INFO
2571 is a plist used as a communication channel.
2573 If optional argument NUM-FMT is a string, it will be used as
2574 a format string for numbers at beginning of each line.
2576 If optional argument REF-FMT is a string, it will be used as
2577 a format string for each line of code containing a reference.
2579 When optional argument DELAYED is non-nil, `org-loc' and
2580 `org-coderef' properties, set to an adequate value, are applied
2581 to, respectively, numbered lines and lines with a reference. No
2582 line numbering is done and all references are stripped from the
2583 resulting string. Both NUM-FMT and REF-FMT arguments are ignored
2584 in that situation.
2586 Return new code as a string."
2587 (let* ((switches (or (org-element-get-property :switches element) ""))
2588 (code (org-element-get-property :value element))
2589 (numberp (string-match "[-+]n\\>" switches))
2590 (accumulatep (string-match "\\+n\\>" switches))
2591 ;; Initialize loc counter when any kind of numbering is
2592 ;; active.
2593 (total-LOC (cond
2594 (accumulatep (org-export-get-loc element info))
2595 (numberp 0)))
2596 ;; Get code and clean it. Remove blank lines at its
2597 ;; beginning and end. Also remove protective commas.
2598 (preserve-indent-p (or org-src-preserve-indentation
2599 (string-match "-i\\>" switches)))
2600 (replace-labels (when (string-match "-r\\>" switches)
2601 (if (string-match "-k\\>" switches) 'keep t)))
2602 (code (let ((c (replace-regexp-in-string
2603 "\\`\\([ \t]*\n\\)+" ""
2604 (replace-regexp-in-string
2605 "\\(:?[ \t]*\n\\)*[ \t]*\\'" "\n" code))))
2606 ;; If appropriate, remove global indentation.
2607 (unless preserve-indent-p (setq c (org-remove-indentation c)))
2608 ;; Free up the protected lines. Note: Org blocks
2609 ;; have commas at the beginning or every line.
2610 (if (string=
2611 (or (org-element-get-property :language element) "")
2612 "org")
2613 (replace-regexp-in-string "^," "" c)
2614 (replace-regexp-in-string
2615 "^\\(,\\)\\(:?\\*\\|[ \t]*#\\+\\)" "" c nil nil 1))))
2616 ;; Split code to process it line by line.
2617 (code-lines (org-split-string code "\n"))
2618 ;; If numbering is active, ensure line numbers will be
2619 ;; correctly padded before applying the format string.
2620 (num-fmt
2621 (when (and (not delayed) numberp)
2622 (format (if (stringp num-fmt) num-fmt "%s: ")
2623 (format "%%%ds"
2624 (length (number-to-string
2625 (+ (length code-lines) total-LOC)))))))
2626 ;; Get format used for references.
2627 (label-fmt (or (and (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
2628 (match-string 1 switches))
2629 org-coderef-label-format))
2630 ;; Build a regexp matching a loc with a reference.
2631 (with-ref-re (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
2632 (replace-regexp-in-string
2633 "%s" "\\([-a-zA-Z0-9_ ]+\\)" label-fmt nil t))))
2634 (org-element-normalize-string
2635 (mapconcat
2636 (lambda (loc)
2637 ;; Maybe add line number to current line of code (LOC).
2638 (when numberp
2639 (incf total-LOC)
2640 (setq loc (if delayed (org-add-props loc nil 'org-loc total-LOC)
2641 (concat (format num-fmt total-LOC) loc))))
2642 ;; Take action if at a ref line.
2643 (when (string-match with-ref-re loc)
2644 (let ((ref (match-string 3 loc)))
2645 (setq loc
2646 ;; Option "-r" without "-k" removes labels.
2647 ;; A non-nil DELAYED removes labels unconditionally.
2648 (if (or delayed
2649 (and replace-labels (not (eq replace-labels 'keep))))
2650 (replace-match "" nil nil loc 1)
2651 (replace-match (format "(%s)" ref) nil nil loc 2)))
2652 ;; Store REF in `org-coderef' property if DELAYED asks to.
2653 (cond (delayed (setq loc (org-add-props loc nil 'org-coderef ref)))
2654 ;; If REF-FMT is defined, apply it to current LOC.
2655 ((stringp ref-fmt) (setq loc (format ref-fmt loc))))))
2656 ;; Return updated LOC for concatenation.
2657 loc)
2658 code-lines "\n"))))
2661 ;;;; For Tables
2663 ;; `org-export-table-format-info' extracts formatting information
2664 ;; (alignment, column groups and presence of a special column) from
2665 ;; a raw table and returns it as a property list.
2667 ;; `org-export-clean-table' cleans the raw table from any Org
2668 ;; table-specific syntax.
2670 (defun org-export-table-format-info (table)
2671 "Extract info from TABLE.
2672 Return a plist whose properties and values are:
2673 `:alignment' vector of strings among \"r\", \"l\" and \"c\",
2674 `:column-groups' vector of symbols among `start', `end', `start-end',
2675 `:row-groups' list of integers representing row groups.
2676 `:special-column-p' non-nil if table has a special column.
2677 `:width' vector of integers representing desired width of
2678 current column, or nil."
2679 (with-temp-buffer
2680 (insert table)
2681 (goto-char 1)
2682 (org-table-align)
2683 (let ((align (vconcat (mapcar (lambda (c) (if c "r" "l"))
2684 org-table-last-alignment)))
2685 (width (make-vector (length org-table-last-alignment) nil))
2686 (colgroups (make-vector (length org-table-last-alignment) nil))
2687 (row-group 0)
2688 (rowgroups)
2689 (special-column-p 'empty))
2690 (mapc (lambda (row)
2691 (if (string-match "^[ \t]*|[-+]+|[ \t]*$" row)
2692 (incf row-group)
2693 ;; Determine if a special column is present by looking
2694 ;; for special markers in the first column. More
2695 ;; accurately, the first column is considered special
2696 ;; if it only contains special markers and, maybe,
2697 ;; empty cells.
2698 (setq special-column-p
2699 (cond
2700 ((not special-column-p) nil)
2701 ((string-match "^[ \t]*| *\\\\?\\([/#!$*_^]\\) *|" row)
2702 'special)
2703 ((string-match "^[ \t]*| +|" row) special-column-p))))
2704 (cond
2705 ;; Read forced alignment and width information, if any,
2706 ;; and determine final alignment for the table.
2707 ((org-table-cookie-line-p row)
2708 (let ((col 0))
2709 (mapc (lambda (field)
2710 (when (string-match
2711 "<\\([lrc]\\)?\\([0-9]+\\)?>" field)
2712 (let ((align-data (match-string 1 field)))
2713 (when align-data (aset align col align-data)))
2714 (let ((w-data (match-string 2 field)))
2715 (when w-data
2716 (aset width col (string-to-number w-data)))))
2717 (incf col))
2718 (org-split-string row "[ \t]*|[ \t]*"))))
2719 ;; Read column groups information.
2720 ((org-table-colgroup-line-p row)
2721 (let ((col 0))
2722 (mapc (lambda (field)
2723 (aset colgroups col
2724 (cond ((string= "<" field) 'start)
2725 ((string= ">" field) 'end)
2726 ((string= "<>" field) 'start-end)))
2727 (incf col))
2728 (org-split-string row "[ \t]*|[ \t]*"))))
2729 ;; Contents line.
2730 (t (push row-group rowgroups))))
2731 (org-split-string table "\n"))
2732 ;; Return plist.
2733 (list :alignment align
2734 :column-groups colgroups
2735 :row-groups (reverse rowgroups)
2736 :special-column-p (eq special-column-p 'special)
2737 :width width))))
2739 (defun org-export-clean-table (table specialp)
2740 "Clean string TABLE from its formatting elements.
2741 Remove any row containing column groups or formatting cookies and
2742 rows starting with a special marker. If SPECIALP is non-nil,
2743 assume the table contains a special formatting column and remove
2744 it also."
2745 (let ((rows (org-split-string table "\n")))
2746 (mapconcat 'identity
2747 (delq nil
2748 (mapcar
2749 (lambda (row)
2750 (cond
2751 ((org-table-colgroup-line-p row) nil)
2752 ((org-table-cookie-line-p row) nil)
2753 ;; Ignore rows starting with a special marker.
2754 ((string-match "^[ \t]*| *[!_^/] *|" row) nil)
2755 ;; Remove special column.
2756 ((and specialp
2757 (or (string-match "^\\([ \t]*\\)|-+\\+" row)
2758 (string-match "^\\([ \t]*\\)|[^|]*|" row)))
2759 (replace-match "\\1|" t nil row))
2760 (t row)))
2761 rows))
2762 "\n")))
2765 ;;;; For Tables Of Contents
2767 ;; `org-export-collect-headlines' builds a list of all exportable
2768 ;; headline elements, maybe limited to a certain depth. One can then
2769 ;; easily parse it and transcode it.
2771 ;; Building lists of tables, figures or listings is quite similar.
2772 ;; Once the generic function `org-export-collect-elements' is defined,
2773 ;; `org-export-collect-tables', `org-export-collect-figures' and
2774 ;; `org-export-collect-listings' can be derived from it.
2776 (defun org-export-collect-headlines (info &optional n)
2777 "Collect headlines in order to build a table of contents.
2779 INFO is a plist used as a communication channel.
2781 When non-nil, optional argument N must be an integer. It
2782 specifies the depth of the table of contents.
2784 Return a list of all exportable headlines as parsed elements."
2785 (org-element-map
2786 (plist-get info :parse-tree)
2787 'headline
2788 (lambda (headline local)
2789 ;; Strip contents from HEADLINE.
2790 (let ((relative-level (org-export-get-relative-level headline local)))
2791 (unless (and n (> relative-level n)) headline)))
2792 info))
2794 (defun org-export-collect-elements (type info &optional predicate)
2795 "Collect referenceable elements of a determined type.
2797 TYPE can be a symbol or a list of symbols specifying element
2798 types to search. Only elements with a caption or a name are
2799 collected.
2801 INFO is a plist used as a communication channel.
2803 When non-nil, optional argument PREDICATE is a function accepting
2804 one argument, an element of type TYPE. It returns a non-nil
2805 value when that element should be collected.
2807 Return a list of all elements found, in order of appearance."
2808 (org-element-map
2809 (plist-get info :parse-tree) type
2810 (lambda (element local)
2811 (and (or (org-element-get-property :caption element)
2812 (org-element-get-property :name element))
2813 (or (not predicate) (funcall predicate element))
2814 element)) info))
2816 (defun org-export-collect-tables (info)
2817 "Build a list of tables.
2819 INFO is a plist used as a communication channel.
2821 Return a list of table elements with a caption or a name
2822 affiliated keyword."
2823 (org-export-collect-elements 'table info))
2825 (defun org-export-collect-figures (info predicate)
2826 "Build a list of figures.
2828 INFO is a plist used as a communication channel. PREDICATE is
2829 a function which accepts one argument: a paragraph element and
2830 whose return value is non-nil when that element should be
2831 collected.
2833 A figure is a paragraph type element, with a caption or a name,
2834 verifying PREDICATE. The latter has to be provided since
2835 a \"figure\" is a vague concept that may depend on back-end.
2837 Return a list of elements recognized as figures."
2838 (org-export-collect-elements 'paragraph info predicate))
2840 (defun org-export-collect-listings (info)
2841 "Build a list of src blocks.
2843 INFO is a plist used as a communication channel.
2845 Return a list of src-block elements with a caption or a name
2846 affiliated keyword."
2847 (org-export-collect-elements 'src-block info))
2850 ;;;; Topology
2852 (defun org-export-get-parent-headline (blob info)
2853 "Return BLOB's closest parent headline or nil.
2854 INFO is a plist used as a communication channel."
2855 (catch 'exit
2856 (mapc
2857 (lambda (el) (when (eq (car el) 'headline) (throw 'exit el)))
2858 (plist-get info :genealogy))
2859 nil))
2861 (defun org-export-get-previous-element (blob info)
2862 "Return previous element or object.
2864 BLOB is an element or object. INFO is a plist used as
2865 a communication channel.
2867 Return previous element or object, a string, or nil."
2868 (let ((parent (car (plist-get info :genealogy))))
2869 (cadr (member blob (reverse (org-element-get-contents parent))))))
2871 (defun org-export-get-next-element (blob info)
2872 "Return next element or object.
2874 BLOB is an element or object. INFO is a plist used as
2875 a communication channel.
2877 Return next element or object, a string, or nil."
2878 (let ((parent (car (plist-get info :genealogy))))
2879 (cadr (member blob (org-element-get-contents parent)))))
2883 ;;; The Dispatcher
2885 ;; `org-export-dispatch' is the standard interactive way to start an
2886 ;; export process. It uses `org-export-dispatch-ui' as a subroutine
2887 ;; for its interface. Most commons back-ends should have an entry in
2888 ;; it.
2890 (defun org-export-dispatch ()
2891 "Export dispatcher for Org mode.
2893 It provides an access to common export related tasks in a buffer.
2894 Its interface comes in two flavours: standard and expert. While
2895 both share the same set of bindings, only the former displays the
2896 valid keys associations. Set `org-export-dispatch-use-expert-ui'
2897 to switch to one or the other.
2899 Return an error if key pressed has no associated command."
2900 (interactive)
2901 (let* ((input (org-export-dispatch-ui
2902 (if (listp org-export-initial-scope) org-export-initial-scope
2903 (list org-export-initial-scope))
2904 org-export-dispatch-use-expert-ui))
2905 (raw-key (car input))
2906 (scope (cdr input)))
2907 ;; Translate "C-a", "C-b"... into "a", "b"... Then take action
2908 ;; depending on user's key pressed.
2909 (case (if (< raw-key 27) (+ raw-key 96) raw-key)
2910 ;; Export with `e-ascii' back-end.
2911 ((?A ?N ?U)
2912 (let ((outbuf
2913 (org-export-to-buffer
2914 'e-ascii "*Org E-ASCII Export*"
2915 (memq 'subtree scope) (memq 'visible scope) (memq 'body scope)
2916 `(:ascii-charset
2917 ,(case raw-key (?A 'ascii) (?N 'latin1) (t 'utf-8))))))
2918 (with-current-buffer outbuf (text-mode))
2919 (when org-export-show-temporary-export-buffer
2920 (switch-to-buffer-other-window outbuf))))
2921 ((?a ?n ?u)
2922 (org-e-ascii-export-to-ascii
2923 (memq 'subtree scope) (memq 'visible scope) (memq 'body scope)
2924 `(:ascii-charset ,(case raw-key (?a 'ascii) (?n 'latin1) (t 'utf-8)))))
2925 ;; Export with `e-latex' back-end.
2927 (let ((outbuf
2928 (org-export-to-buffer
2929 'e-latex "*Org E-LaTeX Export*"
2930 (memq 'subtree scope) (memq 'visible scope) (memq 'body scope))))
2931 (with-current-buffer outbuf (latex-mode))
2932 (when org-export-show-temporary-export-buffer
2933 (switch-to-buffer-other-window outbuf))))
2934 (?l (org-e-latex-export-to-latex
2935 (memq 'subtree scope) (memq 'visible scope) (memq 'body scope)))
2936 (?p (org-e-latex-export-to-pdf
2937 (memq 'subtree scope) (memq 'visible scope) (memq 'body scope)))
2938 (?d (org-open-file
2939 (org-e-latex-export-to-pdf
2940 (memq 'subtree scope) (memq 'visible scope) (memq 'body scope))))
2941 ;; Undefined command.
2942 (t (error "No command associated with key %s"
2943 (char-to-string raw-key))))))
2945 (defun org-export-dispatch-ui (scope expertp)
2946 "Handle interface for `org-export-dispatch'.
2948 SCOPE is a list containing current interactive options set for
2949 export. It can contain any of the following symbols:
2950 `body' toggles a body-only export
2951 `subtree' restricts export to current subtree
2952 `visible' restricts export to visible part of buffer.
2954 EXPERTP, when non-nil, triggers expert UI. In that case, no help
2955 buffer is provided, but indications about currently active
2956 options are given in the prompt. Moreover, \[?] allows to switch
2957 back to standard interface.
2959 Return value is a list with key pressed as car and a list of
2960 final interactive export options as cdr."
2961 (let ((help (format "------------------- General Options --------------------
2962 \[1] Body only: %s
2963 \[2] Export scope: %s
2964 \[3] Visible only: %s
2966 -------------- ASCII/Latin-1/UTF-8 Export --------------
2967 \[a/n/u] to TXT file [A/N/U] to temporary buffer
2969 --------------------- LaTeX Export ---------------------
2970 \[l] to TEX file [L] to temporary buffer
2971 \[p] to PDF file [d] ... and open it"
2972 (if (memq 'body scope) "On" "Off")
2973 (if (memq 'subtree scope) "Subtree" "Buffer")
2974 (if (memq 'visible scope) "On" "Off")))
2975 (standard-prompt "Export command: ")
2976 (expert-prompt (format "Export command (%s%s%s): "
2977 (if (memq 'body scope) "b" "-")
2978 (if (memq 'subtree scope) "s" "-")
2979 (if (memq 'visible scope) "v" "-")))
2980 (handle-keypress
2981 (function
2982 ;; Read a character from command input, toggling interactive
2983 ;; options when applicable. PROMPT is the displayed prompt,
2984 ;; as a string.
2985 (lambda (prompt)
2986 (let ((key (read-char-exclusive prompt)))
2987 (cond
2988 ;; Ignore non-standard characters (i.e. "M-a").
2989 ((not (characterp key)) (org-export-dispatch-ui scope expertp))
2990 ;; Switch back to standard interface.
2991 ((and (eq key ??) expertp) (org-export-dispatch-ui scope nil))
2992 ((eq key ?1)
2993 (org-export-dispatch-ui
2994 (if (memq 'body scope) (remq 'body scope) (cons 'body scope))
2995 expertp))
2996 ((eq key ?2)
2997 (org-export-dispatch-ui
2998 (if (memq 'subtree scope) (remq 'subtree scope)
2999 (cons 'subtree scope))
3000 expertp))
3001 ((eq key ?3)
3002 (org-export-dispatch-ui
3003 (if (memq 'visible scope) (remq 'visible scope)
3004 (cons 'visible scope))
3005 expertp))
3006 (t (cons key scope))))))))
3007 ;; With expert UI, just read key with a fancy prompt. In standard
3008 ;; UI, display an intrusive help buffer.
3009 (if expertp (funcall handle-keypress expert-prompt)
3010 (save-window-excursion
3011 (delete-other-windows)
3012 (with-output-to-temp-buffer "*Org Export/Publishing Help*" (princ help))
3013 (org-fit-window-to-buffer
3014 (get-buffer-window "*Org Export/Publishing Help*"))
3015 (funcall handle-keypress standard-prompt)))))
3018 (provide 'org-export)
3019 ;;; org-export.el ends here