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