org-export: Small cosmetic changes to export UI
[org-mode/org-mode-NeilSmithlineMods.git] / contrib / lisp / org-export.el
blob104f348cdbf906c13b256d02ac9ead7ff46a383e
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 about initial environment
32 ;; or contextual data, all in a single place. The exhaustive list
33 ;; of 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 and publishing tools
96 (require 'org-e-ascii "../../EXPERIMENTAL/org-e-ascii.el")
97 (require 'org-e-html "../../EXPERIMENTAL/org-e-html.el")
98 (require 'org-e-latex "../../EXPERIMENTAL/org-e-latex.el")
99 (require 'org-e-publish "../../EXPERIMENTAL/org-e-publish.el")
102 ;;; Internal Variables
104 ;; Among internal variables, the most important is
105 ;; `org-export-option-alist'. This variable define the global export
106 ;; options, shared between every exporter, and how they are acquired.
108 (defconst org-export-max-depth 19
109 "Maximum nesting depth for headlines, counting from 0.")
111 (defconst org-export-option-alist
112 '((:author "AUTHOR" nil user-full-name t)
113 (:creator "CREATOR" nil org-export-creator-string)
114 (:date "DATE" nil nil t)
115 (:description "DESCRIPTION" nil nil newline)
116 (:email "EMAIL" nil user-mail-address t)
117 (:exclude-tags "EXPORT_EXCLUDE_TAGS" nil org-export-exclude-tags split)
118 (:headline-levels nil "H" org-export-headline-levels)
119 (:keywords "KEYWORDS" nil nil space)
120 (:language "LANGUAGE" nil org-export-default-language t)
121 (:preserve-breaks nil "\\n" org-export-preserve-breaks)
122 (:section-numbers nil "num" org-export-with-section-numbers)
123 (:select-tags "EXPORT_SELECT_TAGS" nil org-export-select-tags split)
124 (:time-stamp-file nil "timestamp" org-export-time-stamp-file)
125 (:title "TITLE" nil nil space)
126 (:with-archived-trees nil "arch" org-export-with-archived-trees)
127 (:with-author nil "author" org-export-with-author)
128 (:with-creator nil "creator" org-export-with-creator)
129 (:with-drawers nil "d" org-export-with-drawers)
130 (:with-email nil "email" org-export-with-email)
131 (:with-emphasize nil "*" org-export-with-emphasize)
132 (:with-entities nil "e" org-export-with-entities)
133 (:with-fixed-width nil ":" org-export-with-fixed-width)
134 (:with-footnotes nil "f" org-export-with-footnotes)
135 (:with-priority nil "pri" org-export-with-priority)
136 (:with-special-strings nil "-" org-export-with-special-strings)
137 (:with-sub-superscript nil "^" org-export-with-sub-superscripts)
138 (:with-toc nil "toc" org-export-with-toc)
139 (:with-tables nil "|" org-export-with-tables)
140 (:with-tags nil "tags" org-export-with-tags)
141 (:with-tasks nil "tasks" org-export-with-tasks)
142 (:with-timestamps nil "<" org-export-with-timestamps)
143 (:with-todo-keywords nil "todo" org-export-with-todo-keywords))
144 "Alist between export properties and ways to set them.
146 The car of the alist is the property name, and the cdr is a list
147 like \(KEYWORD OPTION DEFAULT BEHAVIOUR\) where:
149 KEYWORD is a string representing a buffer keyword, or nil.
150 OPTION is a string that could be found in an #+OPTIONS: line.
151 DEFAULT is the default value for the property.
152 BEHAVIOUR determine how Org should handle multiple keywords for
153 the same property. It is a symbol among:
154 nil Keep old value and discard the new one.
155 t Replace old value with the new one.
156 `space' Concatenate the values, separating them with a space.
157 `newline' Concatenate the values, separating them with
158 a newline.
159 `split' Split values at white spaces, and cons them to the
160 previous list.
162 KEYWORD and OPTION have precedence over DEFAULT.
164 All these properties should be back-end agnostic. For back-end
165 specific properties, define a similar variable named
166 `org-BACKEND-option-alist', replacing BACKEND with the name of
167 the appropriate back-end. You can also redefine properties
168 there, as they have precedence over these.")
170 (defconst org-export-special-keywords
171 '("SETUP_FILE" "OPTIONS" "MACRO")
172 "List of in-buffer keywords that require special treatment.
173 These keywords are not directly associated to a property. The
174 way they are handled must be hard-coded into
175 `org-export-get-inbuffer-options' function.")
177 (defconst org-export-filters-alist
178 '((:filter-babel-call . org-export-filter-babel-call-functions)
179 (:filter-center-block . org-export-filter-center-block-functions)
180 (:filter-comment . org-export-filter-comment-functions)
181 (:filter-comment-block . org-export-filter-comment-block-functions)
182 (:filter-drawer . org-export-filter-drawer-functions)
183 (:filter-dynamic-block . org-export-filter-dynamic-block-functions)
184 (:filter-emphasis . org-export-filter-emphasis-functions)
185 (:filter-entity . org-export-filter-entity-functions)
186 (:filter-example-block . org-export-filter-example-block-functions)
187 (:filter-export-block . org-export-filter-export-block-functions)
188 (:filter-export-snippet . org-export-filter-export-snippet-functions)
189 (:filter-final-output . org-export-filter-final-output-functions)
190 (:filter-fixed-width . org-export-filter-fixed-width-functions)
191 (:filter-footnote-definition . org-export-filter-footnote-definition-functions)
192 (:filter-footnote-reference . org-export-filter-footnote-reference-functions)
193 (:filter-headline . org-export-filter-headline-functions)
194 (:filter-horizontal-rule . org-export-filter-horizontal-rule-functions)
195 (:filter-inline-babel-call . org-export-filter-inline-babel-call-functions)
196 (:filter-inline-src-block . org-export-filter-inline-src-block-functions)
197 (:filter-inlinetask . org-export-filter-inlinetask-functions)
198 (:filter-item . org-export-filter-item-functions)
199 (:filter-keyword . org-export-filter-keyword-functions)
200 (:filter-latex-environment . org-export-filter-latex-environment-functions)
201 (:filter-latex-fragment . org-export-filter-latex-fragment-functions)
202 (:filter-line-break . org-export-filter-line-break-functions)
203 (:filter-link . org-export-filter-link-functions)
204 (:filter-macro . org-export-filter-macro-functions)
205 (:filter-paragraph . org-export-filter-paragraph-functions)
206 (:filter-parse-tree . org-export-filter-parse-tree-functions)
207 (:filter-plain-list . org-export-filter-plain-list-functions)
208 (:filter-plain-text . org-export-filter-plain-text-functions)
209 (:filter-property-drawer . org-export-filter-property-drawer-functions)
210 (:filter-quote-block . org-export-filter-quote-block-functions)
211 (:filter-quote-section . org-export-filter-quote-section-functions)
212 (:filter-radio-target . org-export-filter-radio-target-functions)
213 (:filter-section . org-export-filter-section-functions)
214 (:filter-special-block . org-export-filter-special-block-functions)
215 (:filter-src-block . org-export-filter-src-block-functions)
216 (:filter-statistics-cookie . org-export-filter-statistics-cookie-functions)
217 (:filter-subscript . org-export-filter-subscript-functions)
218 (:filter-superscript . org-export-filter-superscript-functions)
219 (:filter-table . org-export-filter-table-functions)
220 (:filter-target . org-export-filter-target-functions)
221 (:filter-time-stamp . org-export-filter-time-stamp-functions)
222 (:filter-verbatim . org-export-filter-verbatim-functions)
223 (:filter-verse-block . org-export-filter-verse-block-functions))
224 "Alist between filters properties and initial values.
226 The key of each association is a property name accessible through
227 the communication channel its value is a configurable global
228 variable defining initial filters.
230 This list is meant to install user specified filters. Back-end
231 developers may install their own filters using
232 `org-BACKEND-filters-alist', where BACKEND is the name of the
233 considered back-end. Filters defined there will always be
234 prepended to the current list, so they always get applied
235 first.")
237 (defconst org-export-default-inline-image-rule
238 `(("file" .
239 ,(format "\\.%s\\'"
240 (regexp-opt
241 '("png" "jpeg" "jpg" "gif" "tiff" "tif" "xbm"
242 "xpm" "pbm" "pgm" "ppm") t))))
243 "Default rule for link matching an inline image.
244 This rule applies to links with no description. By default, it
245 will be considered as an inline image if it targets a local file
246 whose extension is either \"png\", \"jpeg\", \"jpg\", \"gif\",
247 \"tiff\", \"tif\", \"xbm\", \"xpm\", \"pbm\", \"pgm\" or \"ppm\".
248 See `org-export-inline-image-p' for more information about
249 rules.")
253 ;;; User-configurable Variables
255 ;; Configuration for the masses.
257 ;; They should never be evaled directly, as their value is to be
258 ;; stored in a property list (cf. `org-export-option-alist').
260 (defgroup org-export nil
261 "Options for exporting Org mode files."
262 :tag "Org Export"
263 :group 'org)
265 (defgroup org-export-general nil
266 "General options for export engine."
267 :tag "Org Export General"
268 :group 'org-export)
270 (defcustom org-export-with-archived-trees 'headline
271 "Whether sub-trees with the ARCHIVE tag should be exported.
273 This can have three different values:
274 nil Do not export, pretend this tree is not present.
275 t Do export the entire tree.
276 `headline' Only export the headline, but skip the tree below it.
278 This option can also be set with the #+OPTIONS line,
279 e.g. \"arch:nil\"."
280 :group 'org-export-general
281 :type '(choice
282 (const :tag "Not at all" nil)
283 (const :tag "Headline only" 'headline)
284 (const :tag "Entirely" t)))
286 (defcustom org-export-with-author t
287 "Non-nil means insert author name into the exported file.
288 This option can also be set with the #+OPTIONS line,
289 e.g. \"author:nil\"."
290 :group 'org-export-general
291 :type 'boolean)
293 (defcustom org-export-with-creator 'comment
294 "Non-nil means the postamble should contain a creator sentence.
296 The sentence can be set in `org-export-creator-string' and
297 defaults to \"Generated by Org mode XX in Emacs XXX.\".
299 If the value is `comment' insert it as a comment."
300 :group 'org-export-general
301 :type '(choice
302 (const :tag "No creator sentence" nil)
303 (const :tag "Sentence as a comment" 'comment)
304 (const :tag "Insert the sentence" t)))
306 (defcustom org-export-creator-string
307 (format "Generated by Org mode %s in Emacs %s." org-version emacs-version)
308 "String to insert at the end of the generated document."
309 :group 'org-export-general
310 :type '(string :tag "Creator string"))
312 (defcustom org-export-with-drawers t
313 "Non-nil means export contents of standard drawers.
315 When t, all drawers are exported. This may also be a list of
316 drawer names to export. This variable doesn't apply to
317 properties drawers.
319 This option can also be set with the #+OPTIONS line,
320 e.g. \"d:nil\"."
321 :group 'org-export-general
322 :type '(choice
323 (const :tag "All drawers" t)
324 (const :tag "None" nil)
325 (repeat :tag "Selected drawers"
326 (string :tag "Drawer name"))))
328 (defcustom org-export-with-email nil
329 "Non-nil means insert author email into the exported file.
330 This option can also be set with the #+OPTIONS line,
331 e.g. \"email:t\"."
332 :group 'org-export-general
333 :type 'boolean)
335 (defcustom org-export-with-emphasize t
336 "Non-nil means interpret *word*, /word/, and _word_ as emphasized text.
338 If the export target supports emphasizing text, the word will be
339 typeset in bold, italic, or underlined, respectively. Not all
340 export backends support this.
342 This option can also be set with the #+OPTIONS line, e.g. \"*:nil\"."
343 :group 'org-export-general
344 :type 'boolean)
346 (defcustom org-export-exclude-tags '("noexport")
347 "Tags that exclude a tree from export.
348 All trees carrying any of these tags will be excluded from
349 export. This is without condition, so even subtrees inside that
350 carry one of the `org-export-select-tags' will be removed."
351 :group 'org-export-general
352 :type '(repeat (string :tag "Tag")))
354 (defcustom org-export-with-fixed-width t
355 "Non-nil means lines starting with \":\" will be in fixed width font.
357 This can be used to have pre-formatted text, fragments of code
358 etc. For example:
359 : ;; Some Lisp examples
360 : (while (defc cnt)
361 : (ding))
362 will be looking just like this in also HTML. See also the QUOTE
363 keyword. Not all export backends support this.
365 This option can also be set with the #+OPTIONS line, e.g. \"::nil\"."
366 :group 'org-export-translation
367 :type 'boolean)
369 (defcustom org-export-with-footnotes t
370 "Non-nil means Org footnotes should be exported.
371 This option can also be set with the #+OPTIONS line,
372 e.g. \"f:nil\"."
373 :group 'org-export-general
374 :type 'boolean)
376 (defcustom org-export-headline-levels 3
377 "The last level which is still exported as a headline.
379 Inferior levels will produce itemize lists when exported. Note
380 that a numeric prefix argument to an exporter function overrides
381 this setting.
383 This option can also be set with the #+OPTIONS line, e.g. \"H:2\"."
384 :group 'org-export-general
385 :type 'integer)
387 (defcustom org-export-default-language "en"
388 "The default language for export and clocktable translations, as a string.
389 This may have an association in
390 `org-clock-clocktable-language-setup'."
391 :group 'org-export-general
392 :type '(string :tag "Language"))
394 (defcustom org-export-preserve-breaks nil
395 "Non-nil means preserve all line breaks when exporting.
397 Normally, in HTML output paragraphs will be reformatted.
399 This option can also be set with the #+OPTIONS line,
400 e.g. \"\\n:t\"."
401 :group 'org-export-general
402 :type 'boolean)
404 (defcustom org-export-with-entities t
405 "Non-nil means interpret entities when exporting.
407 For example, HTML export converts \\alpha to &alpha; and \\AA to
408 &Aring;.
410 For a list of supported names, see the constant `org-entities'
411 and the user option `org-entities-user'.
413 This option can also be set with the #+OPTIONS line,
414 e.g. \"e:nil\"."
415 :group 'org-export-general
416 :type 'boolean)
418 (defcustom org-export-with-priority nil
419 "Non-nil means include priority cookies in export.
420 When nil, remove priority cookies for export."
421 :group 'org-export-general
422 :type 'boolean)
424 (defcustom org-export-with-section-numbers t
425 "Non-nil means add section numbers to headlines when exporting.
427 When set to an integer n, numbering will only happen for
428 headlines whose relative level is higher or equal to n.
430 This option can also be set with the #+OPTIONS line,
431 e.g. \"num:t\"."
432 :group 'org-export-general
433 :type 'boolean)
435 (defcustom org-export-select-tags '("export")
436 "Tags that select a tree for export.
437 If any such tag is found in a buffer, all trees that do not carry
438 one of these tags will be deleted before export. Inside trees
439 that are selected like this, you can still deselect a subtree by
440 tagging it with one of the `org-export-exclude-tags'."
441 :group 'org-export-general
442 :type '(repeat (string :tag "Tag")))
444 (defcustom org-export-with-special-strings t
445 "Non-nil means interpret \"\-\", \"--\" and \"---\" for export.
447 When this option is turned on, these strings will be exported as:
449 Org HTML LaTeX
450 -----+----------+--------
451 \\- &shy; \\-
452 -- &ndash; --
453 --- &mdash; ---
454 ... &hellip; \ldots
456 This option can also be set with the #+OPTIONS line,
457 e.g. \"-:nil\"."
458 :group 'org-export-general
459 :type 'boolean)
461 (defcustom org-export-with-sub-superscripts t
462 "Non-nil means interpret \"_\" and \"^\" for export.
464 When this option is turned on, you can use TeX-like syntax for
465 sub- and superscripts. Several characters after \"_\" or \"^\"
466 will be considered as a single item - so grouping with {} is
467 normally not needed. For example, the following things will be
468 parsed as single sub- or superscripts.
470 10^24 or 10^tau several digits will be considered 1 item.
471 10^-12 or 10^-tau a leading sign with digits or a word
472 x^2-y^3 will be read as x^2 - y^3, because items are
473 terminated by almost any nonword/nondigit char.
474 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
476 Still, ambiguity is possible - so when in doubt use {} to enclose
477 the sub/superscript. If you set this variable to the symbol
478 `{}', the braces are *required* in order to trigger
479 interpretations as sub/superscript. This can be helpful in
480 documents that need \"_\" frequently in plain text.
482 This option can also be set with the #+OPTIONS line,
483 e.g. \"^:nil\"."
484 :group 'org-export-general
485 :type '(choice
486 (const :tag "Interpret them" t)
487 (const :tag "Curly brackets only" {})
488 (const :tag "Do not interpret them" nil)))
490 (defcustom org-export-with-toc t
491 "Non-nil means create a table of contents in exported files.
493 The TOC contains headlines with levels up
494 to`org-export-headline-levels'. When an integer, include levels
495 up to N in the toc, this may then be different from
496 `org-export-headline-levels', but it will not be allowed to be
497 larger than the number of headline levels. When nil, no table of
498 contents is made.
500 This option can also be set with the #+OPTIONS line,
501 e.g. \"toc:nil\" or \"toc:3\"."
502 :group 'org-export-general
503 :type '(choice
504 (const :tag "No Table of Contents" nil)
505 (const :tag "Full Table of Contents" t)
506 (integer :tag "TOC to level")))
508 (defcustom org-export-with-tables t
509 "If non-nil, lines starting with \"|\" define a table.
510 For example:
512 | Name | Address | Birthday |
513 |-------------+----------+-----------|
514 | Arthur Dent | England | 29.2.2100 |
516 This option can also be set with the #+OPTIONS line, e.g. \"|:nil\"."
517 :group 'org-export-general
518 :type 'boolean)
520 (defcustom org-export-with-tags t
521 "If nil, do not export tags, just remove them from headlines.
523 If this is the symbol `not-in-toc', tags will be removed from
524 table of contents entries, but still be shown in the headlines of
525 the document.
527 This option can also be set with the #+OPTIONS line,
528 e.g. \"tags:nil\"."
529 :group 'org-export-general
530 :type '(choice
531 (const :tag "Off" nil)
532 (const :tag "Not in TOC" not-in-toc)
533 (const :tag "On" t)))
535 (defcustom org-export-with-tasks t
536 "Non-nil means include TODO items for export.
537 This may have the following values:
538 t include tasks independent of state.
539 todo include only tasks that are not yet done.
540 done include only tasks that are already done.
541 nil remove all tasks before export
542 list of keywords keep only tasks with these keywords"
543 :group 'org-export-general
544 :type '(choice
545 (const :tag "All tasks" t)
546 (const :tag "No tasks" nil)
547 (const :tag "Not-done tasks" todo)
548 (const :tag "Only done tasks" done)
549 (repeat :tag "Specific TODO keywords"
550 (string :tag "Keyword"))))
552 (defcustom org-export-time-stamp-file t
553 "Non-nil means insert a time stamp into the exported file.
554 The time stamp shows when the file was created.
556 This option can also be set with the #+OPTIONS line,
557 e.g. \"timestamp:nil\"."
558 :group 'org-export-general
559 :type 'boolean)
561 (defcustom org-export-with-timestamps t
562 "If nil, do not export time stamps and associated keywords."
563 :group 'org-export-general
564 :type 'boolean)
566 (defcustom org-export-with-todo-keywords t
567 "Non-nil means include TODO keywords in export.
568 When nil, remove all these keywords from the export.")
570 (defcustom org-export-allow-BIND 'confirm
571 "Non-nil means allow #+BIND to define local variable values for export.
572 This is a potential security risk, which is why the user must
573 confirm the use of these lines."
574 :group 'org-export-general
575 :type '(choice
576 (const :tag "Never" nil)
577 (const :tag "Always" t)
578 (const :tag "Ask a confirmation for each file" confirm)))
580 (defcustom org-export-snippet-translation-alist nil
581 "Alist between export snippets back-ends and exporter back-ends.
583 This variable allows to provide shortcuts for export snippets.
585 For example, with a value of '\(\(\"h\" . \"html\"\)\), the HTML
586 back-end will recognize the contents of \"@h{<b>}\" as HTML code
587 while every other back-end will ignore it."
588 :group 'org-export-general
589 :type '(repeat
590 (cons
591 (string :tag "Shortcut")
592 (string :tag "Back-end"))))
594 (defcustom org-export-coding-system nil
595 "Coding system for the exported file."
596 :group 'org-export-general
597 :type 'coding-system)
599 (defcustom org-export-copy-to-kill-ring t
600 "Non-nil means exported stuff will also be pushed onto the kill ring."
601 :group 'org-export-general
602 :type 'boolean)
604 (defcustom org-export-initial-scope 'buffer
605 "The initial scope when exporting with `org-export-dispatch'.
606 This variable can be either set to `buffer' or `subtree'."
607 :group 'org-export-general
608 :type '(choice
609 (const :tag "Export current buffer" 'buffer)
610 (const :tag "Export current subtree" 'subtree)))
612 (defcustom org-export-show-temporary-export-buffer t
613 "Non-nil means show buffer after exporting to temp buffer.
614 When Org exports to a file, the buffer visiting that file is ever
615 shown, but remains buried. However, when exporting to a temporary
616 buffer, that buffer is popped up in a second window. When this variable
617 is nil, the buffer remains buried also in these cases."
618 :group 'org-export-general
619 :type 'boolean)
621 (defcustom org-export-dispatch-use-expert-ui nil
622 "Non-nil means using a non-intrusive `org-export-dispatch'.
623 In that case, no help buffer is displayed. Though, an indicator
624 for current export scope is added to the prompt \(i.e. \"b\" when
625 output is restricted to body only, \"s\" when it is restricted to
626 the current subtree and \"v\" when only visible elements are
627 considered for export\). Also, \[?] allows to switch back to
628 standard mode."
629 :group 'org-export-general
630 :type 'boolean)
634 ;;; The Communication Channel
636 ;; During export process, every function has access to a number of
637 ;; properties. They are of three types:
639 ;; 1. Environment options are collected once at the very beginning of
640 ;; the process, out of the original buffer and configuration.
641 ;; Associated to the parse tree, they make an Org closure.
642 ;; Collecting them is handled by `org-export-get-environment'
643 ;; function.
645 ;; Most environment options are defined through the
646 ;; `org-export-option-alist' variable.
648 ;; 2. Tree properties are extracted directly from the parsed tree,
649 ;; just before export, by `org-export-collect-tree-properties'.
651 ;; 3. Local options are updated during parsing, and their value
652 ;; depends on the level of recursion. For now, only `:genealogy'
653 ;; belongs to that category.
655 ;; Here is the full list of properties available during transcode
656 ;; process, with their category (option, tree or local) and their
657 ;; value type.
659 ;; + `:author' :: Author's name.
660 ;; - category :: option
661 ;; - type :: string
663 ;; + `:back-end' :: Current back-end used for transcoding.
664 ;; - category :: tree
665 ;; - type :: symbol
667 ;; + `:creator' :: String to write as creation information.
668 ;; - category :: option
669 ;; - type :: string
671 ;; + `:date' :: String to use as date.
672 ;; - category :: option
673 ;; - type :: string
675 ;; + `:description' :: Description text for the current data.
676 ;; - category :: option
677 ;; - type :: string
679 ;; + `:email' :: Author's email.
680 ;; - category :: option
681 ;; - type :: string
683 ;; + `:exclude-tags' :: Tags for exclusion of subtrees from export
684 ;; process.
685 ;; - category :: option
686 ;; - type :: list of strings
688 ;; + `:footnote-definition-alist' :: Alist between footnote labels and
689 ;; their definition, as parsed data. Only non-inlined footnotes
690 ;; are represented in this alist. Also, every definition isn't
691 ;; guaranteed to be referenced in the parse tree. The purpose of
692 ;; this property is to preserve definitions from oblivion
693 ;; (i.e. when the parse tree comes from a part of the original
694 ;; buffer), it isn't meant for direct use in a back-end. To
695 ;; retrieve a definition relative to a reference, use
696 ;; `org-export-get-footnote-definition' instead.
697 ;; - category :: option
698 ;; - type :: alist (STRING . LIST)
700 ;; + `:genealogy' :: Flat list of current object or element's parents
701 ;; from closest to farthest.
702 ;; - category :: local
703 ;; - type :: list of elements and objects
705 ;; + `:headline-levels' :: Maximum level being exported as an
706 ;; headline. Comparison is done with the relative level of
707 ;; headlines in the parse tree, not necessarily with their
708 ;; actual level.
709 ;; - category :: option
710 ;; - type :: integer
712 ;; + `:headline-offset' :: Difference between relative and real level
713 ;; of headlines in the parse tree. For example, a value of -1
714 ;; means a level 2 headline should be considered as level
715 ;; 1 (cf. `org-export-get-relative-level').
716 ;; - category :: tree
717 ;; - type :: integer
719 ;; + `:headline-numbering' :: Alist between headlines' beginning
720 ;; position and their numbering, as a list of numbers
721 ;; (cf. `org-export-get-headline-number').
722 ;; - category :: tree
723 ;; - type :: alist (INTEGER . LIST)
725 ;; + `:input-file' :: Full path to input file, if any.
726 ;; - category :: option
727 ;; - type :: string or nil
729 ;; + `:keywords' :: List of keywords attached to data.
730 ;; - category :: option
731 ;; - type :: string
733 ;; + `:language' :: Default language used for translations.
734 ;; - category :: option
735 ;; - type :: string
737 ;; + `:macro-input-file' :: Macro returning file name of input file,
738 ;; or nil.
739 ;; - category :: option
740 ;; - type :: string or nil
742 ;; + `:parse-tree' :: Whole parse tree, available at any time during
743 ;; transcoding.
744 ;; - category :: global
745 ;; - type :: list (as returned by `org-element-parse-buffer')
747 ;; + `:preserve-breaks' :: Non-nil means transcoding should preserve
748 ;; all line breaks.
749 ;; - category :: option
750 ;; - type :: symbol (nil, t)
752 ;; + `:section-numbers' :: Non-nil means transcoding should add
753 ;; section numbers to headlines.
754 ;; - category :: option
755 ;; - type :: symbol (nil, t)
757 ;; + `:select-tags' :: List of tags enforcing inclusion of sub-trees
758 ;; in transcoding. When such a tag is present,
759 ;; subtrees without it are de facto excluded from
760 ;; the process. See `use-select-tags'.
761 ;; - category :: option
762 ;; - type :: list of strings
764 ;; + `:target-list' :: List of targets encountered in the parse tree.
765 ;; This is used to partly resolve "fuzzy" links
766 ;; (cf. `org-export-resolve-fuzzy-link').
767 ;; - category :: tree
768 ;; - type :: list of strings
770 ;; + `:time-stamp-file' :: Non-nil means transcoding should insert
771 ;; a time stamp in the output.
772 ;; - category :: option
773 ;; - type :: symbol (nil, t)
775 ;; + `:use-select-tags' :: When non-nil, a select tags has been found
776 ;; in the parse tree. Thus, any headline without one will be
777 ;; filtered out. See `select-tags'.
778 ;; - category :: tree
779 ;; - type :: interger or nil
781 ;; + `:with-archived-trees' :: Non-nil when archived subtrees should
782 ;; also be transcoded. If it is set to the `headline' symbol,
783 ;; only the archived headline's name is retained.
784 ;; - category :: option
785 ;; - type :: symbol (nil, t, `headline')
787 ;; + `:with-author' :: Non-nil means author's name should be included
788 ;; in the output.
789 ;; - category :: option
790 ;; - type :: symbol (nil, t)
792 ;; + `:with-creator' :: Non-nild means a creation sentence should be
793 ;; inserted at the end of the transcoded string. If the value
794 ;; is `comment', it should be commented.
795 ;; - category :: option
796 ;; - type :: symbol (`comment', nil, t)
798 ;; + `:with-drawers' :: Non-nil means drawers should be exported. If
799 ;; its value is a list of names, only drawers with such names
800 ;; will be transcoded.
801 ;; - category :: option
802 ;; - type :: symbol (nil, t) or list of strings
804 ;; + `:with-email' :: Non-nil means output should contain author's
805 ;; email.
806 ;; - category :: option
807 ;; - type :: symbol (nil, t)
809 ;; + `:with-emphasize' :: Non-nil means emphasized text should be
810 ;; interpreted.
811 ;; - category :: option
812 ;; - type :: symbol (nil, t)
814 ;; + `:with-fixed-width' :: Non-nil if transcoder should interpret
815 ;; strings starting with a colon as a fixed-with (verbatim) area.
816 ;; - category :: option
817 ;; - type :: symbol (nil, t)
819 ;; + `:with-footnotes' :: Non-nil if transcoder should interpret
820 ;; footnotes.
821 ;; - category :: option
822 ;; - type :: symbol (nil, t)
824 ;; + `:with-priority' :: Non-nil means transcoding should include
825 ;; priority cookies.
826 ;; - category :: option
827 ;; - type :: symbol (nil, t)
829 ;; + `:with-special-strings' :: Non-nil means transcoding should
830 ;; interpret special strings in plain text.
831 ;; - category :: option
832 ;; - type :: symbol (nil, t)
834 ;; + `:with-sub-superscript' :: Non-nil means transcoding should
835 ;; interpret subscript and superscript. With a value of "{}",
836 ;; only interpret those using curly brackets.
837 ;; - category :: option
838 ;; - type :: symbol (nil, {}, t)
840 ;; + `:with-tables' :: Non-nil means transcoding should interpret
841 ;; tables.
842 ;; - category :: option
843 ;; - type :: symbol (nil, t)
845 ;; + `:with-tags' :: Non-nil means transcoding should keep tags in
846 ;; headlines. A `not-in-toc' value will remove them
847 ;; from the table of contents, if any, nonetheless.
848 ;; - category :: option
849 ;; - type :: symbol (nil, t, `not-in-toc')
851 ;; + `:with-tasks' :: Non-nil means transcoding should include
852 ;; headlines with a TODO keyword. A `todo' value
853 ;; will only include headlines with a todo type
854 ;; keyword while a `done' value will do the
855 ;; contrary. If a list of strings is provided, only
856 ;; tasks with keywords belonging to that list will
857 ;; be kept.
858 ;; - category :: option
859 ;; - type :: symbol (t, todo, done, nil) or list of strings
861 ;; + `:with-timestamps' :: Non-nil means transcoding should include
862 ;; time stamps and associated keywords. Otherwise, completely
863 ;; remove them.
864 ;; - category :: option
865 ;; - type :: symbol: (t, nil)
867 ;; + `:with-toc' :: Non-nil means that a table of contents has to be
868 ;; added to the output. An integer value limits its
869 ;; depth.
870 ;; - category :: option
871 ;; - type :: symbol (nil, t or integer)
873 ;; + `:with-todo-keywords' :: Non-nil means transcoding should
874 ;; include TODO keywords.
875 ;; - category :: option
876 ;; - type :: symbol (nil, t)
879 ;;;; Environment Options
881 ;; Environment options encompass all parameters defined outside the
882 ;; scope of the parsed data. They come from five sources, in
883 ;; increasing precedence order:
885 ;; - Global variables,
886 ;; - Options keyword symbols,
887 ;; - Buffer keywords,
888 ;; - Subtree properties.
890 ;; The central internal function with regards to environment options
891 ;; is `org-export-get-environment'. It updates global variables with
892 ;; "#+BIND:" keywords, then retrieve and prioritize properties from
893 ;; the different sources.
895 ;; The internal functions doing the retrieval are:
896 ;; `org-export-parse-option-keyword' ,
897 ;; `org-export-get-subtree-options' ,
898 ;; `org-export-get-inbuffer-options' and
899 ;; `org-export-get-global-options'.
901 ;; Some properties, which do not rely on the previous sources but
902 ;; still depend on the original buffer, are taken care of with
903 ;; `org-export-initial-options'.
905 ;; Also, `org-export-confirm-letbind' and `org-export-install-letbind'
906 ;; take care of the part relative to "#+BIND:" keywords.
908 (defun org-export-get-environment (&optional backend subtreep ext-plist)
909 "Collect export options from the current buffer.
911 Optional argument BACKEND is a symbol specifying which back-end
912 specific options to read, if any.
914 When optional argument SUBTREEP is non-nil, assume the export is
915 done against the current sub-tree.
917 Third optional argument EXT-PLIST is a property list with
918 external parameters overriding Org default settings, but still
919 inferior to file-local settings."
920 ;; First install #+BIND variables.
921 (org-export-install-letbind-maybe)
922 ;; Get and prioritize export options...
923 (let ((options (org-combine-plists
924 ;; ... from global variables...
925 (org-export-get-global-options backend)
926 ;; ... from buffer's name (default title)...
927 `(:title
928 ,(or (let ((file (buffer-file-name (buffer-base-buffer))))
929 (and file
930 (file-name-sans-extension
931 (file-name-nondirectory file))))
932 (buffer-name (buffer-base-buffer))))
933 ;; ... from an external property list...
934 ext-plist
935 ;; ... from in-buffer settings...
936 (org-export-get-inbuffer-options
937 backend
938 (and buffer-file-name
939 (org-remove-double-quotes buffer-file-name)))
940 ;; ... and from subtree, when appropriate.
941 (and subtreep (org-export-get-subtree-options)))))
942 ;; Add initial options.
943 (setq options (append (org-export-initial-options) options))
944 ;; Return plist.
945 options))
947 (defun org-export-parse-option-keyword (options &optional backend)
948 "Parse an OPTIONS line and return values as a plist.
949 Optional argument BACKEND is a symbol specifying which back-end
950 specific items to read, if any."
951 (let* ((all
952 (append org-export-option-alist
953 (and backend
954 (let ((var (intern
955 (format "org-%s-option-alist" backend))))
956 (and (boundp var) (eval var))))))
957 ;; Build an alist between #+OPTION: item and property-name.
958 (alist (delq nil
959 (mapcar (lambda (e)
960 (when (nth 2 e) (cons (regexp-quote (nth 2 e))
961 (car e))))
962 all)))
963 plist)
964 (mapc (lambda (e)
965 (when (string-match (concat "\\(\\`\\|[ \t]\\)"
966 (car e)
967 ":\\(([^)\n]+)\\|[^ \t\n\r;,.]*\\)")
968 options)
969 (setq plist (plist-put plist
970 (cdr e)
971 (car (read-from-string
972 (match-string 2 options)))))))
973 alist)
974 plist))
976 (defun org-export-get-subtree-options ()
977 "Get export options in subtree at point.
979 Assume point is at subtree's beginning.
981 Return options as a plist."
982 (let (prop plist)
983 (when (setq prop (progn (looking-at org-todo-line-regexp)
984 (or (save-match-data
985 (org-entry-get (point) "EXPORT_TITLE"))
986 (org-match-string-no-properties 3))))
987 (setq plist
988 (plist-put
989 plist :title
990 (org-element-parse-secondary-string
991 prop
992 (cdr (assq 'keyword org-element-string-restrictions))))))
993 (when (setq prop (org-entry-get (point) "EXPORT_TEXT"))
994 (setq plist (plist-put plist :text prop)))
995 (when (setq prop (org-entry-get (point) "EXPORT_AUTHOR"))
996 (setq plist (plist-put plist :author prop)))
997 (when (setq prop (org-entry-get (point) "EXPORT_DATE"))
998 (setq plist (plist-put plist :date prop)))
999 (when (setq prop (org-entry-get (point) "EXPORT_OPTIONS"))
1000 (setq plist (org-export-add-options-to-plist plist prop)))
1001 plist))
1003 (defun org-export-get-inbuffer-options (&optional backend files)
1004 "Return current buffer export options, as a plist.
1006 Optional argument BACKEND, when non-nil, is a symbol specifying
1007 which back-end specific options should also be read in the
1008 process.
1010 Optional argument FILES is a list of setup files names read so
1011 far, used to avoid circular dependencies.
1013 Assume buffer is in Org mode. Narrowing, if any, is ignored."
1014 (org-with-wide-buffer
1015 (goto-char (point-min))
1016 (let ((case-fold-search t) plist)
1017 ;; 1. Special keywords, as in `org-export-special-keywords'.
1018 (let ((special-re (org-make-options-regexp org-export-special-keywords)))
1019 (while (re-search-forward special-re nil t)
1020 (let ((element (org-element-at-point)))
1021 (when (eq (car element) 'keyword)
1022 (let* ((key (upcase (org-element-get-property :key element)))
1023 (val (org-element-get-property :value element))
1024 (prop
1025 (cond
1026 ((string= key "SETUP_FILE")
1027 (let ((file
1028 (expand-file-name
1029 (org-remove-double-quotes (org-trim val)))))
1030 ;; Avoid circular dependencies.
1031 (unless (member file files)
1032 (with-temp-buffer
1033 (insert (org-file-contents file 'noerror))
1034 (org-mode)
1035 (org-export-get-inbuffer-options
1036 backend (cons file files))))))
1037 ((string= key "OPTIONS")
1038 (org-export-parse-option-keyword val backend))
1039 ((string= key "MACRO")
1040 (when (string-match
1041 "^\\([-a-zA-Z0-9_]+\\)\\(?:[ \t]+\\(.*?\\)[ \t]*$\\)?"
1042 val)
1043 (let ((key
1044 (intern
1045 (concat ":macro-"
1046 (downcase (match-string 1 val)))))
1047 (value (org-match-string-no-properties 2 val)))
1048 (cond
1049 ((not value) "")
1050 ;; Value will be evaled. Leave it as-is.
1051 ((string-match "\\`(eval\\>" value)
1052 (list key value))
1053 ;; Value has to be parsed for nested
1054 ;; macros.
1056 (list
1058 (let ((restr
1059 (cdr
1060 (assq 'macro
1061 org-element-object-restrictions))))
1062 (org-element-parse-secondary-string
1063 ;; If user explicitly asks for
1064 ;; a newline, be sure to preserve it
1065 ;; from further filling with
1066 ;; `hard-newline'. Also replace
1067 ;; "\\n" with "\n", "\\\n" with "\\n"
1068 ;; and so on...
1069 (replace-regexp-in-string
1070 "\\(\\\\\\\\\\)n" "\\\\"
1071 (replace-regexp-in-string
1072 "\\(?:^\\|[^\\\\]\\)\\(\\\\n\\)"
1073 hard-newline value nil nil 1)
1074 nil nil 1)
1075 restr)))))))))))
1076 (setq plist (org-combine-plists plist prop)))))))
1077 ;; 2. Standard options, as in `org-export-option-alist'.
1078 (let* ((all (append org-export-option-alist
1079 ;; Also look for back-end specific options
1080 ;; if BACKEND is defined.
1081 (and backend
1082 (let ((var
1083 (intern
1084 (format "org-%s-option-alist" backend))))
1085 (and (boundp var) (eval var))))))
1086 ;; Build alist between keyword name and property name.
1087 (alist
1088 (delq nil (mapcar
1089 (lambda (e) (when (nth 1 e) (cons (nth 1 e) (car e))))
1090 all)))
1091 ;; Build regexp matching all keywords associated to export
1092 ;; options. Note: the search is case insensitive.
1093 (opt-re (org-make-options-regexp
1094 (delq nil (mapcar (lambda (e) (nth 1 e)) all)))))
1095 (goto-char (point-min))
1096 (while (re-search-forward opt-re nil t)
1097 (let ((element (org-element-at-point)))
1098 (when (eq (car element) 'keyword)
1099 (let* ((key (upcase (org-element-get-property :key element)))
1100 (val (org-element-get-property :value element))
1101 (prop (cdr (assoc key alist)))
1102 (behaviour (nth 4 (assq prop all))))
1103 (setq plist
1104 (plist-put
1105 plist prop
1106 ;; Handle value depending on specified BEHAVIOUR.
1107 (case behaviour
1108 (space
1109 (if (not (plist-get plist prop)) (org-trim val)
1110 (concat (plist-get plist prop) " " (org-trim val))))
1111 (newline
1112 (org-trim
1113 (concat (plist-get plist prop) "\n" (org-trim val))))
1114 (split
1115 `(,@(plist-get plist prop) ,@(org-split-string val)))
1116 ('t val)
1117 (otherwise (plist-get plist prop)))))))))
1118 ;; Parse keywords specified in `org-element-parsed-keywords'.
1119 (mapc
1120 (lambda (key)
1121 (let* ((prop (cdr (assoc key alist)))
1122 (value (and prop (plist-get plist prop))))
1123 (when (stringp value)
1124 (setq plist
1125 (plist-put
1126 plist prop
1127 (org-element-parse-secondary-string
1128 value
1129 (cdr (assq 'keyword org-element-string-restrictions))))))))
1130 org-element-parsed-keywords))
1131 ;; 3. Return final value.
1132 plist)))
1134 (defun org-export-get-global-options (&optional backend)
1135 "Return global export options as a plist.
1137 Optional argument BACKEND, if non-nil, is a symbol specifying
1138 which back-end specific export options should also be read in the
1139 process."
1140 (let ((all (append org-export-option-alist
1141 (and backend
1142 (let ((var (intern
1143 (format "org-%s-option-alist" backend))))
1144 (and (boundp var) (eval var))))))
1145 ;; Output value.
1146 plist)
1147 (mapc (lambda (cell)
1148 (setq plist (plist-put plist (car cell) (eval (nth 3 cell)))))
1149 all)
1150 ;; Return value.
1151 plist))
1153 (defun org-export-initial-options ()
1154 "Return a plist with properties related to input buffer."
1155 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
1156 (list
1157 ;; Store full path of input file name, or nil. For internal use.
1158 :input-file visited-file
1159 ;; `:macro-date', `:macro-time' and `:macro-property' could as well
1160 ;; be initialized as tree properties, since they don't depend on
1161 ;; initial environment. Though, it may be more logical to keep
1162 ;; them close to other ":macro-" properties.
1163 :macro-date "(eval (format-time-string \"$1\"))"
1164 :macro-time "(eval (format-time-string \"$1\"))"
1165 :macro-property "(eval (org-entry-get nil \"$1\" 'selective))"
1166 :macro-modification-time
1167 (and visited-file
1168 (file-exists-p visited-file)
1169 (concat "(eval (format-time-string \"$1\" '"
1170 (prin1-to-string (nth 5 (file-attributes visited-file)))
1171 "))"))
1172 ;; Store input file name as a macro.
1173 :macro-input-file (and visited-file (file-name-nondirectory visited-file))
1174 ;; Footnotes definitions must be collected in the original buffer,
1175 ;; as there's no insurance that they will still be in the parse
1176 ;; tree, due to some narrowing.
1177 :footnote-definition-alist
1178 (let (alist)
1179 (org-with-wide-buffer
1180 (goto-char (point-min))
1181 (while (re-search-forward org-footnote-definition-re nil t)
1182 (let ((def (org-footnote-at-definition-p)))
1183 (when def
1184 (org-skip-whitespace)
1185 (push (cons (car def)
1186 (save-restriction
1187 (narrow-to-region (point) (nth 2 def))
1188 ;; Like `org-element-parse-buffer', but
1189 ;; makes sure the definition doesn't start
1190 ;; with a section element.
1191 (nconc
1192 (list 'org-data nil)
1193 (org-element-parse-elements
1194 (point-min) (point-max) nil nil nil nil nil))))
1195 alist))))
1196 alist)))))
1198 (defvar org-export-allow-BIND-local nil)
1199 (defun org-export-confirm-letbind ()
1200 "Can we use #+BIND values during export?
1201 By default this will ask for confirmation by the user, to divert
1202 possible security risks."
1203 (cond
1204 ((not org-export-allow-BIND) nil)
1205 ((eq org-export-allow-BIND t) t)
1206 ((local-variable-p 'org-export-allow-BIND-local) org-export-allow-BIND-local)
1207 (t (org-set-local 'org-export-allow-BIND-local
1208 (yes-or-no-p "Allow BIND values in this buffer? ")))))
1210 (defun org-export-install-letbind-maybe ()
1211 "Install the values from #+BIND lines as local variables.
1212 Variables must be installed before in-buffer options are
1213 retrieved."
1214 (let (letbind pair)
1215 (org-with-wide-buffer
1216 (goto-char (point-min))
1217 (while (re-search-forward (org-make-options-regexp '("BIND")) nil t)
1218 (when (org-export-confirm-letbind)
1219 (push (read (concat "(" (org-match-string-no-properties 2) ")"))
1220 letbind))))
1221 (while (setq pair (pop letbind))
1222 (org-set-local (car pair) (nth 1 pair)))))
1225 ;;;; Tree Properties
1227 ;; Tree properties are infromation extracted from parse tree. They
1228 ;; are initialized at the beginning of the transcoding process by
1229 ;; `org-export-collect-tree-properties'.
1231 ;; Dedicated functions focus on computing the value of specific tree
1232 ;; properties during initialization. Thus,
1233 ;; `org-export-use-select-tag-p' determines if an headline makes use
1234 ;; of an export tag enforcing inclusion. `org-export-get-min-level'
1235 ;; gets the minimal exportable level, used as a basis to compute
1236 ;; relative level for headlines. `org-export-get-point-max' returns
1237 ;; the maximum exportable ending position in the parse tree.
1238 ;; Eventually `org-export-collect-headline-numbering' builds an alist
1239 ;; between headlines' beginning position and their numbering.
1241 (defun org-export-collect-tree-properties (data info backend)
1242 "Extract tree properties from parse tree.
1244 DATA is the parse tree from which information is retrieved. INFO
1245 is a list holding export options. BACKEND is the back-end called
1246 for transcoding, as a symbol.
1248 Following tree properties are set:
1249 `:back-end' Back-end used for transcoding.
1251 `:headline-offset' Offset between true level of headlines and
1252 local level. An offset of -1 means an headline
1253 of level 2 should be considered as a level
1254 1 headline in the context.
1256 `:headline-numbering' Alist of all headlines' beginning position
1257 as key an the associated numbering as value.
1259 `:parse-tree' Whole parse tree.
1261 `:target-list' List of all targets in the parse tree.
1263 `:use-select-tags' Non-nil when parsed tree use a special tag to
1264 enforce transcoding of the headline."
1265 ;; First, set `:use-select-tags' property, as it will be required
1266 ;; for further computations.
1267 (setq info
1268 (org-combine-plists
1269 info `(:use-select-tags ,(org-export-use-select-tags-p data info))))
1270 ;; Then get `:headline-offset' in order to be able to use
1271 ;; `org-export-get-relative-level'.
1272 (setq info
1273 (org-combine-plists
1274 info `(:headline-offset ,(- 1 (org-export-get-min-level data info)))))
1275 ;; Now, get the rest of the tree properties, now `:use-select-tags'
1276 ;; is set...
1277 (nconc
1278 `(:parse-tree
1279 ,data
1280 :target-list
1281 ,(org-element-map data 'target (lambda (target local) target) info)
1282 :headline-numbering ,(org-export-collect-headline-numbering data info)
1283 :back-end ,backend)
1284 info))
1286 (defun org-export-use-select-tags-p (data options)
1287 "Non-nil when data use a tag enforcing transcoding.
1288 DATA is parsed data as returned by `org-element-parse-buffer'.
1289 OPTIONS is a plist holding export options."
1290 (org-element-map
1291 data
1292 'headline
1293 (lambda (headline info)
1294 (let ((tags (org-element-get-property :with-tags headline)))
1295 (and tags (string-match
1296 (format ":%s:" (plist-get info :select-tags)) tags))))
1297 options
1298 'stop-at-first-match))
1300 (defun org-export-get-min-level (data options)
1301 "Return minimum exportable headline's level in DATA.
1302 DATA is parsed tree as returned by `org-element-parse-buffer'.
1303 OPTIONS is a plist holding export options."
1304 (catch 'exit
1305 (let ((min-level 10000))
1306 (mapc (lambda (blob)
1307 (when (and (eq (car blob) 'headline)
1308 (not (org-export-skip-p blob options)))
1309 (setq min-level
1310 (min (org-element-get-property :level blob) min-level)))
1311 (when (= min-level 1) (throw 'exit 1)))
1312 (org-element-get-contents data))
1313 ;; If no headline was found, for the sake of consistency, set
1314 ;; minimum level to 1 nonetheless.
1315 (if (= min-level 10000) 1 min-level))))
1317 (defun org-export-collect-headline-numbering (data options)
1318 "Return numbering of all exportable headlines in a parse tree.
1320 DATA is the parse tree. OPTIONS is the plist holding export
1321 options.
1323 Return an alist whose key is an headline and value is its
1324 associated numbering \(in the shape of a list of numbers\)."
1325 (let ((numbering (make-vector org-export-max-depth 0)))
1326 (org-element-map
1327 data
1328 'headline
1329 (lambda (headline info)
1330 (let ((relative-level
1331 (1- (org-export-get-relative-level headline info))))
1332 (cons
1333 headline
1334 (loop for n across numbering
1335 for idx from 0 to org-export-max-depth
1336 when (< idx relative-level) collect n
1337 when (= idx relative-level) collect (aset numbering idx (1+ n))
1338 when (> idx relative-level) do (aset numbering idx 0)))))
1339 options)))
1343 ;;; The Transcoder
1345 ;; This function reads Org data (obtained with, i.e.
1346 ;; `org-element-parse-buffer') and transcodes it into a specified
1347 ;; back-end output. It takes care of updating local properties,
1348 ;; filtering out elements or objects according to export options and
1349 ;; organizing the output blank lines and white space are preserved.
1351 ;; Though, this function is inapropriate for secondary strings, which
1352 ;; require a fresh copy of the plist passed as INFO argument. Thus,
1353 ;; `org-export-secondary-string' is provided for that specific task.
1355 ;; Internally, three functions handle the filtering of objects and
1356 ;; elements during the export. More precisely, `org-export-skip-p'
1357 ;; determines if the considered object or element should be ignored
1358 ;; altogether, `org-export-interpret-p' tells which elements or
1359 ;; objects should be seen as real Org syntax and `org-export-expand'
1360 ;; transforms the others back into their original shape.
1362 (defun org-export-data (data backend info)
1363 "Convert DATA to a string into BACKEND format.
1365 DATA is a nested list as returned by `org-element-parse-buffer'.
1367 BACKEND is a symbol among supported exporters.
1369 INFO is a plist holding export options and also used as
1370 a communication channel between elements when walking the nested
1371 list. See `org-export-update-info' function for more
1372 details.
1374 Return transcoded string."
1375 (mapconcat
1376 ;; BLOB can be an element, an object, a string, or nil.
1377 (lambda (blob)
1378 (cond
1379 ((not blob) nil)
1380 ;; BLOB is a string. Check if the optional transcoder for plain
1381 ;; text exists, and call it in that case. Otherwise, simply
1382 ;; return string. Also update INFO and call
1383 ;; `org-export-filter-plain-text-functions'.
1384 ((stringp blob)
1385 (let ((transcoder (intern (format "org-%s-plain-text" backend))))
1386 (org-export-filter-apply-functions
1387 (plist-get info :filter-plain-text)
1388 (if (fboundp transcoder) (funcall transcoder blob info) blob)
1389 backend info)))
1390 ;; BLOB is an element or an object.
1392 (let* ((type (if (stringp blob) 'plain-text (car blob)))
1393 ;; 1. Determine the appropriate TRANSCODER.
1394 (transcoder
1395 (cond
1396 ;; 1.0 A full Org document is inserted.
1397 ((eq type 'org-data) 'identity)
1398 ;; 1.1. BLOB should be ignored.
1399 ((org-export-skip-p blob info) nil)
1400 ;; 1.2. BLOB shouldn't be transcoded. Interpret it
1401 ;; back into Org syntax.
1402 ((not (org-export-interpret-p blob info))
1403 'org-export-expand)
1404 ;; 1.3. Else apply naming convention.
1405 (t (let ((trans (intern
1406 (format "org-%s-%s" backend type))))
1407 (and (fboundp trans) trans)))))
1408 ;; 2. Compute CONTENTS of BLOB.
1409 (contents
1410 (cond
1411 ;; Case 0. No transcoder defined: ignore BLOB.
1412 ((not transcoder) nil)
1413 ;; Case 1. Transparently export an Org document.
1414 ((eq type 'org-data) (org-export-data blob backend info))
1415 ;; Case 2. For a recursive object.
1416 ((memq type org-element-recursive-objects)
1417 (org-export-data
1418 blob backend
1419 (org-combine-plists
1420 info
1421 `(:genealogy ,(cons blob (plist-get info :genealogy))))))
1422 ;; Case 3. For a recursive element.
1423 ((memq type org-element-greater-elements)
1424 ;; Ignore contents of an archived tree
1425 ;; when `:with-archived-trees' is `headline'.
1426 (unless (and
1427 (eq type 'headline)
1428 (eq (plist-get info :with-archived-trees) 'headline)
1429 (org-element-get-property :archivedp blob))
1430 (org-element-normalize-string
1431 (org-export-data
1432 blob backend
1433 (org-combine-plists
1434 info `(:genealogy
1435 ,(cons blob (plist-get info :genealogy))))))))
1436 ;; Case 4. For a paragraph.
1437 ((eq type 'paragraph)
1438 (let ((paragraph
1439 (org-element-normalize-contents
1440 blob
1441 ;; When normalizing contents of an item or
1442 ;; a footnote definition, ignore first line's
1443 ;; indentation: there is none and it might be
1444 ;; misleading.
1445 (and (not (org-export-get-previous-element blob info))
1446 (let ((parent (caar (plist-get info :genealogy))))
1447 (memq parent '(footnote-definition item)))))))
1448 (org-export-data
1449 paragraph backend
1450 (org-combine-plists
1451 info `(:genealogy
1452 ,(cons paragraph (plist-get info :genealogy)))))))))
1453 ;; 3. Transcode BLOB into RESULTS string.
1454 (results (cond
1455 ((not transcoder) nil)
1456 ((eq transcoder 'org-export-expand)
1457 (org-export-data
1458 `(org-data nil ,(funcall transcoder blob contents))
1459 backend info))
1460 (t (funcall transcoder blob contents info)))))
1461 ;; 4. Discard nil results. Otherwise, update INFO, append
1462 ;; the same white space between elements or objects as in
1463 ;; the original buffer, and call appropriate filters.
1464 (when results
1465 ;; No filter for a full document.
1466 (if (eq type 'org-data) results
1467 (org-export-filter-apply-functions
1468 (plist-get info (intern (format ":filter-%s" type)))
1469 (let ((post-blank (org-element-get-property :post-blank blob)))
1470 (if (memq type org-element-all-elements)
1471 (concat (org-element-normalize-string results)
1472 (make-string post-blank ?\n))
1473 (concat results (make-string post-blank ? ))))
1474 backend info)))))))
1475 (org-element-get-contents data) ""))
1477 (defun org-export-secondary-string (secondary backend info)
1478 "Convert SECONDARY string into BACKEND format.
1480 SECONDARY is a nested list as returned by
1481 `org-element-parse-secondary-string'.
1483 BACKEND is a symbol among supported exporters. INFO is a plist
1484 used as a communication channel.
1486 Return transcoded string."
1487 ;; Make SECONDARY acceptable for `org-export-data'.
1488 (let ((s (if (listp secondary) secondary (list secondary))))
1489 (org-export-data `(org-data nil ,@s) backend (copy-sequence info))))
1491 (defun org-export-skip-p (blob info)
1492 "Non-nil when element or object BLOB should be skipped during export.
1493 INFO is the plist holding export options."
1494 ;; Check headline.
1495 (unless (stringp blob)
1496 (case (car blob)
1497 ('headline
1498 (let ((with-tasks (plist-get info :with-tasks))
1499 (todo (org-element-get-property :todo-keyword blob))
1500 (todo-type (org-element-get-property :todo-type blob))
1501 (archived (plist-get info :with-archived-trees))
1502 (tag-list (let ((tags (org-element-get-property :tags blob)))
1503 (and tags (org-split-string tags ":")))))
1505 ;; Ignore subtrees with an exclude tag.
1506 (loop for k in (plist-get info :exclude-tags)
1507 thereis (member k tag-list))
1508 ;; Ignore subtrees without a select tag, when such tag is found
1509 ;; in the buffer.
1510 (and (plist-get info :use-select-tags)
1511 (loop for k in (plist-get info :select-tags)
1512 never (member k tag-list)))
1513 ;; Ignore commented sub-trees.
1514 (org-element-get-property :commentedp blob)
1515 ;; Ignore archived subtrees if `:with-archived-trees' is nil.
1516 (and (not archived) (org-element-get-property :archivedp blob))
1517 ;; Ignore tasks, if specified by `:with-tasks' property.
1518 (and todo (not with-tasks))
1519 (and todo
1520 (memq with-tasks '(todo done))
1521 (not (eq todo-type with-tasks)))
1522 (and todo
1523 (consp with-tasks)
1524 (not (member todo with-tasks))))))
1525 ;; Check time-stamp.
1526 ('time-stamp (not (plist-get info :with-timestamps)))
1527 ;; Check drawer.
1528 ('drawer
1529 (or (not (plist-get info :with-drawers))
1530 (and (consp (plist-get info :with-drawers))
1531 (not (member (org-element-get-property :drawer-name blob)
1532 (plist-get info :with-drawers))))))
1533 ;; Check export snippet.
1534 ('export-snippet
1535 (let* ((raw-back-end (org-element-get-property :back-end blob))
1536 (true-back-end
1537 (or (cdr (assoc raw-back-end org-export-snippet-translation-alist))
1538 raw-back-end)))
1539 (not (string= (symbol-name (plist-get info :back-end))
1540 true-back-end)))))))
1542 (defun org-export-interpret-p (blob info)
1543 "Non-nil if element or object BLOB should be interpreted as Org syntax.
1544 Check is done according to export options INFO, stored as
1545 a plist."
1546 (case (car blob)
1547 ;; ... entities...
1548 (entity (plist-get info :with-entities))
1549 ;; ... emphasis...
1550 (emphasis (plist-get info :with-emphasize))
1551 ;; ... fixed-width areas.
1552 (fixed-width (plist-get info :with-fixed-width))
1553 ;; ... footnotes...
1554 ((footnote-definition footnote-reference)
1555 (plist-get info :with-footnotes))
1556 ;; ... sub/superscripts...
1557 ((subscript superscript)
1558 (let ((sub/super-p (plist-get info :with-sub-superscript)))
1559 (if (eq sub/super-p '{})
1560 (org-element-get-property :use-brackets-p blob)
1561 sub/super-p)))
1562 ;; ... tables...
1563 (table (plist-get info :with-tables))
1564 (otherwise t)))
1566 (defsubst org-export-expand (blob contents)
1567 "Expand a parsed element or object to its original state.
1568 BLOB is either an element or an object. CONTENTS is its
1569 contents, as a string or nil."
1570 (funcall
1571 (intern (format "org-element-%s-interpreter" (car blob))) blob contents))
1575 ;;; The Filter System
1577 ;; Filters allow end-users to tweak easily the transcoded output.
1578 ;; They are the functional counterpart of hooks, as every filter in
1579 ;; a set is applied to the return value of the previous one.
1581 ;; Every set is back-end agnostic. Although, a filter is always
1582 ;; called, in addition to the string it applies to, with the back-end
1583 ;; used as argument, so it's easy enough for the end-user to add
1584 ;; back-end specific filters in the set. The communication channel,
1585 ;; as a plist, is required as the third argument.
1587 ;; Filters sets are defined below. There are of four types:
1589 ;; - `org-export-filter-parse-tree-functions' applies directly on the
1590 ;; complete parsed tree. It's the only filters set that doesn't
1591 ;; apply to a string.
1592 ;; - `org-export-filter-final-output-functions' applies to the final
1593 ;; transcoded string.
1594 ;; - `org-export-filter-plain-text-functions' applies to any string
1595 ;; not recognized as Org syntax.
1596 ;; - `org-export-filter-TYPE-functions' applies on the string returned
1597 ;; after an element or object of type TYPE has been transcoded.
1599 ;; All filters sets are applied through
1600 ;; `org-export-filter-apply-functions' function. Filters in a set are
1601 ;; applied in a LIFO fashion. It allows developers to be sure that
1602 ;; their filters will be applied first.
1604 ;; Filters properties are installed in communication channel just
1605 ;; before parsing, with `org-export-install-filters' function.
1607 ;;;; Special Filters
1608 (defvar org-export-filter-parse-tree-functions nil
1609 "Filter, or list of filters, applied to the parsed tree.
1610 Each filter is called with three arguments: the parse tree, as
1611 returned by `org-element-parse-buffer', the back-end, as
1612 a symbol, and the communication channel, as a plist. It must
1613 return the modified parse tree to transcode.")
1615 (defvar org-export-filter-final-output-functions nil
1616 "Filter, or list of filters, applied to the transcoded string.
1617 Each filter is called with three arguments: the full transcoded
1618 string, the back-end, as a symbol, and the communication channel,
1619 as a plist. It must return a string that will be used as the
1620 final export output.")
1622 (defvar org-export-filter-plain-text-functions nil
1623 "Filter, or list of filters, applied to plain text.
1624 Each filter is called with three arguments: a string which
1625 contains no Org syntax, the back-end, as a symbol, and the
1626 communication channel, as a plist. It must return a string or
1627 nil.")
1630 ;;;; Elements Filters
1632 (defvar org-export-filter-center-block-functions nil
1633 "List of functions applied to a transcoded center block.
1634 Each filter is called with three arguments: the transcoded center
1635 block, as a string, the back-end, as a symbol, and the
1636 communication channel, as a plist. It must return a string or
1637 nil.")
1639 (defvar org-export-filter-drawer-functions nil
1640 "List of functions applied to a transcoded drawer.
1641 Each filter is called with three arguments: the transcoded
1642 drawer, as a string, the back-end, as a symbol, and the
1643 communication channel, as a plist. It must return a string or
1644 nil.")
1646 (defvar org-export-filter-dynamic-block-functions nil
1647 "List of functions applied to a transcoded dynamic-block.
1648 Each filter is called with three arguments: the transcoded
1649 dynamic-block, as a string, the back-end, as a symbol, and the
1650 communication channel, as a plist. It must return a string or
1651 nil.")
1653 (defvar org-export-filter-headline-functions nil
1654 "List of functions applied to a transcoded headline.
1655 Each filter is called with three arguments: the transcoded
1656 headline, as a string, the back-end, as a symbol, and the
1657 communication channel, as a plist. It must return a string or
1658 nil.")
1660 (defvar org-export-filter-inlinetask-functions nil
1661 "List of functions applied to a transcoded inlinetask.
1662 Each filter is called with three arguments: the transcoded
1663 inlinetask, as a string, the back-end, as a symbol, and the
1664 communication channel, as a plist. It must return a string or
1665 nil.")
1667 (defvar org-export-filter-plain-list-functions nil
1668 "List of functions applied to a transcoded plain-list.
1669 Each filter is called with three arguments: the transcoded
1670 plain-list, as a string, the back-end, as a symbol, and the
1671 communication channel, as a plist. It must return a string or
1672 nil.")
1674 (defvar org-export-filter-item-functions nil
1675 "List of functions applied to a transcoded item.
1676 Each filter is called with three arguments: the transcoded item,
1677 as a string, the back-end, as a symbol, and the communication
1678 channel, as a plist. It must return a string or nil.")
1680 (defvar org-export-filter-comment-functions nil
1681 "List of functions applied to a transcoded comment.
1682 Each filter is called with three arguments: the transcoded
1683 comment, as a string, the back-end, as a symbol, and the
1684 communication channel, as a plist. It must return a string or
1685 nil.")
1687 (defvar org-export-filter-comment-block-functions nil
1688 "List of functions applied to a transcoded comment-comment.
1689 Each filter is called with three arguments: the transcoded
1690 comment-block, as a string, the back-end, as a symbol, and the
1691 communication channel, as a plist. It must return a string or
1692 nil.")
1694 (defvar org-export-filter-example-block-functions nil
1695 "List of functions applied to a transcoded example-block.
1696 Each filter is called with three arguments: the transcoded
1697 example-block, as a string, the back-end, as a symbol, and the
1698 communication channel, as a plist. It must return a string or
1699 nil.")
1701 (defvar org-export-filter-export-block-functions nil
1702 "List of functions applied to a transcoded export-block.
1703 Each filter is called with three arguments: the transcoded
1704 export-block, as a string, the back-end, as a symbol, and the
1705 communication channel, as a plist. It must return a string or
1706 nil.")
1708 (defvar org-export-filter-fixed-width-functions nil
1709 "List of functions applied to a transcoded fixed-width.
1710 Each filter is called with three arguments: the transcoded
1711 fixed-width, as a string, the back-end, as a symbol, and the
1712 communication channel, as a plist. It must return a string or
1713 nil.")
1715 (defvar org-export-filter-footnote-definition-functions nil
1716 "List of functions applied to a transcoded footnote-definition.
1717 Each filter is called with three arguments: the transcoded
1718 footnote-definition, as a string, the back-end, as a symbol, and
1719 the communication channel, as a plist. It must return a string
1720 or nil.")
1722 (defvar org-export-filter-horizontal-rule-functions nil
1723 "List of functions applied to a transcoded horizontal-rule.
1724 Each filter is called with three arguments: the transcoded
1725 horizontal-rule, as a string, the back-end, as a symbol, and the
1726 communication channel, as a plist. It must return a string or
1727 nil.")
1729 (defvar org-export-filter-keyword-functions nil
1730 "List of functions applied to a transcoded keyword.
1731 Each filter is called with three arguments: the transcoded
1732 keyword, as a string, the back-end, as a symbol, and the
1733 communication channel, as a plist. It must return a string or
1734 nil.")
1736 (defvar org-export-filter-latex-environment-functions nil
1737 "List of functions applied to a transcoded latex-environment.
1738 Each filter is called with three arguments: the transcoded
1739 latex-environment, as a string, the back-end, as a symbol, and
1740 the communication channel, as a plist. It must return a string
1741 or nil.")
1743 (defvar org-export-filter-babel-call-functions nil
1744 "List of functions applied to a transcoded babel-call.
1745 Each filter is called with three arguments: the transcoded
1746 babel-call, as a string, the back-end, as a symbol, and the
1747 communication channel, as a plist. It must return a string or
1748 nil.")
1750 (defvar org-export-filter-paragraph-functions nil
1751 "List of functions applied to a transcoded paragraph.
1752 Each filter is called with three arguments: the transcoded
1753 paragraph, as a string, the back-end, as a symbol, and the
1754 communication channel, as a plist. It must return a string or
1755 nil.")
1757 (defvar org-export-filter-property-drawer-functions nil
1758 "List of functions applied to a transcoded property-drawer.
1759 Each filter is called with three arguments: the transcoded
1760 property-drawer, as a string, the back-end, as a symbol, and the
1761 communication channel, as a plist. It must return a string or
1762 nil.")
1764 (defvar org-export-filter-quote-block-functions nil
1765 "List of functions applied to a transcoded quote block.
1766 Each filter is called with three arguments: the transcoded quote
1767 block, as a string, the back-end, as a symbol, and the
1768 communication channel, as a plist. It must return a string or
1769 nil.")
1771 (defvar org-export-filter-quote-section-functions nil
1772 "List of functions applied to a transcoded quote-section.
1773 Each filter is called with three arguments: the transcoded
1774 quote-section, as a string, the back-end, as a symbol, and the
1775 communication channel, as a plist. It must return a string or
1776 nil.")
1778 (defvar org-export-filter-section-functions nil
1779 "List of functions applied to a transcoded section.
1780 Each filter is called with three arguments: the transcoded
1781 section, as a string, the back-end, as a symbol, and the
1782 communication channel, as a plist. It must return a string or
1783 nil.")
1785 (defvar org-export-filter-special-block-functions nil
1786 "List of functions applied to a transcoded special block.
1787 Each filter is called with three arguments: the transcoded
1788 special block, as a string, the back-end, as a symbol, and the
1789 communication channel, as a plist. It must return a string or
1790 nil.")
1792 (defvar org-export-filter-src-block-functions nil
1793 "List of functions applied to a transcoded src-block.
1794 Each filter is called with three arguments: the transcoded
1795 src-block, as a string, the back-end, as a symbol, and the
1796 communication channel, as a plist. It must return a string or
1797 nil.")
1799 (defvar org-export-filter-table-functions nil
1800 "List of functions applied to a transcoded table.
1801 Each filter is called with three arguments: the transcoded table,
1802 as a string, the back-end, as a symbol, and the communication
1803 channel, as a plist. It must return a string or nil.")
1805 (defvar org-export-filter-verse-block-functions nil
1806 "List of functions applied to a transcoded verse block.
1807 Each filter is called with three arguments: the transcoded verse
1808 block, as a string, the back-end, as a symbol, and the
1809 communication channel, as a plist. It must return a string or
1810 nil.")
1813 ;;;; Objects Filters
1815 (defvar org-export-filter-emphasis-functions nil
1816 "List of functions applied to a transcoded emphasis.
1817 Each filter is called with three arguments: the transcoded
1818 emphasis, as a string, the back-end, as a symbol, and the
1819 communication channel, as a plist. It must return a string or
1820 nil.")
1822 (defvar org-export-filter-entity-functions nil
1823 "List of functions applied to a transcoded entity.
1824 Each filter is called with three arguments: the transcoded
1825 entity, as a string, the back-end, as a symbol, and the
1826 communication channel, as a plist. It must return a string or
1827 nil.")
1829 (defvar org-export-filter-export-snippet-functions nil
1830 "List of functions applied to a transcoded export-snippet.
1831 Each filter is called with three arguments: the transcoded
1832 export-snippet, as a string, the back-end, as a symbol, and the
1833 communication channel, as a plist. It must return a string or
1834 nil.")
1836 (defvar org-export-filter-footnote-reference-functions nil
1837 "List of functions applied to a transcoded footnote-reference.
1838 Each filter is called with three arguments: the transcoded
1839 footnote-reference, as a string, the back-end, as a symbol, and
1840 the communication channel, as a plist. It must return a string
1841 or nil.")
1843 (defvar org-export-filter-inline-babel-call-functions nil
1844 "List of functions applied to a transcoded inline-babel-call.
1845 Each filter is called with three arguments: the transcoded
1846 inline-babel-call, as a string, the back-end, as a symbol, and
1847 the communication channel, as a plist. It must return a string
1848 or nil.")
1850 (defvar org-export-filter-inline-src-block-functions nil
1851 "List of functions applied to a transcoded inline-src-block.
1852 Each filter is called with three arguments: the transcoded
1853 inline-src-block, as a string, the back-end, as a symbol, and the
1854 communication channel, as a plist. It must return a string or
1855 nil.")
1857 (defvar org-export-filter-latex-fragment-functions nil
1858 "List of functions applied to a transcoded latex-fragment.
1859 Each filter is called with three arguments: the transcoded
1860 latex-fragment, as a string, the back-end, as a symbol, and the
1861 communication channel, as a plist. It must return a string or
1862 nil.")
1864 (defvar org-export-filter-line-break-functions nil
1865 "List of functions applied to a transcoded line-break.
1866 Each filter is called with three arguments: the transcoded
1867 line-break, as a string, the back-end, as a symbol, and the
1868 communication channel, as a plist. It must return a string or
1869 nil.")
1871 (defvar org-export-filter-link-functions nil
1872 "List of functions applied to a transcoded link.
1873 Each filter is called with three arguments: the transcoded link,
1874 as a string, the back-end, as a symbol, and the communication
1875 channel, as a plist. It must return a string or nil.")
1877 (defvar org-export-filter-macro-functions nil
1878 "List of functions applied to a transcoded macro.
1879 Each filter is called with three arguments: the transcoded macro,
1880 as a string, the back-end, as a symbol, and the communication
1881 channel, as a plist. It must return a string or nil.")
1883 (defvar org-export-filter-radio-target-functions nil
1884 "List of functions applied to a transcoded radio-target.
1885 Each filter is called with three arguments: the transcoded
1886 radio-target, as a string, the back-end, as a symbol, and the
1887 communication channel, as a plist. It must return a string or
1888 nil.")
1890 (defvar org-export-filter-statistics-cookie-functions nil
1891 "List of functions applied to a transcoded statistics-cookie.
1892 Each filter is called with three arguments: the transcoded
1893 statistics-cookie, as a string, the back-end, as a symbol, and
1894 the communication channel, as a plist. It must return a string
1895 or nil.")
1897 (defvar org-export-filter-subscript-functions nil
1898 "List of functions applied to a transcoded subscript.
1899 Each filter is called with three arguments: the transcoded
1900 subscript, as a string, the back-end, as a symbol, and the
1901 communication channel, as a plist. It must return a string or
1902 nil.")
1904 (defvar org-export-filter-superscript-functions nil
1905 "List of functions applied to a transcoded superscript.
1906 Each filter is called with three arguments: the transcoded
1907 superscript, as a string, the back-end, as a symbol, and the
1908 communication channel, as a plist. It must return a string or
1909 nil.")
1911 (defvar org-export-filter-target-functions nil
1912 "List of functions applied to a transcoded target.
1913 Each filter is called with three arguments: the transcoded
1914 target, as a string, the back-end, as a symbol, and the
1915 communication channel, as a plist. It must return a string or
1916 nil.")
1918 (defvar org-export-filter-time-stamp-functions nil
1919 "List of functions applied to a transcoded time-stamp.
1920 Each filter is called with three arguments: the transcoded
1921 time-stamp, as a string, the back-end, as a symbol, and the
1922 communication channel, as a plist. It must return a string or
1923 nil.")
1925 (defvar org-export-filter-verbatim-functions nil
1926 "List of functions applied to a transcoded verbatim.
1927 Each filter is called with three arguments: the transcoded
1928 verbatim, as a string, the back-end, as a symbol, and the
1929 communication channel, as a plist. It must return a string or
1930 nil.")
1932 (defun org-export-filter-apply-functions (filters value backend info)
1933 "Call every function in FILTERS with arguments VALUE, BACKEND and INFO.
1934 Functions are called in a LIFO fashion, to be sure that developer
1935 specified filters, if any, are called first."
1936 (loop for filter in filters
1937 if (not value) return nil else
1938 do (setq value (funcall filter value backend info)))
1939 value)
1941 (defun org-export-install-filters (backend info)
1942 "Install filters properties in communication channel.
1944 BACKEND is a symbol specifying which back-end specific filters to
1945 install, if any. INFO is a plist containing the current
1946 communication channel.
1948 Return the updated communication channel."
1949 (let (plist)
1950 ;; Install user defined filters with `org-export-filters-alist'.
1951 (mapc (lambda (p)
1952 (setq plist (plist-put plist (car p) (eval (cdr p)))))
1953 org-export-filters-alist)
1954 ;; Prepend back-end specific filters to that list.
1955 (let ((back-end-filters (intern (format "org-%s-filters-alist" backend))))
1956 (when (boundp back-end-filters)
1957 (mapc (lambda (p)
1958 ;; Single values get consed, lists are prepended.
1959 (let ((key (car p)) (value (cdr p)))
1960 (when value
1961 (setq plist
1962 (plist-put
1963 plist key
1964 (if (atom value) (cons value (plist-get plist key))
1965 (append value (plist-get plist key))))))))
1966 (eval back-end-filters))))
1967 ;; Return new communication channel.
1968 (org-combine-plists info plist)))
1972 ;;; Core functions
1974 ;; This is the room for the main function, `org-export-as', along with
1975 ;; its derivatives, `org-export-to-buffer' and `org-export-to-file'.
1976 ;; They differ only by the way they output the resulting code.
1978 ;; `org-export-output-file-name' is an auxiliary function meant to be
1979 ;; used with `org-export-to-file'. With a given extension, it tries
1980 ;; to provide a canonical file name to write export output to.
1982 ;; Note that `org-export-as' doesn't really parse the current buffer,
1983 ;; but a copy of it (with the same buffer-local variables and
1984 ;; visibility), where include keywords are expanded and Babel blocks
1985 ;; are executed, if appropriate.
1986 ;; `org-export-with-current-buffer-copy' macro prepares that copy.
1988 ;; File inclusion is taken care of by
1989 ;; `org-export-expand-include-keyword' and
1990 ;; `org-export-prepare-file-contents'. Structure wise, including
1991 ;; a whole Org file in a buffer often makes little sense. For
1992 ;; example, if the file contains an headline and the include keyword
1993 ;; was within an item, the item should contain the headline. That's
1994 ;; why file inclusion should be done before any structure can be
1995 ;; associated to the file, that is before parsing.
1997 (defun org-export-as
1998 (backend &optional subtreep visible-only body-only ext-plist noexpand)
1999 "Transcode current Org buffer into BACKEND code.
2001 If narrowing is active in the current buffer, only transcode its
2002 narrowed part.
2004 If a region is active, transcode that region.
2006 When optional argument SUBTREEP is non-nil, transcode the
2007 sub-tree at point, extracting information from the headline
2008 properties first.
2010 When optional argument VISIBLE-ONLY is non-nil, don't export
2011 contents of hidden elements.
2013 When optional argument BODY-ONLY is non-nil, only return body
2014 code, without preamble nor postamble.
2016 Optional argument EXT-PLIST, when provided, is a property list
2017 with external parameters overriding Org default settings, but
2018 still inferior to file-local settings.
2020 Optional argument NOEXPAND, when non-nil, prevents included files
2021 to be expanded and Babel code to be executed.
2023 Return code as a string."
2024 (save-excursion
2025 (save-restriction
2026 ;; Narrow buffer to an appropriate region for parsing.
2027 (when (org-region-active-p)
2028 (narrow-to-region (region-beginning) (region-end)))
2029 (when (and subtreep (not (org-at-heading-p)))
2030 ;; Ensure point is at sub-tree's beginning.
2031 (org-narrow-to-subtree))
2032 ;; Retrieve export options (INFO) and parsed tree (RAW-DATA),
2033 ;; Then options can be completed with tree properties. Note:
2034 ;; Buffer isn't parsed directly. Instead, a temporary copy is
2035 ;; created, where include keywords are expanded and code blocks
2036 ;; are evaluated. RAW-DATA is the parsed tree of the buffer
2037 ;; resulting from that process. Eventually call
2038 ;; `org-export-filter-parse-tree-functions'.
2039 (goto-char (point-min))
2040 (let ((info (org-export-get-environment backend subtreep ext-plist)))
2041 ;; Remove subtree's headline from contents if subtree mode is
2042 ;; activated.
2043 (when subtreep (forward-line) (narrow-to-region (point) (point-max)))
2044 ;; Install filters in communication channel.
2045 (setq info (org-export-install-filters backend info))
2046 (let ((raw-data
2047 (org-export-filter-apply-functions
2048 (plist-get info :filter-parse-tree)
2049 ;; If NOEXPAND is non-nil, simply parse current
2050 ;; visible part of buffer.
2051 (if noexpand (org-element-parse-buffer nil visible-only)
2052 (org-export-with-current-buffer-copy
2053 (org-export-expand-include-keyword nil)
2054 (let ((org-current-export-file (current-buffer)))
2055 (org-export-blocks-preprocess))
2056 (org-element-parse-buffer nil visible-only)))
2057 backend info)))
2058 ;; Complete communication channel with tree properties.
2059 (setq info
2060 (org-combine-plists
2061 info
2062 (org-export-collect-tree-properties raw-data info backend)))
2063 ;; Transcode RAW-DATA. Also call
2064 ;; `org-export-filter-final-output-functions'.
2065 (let* ((body (org-element-normalize-string
2066 (org-export-data raw-data backend info)))
2067 (template (intern (format "org-%s-template" backend)))
2068 (output (org-export-filter-apply-functions
2069 (plist-get info :filter-final-output)
2070 (if (or (not (fboundp template)) body-only) body
2071 (funcall template body info))
2072 backend info)))
2073 ;; Maybe add final OUTPUT to kill ring before returning it.
2074 (when org-export-copy-to-kill-ring (org-kill-new output))
2075 output))))))
2077 (defun org-export-to-buffer
2078 (backend buffer &optional subtreep visible-only body-only ext-plist noexpand)
2079 "Call `org-export-as' with output to a specified buffer.
2081 BACKEND is the back-end used for transcoding, as a symbol.
2083 BUFFER is the output buffer. If it already exists, it will be
2084 erased first, otherwise, it will be created.
2086 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY, EXT-PLIST
2087 and NOEXPAND are similar to those used in `org-export-as', which
2088 see.
2090 Return buffer."
2091 (let ((out (org-export-as
2092 backend subtreep visible-only body-only ext-plist noexpand))
2093 (buffer (get-buffer-create buffer)))
2094 (with-current-buffer buffer
2095 (erase-buffer)
2096 (insert out)
2097 (goto-char (point-min)))
2098 buffer))
2100 (defun org-export-to-file
2101 (backend file &optional subtreep visible-only body-only ext-plist noexpand)
2102 "Call `org-export-as' with output to a specified file.
2104 BACKEND is the back-end used for transcoding, as a symbol. FILE
2105 is the name of the output file, as a string.
2107 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY, EXT-PLIST
2108 and NOEXPAND are similar to those used in `org-export-as', which
2109 see.
2111 Return output file's name."
2112 ;; Checks for FILE permissions. `write-file' would do the same, but
2113 ;; we'd rather avoid needless transcoding of parse tree.
2114 (unless (file-writable-p file) (error "Output file not writable"))
2115 ;; Insert contents to a temporary buffer and write it to FILE.
2116 (let ((out (org-export-as
2117 backend subtreep visible-only body-only ext-plist noexpand)))
2118 (with-temp-buffer
2119 (insert out)
2120 (let ((coding-system-for-write org-export-coding-system))
2121 (write-file file))))
2122 ;; Return full path.
2123 file)
2125 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
2126 "Return output file's name according to buffer specifications.
2128 EXTENSION is a string representing the output file extension,
2129 with the leading dot.
2131 With a non-nil optional argument SUBTREEP, try to determine
2132 output file's name by looking for \"EXPORT_FILE_NAME\" property
2133 of subtree at point.
2135 When optional argument PUB-DIR is set, use it as the publishing
2136 directory.
2138 Return file name as a string, or nil if it couldn't be
2139 determined."
2140 (let ((base-name
2141 ;; File name may come from EXPORT_FILE_NAME subtree property,
2142 ;; assuming point is at beginning of said sub-tree.
2143 (file-name-sans-extension
2144 (or (and subtreep
2145 (org-entry-get
2146 (save-excursion
2147 (ignore-errors
2148 (org-back-to-heading (not visible-only)) (point)))
2149 "EXPORT_FILE_NAME" t))
2150 ;; File name may be extracted from buffer's associated
2151 ;; file, if any.
2152 (buffer-file-name (buffer-base-buffer))
2153 ;; Can't determine file name on our own: Ask user.
2154 (let ((read-file-name-function
2155 (and org-completion-use-ido 'ido-read-file-name)))
2156 (read-file-name
2157 "Output file: " pub-dir nil nil nil
2158 (lambda (name)
2159 (string= (file-name-extension name t) extension))))))))
2160 ;; Build file name. Enforce EXTENSION over whatever user may have
2161 ;; come up with. PUB-DIR, if defined, always has precedence over
2162 ;; any provided path.
2163 (cond
2164 (pub-dir
2165 (concat (file-name-as-directory pub-dir)
2166 (file-name-nondirectory base-name)
2167 extension))
2168 ((string= (file-name-nondirectory base-name) base-name)
2169 (concat (file-name-as-directory ".") base-name extension))
2170 (t (concat base-name extension)))))
2172 (defmacro org-export-with-current-buffer-copy (&rest body)
2173 "Apply BODY in a copy of the current buffer.
2175 The copy preserves local variables and visibility of the original
2176 buffer.
2178 Point is at buffer's beginning when BODY is applied."
2179 (org-with-gensyms (original-buffer offset buffer-string overlays)
2180 `(let ((,original-buffer ,(current-buffer))
2181 (,offset ,(1- (point-min)))
2182 (,buffer-string ,(buffer-string))
2183 (,overlays (mapcar
2184 'copy-overlay (overlays-in (point-min) (point-max)))))
2185 (with-temp-buffer
2186 (let ((buffer-invisibility-spec nil))
2187 (org-clone-local-variables
2188 ,original-buffer
2189 "^\\(org-\\|orgtbl-\\|major-mode$\\|outline-\\(regexp\\|level\\)$\\)")
2190 (insert ,buffer-string)
2191 (mapc (lambda (ov)
2192 (move-overlay
2194 (- (overlay-start ov) ,offset)
2195 (- (overlay-end ov) ,offset)
2196 (current-buffer)))
2197 ,overlays)
2198 (goto-char (point-min))
2199 (progn ,@body))))))
2200 (def-edebug-spec org-export-with-current-buffer-copy (body))
2202 (defun org-export-expand-include-keyword (included)
2203 "Expand every include keyword in buffer.
2204 INCLUDED is a list of included file names along with their line
2205 restriction, when appropriate. It is used to avoid infinite
2206 recursion."
2207 (let ((case-fold-search nil))
2208 (goto-char (point-min))
2209 (while (re-search-forward "^[ \t]*#\\+include: \\(.*\\)" nil t)
2210 (when (eq (car (save-match-data (org-element-at-point))) 'keyword)
2211 (beginning-of-line)
2212 ;; Extract arguments from keyword's value.
2213 (let* ((value (match-string 1))
2214 (ind (org-get-indentation))
2215 (file (and (string-match "^\"\\(\\S-+\\)\"" value)
2216 (prog1 (expand-file-name (match-string 1 value))
2217 (setq value (replace-match "" nil nil value)))))
2218 (lines
2219 (and (string-match
2220 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\"" value)
2221 (prog1 (match-string 1 value)
2222 (setq value (replace-match "" nil nil value)))))
2223 (env (cond ((string-match "\\<example\\>" value) 'example)
2224 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
2225 (match-string 1 value))))
2226 ;; Minimal level of included file defaults to the child
2227 ;; level of the current headline, if any, or one. It
2228 ;; only applies is the file is meant to be included as
2229 ;; an Org one.
2230 (minlevel
2231 (and (not env)
2232 (if (string-match ":minlevel +\\([0-9]+\\)" value)
2233 (prog1 (string-to-number (match-string 1 value))
2234 (setq value (replace-match "" nil nil value)))
2235 (let ((cur (org-current-level)))
2236 (if cur (1+ (org-reduced-level cur)) 1))))))
2237 ;; Remove keyword.
2238 (delete-region (point) (progn (forward-line) (point)))
2239 (cond
2240 ((not (file-readable-p file)) (error "Cannot include file %s" file))
2241 ;; Check if files has already been parsed. Look after
2242 ;; inclusion lines too, as different parts of the same file
2243 ;; can be included too.
2244 ((member (list file lines) included)
2245 (error "Recursive file inclusion: %s" file))
2247 (cond
2248 ((eq env 'example)
2249 (insert
2250 (let ((ind-str (make-string ind ? ))
2251 (contents
2252 ;; Protect sensitive contents with commas.
2253 (replace-regexp-in-string
2254 "\\(^\\)\\([*]\\|[ \t]*#\\+\\)" ","
2255 (org-export-prepare-file-contents file lines)
2256 nil nil 1)))
2257 (format "%s#+begin_example\n%s%s#+end_example\n"
2258 ind-str contents ind-str))))
2259 ((stringp env)
2260 (insert
2261 (let ((ind-str (make-string ind ? ))
2262 (contents
2263 ;; Protect sensitive contents with commas.
2264 (replace-regexp-in-string
2265 (if (string= env "org") "\\(^\\)\\(.\\)"
2266 "\\(^\\)\\([*]\\|[ \t]*#\\+\\)") ","
2267 (org-export-prepare-file-contents file lines)
2268 nil nil 1)))
2269 (format "%s#+begin_src %s\n%s%s#+end_src\n"
2270 ind-str env contents ind-str))))
2272 (insert
2273 (with-temp-buffer
2274 (org-mode)
2275 (insert
2276 (org-export-prepare-file-contents file lines ind minlevel))
2277 (org-export-expand-include-keyword
2278 (cons (list file lines) included))
2279 (buffer-string))))))))))))
2281 (defun org-export-prepare-file-contents (file &optional lines ind minlevel)
2282 "Prepare the contents of FILE for inclusion and return them as a string.
2284 When optional argument LINES is a string specifying a range of
2285 lines, include only those lines.
2287 Optional argument IND, when non-nil, is an integer specifying the
2288 global indentation of returned contents. Since its purpose is to
2289 allow an included file to stay in the same environment it was
2290 created \(i.e. a list item), it doesn't apply past the first
2291 headline encountered.
2293 Optional argument MINLEVEL, when non-nil, is an integer
2294 specifying the level that any top-level headline in the included
2295 file should have."
2296 (with-temp-buffer
2297 (insert-file-contents file)
2298 (when lines
2299 (let* ((lines (split-string lines "-"))
2300 (lbeg (string-to-number (car lines)))
2301 (lend (string-to-number (cadr lines)))
2302 (beg (if (zerop lbeg) (point-min)
2303 (goto-char (point-min))
2304 (forward-line (1- lbeg))
2305 (point)))
2306 (end (if (zerop lend) (point-max)
2307 (goto-char (point-min))
2308 (forward-line (1- lend))
2309 (point))))
2310 (narrow-to-region beg end)))
2311 ;; Remove blank lines at beginning and end of contents. The logic
2312 ;; behind that removal is that blank lines around include keyword
2313 ;; override blank lines in included file.
2314 (goto-char (point-min))
2315 (org-skip-whitespace)
2316 (beginning-of-line)
2317 (delete-region (point-min) (point))
2318 (goto-char (point-max))
2319 (skip-chars-backward " \r\t\n")
2320 (forward-line)
2321 (delete-region (point) (point-max))
2322 ;; If IND is set, preserve indentation of include keyword until
2323 ;; the first headline encountered.
2324 (when ind
2325 (unless (eq major-mode 'org-mode) (org-mode))
2326 (goto-char (point-min))
2327 (let ((ind-str (make-string ind ? )))
2328 (while (not (or (eobp) (looking-at org-outline-regexp-bol)))
2329 ;; Do not move footnote definitions out of column 0.
2330 (unless (and (looking-at org-footnote-definition-re)
2331 (eq (car (org-element-at-point)) 'footnote-definition))
2332 (insert ind-str))
2333 (forward-line))))
2334 ;; When MINLEVEL is specified, compute minimal level for headlines
2335 ;; in the file (CUR-MIN), and remove stars to each headline so
2336 ;; that headlines with minimal level have a level of MINLEVEL.
2337 (when minlevel
2338 (unless (eq major-mode 'org-mode) (org-mode))
2339 (let ((levels (org-map-entries
2340 (lambda () (org-reduced-level (org-current-level))))))
2341 (when levels
2342 (let ((offset (- minlevel (apply 'min levels))))
2343 (unless (zerop offset)
2344 (when org-odd-levels-only (setq offset (* offset 2)))
2345 ;; Only change stars, don't bother moving whole
2346 ;; sections.
2347 (org-map-entries
2348 (lambda () (if (< offset 0) (delete-char (abs offset))
2349 (insert (make-string offset ?*))))))))))
2350 (buffer-string)))
2353 ;;; Tools For Back-Ends
2355 ;; A whole set of tools is available to help build new exporters. Any
2356 ;; function general enough to have its use across many back-ends
2357 ;; should be added here.
2359 ;; As of now, functions operating on footnotes, headlines, links,
2360 ;; macros, references, src-blocks, tables and tables of contents are
2361 ;; implemented.
2363 ;;;; For Footnotes
2365 ;; `org-export-collect-footnote-definitions' is a tool to list
2366 ;; actually used footnotes definitions in the whole parse tree, or in
2367 ;; an headline, in order to add footnote listings throughout the
2368 ;; transcoded data.
2370 ;; `org-export-footnote-first-reference-p' is a predicate used by some
2371 ;; back-ends, when they need to attach the footnote definition only to
2372 ;; the first occurrence of the corresponding label.
2374 ;; `org-export-get-footnote-definition' and
2375 ;; `org-export-get-footnote-number' provide easier access to
2376 ;; additional information relative to a footnote reference.
2378 (defun org-export-collect-footnote-definitions (data info)
2379 "Return an alist between footnote numbers, labels and definitions.
2381 DATA is the parse tree from which definitions are collected.
2382 INFO is the plist used as a communication channel.
2384 Definitions are sorted by order of references. They either
2385 appear as Org data \(transcoded with `org-export-data'\) or as
2386 a secondary string for inlined footnotes \(transcoded with
2387 `org-export-secondary-string'\). Unreferenced definitions are
2388 ignored."
2389 (let (refs)
2390 ;; Collect seen references in REFS.
2391 (org-element-map
2392 data 'footnote-reference
2393 (lambda (footnote local)
2394 (when (org-export-footnote-first-reference-p footnote local)
2395 (list (org-export-get-footnote-number footnote local)
2396 (org-element-get-property :label footnote)
2397 (org-export-get-footnote-definition footnote local))))
2398 info)))
2400 (defun org-export-footnote-first-reference-p (footnote-reference info)
2401 "Non-nil when a footnote reference is the first one for its label.
2403 FOOTNOTE-REFERENCE is the footnote reference being considered.
2404 INFO is the plist used as a communication channel."
2405 (let ((label (org-element-get-property :label footnote-reference)))
2406 (or (not label)
2407 (equal
2408 footnote-reference
2409 (org-element-map
2410 (plist-get info :parse-tree) 'footnote-reference
2411 (lambda (footnote local)
2412 (when (string= (org-element-get-property :label footnote) label)
2413 footnote))
2414 info 'first-match)))))
2416 (defun org-export-get-footnote-definition (footnote-reference info)
2417 "Return definition of FOOTNOTE-REFERENCE as parsed data.
2418 INFO is the plist used as a communication channel."
2419 (let ((label (org-element-get-property :label footnote-reference)))
2420 (or (org-element-get-property :inline-definition footnote-reference)
2421 (cdr (assoc label (plist-get info :footnote-definition-alist))))))
2423 (defun org-export-get-footnote-number (footnote info)
2424 "Return number associated to a footnote.
2426 FOOTNOTE is either a footnote reference or a footnote definition.
2427 INFO is the plist used as a communication channel."
2428 (let ((label (org-element-get-property :label footnote)) seen-refs)
2429 (org-element-map
2430 (plist-get info :parse-tree) 'footnote-reference
2431 (lambda (fn local)
2432 (let ((fn-lbl (org-element-get-property :label fn)))
2433 (cond
2434 ((and (not fn-lbl) (equal fn footnote)) (1+ (length seen-refs)))
2435 ((and label (string= label fn-lbl)) (1+ (length seen-refs)))
2436 ;; Anonymous footnote: it's always a new one. Also, be sure
2437 ;; to return nil from the `cond' so `first-match' doesn't
2438 ;; get us out of the loop.
2439 ((not fn-lbl) (push 'inline seen-refs) nil)
2440 ;; Label not seen so far: add it so SEEN-REFS. Again,
2441 ;; return nil to stay in the loop.
2442 ((not (member fn-lbl seen-refs)) (push fn-lbl seen-refs) nil))))
2443 info 'first-match)))
2446 ;;;; For Headlines
2448 ;; `org-export-get-relative-level' is a shortcut to get headline
2449 ;; level, relatively to the lower headline level in the parsed tree.
2451 ;; `org-export-get-headline-number' returns the section number of an
2452 ;; headline, while `org-export-number-to-roman' allows to convert it
2453 ;; to roman numbers.
2455 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
2456 ;; `org-export-last-sibling-p' are three useful predicates when it
2457 ;; comes to fulfill the `:headline-levels' property.
2459 (defun org-export-get-relative-level (headline info)
2460 "Return HEADLINE relative level within current parsed tree.
2461 INFO is a plist holding contextual information."
2462 (+ (org-element-get-property :level headline)
2463 (or (plist-get info :headline-offset) 0)))
2465 (defun org-export-low-level-p (headline info)
2466 "Non-nil when HEADLINE is considered as low level.
2468 INFO is a plist used as a communication channel.
2470 A low level headlines has a relative level greater than
2471 `:headline-levels' property value.
2473 Return value is the difference between HEADLINE relative level
2474 and the last level being considered as high enough, or nil."
2475 (let ((limit (plist-get info :headline-levels)))
2476 (when (wholenump limit)
2477 (let ((level (org-export-get-relative-level headline info)))
2478 (and (> level limit) (- level limit))))))
2480 (defun org-export-get-headline-number (headline info)
2481 "Return HEADLINE numbering as a list of numbers.
2482 INFO is a plist holding contextual information."
2483 (cdr (assoc headline (plist-get info :headline-numbering))))
2485 (defun org-export-number-to-roman (n)
2486 "Convert integer N into a roman numeral."
2487 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
2488 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
2489 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
2490 ( 1 . "I")))
2491 (res ""))
2492 (if (<= n 0)
2493 (number-to-string n)
2494 (while roman
2495 (if (>= n (caar roman))
2496 (setq n (- n (caar roman))
2497 res (concat res (cdar roman)))
2498 (pop roman)))
2499 res)))
2501 (defun org-export-first-sibling-p (headline info)
2502 "Non-nil when HEADLINE is the first sibling in its sub-tree.
2503 INFO is the plist used as a communication channel."
2504 (not (eq (car (org-export-get-previous-element headline info)) 'headline)))
2506 (defun org-export-last-sibling-p (headline info)
2507 "Non-nil when HEADLINE is the last sibling in its sub-tree.
2508 INFO is the plist used as a communication channel."
2509 (equal
2510 (car (last (org-element-get-contents (car (plist-get info :genealogy)))))
2511 headline))
2514 ;;;; For Links
2516 ;; `org-export-solidify-link-text' turns a string into a safer version
2517 ;; for links, replacing most non-standard characters with hyphens.
2519 ;; `org-export-get-coderef-format' returns an appropriate format
2520 ;; string for coderefs.
2522 ;; `org-export-inline-image-p' returns a non-nil value when the link
2523 ;; provided should be considered as an inline image.
2525 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
2526 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
2527 ;; returns an appropriate unique identifier when found, or nil.
2529 ;; `org-export-resolve-id-link' returns the first headline with
2530 ;; specified id or custom-id in parse tree, or nil when none was
2531 ;; found.
2533 ;; `org-export-resolve-coderef' associates a reference to a line
2534 ;; number in the element it belongs, or returns the reference itself
2535 ;; when the element isn't numbered.
2537 (defun org-export-solidify-link-text (s)
2538 "Take link text S and make a safe target out of it."
2539 (save-match-data
2540 (mapconcat 'identity (org-split-string s "[^a-zA-Z0-9_.-]+") "-")))
2542 (defun org-export-get-coderef-format (path desc)
2543 "Return format string for code reference link.
2544 PATH is the link path. DESC is its description."
2545 (save-match-data
2546 (cond ((string-match (regexp-quote (concat "(" path ")")) desc)
2547 (replace-match "%s" t t desc))
2548 ((string= desc "") "%s")
2549 (t desc))))
2551 (defun org-export-inline-image-p (link &optional rules)
2552 "Non-nil if LINK object points to an inline image.
2554 Optional argument is a set of RULES defining inline images. It
2555 is an alist where associations have the following shape:
2557 \(TYPE . REGEXP)
2559 Applying a rule means apply REGEXP against LINK's path when its
2560 type is TYPE. The function will return a non-nil value if any of
2561 the provided rules is non-nil. The default rule is
2562 `org-export-default-inline-image-rule'.
2564 This only applies to links without a description."
2565 (and (not (org-element-get-contents link))
2566 (let ((case-fold-search t)
2567 (rules (or rules org-export-default-inline-image-rule)))
2568 (some
2569 (lambda (rule)
2570 (and (string= (org-element-get-property :type link) (car rule))
2571 (string-match (cdr rule)
2572 (org-element-get-property :path link))))
2573 rules))))
2575 (defun org-export-resolve-fuzzy-link (link info)
2576 "Return LINK destination.
2578 INFO is a plist holding contextual information.
2580 Return value can be an object, an element, or nil:
2582 - If LINK path exactly matches any target, return the target
2583 object.
2585 - If LINK path exactly matches any headline name, return that
2586 element. If more than one headline share that name, priority
2587 will be given to the one with the closest common ancestor, if
2588 any, or the first one in the parse tree otherwise.
2590 - Otherwise, return nil.
2592 Assume LINK type is \"fuzzy\"."
2593 (let ((path (org-element-get-property :path link)))
2594 ;; Link points to a target: return it.
2595 (or (loop for target in (plist-get info :target-list)
2596 when (string= (org-element-get-property :raw-value target) path)
2597 return target)
2598 ;; Link either points to an headline or nothing. Try to find
2599 ;; the source, with priority given to headlines with the closest
2600 ;; common ancestor. If such candidate is found, return its
2601 ;; beginning position as an unique identifier, otherwise return
2602 ;; nil.
2603 (let ((find-headline
2604 (function
2605 ;; Return first headline whose `:raw-value' property
2606 ;; is NAME in parse tree DATA, or nil.
2607 (lambda (name data)
2608 (org-element-map
2609 data 'headline
2610 (lambda (headline local)
2611 (when (string=
2612 (org-element-get-property :raw-value headline)
2613 name)
2614 headline))
2615 info 'first-match)))))
2616 ;; Search among headlines sharing an ancestor with link,
2617 ;; from closest to farthest.
2618 (or (catch 'exit
2619 (mapc
2620 (lambda (parent)
2621 (when (eq (car parent) 'headline)
2622 (let ((foundp (funcall find-headline path parent)))
2623 (when foundp (throw 'exit foundp)))))
2624 (plist-get info :genealogy)) nil)
2625 ;; No match with a common ancestor: try the full parse-tree.
2626 (funcall find-headline path (plist-get info :parse-tree)))))))
2628 (defun org-export-resolve-id-link (link info)
2629 "Return headline referenced as LINK destination.
2631 INFO is a plist used as a communication channel.
2633 Return value can be an headline element or nil. Assume LINK type
2634 is either \"id\" or \"custom-id\"."
2635 (let ((id (org-element-get-property :path link)))
2636 (org-element-map
2637 (plist-get info :parse-tree) 'headline
2638 (lambda (headline local)
2639 (when (or (string= (org-element-get-property :id headline) id)
2640 (string= (org-element-get-property :custom-id headline) id))
2641 headline))
2642 info 'first-match)))
2644 (defun org-export-resolve-ref-link (link info)
2645 "Return element referenced as LINK destination.
2647 INFO is a plist used as a communication channel.
2649 Assume LINK type is \"ref\" and. Return value is the first
2650 element whose `:name' property matches LINK's `:path', or nil."
2651 (let ((name (org-element-get-property :path link)))
2652 (org-element-map
2653 (plist-get info :parse-tree) org-element-all-elements
2654 (lambda (el local)
2655 (when (string= (org-element-get-property :name el) name) el))
2656 info 'first-match)))
2658 (defun org-export-resolve-coderef (ref info)
2659 "Resolve a code reference REF.
2661 INFO is a plist used as a communication channel.
2663 Return associated line number in source code, or REF itself,
2664 depending on src-block or example element's switches."
2665 (org-element-map
2666 (plist-get info :parse-tree) '(src-block example)
2667 (lambda (el local)
2668 (let ((switches (or (org-element-get-property :switches el) "")))
2669 (with-temp-buffer
2670 (insert (org-trim (org-element-get-property :value el)))
2671 ;; Build reference regexp.
2672 (let* ((label
2673 (or (and (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
2674 (match-string 1 switches))
2675 org-coderef-label-format))
2676 (ref-re
2677 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
2678 (replace-regexp-in-string "%s" ref label nil t))))
2679 ;; Element containing REF is found. Only associate REF to
2680 ;; a line number if element has "+n" or "-n" and "-k" or
2681 ;; "-r" as switches. When it has "+n", count accumulated
2682 ;; locs before, too.
2683 (when (re-search-backward ref-re nil t)
2684 (cond
2685 ((not (string-match "-[kr]\\>" switches)) ref)
2686 ((string-match "-n\\>" switches) (line-number-at-pos))
2687 ((string-match "\\+n\\>" switches)
2688 (+ (org-export-get-loc el local) (line-number-at-pos)))
2689 (t ref)))))))
2690 info 'first-match))
2693 ;;;; For Macros
2695 ;; `org-export-expand-macro' simply takes care of expanding macros.
2697 (defun org-export-expand-macro (macro info)
2698 "Expand MACRO and return it as a string.
2699 INFO is a plist holding export options."
2700 (let* ((key (org-element-get-property :key macro))
2701 (args (org-element-get-property :args macro))
2702 ;; User's macros are stored in the communication channel with
2703 ;; a ":macro-" prefix. If it's a string leave it as-is.
2704 ;; Otherwise, it's a secondary string that needs to be
2705 ;; expanded recursively.
2706 (value
2707 (let ((val (plist-get info (intern (format ":macro-%s" key)))))
2708 (if (stringp val) val
2709 (org-export-secondary-string
2710 val (plist-get info :back-end) info)))))
2711 ;; Replace arguments in VALUE.
2712 (let ((s 0) n)
2713 (while (string-match "\\$\\([0-9]+\\)" value s)
2714 (setq s (1+ (match-beginning 0))
2715 n (string-to-number (match-string 1 value)))
2716 (and (>= (length args) n)
2717 (setq value (replace-match (nth (1- n) args) t t value)))))
2718 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
2719 (when (string-match "\\`(eval\\>" value)
2720 (setq value (eval (read value))))
2721 ;; Return string.
2722 (format "%s" (or value ""))))
2725 ;;;; For References
2727 ;; `org-export-get-ordinal' associates a sequence number to any object
2728 ;; or element.
2730 (defun org-export-get-ordinal
2731 (element info &optional types within-section predicate)
2732 "Return ordinal number of an element or object.
2734 ELEMENT is the element or object considered. INFO is the plist
2735 used as a communication channel.
2737 Optional argument TYPES, when non-nil, is a list of element or
2738 object types, as symbols, that should also be counted in.
2739 Otherwise, only provided element's type is considered.
2741 When optional argument WITHIN-SECTION is non-nil, narrow counting
2742 to the section containing ELEMENT.
2744 Optional argument PREDICATE is a function returning a non-nil
2745 value if the current element or object should be counted in. It
2746 accepts one argument: the element or object being considered.
2747 This argument allows to count only a certain type of objects,
2748 like inline images, which are a subset of links \(in that case,
2749 `org-export-inline-image-p' might be an useful predicate\)."
2750 (let ((counter 0)
2751 ;; Determine if search should apply to current section, in
2752 ;; which case it should be retrieved first, or to full parse
2753 ;; tree. As a special case, an element or object without
2754 ;; a parent headline will also trigger a full search,
2755 ;; notwithstanding WITHIN-SECTION value.
2756 (data
2757 (if (not within-section) (plist-get info :parse-tree)
2758 (or (org-export-get-parent-headline element info)
2759 (plist-get info :parse-tree)))))
2760 ;; Increment counter until ELEMENT is found again.
2761 (org-element-map
2762 data (or types (car element))
2763 (lambda (el local)
2764 (cond
2765 ((equal element el) (1+ counter))
2766 ((not predicate) (incf counter) nil)
2767 ((funcall predicate el) (incf counter) nil)))
2768 info 'first-match)))
2771 ;;;; For Src-Blocks
2773 ;; `org-export-get-loc' counts number of code lines accumulated in
2774 ;; src-block or example-block elements with a "+n" switch until
2775 ;; a given element, excluded. Note: "-n" switches reset that count.
2777 ;; `org-export-handle-code' takes care of line numbering and reference
2778 ;; cleaning in source code, when appropriate.
2780 (defun org-export-get-loc (element info)
2781 "Return accumulated lines of code up to ELEMENT.
2783 INFO is the plist used as a communication channel.
2785 ELEMENT is excluded from count."
2786 (let ((loc 0))
2787 (org-element-map
2788 (plist-get info :parse-tree) `(src-block example-block ,(car element))
2789 (lambda (el local)
2790 (cond
2791 ;; ELEMENT is reached: Quit the loop.
2792 ((equal el element) t)
2793 ;; Only count lines from src-block and example-block elements
2794 ;; with a "+n" or "-n" switch. A "-n" switch resets counter.
2795 ((not (memq (car el) '(src-block example-block))) nil)
2796 ((let ((switches (org-element-get-property :switches el)))
2797 (when (and switches (string-match "\\([-+]\\)n\\>" switches))
2798 ;; Accumulate locs or reset them.
2799 (let ((accumulatep (string= (match-string 1 switches) "-"))
2800 (lines (org-count-lines
2801 (org-trim (org-element-get-property :value el)))))
2802 (setq loc (if accumulatep lines (+ loc lines))))))
2803 ;; Return nil to stay in the loop.
2804 nil)))
2805 info 'first-match)
2806 ;; Return value.
2807 loc))
2809 (defun org-export-handle-code (element info &optional num-fmt ref-fmt delayed)
2810 "Handle line numbers and code references in ELEMENT.
2812 ELEMENT has either a `src-block' an `example-block' type. INFO
2813 is a plist used as a communication channel.
2815 If optional argument NUM-FMT is a string, it will be used as
2816 a format string for numbers at beginning of each line.
2818 If optional argument REF-FMT is a string, it will be used as
2819 a format string for each line of code containing a reference.
2821 When optional argument DELAYED is non-nil, `org-loc' and
2822 `org-coderef' properties, set to an adequate value, are applied
2823 to, respectively, numbered lines and lines with a reference. No
2824 line numbering is done and all references are stripped from the
2825 resulting string. Both NUM-FMT and REF-FMT arguments are ignored
2826 in that situation.
2828 Return new code as a string."
2829 (let* ((switches (or (org-element-get-property :switches element) ""))
2830 (code (org-element-get-property :value element))
2831 (numberp (string-match "[-+]n\\>" switches))
2832 (accumulatep (string-match "\\+n\\>" switches))
2833 ;; Initialize loc counter when any kind of numbering is
2834 ;; active.
2835 (total-LOC (cond
2836 (accumulatep (org-export-get-loc element info))
2837 (numberp 0)))
2838 ;; Get code and clean it. Remove blank lines at its
2839 ;; beginning and end. Also remove protective commas.
2840 (preserve-indent-p (or org-src-preserve-indentation
2841 (string-match "-i\\>" switches)))
2842 (replace-labels (when (string-match "-r\\>" switches)
2843 (if (string-match "-k\\>" switches) 'keep t)))
2844 (code (let ((c (replace-regexp-in-string
2845 "\\`\\([ \t]*\n\\)+" ""
2846 (replace-regexp-in-string
2847 "\\(:?[ \t]*\n\\)*[ \t]*\\'" "\n" code))))
2848 ;; If appropriate, remove global indentation.
2849 (unless preserve-indent-p (setq c (org-remove-indentation c)))
2850 ;; Free up the protected lines. Note: Org blocks
2851 ;; have commas at the beginning or every line.
2852 (if (string=
2853 (or (org-element-get-property :language element) "")
2854 "org")
2855 (replace-regexp-in-string "^," "" c)
2856 (replace-regexp-in-string
2857 "^\\(,\\)\\(:?\\*\\|[ \t]*#\\+\\)" "" c nil nil 1))))
2858 ;; Split code to process it line by line.
2859 (code-lines (org-split-string code "\n"))
2860 ;; If numbering is active, ensure line numbers will be
2861 ;; correctly padded before applying the format string.
2862 (num-fmt
2863 (when (and (not delayed) numberp)
2864 (format (if (stringp num-fmt) num-fmt "%s: ")
2865 (format "%%%ds"
2866 (length (number-to-string
2867 (+ (length code-lines) total-LOC)))))))
2868 ;; Get format used for references.
2869 (label-fmt (or (and (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
2870 (match-string 1 switches))
2871 org-coderef-label-format))
2872 ;; Build a regexp matching a loc with a reference.
2873 (with-ref-re (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
2874 (replace-regexp-in-string
2875 "%s" "\\([-a-zA-Z0-9_ ]+\\)" label-fmt nil t))))
2876 (org-element-normalize-string
2877 (mapconcat
2878 (lambda (loc)
2879 ;; Maybe add line number to current line of code (LOC).
2880 (when numberp
2881 (incf total-LOC)
2882 (setq loc (if delayed (org-add-props loc nil 'org-loc total-LOC)
2883 (concat (format num-fmt total-LOC) loc))))
2884 ;; Take action if at a ref line.
2885 (when (string-match with-ref-re loc)
2886 (let ((ref (match-string 3 loc)))
2887 (setq loc
2888 ;; Option "-r" without "-k" removes labels.
2889 ;; A non-nil DELAYED removes labels unconditionally.
2890 (if (or delayed
2891 (and replace-labels (not (eq replace-labels 'keep))))
2892 (replace-match "" nil nil loc 1)
2893 (replace-match (format "(%s)" ref) nil nil loc 2)))
2894 ;; Store REF in `org-coderef' property if DELAYED asks to.
2895 (cond (delayed (setq loc (org-add-props loc nil 'org-coderef ref)))
2896 ;; If REF-FMT is defined, apply it to current LOC.
2897 ((stringp ref-fmt) (setq loc (format ref-fmt loc))))))
2898 ;; Return updated LOC for concatenation.
2899 loc)
2900 code-lines "\n"))))
2903 ;;;; For Tables
2905 ;; `org-export-table-format-info' extracts formatting information
2906 ;; (alignment, column groups and presence of a special column) from
2907 ;; a raw table and returns it as a property list.
2909 ;; `org-export-clean-table' cleans the raw table from any Org
2910 ;; table-specific syntax.
2912 (defun org-export-table-format-info (table)
2913 "Extract info from TABLE.
2914 Return a plist whose properties and values are:
2915 `:alignment' vector of strings among \"r\", \"l\" and \"c\",
2916 `:column-groups' vector of symbols among `start', `end', `start-end',
2917 `:row-groups' list of integers representing row groups.
2918 `:special-column-p' non-nil if table has a special column.
2919 `:width' vector of integers representing desired width of
2920 current column, or nil."
2921 (with-temp-buffer
2922 (insert table)
2923 (goto-char 1)
2924 (org-table-align)
2925 (let ((align (vconcat (mapcar (lambda (c) (if c "r" "l"))
2926 org-table-last-alignment)))
2927 (width (make-vector (length org-table-last-alignment) nil))
2928 (colgroups (make-vector (length org-table-last-alignment) nil))
2929 (row-group 0)
2930 (rowgroups)
2931 (special-column-p 'empty))
2932 (mapc (lambda (row)
2933 (if (string-match "^[ \t]*|[-+]+|[ \t]*$" row)
2934 (incf row-group)
2935 ;; Determine if a special column is present by looking
2936 ;; for special markers in the first column. More
2937 ;; accurately, the first column is considered special
2938 ;; if it only contains special markers and, maybe,
2939 ;; empty cells.
2940 (setq special-column-p
2941 (cond
2942 ((not special-column-p) nil)
2943 ((string-match "^[ \t]*| *\\\\?\\([/#!$*_^]\\) *|" row)
2944 'special)
2945 ((string-match "^[ \t]*| +|" row) special-column-p))))
2946 (cond
2947 ;; Read forced alignment and width information, if any,
2948 ;; and determine final alignment for the table.
2949 ((org-table-cookie-line-p row)
2950 (let ((col 0))
2951 (mapc (lambda (field)
2952 (when (string-match
2953 "<\\([lrc]\\)?\\([0-9]+\\)?>" field)
2954 (let ((align-data (match-string 1 field)))
2955 (when align-data (aset align col align-data)))
2956 (let ((w-data (match-string 2 field)))
2957 (when w-data
2958 (aset width col (string-to-number w-data)))))
2959 (incf col))
2960 (org-split-string row "[ \t]*|[ \t]*"))))
2961 ;; Read column groups information.
2962 ((org-table-colgroup-line-p row)
2963 (let ((col 0))
2964 (mapc (lambda (field)
2965 (aset colgroups col
2966 (cond ((string= "<" field) 'start)
2967 ((string= ">" field) 'end)
2968 ((string= "<>" field) 'start-end)))
2969 (incf col))
2970 (org-split-string row "[ \t]*|[ \t]*"))))
2971 ;; Contents line.
2972 (t (push row-group rowgroups))))
2973 (org-split-string table "\n"))
2974 ;; Return plist.
2975 (list :alignment align
2976 :column-groups colgroups
2977 :row-groups (reverse rowgroups)
2978 :special-column-p (eq special-column-p 'special)
2979 :width width))))
2981 (defun org-export-clean-table (table specialp)
2982 "Clean string TABLE from its formatting elements.
2983 Remove any row containing column groups or formatting cookies and
2984 rows starting with a special marker. If SPECIALP is non-nil,
2985 assume the table contains a special formatting column and remove
2986 it also."
2987 (let ((rows (org-split-string table "\n")))
2988 (mapconcat 'identity
2989 (delq nil
2990 (mapcar
2991 (lambda (row)
2992 (cond
2993 ((org-table-colgroup-line-p row) nil)
2994 ((org-table-cookie-line-p row) nil)
2995 ;; Ignore rows starting with a special marker.
2996 ((string-match "^[ \t]*| *[!_^/] *|" row) nil)
2997 ;; Remove special column.
2998 ((and specialp
2999 (or (string-match "^\\([ \t]*\\)|-+\\+" row)
3000 (string-match "^\\([ \t]*\\)|[^|]*|" row)))
3001 (replace-match "\\1|" t nil row))
3002 (t row)))
3003 rows))
3004 "\n")))
3007 ;;;; For Tables Of Contents
3009 ;; `org-export-collect-headlines' builds a list of all exportable
3010 ;; headline elements, maybe limited to a certain depth. One can then
3011 ;; easily parse it and transcode it.
3013 ;; Building lists of tables, figures or listings is quite similar.
3014 ;; Once the generic function `org-export-collect-elements' is defined,
3015 ;; `org-export-collect-tables', `org-export-collect-figures' and
3016 ;; `org-export-collect-listings' can be derived from it.
3018 (defun org-export-collect-headlines (info &optional n)
3019 "Collect headlines in order to build a table of contents.
3021 INFO is a plist used as a communication channel.
3023 When non-nil, optional argument N must be an integer. It
3024 specifies the depth of the table of contents.
3026 Return a list of all exportable headlines as parsed elements."
3027 (org-element-map
3028 (plist-get info :parse-tree)
3029 'headline
3030 (lambda (headline local)
3031 ;; Strip contents from HEADLINE.
3032 (let ((relative-level (org-export-get-relative-level headline local)))
3033 (unless (and n (> relative-level n)) headline)))
3034 info))
3036 (defun org-export-collect-elements (type info &optional predicate)
3037 "Collect referenceable elements of a determined type.
3039 TYPE can be a symbol or a list of symbols specifying element
3040 types to search. Only elements with a caption or a name are
3041 collected.
3043 INFO is a plist used as a communication channel.
3045 When non-nil, optional argument PREDICATE is a function accepting
3046 one argument, an element of type TYPE. It returns a non-nil
3047 value when that element should be collected.
3049 Return a list of all elements found, in order of appearance."
3050 (org-element-map
3051 (plist-get info :parse-tree) type
3052 (lambda (element local)
3053 (and (or (org-element-get-property :caption element)
3054 (org-element-get-property :name element))
3055 (or (not predicate) (funcall predicate element))
3056 element)) info))
3058 (defun org-export-collect-tables (info)
3059 "Build a list of tables.
3061 INFO is a plist used as a communication channel.
3063 Return a list of table elements with a caption or a name
3064 affiliated keyword."
3065 (org-export-collect-elements 'table info))
3067 (defun org-export-collect-figures (info predicate)
3068 "Build a list of figures.
3070 INFO is a plist used as a communication channel. PREDICATE is
3071 a function which accepts one argument: a paragraph element and
3072 whose return value is non-nil when that element should be
3073 collected.
3075 A figure is a paragraph type element, with a caption or a name,
3076 verifying PREDICATE. The latter has to be provided since
3077 a \"figure\" is a vague concept that may depend on back-end.
3079 Return a list of elements recognized as figures."
3080 (org-export-collect-elements 'paragraph info predicate))
3082 (defun org-export-collect-listings (info)
3083 "Build a list of src blocks.
3085 INFO is a plist used as a communication channel.
3087 Return a list of src-block elements with a caption or a name
3088 affiliated keyword."
3089 (org-export-collect-elements 'src-block info))
3092 ;;;; Topology
3094 ;; Here are various functions to retrieve information about the
3095 ;; neighbourhood of a given element or object. Neighbours of interest
3096 ;; are parent headline (`org-export-get-parent-headline'), parent
3097 ;; paragraph (`org-export-get-parent-paragraph'), previous element or
3098 ;; object (`org-export-get-previous-element') and next element or
3099 ;; object (`org-export-get-next-element').
3101 ;; All of these functions are just a specific use of the more generic
3102 ;; `org-export-get-genealogy', which returns the genealogy relative to
3103 ;; the element or object.
3105 (defun org-export-get-genealogy (blob info)
3106 "Return genealogy relative to a given element or object.
3107 BLOB is the element or object being considered. INFO is a plist
3108 used as a communication channel."
3109 ;; LOCALP tells if current `:genealogy' is sufficient to find parent
3110 ;; headline, or if it should be computed.
3111 (let ((localp (member blob (org-element-get-contents
3112 (car (plist-get info :genealogy))))))
3113 (if localp (plist-get info :genealogy)
3114 (catch 'exit
3115 (org-element-map
3116 (plist-get info :parse-tree) (car blob)
3117 (lambda (el local)
3118 (when (equal el blob)
3119 (throw 'exit (plist-get local :genealogy))))
3120 info)))))
3122 (defun org-export-get-parent-headline (blob info)
3123 "Return closest parent headline or nil.
3125 BLOB is the element or object being considered. INFO is a plist
3126 used as a communication channel."
3127 (catch 'exit
3128 (mapc
3129 (lambda (el) (when (eq (car el) 'headline) (throw 'exit el)))
3130 (org-export-get-genealogy blob info))
3131 nil))
3133 (defun org-export-get-parent-paragraph (object info)
3134 "Return parent paragraph or nil.
3136 INFO is a plist used as a communication channel.
3138 Optional argument OBJECT, when provided, is the object to consider.
3139 Otherwise, return the paragraph containing current object.
3141 This is useful for objects, which share attributes with the
3142 paragraph containing them."
3143 (catch 'exit
3144 (mapc
3145 (lambda (el) (when (eq (car el) 'paragraph) (throw 'exit el)))
3146 (org-export-get-genealogy object info))
3147 nil))
3149 (defun org-export-get-previous-element (blob info)
3150 "Return previous element or object.
3152 BLOB is an element or object. INFO is a plist used as
3153 a communication channel.
3155 Return previous element or object, a string, or nil."
3156 (let ((parent (car (org-export-get-genealogy blob info))))
3157 (cadr (member blob (reverse (org-element-get-contents parent))))))
3159 (defun org-export-get-next-element (blob info)
3160 "Return next element or object.
3162 BLOB is an element or object. INFO is a plist used as
3163 a communication channel.
3165 Return next element or object, a string, or nil."
3166 (let ((parent (car (org-export-get-genealogy blob info))))
3167 (cadr (member blob (org-element-get-contents parent)))))
3171 ;;; The Dispatcher
3173 ;; `org-export-dispatch' is the standard interactive way to start an
3174 ;; export process. It uses `org-export-dispatch-ui' as a subroutine
3175 ;; for its interface. Most commons back-ends should have an entry in
3176 ;; it.
3178 (defun org-export-dispatch ()
3179 "Export dispatcher for Org mode.
3181 It provides an access to common export related tasks in a buffer.
3182 Its interface comes in two flavours: standard and expert. While
3183 both share the same set of bindings, only the former displays the
3184 valid keys associations. Set `org-export-dispatch-use-expert-ui'
3185 to switch to one or the other.
3187 Return an error if key pressed has no associated command."
3188 (interactive)
3189 (let* ((input (org-export-dispatch-ui
3190 (if (listp org-export-initial-scope) org-export-initial-scope
3191 (list org-export-initial-scope))
3192 org-export-dispatch-use-expert-ui))
3193 (raw-key (car input))
3194 (optns (cdr input)))
3195 ;; Translate "C-a", "C-b"... into "a", "b"... Then take action
3196 ;; depending on user's key pressed.
3197 (case (if (< raw-key 27) (+ raw-key 96) raw-key)
3198 ;; Export with `e-ascii' back-end.
3199 ((?A ?N ?U)
3200 (let ((outbuf
3201 (org-export-to-buffer
3202 'e-ascii "*Org E-ASCII Export*"
3203 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)
3204 `(:ascii-charset
3205 ,(case raw-key (?A 'ascii) (?N 'latin1) (t 'utf-8))))))
3206 (with-current-buffer outbuf (text-mode))
3207 (when org-export-show-temporary-export-buffer
3208 (switch-to-buffer-other-window outbuf))))
3209 ((?a ?n ?u)
3210 (org-e-ascii-export-to-ascii
3211 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)
3212 `(:ascii-charset ,(case raw-key (?a 'ascii) (?n 'latin1) (t 'utf-8)))))
3213 ;; Export with `e-latex' back-end.
3215 (let ((outbuf
3216 (org-export-to-buffer
3217 'e-latex "*Org E-LaTeX Export*"
3218 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
3219 (with-current-buffer outbuf (latex-mode))
3220 (when org-export-show-temporary-export-buffer
3221 (switch-to-buffer-other-window outbuf))))
3222 (?l (org-e-latex-export-to-latex
3223 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)))
3224 (?p (org-e-latex-export-to-pdf
3225 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)))
3226 (?d (org-open-file
3227 (org-e-latex-export-to-pdf
3228 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
3229 ;; Export with `e-html' back-end.
3231 (let ((outbuf
3232 (org-export-to-buffer
3233 'e-html "*Org E-HTML Export*"
3234 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
3235 ;; set major mode
3236 (with-current-buffer outbuf
3237 (if (featurep 'nxhtml-mode) (nxhtml-mode) (nxml-mode)))
3238 (when org-export-show-temporary-export-buffer
3239 (switch-to-buffer-other-window outbuf))))
3240 (?h (org-e-html-export-to-html
3241 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)))
3242 (?b (org-open-file
3243 (org-e-html-export-to-html
3244 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
3245 ;; Publishing facilities
3246 (?F (org-e-publish-current-file (memq 'force optns)))
3247 (?P (org-e-publish-current-project (memq 'force optns)))
3248 (?X (let ((project
3249 (assoc (org-icompleting-read
3250 "Publish project: " org-e-publish-project-alist nil t)
3251 org-e-publish-project-alist)))
3252 (org-e-publish project (memq 'force optns))))
3253 (?E (org-e-publish-all (memq 'force optns)))
3254 ;; Undefined command.
3255 (t (error "No command associated with key %s"
3256 (char-to-string raw-key))))))
3258 (defun org-export-dispatch-ui (options expertp)
3259 "Handle interface for `org-export-dispatch'.
3261 OPTIONS is a list containing current interactive options set for
3262 export. It can contain any of the following symbols:
3263 `body' toggles a body-only export
3264 `subtree' restricts export to current subtree
3265 `visible' restricts export to visible part of buffer.
3266 `force' force publishing files.
3268 EXPERTP, when non-nil, triggers expert UI. In that case, no help
3269 buffer is provided, but indications about currently active
3270 options are given in the prompt. Moreover, \[?] allows to switch
3271 back to standard interface.
3273 Return value is a list with key pressed as CAR and a list of
3274 final interactive export options as CDR."
3275 (let ((help
3276 (format "-------------------- General Options --------------------
3277 \[1] Body only: %s [2] Export scope: %s
3278 \[3] Visible only: %s [4] Force publishing: %s
3281 -------------- ASCII/Latin-1/UTF-8 Export ---------------
3282 \[a/n/u] to TXT file [A/N/U] to temporary buffer
3284 --------------------- LaTeX Export ----------------------
3285 \[l] to TEX file [L] to temporary buffer
3286 \[p] to PDF file [d] ... and open it
3288 --------------------- HTML Export -----------------------
3289 \[h] to HTML file [b] ... and open it
3290 \[H] to temporary buffer
3292 ------------------------- Publish -------------------------
3293 \[F] current file [P] current project
3294 \[X] a project [E] every project"
3295 (if (memq 'body options) "On " "Off")
3296 (if (memq 'subtree options) "Subtree" "Buffer ")
3297 (if (memq 'visible options) "On " "Off")
3298 (if (memq 'force options) "On " "Off")))
3299 (standard-prompt "Export command: ")
3300 (expert-prompt (format "Export command (%s%s%s%s): "
3301 (if (memq 'body options) "b" "-")
3302 (if (memq 'subtree options) "s" "-")
3303 (if (memq 'visible options) "v" "-")
3304 (if (memq 'force options) "f" "-")))
3305 (handle-keypress
3306 (function
3307 ;; Read a character from command input, toggling interactive
3308 ;; options when applicable. PROMPT is the displayed prompt,
3309 ;; as a string.
3310 (lambda (prompt)
3311 (let ((key (read-char-exclusive prompt)))
3312 (cond
3313 ;; Ignore non-standard characters (i.e. "M-a").
3314 ((not (characterp key)) (org-export-dispatch-ui options expertp))
3315 ;; Help key: Switch back to standard interface if
3316 ;; expert UI was active.
3317 ((eq key ??) (org-export-dispatch-ui options nil))
3318 ;; Toggle export options.
3319 ((memq key '(?1 ?2 ?3 ?4))
3320 (org-export-dispatch-ui
3321 (let ((option (case key (?1 'body) (?2 'subtree) (?3 'visible)
3322 (?4 'force))))
3323 (if (memq option options) (remq option options)
3324 (cons option options)))
3325 expertp))
3326 ;; Action selected: Send key and options back to
3327 ;; `org-export-dispatch'.
3328 (t (cons key options))))))))
3329 ;; With expert UI, just read key with a fancy prompt. In standard
3330 ;; UI, display an intrusive help buffer.
3331 (if expertp (funcall handle-keypress expert-prompt)
3332 (save-window-excursion
3333 (delete-other-windows)
3334 (with-output-to-temp-buffer "*Org Export/Publishing Help*" (princ help))
3335 (org-fit-window-to-buffer
3336 (get-buffer-window "*Org Export/Publishing Help*"))
3337 (funcall handle-keypress standard-prompt)))))
3340 (provide 'org-export)
3341 ;;; org-export.el ends here