Manually revert to the Release 7.8.04 tag.
[org-mode.git] / contrib / lisp / org-export.el
blob596b8b4823ba054d9f7c492d75fe2cd1e98cc605
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.
351 All trees carrying any of these tags will be excluded from
352 export. This is without condition, so even subtrees inside that
353 carry one of the `org-export-select-tags' will be removed.
355 This option can also be set with the #+EXPORT_EXCLUDE_TAGS:
356 keyword."
357 :group 'org-export-general
358 :type '(repeat (string :tag "Tag")))
360 (defcustom org-export-with-fixed-width t
361 "Non-nil means lines starting with \":\" will be in fixed width font.
363 This can be used to have pre-formatted text, fragments of code
364 etc. For example:
365 : ;; Some Lisp examples
366 : (while (defc cnt)
367 : (ding))
368 will be looking just like this in also HTML. See also the QUOTE
369 keyword. Not all export backends support this.
371 This option can also be set with the #+OPTIONS line, e.g. \"::nil\"."
372 :group 'org-export-translation
373 :type 'boolean)
375 (defcustom org-export-with-footnotes t
376 "Non-nil means Org footnotes should be exported.
377 This option can also be set with the #+OPTIONS line,
378 e.g. \"f:nil\"."
379 :group 'org-export-general
380 :type 'boolean)
382 (defcustom org-export-headline-levels 3
383 "The last level which is still exported as a headline.
385 Inferior levels will produce itemize lists when exported. Note
386 that a numeric prefix argument to an exporter function overrides
387 this setting.
389 This option can also be set with the #+OPTIONS line, e.g. \"H:2\"."
390 :group 'org-export-general
391 :type 'integer)
393 (defcustom org-export-default-language "en"
394 "The default language for export and clocktable translations, as a string.
395 This may have an association in
396 `org-clock-clocktable-language-setup'."
397 :group 'org-export-general
398 :type '(string :tag "Language"))
400 (defcustom org-export-preserve-breaks nil
401 "Non-nil means preserve all line breaks when exporting.
403 Normally, in HTML output paragraphs will be reformatted.
405 This option can also be set with the #+OPTIONS line,
406 e.g. \"\\n:t\"."
407 :group 'org-export-general
408 :type 'boolean)
410 (defcustom org-export-with-entities t
411 "Non-nil means interpret entities when exporting.
413 For example, HTML export converts \\alpha to &alpha; and \\AA to
414 &Aring;.
416 For a list of supported names, see the constant `org-entities'
417 and the user option `org-entities-user'.
419 This option can also be set with the #+OPTIONS line,
420 e.g. \"e:nil\"."
421 :group 'org-export-general
422 :type 'boolean)
424 (defcustom org-export-with-priority nil
425 "Non-nil means include priority cookies in export.
427 When nil, remove priority cookies for export.
429 This option can also be set with the #+OPTIONS line,
430 e.g. \"pri:t\"."
431 :group 'org-export-general
432 :type 'boolean)
434 (defcustom org-export-with-section-numbers t
435 "Non-nil means add section numbers to headlines when exporting.
437 When set to an integer n, numbering will only happen for
438 headlines whose relative level is higher or equal to n.
440 This option can also be set with the #+OPTIONS line,
441 e.g. \"num:t\"."
442 :group 'org-export-general
443 :type 'boolean)
445 (defcustom org-export-select-tags '("export")
446 "Tags that select a tree for export.
448 If any such tag is found in a buffer, all trees that do not carry
449 one of these tags will be ignored during export. Inside trees
450 that are selected like this, you can still deselect a subtree by
451 tagging it with one of the `org-export-exclude-tags'.
453 This option can also be set with the #+EXPORT_SELECT_TAGS:
454 keyword."
455 :group 'org-export-general
456 :type '(repeat (string :tag "Tag")))
458 (defcustom org-export-with-special-strings t
459 "Non-nil means interpret \"\-\", \"--\" and \"---\" for export.
461 When this option is turned on, these strings will be exported as:
463 Org HTML LaTeX
464 -----+----------+--------
465 \\- &shy; \\-
466 -- &ndash; --
467 --- &mdash; ---
468 ... &hellip; \ldots
470 This option can also be set with the #+OPTIONS line,
471 e.g. \"-:nil\"."
472 :group 'org-export-general
473 :type 'boolean)
475 (defcustom org-export-with-sub-superscripts t
476 "Non-nil means interpret \"_\" and \"^\" for export.
478 When this option is turned on, you can use TeX-like syntax for
479 sub- and superscripts. Several characters after \"_\" or \"^\"
480 will be considered as a single item - so grouping with {} is
481 normally not needed. For example, the following things will be
482 parsed as single sub- or superscripts.
484 10^24 or 10^tau several digits will be considered 1 item.
485 10^-12 or 10^-tau a leading sign with digits or a word
486 x^2-y^3 will be read as x^2 - y^3, because items are
487 terminated by almost any nonword/nondigit char.
488 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
490 Still, ambiguity is possible - so when in doubt use {} to enclose
491 the sub/superscript. If you set this variable to the symbol
492 `{}', the braces are *required* in order to trigger
493 interpretations as sub/superscript. This can be helpful in
494 documents that need \"_\" frequently in plain text.
496 This option can also be set with the #+OPTIONS line,
497 e.g. \"^:nil\"."
498 :group 'org-export-general
499 :type '(choice
500 (const :tag "Interpret them" t)
501 (const :tag "Curly brackets only" {})
502 (const :tag "Do not interpret them" nil)))
504 (defcustom org-export-with-toc t
505 "Non-nil means create a table of contents in exported files.
507 The TOC contains headlines with levels up
508 to`org-export-headline-levels'. When an integer, include levels
509 up to N in the toc, this may then be different from
510 `org-export-headline-levels', but it will not be allowed to be
511 larger than the number of headline levels. When nil, no table of
512 contents is made.
514 This option can also be set with the #+OPTIONS line,
515 e.g. \"toc:nil\" or \"toc:3\"."
516 :group 'org-export-general
517 :type '(choice
518 (const :tag "No Table of Contents" nil)
519 (const :tag "Full Table of Contents" t)
520 (integer :tag "TOC to level")))
522 (defcustom org-export-with-tables t
523 "If non-nil, lines starting with \"|\" define a table.
524 For example:
526 | Name | Address | Birthday |
527 |-------------+----------+-----------|
528 | Arthur Dent | England | 29.2.2100 |
530 This option can also be set with the #+OPTIONS line, e.g. \"|:nil\"."
531 :group 'org-export-general
532 :type 'boolean)
534 (defcustom org-export-with-tags t
535 "If nil, do not export tags, just remove them from headlines.
537 If this is the symbol `not-in-toc', tags will be removed from
538 table of contents entries, but still be shown in the headlines of
539 the document.
541 This option can also be set with the #+OPTIONS line,
542 e.g. \"tags:nil\"."
543 :group 'org-export-general
544 :type '(choice
545 (const :tag "Off" nil)
546 (const :tag "Not in TOC" not-in-toc)
547 (const :tag "On" t)))
549 (defcustom org-export-with-tasks t
550 "Non-nil means include TODO items for export.
551 This may have the following values:
552 t include tasks independent of state.
553 todo include only tasks that are not yet done.
554 done include only tasks that are already done.
555 nil remove all tasks before export
556 list of keywords keep only tasks with these keywords"
557 :group 'org-export-general
558 :type '(choice
559 (const :tag "All tasks" t)
560 (const :tag "No tasks" nil)
561 (const :tag "Not-done tasks" todo)
562 (const :tag "Only done tasks" done)
563 (repeat :tag "Specific TODO keywords"
564 (string :tag "Keyword"))))
566 (defcustom org-export-time-stamp-file t
567 "Non-nil means insert a time stamp into the exported file.
568 The time stamp shows when the file was created.
570 This option can also be set with the #+OPTIONS line,
571 e.g. \"timestamp:nil\"."
572 :group 'org-export-general
573 :type 'boolean)
575 (defcustom org-export-with-timestamps t
576 "If nil, do not export time stamps and associated keywords."
577 :group 'org-export-general
578 :type 'boolean)
580 (defcustom org-export-with-todo-keywords t
581 "Non-nil means include TODO keywords in export.
582 When nil, remove all these keywords from the export.")
584 (defcustom org-export-allow-BIND 'confirm
585 "Non-nil means allow #+BIND to define local variable values for export.
586 This is a potential security risk, which is why the user must
587 confirm the use of these lines."
588 :group 'org-export-general
589 :type '(choice
590 (const :tag "Never" nil)
591 (const :tag "Always" t)
592 (const :tag "Ask a confirmation for each file" confirm)))
594 (defcustom org-export-snippet-translation-alist nil
595 "Alist between export snippets back-ends and exporter back-ends.
597 This variable allows to provide shortcuts for export snippets.
599 For example, with a value of '\(\(\"h\" . \"html\"\)\), the HTML
600 back-end will recognize the contents of \"@h{<b>}\" as HTML code
601 while every other back-end will ignore it."
602 :group 'org-export-general
603 :type '(repeat
604 (cons
605 (string :tag "Shortcut")
606 (string :tag "Back-end"))))
608 (defcustom org-export-coding-system nil
609 "Coding system for the exported file."
610 :group 'org-export-general
611 :type 'coding-system)
613 (defcustom org-export-copy-to-kill-ring t
614 "Non-nil means exported stuff will also be pushed onto the kill ring."
615 :group 'org-export-general
616 :type 'boolean)
618 (defcustom org-export-initial-scope 'buffer
619 "The initial scope when exporting with `org-export-dispatch'.
620 This variable can be either set to `buffer' or `subtree'."
621 :group 'org-export-general
622 :type '(choice
623 (const :tag "Export current buffer" 'buffer)
624 (const :tag "Export current subtree" 'subtree)))
626 (defcustom org-export-show-temporary-export-buffer t
627 "Non-nil means show buffer after exporting to temp buffer.
628 When Org exports to a file, the buffer visiting that file is ever
629 shown, but remains buried. However, when exporting to a temporary
630 buffer, that buffer is popped up in a second window. When this variable
631 is nil, the buffer remains buried also in these cases."
632 :group 'org-export-general
633 :type 'boolean)
635 (defcustom org-export-dispatch-use-expert-ui nil
636 "Non-nil means using a non-intrusive `org-export-dispatch'.
637 In that case, no help buffer is displayed. Though, an indicator
638 for current export scope is added to the prompt \(i.e. \"b\" when
639 output is restricted to body only, \"s\" when it is restricted to
640 the current subtree and \"v\" when only visible elements are
641 considered for export\). Also, \[?] allows to switch back to
642 standard mode."
643 :group 'org-export-general
644 :type 'boolean)
648 ;;; The Communication Channel
650 ;; During export process, every function has access to a number of
651 ;; properties. They are of three types:
653 ;; 1. Environment options are collected once at the very beginning of
654 ;; the process, out of the original buffer and configuration.
655 ;; Associated to the parse tree, they make an Org closure.
656 ;; Collecting them is handled by `org-export-get-environment'
657 ;; function.
659 ;; Most environment options are defined through the
660 ;; `org-export-option-alist' variable.
662 ;; 2. Tree properties are extracted directly from the parsed tree,
663 ;; just before export, by `org-export-collect-tree-properties'.
665 ;; 3. Local options are updated during parsing, and their value
666 ;; depends on the level of recursion. For now, only `:ignore-list'
667 ;; belongs to that category.
669 ;; Here is the full list of properties available during transcode
670 ;; process, with their category (option, tree or local) and their
671 ;; value type.
673 ;; + `:author' :: Author's name.
674 ;; - category :: option
675 ;; - type :: string
677 ;; + `:back-end' :: Current back-end used for transcoding.
678 ;; - category :: tree
679 ;; - type :: symbol
681 ;; + `:creator' :: String to write as creation information.
682 ;; - category :: option
683 ;; - type :: string
685 ;; + `:date' :: String to use as date.
686 ;; - category :: option
687 ;; - type :: string
689 ;; + `:description' :: Description text for the current data.
690 ;; - category :: option
691 ;; - type :: string
693 ;; + `:email' :: Author's email.
694 ;; - category :: option
695 ;; - type :: string
697 ;; + `:exclude-tags' :: Tags for exclusion of subtrees from export
698 ;; process.
699 ;; - category :: option
700 ;; - type :: list of strings
702 ;; + `:footnote-definition-alist' :: Alist between footnote labels and
703 ;; their definition, as parsed data. Only non-inlined footnotes
704 ;; are represented in this alist. Also, every definition isn't
705 ;; guaranteed to be referenced in the parse tree. The purpose of
706 ;; this property is to preserve definitions from oblivion
707 ;; (i.e. when the parse tree comes from a part of the original
708 ;; buffer), it isn't meant for direct use in a back-end. To
709 ;; retrieve a definition relative to a reference, use
710 ;; `org-export-get-footnote-definition' instead.
711 ;; - category :: option
712 ;; - type :: alist (STRING . LIST)
714 ;; + `:headline-levels' :: Maximum level being exported as an
715 ;; headline. Comparison is done with the relative level of
716 ;; headlines in the parse tree, not necessarily with their
717 ;; actual level.
718 ;; - category :: option
719 ;; - type :: integer
721 ;; + `:headline-offset' :: Difference between relative and real level
722 ;; of headlines in the parse tree. For example, a value of -1
723 ;; means a level 2 headline should be considered as level
724 ;; 1 (cf. `org-export-get-relative-level').
725 ;; - category :: tree
726 ;; - type :: integer
728 ;; + `:headline-numbering' :: Alist between headlines and their
729 ;; numbering, as a list of numbers
730 ;; (cf. `org-export-get-headline-number').
731 ;; - category :: tree
732 ;; - type :: alist (INTEGER . LIST)
734 ;; + `:ignore-list' :: List of elements and objects that should be
735 ;; ignored during export.
736 ;; - category :: local
737 ;; - type :: list of elements and objects
739 ;; + `:input-file' :: Full path to input file, if any.
740 ;; - category :: option
741 ;; - type :: string or nil
743 ;; + `:keywords' :: List of keywords attached to data.
744 ;; - category :: option
745 ;; - type :: string
747 ;; + `:language' :: Default language used for translations.
748 ;; - category :: option
749 ;; - type :: string
751 ;; + `:macro-input-file' :: Macro returning file name of input file,
752 ;; or nil.
753 ;; - category :: option
754 ;; - type :: string or nil
756 ;; + `:parse-tree' :: Whole parse tree, available at any time during
757 ;; transcoding.
758 ;; - category :: global
759 ;; - type :: list (as returned by `org-element-parse-buffer')
761 ;; + `:preserve-breaks' :: Non-nil means transcoding should preserve
762 ;; all line breaks.
763 ;; - category :: option
764 ;; - type :: symbol (nil, t)
766 ;; + `:section-numbers' :: Non-nil means transcoding should add
767 ;; section numbers to headlines.
768 ;; - category :: option
769 ;; - type :: symbol (nil, t)
771 ;; + `:select-tags' :: List of tags enforcing inclusion of sub-trees
772 ;; in transcoding. When such a tag is present,
773 ;; subtrees without it are de facto excluded from
774 ;; the process. See `use-select-tags'.
775 ;; - category :: option
776 ;; - type :: list of strings
778 ;; + `:target-list' :: List of targets encountered in the parse tree.
779 ;; This is used to partly resolve "fuzzy" links
780 ;; (cf. `org-export-resolve-fuzzy-link').
781 ;; - category :: tree
782 ;; - type :: list of strings
784 ;; + `:time-stamp-file' :: Non-nil means transcoding should insert
785 ;; a time stamp in the output.
786 ;; - category :: option
787 ;; - type :: symbol (nil, t)
789 ;; + `:with-archived-trees' :: Non-nil when archived subtrees should
790 ;; also be transcoded. If it is set to the `headline' symbol,
791 ;; only the archived headline's name is retained.
792 ;; - category :: option
793 ;; - type :: symbol (nil, t, `headline')
795 ;; + `:with-author' :: Non-nil means author's name should be included
796 ;; in the output.
797 ;; - category :: option
798 ;; - type :: symbol (nil, t)
800 ;; + `:with-creator' :: Non-nild means a creation sentence should be
801 ;; inserted at the end of the transcoded string. If the value
802 ;; is `comment', it should be commented.
803 ;; - category :: option
804 ;; - type :: symbol (`comment', nil, t)
806 ;; + `:with-drawers' :: Non-nil means drawers should be exported. If
807 ;; its value is a list of names, only drawers with such names
808 ;; will be transcoded.
809 ;; - category :: option
810 ;; - type :: symbol (nil, t) or list of strings
812 ;; + `:with-email' :: Non-nil means output should contain author's
813 ;; email.
814 ;; - category :: option
815 ;; - type :: symbol (nil, t)
817 ;; + `:with-emphasize' :: Non-nil means emphasized text should be
818 ;; interpreted.
819 ;; - category :: option
820 ;; - type :: symbol (nil, t)
822 ;; + `:with-fixed-width' :: Non-nil if transcoder should interpret
823 ;; strings starting with a colon as a fixed-with (verbatim) area.
824 ;; - category :: option
825 ;; - type :: symbol (nil, t)
827 ;; + `:with-footnotes' :: Non-nil if transcoder should interpret
828 ;; footnotes.
829 ;; - category :: option
830 ;; - type :: symbol (nil, t)
832 ;; + `:with-priority' :: Non-nil means transcoding should include
833 ;; priority cookies.
834 ;; - category :: option
835 ;; - type :: symbol (nil, t)
837 ;; + `:with-special-strings' :: Non-nil means transcoding should
838 ;; interpret special strings in plain text.
839 ;; - category :: option
840 ;; - type :: symbol (nil, t)
842 ;; + `:with-sub-superscript' :: Non-nil means transcoding should
843 ;; interpret subscript and superscript. With a value of "{}",
844 ;; only interpret those using curly brackets.
845 ;; - category :: option
846 ;; - type :: symbol (nil, {}, t)
848 ;; + `:with-tables' :: Non-nil means transcoding should interpret
849 ;; tables.
850 ;; - category :: option
851 ;; - type :: symbol (nil, t)
853 ;; + `:with-tags' :: Non-nil means transcoding should keep tags in
854 ;; headlines. A `not-in-toc' value will remove them
855 ;; from the table of contents, if any, nonetheless.
856 ;; - category :: option
857 ;; - type :: symbol (nil, t, `not-in-toc')
859 ;; + `:with-tasks' :: Non-nil means transcoding should include
860 ;; headlines with a TODO keyword. A `todo' value
861 ;; will only include headlines with a todo type
862 ;; keyword while a `done' value will do the
863 ;; contrary. If a list of strings is provided, only
864 ;; tasks with keywords belonging to that list will
865 ;; be kept.
866 ;; - category :: option
867 ;; - type :: symbol (t, todo, done, nil) or list of strings
869 ;; + `:with-timestamps' :: Non-nil means transcoding should include
870 ;; time stamps and associated keywords. Otherwise, completely
871 ;; remove them.
872 ;; - category :: option
873 ;; - type :: symbol: (t, nil)
875 ;; + `:with-toc' :: Non-nil means that a table of contents has to be
876 ;; added to the output. An integer value limits its
877 ;; depth.
878 ;; - category :: option
879 ;; - type :: symbol (nil, t or integer)
881 ;; + `:with-todo-keywords' :: Non-nil means transcoding should
882 ;; include TODO keywords.
883 ;; - category :: option
884 ;; - type :: symbol (nil, t)
887 ;;;; Environment Options
889 ;; Environment options encompass all parameters defined outside the
890 ;; scope of the parsed data. They come from five sources, in
891 ;; increasing precedence order:
893 ;; - Global variables,
894 ;; - Options keyword symbols,
895 ;; - Buffer keywords,
896 ;; - Subtree properties.
898 ;; The central internal function with regards to environment options
899 ;; is `org-export-get-environment'. It updates global variables with
900 ;; "#+BIND:" keywords, then retrieve and prioritize properties from
901 ;; the different sources.
903 ;; The internal functions doing the retrieval are:
904 ;; `org-export-parse-option-keyword' ,
905 ;; `org-export-get-subtree-options' ,
906 ;; `org-export-get-inbuffer-options' and
907 ;; `org-export-get-global-options'.
909 ;; Some properties, which do not rely on the previous sources but
910 ;; still depend on the original buffer, are taken care of with
911 ;; `org-export-initial-options'.
913 ;; Also, `org-export-confirm-letbind' and `org-export-install-letbind'
914 ;; take care of the part relative to "#+BIND:" keywords.
916 (defun org-export-get-environment (&optional backend subtreep ext-plist)
917 "Collect export options from the current buffer.
919 Optional argument BACKEND is a symbol specifying which back-end
920 specific options to read, if any.
922 When optional argument SUBTREEP is non-nil, assume the export is
923 done against the current sub-tree.
925 Third optional argument EXT-PLIST is a property list with
926 external parameters overriding Org default settings, but still
927 inferior to file-local settings."
928 ;; First install #+BIND variables.
929 (org-export-install-letbind-maybe)
930 ;; Get and prioritize export options...
931 (let ((options (org-combine-plists
932 ;; ... from global variables...
933 (org-export-get-global-options backend)
934 ;; ... from buffer's name (default title)...
935 `(:title
936 ,(or (let ((file (buffer-file-name (buffer-base-buffer))))
937 (and file
938 (file-name-sans-extension
939 (file-name-nondirectory file))))
940 (buffer-name (buffer-base-buffer))))
941 ;; ... from an external property list...
942 ext-plist
943 ;; ... from in-buffer settings...
944 (org-export-get-inbuffer-options
945 backend
946 (and buffer-file-name
947 (org-remove-double-quotes buffer-file-name)))
948 ;; ... and from subtree, when appropriate.
949 (and subtreep (org-export-get-subtree-options)))))
950 ;; Add initial options.
951 (setq options (append (org-export-initial-options) options))
952 ;; Return plist.
953 options))
955 (defun org-export-parse-option-keyword (options &optional backend)
956 "Parse an OPTIONS line and return values as a plist.
957 Optional argument BACKEND is a symbol specifying which back-end
958 specific items to read, if any."
959 (let* ((all
960 (append org-export-option-alist
961 (and backend
962 (let ((var (intern
963 (format "org-%s-option-alist" backend))))
964 (and (boundp var) (eval var))))))
965 ;; Build an alist between #+OPTION: item and property-name.
966 (alist (delq nil
967 (mapcar (lambda (e)
968 (when (nth 2 e) (cons (regexp-quote (nth 2 e))
969 (car e))))
970 all)))
971 plist)
972 (mapc (lambda (e)
973 (when (string-match (concat "\\(\\`\\|[ \t]\\)"
974 (car e)
975 ":\\(([^)\n]+)\\|[^ \t\n\r;,.]*\\)")
976 options)
977 (setq plist (plist-put plist
978 (cdr e)
979 (car (read-from-string
980 (match-string 2 options)))))))
981 alist)
982 plist))
984 (defun org-export-get-subtree-options ()
985 "Get export options in subtree at point.
987 Assume point is at subtree's beginning.
989 Return options as a plist."
990 (let (prop plist)
991 (when (setq prop (progn (looking-at org-todo-line-regexp)
992 (or (save-match-data
993 (org-entry-get (point) "EXPORT_TITLE"))
994 (org-match-string-no-properties 3))))
995 (setq plist
996 (plist-put
997 plist :title
998 (org-element-parse-secondary-string
999 prop
1000 (cdr (assq 'keyword org-element-string-restrictions))))))
1001 (when (setq prop (org-entry-get (point) "EXPORT_TEXT"))
1002 (setq plist (plist-put plist :text prop)))
1003 (when (setq prop (org-entry-get (point) "EXPORT_AUTHOR"))
1004 (setq plist (plist-put plist :author prop)))
1005 (when (setq prop (org-entry-get (point) "EXPORT_DATE"))
1006 (setq plist (plist-put plist :date prop)))
1007 (when (setq prop (org-entry-get (point) "EXPORT_OPTIONS"))
1008 (setq plist (org-export-add-options-to-plist plist prop)))
1009 plist))
1011 (defun org-export-get-inbuffer-options (&optional backend files)
1012 "Return current buffer export options, as a plist.
1014 Optional argument BACKEND, when non-nil, is a symbol specifying
1015 which back-end specific options should also be read in the
1016 process.
1018 Optional argument FILES is a list of setup files names read so
1019 far, used to avoid circular dependencies.
1021 Assume buffer is in Org mode. Narrowing, if any, is ignored."
1022 (org-with-wide-buffer
1023 (goto-char (point-min))
1024 (let ((case-fold-search t) plist)
1025 ;; 1. Special keywords, as in `org-export-special-keywords'.
1026 (let ((special-re (org-make-options-regexp org-export-special-keywords)))
1027 (while (re-search-forward special-re nil t)
1028 (let ((element (org-element-at-point)))
1029 (when (eq (org-element-type element) 'keyword)
1030 (let* ((key (upcase (org-element-property :key element)))
1031 (val (org-element-property :value element))
1032 (prop
1033 (cond
1034 ((string= key "SETUP_FILE")
1035 (let ((file
1036 (expand-file-name
1037 (org-remove-double-quotes (org-trim val)))))
1038 ;; Avoid circular dependencies.
1039 (unless (member file files)
1040 (with-temp-buffer
1041 (insert (org-file-contents file 'noerror))
1042 (org-mode)
1043 (org-export-get-inbuffer-options
1044 backend (cons file files))))))
1045 ((string= key "OPTIONS")
1046 (org-export-parse-option-keyword val backend))
1047 ((string= key "MACRO")
1048 (when (string-match
1049 "^\\([-a-zA-Z0-9_]+\\)\\(?:[ \t]+\\(.*?\\)[ \t]*$\\)?"
1050 val)
1051 (let ((key
1052 (intern
1053 (concat ":macro-"
1054 (downcase (match-string 1 val)))))
1055 (value (org-match-string-no-properties 2 val)))
1056 (cond
1057 ((not value) nil)
1058 ;; Value will be evaled. Leave it as-is.
1059 ((string-match "\\`(eval\\>" value)
1060 (list key value))
1061 ;; Value has to be parsed for nested
1062 ;; macros.
1064 (list
1066 (let ((restr
1067 (cdr
1068 (assq 'macro
1069 org-element-object-restrictions))))
1070 (org-element-parse-secondary-string
1071 ;; If user explicitly asks for
1072 ;; a newline, be sure to preserve it
1073 ;; from further filling with
1074 ;; `hard-newline'. Also replace
1075 ;; "\\n" with "\n", "\\\n" with "\\n"
1076 ;; and so on...
1077 (replace-regexp-in-string
1078 "\\(\\\\\\\\\\)n" "\\\\"
1079 (replace-regexp-in-string
1080 "\\(?:^\\|[^\\\\]\\)\\(\\\\n\\)"
1081 hard-newline value nil nil 1)
1082 nil nil 1)
1083 restr)))))))))))
1084 (setq plist (org-combine-plists plist prop)))))))
1085 ;; 2. Standard options, as in `org-export-option-alist'.
1086 (let* ((all (append org-export-option-alist
1087 ;; Also look for back-end specific options
1088 ;; if BACKEND is defined.
1089 (and backend
1090 (let ((var
1091 (intern
1092 (format "org-%s-option-alist" backend))))
1093 (and (boundp var) (eval var))))))
1094 ;; Build alist between keyword name and property name.
1095 (alist
1096 (delq nil (mapcar
1097 (lambda (e) (when (nth 1 e) (cons (nth 1 e) (car e))))
1098 all)))
1099 ;; Build regexp matching all keywords associated to export
1100 ;; options. Note: the search is case insensitive.
1101 (opt-re (org-make-options-regexp
1102 (delq nil (mapcar (lambda (e) (nth 1 e)) all)))))
1103 (goto-char (point-min))
1104 (while (re-search-forward opt-re nil t)
1105 (let ((element (org-element-at-point)))
1106 (when (eq (org-element-type element) 'keyword)
1107 (let* ((key (upcase (org-element-property :key element)))
1108 (val (org-element-property :value element))
1109 (prop (cdr (assoc key alist)))
1110 (behaviour (nth 4 (assq prop all))))
1111 (setq plist
1112 (plist-put
1113 plist prop
1114 ;; Handle value depending on specified BEHAVIOUR.
1115 (case behaviour
1116 (space
1117 (if (not (plist-get plist prop)) (org-trim val)
1118 (concat (plist-get plist prop) " " (org-trim val))))
1119 (newline
1120 (org-trim
1121 (concat (plist-get plist prop) "\n" (org-trim val))))
1122 (split
1123 `(,@(plist-get plist prop) ,@(org-split-string val)))
1124 ('t val)
1125 (otherwise (if (not (plist-member plist prop)) val
1126 (plist-get plist prop))))))))))
1127 ;; Parse keywords specified in `org-element-parsed-keywords'.
1128 (mapc
1129 (lambda (key)
1130 (let* ((prop (cdr (assoc key alist)))
1131 (value (and prop (plist-get plist prop))))
1132 (when (stringp value)
1133 (setq plist
1134 (plist-put
1135 plist prop
1136 (org-element-parse-secondary-string
1137 value
1138 (cdr (assq 'keyword org-element-string-restrictions))))))))
1139 org-element-parsed-keywords))
1140 ;; 3. Return final value.
1141 plist)))
1143 (defun org-export-get-global-options (&optional backend)
1144 "Return global export options as a plist.
1146 Optional argument BACKEND, if non-nil, is a symbol specifying
1147 which back-end specific export options should also be read in the
1148 process."
1149 (let ((all (append org-export-option-alist
1150 (and backend
1151 (let ((var (intern
1152 (format "org-%s-option-alist" backend))))
1153 (and (boundp var) (eval var))))))
1154 ;; Output value.
1155 plist)
1156 (mapc (lambda (cell)
1157 (setq plist (plist-put plist (car cell) (eval (nth 3 cell)))))
1158 all)
1159 ;; Return value.
1160 plist))
1162 (defun org-export-initial-options ()
1163 "Return a plist with properties related to input buffer."
1164 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
1165 (list
1166 ;; Store full path of input file name, or nil. For internal use.
1167 :input-file visited-file
1168 ;; `:macro-date', `:macro-time' and `:macro-property' could as well
1169 ;; be initialized as tree properties, since they don't depend on
1170 ;; initial environment. Though, it may be more logical to keep
1171 ;; them close to other ":macro-" properties.
1172 :macro-date "(eval (format-time-string \"$1\"))"
1173 :macro-time "(eval (format-time-string \"$1\"))"
1174 :macro-property "(eval (org-entry-get nil \"$1\" 'selective))"
1175 :macro-modification-time
1176 (and visited-file
1177 (file-exists-p visited-file)
1178 (concat "(eval (format-time-string \"$1\" '"
1179 (prin1-to-string (nth 5 (file-attributes visited-file)))
1180 "))"))
1181 ;; Store input file name as a macro.
1182 :macro-input-file (and visited-file (file-name-nondirectory visited-file))
1183 ;; Footnotes definitions must be collected in the original buffer,
1184 ;; as there's no insurance that they will still be in the parse
1185 ;; tree, due to some narrowing.
1186 :footnote-definition-alist
1187 (let (alist)
1188 (org-with-wide-buffer
1189 (goto-char (point-min))
1190 (while (re-search-forward org-footnote-definition-re nil t)
1191 (let ((def (org-footnote-at-definition-p)))
1192 (when def
1193 (org-skip-whitespace)
1194 (push (cons (car def)
1195 (save-restriction
1196 (narrow-to-region (point) (nth 2 def))
1197 ;; Like `org-element-parse-buffer', but
1198 ;; makes sure the definition doesn't start
1199 ;; with a section element.
1200 (nconc
1201 (list 'org-data nil)
1202 (org-element-parse-elements
1203 (point-min) (point-max) nil nil nil nil nil))))
1204 alist))))
1205 alist)))))
1207 (defvar org-export-allow-BIND-local nil)
1208 (defun org-export-confirm-letbind ()
1209 "Can we use #+BIND values during export?
1210 By default this will ask for confirmation by the user, to divert
1211 possible security risks."
1212 (cond
1213 ((not org-export-allow-BIND) nil)
1214 ((eq org-export-allow-BIND t) t)
1215 ((local-variable-p 'org-export-allow-BIND-local) org-export-allow-BIND-local)
1216 (t (org-set-local 'org-export-allow-BIND-local
1217 (yes-or-no-p "Allow BIND values in this buffer? ")))))
1219 (defun org-export-install-letbind-maybe ()
1220 "Install the values from #+BIND lines as local variables.
1221 Variables must be installed before in-buffer options are
1222 retrieved."
1223 (let (letbind pair)
1224 (org-with-wide-buffer
1225 (goto-char (point-min))
1226 (while (re-search-forward (org-make-options-regexp '("BIND")) nil t)
1227 (when (org-export-confirm-letbind)
1228 (push (read (concat "(" (org-match-string-no-properties 2) ")"))
1229 letbind))))
1230 (while (setq pair (pop letbind))
1231 (org-set-local (car pair) (nth 1 pair)))))
1234 ;;;; Tree Properties
1236 ;; Tree properties are infromation extracted from parse tree. They
1237 ;; are initialized at the beginning of the transcoding process by
1238 ;; `org-export-collect-tree-properties'.
1240 ;; Dedicated functions focus on computing the value of specific tree
1241 ;; properties during initialization. Thus,
1242 ;; `org-export-populate-ignore-list' lists elements and objects that
1243 ;; should be skipped during export, `org-export-get-min-level' gets
1244 ;; the minimal exportable level, used as a basis to compute relative
1245 ;; level for headlines. Eventually
1246 ;; `org-export-collect-headline-numbering' builds an alist between
1247 ;; headlines and their numbering.
1249 (defun org-export-collect-tree-properties (data info backend)
1250 "Extract tree properties from parse tree.
1252 DATA is the parse tree from which information is retrieved. INFO
1253 is a list holding export options. BACKEND is the back-end called
1254 for transcoding, as a symbol.
1256 Following tree properties are set:
1257 `:back-end' Back-end used for transcoding.
1259 `:headline-offset' Offset between true level of headlines and
1260 local level. An offset of -1 means an headline
1261 of level 2 should be considered as a level
1262 1 headline in the context.
1264 `:headline-numbering' Alist of all headlines as key an the
1265 associated numbering as value.
1267 `:ignore-list' List of elements that should be ignored during
1268 export.
1270 `:parse-tree' Whole parse tree.
1272 `:target-list' List of all targets in the parse tree."
1273 ;; First, get the list of elements and objects to ignore, and put it
1274 ;; into `:ignore-list'. Do not overwrite any user ignore that might
1275 ;; have been done during parse tree filtering.
1276 (setq info
1277 (plist-put info
1278 :ignore-list
1279 (append (org-export-populate-ignore-list data info)
1280 (plist-get info :ignore-list))))
1281 ;; Then compute `:headline-offset' in order to be able to use
1282 ;; `org-export-get-relative-level'.
1283 (setq info
1284 (plist-put info
1285 :headline-offset (- 1 (org-export-get-min-level data info))))
1286 ;; Now, properties order doesn't matter: get the rest of the tree
1287 ;; properties.
1288 (nconc
1289 `(:parse-tree
1290 ,data
1291 :target-list
1292 ,(org-element-map
1293 data '(keyword target)
1294 (lambda (blob)
1295 (when (or (eq (org-element-type blob) 'target)
1296 (string= (upcase (org-element-property :key blob))
1297 "TARGET"))
1298 blob)) info)
1299 :headline-numbering ,(org-export-collect-headline-numbering data info)
1300 :back-end ,backend)
1301 info))
1303 (defun org-export-get-min-level (data options)
1304 "Return minimum exportable headline's level in DATA.
1305 DATA is parsed tree as returned by `org-element-parse-buffer'.
1306 OPTIONS is a plist holding export options."
1307 (catch 'exit
1308 (let ((min-level 10000))
1309 (mapc
1310 (lambda (blob)
1311 (when (and (eq (org-element-type blob) 'headline)
1312 (not (member blob (plist-get options :ignore-list))))
1313 (setq min-level
1314 (min (org-element-property :level blob) min-level)))
1315 (when (= min-level 1) (throw 'exit 1)))
1316 (org-element-contents data))
1317 ;; If no headline was found, for the sake of consistency, set
1318 ;; minimum level to 1 nonetheless.
1319 (if (= min-level 10000) 1 min-level))))
1321 (defun org-export-collect-headline-numbering (data options)
1322 "Return numbering of all exportable headlines in a parse tree.
1324 DATA is the parse tree. OPTIONS is the plist holding export
1325 options.
1327 Return an alist whose key is an headline and value is its
1328 associated numbering \(in the shape of a list of numbers\)."
1329 (let ((numbering (make-vector org-export-max-depth 0)))
1330 (org-element-map
1331 data
1332 'headline
1333 (lambda (headline)
1334 (let ((relative-level
1335 (1- (org-export-get-relative-level headline options))))
1336 (cons
1337 headline
1338 (loop for n across numbering
1339 for idx from 0 to org-export-max-depth
1340 when (< idx relative-level) collect n
1341 when (= idx relative-level) collect (aset numbering idx (1+ n))
1342 when (> idx relative-level) do (aset numbering idx 0)))))
1343 options)))
1345 (defun org-export-populate-ignore-list (data options)
1346 "Return list of elements and objects to ignore during export.
1348 DATA is the parse tree to traverse. OPTIONS is the plist holding
1349 export options.
1351 Return elements or objects to ignore as a list."
1352 (let (ignore
1353 (walk-data
1354 (function
1355 (lambda (data options selected)
1356 ;; Collect ignored elements or objects into IGNORE-LIST.
1357 (mapc
1358 (lambda (el)
1359 (if (org-export--skip-p el options selected) (push el ignore)
1360 (let ((type (org-element-type el)))
1361 (if (and (eq (plist-get info :with-archived-trees) 'headline)
1362 (eq (org-element-type el) 'headline)
1363 (org-element-property :archivedp el))
1364 ;; If headline is archived but tree below has
1365 ;; to be skipped, add it to ignore list.
1366 (mapc (lambda (e) (push e ignore))
1367 (org-element-contents el))
1368 ;; Move into recursive objects/elements.
1369 (when (or (eq type 'org-data)
1370 (memq type org-element-greater-elements)
1371 (memq type org-element-recursive-objects)
1372 (eq type 'paragraph))
1373 (funcall walk-data el options selected))))))
1374 (org-element-contents data))))))
1375 ;; Main call. First find trees containing a select tag, if any.
1376 (funcall walk-data data options (org-export--selected-trees data options))
1377 ;; Return value.
1378 ignore))
1380 (defun org-export--selected-trees (data info)
1381 "Return list of headlines containing a select tag in their tree.
1382 DATA is parsed data as returned by `org-element-parse-buffer'.
1383 INFO is a plist holding export options."
1384 (let (selected-trees
1385 (walk-data
1386 (function
1387 (lambda (data genealogy)
1388 (case (org-element-type data)
1389 (org-data
1390 (funcall walk-data (org-element-contents data) genealogy))
1391 (headline
1392 (let ((tags (org-element-property :tags headline)))
1393 (if (and tags
1394 (loop for tag in (plist-get info :select-tags)
1395 thereis (string-match
1396 (format ":%s:" tag) tags)))
1397 ;; When a select tag is found, mark as acceptable
1398 ;; full genealogy and every headline within the
1399 ;; tree.
1400 (setq selected-trees
1401 (append
1402 (cons data genealogy)
1403 (org-element-map data 'headline 'identity)
1404 selected-trees))
1405 ;; Else, continue searching in tree, recursively.
1406 (funcall walk-data data (cons data genealogy))))))))))
1407 (funcall walk-data data nil) selected-trees))
1409 (defun org-export--skip-p (blob options select-tags)
1410 "Non-nil when element or object BLOB should be skipped during export.
1411 OPTIONS is the plist holding export options."
1412 (case (org-element-type blob)
1413 ;; Check headline.
1414 (headline
1415 (let ((with-tasks (plist-get options :with-tasks))
1416 (todo (org-element-property :todo-keyword blob))
1417 (todo-type (org-element-property :todo-type blob))
1418 (archived (plist-get options :with-archived-trees))
1419 (tag-list (let ((tags (org-element-property :tags blob)))
1420 (and tags (org-split-string tags ":")))))
1422 ;; Ignore subtrees with an exclude tag.
1423 (loop for k in (plist-get options :exclude-tags)
1424 thereis (member k tag-list))
1425 ;; Ignore subtrees without a select tag, when such tag is
1426 ;; found in the buffer.
1427 (member blob select-tags)
1428 ;; Ignore commented sub-trees.
1429 (org-element-property :commentedp blob)
1430 ;; Ignore archived subtrees if `:with-archived-trees' is nil.
1431 (and (not archived) (org-element-property :archivedp blob))
1432 ;; Ignore tasks, if specified by `:with-tasks' property.
1433 (and todo
1434 (or (not with-tasks)
1435 (and (memq with-tasks '(todo done))
1436 (not (eq todo-type with-tasks)))
1437 (and (consp with-tasks) (not (member todo with-tasks))))))))
1438 ;; Check time-stamp.
1439 (time-stamp (not (plist-get options :with-timestamps)))
1440 ;; Check drawer.
1441 (drawer
1442 (or (not (plist-get options :with-drawers))
1443 (and (consp (plist-get options :with-drawers))
1444 (not (member (org-element-property :drawer-name blob)
1445 (plist-get options :with-drawers))))))))
1449 ;;; The Transcoder
1451 ;; This function reads Org data (obtained with, i.e.
1452 ;; `org-element-parse-buffer') and transcodes it into a specified
1453 ;; back-end output. It takes care of updating local properties,
1454 ;; filtering out elements or objects according to export options and
1455 ;; organizing the output blank lines and white space are preserved.
1457 ;; Though, this function is inapropriate for secondary strings, which
1458 ;; require a fresh copy of the plist passed as INFO argument. Thus,
1459 ;; `org-export-secondary-string' is provided for that specific task.
1461 ;; Internally, three functions handle the filtering of objects and
1462 ;; elements during the export. In particular,
1463 ;; `org-export-ignore-element' mark an element or object so future
1464 ;; parse tree traversals skip it, `org-export-interpret-p' tells which
1465 ;; elements or objects should be seen as real Org syntax and
1466 ;; `org-export-expand' transforms the others back into their original
1467 ;; shape.
1469 (defun org-export-data (data backend info)
1470 "Convert DATA to a string into BACKEND format.
1472 DATA is a nested list as returned by `org-element-parse-buffer'.
1474 BACKEND is a symbol among supported exporters.
1476 INFO is a plist holding export options and also used as
1477 a communication channel between elements when walking the nested
1478 list. See `org-export-update-info' function for more
1479 details.
1481 Return transcoded string."
1482 (mapconcat
1483 ;; BLOB can be an element, an object, a string, or nil.
1484 (lambda (blob)
1485 (cond
1486 ((not blob) nil)
1487 ;; BLOB is a string. Check if the optional transcoder for plain
1488 ;; text exists, and call it in that case. Otherwise, simply
1489 ;; return string. Also update INFO and call
1490 ;; `org-export-filter-plain-text-functions'.
1491 ((stringp blob)
1492 (let ((transcoder (intern (format "org-%s-plain-text" backend))))
1493 (org-export-filter-apply-functions
1494 (plist-get info :filter-plain-text)
1495 (if (fboundp transcoder) (funcall transcoder blob info) blob)
1496 backend info)))
1497 ;; BLOB is an element or an object.
1499 (let* ((type (org-element-type blob))
1500 ;; 1. Determine the appropriate TRANSCODER.
1501 (transcoder
1502 (cond
1503 ;; 1.0 A full Org document is inserted.
1504 ((eq type 'org-data) 'identity)
1505 ;; 1.1. BLOB should be ignored.
1506 ((member blob (plist-get info :ignore-list)) nil)
1507 ;; 1.2. BLOB shouldn't be transcoded. Interpret it
1508 ;; back into Org syntax.
1509 ((not (org-export-interpret-p blob info)) 'org-export-expand)
1510 ;; 1.3. Else apply naming convention.
1511 (t (let ((trans (intern (format "org-%s-%s" backend type))))
1512 (and (fboundp trans) trans)))))
1513 ;; 2. Compute CONTENTS of BLOB.
1514 (contents
1515 (cond
1516 ;; Case 0. No transcoder defined: ignore BLOB.
1517 ((not transcoder) nil)
1518 ;; Case 1. Transparently export an Org document.
1519 ((eq type 'org-data) (org-export-data blob backend info))
1520 ;; Case 2. For a recursive object.
1521 ((memq type org-element-recursive-objects)
1522 (org-export-data blob backend info))
1523 ;; Case 3. For a recursive element.
1524 ((memq type org-element-greater-elements)
1525 ;; Ignore contents of an archived tree
1526 ;; when `:with-archived-trees' is `headline'.
1527 (unless (and
1528 (eq type 'headline)
1529 (eq (plist-get info :with-archived-trees) 'headline)
1530 (org-element-property :archivedp blob))
1531 (org-element-normalize-string
1532 (org-export-data blob backend info))))
1533 ;; Case 4. For a paragraph.
1534 ((eq type 'paragraph)
1535 (let ((paragraph
1536 (org-element-normalize-contents
1537 blob
1538 ;; When normalizing contents of an item or
1539 ;; a footnote definition, ignore first line's
1540 ;; indentation: there is none and it might be
1541 ;; misleading.
1542 (and (not (org-export-get-previous-element blob info))
1543 (let ((parent (org-export-get-parent blob info)))
1544 (memq (org-element-type parent)
1545 '(footnote-definition item)))))))
1546 (org-export-data paragraph backend info)))))
1547 ;; 3. Transcode BLOB into RESULTS string.
1548 (results (cond
1549 ((not transcoder) nil)
1550 ((eq transcoder 'org-export-expand)
1551 (org-export-data
1552 `(org-data nil ,(funcall transcoder blob contents))
1553 backend info))
1554 (t (funcall transcoder blob contents info)))))
1555 ;; 4. Return results.
1556 (cond
1557 ((not results) nil)
1558 ;; No filter for a full document.
1559 ((eq type 'org-data) results)
1560 ;; Otherwise, update INFO, append the same white space
1561 ;; between elements or objects as in the original buffer,
1562 ;; and call appropriate filters.
1564 (let ((results
1565 (org-export-filter-apply-functions
1566 (plist-get info (intern (format ":filter-%s" type)))
1567 (let ((post-blank (org-element-property :post-blank blob)))
1568 (if (memq type org-element-all-elements)
1569 (concat (org-element-normalize-string results)
1570 (make-string post-blank ?\n))
1571 (concat results (make-string post-blank ? ))))
1572 backend info)))
1573 ;; Eventually return string.
1574 results)))))))
1575 (org-element-contents data) ""))
1577 (defun org-export-secondary-string (secondary backend info)
1578 "Convert SECONDARY string into BACKEND format.
1580 SECONDARY is a nested list as returned by
1581 `org-element-parse-secondary-string'.
1583 BACKEND is a symbol among supported exporters. INFO is a plist
1584 used as a communication channel.
1586 Return transcoded string."
1587 ;; Make SECONDARY acceptable for `org-export-data'.
1588 (let ((s (if (listp secondary) secondary (list secondary))))
1589 (org-export-data `(org-data nil ,@s) backend (copy-sequence info))))
1591 (defun org-export-interpret-p (blob info)
1592 "Non-nil if element or object BLOB should be interpreted as Org syntax.
1593 Check is done according to export options INFO, stored as
1594 a plist."
1595 (case (org-element-type blob)
1596 ;; ... entities...
1597 (entity (plist-get info :with-entities))
1598 ;; ... emphasis...
1599 (emphasis (plist-get info :with-emphasize))
1600 ;; ... fixed-width areas.
1601 (fixed-width (plist-get info :with-fixed-width))
1602 ;; ... footnotes...
1603 ((footnote-definition footnote-reference)
1604 (plist-get info :with-footnotes))
1605 ;; ... sub/superscripts...
1606 ((subscript superscript)
1607 (let ((sub/super-p (plist-get info :with-sub-superscript)))
1608 (if (eq sub/super-p '{})
1609 (org-element-property :use-brackets-p blob)
1610 sub/super-p)))
1611 ;; ... tables...
1612 (table (plist-get info :with-tables))
1613 (otherwise t)))
1615 (defsubst org-export-expand (blob contents)
1616 "Expand a parsed element or object to its original state.
1617 BLOB is either an element or an object. CONTENTS is its
1618 contents, as a string or nil."
1619 (funcall (intern (format "org-element-%s-interpreter" (org-element-type blob)))
1620 blob contents))
1622 (defun org-export-ignore-element (element info)
1623 "Add ELEMENT to `:ignore-list' in INFO.
1625 Any element in `:ignore-list' will be skipped when using
1626 `org-element-map'. INFO is modified by side effects."
1627 (plist-put info :ignore-list (cons element (plist-get info :ignore-list))))
1631 ;;; The Filter System
1633 ;; Filters allow end-users to tweak easily the transcoded output.
1634 ;; They are the functional counterpart of hooks, as every filter in
1635 ;; a set is applied to the return value of the previous one.
1637 ;; Every set is back-end agnostic. Although, a filter is always
1638 ;; called, in addition to the string it applies to, with the back-end
1639 ;; used as argument, so it's easy enough for the end-user to add
1640 ;; back-end specific filters in the set. The communication channel,
1641 ;; as a plist, is required as the third argument.
1643 ;; Filters sets are defined below. There are of four types:
1645 ;; - `org-export-filter-parse-tree-functions' applies directly on the
1646 ;; complete parsed tree. It's the only filters set that doesn't
1647 ;; apply to a string.
1648 ;; - `org-export-filter-final-output-functions' applies to the final
1649 ;; transcoded string.
1650 ;; - `org-export-filter-plain-text-functions' applies to any string
1651 ;; not recognized as Org syntax.
1652 ;; - `org-export-filter-TYPE-functions' applies on the string returned
1653 ;; after an element or object of type TYPE has been transcoded.
1655 ;; All filters sets are applied through
1656 ;; `org-export-filter-apply-functions' function. Filters in a set are
1657 ;; applied in a LIFO fashion. It allows developers to be sure that
1658 ;; their filters will be applied first.
1660 ;; Filters properties are installed in communication channel just
1661 ;; before parsing, with `org-export-install-filters' function.
1663 ;;;; Special Filters
1664 (defvar org-export-filter-parse-tree-functions nil
1665 "Filter, or list of filters, applied to the parsed tree.
1666 Each filter is called with three arguments: the parse tree, as
1667 returned by `org-element-parse-buffer', the back-end, as
1668 a symbol, and the communication channel, as a plist. It must
1669 return the modified parse tree to transcode.")
1671 (defvar org-export-filter-final-output-functions nil
1672 "Filter, or list of filters, applied to the transcoded string.
1673 Each filter is called with three arguments: the full transcoded
1674 string, the back-end, as a symbol, and the communication channel,
1675 as a plist. It must return a string that will be used as the
1676 final export output.")
1678 (defvar org-export-filter-plain-text-functions nil
1679 "Filter, or list of filters, applied to plain text.
1680 Each filter is called with three arguments: a string which
1681 contains no Org syntax, the back-end, as a symbol, and the
1682 communication channel, as a plist. It must return a string or
1683 nil.")
1686 ;;;; Elements Filters
1688 (defvar org-export-filter-center-block-functions nil
1689 "List of functions applied to a transcoded center block.
1690 Each filter is called with three arguments: the transcoded center
1691 block, as a string, the back-end, as a symbol, and the
1692 communication channel, as a plist. It must return a string or
1693 nil.")
1695 (defvar org-export-filter-drawer-functions nil
1696 "List of functions applied to a transcoded drawer.
1697 Each filter is called with three arguments: the transcoded
1698 drawer, as a string, the back-end, as a symbol, and the
1699 communication channel, as a plist. It must return a string or
1700 nil.")
1702 (defvar org-export-filter-dynamic-block-functions nil
1703 "List of functions applied to a transcoded dynamic-block.
1704 Each filter is called with three arguments: the transcoded
1705 dynamic-block, as a string, the back-end, as a symbol, and the
1706 communication channel, as a plist. It must return a string or
1707 nil.")
1709 (defvar org-export-filter-headline-functions nil
1710 "List of functions applied to a transcoded headline.
1711 Each filter is called with three arguments: the transcoded
1712 headline, as a string, the back-end, as a symbol, and the
1713 communication channel, as a plist. It must return a string or
1714 nil.")
1716 (defvar org-export-filter-inlinetask-functions nil
1717 "List of functions applied to a transcoded inlinetask.
1718 Each filter is called with three arguments: the transcoded
1719 inlinetask, as a string, the back-end, as a symbol, and the
1720 communication channel, as a plist. It must return a string or
1721 nil.")
1723 (defvar org-export-filter-plain-list-functions nil
1724 "List of functions applied to a transcoded plain-list.
1725 Each filter is called with three arguments: the transcoded
1726 plain-list, as a string, the back-end, as a symbol, and the
1727 communication channel, as a plist. It must return a string or
1728 nil.")
1730 (defvar org-export-filter-item-functions nil
1731 "List of functions applied to a transcoded item.
1732 Each filter is called with three arguments: the transcoded item,
1733 as a string, the back-end, as a symbol, and the communication
1734 channel, as a plist. It must return a string or nil.")
1736 (defvar org-export-filter-comment-functions nil
1737 "List of functions applied to a transcoded comment.
1738 Each filter is called with three arguments: the transcoded
1739 comment, as a string, the back-end, as a symbol, and the
1740 communication channel, as a plist. It must return a string or
1741 nil.")
1743 (defvar org-export-filter-comment-block-functions nil
1744 "List of functions applied to a transcoded comment-comment.
1745 Each filter is called with three arguments: the transcoded
1746 comment-block, as a string, the back-end, as a symbol, and the
1747 communication channel, as a plist. It must return a string or
1748 nil.")
1750 (defvar org-export-filter-example-block-functions nil
1751 "List of functions applied to a transcoded example-block.
1752 Each filter is called with three arguments: the transcoded
1753 example-block, as a string, the back-end, as a symbol, and the
1754 communication channel, as a plist. It must return a string or
1755 nil.")
1757 (defvar org-export-filter-export-block-functions nil
1758 "List of functions applied to a transcoded export-block.
1759 Each filter is called with three arguments: the transcoded
1760 export-block, as a string, the back-end, as a symbol, and the
1761 communication channel, as a plist. It must return a string or
1762 nil.")
1764 (defvar org-export-filter-fixed-width-functions nil
1765 "List of functions applied to a transcoded fixed-width.
1766 Each filter is called with three arguments: the transcoded
1767 fixed-width, as a string, the back-end, as a symbol, and the
1768 communication channel, as a plist. It must return a string or
1769 nil.")
1771 (defvar org-export-filter-footnote-definition-functions nil
1772 "List of functions applied to a transcoded footnote-definition.
1773 Each filter is called with three arguments: the transcoded
1774 footnote-definition, as a string, the back-end, as a symbol, and
1775 the communication channel, as a plist. It must return a string
1776 or nil.")
1778 (defvar org-export-filter-horizontal-rule-functions nil
1779 "List of functions applied to a transcoded horizontal-rule.
1780 Each filter is called with three arguments: the transcoded
1781 horizontal-rule, as a string, the back-end, as a symbol, and the
1782 communication channel, as a plist. It must return a string or
1783 nil.")
1785 (defvar org-export-filter-keyword-functions nil
1786 "List of functions applied to a transcoded keyword.
1787 Each filter is called with three arguments: the transcoded
1788 keyword, as a string, the back-end, as a symbol, and the
1789 communication channel, as a plist. It must return a string or
1790 nil.")
1792 (defvar org-export-filter-latex-environment-functions nil
1793 "List of functions applied to a transcoded latex-environment.
1794 Each filter is called with three arguments: the transcoded
1795 latex-environment, as a string, the back-end, as a symbol, and
1796 the communication channel, as a plist. It must return a string
1797 or nil.")
1799 (defvar org-export-filter-babel-call-functions nil
1800 "List of functions applied to a transcoded babel-call.
1801 Each filter is called with three arguments: the transcoded
1802 babel-call, as a string, the back-end, as a symbol, and the
1803 communication channel, as a plist. It must return a string or
1804 nil.")
1806 (defvar org-export-filter-paragraph-functions nil
1807 "List of functions applied to a transcoded paragraph.
1808 Each filter is called with three arguments: the transcoded
1809 paragraph, as a string, the back-end, as a symbol, and the
1810 communication channel, as a plist. It must return a string or
1811 nil.")
1813 (defvar org-export-filter-property-drawer-functions nil
1814 "List of functions applied to a transcoded property-drawer.
1815 Each filter is called with three arguments: the transcoded
1816 property-drawer, as a string, the back-end, as a symbol, and the
1817 communication channel, as a plist. It must return a string or
1818 nil.")
1820 (defvar org-export-filter-quote-block-functions nil
1821 "List of functions applied to a transcoded quote block.
1822 Each filter is called with three arguments: the transcoded quote
1823 block, as a string, the back-end, as a symbol, and the
1824 communication channel, as a plist. It must return a string or
1825 nil.")
1827 (defvar org-export-filter-quote-section-functions nil
1828 "List of functions applied to a transcoded quote-section.
1829 Each filter is called with three arguments: the transcoded
1830 quote-section, as a string, the back-end, as a symbol, and the
1831 communication channel, as a plist. It must return a string or
1832 nil.")
1834 (defvar org-export-filter-section-functions nil
1835 "List of functions applied to a transcoded section.
1836 Each filter is called with three arguments: the transcoded
1837 section, as a string, the back-end, as a symbol, and the
1838 communication channel, as a plist. It must return a string or
1839 nil.")
1841 (defvar org-export-filter-special-block-functions nil
1842 "List of functions applied to a transcoded special block.
1843 Each filter is called with three arguments: the transcoded
1844 special block, as a string, the back-end, as a symbol, and the
1845 communication channel, as a plist. It must return a string or
1846 nil.")
1848 (defvar org-export-filter-src-block-functions nil
1849 "List of functions applied to a transcoded src-block.
1850 Each filter is called with three arguments: the transcoded
1851 src-block, as a string, the back-end, as a symbol, and the
1852 communication channel, as a plist. It must return a string or
1853 nil.")
1855 (defvar org-export-filter-table-functions nil
1856 "List of functions applied to a transcoded table.
1857 Each filter is called with three arguments: the transcoded table,
1858 as a string, the back-end, as a symbol, and the communication
1859 channel, as a plist. It must return a string or nil.")
1861 (defvar org-export-filter-verse-block-functions nil
1862 "List of functions applied to a transcoded verse block.
1863 Each filter is called with three arguments: the transcoded verse
1864 block, as a string, the back-end, as a symbol, and the
1865 communication channel, as a plist. It must return a string or
1866 nil.")
1869 ;;;; Objects Filters
1871 (defvar org-export-filter-emphasis-functions nil
1872 "List of functions applied to a transcoded emphasis.
1873 Each filter is called with three arguments: the transcoded
1874 emphasis, as a string, the back-end, as a symbol, and the
1875 communication channel, as a plist. It must return a string or
1876 nil.")
1878 (defvar org-export-filter-entity-functions nil
1879 "List of functions applied to a transcoded entity.
1880 Each filter is called with three arguments: the transcoded
1881 entity, as a string, the back-end, as a symbol, and the
1882 communication channel, as a plist. It must return a string or
1883 nil.")
1885 (defvar org-export-filter-export-snippet-functions nil
1886 "List of functions applied to a transcoded export-snippet.
1887 Each filter is called with three arguments: the transcoded
1888 export-snippet, as a string, the back-end, as a symbol, and the
1889 communication channel, as a plist. It must return a string or
1890 nil.")
1892 (defvar org-export-filter-footnote-reference-functions nil
1893 "List of functions applied to a transcoded footnote-reference.
1894 Each filter is called with three arguments: the transcoded
1895 footnote-reference, as a string, the back-end, as a symbol, and
1896 the communication channel, as a plist. It must return a string
1897 or nil.")
1899 (defvar org-export-filter-inline-babel-call-functions nil
1900 "List of functions applied to a transcoded inline-babel-call.
1901 Each filter is called with three arguments: the transcoded
1902 inline-babel-call, as a string, the back-end, as a symbol, and
1903 the communication channel, as a plist. It must return a string
1904 or nil.")
1906 (defvar org-export-filter-inline-src-block-functions nil
1907 "List of functions applied to a transcoded inline-src-block.
1908 Each filter is called with three arguments: the transcoded
1909 inline-src-block, as a string, the back-end, as a symbol, and the
1910 communication channel, as a plist. It must return a string or
1911 nil.")
1913 (defvar org-export-filter-latex-fragment-functions nil
1914 "List of functions applied to a transcoded latex-fragment.
1915 Each filter is called with three arguments: the transcoded
1916 latex-fragment, as a string, the back-end, as a symbol, and the
1917 communication channel, as a plist. It must return a string or
1918 nil.")
1920 (defvar org-export-filter-line-break-functions nil
1921 "List of functions applied to a transcoded line-break.
1922 Each filter is called with three arguments: the transcoded
1923 line-break, as a string, the back-end, as a symbol, and the
1924 communication channel, as a plist. It must return a string or
1925 nil.")
1927 (defvar org-export-filter-link-functions nil
1928 "List of functions applied to a transcoded link.
1929 Each filter is called with three arguments: the transcoded link,
1930 as a string, the back-end, as a symbol, and the communication
1931 channel, as a plist. It must return a string or nil.")
1933 (defvar org-export-filter-macro-functions nil
1934 "List of functions applied to a transcoded macro.
1935 Each filter is called with three arguments: the transcoded macro,
1936 as a string, the back-end, as a symbol, and the communication
1937 channel, as a plist. It must return a string or nil.")
1939 (defvar org-export-filter-radio-target-functions nil
1940 "List of functions applied to a transcoded radio-target.
1941 Each filter is called with three arguments: the transcoded
1942 radio-target, as a string, the back-end, as a symbol, and the
1943 communication channel, as a plist. It must return a string or
1944 nil.")
1946 (defvar org-export-filter-statistics-cookie-functions nil
1947 "List of functions applied to a transcoded statistics-cookie.
1948 Each filter is called with three arguments: the transcoded
1949 statistics-cookie, as a string, the back-end, as a symbol, and
1950 the communication channel, as a plist. It must return a string
1951 or nil.")
1953 (defvar org-export-filter-subscript-functions nil
1954 "List of functions applied to a transcoded subscript.
1955 Each filter is called with three arguments: the transcoded
1956 subscript, as a string, the back-end, as a symbol, and the
1957 communication channel, as a plist. It must return a string or
1958 nil.")
1960 (defvar org-export-filter-superscript-functions nil
1961 "List of functions applied to a transcoded superscript.
1962 Each filter is called with three arguments: the transcoded
1963 superscript, as a string, the back-end, as a symbol, and the
1964 communication channel, as a plist. It must return a string or
1965 nil.")
1967 (defvar org-export-filter-target-functions nil
1968 "List of functions applied to a transcoded target.
1969 Each filter is called with three arguments: the transcoded
1970 target, as a string, the back-end, as a symbol, and the
1971 communication channel, as a plist. It must return a string or
1972 nil.")
1974 (defvar org-export-filter-time-stamp-functions nil
1975 "List of functions applied to a transcoded time-stamp.
1976 Each filter is called with three arguments: the transcoded
1977 time-stamp, as a string, the back-end, as a symbol, and the
1978 communication channel, as a plist. It must return a string or
1979 nil.")
1981 (defvar org-export-filter-verbatim-functions nil
1982 "List of functions applied to a transcoded verbatim.
1983 Each filter is called with three arguments: the transcoded
1984 verbatim, as a string, the back-end, as a symbol, and the
1985 communication channel, as a plist. It must return a string or
1986 nil.")
1988 (defun org-export-filter-apply-functions (filters value backend info)
1989 "Call every function in FILTERS with arguments VALUE, BACKEND and INFO.
1990 Functions are called in a LIFO fashion, to be sure that developer
1991 specified filters, if any, are called first."
1992 (loop for filter in filters
1993 if (not value) return nil else
1994 do (setq value (funcall filter value backend info)))
1995 value)
1997 (defun org-export-install-filters (backend info)
1998 "Install filters properties in communication channel.
2000 BACKEND is a symbol specifying which back-end specific filters to
2001 install, if any. INFO is a plist containing the current
2002 communication channel.
2004 Return the updated communication channel."
2005 (let (plist)
2006 ;; Install user defined filters with `org-export-filters-alist'.
2007 (mapc (lambda (p)
2008 (setq plist (plist-put plist (car p) (eval (cdr p)))))
2009 org-export-filters-alist)
2010 ;; Prepend back-end specific filters to that list.
2011 (let ((back-end-filters (intern (format "org-%s-filters-alist" backend))))
2012 (when (boundp back-end-filters)
2013 (mapc (lambda (p)
2014 ;; Single values get consed, lists are prepended.
2015 (let ((key (car p)) (value (cdr p)))
2016 (when value
2017 (setq plist
2018 (plist-put
2019 plist key
2020 (if (atom value) (cons value (plist-get plist key))
2021 (append value (plist-get plist key))))))))
2022 (eval back-end-filters))))
2023 ;; Return new communication channel.
2024 (org-combine-plists info plist)))
2028 ;;; Core functions
2030 ;; This is the room for the main function, `org-export-as', along with
2031 ;; its derivatives, `org-export-to-buffer' and `org-export-to-file'.
2032 ;; They differ only by the way they output the resulting code.
2034 ;; `org-export-output-file-name' is an auxiliary function meant to be
2035 ;; used with `org-export-to-file'. With a given extension, it tries
2036 ;; to provide a canonical file name to write export output to.
2038 ;; Note that `org-export-as' doesn't really parse the current buffer,
2039 ;; but a copy of it (with the same buffer-local variables and
2040 ;; visibility), where include keywords are expanded and Babel blocks
2041 ;; are executed, if appropriate.
2042 ;; `org-export-with-current-buffer-copy' macro prepares that copy.
2044 ;; File inclusion is taken care of by
2045 ;; `org-export-expand-include-keyword' and
2046 ;; `org-export-prepare-file-contents'. Structure wise, including
2047 ;; a whole Org file in a buffer often makes little sense. For
2048 ;; example, if the file contains an headline and the include keyword
2049 ;; was within an item, the item should contain the headline. That's
2050 ;; why file inclusion should be done before any structure can be
2051 ;; associated to the file, that is before parsing.
2053 (defun org-export-as
2054 (backend &optional subtreep visible-only body-only ext-plist noexpand)
2055 "Transcode current Org buffer into BACKEND code.
2057 If narrowing is active in the current buffer, only transcode its
2058 narrowed part.
2060 If a region is active, transcode that region.
2062 When optional argument SUBTREEP is non-nil, transcode the
2063 sub-tree at point, extracting information from the headline
2064 properties first.
2066 When optional argument VISIBLE-ONLY is non-nil, don't export
2067 contents of hidden elements.
2069 When optional argument BODY-ONLY is non-nil, only return body
2070 code, without preamble nor postamble.
2072 Optional argument EXT-PLIST, when provided, is a property list
2073 with external parameters overriding Org default settings, but
2074 still inferior to file-local settings.
2076 Optional argument NOEXPAND, when non-nil, prevents included files
2077 to be expanded and Babel code to be executed.
2079 Return code as a string."
2080 (save-excursion
2081 (save-restriction
2082 ;; Narrow buffer to an appropriate region for parsing.
2083 (cond ((org-region-active-p)
2084 (narrow-to-region (region-beginning) (region-end)))
2085 (subtreep (org-narrow-to-subtree)))
2086 ;; Retrieve export options (INFO) and parsed tree (RAW-DATA),
2087 ;; Then options can be completed with tree properties. Note:
2088 ;; Buffer isn't parsed directly. Instead, a temporary copy is
2089 ;; created, where include keywords are expanded and code blocks
2090 ;; are evaluated. RAW-DATA is the parsed tree of the buffer
2091 ;; resulting from that process. Eventually call
2092 ;; `org-export-filter-parse-tree-functions'.
2093 (goto-char (point-min))
2094 (let ((info (org-export-get-environment backend subtreep ext-plist)))
2095 ;; Remove subtree's headline from contents if subtree mode is
2096 ;; activated.
2097 (when subtreep (forward-line) (narrow-to-region (point) (point-max)))
2098 ;; Install filters in communication channel.
2099 (setq info (org-export-install-filters backend info))
2100 (let ((raw-data
2101 (org-export-filter-apply-functions
2102 (plist-get info :filter-parse-tree)
2103 ;; If NOEXPAND is non-nil, simply parse current
2104 ;; visible part of buffer.
2105 (if noexpand (org-element-parse-buffer nil visible-only)
2106 (org-export-with-current-buffer-copy
2107 (org-export-expand-include-keyword)
2108 (let ((org-current-export-file (current-buffer)))
2109 (org-export-blocks-preprocess))
2110 (org-element-parse-buffer nil visible-only)))
2111 backend info)))
2112 ;; Complete communication channel with tree properties.
2113 (setq info
2114 (org-combine-plists
2115 info
2116 (org-export-collect-tree-properties raw-data info backend)))
2117 ;; Transcode RAW-DATA. Also call
2118 ;; `org-export-filter-final-output-functions'.
2119 (let* ((body (org-element-normalize-string
2120 (org-export-data raw-data backend info)))
2121 (template (intern (format "org-%s-template" backend)))
2122 (output (org-export-filter-apply-functions
2123 (plist-get info :filter-final-output)
2124 (if (or (not (fboundp template)) body-only) body
2125 (funcall template body info))
2126 backend info)))
2127 ;; Maybe add final OUTPUT to kill ring before returning it.
2128 (when org-export-copy-to-kill-ring (org-kill-new output))
2129 output))))))
2131 (defun org-export-to-buffer
2132 (backend buffer &optional subtreep visible-only body-only ext-plist noexpand)
2133 "Call `org-export-as' with output to a specified buffer.
2135 BACKEND is the back-end used for transcoding, as a symbol.
2137 BUFFER is the output buffer. If it already exists, it will be
2138 erased first, otherwise, it will be created.
2140 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY, EXT-PLIST
2141 and NOEXPAND are similar to those used in `org-export-as', which
2142 see.
2144 Return buffer."
2145 (let ((out (org-export-as
2146 backend subtreep visible-only body-only ext-plist noexpand))
2147 (buffer (get-buffer-create buffer)))
2148 (with-current-buffer buffer
2149 (erase-buffer)
2150 (insert out)
2151 (goto-char (point-min)))
2152 buffer))
2154 (defun org-export-to-file
2155 (backend file &optional subtreep visible-only body-only ext-plist noexpand)
2156 "Call `org-export-as' with output to a specified file.
2158 BACKEND is the back-end used for transcoding, as a symbol. FILE
2159 is the name of the output file, as a string.
2161 Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY, EXT-PLIST
2162 and NOEXPAND are similar to those used in `org-export-as', which
2163 see.
2165 Return output file's name."
2166 ;; Checks for FILE permissions. `write-file' would do the same, but
2167 ;; we'd rather avoid needless transcoding of parse tree.
2168 (unless (file-writable-p file) (error "Output file not writable"))
2169 ;; Insert contents to a temporary buffer and write it to FILE.
2170 (let ((out (org-export-as
2171 backend subtreep visible-only body-only ext-plist noexpand)))
2172 (with-temp-buffer
2173 (insert out)
2174 (let ((coding-system-for-write org-export-coding-system))
2175 (write-file file))))
2176 ;; Return full path.
2177 file)
2179 (defun org-export-output-file-name (extension &optional subtreep pub-dir)
2180 "Return output file's name according to buffer specifications.
2182 EXTENSION is a string representing the output file extension,
2183 with the leading dot.
2185 With a non-nil optional argument SUBTREEP, try to determine
2186 output file's name by looking for \"EXPORT_FILE_NAME\" property
2187 of subtree at point.
2189 When optional argument PUB-DIR is set, use it as the publishing
2190 directory.
2192 Return file name as a string, or nil if it couldn't be
2193 determined."
2194 (let ((base-name
2195 ;; File name may come from EXPORT_FILE_NAME subtree property,
2196 ;; assuming point is at beginning of said sub-tree.
2197 (file-name-sans-extension
2198 (or (and subtreep
2199 (org-entry-get
2200 (save-excursion
2201 (ignore-errors
2202 (org-back-to-heading (not visible-only)) (point)))
2203 "EXPORT_FILE_NAME" t))
2204 ;; File name may be extracted from buffer's associated
2205 ;; file, if any.
2206 (buffer-file-name (buffer-base-buffer))
2207 ;; Can't determine file name on our own: Ask user.
2208 (let ((read-file-name-function
2209 (and org-completion-use-ido 'ido-read-file-name)))
2210 (read-file-name
2211 "Output file: " pub-dir nil nil nil
2212 (lambda (name)
2213 (string= (file-name-extension name t) extension))))))))
2214 ;; Build file name. Enforce EXTENSION over whatever user may have
2215 ;; come up with. PUB-DIR, if defined, always has precedence over
2216 ;; any provided path.
2217 (cond
2218 (pub-dir
2219 (concat (file-name-as-directory pub-dir)
2220 (file-name-nondirectory base-name)
2221 extension))
2222 ((string= (file-name-nondirectory base-name) base-name)
2223 (concat (file-name-as-directory ".") base-name extension))
2224 (t (concat base-name extension)))))
2226 (defmacro org-export-with-current-buffer-copy (&rest body)
2227 "Apply BODY in a copy of the current buffer.
2229 The copy preserves local variables and visibility of the original
2230 buffer.
2232 Point is at buffer's beginning when BODY is applied."
2233 (org-with-gensyms (original-buffer offset buffer-string overlays)
2234 `(let ((,original-buffer ,(current-buffer))
2235 (,offset ,(1- (point-min)))
2236 (,buffer-string ,(buffer-string))
2237 (,overlays (mapcar
2238 'copy-overlay (overlays-in (point-min) (point-max)))))
2239 (with-temp-buffer
2240 (let ((buffer-invisibility-spec nil))
2241 (org-clone-local-variables
2242 ,original-buffer
2243 "^\\(org-\\|orgtbl-\\|major-mode$\\|outline-\\(regexp\\|level\\)$\\)")
2244 (insert ,buffer-string)
2245 (mapc (lambda (ov)
2246 (move-overlay
2248 (- (overlay-start ov) ,offset)
2249 (- (overlay-end ov) ,offset)
2250 (current-buffer)))
2251 ,overlays)
2252 (goto-char (point-min))
2253 (progn ,@body))))))
2254 (def-edebug-spec org-export-with-current-buffer-copy (body))
2256 (defun org-export-expand-include-keyword (&optional included dir)
2257 "Expand every include keyword in buffer.
2258 Optional argument INCLUDED is a list of included file names along
2259 with their line restriction, when appropriate. It is used to
2260 avoid infinite recursion. Optional argument DIR is the current
2261 working directory. It is used to properly resolve relative
2262 paths."
2263 (let ((case-fold-search t))
2264 (goto-char (point-min))
2265 (while (re-search-forward "^[ \t]*#\\+INCLUDE: \\(.*\\)" nil t)
2266 (when (eq (org-element-type (save-match-data (org-element-at-point)))
2267 'keyword)
2268 (beginning-of-line)
2269 ;; Extract arguments from keyword's value.
2270 (let* ((value (match-string 1))
2271 (ind (org-get-indentation))
2272 (file (and (string-match "^\"\\(\\S-+\\)\"" value)
2273 (prog1 (expand-file-name (match-string 1 value) dir)
2274 (setq value (replace-match "" nil nil value)))))
2275 (lines
2276 (and (string-match
2277 ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\"" value)
2278 (prog1 (match-string 1 value)
2279 (setq value (replace-match "" nil nil value)))))
2280 (env (cond ((string-match "\\<example\\>" value) 'example)
2281 ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
2282 (match-string 1 value))))
2283 ;; Minimal level of included file defaults to the child
2284 ;; level of the current headline, if any, or one. It
2285 ;; only applies is the file is meant to be included as
2286 ;; an Org one.
2287 (minlevel
2288 (and (not env)
2289 (if (string-match ":minlevel +\\([0-9]+\\)" value)
2290 (prog1 (string-to-number (match-string 1 value))
2291 (setq value (replace-match "" nil nil value)))
2292 (let ((cur (org-current-level)))
2293 (if cur (1+ (org-reduced-level cur)) 1))))))
2294 ;; Remove keyword.
2295 (delete-region (point) (progn (forward-line) (point)))
2296 (cond
2297 ((not (file-readable-p file)) (error "Cannot include file %s" file))
2298 ;; Check if files has already been parsed. Look after
2299 ;; inclusion lines too, as different parts of the same file
2300 ;; can be included too.
2301 ((member (list file lines) included)
2302 (error "Recursive file inclusion: %s" file))
2304 (cond
2305 ((eq env 'example)
2306 (insert
2307 (let ((ind-str (make-string ind ? ))
2308 (contents
2309 ;; Protect sensitive contents with commas.
2310 (replace-regexp-in-string
2311 "\\(^\\)\\([*]\\|[ \t]*#\\+\\)" ","
2312 (org-export-prepare-file-contents file lines)
2313 nil nil 1)))
2314 (format "%s#+BEGIN_EXAMPLE\n%s%s#+END_EXAMPLE\n"
2315 ind-str contents ind-str))))
2316 ((stringp env)
2317 (insert
2318 (let ((ind-str (make-string ind ? ))
2319 (contents
2320 ;; Protect sensitive contents with commas.
2321 (replace-regexp-in-string
2322 (if (string= env "org") "\\(^\\)\\(.\\)"
2323 "\\(^\\)\\([*]\\|[ \t]*#\\+\\)") ","
2324 (org-export-prepare-file-contents file lines)
2325 nil nil 1)))
2326 (format "%s#+BEGIN_SRC %s\n%s%s#+END_SRC\n"
2327 ind-str env contents ind-str))))
2329 (insert
2330 (with-temp-buffer
2331 (org-mode)
2332 (insert
2333 (org-export-prepare-file-contents file lines ind minlevel))
2334 (org-export-expand-include-keyword
2335 (cons (list file lines) included)
2336 (file-name-directory file))
2337 (buffer-string))))))))))))
2339 (defun org-export-prepare-file-contents (file &optional lines ind minlevel)
2340 "Prepare the contents of FILE for inclusion and return them as a string.
2342 When optional argument LINES is a string specifying a range of
2343 lines, include only those lines.
2345 Optional argument IND, when non-nil, is an integer specifying the
2346 global indentation of returned contents. Since its purpose is to
2347 allow an included file to stay in the same environment it was
2348 created \(i.e. a list item), it doesn't apply past the first
2349 headline encountered.
2351 Optional argument MINLEVEL, when non-nil, is an integer
2352 specifying the level that any top-level headline in the included
2353 file should have."
2354 (with-temp-buffer
2355 (insert-file-contents file)
2356 (when lines
2357 (let* ((lines (split-string lines "-"))
2358 (lbeg (string-to-number (car lines)))
2359 (lend (string-to-number (cadr lines)))
2360 (beg (if (zerop lbeg) (point-min)
2361 (goto-char (point-min))
2362 (forward-line (1- lbeg))
2363 (point)))
2364 (end (if (zerop lend) (point-max)
2365 (goto-char (point-min))
2366 (forward-line (1- lend))
2367 (point))))
2368 (narrow-to-region beg end)))
2369 ;; Remove blank lines at beginning and end of contents. The logic
2370 ;; behind that removal is that blank lines around include keyword
2371 ;; override blank lines in included file.
2372 (goto-char (point-min))
2373 (org-skip-whitespace)
2374 (beginning-of-line)
2375 (delete-region (point-min) (point))
2376 (goto-char (point-max))
2377 (skip-chars-backward " \r\t\n")
2378 (forward-line)
2379 (delete-region (point) (point-max))
2380 ;; If IND is set, preserve indentation of include keyword until
2381 ;; the first headline encountered.
2382 (when ind
2383 (unless (eq major-mode 'org-mode) (org-mode))
2384 (goto-char (point-min))
2385 (let ((ind-str (make-string ind ? )))
2386 (while (not (or (eobp) (looking-at org-outline-regexp-bol)))
2387 ;; Do not move footnote definitions out of column 0.
2388 (unless (and (looking-at org-footnote-definition-re)
2389 (eq (org-element-type (org-element-at-point))
2390 'footnote-definition))
2391 (insert ind-str))
2392 (forward-line))))
2393 ;; When MINLEVEL is specified, compute minimal level for headlines
2394 ;; in the file (CUR-MIN), and remove stars to each headline so
2395 ;; that headlines with minimal level have a level of MINLEVEL.
2396 (when minlevel
2397 (unless (eq major-mode 'org-mode) (org-mode))
2398 (let ((levels (org-map-entries
2399 (lambda () (org-reduced-level (org-current-level))))))
2400 (when levels
2401 (let ((offset (- minlevel (apply 'min levels))))
2402 (unless (zerop offset)
2403 (when org-odd-levels-only (setq offset (* offset 2)))
2404 ;; Only change stars, don't bother moving whole
2405 ;; sections.
2406 (org-map-entries
2407 (lambda () (if (< offset 0) (delete-char (abs offset))
2408 (insert (make-string offset ?*))))))))))
2409 (buffer-string)))
2412 ;;; Tools For Back-Ends
2414 ;; A whole set of tools is available to help build new exporters. Any
2415 ;; function general enough to have its use across many back-ends
2416 ;; should be added here.
2418 ;; As of now, functions operating on footnotes, headlines, links,
2419 ;; macros, references, src-blocks, tables and tables of contents are
2420 ;; implemented.
2422 ;;;; For Export Snippets
2424 ;; Every export snippet is transmitted to the back-end. Though, the
2425 ;; latter will only retain one type of export-snippet, ignoring
2426 ;; others, based on the former's target back-end. The function
2427 ;; `org-export-snippet-backend' returns that back-end for a given
2428 ;; export-snippet.
2430 (defun org-export-snippet-backend (export-snippet)
2431 "Return EXPORT-SNIPPET targeted back-end as a symbol.
2432 Translation, with `org-export-snippet-translation-alist', is
2433 applied."
2434 (let ((back-end (org-element-property :back-end export-snippet)))
2435 (intern
2436 (or (cdr (assoc back-end org-export-snippet-translation-alist))
2437 back-end))))
2440 ;;;; For Footnotes
2442 ;; `org-export-collect-footnote-definitions' is a tool to list
2443 ;; actually used footnotes definitions in the whole parse tree, or in
2444 ;; an headline, in order to add footnote listings throughout the
2445 ;; transcoded data.
2447 ;; `org-export-footnote-first-reference-p' is a predicate used by some
2448 ;; back-ends, when they need to attach the footnote definition only to
2449 ;; the first occurrence of the corresponding label.
2451 ;; `org-export-get-footnote-definition' and
2452 ;; `org-export-get-footnote-number' provide easier access to
2453 ;; additional information relative to a footnote reference.
2455 (defun org-export-collect-footnote-definitions (data info)
2456 "Return an alist between footnote numbers, labels and definitions.
2458 DATA is the parse tree from which definitions are collected.
2459 INFO is the plist used as a communication channel.
2461 Definitions are sorted by order of references. They either
2462 appear as Org data (transcoded with `org-export-data') or as
2463 a secondary string for inlined footnotes (transcoded with
2464 `org-export-secondary-string'). Unreferenced definitions are
2465 ignored."
2466 (let (num-alist
2467 (collect-fn
2468 (function
2469 (lambda (data)
2470 ;; Collect footnote number, label and definition in DATA.
2471 (org-element-map
2472 data 'footnote-reference
2473 (lambda (fn)
2474 (when (org-export-footnote-first-reference-p fn info)
2475 (let ((def (org-export-get-footnote-definition fn info)))
2476 (push
2477 (list (org-export-get-footnote-number fn info)
2478 (org-element-property :label fn)
2479 def)
2480 num-alist)
2481 ;; Also search in definition for nested footnotes.
2482 (when (eq (org-element-property :type fn) 'standard)
2483 (funcall collect-fn def)))))
2484 ;; Don't enter footnote definitions since it will happen
2485 ;; when their first reference is found.
2486 info nil 'footnote-definition)))))
2487 (funcall collect-fn (plist-get info :parse-tree))
2488 (reverse num-alist)))
2490 (defun org-export-footnote-first-reference-p (footnote-reference info)
2491 "Non-nil when a footnote reference is the first one for its label.
2493 FOOTNOTE-REFERENCE is the footnote reference being considered.
2494 INFO is the plist used as a communication channel."
2495 (let ((label (org-element-property :label footnote-reference)))
2496 ;; Anonymous footnotes are always a first reference.
2497 (if (not label) t
2498 ;; Otherwise, return the first footnote with the same LABEL and
2499 ;; test if it is equal to FOOTNOTE-REFERENCE.
2500 (let ((search-refs
2501 (function
2502 (lambda (data)
2503 (org-element-map
2504 data 'footnote-reference
2505 (lambda (fn)
2506 (cond
2507 ((string= (org-element-property :label fn) label)
2508 (throw 'exit fn))
2509 ;; If FN isn't inlined, be sure to traverse its
2510 ;; definition before resuming search. See
2511 ;; comments in `org-export-get-footnote-number'
2512 ;; for more information.
2513 ((eq (org-element-property :type fn) 'standard)
2514 (funcall search-refs
2515 (org-export-get-footnote-definition fn info)))))
2516 ;; Don't enter footnote definitions since it will
2517 ;; happen when their first reference is found.
2518 info 'first-match 'footnote-definition)))))
2519 (equal (catch 'exit (funcall search-refs (plist-get info :parse-tree)))
2520 footnote-reference)))))
2522 (defun org-export-get-footnote-definition (footnote-reference info)
2523 "Return definition of FOOTNOTE-REFERENCE as parsed data.
2524 INFO is the plist used as a communication channel."
2525 (let ((label (org-element-property :label footnote-reference)))
2526 (or (org-element-property :inline-definition footnote-reference)
2527 (cdr (assoc label (plist-get info :footnote-definition-alist))))))
2529 (defun org-export-get-footnote-number (footnote info)
2530 "Return number associated to a footnote.
2532 FOOTNOTE is either a footnote reference or a footnote definition.
2533 INFO is the plist used as a communication channel."
2534 (let ((label (org-element-property :label footnote))
2535 seen-refs
2536 (search-ref
2537 (function
2538 (lambda (data)
2539 ;; Search footnote references through DATA, filling
2540 ;; SEEN-REFS along the way.
2541 (org-element-map
2542 data 'footnote-reference
2543 (lambda (fn)
2544 (let ((fn-lbl (org-element-property :label fn)))
2545 (cond
2546 ;; Anonymous footnote match: return number.
2547 ((and (not fn-lbl) (equal fn footnote))
2548 (throw 'exit (1+ (length seen-refs))))
2549 ;; Labels match: return number.
2550 ((and label (string= label fn-lbl))
2551 (throw 'exit (1+ (length seen-refs))))
2552 ;; Anonymous footnote: it's always a new one. Also,
2553 ;; be sure to return nil from the `cond' so
2554 ;; `first-match' doesn't get us out of the loop.
2555 ((not fn-lbl) (push 'inline seen-refs) nil)
2556 ;; Label not seen so far: add it so SEEN-REFS.
2558 ;; Also search for subsequent references in footnote
2559 ;; definition so numbering following reading logic.
2560 ;; Note that we don't have to care about inline
2561 ;; definitions, since `org-element-map' already
2562 ;; traverse them at the right time.
2564 ;; Once again, return nil to stay in the loop.
2565 ((not (member fn-lbl seen-refs))
2566 (push fn-lbl seen-refs)
2567 (funcall search-ref
2568 (org-export-get-footnote-definition fn info))
2569 nil))))
2570 ;; Don't enter footnote definitions since it will happen
2571 ;; when their first reference is found.
2572 info 'first-match 'footnote-definition)))))
2573 (catch 'exit (funcall search-ref (plist-get info :parse-tree)))))
2576 ;;;; For Headlines
2578 ;; `org-export-get-relative-level' is a shortcut to get headline
2579 ;; level, relatively to the lower headline level in the parsed tree.
2581 ;; `org-export-get-headline-number' returns the section number of an
2582 ;; headline, while `org-export-number-to-roman' allows to convert it
2583 ;; to roman numbers.
2585 ;; `org-export-low-level-p', `org-export-first-sibling-p' and
2586 ;; `org-export-last-sibling-p' are three useful predicates when it
2587 ;; comes to fulfill the `:headline-levels' property.
2589 (defun org-export-get-relative-level (headline info)
2590 "Return HEADLINE relative level within current parsed tree.
2591 INFO is a plist holding contextual information."
2592 (+ (org-element-property :level headline)
2593 (or (plist-get info :headline-offset) 0)))
2595 (defun org-export-low-level-p (headline info)
2596 "Non-nil when HEADLINE is considered as low level.
2598 INFO is a plist used as a communication channel.
2600 A low level headlines has a relative level greater than
2601 `:headline-levels' property value.
2603 Return value is the difference between HEADLINE relative level
2604 and the last level being considered as high enough, or nil."
2605 (let ((limit (plist-get info :headline-levels)))
2606 (when (wholenump limit)
2607 (let ((level (org-export-get-relative-level headline info)))
2608 (and (> level limit) (- level limit))))))
2610 (defun org-export-get-headline-number (headline info)
2611 "Return HEADLINE numbering as a list of numbers.
2612 INFO is a plist holding contextual information."
2613 (cdr (assoc headline (plist-get info :headline-numbering))))
2615 (defun org-export-numbered-headline-p (headline info)
2616 "Return a non-nil value if HEADLINE element should be numbered.
2617 INFO is a plist used as a communication channel."
2618 (let ((sec-num (plist-get info :section-numbers))
2619 (level (org-export-get-relative-level headline info)))
2620 (if (wholenump sec-num) (<= level sec-num) sec-num)))
2622 (defun org-export-number-to-roman (n)
2623 "Convert integer N into a roman numeral."
2624 (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
2625 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
2626 ( 10 . "X") ( 9 . "IX") ( 5 . "V") ( 4 . "IV")
2627 ( 1 . "I")))
2628 (res ""))
2629 (if (<= n 0)
2630 (number-to-string n)
2631 (while roman
2632 (if (>= n (caar roman))
2633 (setq n (- n (caar roman))
2634 res (concat res (cdar roman)))
2635 (pop roman)))
2636 res)))
2638 (defun org-export-first-sibling-p (headline info)
2639 "Non-nil when HEADLINE is the first sibling in its sub-tree.
2640 INFO is the plist used as a communication channel."
2641 (not (eq (org-element-type (org-export-get-previous-element headline info))
2642 'headline)))
2644 (defun org-export-last-sibling-p (headline info)
2645 "Non-nil when HEADLINE is the last sibling in its sub-tree.
2646 INFO is the plist used as a communication channel."
2647 (not (org-export-get-next-element headline info)))
2650 ;;;; For Links
2652 ;; `org-export-solidify-link-text' turns a string into a safer version
2653 ;; for links, replacing most non-standard characters with hyphens.
2655 ;; `org-export-get-coderef-format' returns an appropriate format
2656 ;; string for coderefs.
2658 ;; `org-export-inline-image-p' returns a non-nil value when the link
2659 ;; provided should be considered as an inline image.
2661 ;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
2662 ;; (i.e. links with "fuzzy" as type) within the parsed tree, and
2663 ;; returns an appropriate unique identifier when found, or nil.
2665 ;; `org-export-resolve-id-link' returns the first headline with
2666 ;; specified id or custom-id in parse tree, or nil when none was
2667 ;; found.
2669 ;; `org-export-resolve-coderef' associates a reference to a line
2670 ;; number in the element it belongs, or returns the reference itself
2671 ;; when the element isn't numbered.
2673 (defun org-export-solidify-link-text (s)
2674 "Take link text S and make a safe target out of it."
2675 (save-match-data
2676 (mapconcat 'identity (org-split-string s "[^a-zA-Z0-9_.-]+") "-")))
2678 (defun org-export-get-coderef-format (path desc)
2679 "Return format string for code reference link.
2680 PATH is the link path. DESC is its description."
2681 (save-match-data
2682 (cond ((string-match (regexp-quote (concat "(" path ")")) desc)
2683 (replace-match "%s" t t desc))
2684 ((string= desc "") "%s")
2685 (t desc))))
2687 (defun org-export-inline-image-p (link &optional rules)
2688 "Non-nil if LINK object points to an inline image.
2690 Optional argument is a set of RULES defining inline images. It
2691 is an alist where associations have the following shape:
2693 \(TYPE . REGEXP)
2695 Applying a rule means apply REGEXP against LINK's path when its
2696 type is TYPE. The function will return a non-nil value if any of
2697 the provided rules is non-nil. The default rule is
2698 `org-export-default-inline-image-rule'.
2700 This only applies to links without a description."
2701 (and (not (org-element-contents link))
2702 (let ((case-fold-search t)
2703 (rules (or rules org-export-default-inline-image-rule)))
2704 (some
2705 (lambda (rule)
2706 (and (string= (org-element-property :type link) (car rule))
2707 (string-match (cdr rule)
2708 (org-element-property :path link))))
2709 rules))))
2711 (defun org-export-resolve-fuzzy-link (link info)
2712 "Return LINK destination.
2714 INFO is a plist holding contextual information.
2716 Return value can be an object, an element, or nil:
2718 - If LINK path matches a target object (i.e. <<path>>) or
2719 element (i.e. \"#+target: path\"), return it.
2721 - If LINK path exactly matches the name affiliated keyword
2722 \(i.e. #+name: path) of an element, return that element.
2724 - If LINK path exactly matches any headline name, return that
2725 element. If more than one headline share that name, priority
2726 will be given to the one with the closest common ancestor, if
2727 any, or the first one in the parse tree otherwise.
2729 - Otherwise, return nil.
2731 Assume LINK type is \"fuzzy\"."
2732 (let ((path (org-element-property :path link)))
2733 (cond
2734 ;; First try to find a matching "<<path>>" unless user specified
2735 ;; he was looking for an headline (path starts with a *
2736 ;; character).
2737 ((and (not (eq (substring path 0 1) ?*))
2738 (loop for target in (plist-get info :target-list)
2739 when (string= (org-element-property :value target) path)
2740 return target)))
2741 ;; Then try to find an element with a matching "#+name: path"
2742 ;; affiliated keyword.
2743 ((and (not (eq (substring path 0 1) ?*))
2744 (org-element-map
2745 (plist-get info :parse-tree) org-element-all-elements
2746 (lambda (el)
2747 (when (string= (org-element-property :name el) path) el))
2748 info 'first-match)))
2749 ;; Last case: link either points to an headline or to
2750 ;; nothingness. Try to find the source, with priority given to
2751 ;; headlines with the closest common ancestor. If such candidate
2752 ;; is found, return its beginning position as an unique
2753 ;; identifier, otherwise return nil.
2755 (let ((find-headline
2756 (function
2757 ;; Return first headline whose `:raw-value' property
2758 ;; is NAME in parse tree DATA, or nil.
2759 (lambda (name data)
2760 (org-element-map
2761 data 'headline
2762 (lambda (headline)
2763 (when (string=
2764 (org-element-property :raw-value headline)
2765 name)
2766 headline))
2767 info 'first-match)))))
2768 ;; Search among headlines sharing an ancestor with link,
2769 ;; from closest to farthest.
2770 (or (catch 'exit
2771 (mapc
2772 (lambda (parent)
2773 (when (eq (org-element-type parent) 'headline)
2774 (let ((foundp (funcall find-headline path parent)))
2775 (when foundp (throw 'exit foundp)))))
2776 (org-export-get-genealogy link info)) nil)
2777 ;; No match with a common ancestor: try the full parse-tree.
2778 (funcall find-headline path (plist-get info :parse-tree))))))))
2780 (defun org-export-resolve-id-link (link info)
2781 "Return headline referenced as LINK destination.
2783 INFO is a plist used as a communication channel.
2785 Return value can be an headline element or nil. Assume LINK type
2786 is either \"id\" or \"custom-id\"."
2787 (let ((id (org-element-property :path link)))
2788 (org-element-map
2789 (plist-get info :parse-tree) 'headline
2790 (lambda (headline)
2791 (when (or (string= (org-element-property :id headline) id)
2792 (string= (org-element-property :custom-id headline) id))
2793 headline))
2794 info 'first-match)))
2796 (defun org-export-resolve-coderef (ref info)
2797 "Resolve a code reference REF.
2799 INFO is a plist used as a communication channel.
2801 Return associated line number in source code, or REF itself,
2802 depending on src-block or example element's switches."
2803 (org-element-map
2804 (plist-get info :parse-tree) '(example-block src-block)
2805 (lambda (el)
2806 (with-temp-buffer
2807 (insert (org-trim (org-element-property :value el)))
2808 (let* ((label-fmt (regexp-quote
2809 (or (org-element-property :label-fmt el)
2810 org-coderef-label-format)))
2811 (ref-re
2812 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
2813 (replace-regexp-in-string "%s" ref label-fmt nil t))))
2814 ;; Element containing REF is found. Resolve it to either
2815 ;; a label or a line number, as needed.
2816 (when (re-search-backward ref-re nil t)
2817 (cond
2818 ((org-element-property :use-labels el) ref)
2819 ((eq (org-element-property :number-lines el) 'continued)
2820 (+ (org-export-get-loc el info) (line-number-at-pos)))
2821 (t (line-number-at-pos)))))))
2822 info 'first-match))
2825 ;;;; For Macros
2827 ;; `org-export-expand-macro' simply takes care of expanding macros.
2829 (defun org-export-expand-macro (macro info)
2830 "Expand MACRO and return it as a string.
2831 INFO is a plist holding export options."
2832 (let* ((key (org-element-property :key macro))
2833 (args (org-element-property :args macro))
2834 ;; User's macros are stored in the communication channel with
2835 ;; a ":macro-" prefix. If it's a string leave it as-is.
2836 ;; Otherwise, it's a secondary string that needs to be
2837 ;; expanded recursively.
2838 (value
2839 (let ((val (plist-get info (intern (format ":macro-%s" key)))))
2840 (if (stringp val) val
2841 (org-export-secondary-string
2842 val (plist-get info :back-end) info)))))
2843 ;; Replace arguments in VALUE.
2844 (let ((s 0) n)
2845 (while (string-match "\\$\\([0-9]+\\)" value s)
2846 (setq s (1+ (match-beginning 0))
2847 n (string-to-number (match-string 1 value)))
2848 (and (>= (length args) n)
2849 (setq value (replace-match (nth (1- n) args) t t value)))))
2850 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
2851 (when (string-match "\\`(eval\\>" value)
2852 (setq value (eval (read value))))
2853 ;; Return string.
2854 (format "%s" (or value ""))))
2857 ;;;; For References
2859 ;; `org-export-get-ordinal' associates a sequence number to any object
2860 ;; or element.
2862 (defun org-export-get-ordinal (element info &optional types predicate)
2863 "Return ordinal number of an element or object.
2865 ELEMENT is the element or object considered. INFO is the plist
2866 used as a communication channel.
2868 Optional argument TYPES, when non-nil, is a list of element or
2869 object types, as symbols, that should also be counted in.
2870 Otherwise, only provided element's type is considered.
2872 Optional argument PREDICATE is a function returning a non-nil
2873 value if the current element or object should be counted in. It
2874 accepts two arguments: the element or object being considered and
2875 the plist used as a communication channel. This allows to count
2876 only a certain type of objects (i.e. inline images).
2878 Return value is a list of numbers if ELEMENT is an headline or an
2879 item. It is nil for keywords. It represents the footnote number
2880 for footnote definitions and footnote references. If ELEMENT is
2881 a target, return the same value as if ELEMENT was the closest
2882 table, item or headline containing the target. In any other
2883 case, return the sequence number of ELEMENT among elements or
2884 objects of the same type."
2885 ;; A target keyword, representing an invisible target, never has
2886 ;; a sequence number.
2887 (unless (eq (org-element-type element) 'keyword)
2888 ;; Ordinal of a target object refer to the ordinal of the closest
2889 ;; table, item, or headline containing the object.
2890 (when (eq (org-element-type element) 'target)
2891 (setq element
2892 (loop for parent in (org-export-get-genealogy element info)
2893 when
2894 (memq
2895 (org-element-type parent)
2896 '(footnote-definition footnote-reference headline item
2897 table))
2898 return parent)))
2899 (case (org-element-type element)
2900 ;; Special case 1: An headline returns its number as a list.
2901 (headline (org-export-get-headline-number element info))
2902 ;; Special case 2: An item returns its number as a list.
2903 (item (let ((struct (org-element-property :structure element)))
2904 (org-list-get-item-number
2905 (org-element-property :begin element)
2906 struct
2907 (org-list-prevs-alist struct)
2908 (org-list-parents-alist struct))))
2909 ((footnote definition footnote-reference)
2910 (org-export-get-footnote-number element info))
2911 (otherwise
2912 (let ((counter 0))
2913 ;; Increment counter until ELEMENT is found again.
2914 (org-element-map
2915 (plist-get info :parse-tree) (or types (org-element-type element))
2916 (lambda (el)
2917 (cond
2918 ((equal element el) (1+ counter))
2919 ((not predicate) (incf counter) nil)
2920 ((funcall predicate el info) (incf counter) nil)))
2921 info 'first-match))))))
2924 ;;;; For Src-Blocks
2926 ;; `org-export-get-loc' counts number of code lines accumulated in
2927 ;; src-block or example-block elements with a "+n" switch until
2928 ;; a given element, excluded. Note: "-n" switches reset that count.
2930 ;; `org-export-unravel-code' extracts source code (along with a code
2931 ;; references alist) from an `element-block' or `src-block' type
2932 ;; element.
2934 ;; `org-export-format-code' applies a formatting function to each line
2935 ;; of code, providing relative line number and code reference when
2936 ;; appropriate. Since it doesn't access the original element from
2937 ;; which the source code is coming, it expects from the code calling
2938 ;; it to know if lines should be numbered and if code references
2939 ;; should appear.
2941 ;; Eventually, `org-export-format-code-default' is a higher-level
2942 ;; function (it makes use of the two previous functions) which handles
2943 ;; line numbering and code references inclusion, and returns source
2944 ;; code in a format suitable for plain text or verbatim output.
2946 (defun org-export-get-loc (element info)
2947 "Return accumulated lines of code up to ELEMENT.
2949 INFO is the plist used as a communication channel.
2951 ELEMENT is excluded from count."
2952 (let ((loc 0))
2953 (org-element-map
2954 (plist-get info :parse-tree)
2955 `(src-block example-block ,(org-element-type element))
2956 (lambda (el)
2957 (cond
2958 ;; ELEMENT is reached: Quit the loop.
2959 ((equal el element) t)
2960 ;; Only count lines from src-block and example-block elements
2961 ;; with a "+n" or "-n" switch. A "-n" switch resets counter.
2962 ((not (memq (org-element-type el) '(src-block example-block))) nil)
2963 ((let ((linums (org-element-property :number-lines el)))
2964 (when linums
2965 ;; Accumulate locs or reset them.
2966 (let ((lines (org-count-lines
2967 (org-trim (org-element-property :value el)))))
2968 (setq loc (if (eq linums 'new) lines (+ loc lines))))))
2969 ;; Return nil to stay in the loop.
2970 nil)))
2971 info 'first-match)
2972 ;; Return value.
2973 loc))
2975 (defun org-export-unravel-code (element)
2976 "Clean source code and extract references out of it.
2978 ELEMENT has either a `src-block' an `example-block' type.
2980 Return a cons cell whose CAR is the source code, cleaned from any
2981 reference and protective comma and CDR is an alist between
2982 relative line number (integer) and name of code reference on that
2983 line (string)."
2984 (let* ((line 0) refs
2985 ;; Get code and clean it. Remove blank lines at its
2986 ;; beginning and end. Also remove protective commas.
2987 (code (let ((c (replace-regexp-in-string
2988 "\\`\\([ \t]*\n\\)+" ""
2989 (replace-regexp-in-string
2990 "\\(:?[ \t]*\n\\)*[ \t]*\\'" "\n"
2991 (org-element-property :value element)))))
2992 ;; If appropriate, remove global indentation.
2993 (unless (or org-src-preserve-indentation
2994 (org-element-property :preserve-indent element))
2995 (setq c (org-remove-indentation c)))
2996 ;; Free up the protected lines. Note: Org blocks
2997 ;; have commas at the beginning or every line.
2998 (if (string= (org-element-property :language element) "org")
2999 (replace-regexp-in-string "^," "" c)
3000 (replace-regexp-in-string
3001 "^\\(,\\)\\(:?\\*\\|[ \t]*#\\+\\)" "" c nil nil 1))))
3002 ;; Get format used for references.
3003 (label-fmt (regexp-quote
3004 (or (org-element-property :label-fmt element)
3005 org-coderef-label-format)))
3006 ;; Build a regexp matching a loc with a reference.
3007 (with-ref-re
3008 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)[ \t]*\\)$"
3009 (replace-regexp-in-string
3010 "%s" "\\([-a-zA-Z0-9_ ]+\\)" label-fmt nil t))))
3011 ;; Return value.
3012 (cons
3013 ;; Code with references removed.
3014 (org-element-normalize-string
3015 (mapconcat
3016 (lambda (loc)
3017 (incf line)
3018 (if (not (string-match with-ref-re loc)) loc
3019 ;; Ref line: remove ref, and signal its position in REFS.
3020 (push (cons line (match-string 3 loc)) refs)
3021 (replace-match "" nil nil loc 1)))
3022 (org-split-string code "\n") "\n"))
3023 ;; Reference alist.
3024 refs)))
3026 (defun org-export-format-code (code fun &optional num-lines ref-alist)
3027 "Format CODE by applying FUN line-wise and return it.
3029 CODE is a string representing the code to format. FUN is
3030 a function. It must accept three arguments: a line of
3031 code (string), the current line number (integer) or nil and the
3032 reference associated to the current line (string) or nil.
3034 Optional argument NUM-LINES can be an integer representing the
3035 number of code lines accumulated until the current code. Line
3036 numbers passed to FUN will take it into account. If it is nil,
3037 FUN's second argument will always be nil. This number can be
3038 obtained with `org-export-get-loc' function.
3040 Optional argument REF-ALIST can be an alist between relative line
3041 number (i.e. ignoring NUM-LINES) and the name of the code
3042 reference on it. If it is nil, FUN's third argument will always
3043 be nil. It can be obtained through the use of
3044 `org-export-unravel-code' function."
3045 (let ((--locs (org-split-string code "\n"))
3046 (--line 0))
3047 (org-element-normalize-string
3048 (mapconcat
3049 (lambda (--loc)
3050 (incf --line)
3051 (let ((--ref (cdr (assq --line ref-alist))))
3052 (funcall fun --loc (and num-lines (+ num-lines --line)) --ref)))
3053 --locs "\n"))))
3055 (defun org-export-format-code-default (element info)
3056 "Return source code from ELEMENT, formatted in a standard way.
3058 ELEMENT is either a `src-block' or `example-block' element. INFO
3059 is a plist used as a communication channel.
3061 This function takes care of line numbering and code references
3062 inclusion. Line numbers, when applicable, appear at the
3063 beginning of the line, separated from the code by two white
3064 spaces. Code references, on the other hand, appear flushed to
3065 the right, separated by six white spaces from the widest line of
3066 code."
3067 ;; Extract code and references.
3068 (let* ((code-info (org-export-unravel-code element))
3069 (code (car code-info))
3070 (code-lines (org-split-string code "\n"))
3071 (refs (and (org-element-property :retain-labels element)
3072 (cdr code-info)))
3073 ;; Handle line numbering.
3074 (num-start (case (org-element-property :number-lines element)
3075 (continued (org-export-get-loc element info))
3076 (new 0)))
3077 (num-fmt
3078 (and num-start
3079 (format "%%%ds "
3080 (length (number-to-string
3081 (+ (length code-lines) num-start))))))
3082 ;; Prepare references display, if required. Any reference
3083 ;; should start six columns after the widest line of code,
3084 ;; wrapped with parenthesis.
3085 (max-width
3086 (+ (apply 'max (mapcar 'length code-lines))
3087 (if (not num-start) 0 (length (format num-fmt num-start))))))
3088 (org-export-format-code
3089 code
3090 (lambda (loc line-num ref)
3091 (let ((number-str (and num-fmt (format num-fmt line-num))))
3092 (concat
3093 number-str
3095 (and ref
3096 (concat (make-string
3097 (- (+ 6 max-width)
3098 (+ (length loc) (length number-str))) ? )
3099 (format "(%s)" ref))))))
3100 num-start refs)))
3103 ;;;; For Tables
3105 ;; `org-export-table-format-info' extracts formatting information
3106 ;; (alignment, column groups and presence of a special column) from
3107 ;; a raw table and returns it as a property list.
3109 ;; `org-export-clean-table' cleans the raw table from any Org
3110 ;; table-specific syntax.
3112 (defun org-export-table-format-info (table)
3113 "Extract info from TABLE.
3114 Return a plist whose properties and values are:
3115 `:alignment' vector of strings among \"r\", \"l\" and \"c\",
3116 `:column-groups' vector of symbols among `start', `end', `start-end',
3117 `:row-groups' list of integers representing row groups.
3118 `:special-column-p' non-nil if table has a special column.
3119 `:width' vector of integers representing desired width of
3120 current column, or nil."
3121 (with-temp-buffer
3122 (insert table)
3123 (goto-char 1)
3124 (org-table-align)
3125 (let ((align (vconcat (mapcar (lambda (c) (if c "r" "l"))
3126 org-table-last-alignment)))
3127 (width (make-vector (length org-table-last-alignment) nil))
3128 (colgroups (make-vector (length org-table-last-alignment) nil))
3129 (row-group 0)
3130 (rowgroups)
3131 (special-column-p 'empty))
3132 (mapc (lambda (row)
3133 (if (string-match "^[ \t]*|[-+]+|[ \t]*$" row)
3134 (incf row-group)
3135 ;; Determine if a special column is present by looking
3136 ;; for special markers in the first column. More
3137 ;; accurately, the first column is considered special
3138 ;; if it only contains special markers and, maybe,
3139 ;; empty cells.
3140 (setq special-column-p
3141 (cond
3142 ((not special-column-p) nil)
3143 ((string-match "^[ \t]*| *\\\\?\\([/#!$*_^]\\) *|" row)
3144 'special)
3145 ((string-match "^[ \t]*| +|" row) special-column-p))))
3146 (cond
3147 ;; Read forced alignment and width information, if any,
3148 ;; and determine final alignment for the table.
3149 ((org-table-cookie-line-p row)
3150 (let ((col 0))
3151 (mapc (lambda (field)
3152 (when (string-match
3153 "<\\([lrc]\\)?\\([0-9]+\\)?>" field)
3154 (let ((align-data (match-string 1 field)))
3155 (when align-data (aset align col align-data)))
3156 (let ((w-data (match-string 2 field)))
3157 (when w-data
3158 (aset width col (string-to-number w-data)))))
3159 (incf col))
3160 (org-split-string row "[ \t]*|[ \t]*"))))
3161 ;; Read column groups information.
3162 ((org-table-colgroup-line-p row)
3163 (let ((col 0))
3164 (mapc (lambda (field)
3165 (aset colgroups col
3166 (cond ((string= "<" field) 'start)
3167 ((string= ">" field) 'end)
3168 ((string= "<>" field) 'start-end)))
3169 (incf col))
3170 (org-split-string row "[ \t]*|[ \t]*"))))
3171 ;; Contents line.
3172 (t (push row-group rowgroups))))
3173 (org-split-string table "\n"))
3174 ;; Return plist.
3175 (list :alignment align
3176 :column-groups colgroups
3177 :row-groups (reverse rowgroups)
3178 :special-column-p (eq special-column-p 'special)
3179 :width width))))
3181 (defun org-export-clean-table (table specialp)
3182 "Clean string TABLE from its formatting elements.
3183 Remove any row containing column groups or formatting cookies and
3184 rows starting with a special marker. If SPECIALP is non-nil,
3185 assume the table contains a special formatting column and remove
3186 it also."
3187 (let ((rows (org-split-string table "\n")))
3188 (mapconcat 'identity
3189 (delq nil
3190 (mapcar
3191 (lambda (row)
3192 (cond
3193 ((org-table-colgroup-line-p row) nil)
3194 ((org-table-cookie-line-p row) nil)
3195 ;; Ignore rows starting with a special marker.
3196 ((string-match "^[ \t]*| *[!_^/$] *|" row) nil)
3197 ;; Remove special column.
3198 ((and specialp
3199 (or (string-match "^\\([ \t]*\\)|-+\\+" row)
3200 (string-match "^\\([ \t]*\\)|[^|]*|" row)))
3201 (replace-match "\\1|" t nil row))
3202 (t row)))
3203 rows))
3204 "\n")))
3207 ;;;; For Tables Of Contents
3209 ;; `org-export-collect-headlines' builds a list of all exportable
3210 ;; headline elements, maybe limited to a certain depth. One can then
3211 ;; easily parse it and transcode it.
3213 ;; Building lists of tables, figures or listings is quite similar.
3214 ;; Once the generic function `org-export-collect-elements' is defined,
3215 ;; `org-export-collect-tables', `org-export-collect-figures' and
3216 ;; `org-export-collect-listings' can be derived from it.
3218 (defun org-export-collect-headlines (info &optional n)
3219 "Collect headlines in order to build a table of contents.
3221 INFO is a plist used as a communication channel.
3223 When non-nil, optional argument N must be an integer. It
3224 specifies the depth of the table of contents.
3226 Return a list of all exportable headlines as parsed elements."
3227 (org-element-map
3228 (plist-get info :parse-tree)
3229 'headline
3230 (lambda (headline)
3231 ;; Strip contents from HEADLINE.
3232 (let ((relative-level (org-export-get-relative-level headline info)))
3233 (unless (and n (> relative-level n)) headline)))
3234 info))
3236 (defun org-export-collect-elements (type info &optional predicate)
3237 "Collect referenceable elements of a determined type.
3239 TYPE can be a symbol or a list of symbols specifying element
3240 types to search. Only elements with a caption or a name are
3241 collected.
3243 INFO is a plist used as a communication channel.
3245 When non-nil, optional argument PREDICATE is a function accepting
3246 one argument, an element of type TYPE. It returns a non-nil
3247 value when that element should be collected.
3249 Return a list of all elements found, in order of appearance."
3250 (org-element-map
3251 (plist-get info :parse-tree) type
3252 (lambda (element)
3253 (and (or (org-element-property :caption element)
3254 (org-element-property :name element))
3255 (or (not predicate) (funcall predicate element))
3256 element)) info))
3258 (defun org-export-collect-tables (info)
3259 "Build a list of tables.
3261 INFO is a plist used as a communication channel.
3263 Return a list of table elements with a caption or a name
3264 affiliated keyword."
3265 (org-export-collect-elements 'table info))
3267 (defun org-export-collect-figures (info predicate)
3268 "Build a list of figures.
3270 INFO is a plist used as a communication channel. PREDICATE is
3271 a function which accepts one argument: a paragraph element and
3272 whose return value is non-nil when that element should be
3273 collected.
3275 A figure is a paragraph type element, with a caption or a name,
3276 verifying PREDICATE. The latter has to be provided since
3277 a \"figure\" is a vague concept that may depend on back-end.
3279 Return a list of elements recognized as figures."
3280 (org-export-collect-elements 'paragraph info predicate))
3282 (defun org-export-collect-listings (info)
3283 "Build a list of src blocks.
3285 INFO is a plist used as a communication channel.
3287 Return a list of src-block elements with a caption or a name
3288 affiliated keyword."
3289 (org-export-collect-elements 'src-block info))
3292 ;;;; Topology
3294 ;; Here are various functions to retrieve information about the
3295 ;; neighbourhood of a given element or object. Neighbours of interest
3296 ;; are direct parent (`org-export-get-parent'), parent headline
3297 ;; (`org-export-get-parent-headline'), parent paragraph
3298 ;; (`org-export-get-parent-paragraph'), previous element or object
3299 ;; (`org-export-get-previous-element') and next element or object
3300 ;; (`org-export-get-next-element').
3302 ;; All of these functions are just a specific use of the more generic
3303 ;; `org-export-get-genealogy', which returns the genealogy relative to
3304 ;; the element or object.
3306 (defun org-export-get-genealogy (blob info)
3307 "Return genealogy relative to a given element or object.
3308 BLOB is the element or object being considered. INFO is a plist
3309 used as a communication channel."
3310 (let* ((type (org-element-type blob))
3311 (end (org-element-property :end blob))
3312 (walk-data
3313 (lambda (data genealogy)
3314 ;; Walk DATA, looking for BLOB. GENEALOGY is the list of
3315 ;; parents of all elements in DATA.
3316 (mapc
3317 (lambda (el)
3318 (cond
3319 ((stringp el) nil)
3320 ((equal el blob) (throw 'exit genealogy))
3321 ((>= (org-element-property :end el) end)
3322 ;; If BLOB is an object and EL contains a secondary
3323 ;; string, be sure to check it.
3324 (when (memq type org-element-all-objects)
3325 (let ((sec-prop
3326 (cdr (assq (org-element-type el)
3327 org-element-secondary-value-alist))))
3328 (when sec-prop
3329 (funcall
3330 walk-data
3331 (cons 'org-data
3332 (cons nil (org-element-property sec-prop el)))
3333 (cons el genealogy)))))
3334 (funcall walk-data el (cons el genealogy)))))
3335 (org-element-contents data)))))
3336 (catch 'exit (funcall walk-data (plist-get info :parse-tree) nil) nil)))
3338 (defun org-export-get-parent (blob info)
3339 "Return BLOB parent or nil.
3340 BLOB is the element or object considered. INFO is a plist used
3341 as a communication channel."
3342 (car (org-export-get-genealogy blob info)))
3344 (defun org-export-get-parent-headline (blob info)
3345 "Return closest parent headline or nil.
3347 BLOB is the element or object being considered. INFO is a plist
3348 used as a communication channel."
3349 (catch 'exit
3350 (mapc
3351 (lambda (el) (when (eq (org-element-type el) 'headline) (throw 'exit el)))
3352 (org-export-get-genealogy blob info))
3353 nil))
3355 (defun org-export-get-parent-paragraph (object info)
3356 "Return parent paragraph or nil.
3358 INFO is a plist used as a communication channel.
3360 Optional argument OBJECT, when provided, is the object to consider.
3361 Otherwise, return the paragraph containing current object.
3363 This is useful for objects, which share attributes with the
3364 paragraph containing them."
3365 (catch 'exit
3366 (mapc
3367 (lambda (el) (when (eq (org-element-type el) 'paragraph) (throw 'exit el)))
3368 (org-export-get-genealogy object info))
3369 nil))
3371 (defun org-export-get-previous-element (blob info)
3372 "Return previous element or object.
3374 BLOB is an element or object. INFO is a plist used as
3375 a communication channel.
3377 Return previous element or object, a string, or nil."
3378 (let ((parent (org-export-get-parent blob info)))
3379 (cadr (member blob (reverse (org-element-contents parent))))))
3381 (defun org-export-get-next-element (blob info)
3382 "Return next element or object.
3384 BLOB is an element or object. INFO is a plist used as
3385 a communication channel.
3387 Return next element or object, a string, or nil."
3388 (let ((parent (org-export-get-parent blob info)))
3389 (cadr (member blob (org-element-contents parent)))))
3393 ;;; The Dispatcher
3395 ;; `org-export-dispatch' is the standard interactive way to start an
3396 ;; export process. It uses `org-export-dispatch-ui' as a subroutine
3397 ;; for its interface. Most commons back-ends should have an entry in
3398 ;; it.
3400 (defun org-export-dispatch ()
3401 "Export dispatcher for Org mode.
3403 It provides an access to common export related tasks in a buffer.
3404 Its interface comes in two flavours: standard and expert. While
3405 both share the same set of bindings, only the former displays the
3406 valid keys associations. Set `org-export-dispatch-use-expert-ui'
3407 to switch to one or the other.
3409 Return an error if key pressed has no associated command."
3410 (interactive)
3411 (let* ((input (org-export-dispatch-ui
3412 (if (listp org-export-initial-scope) org-export-initial-scope
3413 (list org-export-initial-scope))
3414 org-export-dispatch-use-expert-ui))
3415 (raw-key (car input))
3416 (optns (cdr input)))
3417 ;; Translate "C-a", "C-b"... into "a", "b"... Then take action
3418 ;; depending on user's key pressed.
3419 (case (if (< raw-key 27) (+ raw-key 96) raw-key)
3420 ;; Allow to quit with "q" key.
3421 (?q nil)
3422 ;; Export with `e-ascii' back-end.
3423 ((?A ?N ?U)
3424 (let ((outbuf
3425 (org-export-to-buffer
3426 'e-ascii "*Org E-ASCII Export*"
3427 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)
3428 `(:ascii-charset
3429 ,(case raw-key (?A 'ascii) (?N 'latin1) (t 'utf-8))))))
3430 (with-current-buffer outbuf (text-mode))
3431 (when org-export-show-temporary-export-buffer
3432 (switch-to-buffer-other-window outbuf))))
3433 ((?a ?n ?u)
3434 (org-e-ascii-export-to-ascii
3435 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)
3436 `(:ascii-charset ,(case raw-key (?a 'ascii) (?n 'latin1) (t 'utf-8)))))
3437 ;; Export with `e-latex' back-end.
3439 (let ((outbuf
3440 (org-export-to-buffer
3441 'e-latex "*Org E-LaTeX Export*"
3442 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
3443 (with-current-buffer outbuf (latex-mode))
3444 (when org-export-show-temporary-export-buffer
3445 (switch-to-buffer-other-window outbuf))))
3446 (?l (org-e-latex-export-to-latex
3447 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)))
3448 (?p (org-e-latex-export-to-pdf
3449 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)))
3450 (?d (org-open-file
3451 (org-e-latex-export-to-pdf
3452 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
3453 ;; Export with `e-html' back-end.
3455 (let ((outbuf
3456 (org-export-to-buffer
3457 'e-html "*Org E-HTML Export*"
3458 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
3459 ;; set major mode
3460 (with-current-buffer outbuf
3461 (if (featurep 'nxhtml-mode) (nxhtml-mode) (nxml-mode)))
3462 (when org-export-show-temporary-export-buffer
3463 (switch-to-buffer-other-window outbuf))))
3464 (?h (org-e-html-export-to-html
3465 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)))
3466 (?b (org-open-file
3467 (org-e-html-export-to-html
3468 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
3469 ;; Export with `e-odt' back-end.
3470 (?o (org-e-odt-export-to-odt
3471 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)))
3472 (?O (org-open-file
3473 (org-e-odt-export-to-odt
3474 (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
3475 ;; Publishing facilities
3476 (?F (org-e-publish-current-file (memq 'force optns)))
3477 (?P (org-e-publish-current-project (memq 'force optns)))
3478 (?X (let ((project
3479 (assoc (org-icompleting-read
3480 "Publish project: " org-e-publish-project-alist nil t)
3481 org-e-publish-project-alist)))
3482 (org-e-publish project (memq 'force optns))))
3483 (?E (org-e-publish-all (memq 'force optns)))
3484 ;; Undefined command.
3485 (t (error "No command associated with key %s"
3486 (char-to-string raw-key))))))
3488 (defun org-export-dispatch-ui (options expertp)
3489 "Handle interface for `org-export-dispatch'.
3491 OPTIONS is a list containing current interactive options set for
3492 export. It can contain any of the following symbols:
3493 `body' toggles a body-only export
3494 `subtree' restricts export to current subtree
3495 `visible' restricts export to visible part of buffer.
3496 `force' force publishing files.
3498 EXPERTP, when non-nil, triggers expert UI. In that case, no help
3499 buffer is provided, but indications about currently active
3500 options are given in the prompt. Moreover, \[?] allows to switch
3501 back to standard interface.
3503 Return value is a list with key pressed as CAR and a list of
3504 final interactive export options as CDR."
3505 (let ((help
3506 (format "---- (Options) -------------------------------------------
3508 \[1] Body only: %s [2] Export scope: %s
3509 \[3] Visible only: %s [4] Force publishing: %s
3512 --- (ASCII/Latin-1/UTF-8 Export) -------------------------
3514 \[a/n/u] to TXT file [A/N/U] to temporary buffer
3516 --- (HTML Export) ----------------------------------------
3518 \[h] to HTML file [b] ... and open it
3519 \[H] to temporary buffer
3521 --- (LaTeX Export) ---------------------------------------
3523 \[l] to TEX file [L] to temporary buffer
3524 \[p] to PDF file [d] ... and open it
3526 --- (ODF Export) -----------------------------------------
3528 \[o] to ODT file [O] ... and open it
3530 --- (Publish) --------------------------------------------
3532 \[F] current file [P] current project
3533 \[X] a project [E] every project"
3534 (if (memq 'body options) "On " "Off")
3535 (if (memq 'subtree options) "Subtree" "Buffer ")
3536 (if (memq 'visible options) "On " "Off")
3537 (if (memq 'force options) "On " "Off")))
3538 (standard-prompt "Export command: ")
3539 (expert-prompt (format "Export command (%s%s%s%s): "
3540 (if (memq 'body options) "b" "-")
3541 (if (memq 'subtree options) "s" "-")
3542 (if (memq 'visible options) "v" "-")
3543 (if (memq 'force options) "f" "-")))
3544 (handle-keypress
3545 (function
3546 ;; Read a character from command input, toggling interactive
3547 ;; options when applicable. PROMPT is the displayed prompt,
3548 ;; as a string.
3549 (lambda (prompt)
3550 (let ((key (read-char-exclusive prompt)))
3551 (cond
3552 ;; Ignore non-standard characters (i.e. "M-a").
3553 ((not (characterp key)) (org-export-dispatch-ui options expertp))
3554 ;; Help key: Switch back to standard interface if
3555 ;; expert UI was active.
3556 ((eq key ??) (org-export-dispatch-ui options nil))
3557 ;; Toggle export options.
3558 ((memq key '(?1 ?2 ?3 ?4))
3559 (org-export-dispatch-ui
3560 (let ((option (case key (?1 'body) (?2 'subtree) (?3 'visible)
3561 (?4 'force))))
3562 (if (memq option options) (remq option options)
3563 (cons option options)))
3564 expertp))
3565 ;; Action selected: Send key and options back to
3566 ;; `org-export-dispatch'.
3567 (t (cons key options))))))))
3568 ;; With expert UI, just read key with a fancy prompt. In standard
3569 ;; UI, display an intrusive help buffer.
3570 (if expertp (funcall handle-keypress expert-prompt)
3571 (save-window-excursion
3572 (delete-other-windows)
3573 (with-output-to-temp-buffer "*Org Export/Publishing Help*" (princ help))
3574 (org-fit-window-to-buffer
3575 (get-buffer-window "*Org Export/Publishing Help*"))
3576 (funcall handle-keypress standard-prompt)))))
3579 (provide 'org-export)
3580 ;;; org-export.el ends here